[Git][ghc/ghc][wip/T27981-ncg-mystery-box] 42 commits: Prefer the register a vreg is moved into where it dies
Mikolaj Konarski pushed to branch wip/T27981-ncg-mystery-box at Glasgow Haskell Compiler / GHC Commits: 83134fcd by Mikolaj Konarski at 2026-11-23T17:39:57+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 take 0.26% fewer at -O2 and -O1 and 0.72% fewer at -O0 (wave4main 2.2% at -O2 and -O1, clausify 2.4% at -O0), none as much as 0.2% more; vector's benchmarks 0.27% and 0.19% fewer at -O2 and -O1 (next- and prevPermutationBijective 1.4% and 1.0%), none as much as 0.05% more; containers' 0.40% and 0.35% fewer (tree Foldable.elem.bin 4.1% at both) and megaparsec's 0.49% and 0.51% fewer (skipSomeTill 1.3% and endBy1 1.2% at -O2), none as much as 0.1% more beyond their noise. In orthotope's A2T benchmark, compiled at -O1, the 36818 cells take 0.55% fewer by the geometric mean, 23172 of them fewer by 0.2% or more (Shaped's convertE.g over large strided boxed arrays 5.0%) and 8 more. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.097% more compiling perf/compiler's T12707 at -O0, 0.18% more compiling T783 and 0.075% more compiling T9961, and 0.032% less compiling T3294; at -O and -O2, and compiling MR 16269's CmmDiamondChain at any level, its allocation moves by 0.025% or less. The stage-2 compiler allocates 0.007%, 0.007% and 0.049% 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 5.1% more (2.562 against 2.438 GB) and GHC.CmmToAsm.Reg.Linear.State 4.7% more. The 8 rising cells of A2T are all over large arrays: Dynamic's sequenceA over dense boxed arrays takes 2.9% more (642632 instructions a call, of 22.1 million), Ranked's mapA over broadcast Storable arrays 0.35% more (11 instructions a call, of 3207), and six others 0.20% to 0.27% more (58 to 82 instructions a call, of 29 to 30 thousand): Shaped's toVector over windowed Storable arrays, Ranked's and Shaped's update and Ranked's normalize over windowed Unboxed arrays, and Shaped's force over runs of Unboxed elements and force.narrow over dense Unboxed arrays. Counting a tenth of the cells again by the same compiler, at master and at the series' end, moved 6 to 20 of about 3680 by more than 0.2% and at most one by more than 1%, and two counts by one compiler differed by 12% in one large cell, so one count does not tell these 8 rises from the count's spread. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - 055b9cf0 by Mikolaj Konarski at 2026-11-23T17:39:57+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.27% 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 or benchmark of vector's moves by more than its noise; containers' benchmarks take 0.010% fewer at -O2 (intset mapMonotonic 1.3%) and 0.001% more at -O1, and megaparsec's 0.004% fewer at -O2 and 0.007% fewer at -O1 (hexadecimal.4000 0.12% at both, reachOffsetNoLine 0.13% at -O1), none as much as 0.1% more beyond their noise. In orthotope's A2T benchmark, compiled at -O1, the 36818 cells take 0.31% fewer by the geometric mean, 7532 of them fewer by 0.2% or more (Dynamic's anyA over large scaled boxed arrays 9.7%) and 46 more. No benchmark's allocation changes beyond nofib's run-to-run noise. The stage-1 compiler allocates 0.34%, 0.57% and 0.51% more compiling perf/compiler's T12707, T783 and T9961 at -O0, 0.16% and 0.20% more compiling T12707 and T783 at -O and 0.14% and 0.19% more at -O2, and 0.40%, 0.32% and 0.32% more compiling MR 16269's CmmDiamondChain at -O0, -O1 and -O2, and 0.042% less compiling T3294 at -O0; the stage-2 compiler allocates 0.095%, 0.098% and 0.235% 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). This commit is a trade in orthotope's A2T benchmark. Of its 46 rising cells, 32 are Shaped's, plain and summed: maximumA.one over small and large strided Unboxed and boxed arrays takes three instructions a call more (0.87% to 1.06%), and minimumA and maximumA over small dense, flip and strided Unboxed and boxed arrays 1.9 to 2.1 more (0.26% to 0.36%). In six of them, maximumA.one over small strided arrays and minimumA and maximumA over small dense ones, not summed, the look-ahead past a target not yet reached, to the recorded assignments of the blocks it jumps to, 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. On an earlier form of the series, measured on A2T's sample alone, leaving that look-ahead out put these six cells back at the parent commit's counts or below, but its gains went: Ranked's convertE over small dense boxed arrays took 3.1% more and Shaped's ==.rank1 over small dense Unboxed arrays 1.4% more, and the 384 cells that form improved gave back 190.8 of the 5218.3 instructions a call they gained. A fix would need block frequencies before register allocation. The other 14 rising cells are over large arrays, 5 Ranked's and 9 Shaped's: Ranked's ravel, summed over strided boxed arrays, takes 4.1% more (971716 instructions a call, of 23.9 million), Ranked's window over runs of boxed elements 1.35% more, and the other 12 0.22% to 0.51% more (66 to 163 instructions a call, of 28 to 57 thousand). Counting a tenth of the cells again by the same compiler, at master and at the series' end, moved 6 to 20 of about 3680 by more than 0.2% and at most one by more than 1%, and two counts by one compiler differed by 12% in one large cell, so one count does not tell these 14 rises from the count's spread. Figures of variants not taken were measured on earlier forms of the series. Assisted-by: Claude Opus 5.5 - - - - - e4c2979b by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - c4fa0a3a by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - ee0ccb2b by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - b2c7d053 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - bd404186 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 4b7a0185 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 6a5d4086 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 19a474aa by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 60aafe21 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - ed505aa2 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 1450733e by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - e575a226 by Mikolaj Konarski at 2026-11-23T17:39:57+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 - - - - - 9eab723a by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - f929dce0 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 9043161d by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - df73e20a by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 75e976e7 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - cbaa9e3c by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - e883ac0b by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 879b5692 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 0c67b084 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - d0afa091 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 5673c43f by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 980ced82 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 49c398dd by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - af9fcee5 by Mikolaj Konarski at 2026-11-23T17:39:58+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 - - - - - 84491538 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 81e321f2 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 75123fe4 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 9be7addb by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 9df9a615 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 4b02a1c6 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - a7e9a547 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 3f883cf2 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 83db9a81 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 33bfc17a by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 25d6b29f by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - c154625f by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - b3b165ba by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 6b8479b2 by Mikolaj Konarski at 2026-11-23T17:39:59+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 - - - - - 115 changed files: - compiler/GHC/Cmm.hs - compiler/GHC/Cmm/Config.hs - compiler/GHC/Cmm/ContFlowOpt.hs - compiler/GHC/Cmm/Graph.hs - compiler/GHC/Cmm/Info/Build.hs - compiler/GHC/Cmm/LayoutStack.hs - compiler/GHC/Cmm/Lint.hs - compiler/GHC/Cmm/Liveness.hs - compiler/GHC/Cmm/Pipeline.hs - compiler/GHC/Cmm/ProcPoint.hs - compiler/GHC/Cmm/Sink.hs - compiler/GHC/Cmm/UniqueRenamer.hs - compiler/GHC/CmmToAsm.hs - compiler/GHC/CmmToAsm/AArch64.hs - compiler/GHC/CmmToAsm/BlockLayout.hs - compiler/GHC/CmmToAsm/CFG.hs - compiler/GHC/CmmToAsm/Config.hs - compiler/GHC/CmmToAsm/Instr.hs - compiler/GHC/CmmToAsm/LA64.hs - compiler/GHC/CmmToAsm/Monad.hs - compiler/GHC/CmmToAsm/PPC.hs - compiler/GHC/CmmToAsm/README.md - compiler/GHC/CmmToAsm/RV64.hs - compiler/GHC/CmmToAsm/Reg/Graph.hs - compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillClean.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs - compiler/GHC/CmmToAsm/Reg/Linear.hs - compiler/GHC/CmmToAsm/Reg/Linear/Base.hs - compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs - compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs - compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs - compiler/GHC/CmmToAsm/Reg/Linear/State.hs - compiler/GHC/CmmToAsm/Reg/Liveness.hs - compiler/GHC/CmmToAsm/X86.hs - compiler/GHC/CmmToAsm/X86/CodeGen.hs - compiler/GHC/CmmToAsm/X86/Instr.hs - compiler/GHC/Data/Word64Map/Internal.hs - compiler/GHC/Data/Word64Map/Lazy.hs - compiler/GHC/Data/Word64Map/Strict.hs - compiler/GHC/Data/Word64Map/Strict/Internal.hs - compiler/GHC/Driver/Config/Cmm.hs - compiler/GHC/Driver/Config/CmmToAsm.hs - compiler/GHC/Driver/Config/StgToCmm.hs - compiler/GHC/Driver/DynFlags.hs - compiler/GHC/Driver/Flags.hs - compiler/GHC/Driver/Main/Compile.hs - compiler/GHC/Driver/Session.hs - compiler/GHC/StgToCmm/Bind.hs - compiler/GHC/StgToCmm/Config.hs - compiler/GHC/StgToCmm/DataCon.hs - compiler/GHC/StgToCmm/Monad.hs - compiler/GHC/StgToCmm/Utils.hs - compiler/GHC/Types/Unique/FM.hs - compiler/GHC/Types/Unique/Set.hs - docs/users_guide/using-optimisation.rst - rts/include/Cmm.h - + testsuite/tests/cmm/should_compile/JumpTableFixup.cmm - + testsuite/tests/cmm/should_compile/StaticPredShortcut.cmm - + testsuite/tests/cmm/should_compile/StaticPredShortcut.stderr - + testsuite/tests/cmm/should_compile/T27800.cmm - + testsuite/tests/cmm/should_compile/T27980.cmm - + testsuite/tests/cmm/should_compile/T8327.cmm - testsuite/tests/cmm/should_compile/all.T - testsuite/tests/cmm/should_run/all.T - + testsuite/tests/cmm/should_run/cmm_refetch_reassign.hs - + testsuite/tests/cmm/should_run/cmm_refetch_reassign.stdout - + testsuite/tests/cmm/should_run/cmm_refetch_reassign_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_refetch_store.hs - + testsuite/tests/cmm/should_run/cmm_refetch_store.stdout - + testsuite/tests/cmm/should_run/cmm_refetch_store_cmm.cmm - + testsuite/tests/cmm/should_run/cmm_reserved_seed.hs - + testsuite/tests/cmm/should_run/cmm_reserved_seed.stdout - + testsuite/tests/cmm/should_run/cmm_reserved_seed_cmm.cmm - + testsuite/tests/codeGen/should_compile/CopyLoopHeads.hs - + testsuite/tests/codeGen/should_compile/CopyLoopHeads.stderr - + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCall.hs - + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCall.stderr - + testsuite/tests/codeGen/should_compile/CopyLoopHeadsCallG.stderr - + testsuite/tests/codeGen/should_compile/CopyLoopHeadsOff.stderr - + testsuite/tests/codeGen/should_compile/StackLayoutCallLoop.hs - + testsuite/tests/codeGen/should_compile/StackLayoutTagLoop.hs - + testsuite/tests/codeGen/should_compile/StackLayoutTagLoop.stderr - + testsuite/tests/codeGen/should_compile/T20333.hs - + testsuite/tests/codeGen/should_compile/T20333.stderr - + testsuite/tests/codeGen/should_compile/T20333b.hs - + testsuite/tests/codeGen/should_compile/T20333b.stderr - + testsuite/tests/codeGen/should_compile/T20333c.hs - + testsuite/tests/codeGen/should_compile/T20333c.stderr - + testsuite/tests/codeGen/should_compile/T20334.hs - + testsuite/tests/codeGen/should_compile/T20334.stderr - + testsuite/tests/codeGen/should_compile/T27991.hs - testsuite/tests/codeGen/should_compile/all.T - testsuite/tests/codeGen/should_gen_asm/T24813.asm - testsuite/tests/codeGen/should_gen_asm/bytearray-memcpy-unroll.asm - testsuite/tests/codeGen/should_gen_asm/bytearray-memset-unroll.asm - + testsuite/tests/regalloc/T27800_itm.cmm - + testsuite/tests/regalloc/T27981.hs - testsuite/tests/regalloc/all.T - + testsuite/tests/simd/should_run/T27638.hs - + testsuite/tests/simd/should_run/T27638.stdout - + testsuite/tests/simd/should_run/T27638a.hs - + testsuite/tests/simd/should_run/T27638a.stdout - + testsuite/tests/simd/should_run/T27638b.hs - + testsuite/tests/simd/should_run/T27638b.stdout - + testsuite/tests/simd/should_run/T27638c.hs - + testsuite/tests/simd/should_run/T27638c.stdout - + testsuite/tests/simd/should_run/T27638d.hs - + testsuite/tests/simd/should_run/T27638d.stdout - + testsuite/tests/simd/should_run/T27638e.hs - + testsuite/tests/simd/should_run/T27638f.hs - + testsuite/tests/simd/should_run/T27638f.stdout - + testsuite/tests/simd/should_run/T27638g.hs - + testsuite/tests/simd/should_run/T27638g.stdout - testsuite/tests/simd/should_run/all.T The diff was not included because it is too large. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ff5b0a1dcd12da02650cd6a7b487da8... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/ff5b0a1dcd12da02650cd6a7b487da8... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Mikolaj Konarski (@Mikolaj)