-
35ec50c5
by Mikolaj Konarski at 2026-11-20T00:12:51+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed
Note [Unwinding information in the NCG] in that module. The Note
is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists. Two comments further down named MachCodeGen:
as calling cmmMakeDynamicReference for static data, which
the instruction selectors do, and as calling the initialization
of the PIC base register for every procedure that accessed it, which
cmmTopCodeGen in the x86 and PowerPC instruction selectors does,
but not on AIX. They now say so.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout ran
optimizeCFG right after instruction selection. cmmNativeGen runs
it after register allocation and shortcutting. The Note presented
the next two steps, loopInfo's loop analysis and mkGlobalWeights'
refinement of the edge weights, as unconditional; optimizeCFG takes
them only under -fcmm-static-pred, which -O implies, and the Note now
says so. It said that the refined weights are normalized relative
to the most often visited node; they are relative to the entry node,
to which calcFreqs gives frequency 1.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight, the x86-64 instruction selector adds 3 to the false side
of a floating-point comparison, and optHsPatterns' favourFewerPreds
may then prefer one side by its predecessors. It said that calls
are ignored completely; the layout leaves a call's edge out while
it builds chains and while it combines neighbouring chains,
and divides its weight by 64 when it merges the chains.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also
said that edges constituted by a call are ignored. The layout ignores
them while it builds the chains and while it combines neighbouring
chains, and counts a 64th of their weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics where staticBranchPrediction applies three, ohPredicts
being the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said
that it finds back edges by BFS. It finds them by a depth-first search
(classifyEdges in GHC.Data.Graph.Directed).
- The Instruction class asked regUsageOfInstr to state precisely
the registers an instruction reads and writes. x86's states them
as the register allocators are to see them, and the comment now says
so, with examples of where that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and a load at FF32 or FF64;
others keep it, such as a MOV between registers at FF32 or FF64,
printed movss or movsd, and an 8-bit or 16-bit MOV into a general
register. The comment now also says that the usage of the other MOV
instructions has a register destination written, not read.
- Comments in the liveness pass, in both register allocators and
at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In the liveness pass
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides; at the Ord instances,
that the order compares uniques and so is deterministic only
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies; the comment is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block; any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. It stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register; a block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones; what holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that it spills all
the cycle's source registers. It spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
compiled by a GHC build of 2026-10 whose linear allocator
was master's, the fixup code breaks 39 register cycles through a stack
slot in $w$s$wequalT1 and 59 in $w$s$w$ccompare1. The two counts
were not taken again on master. The sentence is deleted.
- A comment at expandNode's case for a move from InBoth to InMem,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that the source's slot
is guaranteed to be the destination's. They can differ where
the virtual register has more than one slot, and the value
is then stored from its register; the comment now says that the guard
fails only there.
- GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels]
in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel,
and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. It starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone, and numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- The stmtToInstrs of X86, AArch64, LA64 and RV64 took the condition
of a conditional branch to be likely false, GHC.Cmm.ContFlowOpt having
arranged for the likely side to fall through. ContFlowOpt also inverts
a condition whatever its likelihood where the condition can
be inverted, the true target has one predecessor and the false target
more than one, so the condition may be likely true; none of the four
genCondBranch functions reads the likelihood.
- mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does
not know about likely annotations. The PowerPC code generator has
printed them as branch hints since 2017, and since 2018 getCfg has
weighted the CFG's edges by them, which on x86-64 the block layout
and the order of some conditional branches' jumps (invertCondBranches)
follow. Its clause on a fallthrough is replaced by what the swap does:
where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- The users' guide said that -fcmm-static-pred's prediction is used
by the register allocation and code layout passes. The prediction
is made only in the x86-64 native code generator, and is used, after
register allocation and without -finfo-table-map, for the layout
and for the order of some conditional branches' jumps
(invertCondBranches). The entry now also says that on x86-64 the graph
colouring allocators (-fregs-graph, -fregs-iterative) weight the uses
and definitions they count by the same heuristics whatever the flag
says, without -finfo-table-map (slurpSpillCostInfo, mkGlobalWeights),
but choose what to spill by live range length alone (chooseSpill,
spillCost_length), so that the flag does not change their allocation.
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written;
the sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
Assisted-by: Claude Opus 5.5
-
f34bb767
by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Define the labels of the NCG's comments
Of what anyone working with the NCG needs, this commit serves "The kind
of each statement in the NCG's comments, shown at the statement: a bug,
half-done work, a likely change or code meant to stay.", "What a comment
that does not show the kind of its statements does and does not claim."
and "How the statements on bugs, half-done work and likely changes
are kept true as the code changes."
Comments only; the generated code is the same.
Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels
that the native code generator's comments put at the head
of a statement. The commits that follow label each statement they add,
and are read under this Note:
BUG wrong behaviour, a missing check or misleading code;
the statement says in short what it leads to and where
it is reached
WIP half-done work
TODO what is likely to change, correct or buggy; a bug marked
TODO alone is accepted for now and worked around
BUG TODO both, where both are to be stressed
no label what is meant to stay; a kept trade-off says why
A BUG statement names its consequence: wrong code, wrong debugging
information, a panic or another failed compilation, assembly
the assembler rejects, only slower or larger code, only a warning
from the assembler, only more C stack space, or only a misled reader.
The Note does not reach back to older comments: their TODO, ToDo, FIXME
and XXX predate its meanings, and an older comment that carries no label
makes no claim that the code is meant to stay.
The Note also says how the labels are kept true. A change to what
a labelled statement describes removes or rewrites the statement
in the same change; BUG and TODO gain the issue's number when the issue
is filed; and a git grep given in the Note lists the labelled lines.
Assisted-by: Claude Opus 5.5
-
4afe468d
by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in the NCG's CFG and block layout
Of what anyone working with the NCG needs, this commit serves "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- postRegCFG in GHC.CmmToAsm (BUG: X86's allocMoreStack retargets every
jump into an entry block to the block it adds after it,
but addImmediateSuccessor moves only the entry block's own edges).
The CFG keeps an edge into the entry block from each block that jumps
there, though the code now jumps to the added block, and lacks
those blocks' edges to the added block. This costs only speed.
It is reached on x86-64, the only target with a CFG after register
allocation, where ncgAllocMoreStack adds blocks, that is, where
allocation needs more spill slots than maxSpillSlots. This rests
on master's code read. The linear allocator's fixup blocks were added
to the CFG before postRegCFG, and the added block is reachable,
through the entry block's edge to it. No reader of the CFG after
postRegCFG panics on these edges: shortcutWeightMap has no lookup
that panics; optimizeCFG's lookups take their blocks and edges
from the CFG itself; sanityCheckCfg compares blocks only; sequenceTop
looks up only the blocks the CFG's edges name, all of them blocks
of the code; and invertCondBranches takes an edge's information
as a Maybe and leaves a jump without it alone.
- build_mapping in shortcutBranches, GHC.CmmToAsm (BUG: under -g a block
that holds only its jump also holds the location and unwinding
information that -g adds, so it is kept where without -g
it is shorted). The code under -g jumps through the kept block,
and on x86-64 static prediction and block layout get another CFG
than without -g. This costs only speed and code size, under -g
and -fasm-shortcutting, on x86 and x86-64, not on Darwin. This rests
on master's code read: split matches a block of exactly one
instruction, and under -g on ELF targets other than AArch64
the instruction selectors put a LOCATION at the head of a block
with a source note, and under -g x86's gives a CmmUnwind an UNWIND,
neither of which emits code. On a development branch whose block
layout differed from master's, this changed the code of a probe
under -g.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG (BUG:
with tables next to code too, a block that is only a tail call's jump
to a label is shortcut away, and with it the edge A -> B). A's branch
has one target fewer in the CFG than in the code, and a loop whose
only exit was the lost edge has no exit in the CFG, so calcFreqs caps
its cycle probability. This costs only speed. It is reached on x86-64,
the only target with a CFG after register allocation,
under -fasm-shortcutting, not on Darwin. This rests on master's code
read: the removed block ends in a tail call and has no edges out
in the CFG; it leaves the code and the CFG together, and no block
becomes unreachable; and the readers of the CFG after
shortcutWeightMap, listed above for postRegCFG, do not panic
on a missing edge.
- getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only
the blocks reachable from the entry, while instruction selection still
covers the blocks that cmmToCmm makes unreachable when, after the Cmm
pipeline has removed the unreachable blocks, it turns a branch
on a constant into a jump). Where such a block updates the CFG
at its current block, as X86's cmpxchg loop for an atomic and, or, xor
or nand does, the compiler panics with "getSuccessorEdges: Block does
not exist". This is reached on x86 and x86-64, at any optimisation
level: cmmToCmm turns a branch on a literal into a jump under every
flag, and the literal comes at -O0 from cmmToCmm's own constant
folding and at -O from sinking's. For x86-64 this rests on master's
code read and on runs of master's compiler under -dcmm-lint.
A procedure whose if (1 != 0) leaves a block with a fetch-and-and
unreachable panics with that message at -O0 and at -O, and also
at both with -finfo-table-map added, under which no CFG is kept after
instruction selection, as on i386. Where the branch tests a local set
to 1 instead, the procedure panics at -O and compiles at -O0. For i386
it rests on master's code read alone, no i386 compiler having
been run: getCfgProc builds the CFG for every target, i386 runs
the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each
update, so addImmediateSuccessor's call of getSuccessorEdges panics
during instruction selection whether or not a CFG is kept after it.
It rests also on ISSUE 28088's record.
A TODO citing ISSUE 20428, at livenessCfg
and at ncgEnableDeadCodeElimination, says that -finfo-table-map turns
dead code elimination off, and with it every use of the CFG
from the liveness pass on. No CFG is then kept after register
allocation, so the layout has neither static prediction nor the chains
of -fblock-layout-cfg, and lays the blocks out without weights.
Note [CFG Edge Weights] now says what -fcmm-static-pred changes:
that under it the weights become estimated frequencies before the layout
uses them.
A TODO in Note [Layout relevant edge weights],
in GHC.CmmToAsm.BlockLayout, citing ISSUE 27799, says that the modifier
on the edges of a conditional branch under-prices such an edge where
buildChains skips the branch's other edge because it would close
a cycle, as it can skip a loop latch's back edge.
At getCfg's case for a switch, master's comment says that the weight -1
given to every target of a switch with more than ten targets, a compiler
performance hack, keeps the layout from considering them. A TODO there
now says that the layout considers them nonetheless, and that what
the hack saves has not been measured.
Other TODOs say:
- at the Ord instance of CfgEdge, that edges of equal weight are ordered
by their labels, which carry no meaning for the layout;
- in Note [Updating the CFG during shortcutting], that where
shortcutting redirects an edge onto one already there, only one
EdgeInfo is kept and the weights are not summed;
- at allEdges' relevantWeight in sequenceChain, that it differs
from directEdges';
- at dropJumps, that a block that only jumps to the next one is left
as an empty label and a jump over it is kept.
In X86's genCondBranch', a comment says that the 3 added to the weight
of a floating-point comparison's false edge breaks layout ties toward
the side GHC.Cmm.ContFlowOpt arranges to fall through.
Assisted-by: Claude Opus 5.5
-
87d38d0a
by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in static branch prediction and loop analysis
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
WIP for half-done work, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- getCfg in GHC.CmmToAsm.CFG (BUG: after fixStgRegisters, a test
of CurrentTSO or CurrentNursery reads BaseReg and is tagged
HeapStackCheck). The exemptions of Note [Static Branch Prediction]
for heap and stack checks then apply to such a test, so its weights
are left unpredicted. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read. The tag
decides the code only through isHeapOrStackCheck, all of whose callers
are in staticBranchPrediction, which runs inside mkGlobalWeights.
mkGlobalWeights reaches the code through staticPredCfg, only
under -fcmm-static-pred, and otherwise only through the graph
allocator's spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28083 (an edge into the entry block is never a back edge,
as mkDomMap leaves the root out of every dominator set). A loop whose
head is the entry block is not found. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read
and ISSUE 28083's record. loopInfo's result reaches the code only
through static prediction and block layout: of its two callers,
loopLevels is never called, and mkGlobalWeights serves staticPredCfg,
under -fcmm-static-pred, and otherwise only the graph allocator's
spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28093 (a self loop is a back edge only where its block dominates
no other block). A block that jumps to itself and to an exit
it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen
does, is not a loop. calcFreqs then takes the block for irreducible
and gives frequency 0 to it and to every block it dominates.
This costs only speed, on x86-64 under -fcmm-static-pred, by the same
path as the BUG of ISSUE 28083. This rests on master's code read,
on the record of ISSUE 28093, and on -ddump-cfg-weights of a loop
calling fetchOrIntArray#, compiled by a GHC built from 3d326d7d28
with changes outside the native code generator: the retry block's
edges and the loop's back edge weigh 0. Between 3d326d7d28
and the master commit this branch starts from, GHC.CmmToAsm.CFG
and cmpxchg_code are unchanged, and the dominator code loses only
a `return = pure`.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG: the back
edge rule supersedes a likely annotation in the Cmm as well). A branch
with both a back edge and another edge is predicted to take the back
edge, whatever its annotation says. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read:
staticBranchPrediction's case for a mix of back edges and other edges
reads no annotation.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO:
a constructor-tag test is predicted like any other comparison,
its equal side unlikely). The prediction is wrong for the trees
of Data.Map and Data.Set, which declare Bin first: in a lookup,
the side that stays in the loop is predicted unlikely. This costs only
speed, on x86-64 under -fcmm-static-pred. It is accepted until
the knowledge of the likely side reaches the CFG, hence TODO as well.
This rests on master's code read.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG (s1
is taken for the true side only where it is ltrue, the label
the branch was made with, which an edge no longer ends at once
the linear allocator's fixup block, by addNodesBetween,
or shortcutting, by shortcutWeightMap, has redirected it). Where
the redirected true edge's new target has the smaller label
of the two, each side gets the other's prediction, and the layout's
estimate takes the likely side for the unlikely one. This costs only
speed, on x86-64 under -fcmm-static-pred. This rests on master's code
read, and on a count over nofib's modules on a development branch
whose static prediction also predicts an inequality with a literal,
which found such branches inverted at -O2 and none at -O1.
- calcFreqs in GHC.CmmToAsm.CFG (BUG: mkGlobalWeights passes the loops
in the order of loopInfo's back edges, by label, and not by nesting).
An enclosing loop's pass can come before an inner loop's and read
the branch probability of an inner back edge where its cycle
probability belongs, which gives nested loops wrong cycle
probabilities. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read.
A WIP in Note [Static Branch Prediction] says that the paper's other
heuristics are stubs.
calcFreqs' comment on an irreducible block, "Rare we don't care", now
says what frequency such a block keeps and, as a TODO, that such blocks
are not rare, that the layout then ranks edges by frequencies that do
not add up, with a loop calling fetchOrIntArray#, compiled by the GHC
named under ISSUE 28093 above, for a case, and what summing their inflow
measured on a development branch.
Other TODOs say:
- in Note [Back edges in loopInfo], that findBackEdges, which
optHsPatterns uses for the back edge bonus, disagrees with loopInfo
on edges into the entry block, on back edges of irreducible cycles
and on self loops;
- at ohPredicts, that only MO_Eq is read, so the spelling
GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted,
and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq
spelling is predicted was tried on a development branch and gained
nothing;
- at lehPredicts, that where a heap or stack check's call to the garbage
collector returns into the procedure, loopInfo takes the cycle through
that call for a loop: the heuristic then says nothing about a branch
into the checking block where that block is the loop's head, and takes
a branch towards a case alternative without such a check for a loop
exit where the head is the block choosing the alternative;
- at calcFreqs, that nothing checks its result, and that a check could
compare each block's frequency with the sum of the frequencies
on its in-edges, which the propagation departs from at some blocks,
among them an irreducible block, a loop head whose cycle probability
is capped, and the entry block;
- at loopMembers, that neither it nor loopLevels has a caller in GHC:
loopMembers since the graph allocator's spill costs, for which
it was added early in 2019, began that year to weight by block
frequencies instead, and loopLevels since it came with the loop
analysis that year.
A comment at optimizeCFG says that static prediction starts
from the weights optHsPatterns leaves, so that their adjustments carry
into the predicted probabilities, except where the back edge rule
replaces them.
Assisted-by: Claude Opus 5.5
-
90ee3014
by Mikolaj Konarski at 2026-11-20T00:12:52+01:00
Document bugs and TODOs in liveness and the register allocators
Of what anyone working with the NCG needs, this commit serves
"The invariants the code depends on.", "Where the code does something
other than what reading it suggests.", "Where the code is known
to behave wrongly or is half done.", "What each known bug leads to, such
as wrong code, a compiler panic or only slower code, and under which
flags and on which targets it is reached." and "Where the code is likely
to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- regAlloc in GHC.CmmToAsm.Reg.Graph (BUG: it hands ncgAllocMoreStack
slotsCount', the highest slot number, which counts the preallocated
slots, where the linear allocator gives only the slots beyond
maxSpillSlots): the preallocated slots are reserved a second time.
This costs C stack space, under -fregs-graph or -fregs-iterative,
on every target, and where a target's mkStackAllocInstr needs more
instructions for a larger amount, code at entry and exit: on AArch64
one instruction more for each 4095 bytes, on RISC-V, LoongArch
and PowerPC more past the range of an immediate, and on Windows x86-64
a call of ___chkstk_ms past 4 KB. This rests on master's code read.
Every target's allocMoreStack moves the stack pointer by the slots
it is given times spillSlotSize. The graph allocator can be chosen
for any target, and trivColorable covers x86, x86-64, PowerPC,
AArch64, RISC-V and LoongArch.
- pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG: it binds
a SpillCostRecord as (reg, uses, defs, life), where the type's
comments give its fields as the writes, the reads and the lifetime).
Only the names are wrong: it prints the two counts in the record's
order, under no names, and their sum divided by the register's node
degree, and nothing in GHC calls it. This rests on master's code read:
slurpSpillCostInfo's incDefs fills the second field and incUses
the third.
- joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG: on x86
a floating-point == or /= test's block ends in two jumps that name one
target, genCondBranch's parity jump and a conditional or unconditional
one, and each is joined on its own). Where that target needs a fixup
block, each of the two jumps gets one, with the same moves, and both
are reachable. This costs only code size, on x86 and x86-64
under the linear allocator. This rests on master's code read
and on constructed Cmm compiled by master's compiler; no module
of nofib or of the compile benchmarks was found to show it. A fix
that shares the block where the two jumps' stack deltas agree,
the target's vregs have the same locations at both and no value moves
between two slots was written on a development branch and is left out.
- joinToTargets_again in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG:
once it has made a fixup block for a target and patched the jump to go
there, the destinations still to consider keep the target's later
occurrences, as a jump table lists a target once for each entry naming
it). Each later occurrence makes the same moves again, into a block
nothing jumps to, which is given an edge in the CFG, laid out
and emitted: dead code. This costs only code size, under the linear
allocator. This rests on master's code read: x86's jumpDestsOfInstr
lists a jump table's targets with their repetitions, and the other
targets with jump tables do likewise. Such a block was found in GHC's
own GHC.CmmToAsm.Dwarf.Constants and in none of nofib's
or the testsuite's modules.
- makeRegMovementGraph, handleComponent and makeMove
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, and the header
of GHC.CmmToAsm.Reg.Linear.StackMap (BUG, ISSUE 27638: since
ISSUE 26668 a virtual register whose format has outgrown its slot gets
new slots, so a jump can need a move between two slots of one
register): such a move ends in makeMove's panic, "makeMove: we don't
handle mem->mem moves". And where handleComponent's cyclic case moves
to an InBoth destination (BUG, a statement of its own, ISSUE 27638
reporting only the panic), the destination's slot is written only
if it is the slot spillR picks; otherwise it keeps a stale value,
which is wrong code where the slot is reloaded. Both are reached
under the linear allocator, where a virtual register's format grows
past 8 bytes, which only a vector format does, and so only on i386,
x86-64 and AArch64, the targets whose code generators take vectors
(checkVecCompatibility in GHC.StgToCmm.Prim; PowerPC's, RV64's
and LA64's stop with sorry on vectors). The first is reached on x86-64
at -O1 and -O2: master's compiler panics so on a function in which
a Double, also broadcast to a DoubleX2#, is live at a join of two arms
of a case that both load eleven Int#s and seventeen Doubles.
No program reaching the second is known. The first can be reached two
ways, by expandNode, both from a jump at which the virtual register
is in one of its slots only: into a block that holds it in another
of its slots only, and into a block that holds it in a register
and another slot, where makeMove loads the register first. A fix
cannot count on a spare register: nothing keeps one free at a jump,
and the block's entry assignment can hold every allocatable register,
on x86-64 the eleven integer registers (rax, rbx, rcx, rdx, rsi, rdi,
r8 to r11 and r14) and the sixteen vector registers, the others being
the stack pointer and those of STG's Base, Sp, Hp and SpLim (freeReg
in compiler/CodeGen.Platform.h). This rests on master's code read,
ISSUE 27638's record and a run of master's compiler. The cyclic case
drops the InMem half of an InBoth destination (expandNode lists InReg
first) and writes only spillR's slot, which is getStackSlotFor's
newest slot of the virtual register and differs from the destination's
only after the register grew. And allocateRegsAndSpill frees
the register of an InBoth virtual register without a store,
so that its next use reloads the slot.
- livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq
compares the registers and not their formats, so the fixpoint can stop
before the formats recorded for a cycle's blocks converge): a vector
register can be recorded live at a format narrower than the value
it holds, and a write at that format then kills
it in minusCoveredRegs, which is wrong code. No program giving a wrong
result is known. This rests on master's code read and ISSUE 27619's
record, whose program shows a register recorded so.
- getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG:
it folds the slot maps of a block's predecessors from the empty map
with mergeSlotMaps, which keeps only the slots both maps hold).
The slot map on entry to a block is always empty, so a reload
is coalesced with a spill only inside one block. This costs only speed
and code size, under -fregs-graph or -fregs-iterative, on every
target. This rests on master's code read; buildGraph
in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce.
- maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's
derived Ord compares a VecFormat's number of elements before their
format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4
FmtDouble, 256 bits): it can keep the narrower of two formats.
Were one register read at both, a write at the narrower would kill
it in minusCoveredRegs, which is wrong code; whether any register
is read so is not known. This rests on master's code read
and ISSUE 27619's record.
The other statements, by part.
The linear allocator:
- Note [The first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump
into a block that the allocator processes records the block's entry
assignment, spilled values included, and that every later jump
conforms to it by fixup code. Its three TODOs are what follows
from that: a loop head recorded from a preheader that spilled
a loop-carried value has the value reloaded on every iteration,
and stored again by every back edge once the body has written it;
a return continuation and the procedure's entry that enter one loop
at two blocks record incompatible assignments (ISSUE 27800);
and the block that a failed heap or stack check returns to
from the garbage collector can be allocated before the hot path's jump
into the checking block and record that block's entry assignment,
as the order of allocation depends on no frequency. process' comment
cites the Note.
- Note [Unique order in the linear allocator],
in GHC.CmmToAsm.Reg.Linear, says, as a TODO, which decisions take
the order of the vregs' uniques as a ranking: the spill victim,
and the order in which saveClobberedTemps moves values out
of clobbered registers. It also says that the order decides
joinToTargets' fixup moves. The comments at those three folds cite it.
- Issues get labels where the code behaves as they report: TODO
for ISSUE 27980, closed as a duplicate of ISSUE 27800,
at findPrefRealReg, for ISSUE 27981 at joinToTargets_first's release
of registers, and for ISSUE 26631 at saveClobberedTemps' choice
of a register; BUG for ISSUE 27638 at handleComponent, makeMove,
makeRegMovementGraph and StackMap's header, whose comments ruled out
a move between two stack slots, which ISSUE 26668 made possible.
- TODOs without an issue: raInsn's elimination of a move gives
the destination the source's register, whatever register an entry
assignment recorded for a block it is live into expects;
findPrefRealReg's preference is keyed by virtual register, while a Cmm
local is one virtual register over all its live ranges; and expandNode
stores a value InBoth at both ends of a jump into the slot
that already holds it.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot
belongs to one virtual register for the whole procedure,
as getStackSlotFor takes new slots only at the next free one, which
only grows, and a register that outgrows its slot gets another,
keeping the first; that the fixups at a jump rely on this; and
that it costs stack, the slots of a procedure adding up over every
register spilled in it.
- Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear,
re-adding a dead spilled register's stack slot to the free list,
is marked WIP: it is not done, as a StackMap never frees a slot.
- A comment at clobberRegs' filter says that frAllocateReg panics
on a register already allocated on AArch64, RISC-V and LoongArch.
- Three designs that a trial on a development branch found no gain
in are recorded beside the code they would change: handing out
the floating-point registers in descending order (at the TODO
for ISSUE 26631 in saveClobberedTemps), taking the entry block first
and then, after each SCC, an SCC holding a block whose entry
assignment is recorded (at the TODO for ISSUE 27800), and putting
fixup moves before an unconditional jump rather than in a block
of their own (in joinToTargets_again).
Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs:
- The fixpoint of livenessSCCs says that it compares the whole map
at every round (TODO, ISSUE 27437), and that its steps are monotone,
so that a test comparing the formats too would reach a result
independent of the order in which the blocks are walked. Regs' Eq says
that it ignores formats (TODO, ISSUE 27619).
- The comment on the SCCs' order says that no block may fall through
before allocation, and liveDieRead's haddock that at a branch it also
holds the registers live into its targets only.
- A comment at computeLiveness' panic on SCCs out of reverse dependent
order says that, where sccBlocks has a CFG, a jump to a block missing
from the CFG reaches it too.
The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment
says that the block frequencies scale only the counts of uses
and definitions, on which no spill choice depends, as spillCost_chaitin,
which would read them, is commented out.
Both allocators: a TODO at patchRegsOfInstr says that, as it maps
a register to a register, both allocators reload a spilled value
into a register for an instruction that reads it, even at its last read,
where an x86 instruction could read the stack slot.
Assisted-by: Claude Opus 5.5
-
dc7ab797
by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Document bugs and TODOs in code generators, DWARF and an unused module
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126:
isNbitEncodeable 12 admits label offsets from -2048 to 2047, while
check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095):
on AArch64, compiling a label at an offset from -2048 to -1 stops
with check_off's error, a pgmError,
"GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit"
for an offset of -8. Below -2048 the guard fails, and the next clause
adds the offset through a register. This rests on master's code read
(litToImm', ImmIndex, check_off), ISSUE 28126's record and a run
of master's x86-64 compiler given an AArch64 target description,
in which a Cmm load from a label less 8, at -O0 and at -O,
and plusAddr# of a string literal and -1#, at -O, stop
with check_off's error; nothing was run on AArch64.
- lower_CmmRegOff in GHC.CmmToAsm.Wasm.FromCmm and the cases
for CmmRegOff of getRegister' in GHC.CmmToAsm.RV64.CodeGen
and GHC.CmmToAsm.LA64.CodeGen, one BUG at each (the sum
is not truncated to a sub-word register's width, as each target's
general lowering of a sub-word MO_Add truncates its result,
and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus
a literal into a CmmRegOff at any width validOffsetRep allows). Where
an operation reads the bits above the width, this is wrong code:
on wasm32 a widening MO_UU_Conv of a sub-word value masks nothing,
and on RV64 and LA64 Note [Signed arithmetic on RISCV64] and LA64's
comment "Signed arithmetic on LoongArch64" keep a sub-word value
zero-extended between operations. This rests on master's code read
alone; nothing was run on these targets. On RV64 and LA64 an offset
that fits in 12 bits goes to the case of MO_Add for such a literal,
or on RV64 for an offset from -2047 to -1 to that of MO_Sub, which
does not truncate either (on RV64 ISSUE 28133); on RV64 an offset
of -2048 goes to MO_Sub's general case, which truncates.
- getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG:
neither mangleIndexTree nor add_int narrows the offset
to the register's width, and cmmMachOpFoldM's folds of literals
into a CmmRegOff sum them unnarrowed). For a 16-bit register whose
offset lies outside 16 bits, add_int's LEA, printed as an ADD
of an immediate where the result takes the operand's register, makes
the assembler warn that it shortened the immediate (addw $90000,%ax
for a 16-bit register plus three times 30000); the shortened immediate
gives the value meant, so this costs only the warning, on x86
and x86-64. An 8-bit register's sum takes an ADD whose immediate
litToImm narrows, an LEA printed as an LEA takes the offset
as a 32-bit displacement without a warning, and a wider register holds
any offset add_int is given. This rests on master's code read
(mangleIndexTree, add_code, add_int and the printing of an LEA
as an ADD in GHC.CmmToAsm.X86.Ppr), on master's compiler, whose
assembly for such a sum in Cmm made the assembler warn so, and on GNU
as given addw and leaw with such an immediate and displacement,
with and without --32: it warned of the addw alone and assembled both.
- getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64
and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap
in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps
the number of the low half's unique): a 64-bit Cmm local and a 64-bit
NCG temporary with the same number share their high half, and where
both are live, writing one overwrites the other's high 32 bits.
This is wrong code on i386; 32-bit PowerPC, which uses the same
functions, was not tried. Equal numbers occur, as the NCG's uniques
count from 0 in each Haskell module (initDUniqSupply 'n' 0
in GHC.Driver.Main.Compile). In genByteSwap, equal high halves
with different low halves can arise so, and the branch for that case
swaps correctly. This rests on master's code read and ISSUE 28125's
record.
- verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG: nothing checks
that a block of native code ends in a transfer of control;
this checks, in a DEBUG compiler, only that nothing but jumps follows
a jump). A block that did not end in one would run on into whichever
block the layout puts after it, which is wrong code; no instruction
selector is known to make such a block. This rests on master's code
read.
- getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105:
each can emit a displacement outside the signed 32-bit range: -i where
i = -2^31; an offset left unchecked; and an offset checked only
at shift 3, as && binds tighter than ||): where the displacement does
not fit, the x86-64 assembler rejects the module. This rests
on master's code read and ISSUE 28105's record.
- getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset
plus a shift (BUG: nor is the offset narrowed to the register's
width). On i386 an offset outside 32 bits reaches the assembler, which
warns and shortens it modulo 2^32, to the address meant, so this costs
only the warning; on x86-64 such an offset is the BUG of ISSUE 28105
at the same clause. This rests on master's code read, nothing having
been compiled for i386, and on GNU as given such displacements
with --32, which it shortened with a warning and assembled.
- genPrim in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 27694: MO_UF_Conv's
genWordToFloat does not return the last block it adds, so a later
statement of the same Cmm block that splits its current block in turn,
as a second conversion does, moves the wrong block's edges): the CFG
lacks the edges of the jumps ending the Cmm block, and where
the linear allocator puts a fixup block on one of them,
addNodesBetween panics with "Can't find weight for edge that should
have one", the panic of ISSUE 27915. Where the second conversion's
last block is a lone jump, shortcutting (-fasm-shortcutting,
on at -O2, never on Darwin) cuts it, and shortcutWeightMap drops
its out-edges, which in the CFG are the only edges into the first
conversion's blocks; the blocks stay in the CFG, unreachable
from the entry and with edges, and classifyEdges
in GHC.Data.Graph.Directed, which findBackEdges calls
for optHsPatterns, panics with "Failed to classify edge of CFG -
not not timed" on an edge out of them. Both are reached on x86-64,
the only target for which backendMaintainsCfg holds, and
not under -finfo-table-map, under which no pass after instruction
selection gets a CFG. -dasm-lint does not catch the missing edges
first, as sanityCheckCfg compares the CFG's blocks with the code's
and not its edges. This rests on master's code read, the records
of ISSUE 27694 and ISSUE 27915, a run of master's compiler on a loop
with two word2Double# in one Cmm block: it panics in addNodesBetween
at -O, at -O2 and at -O -dasm-lint, and compiles at -O0
and at -O -fregs-graph, as the graph allocator makes no fixup blocks;
and a run of master's compiler on two word2Double# in one Cmm block
ahead of a loop: it panics in classifyEdges at -O2, at -O2 -dasm-lint,
at -O2 -fregs-graph, at -O1 -fasm-shortcutting
and at -O0 -fasm-shortcutting, and compiles at -O0, at -O1
and at -O2 -fno-asm-shortcutting.
- addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG: it gives every
unwinding table that does not name Sp the rule Sp has
at the procedure's entry, and the table that X86's addSpUnwindings
adds where the C stack pointer moves, as around a C call, names MachSp
alone). Up to the next table that names Sp, DWARF gives the canonical
frame address by Sp's rule at entry: after a C call, rbp+0 on x86-64,
where before the call it can be another offset, such as rbp+16.
A debugger unwinding from there finds the wrong frame. This is reached
under -g on ELF targets, on x86 and x86-64, as ncgDwarfUnwindings
holds on ELF targets under -g and addSpUnwindings is X86's. This rests
on master's code read and on readelf's reading of the frame table
of an object that master's compiler made under -g.
The other statements:
- backendMaintainsCfg in GHC.CmmToAsm.BlockLayout said that i386 should
work but is untested. It now says, as WIP, that i386 is left out
because it is untested and its iselExpr64 splits blocks for 64-bit
shifts without adding them to the CFG.
- genPrim's comment says that its remaining cases add no blocks, while
MO_UF_Conv's genWordToFloat adds blocks: the BUG above stands there.
- mkRegRegMoveInstr in GHC.CmmToAsm.X86.Instr says that its move clears
the upper part of the register. A TODO says that for a float
or a double it is MOV FF64, printed movsd, which keeps
the destination's upper half.
- invertCondBranches inverts a jump only after an integer comparison.
A TODO says that maybeInvertCond's complement on the flags is as sound
after a floating-point one.
- pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's
start, only a block with an info table (TODO, ISSUE 27668).
- condIntCode' tests a value against zero even on a path where
the instruction computing it has set ZF and SF from it, as on the back
edge of a loop that counts down: it sees only the comparison,
and another path into the test, such as the loop's entry, may set
no flags. Only a condition that reads ZF and SF alone could use
the flags of a dec, which writes OF and leaves CF where TEST clears
both (TODO, ISSUE 27738).
- GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO, that no module
imports it, and that its pass, which ran before allocation, has had
no caller since 2007, when it was taken out of the pipeline in favour
of the coalescing that GHC.Data.Graph.Color.colorGraph does.
Assisted-by: Claude Opus 5.5
-
fe8e80d0
by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
State the NCG's norms and where a branch's likely side is known
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's
own documents and testsuite hold the native code generator to, and what
each means for a change. Under -fobject-determinism the output
is bit-for-bit the same for the same inputs, so an order taken
from uniques is a question for review. The testsuite passes -dcmm-lint
by default, so a test written in Cmm must be one that Cmm lint accepts.
Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says
where the code generator learns which side of a conditional branch
is likely: where the branch is made, as for heap and stack checks;
upstream, and not carried down, for constructor-tag tests; and nowhere,
for the rest, to which static prediction applies its heuristics. It also
states the trade-offs kept with that knowledge, each with its reason:
conditions inverted so that the true side falls through even where
the false side is likely, and edges across calls left out when chains
are built and when neighbouring chains are combined.
Note [Norms of the NCG] points to it.
Assisted-by: Claude Opus 5.5
-
c4dfbac9
by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Rewrite the NCG's overview Note
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe.", "Which targets go
through the NCG, which of its parts each target uses, and what the NCG
takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes
in the order they run, and what each requires of the one before.",
"The invariants the code depends on." and "What the tests cover and what
they do not: which targets CI runs natively, which paths have few
or no tests, and which performance test exercises which pass."
Comments only; the generated code is the same.
Note [Native code generator], the module header of GHC.CmmToAsm, named
CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which
no longer exist, and machine-independent optimisations "defined below",
which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now
says:
- which targets go through cmmNativeGen, that wasm32 has a generator
of its own, and which back end the other targets get by default;
- what the Cmm pipeline hands over, and what the NCG takes from StgToCmm
and the RTS;
- the interfaces through which the machine-independent parts access
a target, and what only some targets have;
- the passes, in the order cmmNativeGen runs them, with the flags
that turn them on and the dump flags that show their output, and,
at step 4, what instruction selection must ensure;
- where the NCG's uniques come from;
- what the assembler and the linker do after it;
- the flags, testsuite directories and benchmarks for working
on the NCG.
For detail it cites the Notes and labelled statements of the preceding
commits.
Assisted-by: Claude Opus 5.5
-
7626094c
by Mikolaj Konarski at 2026-11-20T00:12:53+01:00
Propose two principles for the NCG
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two
principles to GHC's developers and says that the native code generator
does not keep them yet:
- correctness first: semantic correctness is not traded for a measured
gain that an incorrect form gives by accident, until a form with both
has been looked for and the trade agreed in review;
- one TODO set: a departure from correctness that is left in place
is marked TODO, as a member of one set that is accepted for now
and re-investigated together.
No other commit cites the Note, so this commit can be dropped
on its own.
Assisted-by: Claude Opus 5.5
-
8c411224
by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Add a README to the NCG's directory
Of what anyone working with the NCG needs, this commit serves "An order
in which to read the NCG's Notes.", "One place where the terms the NCG's
comments use are defined.", "One small function followed through
the NCG's dumps, in the order of its passes.", "Which parts of the NCG
were examined for bugs, half-done work and likely changes, and which
were not.", "The invariants the code depends on." and "How to find
the pass at fault for a miscompilation or a compiler panic, and how
to reduce the case to a Cmm test."
Documentation only; the generated code is the same.
compiler/GHC/CmmToAsm/README.md is a way in for anyone working
with the native code generator, whether reading its output and dumps,
tracking a fault to its pass, reviewing or making a change,
or maintaining it. It says what to read and what to do, and for each
fact about the code it cites a Note or a comment by name. Its sections:
- Where to start reading: three Notes of GHC.CmmToAsm, then Notes
on the passes, each with its module, in the overview's order.
- Vocabulary: the terms the NCG's comments use without defining them,
each with where it is defined or used.
- Finding the pass at fault for a wrong result or a panic: the oracles
to compare with, the flags that switch a pass off or swap it,
the lints, and how to cut a case down to a Cmm test.
- One function through the dumps: a small loop compiled at -O on x86-64,
with an excerpt for each dump flag in the overview's list of passes
but -ddump-asm-regalloc-stages, which prints nothing under the linear
allocator.
- Reviewing a change: the invariants the code depends on, as questions
by kind of change, each citing the Note or comment that states it.
- What the labelled statements cover: which parts of the NCG they
were first written from, and which were left out.
The excerpts are cut from the dumps of one compilation by a compiler
built from master: each of their lines but "..." is a line of a dump,
in the dump's order, with tabs replaced by spaces. Every Note, function,
module, flag and path the README names exists at this commit.
The overview, Note [Native code generator], now ends by pointing
to the README.
Assisted-by: Claude Opus 5.5
-
ba007117
by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
rts: run finalizers soon after the GC that finds them
scheduleFinalizers puts the finalizer thread at the end of the run
queue, and the thread whose heap overflow caused the GC goes back
to its front unless a context switch is pending. So under the RTS timer
the finalizers wait for the next context switch, 20 ms by default,
and whatever they would free stays live until then: a program that opens
and closes handles fast keeps every closed handle's buffers. nofib's
maillist, which appends to its output a line at a time, peaks at 16.6 MB
of residency where -V0 and -C0, whose scheduler switches whenever
another thread is runnable, keep 1.65 MB.
Request a context switch when scheduling the finalizers, so that they
run at the next block boundary. maillist then keeps 1.65 MB
under the default timer and runs 13.4% fewer instructions at -O2, 12.7%
at -O1 and 12.6% built at -O0. Across nofib, cacheprof runs 0.80% more
at -O2 and 0.96% at -O1, as it does under -V0: run promptly,
the finalizers lower the residency (cacheprof's peak 0.82 MB against
0.89 MB), so the major GCs, triggered by the old generation's size
against the live data, come more often (cacheprof's 148 against 143
at -O2). Built at -O0, gg runs 0.26% more and treejoin 0.46% fewer;
no other program moves by 0.2% beyond its run-to-run noise.
Figures of variants not taken were measured on earlier forms
of the series.
Fixes ISSUE 28060.
Assisted-by: Claude Opus 5.5
-
77cb8da1
by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Address a register offset directly in x86's getAmode
getAmode made the mode of CmmRegOff r n by mangleIndexTree r n, building
the sum r + n for the alternative of x + lit to take apart. It now gives
that alternative's mode, r's register with the offset n, directly,
under the same guard, is32BitLit of n at r's width, and where r
is not PicBaseReg; the other cases go to the mangled sum as before.
For the PicBaseReg condition isPicReg moves from GHC.Cmm.Opt, which did
not export it, to GHC.Cmm.Utils, which exports it and which x86's code
generator imports already. The code generated is the same.
Measured against its parent: nofib's objects are the same size,
as are containers', megaparsec's, vector's and A2T's, and the stage-1
compiler, built by GHC 9.12.4, runs 1.6% fewer instructions compiling
T3294 at -O0, 0.65% at -O and 0.64% at -O2; 0.56%, 0.19% and 0.17% fewer
compiling T12707; and 0.29% and 0.31% fewer compiling T9961 and T783
at -O0. The stage-2 compiler runs 0.090%, 0.065% and 0.11% fewer
compiling nofib's puzzle at -O0, -O1 and -O2, and 0.099% fewer compiling
nofib's programs at -O0 and 0.035% and 0.047% fewer at -O1 and -O2,
geometric means.
The test cmm_regoff loads and stores at q + k for offsets k on both
sides of the 32-bit displacement bounds, q passed as p - k so that
each access is at a known address.
Assisted-by: Claude Opus 5.5
-
756d0c3d
by Mikolaj Konarski at 2026-11-20T00:12:54+01:00
Gather a Cmm sum's literals into one constant, and narrow != as ==
To move into a merge request of its own, together with "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant", "Assign literals after computed values
at the end of a block" and "Drop the assignments that only a discarded
assignment read".
GHC.Cmm.Opt's special case (a - b) + c ==> a + (c - b) fired whatever b
and c were, and where c - b could not fold it put a literal on the left
of a subtraction, which x86 cannot encode as an immediate: containers'
Set.elemAt, at -O2, computed i + ((-1) - s) for its right step, a mov,
a sub and an add where a sub and a dec do. The reassociation (a + b) - c
==> a + (b - c) had the same flaw where b is a literal and c is not,
turning (x * y + 1) - w into x * y + (1 - w). This commit gathers such
sums into one normal form, which x86's code generator now computes
by one LEA or addressing mode (add_int, getAmode); and it narrows !=
against a literal, as ==, and a comparison of two operands widened
alike.
cmmMachOpFold now puts an addition or subtraction at one width
into the form of Note [Additive normal form] in GHC.Cmm.Opt,
its literals summed into one constant: e + k, k - e or e, a difference
e - k being left as it is where e has no constant. This takes the place
of the reassociations of (a + b) - c and (a - b) + c, and that of (a +
b) + c no longer moves a literal c from the top.
That reassociation, (a + b) + c ==> a + (b + c) where c is no literal,
is master's, and reassocAdd now does it: where a is neither a literal,
a register offset nor a MachOp and the folded b + c is a sum at the same
width whose right operand is no literal, it builds a + (b + c)
as it stands, since cmmMachOpFold would return that sum unchanged,
and it folds every other step by cmmMachOpFold, as master's code does.
A left-nested sum of n terms still takes n(n-1)/2 steps to become
right-nested, as in master's reassociation; each step is now cheaper.
The x86 code generator takes the sums left this way into one LEA:
add_int computes (a + b) + k as the address of that form and (a - b) + k
as (a + k) - b, and getAmode makes a complex addressing mode of (a +
b) + k and of (a + (b << s)) + k, and of the same forms less k. One
function, x86_offset_amode, makes these modes and add_int's address
of (a + b) + k: master's clauses of getAmode for x + lit and x - lit
and add_int's default alternative, master's LEA of x's register and k,
now share it. Master's clauses below them that take a shift stay, each
still reached: x + (y << s) by a sum with no literal, the swap
of a shift and a literal by a literal that is no 32-bit displacement,
and, where nothing folds, as at -O with -fno-cmm-sink, (x + k) + (y <<
s) for a register x by array indexing and x + ((y << s) + k)
by hand-written Cmm. Master's getRegister' now makes the LEA
of a register offset r + n directly, as add_int makes it of the sum
mangleIndexTree builds, without building the sum, where r is wider
than 16 bits. It leaves W8, which LEA does not take, and W16
to mangleIndexTree and add_int, which narrows n to r's width: at W16 n,
which cmmMachOpFoldM's folds of literals into a register offset leave
unnarrowed, can be wider than r, and the LEA, printed as an ADD
of an immediate where its result takes r's register, makes the assembler
warn that it shortened the immediate (addw $90000,%ax for a 16-bit x
plus three times 30000), as compiling the same with master's compiler
does. The BUG statement at getRegister''s case for CmmRegOff, which said
that a 16-bit register offset reached the assembler unnarrowed,
is deleted. Measured at the series' end against the clause taking W16,
nofib's assembly at -O1 and -O2 and that of the compile cells T3294,
T12707, T783, T9961 and ManyBasicBlocks is the same, and no cell rises
by 0.001% in instructions or allocation; narrowing n in the clause
itself instead, through Integer, made the cells rise by up to 0.088%
in instructions and 0.115% in allocation (ManyBasicBlocks at -O0).
The narrowing that compares a widened operand with a literal
at the operand's width listed MO_Eq but not MO_Ne, so a byte widened
to a word was tested with != after a zero extension; MO_Ne is added
beside MO_Eq. A comparison of two operands widened alike, from the same
width and both by zero extension or both by sign extension, is now done
at that width as well, under the literal case's rule for signedness
(ISSUE 2080), its tables moved to the top level to serve both. Vector's
awshcc and nofib's reverse-complement, lambda and parser gain where !=
is narrowed like ==, and the boot libraries' comparisons of two operands
widened alike, in text, bytestring and ghc-internal's eqWord32,
are narrowed too, containers running fewer instructions by them.
Gathering a sum's literals can fold a negative constant into a label's
offset, as master's own fold of a label less a literal does. AArch64's
code generator loaded a label at an offset fitting 12 signed bits
by an add whose immediate is unsigned, so an offset such as -8 made
its printer's check_off stop the compilation with an error; a negative
offset now takes the general path, which adds the offset
from a register. That is the fault ISSUE 28126 reports, so this commit
should fix it; the issue's test, which MR 16994 adds as expected broken
on AArch64, has not been run with it.
The tests cmm_fold_lit (Cmm, the reassociations and the narrowing)
and cmm_fold_elemAt (Haskell at -O2, Set.elemAt's step) fail without
these changes, and cmm_addnf compares each shape over boundary values
with the same formula computed in Haskell. cmm_fold_lit is skipped where
the word is 32 bits, where -dcmm-lint, which the testsuite passes
by default, rejects its assignments of a byte widened by %zx64 to a W_;
nothing was run on a 32-bit target. CmmRegOffW16, on x86-64 only,
compiles a 16-bit register plus three constants whose sum does not fit
16 bits, returned and assigned; the assembler's warning on its stderr
is its failure, and through the testsuite's driver, at the series' end,
it fails so with the clause taking W16 and passes without.
Measured against its parent: nofib's programs run 0.22% and 0.21% fewer
instructions at -O2 and -O1 and 0.079% fewer at -O0 (geometric means),
spectral-norm 11.8% fewer at -O2 and -O1, allocating the same;
containers' benchmarks run 0.26% and 0.24% fewer instructions at -O2
and -O1, megaparsec's 0.89% and 0.83% and vector's 0.61% and 0.60%.
The stage-1 compiler runs 2.3%, 1.8% and 1.8% fewer instructions
compiling MR 16269's CmmDiamondChain at -O0, -O1 and -O2, and at most
0.001% more on any compilation of T3294, T12707, T783 and T9961.
Compiling a Cmm procedure that rotates N locals in a loop and returns
their sum at -O1, it runs 0.991, 0.974, 0.940 and 0.898 times
the instructions at N = 50, 100, 200 and 400.
Compiled by the boot compiler, GHC 9.12.4, GHC.Cmm.Opt allocates 49%
more (2.040 against 1.369 GB), the cost of addNormalise's own code;
at the series' top it allocates 1.96 GB, 43% more than master's.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
42c5ef4a
by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Address (i << s) + lit on x86 by a scaled index with no base
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Take
the constant out of a shifted or scaled sum in Cmm's sums", "Fold
cmmOffset's offset into any sum with a constant", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
x86's getAmode took (i << s) + lit, the address of an entry of a closure
table, which tagToEnum# and a derived Enum's toEnum, succ and pred load,
by its default branch: the shift computed into a register, which became
the base, and lit the displacement, as shlq $3,%rax then movq
tbl(%rax),%rbx. Its clause for x + lit, which takes every literal
a displacement holds (is32BitLit), now takes such an x, s at most 3,
as an index scaled by 2^s with no base register and lit
the displacement, movq tbl(,%rax,8),%rbx, with the default branch's
relocation. The clause takes it by x86_offset_amode, the function
it shares with master's clause for x - lit and add_int's default
alternative, so add_int takes the value (x << s) + k into the same LEA,
and an address (j << s) - k, s at most 3, is made the same way, one
instruction shorter. The clause for (a << n) + lit stays,
for the literals x + lit does not take: a label on Windows (Note
[%rip-relative addressing on x86-64]) and an integer or a label's offset
wider than 32 bits, but gives the sum to x86_complex_amode itself, lit
the base, rather than turning it around; its comment says so. Master's
x86_complex_amode now takes the index term and finds the scale itself, i
<< s for s at most 3 scaled by 2^s and any other index unscaled,
so master's clause for x + (y << s) is deleted, the clause for x + y
making the same mode of such a sum. Under -fPIC and -dynamic a table's
label reaches getAmode as PicBaseReg plus the label or as a load
from the GOT, except on Windows, where it is a literal that x + lit does
not take, so those loads are unchanged.
Measured against its parent: nofib's programs run 0.033%, 0.029%
and 0.19% fewer instructions at -O2, -O1 and -O0 (geometric means),
at -O2 CSD 0.52% fewer, cryptarithm2 0.49%, ansi 0.42%, puzzle 0.35%
and cichelli 0.32%, none more by 0.2%, the geometric means of their
allocation unchanged; containers' benchmarks run 0.010% and 0.012% fewer
at -O2 and -O1, IntSet's eq 1.1% and spanAntitone of IntSet and IntMap
1.0% fewer, and vector's 0.086% and 0.082% fewer, findIndexR 1.7%
and 1.6%; megaparsec's geometric means fall by 0.039% and 0.038%
and A2T's sample runs 0.004% fewer, none of their benchmarks rising.
The stage-1 compiler runs at most 0.002% more instructions compiling
T3294, T12707, T783, T9961 and ManyBasicBlocks, and its allocation moves
by 0.003% or less.
The test cmm_scaledlit loads and stores at (i << s) + lbl for s from 0
to 3 and lbl plus or minus 8, and computes (x << s) + k at 64, 32, 16
and 8 bits for s from 0 to 4, with k small or at a bound of 32 bits
or of a narrower width, and at 64 bits past the 32-bit bounds, comparing
each with the same formula computed in Haskell; ClosureTblAmode checks
that tagToEnum#'s closure table is addressed with no base register,
and is skipped on Windows and where code is position-independent
by default.
Assisted-by: Claude Opus 5.5
-
496e20c0
by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Take the constant out of a shifted or scaled sum in Cmm's sums
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Fold cmmOffset's
offset into any sum with a constant", "Assign literals after computed
values at the end of a block" and "Drop the assignments that only
a discarded assignment read".
The additive normal form (Note [Additive normal form] in GHC.Cmm.Opt)
gathered the constants of an addition's operands only where an operand
was a sum, a difference, a register offset or a literal, so p + ((i + 1)
<< 3), the element after i of an array, kept its constant inside
the shift, and x86 computed i + 1 and the shift before loading. addView
now views an operand (e + k) << s or (e + k) * c at width w, k
an integer and s < w, as the term e << s or e * c with the constant k <<
s or k * c, the product distributing over the sum modulo 2^w, where
that constant narrowed to w fits in 32 bits; the old view is sumView.
p + ((i + 1) << 3) becomes (p + (i << 3)) + 8, one address of x86's
getAmode, and the closure table entry ((t - 1) << 3) + lbl becomes (t
<< 3) + (lbl - 8), with one label literal. Left as they are: (k - e) <<
s, whose term e << s would be subtracted, which no x86 address does,
while p + ((1 - j) << 3) + 24, an element of an array in nofib's fem,
gamteb and puzzle, is one address; and a constant wider than 32 bits,
which x86 would move into a register where k cost nothing, as in (x + 1)
<< 40.
Measured against its parent: nofib's CSD runs 0.78% and scs 0.21% fewer
instructions at -O2 and -O1, and built at -O0 dom-lt, n-body, kahan
and fannkuch-redux run 0.60% to 0.69% fewer and others by less,
no program more by 0.2%, the geometric means 0.012%, 0.013% and 0.066%
lower at -O2, -O1 and -O0; vector's benchmarks run 0.12% fewer at -O2
and -O1, nextPermutation and prevPermutation of a small vector 1.8%,
and A2T's sample 0.016% fewer, none of its cells more by 0.2%;
containers' and megaparsec's geometric means move by 0.007% or less;
allocation is unchanged in the packages' benchmarks and moves by 0.037%
or less in nofib's programs and A2T's cells. The stage-1 compiler's
instructions and allocation compiling T3294, T12707, T783, T9961
and ManyBasicBlocks change by 0.003% or less, and the stage-2 compiler's
allocation compiling nofib's programs moves by 0.001% or less at -O2,
-O1 and -O0 (geometric means).
The test cmm_fold_scaled checks in the Cmm dump p + ((i + 1) << 3), q +
(i + 2) * 24 and the two shapes left as they are, and cmm_addnf now also
computes such shifts and products as operands of additions
and subtractions, and loads at them, comparing each with the same
formula computed in Haskell. cmm_fold_scaled is skipped where the word
is 32 bits, where cmmMachOpFoldM folds (i + 1) << 40 to 0, i being 32
bits wide, and i386 passes no argument in the R2 it names; nothing
was run on a 32-bit target.
Assisted-by: Claude Opus 5.5
-
d13b40e4
by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Fold cmmOffset's offset into any sum with a constant
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
cmmOffset summed its offset into a MachOp only of the form e + k
and wrapped any other MachOp in a new addition, folding nothing. Sink's
inl_exp inlines a local's value into a register offset l + n
by cmmOffset, so that (e - 1) + 1 was left as it is: with Sink on,
the NCG never folds, ncgDoConstantFolding being not (gopt
Opt_CoreConstantFolding dflags || gopt Opt_CmmSink dflags). cmmOffset
now reads a MachOp through the additive normal form's own view, addView,
moved with sumView and their types from GHC.Cmm.Opt to GHC.Cmm.Utils,
and adds the offset to the constant of e + k, e - k and k - e alike:
a sum whose constant cancels becomes its term, a register plus
a constant a register offset. Every caller gets it, the NCG's jump-table
index among them. cmmOffset reads the view only of an addition
or a subtraction, never of the shift or product that addView takes
apart, so a local (e + k) << s inlined into an offset stays ((e + k) <<
s) + n, as before. Master's mkRODataLits tests its literals
by isLabelLit in place of its local needsRelocation.
At -O1 and -O2 a derived Enum's succ and pred each lose one instruction,
in nofib's puzzle and ben-raytrace and in ansi-terminal-types,
and dataToTag# x plus or minus a literal loses one; every other object
of nofib's programs at -O0, -O1 and -O2, of containers', megaparsec's
and vector's benchmarks at -O1 and -O2 and of their dependencies stays
the same size, and the instruction counts of puzzle and ben-raytrace
move by 0.0006% or less. The stage-1 compiler's instructions
and allocation compiling T3294, T12707, T783, T9961 and ManyBasicBlocks
change by 0.002% or less, and the stage-2 compiler's allocation
compiling nofib's programs moves by 0.001% or less (geometric means)
and by 0.025% or less in any program. Compiled by the boot compiler, GHC
9.12.4, GHC.Cmm.Utils allocates 40% more (1.066 against 0.760 GB),
sumView inlined into addView, and GHC.Cmm.Opt 11% less (1.955 against
2.208 GB); at the series' top Utils allocates 1.07 GB, about two fifths
again master's.
The test cmm_sinkoff sinks such values into an offset at 64, 32 and 8
bits, its constants at the wrap boundaries, and compares each
with the same formula computed in Haskell; cmm_swoff switches on e - k
and k - e at 64 and 32 bits over jump tables whose range starts at 100.
EnumTagOffset greps the assembly of a constructor's index plus 3 and
minus 1, and of the next and the previous constructor loaded from its
closure table: the - 1 that takes the index from the pointer's tag folds
into the literal and into the table's displacement, where the parent
commit's compiler subtracts it by an instruction of its own in each of
the four.
Assisted-by: Claude Opus 5.5
-
20f0c0ec
by Mikolaj Konarski at 2026-11-20T00:12:55+01:00
Predict an inequality with a literal in static branch prediction
ohPredicts, static branch prediction's opcode heuristic, predicts
that a comparison with a literal is unlikely to come out equal,
but it matched only MO_Eq. The control-flow optimisation turns
an equality into an inequality where that lets the test's true side fall
through (Note [Invert Cmm conditionals] in GHC.Cmm.ContFlowOpt),
and so spelt the same test went unpredicted, its two sides weighted
alike. ohPredicts now predicts the true side of an inequality
with a literal (0.7), as it predicts the false side of an equality,
except where an operand is masked by MO_And, as in a pointer tag test,
(x & 7) != 0, or a test of a bitmap's bits, or is a constructor tag: one
read from an info table, an unboxed sum's, a local register every
assignment to which is a tag, which a pass over the procedure's Cmm
finds, or one less than such a register. Whether those bits are set,
or which constructor a tag names, depends on the type or the data, which
the CFG does not record, so a test of a constructor tag is predicted
as before (Note [Static prediction of tag tests]). That pass
and ohPredicts take one less than a tag register in both its spellings,
CmmRegOff r (-1), as the sink leaves dataToTagLarge#'s r - 1 at -O1
and -O2, and the subtraction of 1, which stays under -fno-cmm-sink.
Predicting every inequality made containers' benchmarks take up to 3.1%
more instructions, through the tag tests of tree lookups; leaving out
only pointer tag tests, intmap fromSet took 1.3% to 1.8% more, through
buildTree's bitmap test.
The pass, tagRegisters, counts an unsafe foreign call's results among
a register's assignments, in a second pass over the blocks made only
where there is a candidate; no other node assigns a local register
in the code generator's input, a safe call being lowered to unsafe ones
before. It drops each candidate assigned a copy of a register that holds
no tag, or one less than such a register, once, and with
it the candidates assigned from it in turn, through a map
from a register to those (tagSource) built only where a candidate
is dropped: filtering all the candidates again until a pass dropped none
took time quadratic in the length of a chain of copies. Measured
at the series' end, each against the code without it: in a Cmm procedure
assigning r = n & 7 in one arm and (r) = ccall labs(n) in the other,
then testing r != 3, the test's edges were weighted 0.5 each without
the count of the call's result and are 0.7 and 0.3 with it;
in a procedure of N if-else diamonds in sequence, the k-th assigning xk
a copy of x(k-1) in one arm and x(k-1) & 7 in the other, then testing xN
!= 3, the compiler ran 30015211 and 2009023957 more instructions at -O1
than with the test xN > 3, for which the tag registers are not computed,
at N = 400 and 3200 (where the whole compile took 3346781123), and runs
3224188 and 33084927 more. With either change nofib's modules compile
to the same assembly at -O1 and -O2, and each compile cell stays within
0.01% of the allocation and 0.005% of the instructions it took before.
What this removes is a tie. In megaparsec's sepEndBy loop, a cold
continuation's edge into the loop's second head weighs as much
as the hot edge into it once "Hand calcFreqs a procedure's loops inner
first" estimates them, because the test before them, written as != 0,
is estimated 50/50; the tie gives the cold block the fall-through,
and every element a jump. With this commit the hot edge is the heavier
one.
The trade is k-nucleotide's hash table lookup: the exits of its bucket
loop, written as tests for zero, come out as != 0 and are now predicted
to stay in the loop, so that with the loop-exit heuristic the loop's
back edge outweighs its entry; block layout gives the back edge
the head's fall-through, and every first probe, which finds its key
about 95% of the time, pays a jump. The commit that lets a loop's back
edge outrank its entry makes this layout anyway. The gains include
containers' intmap compareSize:n (3.4% fewer instructions) and nubOrd
issue1202_repeat (0.89% fewer at -O1), and megaparsec's endBy (0.60%
to 0.64% fewer at -O2).
As a TODO at ohPredicts records, the exception goes by an operand's
form, not by what decides the test: a parity test, its mask inside
arithmetic, is predicted, and an evaluation test, (x & 7) != 0, is left
out with the constructor-tag tests; predicting evaluation tests
as evaluated, in either spelling, cost nofib 0.36% more instructions.
Leaving out as well parity tests, x `rem` 2^p, also as GHC.Cmm.Opt
rewrites it, x - ((x + c) & -2^p), and masks under a conversion, a shift
or the addition of a literal, leaves unpredicted 8 of the 1685
inequalities with a literal predicted in nofib at -O1 and 8 of 2282
at -O2, 220 of 21354 in the boot libraries and the ghc library
and at most 7 in each build of containers', megaparsec's and vector's
benchmarks. It moves nofib's programs by less than 0.06%
in instructions, the benchmarks of containers, megaparsec and vector
within the spread of their runs or by at most 0.016%, the cells
of orthotope's A2T benchmark by less than 0.1%, and the compiler's
instructions by at most 0.001% compiling perf/compiler's T3294, T12707,
T783 and T9961, its allocation not at all.
Measured against the parent commit, in instructions: nofib's programs
move by 0.003% or less at every level, in geometric mean, k-nucleotide
taking 0.46% more at -O2 and 0.26% at -O1; containers' benchmarks move
by 0.004% or less at both levels, the compareSize:2 rows of intmap
and intset and intset's deleteMax taking one instruction a call more;
megaparsec's take 0.028% fewer at -O2 and 0.023% at -O1; vector's move
by 0.005% or less; in orthotope's A2T benchmark maximumA.one over small
strided arrays takes two instructions a call more (0.4% to 0.6%),
and many of its cells take 0.2% to 0.4% fewer, both by a jump
in absAxesAndStartT: of the two return blocks that run back into the tag
test at its head, the layout now places before the test the one most
cells take, and maximumA.one's strided cells take the other.
No benchmark's allocation moves by 0.05% but k-nucleotide's, 0.16% more
at -O2 and 0.060% less at -O1; the compiler allocates at most 0.022%
more compiling perf/compiler's T3294, T12707, T783 and T9961.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
f7ed0249
by Mikolaj Konarski at 2026-11-20T00:12:56+01:00
Find a CFG's back edges by one depth-first search
findBackEdges classified every edge of the CFG (classifyEdges, which
timestamps the visits of a depth-first search from the entry) to find
the few that lead back to a block on the search's path. optHsPatterns
calls it on every procedure, at every optimisation level, to give back
edges their bonus. findBackEdges is now that depth-first search itself:
it visits the successors in the same order and collects, as it goes,
the edges into a block still on its stack, leaving out an edge
from a block to itself, which classifyEdges calls a self loop rather
than a back edge. classifyEdges and its EdgeType,
in GHC.Data.Graph.Directed, had no other user and are gone.
The generated code is the same: the assembly of perf/compiler's T3294,
T12707, T783 and T9961 at -O0 and -O, and the object code of nofib's
programs at -O2, are the parent's. The stage-1 compiler allocates 0.19%
less compiling T3294 at -O0, 0.74% less compiling T12707, 0.97% less
compiling T783 and 0.97% less compiling T9961; at -O, 0.32% less
compiling T12707 and 0.25% less compiling T783; and the stage-2
compiler, compiling nofib's programs at -O2, 0.23% less in geometric
mean and up to 0.39% less (real/compress2). Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, the stage-1 compiler allocates 0.19%
less.
Assisted-by: Claude Opus 5.5
-
079c10cc
by Mikolaj Konarski at 2026-11-20T00:12:56+01:00
Drop jumps over blocks dropJumps empties
dropJumps removes a block's last jump where it can fall through
to the next block, and a jump-only block it so empties stays as a label,
so that a jump over it to the block after is left as a jump to the next
instruction (x86-64's eb 00, which master's intmap benchmarks at -O1
carry). It now looks past the blocks that hold no code or that it leaves
holding none, by a fold from the end over the blocks it has already
processed, among which a block it leaves without code holds none
already. Looking ahead over the blocks still to process instead,
as first written, took time exponential in a run of blocks holding one
jump each; the fold builds the whole list before returning its first
block, and the compiler allocates 0.081% more compiling perf/compiler's
T783 at -O0 than with that look-ahead.
A block holding no code is one with no info table that holds only meta
instructions or none: under -g a block whose jump the layout dropped
keeps its unwinding information, and without -g the only meta
instruction a block can hold is the comment that GHC.Cmm.GenericOpt
makes of an assignment of a register to itself. The test is a function
of its own beside dropJumps, fallsTo: it succeeds at a block whose label
satisfies a predicate, passes over a block holding no code, and fails
elsewhere. Its first argument is the meta test, for a code generator
where the Instruction instance is not in scope; dropJumps passes
the class's isMetaInstr, and as the predicate canFallthroughTo where
the label has no info table.
dropJumps, master's function, is generic over the backends,
so this changes it on every backend. On x86-64 isMetaInstr holds only
of instructions that emit no code, and a jump over a block whose own
jump dropJumps dropped is dropped under -g as without it. On AArch64,
RV64 and LA64 isMetaInstr holds of PUSH_STACK_FRAME and POP_STACK_FRAME
too, which emit code, so there dropJumps rests on no block holding only
those: their code generators emit the two only around a C call, in one
sequence with the call, which nothing checks, and none of the three
backends was built for this change.
Measured against its parent: built at -O1, containers' intset folds
over sparse sets run 1.6% (foldr_elem) and 0.90% (foldl_elem) fewer
instructions and intmap's fromSetA 0.49% to 1.4% fewer, the geometric
mean 0.006% lower, and no benchmark rises; at -O2 containers' benchmarks
neither rise nor fall. nofib's programs move by less than 0.2% at every
level, and their geometric means, megaparsec's and vector's by 0.003%
or less; no cell of A2T's sample moves by 0.1%. The assembly of T3294,
T12707, T783, T9961 and ManyBasicBlocks is the parent's, and the stage-1
compiler runs at most 0.032% more instructions compiling them (T783
at -O0) and allocates up to 0.050% less (T9961 at -O0) and up to 0.035%
more (T783 at -O0).
fallsTo tests a block's instructions before it looks the block up
in the map of info tables, dropJumps' predicate looks the label up only
where the jump can fall to it, and dropJumps binds isMetaInstr strictly;
the comments there say what each other choice cost. Measured
at the series' end, against it with dropJumps passing only over blocks
with no instructions and with the x86-64 code generator's later tests
of the same question as functions of their own: at -O1 with -g nofib's
code changes in some procedures of ben-raytrace, cacheprof, fem, fluid,
hidden, scs, smallpt, minimax and simple, some losing a jump, the others
placing their blocks otherwise; several now equal their code without -g,
and none that equalled it differs. At -O2 with -g nothing changes,
nor does nofib's assembly without -g at -O1 and -O2; the code
of a constructed procedure at -O0 with a block holding only that comment
changes. The compiler runs 0.008% fewer instructions compiling T9961
at -O0, 0.052% fewer compiling T783 there and 0.010% fewer compiling
ManyBasicBlocks at -O1 and -O2, and allocates at most 0.002% more,
compiling T9961 at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
a58e1b1c
by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Let a loop's back edge outrank its entry in block layout
sequenceChain lays the blocks out by fusing chains along the heaviest
edges first, by the final edge weights. Under -fcmm-static-pred,
on at -O1 and -O2, those are the frequencies static prediction
estimates, which can rate a loop's back edge below its entry: where
the branch that decides whether the loop goes on has no back edge among
its targets, the other heuristics predict it, and they can predict
staying in the loop to be unlikely, as in a lookup down a tree (Note
[Static prediction of tag tests]). The entry then falls through
into the loop's head, and every iteration pays a jump back.
optHsPatterns gives back edges a bonus (increaseBackEdgeWeight),
but static prediction replaces the weights of the branches
its heuristics cover with its predictions, so that the bonus counts only
at those it leaves alone, a heap or stack check's and those whose
targets are all back edges, and at a two-way branch back
into the procedure's entry, whose weights static prediction starts from.
sequenceChain now raises (preferBackEdges) each back edge by a little
more than the weight of the heaviest edge into its head that is
not a call, a back edge or a self loop, which keeps the order of several
back edges into one head; Note [Layout relevant edge weights]. A back
edge out of a jump table is not raised: it cannot fall through,
so raising it would only take the head's fall-through from an edge
that can. Nor is a back edge out of a block with another successor:
that block executes its branch whichever successor falls through,
so falling through saves nothing an iteration, while every entry pays
a jump; leaving such edges out takes 1.55% off intset folds:sparse
foldr_elem and 0.78% off foldl_elem, and 6.4% off folds:dense
foldl'_maximum, at -O2. preferBackEdges takes the back edges
from findBackEdges, now exported.
The garbage collector's return to the block that made a heap or stack
check is no such loop: a back edge leaving a block that follows a failed
check stays as it is. checkFailures, in GHC.CmmToAsm.CFG, finds
those blocks: the targets of the less likely edges of a branch
that getCfg tags HeapStackCheck, one whose condition reads SpLim, HpLim
or BaseReg, and their successors, such as the block the garbage
collector returns to, which can be a continuation that a call returns
to as well. A block that follows such a block and whose one out-edge has
the code generator as its source, such as a block the register allocator
puts there, counts as following a failed check too (coldBlocks). Raising
those back edges too makes containers' benchmarks take 0.28% more
instructions (set fromAscList:fusion 3.2%, intset fromList:worstCase
3.0%); leaving out the blocks that follow a failed check but
not the block the register allocator puts after such a block, 0.09% more
(map alter insert 0.9%). A new Note, [Frequencies before register
allocation] in GHC.CmmToAsm.CFG, names two shapes coldBlocks misses:
the block allocMoreStack splits off a block the garbage collector
returns to, and a fixup block on a failure edge, which takes the edge's
tag. A TODO at coldBlocks points there. Building the set in GHC.CmmToAsm
instead, from checkFailures' blocks, the blocks allocMoreStack splits
off a cold entry block and the fixup blocks on an edge out of or
into a cold block, changed a few procedures' layout in nofib and moved
no figure measured, while costing up to 0.03% more compile allocation
at -O0.
Nor is a back edge into the one successor of the procedure's entry block
raised: the entry would then jump to that block at every call, which
a loop that seldom iterates does not win back. The RTS's entry code has
such loops, which retry on an indirection: raising their back edges made
stg_BLACKHOLE_info, stg_enter_info and stg_forceIO_info begin
with a jump into the loop, so that stg_BLACKHOLE_info ran an instruction
more for every blackhole entered. Where the code generator split
the entry block, as allocMoreStack does, and the block holding the rest
of its code has one successor, that successor stands in for the entry's.
Measured against the parent commit, in instructions; sequenceChain runs
only under -fblock-layout-cfg, on at -O1 and -O2. At -O2 nofib's
programs take 0.051% fewer (queens 1.2%, wheel-sieve1 1.0%, banner
0.47%), vector's benchmarks 0.41% fewer (leaffix 3.4%, rootfix 2.7%,
listRank 2.2%), containers' 0.099% fewer and megaparsec's 0.062% fewer
(reachOffsetNoLine 0.78%, reachOffset 0.46% to 0.60%); at -O1 nofib's
take 0.048% fewer (knights 1.3%, wheel-sieve1 0.99%, banner 0.44%);
fannkuch-redux moves by no more than its noise.
Some of containers' and megaparsec's benchmarks rise; the rises
are trades. The rule's own is the jump a loop's entry now pays, which
its iterations seldom win back: intmap lookup_mixed 2.0%, whose lookups
gain nothing from the descent that now falls through, and intset's
intersection and difference benchmarks, about 0.7%: the continuation
that evaluates the second set now jumps into differenceTip's descent,
a loop whose head has two back edges and which runs no iteration where
that set is a Tip, as in these benchmarks, while IntMap's lookups,
of the same shape, iterate about sixteen times an entry and gain 2.5%
to 3.0%; no static rule tells the two apart. megaparsec's hexadecimal,
decimal and octal at -O1 pay the same jump, and so does megaparsec's
scientific.4000, which calls decimal's decimal_: 20 instructions more,
as decimal.4000.
The fused rows, containers' map fromDistinctDescList:fusion, map and set
fromList-distinctAsc:fusion, and map fromListWith-asc:fusion
and fromListWithKey-asc:fusion, take 0.4% to 0.8% more at -O2, and set
fromDistinctDescList:fusion 0.90% more. Raising back edges only
into heads outside every enclosing loop reverts them, and with them
nubInt's noFusion_repeat, which pays the same jump into IntSet's member,
1000 instructions a run, and issue1202_repeat, intmap lookup_mixed
and intset alterF:delete:present; but it gives back the gains of intmap
lookup_hits, lookup_most and index (2.9% to 3.0%), lookup_misses (2.5%),
intset member and alterF:member (1.0% to 1.1%), and vector's listRank
(2.2%) and awshcc (1.8%), at -O2.
Where two back edges raised alike into one head tie, the static order
breaks the tie: at -O1 megaparsec's reachOffset pays 78000 instructions
a call, isWideChar's loop head having two back edges, tied, and the tie
going by label order to the one that ASCII input never takes. Flipping
the order takes 4.0% off intmap lookup_half, 2.0% off lookup_mixed
and 1.2% off intset alterF:delete:present, and at -O1 1.1% off
megaparsec's reachOffsetNoLine and 0.8% off errorBundlePretty, but adds
2.5% to nofib's fasta at -O2 and 1.2% at -O1, gives back 96% of banner's
gain, and adds 5.9% to intset fromAscList:fusion, 2.3% to fromAscList,
1.3% to mapMonotonic and, at -O1, 0.9% to vector's next
and prevPermutationBijective; the static order is kept.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The stage-1 compiler allocates 0.11% and 0.14% more compiling
perf/compiler's T12707 and T783 at -O and 0.097% and 0.13% more at -O2,
and 0.22% more compiling MR 16269's CmmDiamondChain at -O1 and -O2;
elsewhere its allocation moves by less than 0.03%. The stage-2 compiler
allocates 0.25% and 0.23% more compiling nofib's reptile and puzzle
at -O2. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.BlockLayout allocates 14% more (1.143 against 1.001 GB).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
914c7f1e
by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Hand calcFreqs a procedure's loops inner first
calcFreqs estimates block frequencies by Wu and Larus's algorithm, which
takes the loops from inner to outer, as its comment says: an enclosing
loop's frequencies use the cycle probability of each loop inside it,
computed when that loop is processed. mkGlobalWeights handed
it the loops in loopInfo's order, by back edge in the order of the CFG's
labels, so an enclosing loop could come first. calcFreqs then took
the probability of an inner loop's back edge itself, often 1.0,
for that loop's cycle probability, which calcFreqs caps at 1 - 1/512,
so the inner loop's head counted up to 512 times as often as
it was entered. The cycle a heap check makes through the garbage
collector is such an inner loop in any loop that allocates:
in containers' map benchmarks, the head of the loop that looks keys up
was estimated to run several times as often as the edges into it.
mkGlobalWeights now sorts the loops by the size of their bodies,
an inner loop's body being a proper subset of an enclosing one's.
This makes block layout lean on the estimate more. Taking a procedure's
loops in label order could make a head's frequency up to 512 times
its inflow, so that the loop's back edge won by accident; where static
prediction calls staying in a loop over a tree unlikely (Note [Static
prediction of tag tests]), it is now the rule that a back edge outranks
the loop's entry ("Let a loop's back edge outrank its entry in block
layout") that keeps layout from following the estimate.
Measured against the parent commit, in instructions; calcFreqs changes
the generated code only under -fcmm-static-pred, on at -O1 and -O2.
No nofib program moves by 0.2%, no benchmark of containers or megaparsec
rises at -O2, and vector's benchmarks take 0.034% fewer at -O2
(findIndexR_manual 1.07% fewer) and fannkuch-redux 0.19% fewer.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The compiler's allocation compiling perf/compiler's T3294, T12707, T783
and T9961 moves by 0.004% or less.
Assisted-by: Claude Opus 5.5
-
234ccd4d
by Mikolaj Konarski at 2026-11-20T00:12:57+01:00
Count self loops as loops in static branch prediction
loopInfo took an edge for a back edge where its target dominates
its source, by mkDomMap's sets, which hold a block's own label only
where the block is a leaf of the dominator tree. So a self loop counted
as a back edge only from a leaf, and the retry of an atomic operation
that x86 emulates with a compare-and-swap loop (cmpxchg_code), whose
block dominates the block after it, counted as none: calcFreqs then took
that block for irreducible and gave frequency 0 to it, to every block
it dominates and to their edges, a surrounding loop's back edge among
them. mkDomMap's sets now hold each block's own label but the root's,
so that a self loop counts as a back edge but at the root, which no edge
enters as a back edge. mkDomMap also builds the map in one fold
over the dominator tree, inserting each block but the root as it walks
the tree, where it built a list of pairs, each block
with its dominators, and made a map of the list. The fold is taken
from Simon Jakobi's MR 16269, for ISSUE 27448, which also changes what
the sets hold. This fixes ISSUE 28093, self loops missed as back edges,
as MR 16269 does.
The retry edge cmpxchg_code adds now has a TransitionSource of its own,
AsmCodeGenRetry, which staticBranchPrediction leaves out of its rule
that a back edge is more likely than any other edge, so that the retry
is predicted to be rare rather than to repeat seven times in eight. Note
[Static Branch Prediction] says so. Andreas Klebinger's MR 16535
overlaps with this commit at that edge: it builds that loop's edges
by continueInNewBlock and addColdSelfLoop, and the two changes conflict
there.
The back edges staticBranchPrediction tests were a Set of pairs,
master's, looked up for each successor of each block; they are now
a LabelMap from each block to the LabelSet of the blocks its back edges
enter, looked up once a block.
Measured against the parent commit, on x86-64: the assembly
of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O
is the same, and so are the objects of nofib's programs at -O2;
of containers' objects only graph-benchmarks' Main changes,
and no benchmark of containers, vector or megaparsec moves beyond
its noise. The stage-1 compiler allocates at -O 5.5% less compiling
perf/compiler's T783, 0.35% less compiling T12707, 0.25% less compiling
T3294 and 0.008% less compiling T9961, and 27.6% and 27.5% less
compiling MR 16269's CmmDiamondChain at -O1 and -O2. Most of the saving
is the fold's, at T783 and CmmDiamondChain. At -O0, where static
prediction is off, the allocation moves by 0.002% or less.
Assisted-by: Claude Opus 5.5
-
87329858
by Mikolaj Konarski at 2026-11-20T00:12:58+01:00
Specialise the linear allocator and liveness pass to x86-64
The linear allocator is overloaded in the instructions and in the free
registers, and the liveness pass in the instructions, so on x86-64 too
they called every instruction method through a dictionary: the code
generator is specialised for each target, but its calls of regAlloc
and cmmTopLiveness went to the overloaded functions. Both now have
a SPECIALISE pragma for x86's instructions, and NOINLINE [0], without
which neither rule fires, when the boot compiler builds stage 1 or when
the stage-1 compiler builds stage 2: cast worker/wrapper makes each
function an alias of its body, cast to UniqDSM, and the alias inlines
from the function's own phase whatever its rules' phase, so it inlines
into the code generator before the call there becomes one at x86's
instructions, which is what the rule rewrites. A phase on the SPECIALISE
pragmas alone, [0] or [2], makes neither rule fire. linearRegAlloc
passes the other targets' free registers through a NOINLINE function,
which the specialiser does not specialise, so that only x86-64's get
a copy of the allocator; Note [Specialising the linear allocator].
The allocator's constraint synonym no longer requires Outputable free
registers, which nothing prints, and is renamed
from OutputableRegConstraint to RegAllocConstraint. Liveness.hs now
imports GHC.CmmToAsm.X86 for its Instruction instance, which Linear.hs,
importing Liveness.hs, has as well, so the allocator's modules
that import either compile after the x86 code generator; this makes
no import cycle, as of the allocator's modules the x86 code generator
imports only GHC.CmmToAsm.Reg.Target.
Specialising joinToTargets as well, with NOINLINE [0], saved
the compiler less allocation than this commit does.
The idea of specialising the allocator comes from the draft MR 4764
by Ben Gamari and Andreas Klebinger, which overlaps with this commit:
MR 4764 specialises the linear allocator to x86-64 and i386,
by INLINEABLE pragmas on the allocator's functions and SPECIALIZE
pragmas in GHC.CmmToAsm.X86, and this commit specialises it
and the liveness pass to x86-64, by the SPECIALISE pragmas above.
The generated code is the same: nofib's object files are the parent's
size. The stage-1 compiler allocates 1.8% less compiling perf/compiler's
T3294 at -O0 and 0.66% less at -O, 1.2% less compiling T12707 at -O0
and 0.40% less at -O, 1.0% less compiling T783 at -O0 and 0.20% less
at -O, and 1.7% less compiling T9961 at -O0, though only 0.014% less
at -O, where CI compiles it. Compiling MR 16269's CmmDiamondChain at -O1
and -O2, it allocates 0.55% less. Compiled by the boot compiler, GHC
9.12.4, GHC.CmmToAsm.Reg.Linear allocates 59% more (2.590 against
1.625 GB) and GHC.CmmToAsm.Reg.Liveness 28% more (2.095 against
1.640 GB). The compiler's code grows by about 100 KB. The series'
figures for its pragmas, these among them, come from stage-1 compilers
built by GHC 9.12.4; at the series' top a stage-2 compiler
with the series' pragmas, against one without them, keeps every sign:
compiling T3294, T783, T12707 and T9961 at -O0, -O and -O2 and MR
16269's CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, it runs
0.032% to 4.7% fewer instructions and allocates 0.038% to 4.1% less.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
2028ebe5
by Mikolaj Konarski at 2026-11-20T00:12:58+01:00
Record the linear allocator's spills only for -ddump-asm-stats
recordSpill kept every spill and reload the linear allocator inserts,
with its reason, in ra_spills, for the statistics -ddump-asm-stats
prints, their only reader. It now keeps them only when that flag is on.
The statistics printed are the same, and so is the generated code.
The stage-1 compiler allocates 0.20% less compiling perf/compiler's
T3294 at -O0.
Assisted-by: Claude Opus 5.5
-
03af9ec6
by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Check the order of liveness SCCs where jump targets are looked up
computeLiveness checked that a procedure's SCCs come in reverse
dependency order (checkIsReverseDependent) in a walk of its own,
gathering every instruction's jump destinations, and panicked otherwise.
The liveness pass looks every jump target's live-in registers up anyway,
taking none for a target missing from its map; that lookup now panics
instead, naming the target. For this, livenessSCCs enters the blocks
of a cyclic SCC in the map before the SCC's first walk, with no register
live, which is what the lookup took them to have, so that a target can
be missing only where the SCCs are out of order, or where the CFG
that gave the reachable blocks (sccBlocks) lacks it. The separate walk
goes, and with it computeLiveness, which then only called livenessSCCs:
regLiveness calls that itself. The generated code is the same.
The stage-1 compiler allocates 0.62% less compiling perf/compiler's
T3294 at -O0 and 0.24% less at -O, 0.55% less compiling T12707 at -O0
and 0.22% less at -O, 0.68% less compiling T783 at -O0 and 0.16% less
at -O, and 0.67% less compiling T9961 at -O0. Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, it allocates 0.13% less.
Assisted-by: Claude Opus 5.5
-
d3c2afe1
by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Keep a procedure's imports only where they are emitted
cmmNativeGens forced the imported symbols of each procedure, rendered
as text, to avoid a space leak, and kept them for makeImportsDoc, which
emits them only where needImportedSymbols holds; on x86-64 Linux
that takes -dynamic -fno-PIC. Where needImportedSymbols does not hold,
cmmNativeGens now neither forces nor keeps them. The generated code
is the same, also under -dynamic, -fPIC and -dynamic -fno-PIC.
The stage-1 compiler allocates 0.15% less compiling perf/compiler's
T9961 at -O0.
Assisted-by: Claude Opus 5.5
-
953e142b
by Mikolaj Konarski at 2026-11-20T00:12:59+01:00
Copy no register list in x86's mkRU where every register counts
regUsageOfInstr on x86 and x86-64 filtered both of an instruction's
register lists, keeping the virtual registers and the real ones
an allocator may hand out (interesting), and so copied both lists
for every instruction. mkRU now returns a list unchanged where every
register in it is kept. Sylvain Henry's MR 16843 (ISSUE 28008) overlaps
with this commit: MR 16843's register usage DSL tests each register
as it adds it, but copies a list of registers it is given as it tests
them, where this commit returns such a list unchanged when every
register in it is kept. The generated code is the same. The stage-1
compiler allocates 1.2% less compiling perf/compiler's T3294 at -O0
and 0.46% less at -O, 0.76% less compiling T12707 at -O0 and 0.24% less
at -O, 0.53% less compiling T783 at -O0, and 1.5% less compiling T9961
at -O0. Compiling MR 16269's CmmDiamondChain at -O1 and -O2,
it allocates 3.3% less.
Assisted-by: Claude Opus 5.5
-
3762a8fb
by Mikolaj Konarski at 2026-11-20T00:13:00+01:00
Mark the registers an instruction clobbers allocated, free or not
clobberRegs marked allocated those of the registers an instruction
clobbers that were free, listing the free registers of every class
for each instruction that writes a real register, with its own copy
of allFreeRegs from GHC.CmmToAsm.Reg.Linear.FreeRegs, and looking each
clobbered register up in the list. The FR class now has frClobberRegs,
which marks the clobbered registers allocated: by default those of them
that are free, by allFreeRegs, as clobberRegs did, since on AArch64,
RISC-V and LoongArch allocateReg panics on a register already allocated;
on x86-64, whose allocateReg marks a register that is not free
as it marks a free one, it marks every one of them, listing nothing.
clobberRegs calls it, and GHC.CmmToAsm.Reg.Linear no longer imports
the register class modules that only the copy used. The free registers
after a clobber are the same on every target, and so is the generated
code on x86-64.
The stage-1 compiler allocates 0.093% less compiling perf/compiler's
T3294 at -O0, 0.42% less compiling T12707, 0.47% less compiling T783,
and 1.2% less compiling T9961; at -O, 0.13% less compiling T12707.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.49%
less. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.FreeRegs allocates 73% more (0.489 against
0.283 GB).
Assisted-by: Claude Opus 5.5
-
3850efc8
by Mikolaj Konarski at 2026-11-20T00:13:00+01:00
Keep an instruction's register usage in its liveness
The liveness pass's backward walk computes the register usage of every
instruction it annotates (regUsageOfInstr), and its forward walk
(livenessForward), the linear allocator's genRaInsn and the graph
allocator's spill cost (slurpSpillCostInfo) and spiller (regSpill_instr)
computed it again. Liveness now keeps it (liveUsage), and those use
the kept usage instead. patchRegsLiveInstr, which only the graph
allocator reaches, computes the patched instruction's usage again,
as an instruction's usage can depend on whether its registers are equal:
x86's VXOR of a register with itself into itself reads nothing. A new
Note in GHC.CmmToAsm.X86.Instr, [What x86's regUsageOfInstr reports],
lists that case with the others where the usage is not what
the processor does. This commit overlaps with Sylvain Henry's MR 16843
(ISSUE 28008), which keeps the usage in the liveness annotation too
and also builds it more cheaply in every backend, but has neither
that Note nor the two changes to genRaInsn below; MR 16843 was read
before this commit was written. genRaInsn also takes the list
of the virtual registers an instruction reads as it is built, where
master passed it through nubOrdOn to remove repeats: a register read
twice is found at its second lookup in the register its first gave it,
so that the instruction is patched alike, and Data.Containers.ListUtils
is no longer imported. It also patches an instruction's registers
without master's patch_map, a UniqFM that listToUFM built for every
instruction from the virtual registers the instruction reads and writes,
paired with the real registers allocated to them: patchLookup takes,
by unique, the register of the last written pair whose vreg is the one
it is given, or else of the last read one, the entry listToUFM kept.
The generated code is the same, with the linear allocator
and with -fregs-graph. The stage-1 compiler allocates 3.8% less
compiling perf/compiler's T3294 at -O0 and 1.4% less at -O, 1.8% less
compiling T12707 at -O0 and 0.54% less at -O, 1.3% less compiling T783
at -O0, and 2.3% less compiling T9961 at -O0. Compiling MR 16269's
CmmDiamondChain at -O1 and -O2, it allocates 0.34% less.
Assisted-by: Claude Opus 5.5
-
33aad82b
by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Walk a block of a cyclic SCC again only when its successors change
livenessSCCs annotated the blocks of a cyclic SCC by walking all of them
again until the registers live on entry to every block stopped changing,
comparing two whole block maps as lists after each round. livenessCyclic
now walks a block again only when the registers live on entry to one
of its successors in the SCC, or their formats, have changed since
its last walk. A block walked again takes each instruction's usage
from its last walk (livenessBlockAgain), and master's liveness1 hands
the usage it computes to liveness1U, which the two share. The old loop
compared only which registers are live (the Eq of Regs ignored formats),
so it could stop before a wider format had reached every block
of the SCC, the case Note [Register formats in liveness analysis]
describes; the new one carries formats through as well, and Regs' Eq now
compares them too. This fixes ISSUE 27619 and does what ISSUE 27437
asks: the walk itself finds the changes, and no whole block map
is compared. Two vector formats of a register are now compared by width
where the liveness join keeps the wider (compareFormats) and where
a write kills a vector value no wider than the format written.
This commit overlaps with MR 16537, Simon Jakobi's, which fixes both
issues by iterating the fixpoint over the SCC's blocks until the formats
of the registers live on entry converge. An earlier version of MR 16537
also removed the derived Ord of formats, comparing them by width,
and this commit follows that version in comparing vector formats
by width and takes its regression test T27619 unchanged; it follows MR
16537 in carrying the formats through, and walks again only the blocks
whose successors changed where MR 16537 walks every block of the SCC
each round.
The liveness join keeps the wider of two vector formats of a register:
compareFormats, in GHC.CmmToAsm.Reg.Regs, compares two vector formats
by width, and two vectors of one width, as every other pair, by Format's
derived Ord, so that the order stays total. minusCoveredRegs lets
a write kill a vector value no wider than the format written,
and master's shrinkingRegs, which nothing calls, is deleted.
In liveness1U, delCoveredRegs, new in GHC.CmmToAsm.Reg.Regs and sharing
minusCoveredRegs' test of whether a write kills a value, takes
the registers an instruction writes out of the live set without building
their set, where master's liveness1 built it by mkRegsMaxFmt
for minusCoveredRegs. The derived Ord, which ISSUE 27619 also notes,
ranks a vector by its number of elements before their format: by it,
the join could keep a register read at two vector formats
at the narrower, and a write at the narrower kill a value live
at the wider, cases no x86 input was found to reach, and a write killed
no value live at a format of its width ranked above its own. The new
unit test testFormatWidths, in regalloc_unit_tests, checks the join both
ways and the kill between formats of different widths and of one;
it fails without the width comparison.
The generated code is the same on every program measured outside SIMD
code. Of perf/compiler's T3294, T12707, T783 and T9961, only T9961 at -O
has a cyclic SCC, and the stage-1 compiler's allocation compiling
it moves by 0.006%; compiling nofib's programs at -O2, the stage-2
compiler allocates 0.30% less in geometric mean and up to 4.2% less
(spectral/puzzle). Compiling MR 16269's CmmDiamondChain at -O1 and -O2,
the stage-1 compiler allocates 31.9% and 31.8% less. Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Liveness allocates
23% more (2.312 against 1.886 GB) and GHC.CmmToAsm.Reg.Regs 12% more
(0.208 against 0.186 GB).
In SIMD code, of the testsuite's simd tests compiled at -O1 and -O2,
with and without -mavx2, int32x4_basic and word32x4_basic,
with and without _baseline, lose a register move without -mavx2
to the width comparison: SSE2's Int32X4 insertion writes at VecFormat 4
FmtInt32 registers it reads at VecFormat 4 FmtFloat, so that
by the derived Ord the write killed nothing and those registers
were live into the procedure. int8x16_arith and word8x16_arith change
a symbol's name only, and every other test that compiles gives the same
code, as nofib's multiplier, primes, puzzle and para do. Compiling
perf/compiler's T3294, T783, T12707 and T9961, MR 16269's
CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, the width
comparison changes the compiler's instructions and allocation hardly
at all.
livenessCyclic takes the blocks to walk highest position in the SCC
first. With them taken in the order queued, the compiler ran 4.3% more
instructions and allocated 5.5% more compiling CmmDiamondChain at -O0,
and 3.6% and 4.5% more at -O1 and -O2; with the lowest taken first, 5.7%
more instructions at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
d0c85638
by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Fill in liveBorn only for the graph allocator and -ddump-asm-liveness
The liveness pass recorded, for every instruction, the registers born
there (liveBorn), which costs a forward walk over every instruction
of every block. Only the graph allocator and -ddump-asm-liveness use it.
regLivenessBorn is now a pass of its own, which the graph allocator,
its iterative variant included, runs on its input and again after
recomputing liveness, and which CmmToAsm runs only for the dump.
The generated code is the same, with the linear allocator
and with -fregs-graph. The stage-1 compiler allocates 2.5% less
compiling perf/compiler's T3294 at -O0 and 0.91% less at -O, 1.8% less
compiling T12707 at -O0 and 0.63% less at -O, 1.7% less compiling T783
at -O0 and 0.29% less at -O, and 2.2% less compiling T9961 at -O0;
with -fregs-graph it allocates up to 0.3% more (T9961 at -O0). Compiling
MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.85% less.
Figures that the per-commit measurements do not cover were measured
on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
973fc6e4
by Mikolaj Konarski at 2026-11-20T00:13:01+01:00
Prefer the register a vreg is moved into where it dies
The linear allocator preferred, for a vreg, the first register
it was recorded in on entry to any block (findPrefRealReg); Note [The
first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, gains a paragraph saying
that the first jump into a block decides that register too.
The allocator now has preferences, tried best first. firstFreeInOrder
takes the free registers of the vreg's class and returns the first
preference among them, else the first of them. allocRegsAndSpill_spill
takes its choice, and so does saveClobberedTemps, which took the first
free register where it moves a value out of a clobbered one. This commit
adds one preference, ahead of the first-used register: the real register
the current block moves the vreg into where the vreg dies. A value
computed into a vreg that the block then moves into R1, before
an evaluation or a return, is computed in R1, and the move, now
from a register to itself, is dropped by genRaInsn. The first-used
register, which keeps a loop variable in one register at both ends
of a loop, gains nothing for a value that dies in the block. Ranked
after it, the new preference cost nofib's scs 0.2% more instructions
once later commits changed the order of the free registers: a spilled
value was reloaded into its first-used register and then moved into R1's
register. processBlock builds, for each block, the map from a vreg
to the register the block moves it into where it dies (dyingMoves,
rc_moveDests). The preference is taken from Andreas Klebinger's MR
16693, whose choice of a free register prefers the real register a vreg
is moved into where it dies, in any block (ISSUE 27742); this commit
takes the moves of the current block, a subset of those.
The map lives in a record of its own, RA_Context, which RA_State holds
in one strict field (ra_context), rather than in RA_State itself, where
an unused field alone makes the compiler allocate 0.3% more compiling
T3294 at -O0. The NCG configuration, which the allocator uses but does
not update either, moves there too (rc_config, was ra_config), and runR
takes the context in its place.
The expected assembly of codeGen/should_gen_asm's T24813 loses the movq
before each function's jmp: each popcount is now computed in R1.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs, linked with the same libraries for both, take 0.26%
fewer (0.26% at -O1, 0.72% at -O0), none as much as 0.2% more beyond
their run-to-run noise; vector's benchmarks 0.27% fewer, none more;
containers' 0.41% fewer, none as much as 0.1% more beyond their noise;
megaparsec's 0.51% fewer (skipSomeTill 1.3%, endBy1 1.2%), none more;
fannkuch-redux moves by no more than its noise at -O2 and -O1.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The stage-1 compiler allocates 0.10% more compiling perf/compiler's
T12707 at -O0, 0.19% more compiling T783, and 0.085% more compiling
T9961; compiling T3294 its allocation moves by 0.029% or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
9a74616a
by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Prefer a vreg's register at a recorded jump target (ISSUE 27980)
firstFreeInOrder now puts first the register the vreg has on entry
to a jump target of the current block whose assignment is already
recorded (jumpLocRegs), such as a loop header jumped to from the loop's
end: in that register the vreg needs no fixup move at the jump.
For a target not yet reached, it takes the recorded assignments
of the blocks that target jumps to, up to three jumps on. The first-used
register, which a loop variable took until now, is the one the vreg
was recorded in by whichever block recorded it first, which need
not be the target. processBlock looks up the recorded assignments
of the block's jump targets once, when the block starts (rc_jumpLocs,
in RA_Context), taking the targets from a map of each block's jump
targets that linearRegAlloc' builds once for the procedure (jumpSuccs):
a target's assignment is recorded only at the block's jumps, after which
no preference is looked up. Built lazily, that map makes the compiler
allocate 0.3% more compiling perf/compiler's T3294 at -O0.
In ISSUE 27980's reproducer the loop's continuation then reloads
a variable straight into the register the loop header has it in,
and the fixup block goes away. vector's quickhull and nofib's sphere
and fibheaps show the same pattern, a rotation through a spill slot
gone. It is a preference, applying where the block that gives the vreg
a register jumps to a target whose assignment is recorded and the vreg's
register there is free; the fixups of ISSUE 27800, of which ISSUE 27980
was closed as a duplicate, stay.
The test, T27980, is the Cmm of ISSUE 27980's reproducer, its allocator
statistics (-ddump-asm-stats) searched for fixup moves: with the parent
commit's compiler the loop's back edge pays one.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's sphere takes 0.28% fewer at -O2 and fibheaps 0.24% fewer at -O1,
vector's quickhull 0.68% fewer at -O1, and no other program of nofib's,
benchmark of vector's or fannkuch-redux moves by more than its noise;
containers' benchmarks take 0.010% fewer (intset mapMonotonic 1.4%)
and megaparsec's 0.004% fewer (hexadecimal.4000 0.12%), none as much
as 0.1% more beyond their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.34%,
0.56% and 0.50% more compiling perf/compiler's T12707, T783 and T9961
at -O0, 0.16% and 0.19% more compiling T12707 and T783 at -O, and 0.32%
more compiling MR 16269's CmmDiamondChain at -O1 and -O2, and 0.046%
less compiling T3294 at -O0; the stage-2 compiler allocates 0.079%,
0.079% and 0.20% more compiling nofib's programs at -O2, -O1 and -O0
(geometric means). Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 24% more (3.171 against 2.562 GB).
The look-ahead past a target not yet reached, to the recorded
assignments of the blocks it jumps to, is a trade in the sample
of orthotope's A2T benchmark. Shaped's maximumA.one over small strided
Unboxed and boxed arrays takes three instructions a call more (up
to 0.88%), and Shaped's minimumA and maximumA over small dense Unboxed
and boxed arrays two more: the look-ahead leaves a swap of two registers
through a spill slot on the hot edge into a join of Shaped's operations,
where the parent commit paid the same swap on another edge. Without
that look-ahead the six cells are back at the parent commit's counts
or below, but its gains go: Ranked's convertE over small dense boxed
arrays takes 3.1% more and Shaped's ==.rank1 over small dense Unboxed
arrays 1.4% more, and the 384 cells this commit improves give back 190.8
of the 5218.3 instructions a call they gain. That toggle was measured
on the A2T sample alone. A fix would need block frequencies before
register allocation.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
03790c0d
by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Prefer the register a later block moves a vreg into where it dies
firstFreeInOrder now has a last preference: the real register a block
the vreg is live into moves it into where it dies, for a vreg computed
blocks earlier, such as R1 for a value evaluated some blocks after
it is computed (wideMoveDests, once a procedure; rc_wideDests).
The blocks that follow a failed heap or stack check, such
as those calling the garbage collector, do not count: the move there
seldom runs, and the register it names can cost a move in the hot code.
The preference is left out where that register is live together
with the vreg somewhere, which a walk of the blocks finds: at a block's
entry, after an instruction's writes, and where a vreg born while
the vreg is live is moved into that register where it dies, in the block
it is born in. The walk follows a vreg on into the vreg it is moved
into where it dies, to which the allocator gives the same register,
dropping the move; and it takes an instruction's writes
from its register usage, liveBorn being filled in only for the graph
allocator and the liveness dump. It visits only the blocks a destination
is live into or written in, a move into one where a vreg dies included,
as elsewhere no destination is live during the walk; and the candidates
and the moves of a vreg into another where it dies, which the walk
follows, are found in one pass over the procedure's blocks. Nor
is it taken where another vreg the block reads or writes,
with no location yet, has the register as its first-used one
(rc_claims): without this, in vector's leaffix and listRank at -O1
a bound or an array reloaded after a call took its wide destination,
displacing the values whose first-used register it is, and the loop's
latch fixups grew from three instructions to five and six. A vreg
already given a location claims nothing, so that a literal in intset
instanceOrd:dense keeps its wide destination where an already coalesced
vreg has it as its first-used register. processBlock's claims take
an instruction's register usage from its liveness, where it has one,
rather than computing it again. dyingMoves now gives moves into vregs
as well, and is INLINE: out of line it makes the compiler allocate 1.0%
more compiling perf/compiler's T3294 at -O0. This preference
and the earlier one for the current block's moves ("Prefer the register
a vreg is moved into where it dies") together overlap with
that of Andreas Klebinger's MR 16693, the real register a vreg is moved
into where it dies, in any block.
Counting those blocks, in containers' map foldMap_traverseSum a node
and its field both had %rbx as their destination, the field from the hot
block that evaluates it, the node only from the heap check's failure
block, which calls the garbage collector; the node, allocated first,
took %rbx, and the field, given %rax, moved into %rbx at every
evaluation: 1.5% more instructions. CmmToAsm takes those blocks
from checkFailures (allocCold) and passes them to the linear allocator,
wherever the backend maintains the CFG, -finfo-table-map or not;
that is on x86-64 only, and elsewhere the set is empty. Leaving out only
the failure targets that no other edge enters, as an earlier form
of this change did, changes no code in perf/compiler's T3294, T12707,
T783 and T9961 or in containers' benchmarks, and makes the compiler
allocate slightly more.
The rule for a vreg born while the vreg is live keeps the register
for the later vreg, which its own block moves into it. Without it,
in containers' graph buildG the loop's index and lower bound took R2's
and R3's registers, which the block making the loop's call needed
for its arguments, and that block ended with three moves an edge, 3.3%
more instructions. Counting every vreg born while the vreg is live
and moved into the register in any block made containers' map insertWith
take 3% more instructions: its value argument arrives in R3
and is passed in R3 to both recursive calls, and the node's key, born
later in the loop and moved into R3 in another block, made it lose R3
as a preference, so every iteration moved it out of R3 and back. Note
[Frequencies before register allocation] gains a bullet saying
that where blocks give a vreg different destinations the last block's
wins, with a TODO at wideMoveDests: taking the hottest block's instead,
by mkGlobalWeights, moved containers' benchmarks both ways by up to 1.4%
and cost 0.24% more compile allocation, its estimate made
for this alone. A comment there notes that a destination no allocator
hands out, Sp, Hp or BaseReg, stays a candidate; leaving those out
changed no code measured and costs compile allocation.
Where no preference is free, firstFreeInOrder now leaves out, while
others remain, the free registers the current block moves another vreg
into where it dies: a vreg given one would keep the other from being
computed in it, or have to move out of its way. Those registers are kept
as a mask by register number, the first free register taken without
filtering the list where the block moves no other vreg into a register
where it dies, and the claims are walked only where no earlier
preference is free and the wide destination is, so that the compiler's
allocation compiling a procedure of many C calls grows
with the procedure as at the parent. That mask is made from two masks
of the block's moves, made once a block: the registers they enter,
and those that two or more vregs enter, the vreg's own register left out
where it alone enters that one. The two are held with the block's map
in one value, and the blocks that move no vreg share one. Folding
the block's moves at every choice instead made the stage-1 compiler run
2.3% more instructions compiling the battery's scaling program ccalls,
400 C calls in one block, at -O1; the masks add to no compilation
of perf/compiler's tests or of CmmDiamondChain more than 0.006%
of that fold's allocation or 0.001% of its instructions. Held as a pair
in a field of their own, they cost up to 0.076% more allocation (T9961
at -O0); held in the one value, made from the list of the block's moves,
up to 0.27% (T3294 at -O0), and made from the block's map, 0.016% (T9961
at -O0), the rest going when the function making it was marked OPAQUE:
its worker and wrapper had allocated a value for each block, the empty
one too. The figures below were measured with the fold. Without this,
containers' graphFromEdges and stronglyConnCompR took up to 1.1% more
instructions at -O1: the index-error block of their key lookup passes lo
and hi in R3 and R4, so the new preference gives them those registers
in the lookup's loop, and the array element, which has no preference,
took the first free register, R1's, into which the loop moves the key
before storing the element: every probe moved the element out
of it first.
mkMoveDests, which builds the masks of the block's moves,
and wideMoveDests, for its mask of the wide destinations, assert
that each register number they set is below 64: setBit sets nothing past
it, so that a register numbered past it would drop out
of the preferences in silence, and the backends number their real
registers below 64. Only a compiler built with assertions on checks
them, and none was built; in the perf flavour they cost nothing,
measured at the series' end: nofib's assembly at -O1 and -O2 and
that of the compile cells is the same, and no cell moves by 0.001%
in instructions or allocation.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs take 0.27% fewer (0.28% at -O1, 0.25% at -O0), none
as much as 0.2% more beyond their run-to-run noise; vector's benchmarks
0.26% fewer (generateIO 3.8%), none more; megaparsec's 0.20% fewer
(skipCount 0.86%, choice 0.58%), none more at -O2; fannkuch-redux moves
by no more than its noise. The benchmarks of containers take 0.72% fewer
(intset fromAscList:sparse:fusion 6.3%, intmap symmetricDifference up
to 5.4%). No benchmark's allocation changes beyond nofib's run-to-run
noise. Counting the failure blocks' moves, the stage-1 compiler
allocates 0.19% more compiling perf/compiler's T3294 at -O0, 0.26% more
compiling T12707, 0.19% more compiling T783, and 0.20% more compiling
T9961; leaving them out takes back half or more of each. Compiling MR
16269's CmmDiamondChain at -O1 and -O2, it allocates 0.12% more. It runs
0.50% more instructions than the parent's compiling CmmDiamondChain
at -O0 and 0.41% and 0.40% more at -O1 and -O2, 0.84% more compiling
T12707 at -O0 and 0.61% to 0.65% more compiling T3294, T783 and T9961
at -O0. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 72% more (5.461 against 3.171 GB).
Some rows rise, and a later commit takes back each one this paragraph
names by undoing its cause. At -O1 megaparsec's endBy takes up to 0.51%
more: its loop's join fixup, a cycle through the C stack that exists
because the block the garbage collector returns to records the join's
registers, gains a move an element; the commit after the next, "Allocate
the blocks the garbage collector returns to last", removes the whole
fixup, and with it the same loop's rotation in containers' map alter
insert, 1.3% more here, and alterF alter insert. endBy's rise is also
a trade: leaving out the wide destination's preference puts endBy back
at the parent's count, 0.47% to 0.50% fewer instructions, and gives back
megaparsec's gains, reachOffsetNoLine taking 3.9% more, reachOffset 3.4%
and errorBundlePretty 3.0%. containers' graph buildG takes up to 2.2%
more, its loop index, given no preference, now taking R1's register,
which the call at the loop's end needs, so that moves on every edge
remain, and intmap index 0.53% more, and in orthotope's A2T benchmark
sumA and productA over large broadcast boxed arrays 3.4% to 3.6% more,
the element passing through R1's register one move more an element;
"Order x86-64 free registers around R1 and clobbers (ISSUE 27981)" takes
all three back, returning buildG's block to the shape it has at "Prefer
a vreg's register at a recorded jump target (ISSUE 27980)" and loading
A2T's element straight into R1. vector's listRank takes 2.0M more
instructions at -O1, and A2T's convert.g and convertE.g over large
strided boxed arrays 18.75% more and its max.g and min.g 8.0% more,
their rnf loop swapping its index through R1's register, three moves
an element; "Allocate a loop before a continuation that enters it" takes
both back: in listRank the block before the join loads straight
into the join's registers, and the cycle through 0x40(%rsp) that holds
this commit's move is gone, and the rnf loop's swap is gone.
The rows of containers' intmap symmetricDifference-block, intmap
and intset union-block, map fromDescListWithKey:fusion and map
insertWith', and IntMap's and IntSet's union-disj_sn_swap
and union-disj_tn_swap at -O2, two instructions more each
by union-block's moves run once, are a trade: each pays moves in one
procedure, following from the register choices the preference makes,
with no local fix known; leaving the preference out reverts them
and gives back its gains. So are, in orthotope's A2T benchmark, fromList
and fromList.map over small strided Storable arrays, 0.87% to 1.09%
more, Shaped's by a register move more an element in OpsShaped's loop,
and Dynamic's and Ranked's foldrA over small Storable arrays, two
instructions more a call: taking out both of this commit's changes
to firstFreeInOrder's choice, the last preference and the free registers
it leaves out, reverts the 14 cells of the benchmark's sample that rise,
these and convert.g and convertE.g over small strided boxed arrays,
and gives back 509 of the 569 that fall. At "Allocate the blocks
the garbage collector returns to last" the fromList cells take 4.0%
to 4.4% fewer instructions than at the parent.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
e73e2de4
by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Put a block's reloads after its leading unwind in stack layout
To move into a merge request of its own, together with "Keep Sp put
across loops and tag tests in stack layout".
Under -g, maybeAddSpAdj starts each block's middle with an unwind giving
the block's Sp rule, and insertReloadsAsNeeded puts a proc point's
reloads before it, so that they run under the rule of the block laid out
before this one. At a return point that rule also covers the return
address (Note [Info Offset] in GHC.CmmToAsm.Dwarf.Types), and at -O0,
where no sinking moves the reloads, the unwind tables are wrong there,
on master at return points of nofib's multiplier, puzzle and para,
though not of primes, compiled at -O0 -g. The next two commits make
it frequent at -O0: the allocator moves the blocks the garbage collector
returns to, and then the continuations that enter a loop making no call,
with the SCCs only they lead to, to the end of its output, so that such
a continuation no longer follows its call block.
withReloads puts the reloads after a leading unwind. Without -g a middle
starts with none and the code is the same: compiled by this commit,
the four programs at -O0, -O1 and -O2 and the 15 compile-cost cells give
the same objects and assembly; with -g only their -O0 output differs,
and at -O0 none of their return points is under a wrong rule.
Cost: withReloads is one foldr, which fuses with insertReloads's
comprehension as the fold it replaces did. Compiling T3294 at -O0, -O
and -O2 takes the stage-1 compiler 0.012%, 0.007% and 0.005% fewer
instructions; the other compile-cost cells, and nofib's puzzle at -O2
compiled by the stage-2 compiler, change by at most 0.003%
in instructions, and allocation moves by at most 0.001% in every cell.
Assisted-by: Claude Opus 5.5
-
0c780f4c
by Mikolaj Konarski at 2026-11-20T00:13:02+01:00
Allocate the blocks the garbage collector returns to last
The linear allocator records, at the first jump it allocates
into a block, the registers the block starts with, and later jumps
into the block move their values to match. linearRA_SCCs allocated
the SCCs in order, so the block the garbage collector returns to after
a heap or stack check fails, which jumps back into the block that made
the check, could be allocated before the hot path reached that block,
and so fix the registers it starts with. In containers' map alter
the block that builds the new node makes such a check; its return block,
allocated first, reloaded the new subtree into %rdi, R4, where
the rebalancing call takes it, while the hot path still held the other
subtree there, so the hot path reached the block through a fixup block
rotating registers at every level the insertion returns through.
linearRA_SCCs now allocates those return blocks (the procedure's entry
blocks in the set checkFailures gives, which it now takes, those
in a cycle excepted), and any SCC only they lead to, after the others,
so that another predecessor, in map alter the hot path, records
the registers and the return block pays the fixup. As it now tests every
block for whether a jump has reached it, it looks the entry blocks up
in a set built once rather than in their list. This commit overlaps
with Sylvain Henry's MR 16673 (ISSUE 27800), read before this commit
was written: both defer, in linearRA_SCCs, return blocks outside cycles;
MR 16673 those that jump into a loop, calls' continuations included,
with the acyclic blocks only they lead to, and this commit
those the garbage collector returns to, whether or not they jump
into a loop, with any SCC only they lead to.
Taking no wide move destination while allocating such a block, instead,
fixes map alter but makes map insertWith take 3% more instructions,
the mirror case: its return block, allocated first, reloads the value
argument into R3's %rsi, its wide destination, where the hot path has
it; without that destination it reloads it into %rax, and the hot path
moves it out of %rsi and back at every level. Note [Frequencies before
register allocation] gains a bullet saying that checkFailures also
counts as cold blocks the hot path may run, a continuation that a call
returns to as well and a failure target that another edge enters,
and that an estimate computed in a Cmm pass could replace
the classification; linearRA_SCCs and checkFailures gain TODOs pointing
there. Where such a continuation is on the path into a loop, deferring
it measured better than leaving it out of the set: the loop
is then allocated first, starting from the block the garbage collector
returns to from the loop's own check, so that the path into the loop
pays the moves once and the loop's latches none (containers'
set-benchmarks); leaving such continuations out costs nofib's scs 1.1%
more instructions and vector's maximumOn 2.9%, and leaving out such
failure targets changes no code measured and costs compile allocation.
Allocating a loop before the path into it on purpose, by deferring
the blocks that jump into an SCC holding an entry block, costs
fannkuch-redux 13% at -O1, whose inner loop lies in its outer loop's
SCC. MR 16673's deferral, of every return continuation outside a cycle
that jumps into a loop, is not used either, because it was found
incorrect: it defers as cold a continuation that is itself inside a loop
through the Haskell stack, and fannkuch-redux then runs 16 to 19% more
instructions.
From "Use block frequencies to order the linear allocator's SCCs" on,
the deferral orders the SCCs only where no block frequencies
are estimated, on x86-64 without -fcmm-static-pred, as at -O0, or where
the estimate lacks one of the procedure's blocks, as it can
under -finfo-table-map (ISSUE 28088); elsewhere at -O1 and -O2
that commit's order replaces it.
With the return blocks allocated last, a block that reloads a value can
find the vreg's first-used register, the one whichever block recorded
the vreg first gave it, to be another value's: in containers' map
fromList-distinctAsc at -O2 such a reload took it over its own wide
destination. firstFreeInOrder now passes over the first-used register
for the wide destination where a walk from the current block's jump
targets, through the blocks the vreg is live into and stopping
at those whose assignment is recorded, reaches no recorded block
but reaches one that moves the vreg into the wide destination where
it dies, and the value live into a block recorded with the vreg
in the first-used register reaches none of the blocks the walk passed
(staleWalk, staleMeets). The vreg is then marked (markStaleFirst),
and for a marked vreg whose walk reaches a recorded block holding
it in another free register, that register is taken: in sequence's
update.100 and adjust.100 at -O1, the continuations reloading
into the same vregs then agree, where the later ones kept the stale
register and paid a swap through the C stack. Both tests end by listing
the recorded blocks that hold the vreg in its first-used register
(blocksHolding), a visit to every recorded assignment, and both fail,
leaving the vreg its first-used register as a preference, where more
than 256 assignments are recorded: unbounded, compiling at -O0
a procedure of N two-way branches in sequence, each after a call's
return, whose arms pass a call a variable written afresh before
the branch, the listings visited a number of assignments quadratic in N.
The walks behind both give up after 64 blocks (liveWalk), a cap tested
after whether the next block is seen already or one the vreg is not live
into, and in a trace at the series' end reached by no walk compiling
nofib's modules at -O1 and -O2 or the compile cells' sources. TODO:
the bound of 256 recorded assignments, like the cap of 64 blocks,
is arbitrary and should be generalised; compiling nofib's modules
at -O2, no listing visited more than 132, and an index of the holders
in place of the bound, each recorded assignment adding a thunk to it,
made the compiler allocate 0.068% more compiling T9961 at -O0 and 0.048%
more compiling T783 at -O0. Measured at the series' end, against
it without the bound: compiling the N branches at -O0, the compiler ran
0.37, 0.85, 2.23 and 6.69 thousand million instructions for N = 400,
800, 1600 and 3200 without it and 0.32, 0.59, 1.13 and 2.22 with it,
the variable then keeping its first-used register and each arm moving
it into the argument's; nofib's modules compile to the same assembly
at -O1 and -O2, and no compile cell's instructions rose by 0.005%
or its allocation by 0.01%, the assembly the same. And genRaInsn reloads
a vreg that an instruction only moves, where it dies, into a register
free by then straight into that register, and drops the move
(reload_into), as in map union at -O2.
Master's process and genRaInsn, in GHC.CmmToAsm.Reg.Linear, build less.
process, which allocates a cyclic SCC's blocks, takes linearRA_SCCs'
accumulator and conses each block's code onto it, where it returned
a list of lists that linearRA_SCCs concatenated. genRaInsn joins
an instruction's spills, reloads and clobber saves onto the code after
it strictly, where master's concat left a thunk for each instruction.
Measured against the parent commit, in instructions: nofib's programs
take 0.11% fewer (wheel-sieve2 2.2%; 0.18% at -O1, fasta 10.7%), none
but knights at -O1, below, as much as 0.2% more beyond their run-to-run
noise; vector's benchmarks 1.2% fewer (maximumOn 17%, minimumOn 15%);
megaparsec's 3.6% fewer (endBy 22%, skipMany 16%); fannkuch-redux moves
by no more than its noise. containers' benchmarks take 0.22% fewer
(intset fromList:worstCase 8.2%, and map alter insert, the case above,
1.3%). No benchmark's allocation changes beyond nofib's run-to-run
noise. The stage-1 compiler allocates 0.54%, 0.44% and 0.59% less
compiling perf/compiler's T12707, T783 and T9961 at -O0, and at most
0.006% more in any other cell, MR 16269's CmmDiamondChain's included;
the stage-2 compiler allocates 0.081%, 0.074% and 0.24% less compiling
nofib's programs at -O2, -O1 and -O0 (geometric means). Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 23%
more (6.725 against 5.461 GB) and GHC.CmmToAsm.Reg.Linear.Base 16% more
(0.591 against 0.511 GB).
At -O1, vector's permutation benchmarks take 4.65% to 5.26% more,
quickhull 2.6% more and nofib's knights 0.52% more, and in orthotope's
A2T benchmark Summed's sumView over boxed arrays up to 1% more
and summed reduce over small dense boxed arrays 4.4% more: in their
loops another predecessor now records a join's registers, one where
a loop value with no preference has taken R1's %rbx,
and the predecessors that receive an evaluated value in %rbx reach
the join through a fixup that swaps or rotates registers at every
iteration. "Order x86-64 free registers around R1 and clobbers (ISSUE
27981)", which puts %rbx last in x86-64's fallback order, removes
these moves in the same blocks; the rotation left in quickhull's split
loop is there before this commit. A2T's generate.scalar over strided
Storable arrays takes 1.6% more, a swap through the C stack and two
moves into R1's %rbx at a join once a call, which that commit removes
too.
The other rises are the deferral's price, and leaving the deferral out
reverts them. The blocks the garbage collector returns to now pay
the moves into the registers the hot path recorded, by design:
containers' main426, $wascLinkTop and $sgo2 pay more instructions a call
at -O1; and megaparsec's many pays swaps through the C stack at every
collection, the hot path having had no fixup to lose.
With the allocation order changed, other blocks move values between
registers, with no local fix known: containers' intset
fromAscList:sparse:fusion, map fromDescListWithKey,
fromDistinctDescList, fromAscListWithKey and fromList-distinctAsc:fusion
(-O1), IntSet's symmetricDifference-block_sn_swap,
symmetricDifference-disj_tn_swap and difference-disj_nt and sequence
update.10, and megaparsec's endBy1. "Use block frequencies to order
the linear allocator's SCCs" takes back endBy1's rise by undoing
its cause: from it on, at -O1 and -O2, the hot path again records
the registers of the join in $weta4's loop, which here the continuation
of Data.Text's empty records, and $weta4 runs 133.18 instructions
a call, against 143.18 at that commit's parent. In orthotope's A2T
benchmark 19 cells of the sample take more, each back at the parent's
count with the deferral left out: Shaped's unravel.one and unravel
over small arrays three instructions a call more (unravel.one over small
dense arrays 0.72%), unravel.one storing a value to the C stack
and reloading it and moving a register once more a call, and ==.rank3
over small dense Storable and Unboxed arrays and zipWithA over small
scalar Storable ones two more; against the deferral left out, 19 cells
of the sample take more and 156 fewer. A2T's rotate.inner over large
dense Storable arrays takes 1.7% more, its loop reassigned; "Allocate
a loop before a continuation that enters it" removes about half of that,
a store and a reload through the C stack. In vector's findIndexR, which
takes 3.2% more at -O1, the procedure's entry now records the loop's
registers, with the predicate in R2's %r14, where it arrives,
and another loop value in R1's %rbx; as the loop calls the predicate
through %rbx, every iteration moves that value out of %rbx
and the predicate in, by way of %rdx: more moves than before. "Order
x86-64 free registers around R1 and clobbers (ISSUE 27981)" puts
the other value elsewhere, removing the move out of %rbx; not deferring
a return block that a warm block enters takes back the rest, but costs
nofib's fasta 13 instructions an iteration at -O1, and telling a loop's
only latch from a colder second latch needs block frequencies. At -O1
megaparsec's skipMany takes 0.95% to 0.96% more, a move an element
that lasts until "Keep Sp put across loops and tag tests in stack
layout" removes it: the hot path, now allocated before the block
the garbage collector returns to, takes the first free register where
the join's recorded one is expected. Leaving the deferral out reverts
it, with most of the procedures of megaparsec's bench-speed
that this commit changes; extending the claims of "Prefer the register
a later block moves a vreg into where it dies" to the vregs a jump
target writes removes the move but makes many of containers' benchmarks
take more instructions, intmap fromAscList 3.3% and intersection-mix_nn
1.0% among them.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
708ad583
by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Allocate a loop before a continuation that enters it
The linear register allocator gives a block the assignment of the first
jump into it that it allocates, and the SCC order puts a return
continuation before a loop it jumps into. Where the continuation's jump
was the first into a block of the loop, it decided that block's
registers, and the loop's own edges into the block paid fixup moves
at every iteration: in the reproducer of ISSUE 27800, two swaps
an iteration.
Defer such a continuation, as the blocks the garbage collector returns
to are deferred, so that the loop's own edges decide and the fixup goes
on the continuation's edge into the loop. This takes from MR 16673,
by Sylvain Henry, its deferral of a return continuation that jumps
into a loop, which is what fixes the issue there, as an extension
of the series' own deferral, not as MR 16673's code, and adds two
conditions it lacks:
* the loop calls nothing: a loop that calls C keeps its values
in spill slots, which a deferred continuation that is hot through
the Haskell stack then pays for (nofib's fannkuch-redux ran 16%
more instructions with the deferral unconditional);
* no assignment is recorded yet for the block the continuation jumps
into: once another jump has recorded one, deferring changes only
the order of allocation, by which block layout breaks its ties
(containers' intset fromAscList, one jump more an element).
The deferral remains a bet that a continuation runs less often
than the loop it jumps into, and it loses where the continuation
is the return point of a call made at every iteration of that loop,
which then pays the fixup at every iteration instead: megaparsec's
reachOffsetNoLine takes 0.96% more instructions at -O2 and reachOffset
0.28% to 0.36% more, nofib's mandel2 0.33% more, and containers' fused
fromDistinctDescList rows 8.1% to 8.8% more at -O1; it loses as well
where the loop runs no trip or few, the continuation paying the fixup
once a call: in orthotope's A2T benchmark convert.g over empty strided
boxed arrays takes 1.1% more, summed force.narrow over empty dense
Storable arrays 0.5% more and rev over small scalar Storable ones 0.4%
more. This is the trade the deferral makes, its toggle the deferral
itself, which reverts both these and the fromAscList family's gains:
the cases differ only in how often a call path runs, on which
no structural order depends. In the sample of orthotope's A2T benchmark,
34 cells take more against the parent, each back at the parent's count
with the toggle: concatOuter over small dense Storable arrays six
instructions a call more (0.62%), rev over small strided and dense
arrays three to five (0.42% to 0.49%), and ==.rank5, mapA
and zipWithA.singleR over small arrays among the rest, two to six;
against the toggle, 34 cells take more and 295 fewer. A third condition,
deferring only a continuation whose call the loop it jumps into does
not reach, breaks T27800, leaving a swap through a spill slot on both
hot edges, loses every gain of containers' fromAscList family
and vector's listRank and awshcc, makes nofib's fasta take 10.3% more
at -O2, and leaves megaparsec's reachOffsetNoLine where this commit puts
it. A2T's generate.scalar over strided Unboxed arrays takes 2.0% more,
a swap through the C stack and moves into R1's %rbx at a join once
a call, which "Order x86-64 free registers around R1 and clobbers (ISSUE
27981)" removes.
From "Use block frequencies to order the linear allocator's SCCs" on,
this deferral acts only where no block frequencies are estimated,
on x86-64 without -fcmm-static-pred, as at -O0, and on the other
targets, or where the estimate lacks one of the procedure's blocks,
as it can under -finfo-table-map (ISSUE 28088); elsewhere at -O1 and -O2
on x86-64 that commit's order replaces it, and T27800, compiled at -O,
exercises that order.
The test, T27800, is the Cmm of MR 16673's T27800.cmm, its assembly
searched for swaps and spill slots: the loop's edges carry neither,
and T27800.stderr expects the lines of the fixup on the cold edge out
of the continuation, a swap through a spill slot.
Measured against the parent commit, in instructions: vector's benchmarks
take 0.96% fewer at -O1 (hybcc 5.9%, listRank 5.8%, awshcc 3.2%, leaffix
3.8%) and move by no more than their noise at -O2; nofib's programs move
by less than 0.01% at -O2 and at -O1 in geometric mean, simple taking
0.28% and 0.21% more; containers' benchmarks move by less than 0.01%
at both levels in geometric mean, the fromAscList family taking 2.9%
to 7.8% fewer at -O2, its swap through a spill slot on each back edge
gone, though intmap fromAscList:fusion takes 1.3% more there
and the fused fromDistinctAscList rows 2.2% to 2.3% more at -O1,
and graphFromEdges up to 1.7% fewer at -O1; fannkuch-redux moves
by no more than its noise. No benchmark's allocation changes beyond
nofib's run-to-run noise. The stage-1 compiler allocates at most 0.025%
more compiling perf/compiler's T3294, T12707, T783 and T9961.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
c191c361
by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Skip registers written before a saved value's next read (ISSUE 26631)
saveClobberedTemps, saving a value out of a register an instruction
clobbers, such as an argument register of a C call, moved it
into the first free register in order, even one a later instruction
of the block writes before it reads the value again; then the value
moved again or was spilled there. It now leaves out the registers
the rest of the block writes before it next reads the value
(unwrittenBeforeRead), and where every free register is one, spills
the value at once. On System V every float and vector register
is caller-saved, so such a value live across a C call ends in memory
anyway: in simd013 the moves and a spill before the call become a spill
(ISSUE 26631). Writes in later blocks are not looked at. containers'
intmap and map mapMaybe and nofib's x2n1 and reverse-complement show
the pattern: values crossing a C call stored at once rather than first
moved into a caller-saved register, and mapMaybe's divisor kept out
of %rdx, which cqto writes.
Spilling at once wherever the first free register is written somewhere
in the value's live range instead, by the clobber map that "Order x86-64
free registers around R1 and clobbers (ISSUE 27981)" builds
(rc_clobbers), makes fannkuch-redux take 1.1% more instructions: a loop
bound kept in %rbx across a memcpy call is spilled and reloaded at every
iteration, %rbx being written elsewhere in the bound's live range,
though not before the loop reads it.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs take 0.035% fewer (k-nucleotide 2.0%), none as much
as 0.2% more; fannkuch-redux 0.32% fewer (0.35% at -O1); containers'
benchmarks 0.003% fewer at -O2 and at -O1, none more beyond their noise;
megaparsec's 0.014% fewer (string 0.17%), none more; vector's benchmarks
move by no more than their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.010%
or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
69cc21e7
by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Assign literals after computed values at the end of a block
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant" and "Drop the assignments that only
a discarded assignment read".
GHC.Cmm.Sink emits the assignments it sinks no further at the end
of a block, in their order. An assignment of a literal to a local
register now goes after the later ones where each of those assigns,
to another local register, a literal or the result of a machine
operation that reads neither that register nor the literal's. A literal
reads neither memory nor a register, and none of the assignments
it passes reads or writes its register, so every value stays the same.
Set first, a constant can take the register that a later value is
to be in at the block's end, while the value's operands still hold
the register the constant is to be in. In Data.Text's UTF-8 decoding,
as inlined into megaparsec's benchmarks, the ASCII path sets the width,
1, and then the character, the zero-extended byte, and jumps
to the join, whose recorded assignment has the width in %r14
and the character in %rbx. Once a later commit makes %rbx x86-64's last
choice, the byte is loaded into %r14; set first, the width would
then take %rbx and the character %r14, and the join's fixup would swap
them at every character. Set last, the width takes %r14, and the byte
is zero-extended into %rbx.
A copy or an update in place keeps a literal before it: in a trial
that let it pass them as well, the literal changed the registers
of a join's recorded assignment in megaparsec's manyTill benchmark
and of a loop head's in Text.Megaparsec.Stream's reachOffset, whose
other predecessors then paid a move a character.
At the series' end the commit still gains, by less than below
in someTill (0.07% against 0.72%). With its code switched off
at the tip, megaparsec's benchmarks run more instructions, by up
to 0.16% (sepEndBy1) at -O2 and 0.13% at -O1, and none fewer past their
noise; in the benchmark some, the difference is in the ASCII path, which
then sets the width first, as above, and the join's fixup swaps %rbx
and %r14. Without the commit, the same decoding's paths for 2- to 4-byte
characters each set the width before the character while %rax still
holds the array, and end with one more move: a loop of takeWhile
isNumber and foldl' over digits 2, 3 or 4 bytes wide then runs 0.99 more
instructions a character, and no more at 1 byte; none of megaparsec's
benchmarks has non-ASCII input.
Measured on x86-64 against its parent: megaparsec's benchmarks at -O2
run 0.029% fewer instructions over those stable across runs (someTill
0.72%), none more. Of nofib's programs only cacheprof's, k-nucleotide's
and veritas's objects change size, cacheprof's in the order
of its instructions alone and k-nucleotide's in its registers, and none
moves by as much as 0.2%; containers' and vector's benchmarks move
by no more than their noise. The assembly of perf/compiler's T3294,
T12707, T783 and T9961 at -O0 and -O is the same; at -O the stage-1
compiler allocates up to 0.010% more compiling them (T9961) and 0.0063%
and 0.0065% more compiling MR 16269's CmmDiamondChain at -O1 and -O2,
and at -O0 up to 0.0066% more (T9961).
Figures of variants not taken were measured on earlier forms
of the series.
The lines below name the perf tests that the series as a whole moves
below their windows against master; this commit by itself moves none
of them out of its window.
Metric Decrease:
CoOpt_Read
ManyAlternatives
ManyConstructors
T10421
T11545
T12227
T12234
T12425
T12707
T13035
T13056
T13253
T13253-spj
T13379
T13960
T14683
T15164
T15304
T15630
T15630a
T15703
T16577
T17516
T17836
T18140
T18282
T18304
T18698a
T18698b
T18730
T18923
T1969
T19695
T20049
T20261
T21839c
T24471
T26425
T26989
T3064
T3294
T4801
T5030
T5321FD
T5321Fun
T5631
T5642
T6048
T783
T9198
T9233
T9630
T9675
WWRec
Assisted-by: Claude Opus 5.5
-
6d29c475
by Mikolaj Konarski at 2026-11-20T00:13:03+01:00
Prefer a loop variable's register for the value moved into it
A vreg that the current block moves, where it dies, into another vreg,
such as a loop's next index moved into the index variable before
the jump back to the loop's header, now prefers the first register
that the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded,
give that other vreg, as it prefers a real register the block moves
it into: processBlock adds such moves to rc_moveDests, from rc_jumpLocs.
In that register the move goes away, and the other vreg is where
the first of those assignments to hold it in a register has it.
A move counts only where the block does not write its source again
(dyingMovesLast): a preference is looked up by the vreg, so it would
otherwise reach the vreg's later value. Where such a move counted,
in nofib's gcd, whose loop ends by shifting loop variables (t2C8 :=
t2Cb, then t2Cb := a new value), the new value took the register
the loop's header gives t2C8, and the jump to the header then had
to exchange two registers through a stack slot: 0.4% more instructions.
dyingMovesLast shares dyingMoves' test of a move where the vreg dies
(dyingMove). The moves into real registers include those of a vreg
the block writes again after the move, its later value then preferring
that register too; leaving them out changed no code measured and costs
compile time.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
containers' benchmarks take 0.10% fewer: map lookup absent and alterF
lookup absent 5.2% fewer, and lookupge-map's GE Twan 2.8% to 3.4%;
fannkuch-redux 0.014% fewer; nofib's programs and vector's benchmarks
move by no more than their noise. No benchmark's allocation changes
beyond nofib's run-to-run noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.011%
or less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
0c50d530
by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Add a union sharing the first map's subtrees to GHC.Data.Word64Map
GHC.Data.Word64Map gains unionShared, exported as union is,
and GHC.Types.Unique.Set gains unionUniqSetsShared, its form
at UniqSet's type and with unionUniqSets' bias. For all maps,
unionShared m1 m2 equals union m1 m2, the same trie with m1's value
where both maps have the key; but it walks the two tries together,
handing a part of m2 with a key outside the range of the subtree of m1
it has reached to union with that subtree, and returns a subtree
it reaches unchanged where m2's part of it is the same object,
by reallyUnsafePtrEquality#, a key the subtree has or empty, or where
the walk returns both halves of the subtree unchanged. So where m2 has
no key that m1 lacks, the result is m1 itself. The pointer test only
saves work and sharing: where it answers False for the same object,
the result is still equal. Where the two maps were made from one map
by k insertions and deletions and m2 has no key that m1 lacks, it takes
O(k * min(n, W)) where union takes O(n + m). The next commit's
regClobbers unites with it the sets of registers live across
instructions, which the liveness pass builds from one another, where
unionUniqSets copies the whole set at every union.
Tested against union over pairs of maps made from one another
by insertions, deletions and changes of values, or independently,
with keys dense, sparse and over the whole 64-bit range and each value
naming the map and the edit or key that gave it: each result equals
union's, with m1's values, and is m1 itself wherever m2 has no key
that m1 lacks; a variant keeping m2's value at a common key fails
the first, and one handing an empty m2 to union, whose result there
was not m1 itself, the second. GHC's testsuite has no test
of GHC.Data.Word64Map or of GHC.Types.Unique.Set, and none is added.
Assisted-by: Claude Opus 5.5
-
af3e2cc9
by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Order x86-64 free registers around R1 and clobbers (ISSUE 27981)
On x86-64, where none of its preferences is free, a vreg now takes R1's
register, %rbx, last in each of the two parts below: an evaluation
and a return write it, so a value given it may have to move out of their
way, and a loop variable given it at the loop's entry moves at every
iteration (ISSUE 27981). Before the others it takes the registers
no instruction writes while the vreg is live past the write: for a vreg
live across a C call, these are the registers the call preserves,
on System V R2's %r14 and %rbx, and for one still live where an argument
is moved into R2's %r14 for a jump, they exclude %r14. Given a register
such an instruction writes, the vreg would have to move out of the way.
Where no preference is free, firstFreeInOrder leaves out the free
registers the block moves other vregs into where they die, and takes
the first of the rest; on x86-64, where the allocator's context holds
regClobbers' map (rc_clobbers, Nothing elsewhere), it takes the one
fallbackReg picks, the first free register in this order, R1's register
taken from a constant rather than from globalRegMaybe at every call.
Where the block moves no other vreg into a register where it dies,
firstFreeInOrder hands fallbackReg the free registers themselves, rather
than a filtered copy. In the reproducer of ISSUE 27981 this commit
already removes the back edge's fixups; the next commit removes
the cause the issue names. In T27800, the test of ISSUE 27800,
the continuation's edge into the loop no longer swaps through a spill
slot, and T27800.stderr, which expected those lines, is deleted.
regClobbers finds, for each vreg, the registers written while
it is live, once a procedure on x86-64: the liveness pass now records,
at each instruction that writes a real register, the registers live
after it (liveAcross), and regClobbers adds the written registers
to every vreg among those that is live past the instruction, as bits
by register number, finding the vregs an instruction writes once
for the instruction rather than once for each vreg live past it;
and firstFreeInOrder binds strictly the vreg's first-used preference,
which noPrefs reads a second time. Only x86-64's fallback uses them,
and on the other targets RA_Context's field is empty, so that no unread
thunk keeps the procedure's code alive. patchRegsLiveInstr, which
rewrites an instruction's registers after liveness for the graph
allocator, leaves liveAcross as liveness made it, the linear allocator
alone reading it, before any register is rewritten; the review question
of the README in compiler/GHC/CmmToAsm on rewriting registers after
liveness names liveAcross beside liveUsage. A move of the vreg itself
into a register is no such write. Where the vregs live past a write
number more than 24, as at most divisions of MR 16269's CmmDiamondChain,
regClobbers unites them with those live past the earlier writes
of the same registers and marks each union's vregs once at the end,
rather than looking each up at every write; a smaller set is marked
a vreg at a time, and the masks are the same either way. The union,
unionUniqSetsShared over the previous commit's unionShared, returns
the newer set itself where the accumulated set adds nothing to it:
the liveness pass builds the sets live across consecutive instructions
from one another, so the accumulated set stays the newest set itself
and a union walks only the few paths that differ. With unionUniqSets,
which copies the whole set, the stage-1 compiler ran 3.5% more
instructions compiling the battery's scaling program ccalls, 400 C calls
in one block, at -O1, and 0.13% to 0.15% more instructions and 0.86%
to 1.0% more allocation compiling CmmDiamondChain, against figures below
measured with it. It tests an instruction for registers live past it,
a set the liveness pass leaves empty where the instruction writes
no real register, before it computes the mask of the registers written,
which is then not 0, as a debug compiler asserts, and counts a set's
members only up to the threshold. Leaving out the writes in the blocks
that follow a failed check costs containers' lookupge-intmap Milan
lookups 0.5 to 1% more instructions, a failure block's write having kept
a vreg, by accident, out of a register that a later vreg is moved into;
Note [Frequencies before register allocation] gains a bullet
on the case, with a TODO at regClobbers. Andreas Klebinger's MR 16693,
read before this commit was written, charges a vreg for each register
that an instruction in a loop starts writing while the vreg is live
across it, and this order overlaps with that clobber cost: both steer
a vreg away from the registers written while it is live, MR 16693
by a cost counted within loops, this commit by the order of the free
registers, from the writes met anywhere the vreg is live.
On x86-64, for a vreg that has preferences, all of them taken,
fallbackReg also leaves out, where a free register would remain,
the registers that one of the assignments the block's jumps lead to,
a recorded jump target's or that of a block up to three jumps past
a target not yet recorded (rc_jumpLocs), gives another vreg, so
that the vreg does not take a register that a jump on the way there will
need for that one: a part of what ISSUE 26666 asks.
fallbackReg also leaves out, where others remain, the free registers
that the blocks up to three jumps ahead that the vreg is live into move
another vreg into where it dies, the vreg's own such destinations
excepted: given one, the vreg would keep the other from being computed
in it, or have to move out of its way there. Not for a vreg live across
a C call, which leaves its register at the call anyway: a block after
the call, such as k-nucleotide's copy of a new key, would put it
on an argument register that the call's own setup needs,
and the arguments were swapped through %r9. Nor where a jump target
not yet recorded that the vreg is live into has two or more
predecessors, those after a failed heap or stack check not counted:
its register there binds them all, and a walk from one of them reaching
a rare exit put megaparsec's manyTill counter on a register its hot
predecessor holds, a move in the join's fixup. With this look-ahead
IntMap's union-mix_sn_swap, union-mix_nn and union-mix_nn_swap take
fewer instructions at -O2, and at -O1 intmap fromAscList,
fromAscList:fusion and intset fromAscList:sparse. The look-ahead costs
the compiler instructions and allocation compiling perf/compiler's T3294
and MR 16269's CmmDiamondChain at -O0; in this commit's own figures
the saving of R1's constant and of choosing the fallback by rc_clobbers
cancels most of it. The look-ahead's walk keeps, for each block it walks
on from with two jumps or more left, the most jumps it had left there,
and walks on from the block again only with more, so that raising
its limit of three would not make it exponential in the jumps; at three
this costs hardly any more instructions compiling nofib's puzzle at -O2,
and the code is the same. The masks by register number this commit adds,
regClobbers', that of the registers in the assignments in rc_jumpLocs
that fallbackReg leaves out and the look-ahead's (dyingIn's for each
block, and lastDestBit's for the vreg's own destination, in the upper
half), assert where they are built that each number they set is below
64, and below 32 in lastDestBit, and aheadWalks that a block's mask has
no bit from 32 up: setBit and bit set nothing past the range, so
that a register numbered past it would drop out of the preferences
in silence, and x86-64 numbers its registers 0 to 31. Only a compiler
built with assertions on checks them, and none was built; in the perf
flavour they cost nothing, measured at the series' end: nofib's assembly
at -O1 and -O2 and that of the compile cells is the same, and no cell
moves by 0.001% in instructions or allocation.
raInsn no longer drops a move from one vreg into another, giving
the destination the source's register, where one of the assignments
the block's jumps lead to, a recorded jump target's or that of a block
up to three jumps past a target not yet recorded (rc_jumpLocs), has
the destination in a free register other than the source's and another
vreg in the source's: the move then puts the destination where
that assignment has it, and a jump on the way there does not have
to swap it with that other vreg, as in containers' IntSet compare
(intset instanceOrd:dense). Where none has a vreg in the source's
register, the move is dropped as before, the jump moving the destination
on its own edge rather than the move running on every path out
of the block.
The expected assembly of codeGen/should_gen_asm's
bytearray-memcpy-unroll and bytearray-memset-unroll names other
registers now; the instructions and their order are the same.
Simpler forms cost more. %rbx last for every vreg costs up to 3% more
instructions in procedures that make C calls. %r14 first as well,
wherever no vreg is live across a C call, gains in some loops but costs
up to 3% more elsewhere, where %r14 is used later, for R2 or in a jump
target's recorded assignment. Taking the registers a C call preserves
first for every vreg live across one, ignoring every other write, makes
fannkuch-redux take 1.3% more instructions: a loop variable live across
a call elsewhere in the procedure is given %r14 and moves out of R2's
way at every iteration.
Measured against the parent commit, in instructions: nofib's programs
take 0.40% fewer (fasta 5.3%, k-nucleotide 4.3%, bspt 2.4%; 0.48%
at -O1, 0.099% at -O0), none as much as 0.2% more beyond their
run-to-run noise; fannkuch-redux 0.22% fewer; vector's benchmarks 1.3%
fewer (nextPermutationBijective 4.4%, findIndexR 3.4%), none more
than 0.001%; containers' benchmarks 0.38% fewer (intset partition 6.1%,
intset filter 5.2%, graph buildG 0.54% to 3.9%); megaparsec's benchmarks
1.5% fewer (reachOffsetNoLine 7.6%, many 6.6% to 6.8%). No benchmark's
allocation changes beyond nofib's run-to-run noise. The stage-1 compiler
allocates 0.13% more compiling perf/compiler's T3294, 0.28% more
compiling T12707, 0.18% more compiling T783 and 0.32% more compiling
T9961, each at -O0, and 0.069% or less at -O and -O2. Compiling MR
16269's CmmDiamondChain, it allocates 1.6% more at -O0 and 1.3% more
at -O1 and -O2. A stage-1 compiler runs 3.2% more instructions
than the parent's compiling CmmDiamondChain at -O0 and 2.7% more at -O1
and -O2, and 1.2% more compiling T9961 at -O0, every other cell
under 1%. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 20% more (9.14 against 7.61 GB)
and GHC.CmmToAsm.Reg.Liveness 14% more (2.67 against 2.34 GB).
That compile cost is a trade, its toggle regClobbers' map: left empty,
so that the fallback orders the free registers without the clobbering
writes, it takes the commit's compile cost against its parent to 0.9%
for CmmDiamondChain at -O0 and 0.75% at -O1 and -O2, and to 0.18%
for T9961 at -O0; but the assembly of CmmDiamondChain, of T12707
and T3294 at -O0 and of T9961 at -O and -O2 changes, and so does
that of nofib programs at each level, of which, compiled by stage-1
compilers over the same libraries and run as nofib runs them, shootout's
fasta takes 5.5% more instructions at -O2, k-nucleotide 3.1%
and fannkuch-redux 2.3% more, wheel-sieve2 1.2% and wheel-sieve1 1.1%
more, and all of them together 0.25% more at -O2 and 0.15% at -O1
and the same to 0.01% at -O0, none 0.2% fewer. The map is kept,
and its cost with it.
The rises in containers are trades, each with a toggle. At -O1 IntSet's
union-common and union-mix take 0.44% to 0.84% more, union-block 0.26%
to 0.40% and IntMap's union-common 0.15% to 0.51%, and no later commit
takes them back: union_info loads the subtree field into %rdi rather
than %rsi, and each of its recursion-call blocks adds a move,
the partition of the free registers by clobbering writes being tied,
the field moved into %rsi on two paths while %rsi is written
on the third; which side wins depends on how the input sets overlap.
Not counting as clobbered a vreg's own dying-move destinations up
to three jumps ahead, except for vregs live across a C call, takes them
back, but makes intset fromAscList:sparse take 2.64% more, map
fromListWith-desc and its siblings 0.87% to 1.08% more, IntSet's
and IntMap's symmetricDifference common, mix and block rows 0.30%
to 0.59% more and Map's union-common_nn 0.49% more (-O2), and costs
0.27% more compile allocation for T3294 at -O0. map
fromListWith-desc:fusion takes 0.98% more at -O2: of four
specialisations of one insertion loop, which share R4 between two
subtree fields, the order wins three, and the variant that wins
the fourth makes the other three take 1.0% to 1.1% more. At -O1
the fused fromAscList family, intmap lookup_misses and map
fromList-distinctAsc:fusion take more by R1's place last in the order;
R1 in its natural place reverts them, but brings back graph buildG's
rise of "Prefer the register a later block moves a vreg into where
it dies" (up to 2.2%) and makes intset folds:dense foldr'_maximum take
5.8% more. intset mapMonotonic takes 1.27% more at -O2, the order
putting %rsi after %rax so that the hot path's reload cannot take %rax;
leaving out the registers the assignments in rc_jumpLocs give other
vregs for vregs without preferences too fixes it, but makes set
alterF:insert:present take 2.4% more, alterF:delete:absent 2.7% and map
fromAscList:fusion 1.9%. intset fromList:randomDups:fusion takes 0.55%
more at -O1; R1 in its natural place for vregs that die in their block
fixes it, but gives back folds:dense foldr'_maximum's gain (5.5%)
and folds:sparse foldr'_maximum's (0.9%). At -O2 intset
difference-block_sn_swap takes 54 instructions more (0.32%)
and difference-block_ns 54 fewer: in IntSet's difference the partition
of the free registers by clobbering writes moves a reload off %rsi,
and a move goes from the two blocks that tail-call one specialisation
to the two that tail-call the other; which of them is hot decides
between the rows. Not partitioning the free registers by clobbering
writes takes difference-block_sn_swap back, where the union rows' toggle
makes it take more still, but then containers' benchmarks take 0.040%
more at -O2 by the geometric mean, 137 rising and 58 falling (graph dfs,
dff and topSort on maxDAG n=1500 1.8%).
In the sample of orthotope's A2T benchmark twelve cells over small
arrays take one instruction a call more (0.21% to 0.29%), eleven of them
trades of two parts of this commit, each shown by its toggle
and not traced in the code. Three, generate.scalar over strided Storable
arrays in Shaped, Ranked and Dynamic, take more by R1's place last
in the order: R1 in its natural place takes them back and moves 181
cells of the sample, 80 up and 101 down, but makes set
fromAscList:fusion take 1.55% more at -O2. The other eight, Shaped's <$,
pure, stretchOuter, rnf, update.none, concatOuter.one, append.emptyR
and append.emptyL over boxed arrays, take more by fallbackReg leaving
out, for a vreg with preferences, the registers the assignments
in rc_jumpLocs give other vregs: with that left out the eight are back,
but 144 cells move, 91 up and 53 down, toList over small strided boxed
arrays taking 2.3% more and reduce 1.9% more. The compile cost
this commit adds on the battery's scaling program claims, a loop whose
body is one block of N steps, grows linearly with N and is mostly
that of the same exclusion, a trade: at -O0 and N=800 the stage-1
compiler allocates 4.2% more than the parent's and runs 4.6% more
instructions, the differences twice those at N=400, and without
the exclusion 89% of the added bytes and 67% of the added instructions
go, but then over the whole A2T benchmark, not its sample, 47 cells take
more instructions by over 0.2% and 14 fewer, 0.028% more
by the geometric mean, and megaparsec's benchmarks 0.024% more at -O1
(manyTill 0.33%).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
926bf688
by Mikolaj Konarski at 2026-11-20T00:13:04+01:00
Free every register not live into a newly reached block (ISSUE 27981)
On the first jump to a block, joinToTargets_first recorded, beside
the block's assignment, the block's free registers, the source block's
with those of the vregs not live into the target released, and initBlock
started the block with them. A real register still allocated at the jump
and not live into the target, R1 above all where it is allocatable,
therefore stayed allocated in the target block until the block wrote
it and that value died: a value the block reloads cannot go back to it,
and the block's jumps may need fixup moves. initBlock now derives
the free registers on entry to every block: every allocatable one
but the real registers live into it and those holding the vregs
of its recorded assignment, if it has one; a recorded assignment
no longer carries free registers, and joinToTargets no longer computes
the registers to release (to_free), nor needs FR. In its reproducer
the previous commit already removes the fixups, so the reproducer does
not show this fix alone; its inline form, too, runs as many instructions
an element as with the parent commit. The test, T27981, is ISSUE 27981's
reproducer, its allocator statistics searched for fixup moves: it passes
with the parent commit's compiler, which already removes them, and fails
with that commit's parent's, which puts them on the loop's back edge.
allocateRealRegs marks the real registers among those live into a block
allocated, and is INLINABLE, so that x86's allocator runs
it specialised: with the pragma, the compiler runs up to 0.55% fewer
instructions compiling MR 16269's CmmDiamondChain at -O0 than without
it, and allocates up to 0.013% less compiling nofib's puzzle at -O0.
initBlock takes the procedure's initial free registers from RA_Context
(rc_initFree) rather than rebuild them for each block; runR starts
the allocator with them too, and with an empty block assignment,
register assignment and stack map, taking none of them as arguments;
joinToTargets_first, left with two statements, is inlined by hand
at its one call site.
This applies on every target the linear allocator serves; the figures
below are x86-64's. Measured against the parent commit, in instructions:
nofib's programs, vector's benchmarks and fannkuch-redux move by no more
than their noise; containers' benchmarks take 0.035% fewer (tree edges
1.4%, graph transposeG 1.3% and buildG 1.1%), none more beyond their
noise, and megaparsec's 0.25% fewer (many 1.2%, sepEndBy 0.85%
to 0.88%), none more. No benchmark's allocation changes beyond nofib's
run-to-run noise. The stage-1 compiler allocates 0.16% less compiling
perf/compiler's T3294, 0.74% less compiling T12707, 0.75% less compiling
T783 and 1.1% less compiling T9961, each at -O0, and up to 0.25% less
at -O and -O2. Compiling MR 16269's CmmDiamondChain, it allocates 4.3%
less at -O0 and 3.6% and 3.5% less at -O1 and -O2.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
61601520
by Mikolaj Konarski at 2026-11-20T00:13:05+01:00
Write the linear allocator's state only where it changes
releaseRegs, which genRaInsn calls twice for every instruction,
with the registers the instruction reads for the last time and
those it writes that die at once, wrote the assignment and the free
registers back to the allocator's state even where it had no register
to release; saveClobberedTemps, for every instruction that writes a real
register, folded over the whole assignment in the monad and wrote
it back even where no value sat in a clobbered register. Each write
builds a new RA_State. releaseRegs now returns at once where it has
nothing to release, and saveClobberedTemps picks the values to save
by a pure fold, in the order the monadic one took them, and writes
the state only where there are some. Both now take the dying registers
as the set the liveness annotation holds, where master's genRaInsn
listed the set's registers at every instruction for them: releaseRegs
folds over the set, and saveClobberedTemps tests a value's register
for membership in it. The generated code is the same.
The stage-1 compiler allocates 3.1% less compiling perf/compiler's T3294
at -O0 and 1.1% less at -O, 2.1% less compiling T12707 at -O0 and 0.69%
less at -O, 1.8% less compiling T783 at -O0 and 0.29% less at -O,
and 3.0% less compiling T9961 at -O0, though 0.016% less at -O.
Compiling MR 16269's CmmDiamondChain, it allocates 9.1% less at -O0
and 7.5% and 7.4% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
-
f7dcd444
by Mikolaj Konarski at 2026-11-20T00:13:05+01:00
Find the linear allocator's spill candidates in one fold
Where no register of a vreg's class is free, allocRegsAndSpill_spill
frees the register of another vreg: the first one that is in a register
and in a stack slot, else the first one only in a register, among
those it need not keep. It found them by filtering the whole assignment
to the vregs in a register, deleting those to keep, listing the rest
and searching the list twice. It now folds over the assignment once,
keeping the first vreg of each kind, in the order the list had them.
The generated code is the same.
The stage-1 compiler allocates 9.3% less compiling perf/compiler's T3294
at -O0 and 4.0% less at -O, and 0.51% less compiling T12707 at -O0;
its allocation compiling T783 and T9961 rises by 0.0055% or less.
Compiling MR 16269's CmmDiamondChain, it allocates 0.41% less at -O0
and 0.33% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
-
5f9868ff
by Mikolaj Konarski at 2026-11-20T00:13:06+01:00
Walk register assignments without listing them
clobberRegs listed the whole assignment, for every instruction
that writes a real register, to move the vregs that are in a clobbered
register and in a stack slot to the slot only. saveClobberedTemps' fold
over the assignment, which picks the vregs in a clobbered register
to save, now picks those too and records them InMem, as it now records
a vreg it spills, so that master's clobberRegs only marks the clobbered
registers allocated. joinToTargets_again listed the recorded assignment
of a jump target and the current one, restricted to the vregs live
into the target, to compare them ignoring the formats. Master's
joinToTargets' now passes it the whole current assignment,
and recordedLocsHold tests on the two maps themselves that every vreg
of the recorded assignment is at its recorded location: a recorded
assignment holds only vregs live into its block,
and makeRegMovementGraph moves only the vregs it holds. The generated
code is the same but for the numbering of fixup labels after a jump
at which a vreg live into the target has a location that the recorded
assignment does not give it.
The stage-1 compiler allocates up to 0.095% less (T9961 at -O0),
and at most 0.00017% more, compiling perf/compiler's T3294, T12707, T783
and T9961. Compiling MR 16269's CmmDiamondChain, it allocates 6.9% less
at -O0 and 5.6% and 5.5% less at -O1 and -O2.
Assisted-by: Claude Opus 5.5
-
737add03
by Mikolaj Konarski at 2026-11-20T00:13:06+01:00
Sort a procedure's blocks only where its first block is not first
regAlloc sorted the linear allocator's blocks to keep the procedure's
first block at the front; it now sorts them only where that block
is not at the front already. The generated code is the same.
The stage-1 compiler allocates 0.094% less compiling perf/compiler's
T3294 at -O0, 0.33% less compiling T12707 at -O0 and 0.12% less at -O,
0.29% less compiling T783 at -O0 and 0.083% less at -O, and 0.51% less
compiling T9961 at -O0.
Assisted-by: Claude Opus 5.5
-
86f29929
by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
Compute the dying registers and the live-in map of liveness strictly
liveness1 left, in each instruction's liveness, the registers read
for the last time there and those written there that die at once
as thunks, which the linear allocator forces at every instruction;
livenessSCCs likewise left the map of the registers live into each block
to be computed later, through the acyclic SCCs. They are now computed
as the liveness pass goes, but for the registers that die at a branch
because they are live into its targets only: livenessCyclic walks
a block again whenever a successor's live-in set has changed and keeps
only its last walk, and computing that set at every walk made
the stage-1 compiler run 8.8% more instructions than the parent commit's
compiling the battery's scaling program nest, 400 loops nested in one
procedure, at -O1, against 0.6% more with the set lazy, to save at most
0.045% of its allocation (T9961 at -O0). The generated code is the same.
The stage-1 compiler allocates 0.77% less compiling perf/compiler's
T3294 at -O0 and 0.25% less at -O, 0.55% less compiling T12707 at -O0
and 0.19% less at -O, 0.65% less compiling T783 at -O0 and 0.13% less
at -O, and 0.66% less compiling T9961 at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
1939d3d5
by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
Skip the address registers x86's mkRU would drop
regUsageOfInstr on x86 and x86-64 added every register an address names
to an instruction's register lists, and mkRU then filtered out the ones
the allocators do not manage, such as Sp's %rbp, Hp's %r12 and BaseReg's
%r13, copying each list that held one: those of every access
to the stack or the heap. An address's registers that mkRU would drop
are now left out where they are added. This commit is a subset
of Sylvain Henry's MR 16843, whose register usage DSL adds each
register, an address's included, only where the allocators manage it.
The generated code is the same.
The stage-1 compiler allocates 0.83% less compiling perf/compiler's
T3294 at -O0 and 0.28% less at -O, 0.38% less compiling T12707 at -O0
and 0.12% less at -O, 0.35% less compiling T783 at -O0, and 0.25% less
compiling T9961 at -O0.
Assisted-by: Claude Opus 5.5
-
7f026802
by Mikolaj Konarski at 2026-11-20T00:13:07+01:00
List a CFG's edges once in block layout
sequenceChain listed the edges of the CFG twice, once for the chains
it builds and once for the edges left between them; it now lists them
once. The sets of the edges that buildChains and combineNeighbourhood
fuse, master's Sets of pairs of BlockIds, are now LabelMaps from each
block to the LabelSet of the blocks its fused edges enter,
and combineNeighbourhood lists each of its chains once by taking
it at the lowest of its ends, where master removed the repeats
with nubOrd. The generated code is the same.
The stage-1 compiler allocates 0.12% less compiling perf/compiler's
T12707 at -O, 0.16% less compiling T783, and 0.031% less compiling
T3294; at -O0 its allocation rises by 0.0019% or less. Compiling MR
16269's CmmDiamondChain at -O1 and -O2, it allocates 0.30% less.
Assisted-by: Claude Opus 5.5
-
f2f3f9c7
by Mikolaj Konarski at 2026-11-20T00:13:08+01:00
Build no lists of results in calcFreqs
calcFreqs, which static prediction runs for every procedure, built
a list of results for each block's out-edges (forM in calcOutFreqs) and,
for each block's predecessors, a list of Bools to test for irreducible
flow and a list of probabilities to sum. It now uses forM_, anyM
and a left fold from 0, which adds the probabilities in sum's order,
so that the frequencies are the same, and so is the generated code.
isBackEdge, master's, looks an edge up in an IntMap of IntSets rather
than in a Set of pairs.
At -O the stage-1 compiler allocates up to 0.099% less compiling
perf/compiler's T3294, T12707, T783 and T9961 (T12707); at -O0, where
static prediction is off, its allocation moves by 0.0045% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.31%
less.
Assisted-by: Claude Opus 5.5
-
5603ac7e
by Mikolaj Konarski at 2026-11-20T00:13:08+01:00
Give back edges no bonus where static prediction estimates the weights
optHsPatterns raised every back edge of positive weight by backEdgeBonus
(increaseBackEdgeWeight), after a depth-first search for them;
under -fcmm-static-pred, on at -O1 and -O2, staticPredCfg then replaces
the weights of the branches its heuristics cover with its predictions
and estimates frequencies from them. The bonus is now left out there:
optHsPatterns takes the back edges to raise, which optimizeCFG gives
as none where static prediction follows and as findBackEdges' elsewhere,
and the procedure's map of info tables in place of the procedure,
its equation for CmmData deleted: optimizeCFG, its one caller, returns
a CmmData's CFG unchanged. The bonus counted only at the branches static
prediction leaves alone, a heap or stack check's and those whose targets
are all back edges, and at a two-way branch back into the procedure's
entry, whose weights static prediction starts from, loopInfo counting
no edge into the entry a back edge. Leaving it out of those as well
changed no code measured. The generated code is the same on every
program measured: perf/compiler's T3294, T12707, T783 and T9961 at -O0
and -O, and nofib's programs at -O2 and -O1, whose objects
are identical.
At -O the stage-1 compiler allocates up to 0.15% less compiling
perf/compiler's T3294, T12707, T783 and T9961 (T783); at -O0, where
static prediction is off, its allocation moves by 0.00054% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.47%
less.
Assisted-by: Claude Opus 5.5
-
d20eab44
by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
In sccBlocks, look blocks up in the CFG, not in a set of them
sccBlocks, in GHC.CmmToAsm.Reg.Liveness, built a set of every block
of the CFG, which holds only reachable blocks, to keep the procedure's
blocks that are in it; it now looks each block up in the CFG itself.
The generated code is the same.
The stage-1 compiler allocates up to 0.24% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T783), and up
to 0.059% less at -O (T783). Compiling MR 16269's CmmDiamondChain at -O1
and -O2, it allocates 0.11% less.
Assisted-by: Claude Opus 5.5
-
2b473b71
by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
Inline x86's takeRegRegMoveInstr
takeRegRegMoveInstr, which the register allocators and the liveness pass
call on every instruction they look for a register-to-register move in,
built a Just and a pair for each move it found. Most callers take both
apart at once. Inlined, it builds neither where its caller takes them
apart. The generated code is the same.
The stage-1 compiler allocates up to 0.13% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T9961); at -O
its allocation moves by 0.012% or less. Compiled by the boot compiler,
GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 12% more (9.23 against
8.22 GB).
Assisted-by: Claude Opus 5.5
-
47c937c7
by Mikolaj Konarski at 2026-11-20T00:13:09+01:00
Swap the registers of a cyclic join fixup where one instruction can
Where a jump's target has a recorded assignment, joinToTargets moves
the vregs into it, and where the moves form a cycle, handleComponent
spilled one source to its stack slot and reloaded it
into its destination after the other moves: a store and a load,
and a stack slot the vreg may not have had. The Instruction class now
has mkRegRegSwapInstr, which gives an instruction that swaps two
registers of a format where there is one, and by default Nothing; on x86
and x86-64 it is xchg for the general-purpose registers. handleComponent
now swaps a cycle's first source with its destination where it can,
so that a cycle of n moves takes n - 1 swaps; it spills as before
otherwise, as for floating-point and vector registers. An xchg is two
micro-ops on Zen 3, but breaking a cycle through a free register
instead, with three movs, ran in as many CPU cycles there and took more
instructions (megaparsec's benchmarks 0.114% more instructions at -O2,
skipManyTill 2.1% more); breaking floating-point cycles through a free
register changed nothing measured, the register cycles it would convert
occurring only a few times in all the suites. With master's allocator,
orthotope's $w$s$wequalT1 and $w$s$w$ccompare1 break register cycles
through stack slots.
The stage-1 compiler's allocation compiling perf/compiler's T3294,
T12707, T783 and T9961 moves by 0.0054% or less at -O0 and -O.
Of nofib's programs only puzzle moves by more than 0.2% in instructions:
it runs 0.41% fewer, and 0.7% fewer cycles. containers' benchmarks move
by less than 0.1% but for graph bcc.star,n=100, which runs 0.23% fewer;
vector's quickhull runs 0.99% fewer at -O1, its other benchmarks moving
by 0.028% or less, and megaparsec's run 0.40% fewer (skipManyTill 4.0%,
endBy1 1.4% to 1.7%), none more. In megaparsec's count, sepBy
and sepEndBy and in vector's quickhull, cycles through stack slots
become xchg instructions.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
9a831313
by Mikolaj Konarski at 2026-11-20T00:13:10+01:00
Store no value into the slot holding it at a join
expandNode turned a vreg that is InBoth in the same stack slot at both
ends of a join into a store into that slot, beside a register move where
the registers differ and alone where they do not, though the slot
already holds the value. Such a vreg now needs at most the move.
expandNode is now one closed form in place of master's cases: a vreg
already in place needs no move, and otherwise the value is moved
from the source's register where it has one, to the destination's
register unless it is the source's, and to the destination's slot unless
it is the source's, the register before the slot. Master's alternatives
and their recursive call give the same moves but for a destination slot
that is the source's, into which they stored the value.
Measured on x86-64 against its parent, in instructions: the change
removes stores and nothing else. vector's benchmarks take 0.28% fewer
at -O2 (leaffix 5.26%, rootfix 2.81%); nofib's programs move by less
than 0.2% at -O2, -O1 and -O0, and no benchmark of containers, vector
or megaparsec rises beyond its noise. The stage-1 compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's
CmmDiamondChain moves by 0.014% at most.
Assisted-by: Claude Opus 5.5
-
28337a44
by Mikolaj Konarski at 2026-11-20T00:13:10+01:00
Make a join's slot-to-slot move through a free register (ISSUE 27638)
A vreg gets a new stack slot where its format outgrows its old one
(getStackSlotFor, ISSUE 26668), as a Double's does when x86's broadcast
writes its register in place at DoubleX2# (vector_float_broadcast_sse
and _avx shuffle the register of a Cmm local). On two paths to a join
it can then be in memory only, in a different slot on each,
and the join's fixup needs a move from one slot to the other, on which
makeMove panicked ("we don't handle mem->mem moves").
makeMove now moves the value through a register free at the jump,
at the narrower of the two formats, no more than the source slot holds
or the destination slot takes; where no register of that format's class
is free and the format is at most a word wide, through an integer
register free at the jump; and otherwise by the Instruction class's new
mkSlotSlotMoveInstr: on x86 and x86-64 a word at a time through %eax
or %rax, saved in the destination's first word and given back
by an exchange. Elsewhere the method gives Nothing, its default,
and makeMove panics with a message of its own. Such a move
is a component of its own in the graph of the fixup's moves, both slots
being its vreg's, so joinToTargets_again makes these moves before
the others, while every register free at the jump holds nothing;
joinToTargets needs FR again, for the free registers.
The exchange, XCHG with a memory operand, is locked whatever its prefix,
so it costs more cycles than the one instruction it counts as; how many
was not measured. PUSH of each source word and POP
into the destination's would need no lock, no register and one
instruction fewer, but between the two the stack pointer is a word lower
and nothing tells the unwinding tables, which get a row at each DELTA
from an UNWIND whose label the method cannot make. The move is rare:
at the series' end nofib's modules at -O1 and -O2 hold XCHG between
registers only.
Where the jump's target expects the value in a register as well
as in the other slot, handleComponent instead loads that register
from the source slot and stores the register into the other slot
at the narrower of the two formats, needing no free register;
the slot-to-slot move, and its panic, are left to a value the target
expects in a slot only. That fixup is in no cycle either, its source
slot being the vreg's own, and no other move of the fixup writes
the register or the slot. handleComponent loses master's argument
of the jump instruction, which none of its equations read, the cyclic
one only passing it on to its own recursive calls.
The test, T27638, broadcasts a Double in one arm of a case between two C
calls; the parent commit's compiler panics compiling it at -O0, -O1
and -O2. Its variants: T27638a broadcasts a Float#; in T27638b the other
arm, which comes first, the broadcast being the default, uses the Double
again, so that the jump's target expects it both in a register and
in a slot; in T27638c nineteen Doubles are live at the join, so
that the move goes through a general-purpose register, and in T27638d
thirteen Int#s beside them, both compiled at -O; T27638f, compiled
at -O, is T27638d with the other arm using the Double again and first,
as in T27638b, and with eleven Int#s loaded after the Doubles,
and T27638g, compiled at -O, is T27638d with eleven Int#s loaded after
the Doubles, so that no register is spare at its join. The parent
commit's compiler panics on T27638a and T27638b at -O0, -O1 and -O2
and on T27638c, T27638d, T27638f and T27638g at -O1 and -O2,
and this commit's compiler without mkSlotSlotMoveInstr panics on T27638g
at -O1 and -O2. This commit's compiler sends T27638b through the fixup
into a register and another slot at -O0, -O1 and -O2 and T27638f at -O1
and -O2, and both compile and run to their outputs at -O0, -O1 and -O2.
Without both the new equation and mkSlotSlotMoveInstr it panics
on T27638f at -O1 and -O2, no register of either class being spare
at its join; T27638b, with a register spare at its join, it compiles,
moving the value through that register. At the series' tip the compiler
without the equation and the method likewise panics on T27638f at -O1
and -O2, and with them compiles T27638b and T27638f, which run to their
outputs at -O0, -O1 and -O2. With the fix, ISSUE 27638's own reproducer
(T27638e, compiled at -O), where move coalescing gives a Double vreg
a dying vector's location and format, compiles at -O1 and -O2, as does
a generated program that panicked at -O0, its output master's.
Cost: compiling perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain at -O0, -O1 and -O2, the stage-1 compiler runs
at most 0.0062% more instructions (T9961 at -O0) and allocates at most
0.011% more (T9961 at -O), the assembly the same in every cell; measured
on an earlier form of this commit, the stage-2 compiler ran up to 0.060%
more instructions compiling nofib's puzzle (at -O0), its allocation
moving by 0.002% or less. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.JoinToTargets allocates 29% more (0.684 against
0.529 GB) and its object is 36% larger, the cost of makeMove's
slot-to-slot clause.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
7a427822
by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
Predict branches into loop heads that only a heap or stack check makes
staticBranchPrediction's loop exit heuristic, lehPredicts, says nothing
about a branch into a loop head. A heap or stack check that fails calls
the garbage collector, which returns to a block that jumps back
to the check, and loopInfo counts that cycle as a loop; so in a loop
that holds such a check, the check's block is a loop head,
and the heuristic said nothing about the test that stays in the loop
by branching to it. loopHeads now leaves out a head whose back edges all
leave a block of coldBlocks, and the loop levels the heuristic compares
count only the loops left: counting the others too would put a block
that heads only such a cycle a level deeper than its siblings,
so that the heuristic would predict any branch into it. The set
is coldBlocks, not checkFailures: static prediction runs after register
allocation, so the cycle can close from a block the allocator put after
one that follows the failed check, which coldBlocks holds
and checkFailures does not. loopInfo no longer counts loop levels
(liLevels), which staticBranchPrediction now counts over the loops left,
and loopLevels and loopMembers, which had no caller, go, with the import
of GHC.Data.Graph.Directed that only loopMembers used. A back edge
leaving a continuation that a call returns to as well as the garbage
collector counts the same, so a loop closed through such a call loses
its head too; telling the two apart moved no figure measured.
As committed, with the levels limited, this shows no saving in cycles:
nofib's programs ran 0.3% more in geometric mean (below). The saving
sought is in cycles, not instructions: with the stay side predicted,
the layout can let it fall through, a taken jump fewer an iteration,
and a conditional jump is one instruction whether taken or not. Before
the levels were limited, lookupGE3's loop in containers' lookupge-map
took one jump an iteration instead of two, the tag test's jump backward
in the layout to the heap check and then one out of the comparison,
and GE Twan ran 2% to 11% fewer cycles at no more than 0.03% more
instructions; limiting them leaves that loop's jumps as they were.
Measured against the parent commit, on x86-64: the instructions
of nofib's programs and of containers', vector's and megaparsec's
benchmarks move by 0.003% or less in geometric mean, and only intmap
fromSet past its bar, 1.0% fewer at -O1. In cycles nofib's programs fell
0.01% in geometric mean with the heads left out and rose 0.3%
with the levels limited, single programs moving by up to 12% either way
where unchanged code lands elsewhere: gcd's 4.7% rise comes
from its bignum code, unchanged but placed 80 bytes later,
and hartel/listcopy's 12% from code that a grown function moved.
The stage-1 compiler allocates 0.11% less compiling perf/compiler's T783
at -O and 0.061% less compiling T12707, its allocation compiling T3294
and T9961 moving by 0.0084% or less; at -O0 its allocation moves
by 0.0044% or less.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
ad900b35
by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
NCG: invert floating-point conditional branches too
invertCondBranches turns a block's `jcc next; jmp other`
into `jncc other` only where the condition comes from an integer
comparison. maybeInvertCond complements the condition on the flags,
which nothing between the two jumps changes, so the swapped jumps take
the same path for every outcome of a floating-point comparison too,
an unordered one included, in each shape genCondBranch' emits for one.
Most such pairs nofib's objects keep at -O2 follow a ucomisd and go.
mandel2 runs 2.6% fewer instructions and smallpt 0.70% fewer at -O2;
no other program whose code changes moves by 0.1%.
Assisted-by: Claude Opus 5.5
-
90b9217f
by Mikolaj Konarski at 2026-11-20T00:13:11+01:00
Drop the assignments that only a discarded assignment read
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant" and "Assign literals after computed values
at the end of a block".
Cmm sinking computes liveness once, before its walk, so where the walk
discards an assignment that nothing reads, such as a copy, it keeps
the assignments that only that one read (ISSUE 8327). Its liveness
is now faint: an assignment to a local register that is dead after
it uses nothing, so a register that only such assignments read is dead
as well. Master's annotate, which pairs each node with the registers
live after it, now leaves out every assignment to a local register dead
after it, so that sinking drops a chain of assignments that only one
another read in one pass, across blocks and loops; master's
shouldDiscard, the walk's test for such an assignment, is deleted,
the walk testing its other case, r = r, by noOpAssignment. Nothing
is folded or inlined again. Master's cmmLocalLivenessL is now
localLivenessBy given gen_killL, localLivenessBy taking the step
over a block's middle nodes, and sinking's liveness is localLivenessBy
given the faint step, so that sinking checks it as cmmLocalLivenessL
does, panicking where a local register is live on entry
to the procedure; by the faint liveness, a register that only
a discarded assignment reads no longer counts. At -O, hand-written Cmm
that reads a register before writing it on some path reaches sinking so:
stack layout checks only a procedure declared with a parameter list,
and only where it needs the liveness, as at a call, and CmmLint only
under -dcmm-lint. Without the check, on a procedure that returns
a register written on one branch only, the linear register allocator
panicked, and with -fregs-graph the compiler produced code that returns
a register nothing wrote.
A second sinking pass over every procedure, its liveness recomputed,
drops them as well, but in a trial it made the compiler allocate 60%
more compiling perf/compiler's T3294 at -O, and its constant folding,
which in that trial rewrote (a - b) + c to a + (c - b) whatever b and c
were, cost containers' elemAt benchmarks up to 2.4% more instructions.
Recomputing liveness until no assignment is dead drops them too,
but takes a pass for each link of a chain of assignments each read only
by the next: on a procedure with a chain of 400, the compiler allocated
9.2 times what master's does.
The test, T8327, is a Cmm loop that assigns a constant read only
by a copy that nothing reads; the constant must not appear in its Cmm.
With the parent commit's compiler it does.
Measured against the parent commit, on x86-64: vector's benchmarks
at -O1 run 2.1% fewer instructions (sum[base] 14.3%, map[base] 9.1%,
spectral 5.0%, generateIO 4.0%), none more by over 0.003%;
in sum[base]'s loop, the address of the SPEC token that vector's stream
fusion passes from one iteration to the next was loaded at each
iteration, read only by an assignment that sinking discarded. At -O2
none moves by more than 0.028%, and those that move most have the same
code. containers' benchmarks at -O2 run up to 9.5% fewer (nubOrd
noFusion_repeat 9.5%, issue1202_repeat 4.7%, set alterF:insert:present
2.9%, lookupge-map GE split 0.61%), none more; at -O1 only
Data.Sequence's code changes, and no benchmark moves beyond its noise.
megaparsec's benchmarks at -O2 run up to 1.0% fewer (skipManyTill 1.0%,
manyTill 0.66% to 0.71%), none more, and at -O1 none moves. Of nofib's
programs only rewrite's objects change, and no program moves by as much
as 0.2%; fannkuch-redux does not change. The stage-1 compiler allocates
0.095% and 0.092% less compiling perf/compiler's T3294 at -O and at -O2,
0.11% and 0.10% less compiling T12707, 0.052% to 0.056% less compiling
T783 and 0.13% less compiling MR 16269's CmmDiamondChain at -O1 and -O2;
at -O0, and compiling T9961, within 0.0038% of what it allocates
at the parent commit. Compiling nofib's puzzle at -O2, the stage-2
compiler allocates 0.12% less.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
b1568b76
by Mikolaj Konarski at 2026-11-20T00:13:12+01:00
Keep Sp put across loops and tag tests in stack layout
To move into a merge request of its own, together with "Put a block's
reloads after its leading unwind in stack layout".
Stack layout gives a block the stack map of the first
of its predecessors it visits, and every later edge into the block gets
a fixup. It sets a diamond's frame (Note [diamond proc point]) up before
the tag test, trimmed to the variables live in the continuation,
and the continuation reloads them all, on the evaluated path too.
So in a loop whose body evaluates a variable, every iteration moves Sp
twice and stores the loop's invariants again, and where the variable
was evaluated already, it reloads registers that still hold their
values.
These changes to GHC.Cmm.LayoutStack keep Sp and the slots put:
* a loop head takes the stack map its back edges have in common,
by a second layout run where that pays, and the edge into the loop
pays the difference once (Note [Loop head stack maps]); a back edge
reached only through unlikely branches proposes nothing, and a head
every cycle through which makes a non-tail call to its own procedure
is left alone, its loop turning about once an entry (nofib's tak,
containers' foldrWithKey');
* a loop head that takes no such map, its back edges differing
in depth or needing no fixup, gets in the second run the depth
of the deepest continuation in its loop, with the loop's invariants
in the slots that continuation's frame gives them: a call returning
into the loop keeps that depth, where it moved Sp twice
an iteration, down at the call and up at the fixup on the edge where
its return path joins a path that made no call, and the edge
into the loop pays the Sp move and the invariants' stores once (Note
[Reserved frames in loops]), and where the second run seeds both
kinds of head and its seeds do not all hold, a third run seeds only
the heads that take a common stack map;
* the continuation becomes its reloads and a jump to its body, which
the evaluated path jumps to directly, where proc points
are not split and the reloads this adds at earlier proc points stay
at most two a diamond, or else for the diamonds whose tag test
follows no proc point whose reloads grow (Note [Tagged path skips
the reloads]); on a loop holding at most sixteen diamonds'
continuations the body takes every variable in its register but one
live across an inner loop that does not read it, and elsewhere only
those stored on the call's edge, reloading the rest itself where
they are used;
* the return address is stored on the call's edge only, where the call
is the only block returning to the continuation;
* a variable that at most one later call needs in a slot is stored
on the call's edge only too, that later call storing it on its own
path (Note [Tagged path skips the stores]);
* a diamond's frame keeps the stack's depth, its dead slots left
as holes (Note [Diamond frames keep their depth]);
* the frame a call into a diamond's continuation pushes is trimmed
to its live variables after layout, by a pass of its own, where,
among other conditions, proc points are not split and either
the procedure is called by a thunk of its Cmm group, as a lazy
list's producer is by the thunk of the list's tail, or trimming
takes at least half as many words as the frame keeps beside
its return address, the holes older than its youngest variable among
them, and the procedure is a thunk or the continuation is
on no loop: the call can evaluate a thunk that leads back to such
a frame, and each level of the recursion would hold the holes
(nofib's primes and multiplier); each call returning there moves Sp
up to the trimmed frame, the continuation moves it back down,
and the tagged path moves it nowhere (the same Note).
This fixes ISSUE 27991 for its example, whose loop stores nothing
on the stack at its iterations, and ISSUE 8905 in part: where a loop's
body evaluates a variable, the call's frame is set up on the call's path
only in the cases above, the others keeping the stores and reloads
it describes.
The reservation leaves these cases out, each having paid more
than it saved:
* a continuation reached only through unlikely branches, which
reserves nothing: a heap check's GC call returns into many a loop
that makes no other call, whose every entry and exit would pay
for a frame only that rare path uses (megaparsec's word32be,
containers' lookupGE). A block is reached so where every edge
into it is the unlikely side of a branch, the side a branch
on a literal never takes, or leaves another such block, in the least
set so closed, which leaves out a loop that only such blocks enter,
and this commit marks MAYBE_GC's test unlikely in rts/include/Cmm.h,
so that the primops whose `again: MAYBE_GC(again)` retries through
the GC call, newArray# and newAlignedPinnedByteArray# among them,
set up no frame on their fast path;
* a loop that only permutes the variables live at its head,
as integerAdd's swap of its arguments, which turns a few times
an entry;
* a loop making a non-tail call to its own procedure, each level
of the recursion then holding the reserved frame, a stack
the garbage collector scans (containers' foldl' over a line-shaped
tree);
* a loop holding a head seeded from its back edges, whose seed expects
its variables in other slots than the reserved frame gives them
(nofib's puzzle, six register swaps at a join).
A variable that the continuation's code saves at the first call
it reaches without a conditional branch, within eight blocks,
not redefining it on the way, is still stored before the test, whether
or not that code reads it: the tagged path would store it there anyway,
and the call's path would reload it at the continuation to store
it again (nofib's fasta, and A2T's zipWith5A and broadcast over small
arrays). In a procedure that makes a non-tail call of itself, and
for a diamond on a cycle of blocks, cold ones left out, that makes
no non-tail call into the procedure's recursion (its strongly connected
component in its Cmm group's call graph, computed once a group
in GHC.Cmm.Pipeline), those stores all stay only where the call's frame,
set up there, is no deeper with them all, and otherwise each only where
that frame has its variable in the slot the diamond's frame gives it,
in the call's own slot order or, where the frame is then no deeper
and its youngest slot of a variable that one or more later non-tail
calls of the procedure itself need, and of one that two or more need,
lies no younger than in that order, in the plain one: otherwise the slot
would deepen every level of the recursion (containers' PostOrder folds),
or a loop's seeded frame would be set up and dropped every iteration
(containers' intset insert and sequence update.10). Where tagSkip
refuses a diamond whose call's edge holds stores, those stores are made
before the test, at the end of the test's block after its Sp adjustment,
and not on both paths. A diamond laid out after its continuation stores
nothing on the call's edge only, the continuation's blocks having taken
each variable of its frame to be in its slot. No input was found
that lays a diamond out so, and by reading none comes from code
generated from Haskell, so no test reaches the case; measured
at the series' end, the guard costs the compiler 0.0053% more
instructions compiling T3294 at -O0, nofib's assembly at -O1 and -O2
unchanged, and testing instead whether the continuation has a stack map,
laid out or not, changes two procedures of compress2's Encode at -O2.
A procedure is matched with the calls into it, for its recursion
and for the thunks of its group that call it, by its info table's label,
which a call targets only where tables are next to code: elsewhere,
unregisterised, wasm32 and powerpc64le among them, calls target entry
labels, and stack layout lays every procedure out as one neither
recursive nor called by a thunk, as the comment at cpsTop's self_lbl
says.
tagSkip, which splits the continuations, checks the limit of two reloads
a diamond first against a bound read off the graph, each diamond's
variables taken in registers times the proc points whose regions hold
its tag test, and runs its analyses only where the bound exceeds
the limit; there it takes each block's live-in from the liveness
analysis, computing it only at a proc point that is no split
continuation, its loop rule (across) is one set a continuation,
the variables live across an inner component that the component does
not read, and the continuations on one loop share each block's
successors in it. laterSearch, which counts the later calls that need
a variable in a slot, searches only as far as each query needs,
over Steps that link each block to its successors' so that a search
looks up only its first block; across numbers each loop's blocks,
and liftFrames and tagSkip no longer walk every frame. Layout's search
for back edges, and has_loop, look for a back edge before testing
the cold blocks, so that the cold blocks are computed only where one
is found; the strongly connected components, shared by loopHeadSeeds
and reservedSeeds, are computed only where a loop head passes
loopHeadSeeds' other tests or, for reservedSeeds, an edge enters a proc
point that is not cold; liftFrames tests a frame against its size rule
before its loop, and asserts that a diamond's continuation takes one
word of arguments, layout recording a diamond only at such
a continuation; and a block's middle nodes are copied by (++) only where
something is appended. In GHC.Cmm.Info.Build, cafAnal takes a jump
into a split body as a reference to its continuation's info label,
asserting that the continuation is in contLbls, as a call's
continuation, the only kind a body is split off, always is: otherwise
each block's set gathered every later continuation, at a cost growing
with the square of a procedure's chain of evaluations. cafAnal panics
where a body is reached and its continuation is not, whose info table,
and the SRT covering the body, would then be dropped: no input shows it,
stack layout splitting a body off only where a call it lays out returns
there and leaving that call reached, and cmmSink, the one pass between
layout and cafAnal, changing no block's successors. The test is made
only where a body was split: made for every procedure, measured
at the series' end, it cost 0.0066% more instructions compiling T9961
at -O0. laterSearch goes depth first for 32 blocks and then on breadth
first from the blocks still to enter, which gives the same answer,
the answer being reachability over the states (block, whether a call
is counted): depth first only, a search ran down a loop's exit through
every later loop before the calls in the loop, and the stage-1 compiler
ran 3.0% more instructions compiling the battery's scaling program
lists, 400 loops in sequence over one list, at -O1; breadth first only,
it ran up to 0.036% more compiling perf/compiler's T12707 at -O0, both
against a form that started the search again breadth first
from the first block, in a second loop sharing the first's guards.
That form makes the stage-1 compiler run 0.127% fewer instructions
and allocate 0.125% less compiling lists at -O1 than the one loop,
the gap growing linearly with the number of loops; the one loop is kept
as the simpler. None of this changes the generated code.
Layout joins the block on a call's edge to the call's block where
it ends, where the call has no other way in and the procedure has
a diamond, by master's splice, which GHC.Cmm.ContFlowOpt now exports,
beside master's callContinuation_maybe, and marks INLINE (exported
without the pragma, it made the compiler allocate 0.018% more compiling
ManyBasicBlocks.cmm at -O0): unjoined, each tag test adds a block
to the maps the later passes keep of blocks, and at -O0, where no later
pass joins blocks, a jump.
A heap or stack check's GC call returns to a continuation that reloads
the variables and jumps back to the check. Where a split body jumps
to that check too, holding the variables in other registers
than the reloads give them, the allocator would fix the check's
registers from the retry and permute them on the hot path at every pass;
so, where the block the check's passing branch leads to ends in a jump,
or the block after it does where the first only jumps on, holding
at most unwinding information, ticks and comments, as under -g,
the retry, the jump to the check of the continuation or of the block
it jumps to, split body or not, jumps to a copy of the check, whose
passing branch leads to a copy of that block, and the hot check keeps
one way in (Note [Retries copy their checks]; A2T's rotate.inner
over large dense Storable arrays, which permuted its registers
by a cycle of xchg at each allocating check).
A change to GHC.CmmToAsm.BlockLayout goes with these:
* with the latch's fixup gone, a loop's exit can have the latch's
conditional edge and another block's unconditional one as direct
predecessors of near equal weight; buildChains, dropping the latch's
edge back into the loop as closing a cycle, left the latch's other
edge at its weight, so the other block fell into the exit
and the latch paid a jump an iteration (ISSUE 27799's reproducer,
with or without -fobject-determinism); where buildChains drops
a conditional edge from a chain's end into that chain's start,
the branch's other edge, if lighter and its target, unplaced
or starting a chain, has no info table, now takes the dropped edge's
weight (Note [Latch edges after a cycle]). It looks that edge up
in the CFG it holds, weighed by relevantWeight as the edges
sequenceChain gives it are, and puts its raised copy first, leaving
the edge, which then joins two placed blocks, to be passed over;
preferBackEdges raises some of the edges given too, but only edges
out of a block with one successor, and the latch's source has two.
relevantWeight, master's local of sequenceChain's directEdges,
becomes top-level for this, taking the blocks with an info table
as an argument.
Three tests in codeGen/should_compile check x86-64 assembly.
StackLayoutTagLoop, a loop that evaluates a list and then its head, two
diamonds whose frames differ, expects three moves of %rbp, Sp's
register, one where the loop is entered and one at each of its two
exits: master's compiler makes five, as does this commit's without
the loop-head seeds, and without a diamond's kept depth it makes six.
StackLayoutCallLoop, a loop calling a function on one of its paths,
checks the assembly for a return address stored below Sp, which
the parent commit's code stores; it is skipped on Windows and where code
is position-independent by default (Darwin and OpenBSD), where a label
is no immediate operand and the pattern cannot match, as master's
compiler passes it under -fPIC on x86_64-linux. Nothing was run
on those systems. The third, T27991, the example of ISSUE 27991,
searches the assembly for any movq of a register to an address off %rbp:
with the parent commit's compiler its loop stores two at every
iteration.
A loop head's seed in the second run keeps, of the slots its back edges
share, those within its depth: where the back edges arrive
from the deeper frames of continuations only unlikely branches reach,
a shared slot would lie below the seed's Sp, and the next call's frame,
set up from the seed, would index allocateIn's map of the stack out
of range. The test cmm_reserved_seed in cmm/should_run is such a loop
in hand-written Cmm, with one call and two more behind unlikely branches
whose continuations hold more variables; master's compiler compiles
it with -dcmm-lint at -O0, -O1 and -O2, and it prints the same values
at each. Without the restriction the compiler dies compiling it,
with "Ix{Int}.index: Index (6) out of range ((1,5))", in the ways normal
and optasm. It is not restricted to 64-bit targets and was run on x86-64
only.
Taking the variables in registers at the join is a trade: containers'
set foldMap_traverseSum takes 3.3% more instructions at -O1, and at -O2
map's fromSetA inner rows 0.43% to 0.45% more and intmap's Strict
fromSetA inner row 0.32% more (0.14% at -O1), the split continuation's
body moving its variables between registers at the join where
the parent's code used a memory operand; and orthotope's A2T benchmark's
window.zero, summed over large arrays, takes 5.04% more with boxed
elements and 3.37% more with Storable and Unboxed ones, its sumView
loading five to eight frame slots into registers on the path every
iteration takes; where a loop's elements take the call path, the split
continuation reloads the variables its body takes in registers at every
continuation, where the parent reloaded each at its use, as in A2T's
zipWith5A and concatOuter.map over small arrays, window over large runs
of Unboxed elements and rotate.inner over large dense Storable arrays.
The trade's toggle is Note [Tagged path skips the reloads]: the body
reading the variables from their slots instead makes nofib's compress
take 6.8% more instructions and queens 6.1% more.
Taking them in registers only on loops holding at most sixteen
continuations is a trade too: nofib's para takes 0.27% more instructions
at -O1, by one loop holding more, where taking them in registers saves
reloads and register moves at -O1 and costs reloads at -O2, nearly every
diamond there taking its call path. Lifting the limit reverts it,
but makes para take 0.50% more at -O2 and puzzle 4.38% more at -O1
and 2.23% more at -O2.
Storing on the call's edge only a variable that one later call needs
is a trade: at -O0 nofib's tak, mandel2, life, rfib, fasta and others
take more instructions, at -O1 multiplier, and at -O2 atom, ansi
and life, the path through a diamond's call paying a jump to the split
body and a register move more; the diamonds that lose and
those that gain differ only in their callers' arguments, which lie
outside the procedure that stack layout processes. In containers' graph
benchmarks the first of dfs's two calls stores on its edge a variable
the second call does not need, and line inputs gain by the smaller first
frame, dfs.line,n=1000000 24% fewer bytes at -O2 and -O1. Storing every
variable before the test instead makes nofib's programs take 0.91%
and 0.98% more instructions and containers' benchmarks 2.3% and 2.7%
more, at -O2 and -O1, and megaparsec's 3.4% more at -O2.
Stored in the older of two fresh slots, dfs's variable would leave
a hole in the second call's frame, a word a level of the recursion,
and make star inputs allocate a stack chunk more each time those words
add up to one. So for the frame of a non-tail call of the procedure
itself, in a procedure that loops, the variables later such calls need
take the older slots, where the frame would otherwise put one that none
of them needs in a slot older than one that one needs, and the next such
call's frame, once the others have died, trims from the young end.
This is a trade: against the commit without it, at -O2 and on graphs
of a million nodes, dfs.star allocates 10.2% fewer bytes and scc.star
and scc.line 5.4% fewer, and the depth-first searches over stars,
and scc and stronglyConnCompR over lines, take 0.5% to 1.65% fewer
instructions, while containers' other Data.Graph benchmarks take up
to 0.56% more, the most on graphs of a hundred nodes, the second
of dfs's calls moving Sp up to its trimmed frame where the hole kept
it put; and the compiler allocates 0.14% more compiling T9961 at -O0.
Ordering the slots of every frame instead costs an Sp move at each
trimmed call of other recursions, containers' foldMap_elem 1.2% more
instructions and nofib's binary-trees 0.76% more, and ordering every
frame of a procedure that calls itself and loops costs Sp moves at each
node of Data.Tree's folds over a node's children, Foldable1's foldMap1
over a line 6.8% more instructions. Whether the plain order puts
a variable that no later such call needs in an older slot than one
that one needs is asked in one pass over the frame's new variables,
which stops at the first such pair: comparing every pair, measured
at the series' end, the compiler ran 0.45%, 0.64% and 0.77% more
instructions compiling at -O1 a procedure that calls itself twice
and sums N words between the two calls and N after, the first call's
frame slotting N variables that no later call needs, with N at 200, 400
and 800.
Reserving a loop's frame is a trade: nofib's boyer2 takes 0.21% more
instructions, a loop's entry moving Sp and shuffling registers at each
iteration for a call path run less than half as often, and containers'
tree PostOrder.Foldable maximum 1.35% more at n=1000 and 0.39% more
at n=1000000; a further left-out case, for loops calling a procedure
private to the module, reverts them, but also gives back the gains
of nofib's sched (0.9%), transform (0.4%) and parstof (0.3%).
megaparsec's reachOffset-1000-1000 takes 1758 instructions
with or without that case, a few more than without the reservation:
the reservation's own trade. Giving a loop head the stack map its back
edges have in common is a trade too: a loop whose head is its exit test
and that runs no trip or one moves Sp down at its entry and up
at its exit, where the parent moved it at neither, so
that in orthotope's A2T benchmark Ranked's and Dynamic's scalar strided
cells over Storable and Unboxed elements take 2 and 3 instructions
a call more, the generate.scalar strided cells over Unboxed elements 2
to 6 more and Shaped's over Storable and boxed ones 1 more, and Shaped's
empty toVector and toUnorderedVectorT cells 3 to 4 more; leaving
the loop-head maps out reverts these with the gain on ISSUE 27991's
example. Copying such a head's exit test onto the edges into its loop,
where its map holds without the copy and the loop's exit reaches
no call, takes these back, but makes containers' intset fromAscList take
20% more instructions, in the garbage collector, and map
fromDescListWithKey 3.4% more at -O1.
Taking a block as cold where every edge into it is cold, rather than one
that an unlikely branch alone enters, is a trade: containers'
graphFromEdges takes up to 0.54% more instructions and nofib's awards
0.55% more at -O2 and -O1, where the wider rule changes the code
of GHC.Internal.Data.OldList and of awards' QSort, and containers' set
foldMap_traverseSum 0.77% fewer at -O2; the narrower rule leaves a frame
on the primops that retry through MAYBE_GC.
Code grows: nofib's objects take 1.3% more bytes at -O2 and 1.2% at -O1
(0.13% at -O0), as the split continuations' bodies move their variables
into registers at the joins and reload them at the continuations,
and each trimmed frame's call moves Sp up and its continuation moves
it back down. Not trimming takes back about a quarter of that and costs
primes' and multiplier's stack; the trade's toggle, the bodies reading
their variables from their slots, takes back the moves and reloads only
by storing on both paths, which makes code larger still.
The compile cost is that of these analyses and of the larger code:
against the parent commit the stage-1 compiler allocates 1.3% more
compiling perf/compiler's T12707 at -O0 (0.95% and 0.86% at -O and -O2),
0.87% more compiling T9961 and 0.56% more compiling T783 at -O0,
and 1.9% less compiling T3294 at -O0; over nofib's compilations
the stage-2 compiler allocates 1.7%, 1.6% and 0.79% more in geometric
mean at -O2, -O1 and -O0. Compiling MR 16269's CmmDiamondChain,
the stage-1 compiler allocates up to 0.059% less and runs 0.85% to 0.88%
fewer instructions. T12707's is a trade: of the 0.84% more instructions
the stage-1 compiler runs compiling it at -O0, turning tagSkip
and liftFrames off takes back about 0.6 points and gives up what they
gain, and the rest is layout's work a diamond and that of the passes
after it on the code layout changes; nofib's compile cost, at -O2
and puzzle's the most (the stage-2 compiler allocating 8.8% more
compiling puzzle at -O2), goes with the size trade, the passes after
layout working on the larger code.
Stack layout's local liveness is an LRegSet, as in master's
cmmLocalLivenessL, and the Data.Set form goes: GHC.Cmm.Liveness's
cmmLocalLiveness, noLiveOnEntry and the SPECIALIZE pragmas
of liveLattice and xferLive are deleted, those two now typed
at GlobalRegUse, their one remaining use, CmmLocalLive becomes LRegSet,
and liveLatticeL tests a change by isSubsetOfUniqueSet rather
than by the joined set's size; GHC.Cmm.Lint calls cmmLocalLivenessL;
insertReloadsAsNeeded runs over LRegSet; and setupStackFrame takes
the liveness map, as master's does, with a table, by unique,
of the defined variables live at any proc point, in which allocateIn
looks a variable up only where it stores it, testing membership
in the LRegSet. This is a trade, measured on an earlier form
of this change, which built from the table a Data.Set of the variables
live at each proc point: against the same tree with the Data.Set form,
the compiler runs 0.138% more instructions and allocates 0.017% more
compiling T783 at -O0, and 0.025% and 0.037% more compiling puzzle
at -O0 (T783's in Word64Set's operations on its small sets
and the table's walk; puzzle's instructions in the table, its walk
over every node's definitions and the Data.Sets built from it, the set
operations themselves running fewer, and puzzle's allocation
in Word64Set's insertions and deletions), and less in every other
compilation measured: T3294 at -O0 2.31% fewer instructions and 1.79%
less allocation, CmmDiamondChain at -O0 1.17% and 0.51%, puzzle at -O2
0.18% fewer instructions. Keeping the Data.Set form reverts both.
setupStackFrame, aheadSaves and cmmLayoutStack, for the variables live
at its proc points, look up the variables live on entry to a block
by a new liveOnEntry, which panics for a block without a liveness fact,
where master's setupStackFrame took the empty set: the analysis gives
a fact to every block the entry reaches, and every block they look up
is so reached.
Where the second run's seeds do not all hold, or the third's where
that runs, the heads whose seeds held run again with theirs alone (Note
[Loop head stack maps]). This is a trade: the run costs the compiler
0.016% more instructions and 0.020% more allocation compiling puzzle
at -O2, and nothing in the other compilations measured, and makes
nofib's gen_regexps take 9.05% fewer instructions at -O2 and -O1, two Sp
moves fewer a character of its inner walk over each string and one more
a string, cacheprof 0.38% fewer, containers' transposeG 2.9% to 3.4%
fewer and megaparsec's scientific 2.5% to 3.9% fewer at -O2. Keeping
the first run at once reverts both.
In GHC.StgToCmm.Utils, emitMultiAssign, master's code, no longer assigns
a variable to itself, as a self-recursive tail call or a jump
to a let-no-escape binding passing an argument unchanged did: layout
takes an assignment to a variable as leaving the variable's slot stale,
so that the next call stored it again. This is a trade: the compiler
runs 0.151% and 0.156% fewer instructions compiling T783 at -O and -O2,
and 0.022% and 0.023% more compiling T12707 at -O and -O2, where
it allocates 0.026% and 0.027% more, in maps and sets keyed by uniques,
which shift once those assignments are gone; the generated code differs
only in its labels. Emitting the assignments again, with layout
exempting them, reverts both.
Measured against the parent commit, on x86-64, in instructions: nofib's
programs take 3.8% fewer at -O2, 4.5% at -O1 and 0.73% at -O0
in geometric mean (gen_regexps 34%, queens 24% and bspt 20% at -O2,
k-nucleotide 40% at -O1), and some take more: at -O0 tak 1.45%, life
1.31%, mandel2 1.31%, rfib 1.02%, nucleic2 0.75%, parstof 0.68%, kahan
0.61%, digits-of-e1 0.58%, fasta 0.48%, fulsom 0.42%, atom 0.26%
and solid 0.23%, at -O1 life 1.32%, ansi 0.36%, multiplier 0.32%
and atom 0.31%, and at -O2 life 1.32%, ansi 0.33% and atom 0.32%.
containers' benchmarks take 6.2% fewer at -O2 and 6.7% at -O1 (graph
dfs.maxDAG,n=15 36%), and more in intmap's cps folds, 0.94% to 1.01%
at -O2 and -O1, set foldMap_traverseSum and the fromSetA rows above,
and sequence fromFunction.ix10000/5000, 0.82% at -O1. megaparsec's take
6.7% fewer at -O2 and 4.8% at -O1 (reachOffsetNoLine 23% at -O2, string'
13% at -O1), and vector's 4.3% fewer at -O2 and 10.6% at -O1 (minimumOn
31%), none of either more. Of the cells of A2T's sample that move
by 0.2% or more, all take fewer (toList and toVector over small dense
boxed arrays 28%) but the scalar and generate.scalar strided cells
above. No nofib program's allocation moves; containers' set
alterF:insert:absent allocates 3.11% more at -O2 and -O1, a stack chunk,
and intmap difference-common_nn_swap a stack chunk more at -O2, where
difference-common_sn_swap allocates one fewer. Compiled by the boot
compiler, GHC 9.12.4, GHC.Cmm.LayoutStack allocates 4.2 times as much
(7.87 against 1.89 GB) and GHC.Cmm.Pipeline 52% more (0.757 against
0.498 GB). Compiling the battery's scaling programs calls, lists
and allocs at -O1, from N = 100 to N = 400, the stage-1 compiler
allocates 1.4% to 1.9%, 9.6% to 9.2% and 1.2% to 1.7% more
than the parent commit's; the ratio no longer rises with N for lists
and rises by up to 0.5 points for calls and allocs.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
cc9b448d
by Mikolaj Konarski at 2026-11-20T00:13:12+01:00
Load a field again after a call from its saved constructor
To move into a merge request of its own, on top of that of "Keep Sp put
across loops and tag tests in stack layout".
This commit's code lies outside GHC.CmmToAsm, which it changes only
in a comment and in its README: it changes stack layout,
GHC.Cmm.LayoutStack, sinking, GHC.Cmm.Sink, StgToCmm, which records
for it the registers a case alternative loads its constructor's fields
into, and the driver, which turns it on only for the Cmm that StgToCmm
generates.
A case alternative loads the fields of its constructor where it starts,
so a field used only after a call is loaded before the call and saved
across it (ISSUE 20334). Saving the constructor in place of its fields
could keep dead fields alive (ISSUE 20333), but where the constructor's
variable is saved across the call anyway, its slot keeps them alive
already. There stack layout now saves the field nowhere and loads
it from the constructor after the call, where the variable is reloaded,
or, in a body split off a tag test's continuation, after the test,
on the paths that use it.
This runs only under -fcmm-sink, without which the load before the call
would stay, and only over Cmm generated from STG: hand-written Cmm keeps
none of the convention it rests on, a local of a GC pointer's type there
able to hold any address, of memory the procedure or a call writes.
Master's CmmConfig gains cmmOptRefetchFields, which refetchPass tests,
which master's initCmmConfig sets False, and which master's doCodeGen
(GHC.Driver.Main.Compile), the one caller of cmmPipeline over the Cmm
that StgToCmm generates, sets from -fcmm-sink; so a Cmm file, and Cmm
that a client of the GHC API parses and runs cmmPipeline over,
as the testsuite's regalloc_unit_tests does, loads no field again.
StgToCmm records the registers of each case alternative that loads every
field of its constructor, two or more (a CgConFields statement
in the code, which emitProc collects into CmmStackInfo's con_fields
while flattening the code), and two rules decide the proc points where
a field is live. Where its constructor's variable c is live, a field
is left out at every such point or at none: at each where the field
is wanted after the call (used before the next proc point, saved at one,
or the region larger than the sixteen blocks walked), c must be used
there too. Where c is dead, the decision is made per call: c is saved
in place of the fields where every register of their alternative
is live, two or more of them are saved across no call where only some
of them are live, nor across a diamond's call whose body uses some
of them, one of them is live at some proc point that is neither
the procedure's entry nor reached only through unlikely branches,
as a continuation only calls to the collector return to is, and no proc
point where c is dead and all of them are live is on a cycle of blocks,
none of them cold, that assigns none of them and uses one of them,
and nowhere else, so that it keeps no dead field alive, its store
replaces two or more, a diamond's tagged path keeps the fields
in registers, and no loop reloads c on every trip.
Wherever a field is live, c must hold the constructor the field
was loaded from, so a field is saved where it is live at the start
of a block assigning c, or loaded in a block that assigns c after
the load (the walk assigns, in fieldRefetches): for x = W_[c + 7]; c =
W_[c + 15]; call f(x), with x and c live after the call, in one block
as written or once cmmCfgOpts has merged two, x would otherwise
be loaded from the new c. Code generated from Haskell is taken
not to have that second shape, a field's load being its register's only
assignment and preceding its uses, and the register of a binder in scope
being assigned again only by a self-recursive tail call or a jump
to a recursive join point, after which the field is dead: an argument
from StgToCmm's conventions, not a proof. Measured at the series' end,
nofib's assembly at -O1 and -O2 is the same with and without that rule,
and with hand-written Cmm left out no test reaches it.
A function closure loads its free variables where its code starts,
and their registers are listed as an alternative's too, so
that the closure is saved in their place across a call after which they
are live and it is dead (ISSUE 20333), and across a diamond's call.
Against its parent, nofib's puzzle runs 5.7% and mate 2.4% fewer
instructions at -O1, and no program runs 0.2% more at -O1 or -O2;
containers' IntMap symmetricDifference benchmarks run up to 9.0% fewer
at -O1 and the map and set cpsOneShotSum folds 2.6% to 4.0% fewer at -O2
and -O1; T20333's code at -O has half as many stores of a double
to the stack; and the stage-2 compiler takes 1.3% fewer instructions
and 0.48% less allocation compiling puzzle at -O1, and 0.23% fewer
instructions and 0.060% more allocation at -O2, its code changed
at both. Past their bars upward: containers' intmap union-disj_nn
and union-disj_nn_swap at -O1, 111% and 104% more instructions,
allocating 33496 bytes against 728, a stack chunk more (on an earlier
form of the series the benchmark's warm-up call stayed within
the initial stack and the measured call overflowed it, and with a larger
initial stack they ran fewer instructions and allocated the same),
and the rows allocating one stack chunk more, intmap
difference-common_nn_swap at -O1 and symmetricDifference-mix_ns
and mix_sn_swap and sequence splitAt/append.100 at -O2; intmap
restrictKeys:random, 0.46% more instructions at -O2, and the intmap
symmetricDifference-disj_nn_swap row, two instructions more at -O2;
megaparsec's scientific benchmarks, 0.17% to 0.24% more at -O2 and 0.56%
to 0.85% more at -O1, and reachOffsetNoLine 0.49% more at -O1;
and the reshape cells of orthotope's A2T sample, four instructions
a call more (0.31% to 0.61%), and its Storable and Unboxed stretchOuter
cells one more (0.25%).
Stack layout follows the alternatives in one walk over the proc points,
leaving one once fewer than two of its registers remain to be saved
in place of its constructor's variable: over every alternative at every
proc point the compiler allocated 0.49% more compiling Data.Colour.Names
at -O2, whose one function closure's free variables are each live up
to one call of a chain, and it now allocates within 0.03% of what
the series' end allocates without this commit.
Saving the closure holds it from its assignment to the call beside
the free variables used on the way, so where the blocks reached
from its assignment without passing a proc point hold a loop, on the way
to the call or not, it is saved in their place only where one of them
is used in none of those blocks that assign the closure or start
with it dead: in spectral-norm's timesAtAv, whose loops use two
of its closure's four free variables and a call after them the other
two, the closure otherwise held one register more in the loops and ran
5.9% more instructions. Without a loop the register held more costs one
spill and reload at most, and saving the closure in place of k free
variables saves k - 1 stores for one load more. A constructor's
alternative keeps the rule above: declining where a loop before the call
used three of four fields cost two instructions a call, and in loop-free
code declining moved nofib's fish by +0.28%, its gains in multiplier
and boyer being those of the rule for heap checks below. The test costs
instructions compiling puzzle at -O2, in stack layout's own walks.
At a diamond, saving the closure in place of k free variables saves
the tagged path k loads and k stores for a move of the closure out of R1
and its store, and costs its reload and the k loads from it, which fold
into their uses as reloads from the stack do: 2k - 3 instructions fewer,
less one for each used after a store to the heap, which its load does
not pass.
Where none of an alternative's registers is live at a proc point
that is neither the procedure's entry nor reached only through unlikely
branches, as a continuation only calls to the collector return to is,
they are saved across those calls and its constructor's variable is not:
holding the variable to the check costs the path passing it a register,
nofib's boyer copying it to another one, and saving it in their place
saves stores only on the path to the collector. Against this commit
without the rule, nofib's multiplier runs 0.26% and boyer 0.21% fewer
instructions at -O2, 0.22% and 0.21% at -O1, and no program runs 0.2%
more at -O2, -O1 or -O0, where no object changes; megaparsec's
benchmarks run 0.30% fewer at -O2 and 0.53% at -O1 by their geometric
mean, up to 3.0% fewer, and none more; no containers benchmark runs 0.1%
more and no vector benchmark moves by 0.05%; and the compiler's
allocation moves by under 0.01% compiling T3294, T12707, T783, T9961
and CmmDiamondChain, and rises by 0.1% on no module of containers,
vector or megaparsec.
Sinking, GHC.Cmm.Sink, now carries a load that may read the heap past
an assignment to Hp: master's conflicts held every such load above any
assignment to Hp, and so above a heap check, also where only the path
passing the check uses it, so that the fields loaded again at a proc
point, or in a body split off one, that ends in a heap check would
not fold into their uses. An assignment to Hp writes no memory,
and a load whose address uses Hp stays above it, the assignment writing
a register the load reads; below it, the stores into the new object
conflict with every load that may read the heap, and the collector runs
only in the check's call, which no load from memory crosses. So a load
moved below the check reads on the passing path the word it read above
it, and after a collection the code runs again from the call's
continuation through what the frame saved, which stack layout fixed
before sinking runs; the rule that an assignment to Sp conflicts
with a read of the stack stays.
That is a trade, measured on a form of the series' end without master's
rule against an earlier form with it, where stack layout loaded below
such a check the fields passing through it. It costs containers' intmap
fromList and fromListWith benchmarks over random duplicate keys 0.17%
to 0.22% more instructions at -O2 and 0.18% to 0.24% more at -O1, one
register move in one block, where a field's load passes the assignment
of the register holding its address, and nofib's maillist 0.03% more
at every level, in ghc-internal's hClose_help. Against that, nofib's
programs run 0.007% fewer instructions at -O2 and -O1 by the geometric
mean and fannkuch-redux 0.24% and 0.22% fewer, containers' IntSet
symmetricDifference benchmarks run 0.11% to 0.74% fewer at -O2 and 0.23%
to 0.65% fewer at -O1, and megaparsec's scientific benchmarks as many
but at the largest size, 0.16% and 0.17% more, inside the spread
of the runs with the rule.
Where all of an alternative's registers are live and its constructor's
variable is dead at a proc point on a cycle of blocks, none of them
cold, that assigns none of them and uses one of them, the fields
are saved, their stores running once before the cycle, where
the variable would be reloaded on every trip: orthotope's
genericFoldlStored, folding a boxed vector by a call at each element,
ran one instruction more an element with the vector saved in place
of its three fields. And a loop head's seed (Note [Loop head stack
maps]) can move an inner loop's head off the depth at which its back
edges arrive, which then move Sp twice a turn of the inner loop,
as in orthotope's sumA over a strided view; such a head, its back edges
at one depth needing no fixup in stack layout's first run, is now seeded
with their first-run map in one run more, kept if all its seeds hold,
at the cost of one instruction an entry of an inner loop that does
not turn. Against this commit without both, in orthotope's A2T benchmark
the large boxed Dynamic sumA, rerank and rerank.one cells run 0.50%
to 4.2% fewer instructions and anyA's large runs and window cells
of Storable and Unboxed arrays 11% to 14% fewer, all of them,
in the forced mode, back to the parent commit's counts, and the small
ones 1.1% to 1.6% fewer; vector's map[lens] runs 1.1% fewer at -O2
and -O1, back to the parent's count; no nofib program moves by 0.2%
at -O2 or -O1, nor any containers or megaparsec benchmark at either,
nor any other vector benchmark by 0.05%; and the compiler's instructions
and allocation move by 0.011% or less compiling T3294, T12707, T783,
T9961 and CmmDiamondChain.
Measured on an earlier form of the series, against that form's tip,
with an earlier form of this change: containers' benchmarks ran 0.58%
fewer instructions at -O2 and 0.77% fewer at -O1, the rows that rose,
in instructions or by one stack chunk's allocation, rising no more
under a larger initial stack; and in orthotope's A2T benchmark every
rotate cell allocated the same and none ran more than 0.1 instructions
a call more, rotating an empty dense Storable array taking 620.78
instead of 626.76.
The test T20334 greps the assembly of three functions for Doubles stored
on the stack: the reproducer posted on ISSUE 20334, a variant whose call
is to length, and one whose constructor is dead across the calls, saved
in place of its fields. Of the 11 the parent commit stores, only
the three of V's constructor function's entry to the GC remain. T20333
greps the same in ISSUE 20333's example, in Double#s, and in a variant
whose closure's free variables are used after a call: of the 16
the parent commit stores, only the 8 of foo's and bar's entry to the GC
remain. T20333b and T20333c grep the offsets of the stores below Sp:
where a function closure's four free variables are used in both arms
of a branch before a call and after it, the closure's entry stores one
value on each path where the parent commit's code stores four; and where
a case alternative uses its constructor's four fields across a loop
and a call, the parent commit's two stores below Sp in its function go.
Two tests in cmm/should_run are hand-written Cmm, skipped on 32-bit
targets. cmm_refetch_store loads a word through a local of a GC
pointer's type at an offset that is no multiple of the word size, has
a call, or the procedure itself between two calls, store to that word,
and returns the word loaded: with fields loaded again in Cmm files,
its procedures returned 353123 and 101016162 in place of 353025
and 101016065. cmm_refetch_reassign loads a field from c
and then assigns c in the same block, in one block as written and in two
that cmmCfgOpts merges, and prints 66049 for each, where the field
loaded again from the new c printed 66050; with no field loaded again
in Cmm files it no longer reaches the walk that saves such a field.
Measured at the series' end, leaving the reload off for Cmm files keeps
the same assembly for every .cmm file of rts and libraries that compiles
alone at -O2, plain and with -DTHREADED_RTS, the vector variants
of Jumps and AutoApply not compiled.
Master's cmmLayoutStack now maps the lowering of safe foreign calls
over the blocks only in a procedure where a block ends in one,
and rebuilds the graph from a list of blocks only where it lowered
a call or joined an edge block; elsewhere it returns the graph
that insertReloadsAsNeeded, master's too, now returns in place
of its list of blocks.
Measured with stage-1 compilers against the parent commit, the compiler
runs 0.075% more instructions and allocates 0.023% less compiling
perf/compiler's T12707 at -O, whose assembly changes, and 0.065% more
and 0.024% less at -O2; it runs 0.0028% and 0.0050% fewer instructions
and allocates 0.025% less compiling T3294 at -O and -O2, and runs 0.14%
and 0.15% fewer instructions compiling MR 16269's CmmDiamondChain at -O1
and -O2, their assembly unchanged; and for T9961 at -O and -O2
it changes by 0.014% or less, while it runs 0.085% fewer instructions
and allocates 0.14% less compiling T783 there and allocates 0.29% less
compiling CmmDiamondChain. Compiled by the boot compiler, GHC 9.12.4,
GHC.Cmm.LayoutStack allocates 31% more (10.30 against 7.87 GB),
the simplifier allocating 35% more and the code generator 28% more,
as the module holds 31% more lines of code. Collecting the alternatives'
registers while flattening the code and deciding once a procedure
whether any field is loaded again took 0.065 points off T12707's
instructions at -O. What remains, in a procedure with a proc point other
than its entry, is the walk over every middle node that finds the field
loads: with the analysis after it skipped, the compiler runs within
0.003 points of these figures compiling T3294 and T12707 at -O
and CmmDiamondChain at -O1, and with the pass that loads them again off,
no more than the parent commit's; only the code generator listing
the loads as it emits them could spare the walk, which was not tried.
At -O0, where the analysis is off and the assembly the same,
the compiler runs 0.27% fewer instructions compiling T9961, 0.14% fewer
for T12707, 0.28% fewer for T783, 0.17% fewer for CmmDiamondChain
and 0.030% fewer for T3294, and allocates 0.086% to 0.56% less:
cmmLayoutStack no longer rebuilding its graph in every procedure, at any
level or in Cmm files, ofBlockList inserts a quarter fewer blocks
compiling T9961 at -O0, and CmmDiamondChain, a Cmm file, falls alike
at -O0, -O1 and -O2. Compiling nofib's programs, the stage-1 compiler
allocates 0.064% more for simple at -O1 and 0.053% more at -O2, 0.059%
and 0.080% more for bspt, 0.054% and 0.20% for sorting, 0.069%
and 0.054% for sphere, 0.044% and 0.054% for anna, 0.019% and 0.041%
for transform, and 0.001% and 0.003% for clausify. The cycles of blocks,
none of them cold, on which an alternative's registers are all live
and none assigned are found once for all of its proc points; with them
found by a walk from each proc point, the compiler allocated 0.45%
and 0.27% more compiling simple and bspt at -O1.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
26433c22
by Mikolaj Konarski at 2026-11-20T00:13:13+01:00
Jump conditionally to a likely false comparison's false target
genCondBranch jumps to the true target conditionally and to the false
one after, and ignores cml_likely. Where the layout makes either target
a fall-through, invertCondBranches and dropJumps leave one conditional
jump whichever order it emits; where neither jump falls through,
the conditional jump is the shorter way to its target,
so invertCondBranches now swaps the two jumps of an integer comparison
likely false whose true target does not come next. After layout rather
than before genCondBranch: swapped there, every heap and stack check's
jumps were swapped and swapped back by invertCondBranches, costing up
to 0.29% more instructions compiling at -O0. invert examines a block's
last two instructions once and chooses between the old rule and the new
one. Master's test that the conditional jump's target is the next block
becomes a call of GHC.CmmToAsm.BlockLayout's fallsTo with the target's
label, which looks past the blocks between that hold only meta
instructions and have no info table, as a block whose jump the layout
dropped holds its unwinding information under -g, so that such
information changes no inversion.
Measured on x86-64 against its parent, in instructions: containers'
IntMap fromSet and fromSetA rows take 0.32% to 0.46% fewer at -O2
and fromSet 0.36% fewer at -O1, beyond the leftover jump "Drop jumps
over blocks dropJumps empties" removes there; no benchmark rises beyond
its noise, and the stage-1 compiler's allocation moves by 0.052% or less
compiling each of perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain, at every level measured.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
28ab5db0
by Mikolaj Konarski at 2026-11-20T00:13:13+01:00
Add an estimate of block frequencies for the linear allocator
blockFrequencies in GHC.CmmToAsm.CFG makes mkGlobalWeights' estimate
of how often each block runs, for the linear allocator, from the native
CFG before allocation: static prediction's edge probabilities
(the two-way rule factored out of staticBranchPrediction
as predictBranch, shared, given the procedure's tagRegisters
as the layout's estimate is) and calcFreqs' fixpoint, with loops found
by one depth-first search and the whole computation in two arrays.
The arrays take every edge's target for a node of the CFG, which a debug
compiler asserts: getCfg makes a node of every block it reaches,
and a later writer adds an edge by addEdge, which makes its target one.
A later commit passes it to the linear allocator. Compiled by the boot
compiler, GHC 9.12.4, GHC.CmmToAsm.CFG allocates 20% more (3.88 against
3.24 GB).
Assisted-by: Claude Opus 5.5
-
419155c1
by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Use block frequencies to order the linear allocator's SCCs
Where block frequencies are estimated, linearRA_SCCs allocates the SCCs
in an order computed before allocation from the estimate and the jumps
(hotFirst): the procedure's first block first where no loop holds it,
then the earliest in dependency order among those it can allocate,
and it sets aside an entry other than the first block while a block
it jumps to, not yet reached, runs more than 1.2 times as often
as the entry; where nothing can be allocated, the entry set aside
that the estimate calls hottest goes next, the entries set aside kept
in a set by estimate, hottest first and ties to the earlier, from which
each such fallback takes the first still set aside. This replaces
the deferral of the blocks the garbage collector returns to and
of a continuation entering a call-free loop, which stay where there
is no estimate: on x86-64 without -fcmm-static-pred, as at -O0,
and on other targets, where allocCold is empty and only
the continuation's deferral stays. They stay too where the estimate
lacks one of the procedure's blocks: under -finfo-table-map, where
the native code generator drops no dead code, liveness keeps
the continuation of a call that cmmToCmm made unreachable, while
the CFG, and so the estimate, holds only the blocks the entry reaches
(ISSUE 28088); hotFirst returns Nothing there, and linearRA_SCCs takes
its branch without an estimate. The first block first keeps a loop
calling itself on the argument registers (Data.Tree's and Data.Map's
folds); the hottest entry set aside first gives a join of two
continuations, both waiting, the hotter's registers (Data.IntMap's
mapKeysMonotonic at -O1). hotFirst is NOINLINE, so that its local thunks
are not allocated for every procedure at -O0, where it is not called.
CmmToAsm passes Linear.regAlloc the estimate of block frequencies
from a given entry where static prediction is on (-fcmm-static-pred),
as for the layout's estimate, and regAlloc computes it
from the procedure's first block.
The test T27800_itm in regalloc, the loop of cmm/should_compile/T27800
and a call behind a branch on a constant, compiled with -finfo-table-map
on x86-64, checks by -ddump-asm-stats that only the continuation's jump
into the loop pays a fixup move: allocated in the given order, each
of the loop's two jumps went through a block moving a register. Measured
at the series' end, a compiler tracing hotFirst's branch for a missing
block took it for the test's procedure and never while compiling nofib
at -O1 under -finfo-table-map. Keeping the entries set aside in a list,
filtered and folded over for the hottest at each fallback, the compiler
ran 0.51 and 15.0 thousand million instructions compiling at -O1
a procedure of 400 and 3200 two-way branches in sequence whose arms each
end in a call, where it runs 0.34 and 2.44, measured at the series' end.
The users' guide's entry of -fcmm-static-pred, master's, now says
that the prediction also orders the blocks the linear register allocator
allocates, master's sentence that the flag has no effect
under -finfo-table-map now limited to the layout, and that the flag has
no effect on other architectures than x86-64.
Within a cyclic SCC that holds a block whose first jump target in
it and another differ in estimate by a factor of 1.2, and
that is entered at some block, reached from outside it or an entry,
hotFirst gives the blocks hottest first (hotOrder), starting from every
such block, each block's jump targets in the SCC reached as it goes,
so that the hotter side of the branch fixes its join's registers
and the colder side pays the moves. Entered at more blocks, its joins
also meet registers fixed apart from the order, an outside predecessor's
at a block reached from outside and none at an entry, and the order
ranks such blocks by an entry's heat, the estimate's guess for the call
or evaluation returning to it. Ordering such an SCC too is a trade:
measured at the end of the series against that end with only the SCCs
entered at one block ordered, orthotope's A2T runs 0.52% to 0.54% fewer
instructions in its eight indexIndex cells over small arrays (Dynamic
and Ranked, Storable and Unboxed, dense and strided), and the compiler
runs 0.40% more instructions and allocates 0.15% more compiling nofib's
puzzle at -O2, whose loops are entered at many blocks, puzzle's run
unchanged. Measured with the order placed at the end of the series,
against that end, in instructions: megaparsec's skipManyTill, manyTill
and endBy take fewer at -O2, and nofib's wheel-sieve1 fewer at -O2
and -O1, wheel-sieve2 too, and k-nucleotide at -O2, and no benchmark
takes more beyond its noise; no compile-cost cell moves beyond
its noise.
Measured on x86-64 against its parent, with both stage-1 compilers
over the same libraries, in instructions by the geometric mean: at -O2
and -O1 nofib's programs take 0.177% and 0.156% fewer, containers'
benchmarks 0.439% and 0.481%, vector's 0.354% and 0.567%
and megaparsec's 0.403% and 0.190%, and orthotope's A2T benchmark takes
0.410% fewer. No program's allocation moves by 0.2%, and nofib's objects
take 0.349% and 0.358% fewer bytes at -O2 and -O1, puzzle's 0.55%
and pidigits' 0.30% more at -O2 and scc's 0.20% more at -O1.
The order is a trade, its toggle the order itself (hotFirst's guard
in linearRA_SCCs). Against its parent these rows rise past their bars.
In loops closed through a call, which the estimate rates at a trip
multiplier far below the run's, containers' map
fromList-distinctAsc:fusion takes 2.4% more and set
fromDistinctDescList:fusion 2.0% more at -O2. Where the block now
allocated first fixes a join's registers for the blocks after it,
megaparsec's count', some, skipSome and sepEndBy1 take more moves
an element, 0.26% to 0.88% more at -O1 and -O2, a continuation's reloads
landing in other registers, and containers' fromAscListWithKey
and fromDescListWithKey, 0.42% and 0.36% more at -O2, and map alterF's
lookup present, 0.79% and 0.39% more at -O2 and -O1, and lookup absent,
0.37% more at -O1, take a move or a shuffle more at a join. Containers'
map fromListWith-asc:fusion and fromListWithKey-asc:fusion take 0.97%
to 0.98% more at -O2 and map fromDistinctDescList:fusion 0.85% more
there, megaparsec's sepBy and sepBy1 0.35% to 0.37% more at -O1,
vector's next/prevPermutation baseline 0.10% more at -O2, nofib's fasta
2.7% more at -O2, puzzle 0.60% more at -O2 and cacheprof 0.23% more
at -O1, and 17 cells of orthotope's A2T benchmark more than 0.2%, up
to 0.69% (Dynamic's ==.units over small strided Unboxed arrays).
The other rises are a trade against allocating the SCCs hotter first
among those that can be allocated, as an earlier form of this commit
did: nofib's scs takes 1.8% more at -O2 and -O1, 1.3% with the SCCs
hotter first, fasta 1.5% more at -O1 and cacheprof 0.24% more at -O2,
neither rising with them, containers' intset fromList:asc:sparse:fusion
0.94% more at -O2, not moving with them, and megaparsec's scientific
1.26% to 1.41% more at -O1 and 1.09% to 1.57% at -O2, 0.10% to 0.43%
and 0.64% to 1.19% with them, and the compiler runs 0.28% more
instructions compiling nofib's kahan at -O1, 0.08% with them.
But the SCCs hotter first give up what this order gains over them,
orthotope's A2T taking 0.163% fewer instructions rather than 0.410%
and vector's benchmarks at -O2 0.070% fewer rather than 0.354%, and make
megaparsec's choice take 1.2% more at -O1.
Two other uses of the estimate, which the Note's bullets name,
were refuted. Taking at wideMoveDests the destination of the hottest
of the blocks that give a vreg one moved containers' benchmarks both
ways, 17 rising and 16 falling at -O1 and 49 and 71 at -O2
(intersection-mix 2.5% fewer instructions, symmetricDifference-common
1.35% more), 0.007% and 0.081% fewer in all. Counting a write
in regClobbers only where its block's estimate is at least half
that of the block allocating the vreg made containers' benchmarks take
0.108% more instructions at -O1 (85 rising, 59 falling) and 0.170% more
at -O2 (92 and 30), and the compiler allocate 14% to 17% more compiling
CmmDiamondChain.
The estimate and the order are the compile cost: the stage-1 compiler
allocates at most 0.042% more at -O0 (T9961) and 0.058% more at -O
and -O2 (T783 at -O) compiling perf/compiler's T3294, T12707, T783
and T9961, and runs up to 0.33% more instructions (T783 at -O);
compiling MR 16269's CmmDiamondChain at -O1 and -O2 it runs 0.57% more
instructions and allocates 0.063% more; compiling nofib's programs
at -O1 and -O2 it runs 0.155% and 0.169% more instructions
by the geometric mean, up to 0.83% more (puzzle at -O2), and allocates
0.050% and 0.058% more. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 17% more (10.78 against 9.23 GB).
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
ba6a6330
by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Propagate wide move destinations back, preferring the target's register
The last preference of "Prefer the register a later block moves a vreg
into where it dies", a vreg's wide destination, now reaches back along
moves: wideMoveDests also gives a vreg moved where it dies, in a warm
block, into a vreg that has a wide destination, that destination, up
to four moves back, and the walk of the blocks checks it as it checks
the others. A vreg given a destination so first takes the first-used
register of the vreg it is moved into, the claims test skipped,
as that vreg, dead, still claims its register: given the destination
itself, a closure moved into a join's vreg took the register that vreg
is moved into later, not the one it has at the join, and every path
into the join ended in a move (containers' map fromListWith-asc, 1.26%
more at -O1). Note [Register preferences in the linear allocator] says
that this preference, the fourth, is not counted where the fallback
leaves out, for a vreg with preferences, the free registers that one
of the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded,
gives any vreg: noPrefs does not count it. Where a procedure has
no candidate the propagation returns at once, and it shares its list
of moves with the walk. The commit also keeps wideMoveDests
from inlining until the last simplifier phase (NOINLINE [0]),
and linearRegAlloc' flattens a procedure's SCCs into one list, once,
for wideMoveDests and the three other walks over the blocks. Inlined,
wideMoveDests had its local bindings floated out as thunks built
for every procedure, so that the stage-2 compiler, built by the series'
stage-1 compiler, allocated 0.14% more than the parent's compiling
perf/compiler's T9961 at -O0. The pragma alone made the stage-1
compiler, built by GHC 9.12.4, allocate up to 0.107% more than without
it in ten of the fifteen compile cells below, as without it the CSE
of GHC 9.12.4 had shared one flattened list among the four walks, which
flattening once now does by design.
In containers' tree PostOrder foldl'_sum a loop's carry is now computed
in R2's %r14, where the recursive call takes it, rather than in another
register moved there and back. Measured on x86-64 against its parent,
in instructions: vector's maximumOn takes 15.4% fewer, containers' tree
PostOrder folds 0.77% to 4.4% fewer, nofib's k-nucleotide 0.60% fewer
at -O2 and 0.48% at -O1, and clausify and digits-of-e2 0.31% to 0.39%
fewer at both.
The propagation is a trade, its toggle propagating along no move, which
reverts every gain with the rises: against its parent, map
fromDescListWithKey takes 0.33% more at -O1, a move every fourth element
where the step entered after each descLinkTop or ascLinkTop swaps
the stack and its left subtree. Megaparsec's reachOffsetNoLine-0 rows,
which the toggle reverts too, take 0.65% more at -O1 against the parent.
A propagated destination yields to a vreg directly destined
for that register and born while the propagated one is live only where
the estimate of "Add an estimate of block frequencies for the linear
allocator" runs that vreg's own move into the register more often
than the move ending the propagated chain, the walk of the blocks
then also taking the blocks that write such a vreg: this takes back
the rows of map fromAscList and fromDescList at -O2, 0.36% of their
0.39% more, and keeps maximumOn's gain and the fused rows.
fromDescListWithKey's -O1 rise stays the trade, the estimate rating
its loop exit above its in-loop tail call. Against its parent,
the stage-1 compiler allocates less and runs fewer instructions in every
compile cell (perf/compiler's T3294, T12707, T783 and T9961 and MR
16269's CmmDiamondChain, each at -O0, -O1 and -O2), by more than 0.01%
and 0.005% in most and by up to 0.173% and 0.086%, compiling T3294
at -O0; the stage-2 compiler allocates 0.20% less compiling T9961 at -O0
(394109104 against 394903232 bytes), and less in every cell under +RTS
-A3G -V0. The code generated is the same with and without the pragma
and the flattening, every object built for the measurements being
identical but for symbol names derived from uniques in orthotope's A2T
benchmark, so the run-time figures above stand.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
1aeb784b
by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Give a vreg the register a recorded join holds it in
Where a register is free for a vreg but the first register
that the assignments the block's jumps lead to, a recorded jump target's
or that of a block up to three jumps past a target not yet recorded
(rc_jumpLocs), give the vreg is another one, held by a vreg
that no instruction left in the block reads and that one
of those assignments has in its slot and none in a register,
allocRegsAndSpill_spill now spills the holder, a store the way there
would need anyway and none where the holder is in its slot already,
and gives the vreg its register in place of the free one. The test uses
the position of each instruction in its block and the block's last reads
of the vregs live out of it, built where the test consults them.
joinToTargets' now reads the registers live into each block
from the allocator's context (rc_live), so that master's linearRA,
raInsn, genRaInsn, joinToTargets and joinToTargets_again no longer pass
them on.
Measured on x86-64 against its parent, in instructions: megaparsec's
manyTill benchmarks take 0.074% to 0.14% fewer at -O2, and nofib's
puzzle 0.26% fewer at -O2 and 0.70% fewer at -O1, no benchmark taking
more. The stage-1 compiler allocates 0.081% to 0.12% more compiling
at -O0.
Assisted-by: Claude Opus 5.5
-
bcca6ae7
by Mikolaj Konarski at 2026-11-20T00:13:14+01:00
Spill a vreg its block reads no more
Of the vregs in both a register and their slot, else of those
in a register only, allocRegsAndSpill_spill evicts the first
that no instruction left in the block reads, else the first, except
that a vreg live into a jump target with no recorded assignment
that another block jumps to as well counts as read again where neither
the block nor that target is in a cycle. Evicted, such a vreg would
be in its slot in the assignment the block records for the join,
so that every later jump there would store it and the code after
the join reload it: in megaparsec's someTill the cold paths of a UTF-8
decoder, allocated before the hot one, so cost a store and a reload
an element. Where the block or that target is in a loop, as a loop's
head is, the eviction stands: there it keeps a register free
for the loop. The victim is sought in one fold over the assignment,
and only where a vreg of the evicted register class is live out
of the block, the previous choice standing elsewhere; the map of last
reads is built only where it is consulted, and a procedure's joins
outside cycles once, where building a block's last reads first consults
them.
Before that choice, the previous commit's rule applies where no register
is free as well: where the first register that the assignments
in rc_jumpLocs, a recorded jump target's or that of a block up to three
jumps past a target not yet recorded, give the vreg has a holder
that no instruction left in the block reads, and one
of those assignments has the holder in its slot and none in a register,
the holder goes to its slot here rather than on the way to that block,
and the vreg takes its register. The test runs only where a vreg
of the class is live out of the block, as such a holder is, and where
an assignment it could consult is recorded. With it at the end
of an earlier form of the series, against that end, nofib's puzzle
at -O2, containers' bcc.star and megaparsec's scientific benchmarks take
fewer instructions, no benchmark of nofib, containers or megaparsec
taking more beyond its noise, and the compiler's allocation
and instructions barely rise in each compilation measured.
Each of allocRegsAndSpill_spill's evictions now goes through one local
function, ahead, which spills a vreg in a register only by spillR
and recordSpill and ends in evicted, which updates the assignment, loads
the vreg if need be and allocates the rest: the previous commit's rule
takes it, and so does the victim, in place of master's two cases
of eviction and their own copies of that code, the assignment of a vreg
in both a register and its slot now set before the load rather
than after, neither reading what the other writes. The fold keeps
the highest rank so far with the first vreg of that rank (Victim),
a trade against keeping a candidate of each kind: measured on an earlier
form of the series, the compiler ran 0.0185% more instructions compiling
ManyBasicBlocks.cmm at -O0, 0.0225% more at -O1 and 0.0246% more at -O2,
allocating 0.025% to 0.029% less, and compiling T3294 0.021% fewer
at -O0 and 0.009% to 0.010% fewer at -O and -O2, allocating 0.32% less
at -O0, the assembly the same.
Master's anyUFM and allUFM, in GHC.Types.Unique.FM, now walk the map
by Foldable's any and all; liveOutClass tests a live-out set
by uniqSetAny.
Measured on x86-64 against its parent, in instructions, besides the rows
above: vector's awshcc takes 4.7% fewer at -O2, tridiag 1.7%
and quickhull 1.0%, containers' IntSet and IntMap union
and symmetricDifference benchmarks fall at -O2, and nofib's dom-lt takes
0.73% fewer at -O2 and 0.72% at -O1 and scs 0.45% at both, no benchmark
of those suites taking more beyond its noise. With the previous commit
the stage-1 compiler allocates 0.73% less compiling perf/compiler's
T3294 at -O0, and compiling MR 16269's CmmDiamondChain it runs 0.45%
to 0.55% more instructions and allocates 0.28% to 0.36% more, part
of them this commit's set of a procedure's joins outside cycles.
In orthotope's A2T benchmark, against the previous commit, the rule
is a trade: ==, /=, compare and < over large Storable arrays take 6.1%
to 7.1% more instructions, in a nest whose block before the inner loop,
needing a register for the loop's index, evicts the loop's bound, which
it reads no more, so that the loop reloads the bound at every trip; max
over large strided Unboxed arrays takes 13% fewer, and < over large
scaled and zipWith3A over large scalar Unboxed arrays gain alike.
Leaving the rule out reverts both. Counting such a vreg as read again
where a hotter block reads it, and storing it before a jump
into a hotter block or a loop that does not read it, with or without
a test of the loop's register pressure, each took back the rise but lost
elsewhere.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
eb44b362
by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Copy small loop heads over the jumps to them after block layout
Block layout lets one edge into a loop head fall through and makes
the others jump: the loop's entry once a run, every other back edge once
an iteration. copyLoopHeads, a new NcgImpl method that x86-64 implements
in GHC.CmmToAsm.X86.CodeGen and that cmmNativeGen runs under the chain
layout, after sequenceTop and before invertCondBranches, copies a loop
head of at most eight instructions and a conditional branch
over the jumps to it that the layout left: a block whose one successor
is the head, and which still ends in a jump to it, ends in the head's
instructions instead and goes straight on to whichever of the head's
successors its branch picks, the copy's last jump dropped where
its target is placed next, as dropJumps drops a jump. A copy
into the loop's entry saves the jump into the loop; a copy into a back
edge's source rotates the loop for that edge. Note [Copying loop heads];
Note [CFG based code layout] lists the new step.
A loop head is a target of a back edge that optimizeCFG now returns
with the weights: one of static prediction's loops (mkGlobalWeightsWith
returns loopInfo's back edges too), or, where static prediction does
not run, one of findBackEdges', which optHsPatterns raises.
copyLoopHeads looks only at the jumps to the back edges' targets,
and cmmNativeGen runs it only in a procedure with back edges. Where
static prediction runs, optimizeCFG also returns those of findBackEdges'
back edges that are none of the loops' and not into the entry, which
only an irreducible region has and calcFreqs finds; cmmNativeGen reads
them only for the layout's search below. The layout runs on the CFG
it has under -fno-asm-copy-loop-heads, so the block it lets fall through
into a head takes no copy, and no path through a copy executes more
instructions than through the jump it replaces. A copy's edges
in the CFG are the head's, unscaled: after layout only
invertCondBranches reads them. A block that follows a failed heap
or stack check takes no copy. Under -g a head's leading unwind
annotations are passed over, and left out of its copies, and a head
is copied only into a block whose unwinding rules at its jump
are the head's for each register whose rule both state, each side's
annotations folded into the rules in force after them, a later
annotation winning register by register: the one that follows a C call's
DELTA names MachSp alone, leaving the block's rule for Sp in force,
so that a block that calls C and does not move Sp afterwards takes
the copy under -g as without it. Where the block states no rule
for a register, as a fixup block of register allocation states none
at all, the copy runs under the rules DWARF has in force at the block's
own code, those of the code before it in the final layout, which can
differ from the head's own. BUG: after a C call those rules are wrong
already, master's addDefaultUnwindings (GHC.CmmToAsm.Dwarf) completing
every table that does not name Sp with the rule Sp has
at the procedure's entry, so that the rest of the block's code, a copy
at its end included, is unwound by that rule; Note [Copying loop heads]
says so, and master's compiler prints such rows too. The tests
CopyLoopHeadsCall and CopyLoopHeadsCallG count the head's comparison,
three times, in a loop whose jumps to the head each follow a C call,
without -g and with it; with the annotations compared whole, the second
found it once. Measured at the series' end against that comparison,
nofib's assembly without -g is the same at -O1 and -O2, and under -g
it changes in ben-raytrace's Sampler and in fannkuch-redux at both
levels.
Where the layout placed neither of the head's successors after a block
that takes a copy, the copy ends in a conditional jump and a jump.
pullRuns then moves to after the copy the run of blocks that one
of the two successors starts, the head's likelier successor tried first,
where no block falls into the run: the copy then falls into it,
or invertCondBranches makes it do so. No path loses a fall-through,
as neither the copy, nor the block before the run, nor the run's last
block fell into the block after it. The run that moves is not the first,
which holds the entry, nor one that starts with an info table, nor one
after which the copy's own run has already moved. A run moves only
if the last instruction of its last block transfers control
unconditionally, the test by which endsRun ends a run, so that pullRuns
does not rest on the code generator ending every block in such
a transfer; a TODO says that the test can go if that is made binding,
verifyBasicBlock checking, in a DEBUG compiler, only that no other
instruction follows a jump. A run also ends at a copy that ends
in a conditional jump and a jump where the block placed next has an info
table, which nothing falls into or past (fallsTo), as the continuation
that returns into a loop's head where its code is the head's: an info
table, no code, and the fall into the head. No fall-through is lost,
block layout keeping the jump into a block with an info table
and invertCondBranches dropping none into one. Taken to run on
into the head's run, a copy in the block placed before such
a continuation, as in the loop's entry, kept its conditional jump
and its jump where the copy made before layout fell into the loop's
exit: measured at the series' end on a program that builds a star graph
of 10000 vertices with Data.Graph's buildG and forces it 200 times,
as containers' benchmark buildG.star does, whose rnf of a list, entered
once an array element, has that shape, the program ran 177,686,901
instructions with the copying before layout, 179,686,689 with no run
ended there, one more an element, and 177,686,902 with it at -O2,
and 176,021,604, 178,021,322 and 176,022,116 at -O1. Every procedure
of nofib whose assembly that end of a run changes, at -O1 and -O2, holds
fewer instructions, most of them one fewer. A block that holds only meta
instructions, as one whose jump the layout dropped holds its unwinding
information under -g, counts as holding no code for the copy's last jump
and for the runs, so that the copies and the moves do not depend on -g.
pullRuns finds the first run of the chain of moved runs that a deciding
run ends in a map from each such chain's last run to its first, kept
with the map back by one insertion in each at a move: walking up
the chain run by run instead, measured at the series' end on a harness
calling copyLoopHeads on loops in sequence whose moves chain through
them, it ran 103.5e9 instructions at 16000 loops where it runs 4.0e9,
growing 3.5 to 4.1 times at each doubling where it grows 2.1 to 2.2
times.
Where no run moves, the copy still ends in a conditional jump
and a jump, neither to the block placed next, as the head has them:
in nofib's real/parser the copy of pgAlts's test in the loop's entry
ended in je exit; jmp body, the je never taken. Where the head's branch
says nothing of its likely side (cml_likely), which invertCondBranches
goes by, and the head's edge to the last jump's target weighs
over a tenth more than its other edge, the two jumps swap (orient),
so that the likelier path executes one jump, unless the conditional
jump's target has an info table (below). The margin leaves out the pairs
that static prediction weighs equal, which only a tie-break tells apart:
optimizeCFG's favourFewerPreds tilts the two edges of an evaluatedness
test toward the successor with fewer predecessors (as in nofib's
queens), and with the pair oriented by any difference in weight, queens
ran 0.5% more instructions at -O1, and grep, fibheaps and mate 0.2%
more, than with the copying before layout. TODO: the margin of a tenth
is arbitrary and should be generalised.
orient leaves a copy as it is where its conditional jump's target has
an info table: optHsPatterns' penalizeInfoTables lowers the weight
of an edge into such a block, since no block falls into it, and static
prediction starts each branch from the weights so lowered, so
that the lighter weight of that edge states no likelihood. A head
that tests whether a closure is evaluated and goes straight
to the continuation that the evaluation returns to has such an edge
on its evaluated side: in lookupGE4_fMin of containers' benchmark
lookupge-intmap that edge weighs less than the other, and with the jumps
swapped the copy in the procedure's entry jumps conditionally
to the code that enters the closure, the evaluated path paying the jump.
Where the last jump's target has an info table and its edge still weighs
over a tenth more, the swap stands. Measured at the series' end against
swapping those copies too, lookupge-intmap's GE Milan far runs one
instruction fewer a call of lookupGE4_fMin, hartel/sched 0.167%
and 0.174% fewer at -O1 and -O2, and hartel/parstof 0.058% fewer at -O1,
which was not traced. In nofib's assembly the rule undoes only the swaps
of copies that test a pointer's tag bits, and every procedure it changes
holds as many instructions, so that a program runs more where its paths
through those copies more often enter the closure than find
it evaluated: paraffins runs 0.0053% and 0.0043% more instructions
at -O1 and -O2 than with the copying before layout, hartel/transform
0.0070% and 0.0060% more and anna 0.0079% more at -O2, a cause deduced
from the code and not traced.
Where optimizeCFG returns no back edge, the blocks the entry reaches
hold no cycle that avoids it, and the chain layout's own search for back
edges could find only edges into the entry, which it raises none of,
raising a back edge only above another edge into its head
that is neither a back edge nor a self loop: an edge into the entry
from a block the entry reaches is one or the other, and the CFG holds
no other, getCfg taking only the blocks the entry reaches (ISSUE 28088).
So it now skips that search: cmmNativeGen hands the fact to master's
sequenceTop, which hands it to master's sequenceChain, each gaining
a Bool argument. This is a trade, measured against this commit with only
the skip reverted: compiling T9961 at -O0 the compiler runs 0.0070% more
instructions and allocates 0.0060% more, the cost of carrying one more
value through cmmNativeGen, mapM's loop and sequenceTop; against that,
compiling T783 it runs 0.141% fewer instructions and allocates 0.148%
less at -O and 0.132% and 0.138% at -O2, T12707 0.080% and 0.088% at -O
and 0.070% and 0.079% at -O2, and T3294 0.012% and 0.010% at -O
and 0.012% and 0.011% at -O2, the assembly the same.
The flag -fasm-copy-loop-heads, on at -O1 and -O2 as -fblock-layout-cfg
is, lets the copying be turned off; the tests CopyLoopHeads
and CopyLoopHeadsOff check both settings.
cmmNativeGen now passes Linear.regAlloc the estimate of block
frequencies rooted at the graph's g_entry, the first native block
on x86-64, in place of the function of an entry that regAlloc applied
to the procedure's first block.
In master's cmmNativeGen, optimizedCFG is now bound strictly, together
with the layout's flag and the copying step, from optimizeCFG's result
by one chain of tests before maybeDumpCfg, and branchOpt cases
on the copying step: where it runs, invertCondBranches is mapped
over the copied blocks with the CFG holding the copies' edges. invert
takes that CFG, and branchOpt's local invertConds is deleted. The step
is bound strictly, as a function of the blocks as layout placed them,
so that where it does not run it is a static Nothing: with the copies
and their CFG bound strictly instead, the compiler ran 0.029% more
instructions and allocated 0.040% more compiling T9961 at -O0, where
nothing is copied, and with them bound in branchOpt's where, 0.023%
and 0.027% more. With the step's own tests made after sequenceTop, every
decl, a data decl too, ran them after maybeDumpCfg's return, reloading
from the stack the variables cmmNativeGen holds in registers there:
by callgrind, compiling T9961 at -O, cmmNativeGen ran 53 instructions
more a decl, and the compiler ran 0.010% and 0.011% more instructions
compiling T9961 at -O and -O2 than with the copying before layout.
optimizeCFG returns the CFG and its two lists of back edges evaluated,
as master's cmmNativeGen forced the CFG that optimizeCFG returned there:
left lazy, the CFG made the compiler allocate 0.048% more compiling
T9961 at -O0 and 0.019% more at -O. Master's binding config = ncgConfig
ncgImpl, at the top of cmmNativeGen, gains a bang: left lazy, config
is a thunk that the code generator's state holds and that every read
of the config, the platform or the weights enters, an indirection after
its first evaluation; measured on master, the bang alone makes
the compiler run 0.143% fewer instructions compiling T9961 at -O0,
0.155% fewer compiling T3294 and 0.106% fewer compiling T12707 there,
the assembly the same (under +RTS -A3G -V0, where these compiles collect
nothing; under GHC's own RTS options the gain compiling T9961 at -O0
is about half). Below that binding, the chain's settings,
-fblock-layout-cfg, -fasm-copy-loop-heads and whether the backend
maintains the CFG, are read from config once a decl and bound strictly
as one Int, which the chain's two guards test: with config bound
strictly and the settings read in those guards instead, the compiler ran
0.012% more instructions compiling T9961 at -O0, and 0.002% and 0.003%
more at -O and -O2. Step 11 of the overview at the top of GHC.CmmToAsm
names the copying, and the README in compiler/GHC/CmmToAsm names Note
[Copying loop heads] for step 11 and, among the flags to switch off,
-fno-asm-copy-loop-heads before -fno-block-layout-cfg, which stops
the copying too.
Measured against the parent commit, in instructions, with no benchmark
of the battery rising by more than its noise: at -O2 nofib's programs
take 0.24% fewer (fannkuch-redux 2.1%, knights 1.3%, eff/CSD 1.1%,
digits-of-e1 1.0%), containers' benchmarks 0.51% fewer (intmap
lookup_half 7.2%, lookup_most 5.7%, lookup_hits 5.6%, intset member
3.4%, nubInt issue1202_repeat 3.3%), megaparsec's 0.35% fewer (string'
1.1% to 1.2%, skipManyTill 1.1%) and vector's 1.3% fewer
(nextPermutation 5.3%, nextPermutationBijective 4.1% to 4.8%, hybcc
0.97%); at -O1 nofib's 0.22% fewer (fannkuch-redux 1.9%), containers'
0.58%, megaparsec's 0.35% (reachOffsetNoLine 1.6%, reachOffset 0.92%
to 1.3%) and vector's 1.1% (leaffix 0.62%, awshcc 0.61%); at -O0, where
it does not run, nofib's 0.15% fewer, through the libraries' code.
This takes back some of the trades of the commit that lets a loop's back
edge outrank its entry: IntSet's difference and intersection benchmarks
take 0.85% to 0.87% fewer instructions than at the parent at -O2
and -O1, nubInt's noFusion_repeat 2.4% fewer, megaparsec's reachOffset
at -O1 0.92% to 1.3% fewer; and vector's awshcc at -O1, whose loop's two
back edges both jumped, executes fewer jumps a call, those of one
of those back edges among them. Code grows: nofib's objects' text
by 0.66% at -O2 and 0.54% at -O1, the stage-2 compiler's by 0.75%.
The stage-1 compiler runs 0.0196% and 0.0158% more instructions
and allocates 0.0200% and 0.0214% less compiling perf/compiler's T9961
at -O and -O2, as measured on this commit with config forced by the Int
alone, the bang unwritten (TODO: the rise is the work the copying does
a procedure; by callgrind at -O on this commit without the Int
and the bang, where the rise was 0.0222%, deciding on and running
the copying, in cmmNativeGen, copyLoopHeads and invertCondBranches
over the copies, makes 0.015% of the instructions, testing its three
settings, kept live in cmmNativeGen across register allocation, 0.0073%,
and the skip's test 0.0017%, against 0.0017% fewer from the rest
of the change; this commit's rise is not split so), allocates 0.045%
and 0.13% less for T12707 and T783 at -O, for skipping the chain
layout's search for back edges (above), and 0.045% and 0.010% more
with that search kept, and the stage-2 compiler 0.11% and 0.14% more
for nofib's puzzle and reptile at -O2, its code generator working
on the copies.
Against the form of this change that copied loop heads before layout,
measured at the series' end with both stage-1 compilers over the same
libraries, in instructions, the lowest of three rounds: nofib's programs
take 0.009% fewer in total at -O1 and 0.025% fewer at -O2, dom-lt 0.43%
and 0.47% fewer, last-piece 0.32% and 0.35% fewer and hartel/sched 0.17%
and 0.18% fewer at -O1 and -O2, and mkhprog 0.53% and infer 0.34% fewer
at -O2; parser runs within 0.002% of its counts there; and no program
takes 0.05% more. Compiling T9961 at -O and -O2, where its assembly
differs, the compiler runs 0.003% and 0.002% more instructions,
allocating 0.009% and 0.004% less. Measured at an earlier form
of the series' end, it ran 0.041% and 0.034% fewer instructions
compiling ManyBasicBlocks.cmm at -O1 and -O2, 0.013% fewer compiling
T9961 at -O0, allocating 0.021% less, and 0.010% fewer compiling T12707
there.
Measured on the battery with the copying after layout but before orient,
against the form before layout: containers' nubInt and nubOrd
noFusion_repeat rows ran one instruction more an element, 2.0% to 2.8%
more at -O2 and -O1, vector's small next/prevPermutation rows 1.97% more
at -O2, and the stage-2 compiler 0.047% and 0.041% more instructions
compiling T3294 at -O and -O2, in a loop of GHC.Cmm.Sink entered
from a copy of its head's test left ending in a conditional jump
and a jump, as containers' nubIntOn's is. On programs that hold
those rows' code, compiled at the series' end with orient switched off
and on, orient takes the nubInt and nubOrd repeat rows from 1.9%
and 1.7% more than the form before layout to 0.002% more,
and the Permutation rows from one instruction more a call to 14,463
fewer over 3 x 9! calls; Sink's loop, read and not run, then has
the entry path of the form before layout and one jump more on an entry
that leaves at once.
Measured on the battery at the series' end against the form before
layout, containers' Set and Map fromDistinctAscList:fusion benchmarks
run 0.59% and 0.73% more instructions at -O2 and 0.60% and 0.73% more
at -O1, one jump more every two elements, with no copy involved:
in their fused loop a block that joins three paths back to the loop's
test has, by static prediction, its heaviest edge from the block
that runs when the stack is empty, which block layout lets fall through,
as it does under -fno-asm-copy-loop-heads. Before, the entry's copy,
made ahead of layout, gave the loop two entries, findBackEdges' search
took the two other edges into that block for back edges,
and preferBackEdges raised them: a gain by the search's order,
not by the weights. containers' bcc.line,n=100 runs 0.12% more at -O1,
one jump more a vertex, and, measured on a build of the benchmark's
module, about six instructions a vertex fewer than without the copies:
a copy there ends in a conditional jump and a jump, each of whose
targets another block falls into, so that pullRuns moves neither, where
the copy made before layout had taken one of the two falls. A2T's cells
run a few instructions a call more or fewer, under 1%, about as many
cells each way; that orient's choices on predictions near a coin flip
account for them is inferred, not traced.
The bound of eight instructions, measured on the form that copied loop
heads before layout: at four, nubInt's issue1202_repeat keeps a third
of its gain; at six, nofib's x2n1 runs 0.86% more instructions at -O2
and at -O1, in the loops of (^), whose heads hold eight. Against six,
eight trades code size for run time: no program runs more instructions
or allocates more by 0.2%, and nofib's objects grow by 0.01% in total
at -O2 and 0.03% at -O1, x2n1's by 3.1%. A bound of ten gained no more,
its objects larger; nor did heads of up to 64 copied only over a jump
weighted at least a sixteenth for each instruction beyond six, their
objects larger too. Not taken: a block ending in a conditional branch
and a jump to the head copying it too, which moved nothing in nofib;
and a second pass, its back edges found again by findBackEdges, which
cost CmmDiamondChain 0.5% more compile allocation.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
-
3461f01e
by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Use one estimator of block frequencies for the layout and the allocator
Static prediction made the layout's estimate by mkGlobalWeights
over LabelMaps: loopInfo's dominators and loops,
staticBranchPrediction's probabilities, normalised
by cfgEdgeProbabilities, and calcFreqs' fixpoint; blockFrequencies made
the linear allocator's in two arrays by the same rules. Both are now
made by one estimator, freqEstimate, the allocator's array code, which
returns the probabilities and the back edges too, on two CFGs:
staticPredCfg calls it on the CFG shortcutting leaves,
and blockFrequencies on the CFG as instruction selection gives it;
and loopInfo, LoopInfo, mkGlobalWeights, mkGlobalWeightsWith,
staticBranchPrediction, cfgEdgeProbabilities, calcFreqs and CFG's
revPostorderFrom are deleted, with the commented-out traces naming them.
The graph allocator's spill costs no longer scale the counts of uses
and definitions by block frequencies, which nothing reads: chooseSpill
takes the lifetimes alone, and pprSpillCostRecord, the one function
that names the counts, has no caller. Each use and definition counts 1,
as where no CFG was passed, and master's slurpSpillCostInfo, regAlloc
and regAlloc_spin lose their CFG argument, cmmNativeGen no longer
passing livenessCfg.
Where a loop head has back edges from blocks it dominates
and from blocks it does not, its loop is now the dominated ones',
as loopInfo's was, where blockFrequencies left the head out;
and a loop's levels count the blocks reached from its warm back edges,
as staticBranchPrediction counted them, where blockFrequencies counted
the whole loop. calcFreqs' irreducible skip stays for the layout: given
True, as staticPredCfg gives it, freqEstimate skips a block entered
by a back edge from a block it does not dominate, which then runs once
each time a loop holding it, or the procedure, runs where it heads
a loop, and else never; given False, as blockFrequencies gives it,
it sums the block's inflow as before. A branch's weights are made
probabilities once, before the rules apply, where both estimators made
them so again after the rules, so that the rules' probabilities
are rounded once; this moves blocks in a few of nofib's objects at -O1
and -O2, their instruction counts the same.
ohPredicts, static prediction's rule that a comparison with a literal
comes out unequal, which "Add an estimate of block frequencies
for the linear allocator" moved out of master's staticBranchPrediction,
read which side of a two-way branch an edge is on off the label
the branch was made with (s1 == ltrue), as master's did. The edge
no longer ends at that label once a fixup block of the register
allocator (addNodesBetween) or a shortcut (shortcutWeightMap) has moved
it: where the moved true edge's new target had the smaller label
of the two, the layout's estimate took the likely side for the unlikely
one. The fault is master's; it costs only speed, on x86-64
under -fcmm-static-pred. The BUG statement at ohPredicts that says
so is deleted. getCfg now records the side on the edge: master's
BranchInfo gets the constructors NoInfoTrue and HeapStackCheckTrue
for the edge made for a CmmCondBranch's true target, isTrueSide reads
them, ohPredicts goes by it, and predictBranch loses the label
it compared. An edge keeps its EdgeInfo wherever it is moved,
so the side stays that of the branch; a branch whose two targets are one
block has one edge, recorded as the true side. Master's CmmSource's
trans_info becomes strict and master's getCfg evaluates a branch's info
where it makes the edges, so that the two sides' sources replace the one
source and its thunk; master's isHeapOrStackCheck matches both check
constructors; and master's invertCondBranches (GHC.CmmToAsm.X86.CodeGen)
compares the two edges' Cmm nodes where it compared their
TransitionSources, which now differ between a branch's sides,
and accepts what it accepted, the info being a function of the node.
The test StaticPredShortcut in testsuite/tests/cmm/should_compile has
a true edge that -fasm-shortcutting moves to a block whose label
is smaller than the false target's, and checks on x86-64 that the false
target's code comes before the true target's in the assembly, as it does
without -fasm-shortcutting; with the side read off the label, the layout
put the true target's first.
Measured against its parent. Compiling, the stage-1 compiler runs 8.04%
and 8.02% fewer instructions and allocates 9.0% and 8.9% less on MR
16269's CmmDiamondChain at -O1 and -O2, 2.8% and 2.6% fewer instructions
on T783 at -O and -O2, 2.5% and 2.3% on T12707, 0.72% and 0.69% on T3294
and 0.054% and 0.068% on T9961, and moves by 0.026% or less at -O0;
the stage-2 compiler runs 2.4% and 3.4% fewer instructions on nofib's
puzzle at -O1 and -O2 and, over nofib's modules, 1.3% and 1.5% fewer
instructions and 2.0% and 2.1% less allocation at -O1 and -O2 (geometric
means).
The generated code is the same at -O0; at -O1 and -O2, a few of nofib's
objects differ, the estimates differing by rounding only but
for the allocator's of one procedure in spectral/para at -O2, which
moves by the rule above, and for the branches whose side a stale label
inverted; no nofib program moves by 0.2% in instructions or allocation,
and at -O1 and -O2 containers' benchmarks move by 0.046% at most,
megaparsec's by none past 0.05%, and vector's by 0.028% at most.
Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way
branch's probability moves but by rounding, or where a stale label
inverted it, and the back edges are the same as the old estimator's,
and the layout's frequencies differ from its by rounding only,
or by such a branch.
Measured at the series' end against it without the recorded side,
with stage-1 compilers over the same libraries: an instrumented pair
traced every branch ohPredicts predicts in nofib's modules and every
move of an edge, and replaying the moves, the recorded side
is the branch's on every edge with a stale label at -O1 and -O2,
and equal to the old reading on every other; the old reading
was inverted nowhere at -O1, and at -O2 in real/fluid,
shootout/k-nucleotide, spectral/hartel, imaginary/bernouilli
and shootout/n-body. nofib's assembly is the same at -O1 and differs
at -O2 in modules of those programs but n-body. Of their executed
instructions (five interleaved rounds, the lowest) none rises beyond
its spread, spectral/hartel/ida's fall by 0.0025%,
and shootout/k-nucleotide's lowest is 0.012% lower, within the spread
of the rounds with the recorded side. Compiling T3294, T12707, T783
and T9961 at -O0, -O and -O2 and ManyBasicBlocks.cmm at -O0, -O1
and -O2, the compiler runs no more instructions in any cell
and allocates at most 0.006% more (T783 at -O0); with the side
as a third field of CmmSource instead, it allocated up to 0.026% more.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
cd45ff8f
by Mikolaj Konarski at 2026-11-20T00:13:15+01:00
Count irreducible regions in layout frequencies and duplicate small runs
The layout's estimate skipped, as calcFreqs did, every block entered
by a back edge from a block it does not dominate: such a block ran once
each time a loop holding it, or the procedure, ran where it headed
a loop, and else never, whatever flowed into it. freqEstimate now sums
its inflow as for any other block, as the allocator's estimate does,
and loses its Bool argument.
Counting the region's blocks changes the layout of orthotope's
$wabsAxesAndStartT: the small block that returns, which more than one
copy of the loop's head wants, is no longer placed after the back edge's
source that the loop's path takes, so the copying moves it after
the first copy in placement order that wants it, the entry's,
and the loop's path through its own copy jumps to it, one jump more
a call. So a copy left ending in a jump to a small run that another copy
took now ends in a duplicate of that run instead: at most eight
instructions, the bound of a copied head, and a jump, with no info
table, call or label, the condition inverted where the run
is the conditional jump's target. Under -g the duplicate drops
the unwinding information ahead of the run's first instruction,
as a copy drops a head's, and is made only where the copying block's
rules at its end agree with the run's for each register both state;
a run holding such information after an instruction, as one whose code
adjusts Sp does, is not duplicated.
Measured against its parent without the duplication, here and
in the next paragraph. Compiling, the stage-1 compiler runs 0.012% fewer
instructions on MR 16269's CmmDiamondChain at -O1 and -O2, and within
0.0025% elsewhere.
At -O1 and -O2, some of nofib's objects differ. nofib's mkhprog at -O2
and eliza and megaparsec's many and skipMany at -O1, which this change
moved on earlier forms of the series, move by 0.06% or less; containers'
benchmarks move by 0.041% at most, vector's by none past 0.05%.
Over containers at -O1 and -O2 and nofib at -O1 and -O2, no two-way
branch's probability moves and the back edges stay the same;
the frequencies differ from the parent's in some procedures
of containers' and of nofib's at -O1 and -O2.
Measured against this commit without the duplication, in instructions:
orthotope's A2T benchmark takes 0.068% fewer by the geometric mean, 114
cells fewer by more than 0.2% and none more; megaparsec's benchmarks
0.065% fewer at -O1, 13 falling and none rising, and at -O2 none rises
or falls; at -O2 seven of containers' benchmarks fall and none rises;
vector's move by none past 0.05%; and no nofib program runs more
instructions or allocates more by 0.2%. No compile cell moves past 0.01%
in allocation or 0.005% in instructions, and their assembly is the same.
The duplicates trade code size for run time: nofib's objects grow
by 0.137% in total at -O2, 24 programs' by more than 0.2%
(fannkuch-redux 1.58%, pidigits 1.47%, primetest 1.25%), and by 0.083%
at -O1, 18 programs' by more than 0.2% (pidigits 1.30%, puzzle 1.13%);
in nofib's assembly every block the duplication changes has a jump
replaced by its target's code.
Assisted-by: Claude Opus 5.5
-
9656b83b
by Mikolaj Konarski at 2026-11-20T00:13:16+01:00
Walk liveness first over instructions as the code generator gives them
natCmmTopToLive wrapped every instruction as LiveInstr (Instr i)
Nothing, in a list of its own, which the first liveness walk dropped
at once for a LiveInstr carrying the liveness. Now natCmmTopToLive
returns the procedure's SCCs of NatBasicBlocks, and the walk takes
an accessor giving each element's InstrSR: Instr on the first walk,
a LiveInstr's own when the graph allocator walks again. regLivenessOf
is INLINE and livenessSCCs is a wrapper around a local loop, so
that the first walk's copy for x86 has the accessor constant
in its loops over the SCCs: as a plain recursive function, specialised
to x86 with the accessor an argument, it made the compiler run 0.046%
more instructions and allocate 0.056% more compiling CmmDiamondChain
at -O0. livenessBlock takes the accessor as an argument: INLINE, it made
the compiler run 0.05% more instructions compiling T3294 at -O0.
livenessBack is a wrapper around a local loop too, which does not pass
the accessor, the platform and the block map again at each instruction.
sccBlocks, master's, now returns beside the SCCs a map of each block's
jump targets, the lists its graph's nodes carry, and LiveInfo, master's,
carries the map in a fifth field, matched with one field more at each
of its sites: Liveness.hs's, Linear.regAlloc's, and the graph
allocator's in Spill.hs, SpillClean.hs and SpillCost.hs, which pass
it through or ignore it. livenessCyclic takes a block's predecessors
in the SCC from the map and linearRegAlloc' its context's rc_succs,
where each walked every instruction of the SCC or of the procedure
(jumpSuccs, deleted): the compiler runs fewer instructions compiling
T9961 at -O0 and allocates less compiling CmmDiamondChain at -O0.
The liveness pass is pure: master's cmmTopLiveness and regLiveness,
and regLivenessOf, return the declaration itself, where they returned
it in UniqDSM without drawing a unique, and Liveness no longer imports
GHC.Types.Unique.DSM. cmmNativeGen maps the pass over the procedures
by strictMap and gives the allocators usGen, the supply the pass
returned untouched, and the graph allocator binds the code it walks
again by let and map. Master's livenessSCCs and livenessBack no longer
take the starting values of their accumulators, which their one caller
gave as empty.
Measured with stage-1 compilers against the parent commit on x86-64:
the assembly of perf/compiler's T3294, T12707, T783 and T9961 at -O0, -O
and -O2 and of MR 16269's CmmDiamondChain at -O0, -O1 and -O2
is byte-identical, and so is that of T3294 and T9961 at -O
under -fregs-graph and -fregs-iterative. The stage-1 compiler allocates
1.76% less compiling T3294 at -O0, 1.55% less for T9961, 1.17%
for T12707 and 1.01% for T783, 0.051% to 0.57% less at -O and -O2,
and 0.63% to 0.72% less for CmmDiamondChain, and runs 0.057% to 1.05%
fewer instructions, counted with an allocation area larger than all
a compilation allocates.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
-
ff5b0a1d
by Mikolaj Konarski at 2026-11-20T00:13:16+01:00
Lower master's NCG helpers' compile cost and drop needless blocks
mapWeights in GHC.CmmToAsm.CFG rebuilt the CFG by a fold over the list
of its edges, inserting each edge again by addEdge with its new weight.
It now maps over the CFG's nested maps, which keep their shape.
adjustEdgeWeight and setEdgeWeight looked the edge up and inserted
it again by addEdge. They now adjust the edge in place by mapAdjust,
setEdgeWeight by adjustEdgeWeight.
optHsPatterns' favourFewerPreds counted the predecessors that could fall
through into a block in a reversed copy of the CFG filtered
to those edges, taking the length of the block's list of successor edges
there, for both targets of each conditional branch of equal weights.
It now counts them for every block by one fold over the CFG into a map,
and skips a branch whose two targets have equal counts, whose weights
the adjustment by zero left as they were. Master's alternative
of its local modifiers for equal counts, which adjusted both edges
by zero, is deleted, unreachable under the skip.
sequenceChain in GHC.CmmToAsm.BlockLayout built a set of the blocks
its chains placed and filtered every block of the procedure against it,
for a list of unplaced blocks that is empty unless the layout has
a fault. The set and the filter now run only where the chains' list
of blocks is not as long as the procedure's map of blocks. Where
the lengths are equal and a block is unplaced, the list names a block
twice or one not in the map, which fails later, in the assembler
or in getBlock, with the unplaced blocks appended or without;
the assertion that every block is placed stays.
In the same module, buildChains' fuseChain took the fused chain's first
block as the head of takeL 1 and its last as the head of takeR 1, each
building a list out of the chain's OrdList: fromOL walks the chain's
left spine and fromOLReverse its right one, allocating as they go.
It now takes them by headOL and lastOL, which give the same block
and build no list. The two agree on every chain buildChains builds: each
is made by chainFromList of two blocks, chainSingleton, chainSnoc,
chainCons and chainConcat, the last three on non-empty chains,
so no part of a chain is an empty list, and headOL and lastOL panic only
on a list with an empty part; a test of the OrdList module over every
chain those build up to depth three, and over long spines of each kind,
found no difference. Measured at the series' end against it without
this change, nofib's assembly at -O1 and -O2 and the compile cells'
are the same, no cell runs 0.005% more instructions or allocates 0.01%
more, and ManyBasicBlocks compiles with 0.025% and 0.027% fewer
instructions and 0.116% less allocation at -O1 and -O2; the diamonds
scaling probe allocates 0.4%, 0.9% and 2.0% less at N = 100, 200
and 400, the bytes saved growing as N squared. On the parent of "Copy
small loop heads over the jumps to them after block layout", where
deadchain's chains fuse in fuseChain, the change also lowers deadchain's
allocation by 2.4% at N = 400.
combineNeighbourhood's applyEdges took the first and last blocks of each
chain it fused by getFronts and getEnds of the new chain, and the parts'
other ends by getFronts c1 and getEnds c2. getEnds is takeR, the first
two of fromOLReverse, which walks the chain's OrdList down its right
spine, allocating as it goes, until it meets the last blocks; getFronts
walks the left spine alike. Where chains fuse one after another
onto the front of one chain, its right spine grows by one at each
fusion, and the walks cost a quadratic in the fusions. FrontierMap's
entries now hold both of a chain's ends, computed once a chain
as before, and a fused chain's are taken from its parts': its first
blocks are the first of c1's and then of c2's, its last the last of c2's
and then of c1's. Those are the same lists in the same order, as fromOL
and fromOLReverse of an appOL are those of its parts appended: a test
of the OrdList module found them equal for every pair of lists
its functions build up to depth two, and for long spines of each kind.
One entry now serves both maps. The code is master's but for one line,
applyEdges' result, which "List a CFG's edges once in block layout"
wrote. Measured at the series' end against it without this change,
nofib's assembly at -O1 and -O2 and the compile cells' are the same,
no cell runs 0.005% more instructions or allocates 0.01% more, T3294
compiles with 0.107% and 0.103% less allocation at -O and -O2 and T12707
with 0.043% and 0.040% less; the deadchain scaling probe at -O1
allocates 2.4%, 4.8% and 9.2% less at N = 200, 400 and 800 and runs
0.7%, 1.6% and 3.4% fewer instructions, the probes allocs and calls
allocate 0.2% to 0.5% less from N = 100 to 400, chain and nest 0.1%
to 0.3% less, and every probe's assembly is the same. On the parent
of "Copy small loop heads over the jumps to them after block layout"
the change lowers the allocation of T3294, T12707, allocs, calls, chain
and nest as here, the walks costing there already, and moves deadchain's
by 32 bytes: the quadratic on deadchain entered at that commit.
shortcutBranches in GHC.CmmToAsm applied the mapping of the blocks
it cut to every procedure even where it cut none. Where the mapping
is empty it now returns the procedures as they are.
shortcutBranches' build_mapping shorted only a block of exactly one
instruction, a jump. Under -g a block that holds only its jump also
holds the location and unwinding information that -g adds, so
it was kept, and static prediction and layout saw another CFG
than without -g. Under -g on ELF targets a block whose instructions
are meta instructions and then one jump is now shorted as a lone jump
is; elsewhere the test is master's. That information covered only
the jump, and the debug block of a label that is gone is dropped
by cmmDebugLink as it was for a shorted block. The BUG statement
at build_mapping now names the targets where the block is still kept,
those where ncgDwarfUnwindings does not hold, Windows among them.
x86's genCondBranch passed genCondBranch' whether the platform
is 32-bit, which genCondBranch' did not read; genCondBranch' is now
genCondBranch's body, and Note [CFG Edge Weights] in GHC.CmmToAsm.CFG
names genCondBranch as the place that adds 3 to the weight
of a floating-point comparison's false edge.
tryToInline in GHC.Cmm.Sink inlined a trivial assignment that is live
after the node into the node, rebuilding and folding the node, even
where the node does not mention the assignment's register. Such
an assignment is now kept with the node left as it is. Where it does
inline and keep an assignment, it passes on the counts of the registers
the node uses with the right-hand side's added, as it does where
it inlines and discards one, so that a register an earlier kept inlining
brought into the node is counted.
sccBlocks in GHC.CmmToAsm.Reg.Liveness listed a block's jump targets
by `concatMap jumpDestsOfInstr`. On x86 the block of a floating-point
comparison that tests for an unordered result ends in jumps that name
one target twice, so the list held that target twice. It now leaves out
the single target of a jump that repeats one of the first two distinct
such targets of the block, and lists a jump table's targets as before;
the list keeps every target, in the order of its first jump.
Master's raInsn in GHC.CmmToAsm.Reg.Linear kept, in a block comment,
a trace of the move it eliminates that names r_dying and w_dying, which
are not in scope there, so that the trace would not compile if enabled;
it is deleted, and the comment above it, which said that a fixed source
register is allocatable, as otherwise it would not be in r_dying, names
liveDieRead, the set in which the move's guard looks the register up.
joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets takes a jump's
destinations once, and a jump table lists a target once for each entry
naming it. Where such a target needed a fixup block, its first entry
made one and the jump was patched to send every entry naming the target
there; each later entry then made the same moves again, into a block
nothing jumps to, which was given an edge in the CFG, laid out
and emitted. Once joinToTargets_again has made the fixup block, it now
drops the target's later occurrences from the destinations still
to consider. The BUG statement there is deleted. The test JumpTableFixup
in testsuite/tests/cmm/should_compile compiles a jump table that names
such a target in three entries and checks that the linear allocator
records one fixup block, on x86-64.
In GHC.CmmToAsm.Reg.Graph.SpillCost, under the comment's statement
of Chaitin's formula, which weights each use and def by its block's
frequency, a sentence now says that slurpSpillCostInfo counts every use
and def once, whatever the frequency of its block.
GHC.CmmToAsm.Reg.Linear.Base's ReadingOrWriting, which no code used
and the module did not export, is deleted, and so is the module's
LambdaCase pragma, which no code of the module uses.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5