[Git][ghc/ghc][wip/T27981-ncg-mystery-box] 72 commits: Fix stale and false comments in the NCG
by Mikolaj Konarski (@Mikolaj) 26 Nov '26
by Mikolaj Konarski (@Mikolaj) 26 Nov '26
26 Nov '26
Mikolaj Konarski pushed to branch wip/T27981-ncg-mystery-box at Glasgow Haskell Compiler / GHC
Commits:
1c2ce844 by Mikolaj Konarski at 2026-11-26T23:24:08+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- The comment on NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad,
placed Note [Unwinding information in the NCG] in that module.
The Note is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists, and which labels each converts. Two comments
further down named MachCodeGen. One named it as calling
cmmMakeDynamicReference for static data, which the instruction
selectors do for some labels, such as those of floating point literals
on i386 and PowerPC. The other named it as calling the initialization
of the PIC base register for every procedure that accessed it, which
cmmTopCodeGen does on i386 and on 32-bit PowerPC but not AIX. They now
say so. The first also said that cmmToCmm calls
cmmMakeDynamicReference for every CmmLabel in the Cmm code, where
it does so only in procedures' code, and the second
that the initialization adds its instructions to the top
of the procedure, where on ELF it also adds them to the top of each
block with an info table. They now say that too.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted. Its TODO, to make arch
specific versions of RegAlloc.Graph.TrivColorable, named a module now
called GHC.CmmToAsm.Reg.Graph.TrivColorable, and dates from 2009, when
that module chose its counts of registers by the host's architecture.
trivColorable now takes the target platform, by which it chooses each
architecture's count, and the squeeze functions of the target's Regs
module, which this module's targetVirtualRegSqueeze
and targetRealRegSqueeze choose. The TODO is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout placed
optimizeCFG right after instruction selection. cmmNativeGen runs it,
where it keeps the CFG (x86-64, not under -finfo-table-map), after
register allocation and shortcutting. The Note presented the next two
steps, loopInfo's loop analysis and mkGlobalWeights' refinement
of the edge weights, as unconditional. optimizeCFG takes them only
under -fcmm-static-pred, which -O implies, and the Note now says so.
The Note said that the refined weights are normalized relative
to the most often visited node. They are relative to the entry node,
to which calcFreqs gives frequency 1.
- The haddock of the Ord instance of CfgEdge, in GHC.CmmToAsm.CFG, said
that edges are sorted ascending pointwise by weight, source
and destination. The instance orders them lexicographically,
and "pointwise" is deleted.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG said
that its author knew of a jump target that is an immediate value only
without tables next to code. With tables next to code a tail call's
jump to a label has one, which x86's canShortcut accepts,
and the sentence is deleted.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight. On x86-64 the instruction selector adds 3 to the false side
of a floating-point comparison, and, where the weights stay equal,
as they do not after that 3, optHsPatterns' favourFewerPreds may
weight one side above the other by their predecessors. It said
that calls are ignored completely; the layout leaves a call's edge out
while it builds chains and while it combines neighbouring chains,
and divides its weight by 64 when it merges the chains.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout said
that edges constituted by a call are ignored. The layout ignores them
while it builds the chains and while it combines neighbouring chains,
and counts a 64th of their weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics. staticBranchPrediction applies three, ohPredicts being
the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said that back
edges are found by BFS. findBackEdges finds them by a depth-first
search (classifyEdges in GHC.Data.Graph.Directed).
- A comment in the Instruction class said that regUsageOfInstr
is to state precisely the registers an instruction reads and writes.
x86's regUsageOfInstr returns them as the register allocators
are to use them. The comment now says so, with examples of where
that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and, up to bit 127, a load
at FF32 or FF64. Others keep it, such as a MOV between registers
at FF32 or FF64, printed movss or movsd, and an 8-bit or 16-bit MOV
into a general register. The comment now also says that the usage
of the other MOV instructions has a register destination written,
not read. The comment at the MOVD arm said that MOVD and MOVQ always
zero any remaining upper part of the destination. The legacy forms GHC
prints zero it only up to bit 127, keeping bits 128 and above of a ymm
register, and the comment now says up to bit 127.
- Comments in GHC.CmmToAsm.Reg.Liveness, in both register allocators
and at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In GHC.CmmToAsm.Reg.Liveness
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides. At the Ord instances, each now
says that the order compares uniques and so is deterministic
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies. The sentence is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block. Any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. process stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register. A block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint. The one in a round that spills also said
that the graph is then validated, which it is not: nothing evaluates
the validated graph that round stores, and that comment is deleted.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
Its allocateReg took the set first and its getFreeRegs classed
registers by regClass, which GHC does not have; both now follow
the instances (the register first, targetClassOfRealReg). It made
releasing a free register and allocating an allocated one no-ops
and now says that the AArch64, RISC-V and LoongArch instances panic
there.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones. What holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that all the cycle's
source registers are spilled. handleComponent spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
the fixup code breaks register cycles through a stack slot
in $w$s$wequalT1 and in $w$s$w$ccompare1. The sentence is deleted.
- A comment at expandNode's case for a move from InBoth to InMem,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that the source's slot
is guaranteed to be the destination's. They can differ where
the virtual register has more than one slot, and the value
is then stored from its register. The comment now says that the guard
fails only there.
- A comment in GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal
proc labels] in GHC.Cmm.Label, across two lines. The Note
is in GHC.Cmm.CLabel, and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. getFreeRegs starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone. It numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- A comment in the stmtToInstrs of each of X86, AArch64, LA64 and RV64
said that the condition of a conditional branch can be assumed likely
false, because GHC.Cmm.ContFlowOpt arranges for the likely side
to fall through. ContFlowOpt also inverts a condition whatever
its likelihood where the condition can be inverted, the true target
has one predecessor and the false target more than one,
so the condition may be likely true. None of the four genCondBranch
functions uses the likelihood.
- A comment in mkCmmIfThenElse', in GHC.StgToCmm.Monad, said
that the NCG does not know about likely annotations. The PowerPC code
generator has printed them as branch hints since 2017. Since 2018
getCfg has weighted the CFG's edges by them, and on x86-64 without
-finfo-table-map the block layout (not under -fblock-layout-weightless
without -fblock-layout-cfg) and the order of some conditional
branches' jumps (invertCondBranches) follow these weights.
The comment's clause on a fallthrough is replaced by what the swap
does: where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- A comment at makeImportsDoc, in GHC.CmmToAsm, put a hack
for .subsections_via_symbols in PprMach.pprNatCmmDecl. A comment above
initializePicBase_x86, in GHC.CmmToAsm.PIC, cited PprMach.hs for how
FETCHGOT is printed. No module PprMach is left. The first comment now
cites the printers' pprNatCmmDecl and Note [Subsections Via Symbols]
in GHC.CmmToAsm.X86.Ppr, and the second cites GHC.CmmToAsm.X86.Ppr.
- A comment in raInsn, in GHC.CmmToAsm.Reg.Linear, said that a real
source register must be allocatable, since it would otherwise
not be in r_dying, a name raInsn does not have. The guard looks
the register up in liveDieRead, which the comment now names.
- A comment in genRaInsn, in GHC.CmmToAsm.Reg.Linear, said that using
nub on the registers read is no problem. The code uses nubOrdOn,
and the clause is deleted.
- The comment at initBlock's case for a block without an entry
assignment, in GHC.CmmToAsm.Reg.Linear, took the block to be part
of a loop that the allocator iterates over again. No block
is allocated twice. The case is reached by an entry block, or
by a block that no allocated jump reaches. The comment now says so,
and what the case does.
- The haddock of lookupFirstUsed, in GHC.CmmToAsm.Reg.Linear.Base, said
that it gives the register a virtual register was first assigned to.
lookupFirstUsed gives the variable's register in the first entry
assignment, in allocation order, that maps it to a register,
as findPrefRealReg's comment now says. The haddock now says so too.
- The haddock of minusCoveredRegs, in GHC.CmmToAsm.Reg.Regs, said
that it removes a register only where its format in the second
argument is at least as large as in the first. minusCoveredRegs
removes a register at a scalar format in the first whatever its format
in the second, and compares a vector format by Format's derived Ord;
the haddock now says so.
- The haddock of shrinkingRegs, in GHC.CmmToAsm.Reg.Regs, said
that it computes the registers in both arguments whose size is smaller
in the second. shrinkingRegs also keeps every register of the first
argument that is not in the second, and compares the formats
by Format's derived Ord; the haddock now says so.
- A comment in getAmode, in GHC.CmmToAsm.X86.CodeGen, said that a clause
turns lit1 << n + lit2 into lit2 + lit1 << n for the next clause.
The shifted operand is any expression. The clause is reached only
for a literal that the clause for x + lit does not take. The swapped
sum goes to the clause for x + (y << shift) or to the one for x + y.
The comment now says so.
- Note [Sinking and inlining] and the comment at shouldDiscard,
in GHC.Cmm.Sink, compared sinking's deletion of dead assignments
with removeDeadAssignments, which no longer exists. They now say only
that sinking does not delete every dead assignment, without master's
reason, that it would need multiple passes: no number of passes
deletes a local that only its own assignment in a loop reads,
or a dead store to a global register.
- The haddock of FrontierMap, in GHC.CmmToAsm.BlockLayout, said
that it maps the blocks near the end of a chain, and gave the front
blocks [A,B] of [A,B,C,D,E] as the end region. combineNeighbourhood
keeps one such map for the ends of the chains and one for their
fronts. The haddock now says so, with an entry of each.
- Note [When does an assignment conflict?], in GHC.Cmm.Sink, swapped
'A' and 'N' in its conditions (C1) and (C2). Its own (C1a) and (C1b),
and the labels in conflicts, have (C1) where N assigns to a register
A mentions, and (C2) where N reads the register A assigns.
The conditions now say so.
- The users' guide's entry of -fcmm-static-pred said that the prediction
is made on the final Cmm code and used by the register allocation
and code layout passes. The prediction is made only in the NCG
for x86-64, on the NCG's CFG after register allocation
and shortcutting. It is used, without -finfo-table-map, for the layout
(not under -fblock-layout-weightless without -fblock-layout-cfg)
and for the order of some conditional branches' jumps
(invertCondBranches). The entry now also says that the graph colouring
allocators (-fregs-graph, -fregs-iterative) choose what to spill
by live range length alone (chooseSpill, spillCost_length),
so that the flag does not change their allocation.
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written.
The sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
- The users' guide's entries of -fblock-layout-cfg
and -fblock-layout-weightless did not say that the flags act only
where the CFG is kept. sequenceTop uses the chain algorithm,
and the old algorithm uses the edge weights, only on x86-64
and without -finfo-table-map. Both entries now say so.
The -fblock-layout-cfg entry also said that the flag builds a control
flow graph, which cmmNativeGen builds whatever the flag says, and set
the chain algorithm against the last jump of each block, which the old
algorithm follows there only under -fblock-layout-weightless; it now
sets it against at most one edge per block.
The -fblock-layout-weightless entry said that without the flag the old
algorithm also uses the heaviest outgoing edge; it uses that edge
instead of the last jump, or none where that edge's weight
is not positive or the block has more than two successors.
- A comment above initializePicBase_x86, in GHC.CmmToAsm.PIC,
and the one on FETCHGOT, in GHC.CmmToAsm.X86.Instr, said that FETCHGOT
prints its last line as addl __GLOBAL_OFFSET_TABLE__+.-1b
and the register. GHC.CmmToAsm.X86.Ppr prints addl
$_GLOBAL_OFFSET_TABLE_+(.-1b), with one underscore at each end
of the symbol, and the comments now show that line.
- The short description of -fblock-layout-weightless in the users' guide
said that the flag ignores the CFG's weights for code layout. The flag
acts only on the old layout algorithm, as the entry's own text says,
and at -O, where -fblock-layout-cfg replaces that algorithm,
it changes nothing. The short description now names the old algorithm.
- Note [When does an assignment conflict?], in GHC.Cmm.Sink, said
that (C1) includes two situations, and lists three, (C1a) to (C1c).
It now says three.
- Note [Internal proc labels], in GHC.Cmm.CLabel, named the flag
-fexpose-all-symbols and said that it is enabled by default,
and the haddock of ppInternalProcLabel named Opt_ExposeAllSymbols.
The flag is -fexpose-internal-symbols, whose GeneralFlag
is Opt_ExposeInternalSymbols, and it is off by default. Both now say
so.
- The haddock of FrontierMap, in GHC.CmmToAsm.BlockLayout, said "cheaper
then" where it means "cheaper than", which it now says.
- Note [Sinking and inlining], in GHC.Cmm.Sink, said that an assignment
is cheap where its right-hand side is a local register. isTrivial,
which decides it, also accepts a literal, and a global register held
in a machine register or, on ARM, any global register. The Note now
says so.
- The users' guide's entries of -g and -fexpose-internal-symbols said
that -g2 implies -fexpose-internal-symbols. setDebugLevel,
in GHC.Driver.Session, sets the flag only above level 2, so -g3
implies it, and -g, which is level 2, does not. Both entries now say
level 3.
- A comment at CmmUnsafeForeignCall, in GHC.Cmm.Node, named
GHC.Platform.callerSaves, which GHC.Platform does not export.
The function is GHC.Platform.Regs.callerSaves, which the comment now
names.
- Note [Internal proc labels], in GHC.Cmm.CLabel, and the users' guide's
entry of -fexpose-internal-symbols said that the flag makes GHC
produce symbols for procedures internal to a module, and the haddock
of ppInternalProcLabel made the function's label conditional
on the flag. Only the code generator for x86 and x86-64 tests
the flag, in pprExposedInternalProcLabel, before it calls
ppInternalProcLabel, which tests none. The three now say so. The entry
also said that -fno-expose-internal-symbols suppresses all non-global
symbol table entries; it suppresses only the labels that the flag
adds, and the sentence is deleted.
- Note [Chain based CFG serialization], in GHC.CmmToAsm.BlockLayout,
said that the chains are built ignoring calls and edges into a block
prefixed by an info table, and its example of a block that ends up
in a chain of its own was reached by such a jump. sequenceChain
ignores only call edges there and keeps an edge into an info table's
block at an eighth of its weight. The Note now names only calls,
and its example reaches the block by a call.
- The comment on cmmMakeDynamicReference above ReferenceKind,
in GHC.CmmToAsm.PIC, said that a function for recording an imported
symbol must be passed in, addImportCmmOpt or addImportNat.
cmmMakeDynamicReference takes no such argument: it runs in an instance
of CmmMakeDynamicReferenceM, whose addImport is addImportCmmOpt
for CmmOptM and addImportNat for NatM. The comment now says so.
- The users' guide's chapter on debugging compiled programs gave -g's
levels as 0, 1 or 2 in the flag's short description,
and its walkthrough said that there are three levels, -g2 emitting
everything GHC knows, and that the GHC-specific annotations
are emitted with -g2. The entry accepts levels 0 to 3,
and the GHC-specific DWARF information needs -g3: ncgDwarfSourceNotes,
in GHC.Driver.Config.CmmToAsm, holds only above level 2. The three
places now name level 3.
- The users' guide's entry of -g said that only DWARF debug information
is supported on x86-64 and i386, and a tip of its chapter on debugging
compiled programs said how to extract the debug information on Mac OS
X with dsymutil. Only the native code generator emits DWARF,
and ncgDwarfEnabled, in GHC.Driver.Config.CmmToAsm, holds only for ELF
targets other than AArch64: Mac OS X gets none, and x86, x86-64,
64-bit PowerPC with the ELFv2 ABI, RISC-V and LoongArch get it,
with unwinding records that follow the Haskell stack pointer through
a procedure only on x86 and x86-64, where extractUnwindPoints returns
unwinding points. The entry now says so, and the tip is deleted.
- The haddock of mkGlobalWeights, Note [Static Branch Prediction]
and the comment above calcFreqs, in GHC.CmmToAsm.CFG, gave the title
of Wu and Larus's paper as "Static Branch Prediction and Program
Profile Analysis". The paper, at MICRO-27 in 1994, is "Static Branch
Frequency and Program Profile Analysis", which the three now give.
- The users' guide's chapter on debugging compiled programs said
that the debugging information does not affect the optimizations GHC
performs. Under -g the native code generator can keep a block
that holds only a jump, which -fasm-shortcutting removes without -g,
as in the testsuite's T5149_cmm.cmm at -O2 on x86-64: compiled
by a compiler of master's code, it jumps to g5149 directly without -g
and through a kept block with it. The sentence is deleted.
- Comments named modules and files by names that no longer exist,
or never did. The header of GHC.Platform.Reg named NCGMonad, now
GHC.CmmToAsm.Monad, which it now names. The header
of GHC.CmmToAsm.Format had a TODO, from 2009, saying that the module
is shared by all architectures because NCGMonad needs it to make
a virtual register, and that architecture specific formats would
be better, as SPARC does not use FF80. The SPARC code generator
and FF80 have since been removed, and since 2024 the register
allocators use Format too, for RegWithFormat; the TODO is deleted.
Note [GHC's data format representations], in the same module, named
Format.Format, now GHC.CmmToAsm.Format.Format. The header
of GHC.CmmToAsm.Reg.Graph.Base placed the hand written versions
of its functions in MachRegs*.hs, and the comment on its RegClass
placed the allocatable register classes in MachRegs.hs; the header
of GHC.CmmToAsm.Reg.Graph.X86 placed the reference in RegArchBase.hs
and trivColorable in MachRegs.hs; and the commented-out specification
in GHC.CmmToAsm.Reg.Graph.TrivColorable compared its worst
with RegArchX86. The comments now name the squeeze functions of each
architecture's Regs module, which trivColorable takes,
GHC.Platform.Reg.Class, GHC.CmmToAsm.Reg.Graph.Base,
GHC.CmmToAsm.Reg.Graph.TrivColorable and GHC.CmmToAsm.Reg.Graph.X86.
The comment on the PowerPC calling conventions
in GHC.CmmToAsm.PPC.CodeGen pointed to MachRegs.hs for the argument
and nonvolatile registers, and now points to GHC.CmmToAsm.PPC.Regs.
The haddock of PicBaseReg, in GHC.Cmm.Reg, named the module
PositionIndependentCode, and comments in the AArch64, RISC-V
and LoongArch instruction selectors named Cmm.CmmToAsm.PIC; both now
name GHC.CmmToAsm.PIC. A comment in GHC.CmmToAsm.Reg.Liveness named
Digraph, now GHC.Data.Graph.Directed. Comments in GHC.Cmm.CLabel
and GHC.Cmm.Sink named PprC, now GHC.CmmToC, and comments
in GHC.Cmm.DebugBlock and GHC.Cmm.Utils named CmmSink, and one
in compiler/CodeGen.Platform.h CmmSink.hs, now GHC.Cmm.Sink.
The comment on isTrivial's case for ARM, in GHC.Cmm.Sink, said
that CodeGen.Platform.ARM does not have globalRegMaybe. When the case
was added, in 2014, globalRegMaybe panicked on ARM; GHC.Platform.ARM's
globalRegMaybe does not, and the comment now says so. A comment
in GHC.Cmm.Parser said that OldCmm does not support a first class else
statement. OldCmm was removed in 2012, and the comment is deleted.
GHC.Cmm.Info named rts/include/rts/storage/InfoTable.h, and Note [No
static object resurrection], in GHC.Cmm.Info.Build, named smStorage.h;
the files are rts/include/rts/storage/InfoTables.h
and rts/sm/Storage.h.
Assisted-by: Claude Opus 5.5
- - - - -
a82d88cc by Mikolaj Konarski at 2026-11-26T23:24:09+01:00
Define the labels of the NCG's comments
Of what anyone working with the NCG needs, this commit serves "The kind
of each statement in the NCG's comments, shown at the statement: a bug,
half-done work, a likely change or code meant to stay.", "What a comment
that does not show the kind of its statements does and does not claim.",
"How the statements on bugs, half-done work and likely changes are kept
true as the code changes." and "Each known bug's tracker issue, named
at the code it concerns."
Comments only; the generated code is the same.
Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels
that comments added to the native code generator since then put
at the head of a statement. The commits that follow label each statement
they add, and are read under this Note:
BUG wrong behaviour, a missing check or misleading code;
the statement says in short what it leads to and,
where the code shows it, where it is reached
WIP half-done work
TODO what is likely to change, correct or buggy; a bug marked
TODO alone is accepted for now and worked around
BUG TODO both, where both are to be stressed
no label what is meant to stay, but a statement citing a labelled
one is of its kind; a kept trade-off says why
A BUG statement names its consequence: wrong code, wrong debugging
information, a panic or another failed compilation, assembly
the assembler rejects, only slower or larger code, only a warning
from the assembler, only more C stack space, or only a misled reader.
The Note does not reach back to older comments: their TODO, ToDo, FIXME
and XXX predate its meanings, and an older comment's lack of a label
makes no claim that the code is meant to stay.
The Note also says how the labels are kept true. A change to what
a labelled statement describes removes or rewrites the statement,
and each statement that cites it, in the same change; BUG, TODO and BUG
TODO gain the issue's number when the issue is filed; and a git grep
given in the Note lists the labelled lines.
Assisted-by: Claude Opus 5.5
- - - - -
81ba43fe by Mikolaj Konarski at 2026-11-26T23:24:10+01:00
Document bugs and TODOs in the NCG's CFG and block layout
Of what anyone working with the NCG needs, this commit serves "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached.", "Each known
bug's tracker issue, named at the code it concerns." and "Where the code
is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
TODO for what is likely to change, none for what is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- postRegCFG in GHC.CmmToAsm (BUG: X86's allocMoreStack retargets every
jump into an entry block to the block it adds after it,
but addImmediateSuccessor moves only the entry block's own edges).
The CFG keeps an edge into the entry block from each block that jumps
there, though the code now jumps to the added block, and lacks
those blocks' edges to the added block. This costs only speed.
It is reached on x86-64, the only target with a CFG after register
allocation, where ncgAllocMoreStack adds blocks, that is, where
allocation needs more spill slots than maxSpillSlots. This rests
on master's code read. The linear allocator's fixup blocks were added
to the CFG before postRegCFG, and the added block is reachable,
through the entry block's edge to it. No reader of the CFG after
postRegCFG panics on these edges: shortcutWeightMap has no lookup
that panics; optimizeCFG's lookups take their blocks and edges
from the CFG itself; sanityCheckCfg compares blocks only; sequenceTop
looks up only the blocks the CFG's edges name, all of them blocks
of the code; and invertCondBranches takes an edge's information
as a Maybe and leaves a jump without it alone.
- build_mapping in shortcutBranches, GHC.CmmToAsm (BUG: under -g a block
that holds only its jump can also hold the location and unwinding
information that -g adds, and is then kept where without -g
it is shorted). The code under -g jumps through the kept block,
and on x86-64 static prediction and block layout get another CFG
than without -g. This costs only speed and code size, under -g
and -fasm-shortcutting, on x86 and x86-64, not on Darwin. This rests
on master's code read: split matches a block of exactly one
instruction, and under -g on ELF targets other than AArch64
the instruction selectors put a LOCATION at the head of a block
with a source note, and under -g x86's gives a CmmUnwind an UNWIND,
neither of which emits code. On a development branch whose block
layout differed from master's, this changed the code of a probe
under -g.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG (BUG:
with tables next to code too, a block that is only a tail call's jump
to a label is shortcut away, and with it the edge A -> B). A's branch
has one target fewer in the CFG than in the code, and a loop whose
only exit was the lost edge has no exit in the CFG, so calcFreqs caps
its cycle probability. This costs only speed. It is reached on x86-64,
the only target with a CFG after register allocation,
under -fasm-shortcutting, not on Darwin, not under -finfo-table-map,
not for a jump through a symbol pointer, and under -g only
for a jump-only block to which -g adds nothing. This rests on master's
code read: the removed block ends in a tail call and has no edges out
in the CFG; it leaves the code and the CFG together, and no block
becomes unreachable; and the readers of the CFG after
shortcutWeightMap, listed above for postRegCFG, do not panic
on a missing edge.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG,
its BUG TODO (where a redirected edge A -> C coincides with an edge
A -> C already there, or with another redirected edge, only one
EdgeInfo is kept, chosen by the order of the fold over A's targets
in update_from_edge). The weights are not summed. This costs only
speed, on x86-64 under -fasm-shortcutting, not on Darwin,
not under -finfo-table-map, and under -g only for a jump-only block
to which -g adds nothing. This rests on master's code read and
on a run of master's compiler at -O0 -fasm-shortcutting, where
in the Cmm procedure f (W_ x, W_ y, W_ z) { W_ t; if (x > y) (likely:
True) { goto b; } else { goto c; } b: t = y; goto c; c: R1 = z + 1;
jump g [R1]; } the two edges into c become one with the weight of one
of them.
- getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only
the blocks reachable from the entry, while instruction selection still
covers the blocks that cmmToCmm makes unreachable when, after the Cmm
pipeline has removed the unreachable blocks, it turns a branch
on a constant into a jump). Where the selector splits such a block
in the CFG (addImmediateSuccessor), as X86's cmpxchg loop
for an atomic and, or, xor or nand does, the compiler panics
with "getSuccessorEdges: Block does not exist". This is reached on x86
and x86-64, at any optimisation level: cmmToCmm turns a branch
on a literal into a jump under every flag, and the literal comes
at -O0 from cmmToCmm's own constant folding and at -O from sinking's.
For x86-64 this rests on master's code read and on runs of master's
compiler under -dcmm-lint. A procedure whose if (1 != 0) leaves
a block with a fetch-and-and unreachable panics with that message
at -O0 and at -O, and also at both with -finfo-table-map added,
under which no CFG is kept after instruction selection, as on i386.
Where the branch tests a local set to 1 instead, the procedure panics
at -O and compiles at -O0. For i386 it rests on runs of a compiler
of master's code given an i386 target description through -B,
with -dcmm-lint, where f (bits32 p) { bits32 r; if (1 != 0) { return
(1); } (r) = prim %fetch_and32(p, 18::bits32); return (r); } panics
with that message at -O0 and at -O, with -finfo-table-map too,
and compiles where it tests p != 0 instead, and on master's code read:
getCfgProc builds the CFG for every target but wasm32, i386 runs
the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each
update, so addImmediateSuccessor's call of getSuccessorEdges panics
during instruction selection whether or not a CFG is kept after it.
It rests also on ISSUE 28088's record.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout (BUG
TODO, ISSUE 27799: where buildChains skips a conditional branch's
other edge because it would close a cycle, as it can skip a loop
latch's back edge, not fusing this edge leaves an unconditional jump
as well, and the modifier on the edges of a conditional branch
then under-prices this edge). An unconditional edge of nearly equal
weight from another predecessor can be fused with the target first,
and the loop then ends in a conditional jump to the exit
and an unconditional one back. This costs only speed, on x86-64
under -fblock-layout-cfg, not under -finfo-table-map. This rests
on master's code read (directEdges' relevantWeight in sequenceChain),
on ISSUE 27799's record and on a run of master's compiler at -O2
on the issue's program: under -fobject-determinism its latch ends
in jge and jmp, and without it in jl alone.
Two TODOs for ISSUE 20428, at livenessCfg in cmmNativeGen
and at ncgEnableDeadCodeElimination in initNCGConfig, say that since
55a6377a5d, a workaround for that issue, -finfo-table-map turns dead
code elimination off, and with it every use of the CFG from the liveness
pass on. No CFG is then kept after register allocation, so the layout
has neither static prediction nor the chains of -fblock-layout-cfg,
and lays the blocks out without weights.
Note [CFG Edge Weights] now says what -fcmm-static-pred changes:
that under it, where the CFG is kept (x86-64,
not under -finfo-table-map), the weights become estimated frequencies
before the layout uses them.
At getCfg's case for a switch, master's comment says that the weight -1
given to every target of a switch with more than ten entries (its case
values and its default), a compiler performance hack, keeps the layout
from considering them. A TODO there now says that, where the CFG
is kept, the layout considers them nonetheless, and that what the hack
saves has not been measured.
Other TODOs say:
- at the Ord instance of CfgEdge, that edges of equal weight are ordered
by their labels, which carry no meaning for the layout;
- at allEdges' relevantWeight in sequenceChain, that it differs
from directEdges';
- at dropJumps, that a block that only jumps to the next one is left
as an empty label and a jump over it is kept.
In X86's genCondBranch', a comment says that the 3 added to the weight
of a floating-point comparison's false edge breaks layout ties toward
the false target.
Assisted-by: Claude Opus 5.5
- - - - -
b204d9cf by Mikolaj Konarski at 2026-11-26T23:24:10+01:00
Document bugs and TODOs in static branch prediction and loop analysis
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Which
designs were tried and given up, and the measurement or the bug
that decided each.", "Where the code does something other than what
reading it suggests.", "Where the code is known to behave wrongly
or is half done.", "What each known bug leads to, such as wrong code,
a compiler panic or only slower code, and under which flags and on which
targets it is reached.", "Each known bug's tracker issue, named
at the code it concerns." and "Where the code is likely to change,
and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
WIP for half-done work, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- getCfg in GHC.CmmToAsm.CFG (BUG: after fixStgRegisters, a test of any
global register with no machine register on the target, CurrentTSO
or CurrentNursery among them, reads BaseReg and is tagged
HeapStackCheck). The exemptions of Note [Static Branch Prediction]
for heap and stack checks then apply to such a test, so its weights
are left unpredicted. This costs only speed, on x86-64
under -fcmm-static-pred, not under -finfo-table-map. This rests
on master's code read. The tag decides the code only through
isHeapOrStackCheck, all of whose callers
are in staticBranchPrediction, which runs inside mkGlobalWeights.
mkGlobalWeights reaches the code through staticPredCfg, only
under -fcmm-static-pred, and otherwise only through the graph
allocator's spill costs, on whose frequencies no spill choice depends.
optimizeCFG, which calls staticPredCfg, runs only where the CFG
is kept, and so not under -finfo-table-map.
- Note [Back edges in loopInfo], added to GHC.CmmToAsm.CFG, its BUG
citing ISSUE 28083 (an edge into the entry block is never a back edge,
as mkDomMap leaves the root out of every dominator set). A loop whose
head is the entry block is not found. This costs only speed, on x86-64
under -fcmm-static-pred, not under -finfo-table-map. This rests
on master's code read and ISSUE 28083's record. loopInfo's result
reaches the code only through static prediction and block layout:
of its two callers, loopLevels is never called, and mkGlobalWeights
serves staticPredCfg, under -fcmm-static-pred, and otherwise only
the graph allocator's spill costs, on whose frequencies no spill
choice depends.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28093 (a self loop is a back edge only where its block dominates
no other block). A block that jumps to itself and to an exit
it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen
does, is not a loop. calcFreqs then counts the block as irreducible
and, unless the block heads a loop that loopInfo finds, gives
it frequency 0, and so 0 to the edges out of it. This costs only
speed, on x86-64 under -fcmm-static-pred, not under -finfo-table-map,
by the same path as the BUG of ISSUE 28083. This rests on master's
code read, on the record of ISSUE 28093, and on -ddump-cfg-weights
by the compiler of master 37ad471050: of MR 16269's test T28093.cmm,
a self loop whose block dominates the exit, which weighs the self edge
and the exit edge 0, and of a loop calling fetchOrIntArray#, which
weighs the retry block's edges and the loop's back edge 0.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG: the back
edge rule supersedes a likely annotation in the Cmm as well). A branch
with both a back edge and another edge is predicted to take the back
edge, whatever its annotation says, unless an edge of it is tagged
HeapStackCheck (a heap or stack check). This costs only speed,
on x86-64 under -fcmm-static-pred, not under -finfo-table-map.
This rests on master's code read: staticBranchPrediction's case
for a mix of back edges and other edges tests no annotation.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO:
a constructor-tag test is predicted like any other comparison).
The prediction is wrong for the trees of Data.Map and Data.Set, which
declare Bin first, where the test is left spelt as an equality,
as in Data.Map's lookup: the side that stays in the loop is predicted
unlikely. This costs only speed, on x86-64 under -fcmm-static-pred,
not under -finfo-table-map. It is accepted until the knowledge
of the likely side reaches the CFG, hence TODO as well. This rests
on master's code read and on a compiler of master's code at -O1
and -O2, which left the test of Data.Map's lookup an equality
and inverted that of its member.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG
(ohPredicts treats s1 as the true side only where it is ltrue,
the label the branch was made with, which an edge no longer ends
at once the linear allocator's fixup block, by addNodesBetween,
or shortcutting, by shortcutWeightMap, has redirected it). Where
the redirected true edge's new target has the smaller label
of the two, each side gets the other's prediction. This costs only
speed, on x86-64 under -fcmm-static-pred, not under -finfo-table-map.
This rests on master's code read, and on a compiler of master
37ad471050's code with a counter added, which found over nofib's
modules 7 of the 4874 unannotated equality tests with a literal
predicted inverted at -O2 and none of the 4401 at -O1.
- calcFreqs in GHC.CmmToAsm.CFG (BUG: mkGlobalWeights passes the loops
in the order of loopInfo's back edges, descending by label, and
not by nesting). An enclosing loop's pass can come before an inner
loop's and use the branch probability of an inner back edge where
its cycle probability belongs, which gives nested loops wrong cycle
probabilities. This costs only speed, on x86-64
under -fcmm-static-pred, not under -finfo-table-map. This rests
on master's code read and on -ddump-cfg-weights by a compiler
of master's code at -O1 and -O2: of a .cmm procedure of a counting
loop nested in another, the outer loop's latch having the larger
label, which weighs the outer back edge 448, and of the same nest
with the inner loop's test inverted, giving the inner latch the larger
label, which weighs the outer back edge 7.
A WIP in Note [Static Branch Prediction] says that the paper's other
heuristics are stubs.
calcFreqs' comment on an irreducible block, "Rare we don't care", now
says what frequency such a block keeps and, as a TODO, that such blocks
are not rare, that the layout then ranks edges by frequencies that do
not add up, with a loop calling fetchOrIntArray#, compiled
by the compiler of master 37ad471050, for a case, and that summing their
inflow was tried on a development branch and kept there.
Other TODOs say:
- in Note [Back edges in loopInfo], that findBackEdges, which
optHsPatterns uses for the back edge bonus, and loopInfo differ
on edges into the entry block, on back edges of irreducible cycles
and on a self loop only where its block dominates no other block;
- at ohPredicts, that only MO_Eq is read, so the spelling
GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted,
and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq
spelling is predicted was tried on a development branch and cost nofib
0.36% more instructions at -O2;
- at lehPredicts, that where a heap or stack check's call to the garbage
collector returns into the procedure, loopInfo counts the cycle
through that call as a loop: lehPredicts then returns Nothing
for a branch into the checking block where that block is the loop's
head, and counts a branch towards a case alternative without such
a check as a loop exit where the head is the block choosing
the alternative;
- at calcFreqs, that nothing checks its result, and that a check could
compare each block's frequency with the sum of the frequencies
on its in-edges, which the propagation departs from at some blocks,
among them an irreducible block, a loop head whose cycle probability
is capped, and the entry block;
- at loopMembers, that neither it nor loopLevels has a caller in GHC:
loopMembers since the graph allocator's spill costs, for which
it was added early in 2019, began that year to weight by block
frequencies instead, and loopLevels since it came with the loop
analysis that year.
A comment at optimizeCFG says that static prediction starts
from the weights optHsPatterns leaves, so that their adjustments carry
into the predicted probabilities, except where the back edge rule
replaces them.
Assisted-by: Claude Opus 5.5
- - - - -
2bfbd24d by Mikolaj Konarski at 2026-11-26T23:24:11+01:00
Document bugs and TODOs in liveness and the register allocators
Of what anyone working with the NCG needs, this commit serves "Which
designs were tried and given up, and the measurement or the bug
that decided each.", "The invariants the code depends on.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached.", "Each known
bug's tracker issue, named at the code it concerns." and "Where the code
is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- regAlloc in GHC.CmmToAsm.Reg.Graph (BUG: once regSpill has grown
the pool of slots, it returns slotsCount', the pool's highest slot
number, which counts the preallocated slots and every slot
of the pool, used or not, as the stack needed, and the driver passes
it to ncgAllocMoreStack, where the linear allocator's regAlloc returns
only the slots from maxSpillSlots on): the preallocated slots
are reserved a second time, and with them the slots that no spill
uses, as the pool starts with maxSpillSlots+1 slots and regSpill
in GHC.CmmToAsm.Reg.Graph.Spill grows it 512 slots at a time when
a round of spilling needs more than are free. This costs C stack
space, under -fregs-graph or -fregs-iterative, on every target
but wasm32, and where a target's mkStackAllocInstr returns more
instructions for a larger amount, code at entry and exit: on AArch64
one instruction more for each 4095 bytes, on RISC-V, LoongArch
and PowerPC more past the range of an immediate, and on Windows x86-64
a call of ___chkstk_ms past 4 KB. This rests on master's code read
and on a compile by a compiler of master's code, at -O0 on x86-64,
of a procedure whose live locals took 2042 spill slots:
under -fregs-graph its code reserved 2551 slots (subq $20416,%rsp),
and under the linear allocator 32 bytes. The graph allocator can
be chosen for any target but wasm32, and trivColorable covers x86,
x86-64, PowerPC, AArch64, RISC-V and LoongArch.
- regAlloc_spin in GHC.CmmToAsm.Reg.Graph, its branch for a round
that spills (BUG: nothing evaluates the graph it validates
under -dasm-lint, which goes only into the lazy raGraph field
of a RegAllocStatsSpill, while only a RegAllocStatsStart's raGraph
is ever accessed). So -dasm-lint validates no graph of a round
that spills, only that of the round that colours every node,
and checks less than it appears to. The code is the same: this only
misleads a reader, under -fregs-graph or -fregs-iterative, on every
target but wasm32. This rests on master's code read (the accesses
to raGraph in GHC.CmmToAsm.Reg.Graph.Stats and GHC.CmmToAsm, all
of a RegAllocStatsStart, raGraph being a lazy field) and on a program
built against the ghc package of a compiler of master's code, which
passed a RegAllocStatsSpill whose raGraph is an error through
the printing of -ddump-asm-regalloc-stages and -ddump-asm-stats
without forcing it. The stages dump's printing of that graph, which
forced the check, was commented out and then deleted in e174477111
(2010).
- pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG: it binds
a SpillCostRecord as (reg, uses, defs, life), where the type's
comments give its fields as the writes, the reads and the lifetime).
Only the names are wrong: it prints the two counts in the record's
order, under no names, and their sum divided by the register's node
degree, and nothing in GHC calls it. This rests on master's code read:
slurpSpillCostInfo's incDefs fills the second field and incUses
the third.
- regAlloc in GHC.CmmToAsm.Reg.Linear, at extra_stack (BUG: stack_use
counts the slots used, while the C stack area that the RTS reserves
holds slots 0 to maxSpillSlots): at maxSpillSlots+1 slots regAlloc
returns 1 as the extra stack needed, where none is, and beyond
that one slot more than is needed. This costs C stack space, 16 bytes
at most, as each target's allocMoreStack rounds the amount up
to a multiple of 16 bytes, and at maxSpillSlots+1 slots the blocks
and stack adjustments that ncgAllocMoreStack adds at entry and exit,
under the linear allocator, on every target but wasm32. This rests
on master's code read: getStackUse returns the stack map's next free
slot, counted from 0 (emptyStackMap); each target's maxSpillSlots
is the number of slots the area holds less 1,
and its spillSlotToOffset puts slot maxSpillSlots inside the area;
and cmmNativeGen gives the graph allocator the free slots 0
to maxSpillSlots.
- saveClobberedTemps in GHC.CmmToAsm.Reg.Linear (BUG TODO, ISSUE 26631:
my_reg is the first free register of the class that the instruction
does not clobber, chosen without regard to what the instructions
before the value's next read do to it). Where they write it too,
as the moves of a C call's arguments into their registers do,
the value is moved from register to register, and where the call
clobbers every register of the value's class, as on x86-64 a C call
clobbers every floating-point register except on Windows, the call
then spills it all the same. This costs only speed, under the linear
allocator, on every target but wasm32. This rests on master's code
read, on ISSUE 26631's record and on a run of master's compiler at -O
on x86-64 of f x y z = c_hypot z x + y * z on Doubles, f marked
NOINLINE and c_hypot an unsafe foreign import of hypot, which moved z
from xmm3 to xmm0 to xmm4 and then spilled it before the call
of hypot.
- joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG: on x86
a floating-point == or /= test's block ends in three jumps, two
of which name one target, genCondBranch's parity jump
and a conditional or unconditional one, and each is joined
on its own). Where that target needs a fixup block, each of the two
jumps gets one, with the same moves, and both are reachable.
This costs only code size, on x86 and x86-64 under the linear
allocator. This rests on master's code read and on constructed Cmm
compiled by master's compiler. No module of the compile benchmarks,
compiled by master's compiler, was found to show it. A fix that shares
the block where the two jumps' stack deltas agree, the target's vregs
have the same locations at both and no value moves between two slots
was written on a development branch and is left out.
- Note [The first jump into a block fixes its entry assignment], added
to GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG TODO, ISSUE 27800:
a return continuation is an entry block, and the allocator, going
in SCC order, processes one that jumps into a loop from outside
it before that loop). Where the procedure's entry and such
a continuation enter one loop at two different blocks, the two can
record incompatible assignments, and the loop's own edges then get
fixup code that runs on every iteration. This costs only speed,
under the linear allocator, on every target but wasm32. MR 16673
proposes a fix. This rests on master's code read and on ISSUE 27800's
record, whose Cmm procedure gets two fixup blocks inside its loop
on x86-64.
- joinToTargets_first in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG
TODO, ISSUE 27981: to_free holds only registers that hold virtual
registers, so a real register still allocated at the jump, such as R1
on x86-64 where it is read after a conditional branch, stays allocated
in the free registers recorded for the block, even when it is not live
into it). The block's code then cannot use that register, and a jump
from it into a block whose entry assignment holds a value there gets
fixup moves, which on a loop's back edge run on every iteration.
This costs only speed, under the linear allocator, where an STG
register's machine register is handed out between its uses: x86-64,
PowerPC and, for XMM1 to XMM4, i386. This rests on master's code read,
on ISSUE 27981's record and on a run of master's compiler at -O
on the issue's program on x86-64, in which a loop's return
continuation falls into a fixup block of two moves before the loop
head on every iteration.
- joinToTargets_again in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG:
once it has made a fixup block for a target and patched the jump to go
there, the destinations still to consider keep the target's later
occurrences, as a jump table lists a target once for each entry naming
it). Each later occurrence makes the same moves again, into a block
nothing jumps to, which is given an edge in the CFG, laid out
and emitted: dead code. This costs only code size, under the linear
allocator. This rests on master's code read: x86's jumpDestsOfInstr
lists a jump table's targets with their repetitions, and the other
targets with jump tables do likewise. Such a block was found in GHC's
own GHC.CmmToAsm.Dwarf.Constants and in none of nofib's
or the testsuite's modules.
- makeRegMovementGraph, handleComponent and makeMove
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, and the header
of GHC.CmmToAsm.Reg.Linear.StackMap (BUG, ISSUE 27638: since ISSUE
26668 a virtual register whose format has outgrown its slot gets new
slots, so a jump can need a move between two slots of one register):
such a move ends in makeMove's panic, "makeMove: we don't handle
mem->mem moves". And where handleComponent's cyclic case moves
to an InBoth destination (BUG, a statement of its own, ISSUE 27638
reporting only the panic), the destination's slot is written only
if it is the slot spillR picks; otherwise it can keep a stale value,
which is wrong code where the slot is reloaded. Both can be reached
only under the linear allocator, where a virtual register's format
grows past 8 bytes, which only a vector format does, and so only
on i386, x86-64 and AArch64, the targets whose code generators take
vectors (checkVecCompatibility in GHC.StgToCmm.Prim; PowerPC's, RV64's
and LA64's stop with sorry on vectors). The first is reached on x86-64
at -O0, -O1 and -O2: master's compiler panics so at all three
on a function in which a Double# is passed to an unsafe foreign call
of type Double# -> Double#, then broadcast to a DoubleX2# whose lane
goes to a second such call in one arm of a case whose other arm
returns the first call's result, and used again after the case.
No program leaving a stale slot is known. The first can be reached two
ways, by expandNode, both from a jump at which the virtual register
is in one of its slots only: into a block that holds it in another
of its slots only, and into a block that holds it in a register
and another slot, where makeMove loads the register first. A fix
cannot count on a spare register: nothing keeps one free at a jump,
and the block's entry assignment can hold every allocatable register,
on x86-64 the eleven integer registers (rax, rbx, rcx, rdx, rsi, rdi,
r8 to r11 and r14) and the sixteen vector registers, the others being
the stack pointer and those of STG's Base, Sp, Hp and SpLim (freeReg
in compiler/CodeGen.Platform.h). This rests on master's code read,
ISSUE 27638's record and a run of master's compiler. The cyclic case
drops the InMem half of an InBoth destination (expandNode lists InReg
first) and writes only spillR's slot, which is getStackSlotFor's
newest slot of the virtual register and differs from the destination's
only after the register grew. And allocateRegsAndSpill frees
the register of an InBoth virtual register without a store,
so that its next use reloads the slot.
- expandNode in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG TODO: where
the destination is InBoth with the source's slot, as when a virtual
register is InBoth at both ends of the jump, it stores the value
into a slot that already holds it). This costs only speed and code
size, under the linear allocator, on every target but wasm32.
This rests on master's code read: the case of an InBoth source drops
the source's slot and expands the node as from an InReg source, whose
cases for an InBoth destination keep the store to its slot.
- livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq
compares the registers and not their formats, so the fixpoint can stop
before the formats recorded for a cycle's blocks converge): a vector
register can be recorded live at a format narrower than the value
it holds, and a write at that format then kills
it in minusCoveredRegs, which is wrong code. No program giving a wrong
result is known. This rests on master's code read and ISSUE 27619's
record, whose program shows a register recorded so.
- getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG:
it folds the slot maps of a block's predecessors from the empty map
with mergeSlotMaps, which keeps only the slots both maps hold).
The slot map on entry to a block is always empty, so a reload
is coalesced with a spill only inside one block. This costs only speed
and code size, under -fregs-graph or -fregs-iterative, on every target
but wasm32. This rests on master's code read; buildGraph
in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce.
- maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's
derived Ord compares a VecFormat's number of elements before their
format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4
FmtDouble, 256 bits): it can keep the narrower of two formats.
Were one register read at both, a write at the narrower would kill
it in minusCoveredRegs, which is wrong code; whether any register
is read so is not known. This rests on master's code read and ISSUE
27619's record. The haddocks of minusCoveredRegs and shrinkingRegs,
which compare formats by the same Ord, point to it.
The other statements, by part.
The linear allocator:
- Note [The first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump
into a block that the allocator processes records the block's entry
assignment, spilled values included, and that every later jump
conforms to it by fixup code. Its two TODOs, and its BUG TODO
for ISSUE 27800 above, are what follows from that: a loop head
recorded from a preheader that spilled a loop-carried value has
the value reloaded on every iteration, and stored again by every back
edge once the body has written it; and the block that a failed heap
or stack check returns to from the garbage collector can be allocated
before the hot path's jump into the checking block and record
that block's entry assignment, as the order of allocation depends
on no frequency. process' comment cites the Note.
- Note [Unique order in the linear allocator], added
to GHC.CmmToAsm.Reg.Linear, first lists the tags that the vregs'
uniques carry, in their order, and says which of them
-fobject-determinism renames. It then says, as a TODO, which decisions
take the order of the vregs' uniques as a ranking: the spill victim,
and the order in which saveClobberedTemps moves values out
of clobbered registers. It also says that the order decides
joinToTargets' fixup moves. The comments at those three folds cite it.
- Issues get labels where the code behaves as they report: BUG TODO
for ISSUE 26631, ISSUE 27800 and ISSUE 27981 above, and BUG for ISSUE
27638 at handleComponent, makeMove, makeRegMovementGraph
and StackMap's header, whose comments ruled out a move between two
stack slots, which ISSUE 26668 made possible.
- TODOs without an issue: raInsn's elimination of a move gives
the destination the source's register, whatever register an entry
assignment recorded for a block it is live into; and findPrefRealReg's
preference is keyed by virtual register, while a Cmm local is one
virtual register over all its live ranges.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot
belongs to one virtual register for the whole procedure,
as getStackSlotFor takes new slots only at the next free one, which
only grows, and a register that outgrows its slot gets another,
keeping the first; that the fixups at a jump rely on this; and
that it costs stack, the slots of a procedure adding up over every
register spilled in it.
- Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear,
re-adding a dead spilled register's stack slot to the free list,
is marked WIP: it is not done, as a StackMap never frees a slot.
- A comment at clobberRegs' filter says that on AArch64, RISC-V
and LoongArch frAllocateReg panics on a register that is not free.
- Three designs that a trial on a development branch found no gain
in are recorded beside the code they would change: handing out
the floating-point registers in descending order (at the BUG TODO
for ISSUE 26631 in saveClobberedTemps), taking the entry block first
and then, after each SCC, an SCC holding a block whose entry
assignment is recorded, a cyclic one first (at the BUG TODO for ISSUE
27800), and putting fixup moves before an unconditional jump rather
than in a block of their own (in joinToTargets_again).
Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs:
- The comment at the fixpoint of livenessSCCs says that its test
compares the whole map, where only the SCC's blocks can change (TODO,
ISSUE 27437), and that its steps are monotone, so that a test
comparing the formats too would reach a result independent
of the order in which the blocks are walked. The comment at Regs' Eq
says that Eq ignores formats and that ISSUE 27619 proposes one
that compares them (TODO, ISSUE 27619), and points to the BUG
at livenessSCCs for what ignoring them leads to.
- The comment on the SCCs' order says that no block may fall through,
and liveDieRead's haddock that at a branch it also holds the registers
live into its targets only.
- A comment at computeLiveness' panic on SCCs out of reverse dependent
order says that, where sccBlocks has a CFG, a jump to a block missing
from the CFG reaches it too.
The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment
says that the block frequencies scale only the counts of uses
and definitions, on which no spill choice depends, as spillCost_chaitin,
which would use them, is commented out.
Both allocators: a TODO at patchRegsOfInstr says that, as it maps
a register to a register, both allocators reload a spilled value
into a register for an instruction that reads it, even at its last read,
where an x86 instruction could read the stack slot.
Assisted-by: Claude Opus 5.5
- - - - -
d0fdb236 by Mikolaj Konarski at 2026-11-26T23:24:11+01:00
Document bugs and TODOs in code generators, DWARF and an unused module
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached.", "Each known
bug's tracker issue, named at the code it concerns.", "Where the code
is likely to change, and how." and "What the NCG leaves to the assembler
and the linker: which operand ranges a code generator checks and which
only the assembler rejects, which branches the NCG lengthens, and which
assemblers its output is written for."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126:
isNbitEncodeable 12 admits label offsets from -2048 to 2047, while
check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095):
on AArch64, compiling a label at an offset from -2048 to -1 stops
with check_off's error, a pgmError,
"GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit"
for an offset of -8. Below -2048 the guard fails, and the next clause
adds the offset through a register. This rests on master's code read
(litToImm', ImmIndex, check_off), ISSUE 28126's record and a run
of master's x86-64 compiler given an AArch64 target description,
in which a Cmm load from a label less 8, at -O0 and at -O,
and plusAddr# of a string literal and -1#, at -O, stop
with check_off's error; nothing was run on AArch64.
- lower_CmmRegOff in GHC.CmmToAsm.Wasm.FromCmm and the cases
for CmmRegOff of getRegister' in GHC.CmmToAsm.RV64.CodeGen
and GHC.CmmToAsm.LA64.CodeGen, one BUG at each (the sum
is not truncated to a sub-word register's width, as each target's
general lowering of a sub-word MO_Add truncates its result,
and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus
or minus a literal into a CmmRegOff at any width validOffsetRep
allows). Where an operation reads the bits above the width,
this is wrong code: on wasm32 a widening MO_UU_Conv of a sub-word
value masks nothing, and on RV64 Note [Signed arithmetic on RISCV64]
keeps a sub-word value zero-extended between operations. On LA64
the first case breaks the same invariant, stated under "Signed
arithmetic on LoongArch64", but no wrong code is known: each reader
of a sub-word register there extends or masks it first, or reads
its low bits alone. LA64's second case is, for a register of 8 or 16
bits, a compiler panic, "LA64.ppr: ADD error": its ADD of two
registers at the register's width is one that GHC.CmmToAsm.LA64.Ppr
prints at 32 and 64 bits alone. An 8-bit register reaches it where
the folds add literals one at a time to a CmmRegOff, summing
the offsets unnarrowed. This rests on master's code read, ISSUE
28133's record and runs of a compiler of master's code given RISC-V
and LoongArch target descriptions through -B, on Cmm with -dcmm-lint:
a bits8 local plus 1, compared with 0 at -O -fno-cmm-sink, under which
the NCG folds nothing into a CmmRegOff, became on RV64 an add
with no truncation before the comparison; a bits16 local plus 5000,
and a bits8 local plus 100 added 21 times in one expression, each
local also stored, at -O0 and at -O, were returned through %zx64
with no truncation on RV64 and made the compiler panic so on LA64;
and on LA64 a bits8 local plus 1 was extended or masked wherever
it was shifted, multiplied, negated, divided, compared, switched on,
converted or passed to a C call. Nothing was run on these targets,
and nothing was compiled for wasm32. On RV64 and LA64 an offset
that fits in 12 bits goes to the case of MO_Add for such a literal,
or on RV64 for an offset from -2047 to -1 to that of MO_Sub, which
does not truncate either; on RV64 an offset of -2048 goes to MO_Sub's
general case, which truncates. RV64's BUG cites ISSUE 28133, which
reports the cases of MO_Add, MO_Sub and MO_Or for a register
and a 12-bit literal, the first two of which RV64's first case
reaches, for an offset that fits in 12 bits; its other case has
no issue.
- makeFarBranches in GHC.CmmToAsm.AArch64.CodeGen (BUG: instr_pos counts
an LDR of a label as one instruction, where it prints as two, or three
with an offset, and the meta instructions LOCATION, DELTA,
PUSH_STACK_FRAME, POP_STACK_FRAME and, in a DEBUG compiler,
MULTILINE_COMMENT as one each, where replace_jump counts them
as none). The estimate of a branch's distance can fall short,
that of a backward branch by at least one for each of these meta
instructions before its target, and a conditional branch beyond
its reach is then left as it is, on AArch64. LLVM's assembler
(clang 18) and GNU as 2.42 reject such a module. This rests
on master's code read (instr_pos, replace_jump, isMetaInstr,
and the printing of LDR in GHC.CmmToAsm.AArch64.Ppr) and on a compiler
of master's code given an AArch64 target description through -B:
of a Cmm procedure that branches over 42000 stores of a label plus
an offset to addresses 8 bytes apart, it printed at -O0 a cbz whose
target lay 1109912 bytes on, past its reach of 1 MiB, which LLVM's
assembler rejected ("fixup value out of range"), as GNU as did
("conditional branch out of range"); with 70000 stores the estimate
passed the threshold and the branch was rewritten. Of a procedure
of 2000 C calls, each with a PUSH_STACK_FRAME, printed as two
instructions, a POP_STACK_FRAME and two DELTA, then a loop of 263000
stores, it printed at -O0 a cbnz whose target lay 263002 instructions
back, past its reach, which both assemblers rejected likewise; without
the calls the branch was rewritten.
- makeFarBranches in GHC.CmmToAsm.RV64.CodeGen (BUG: max_jump_dist
is 2^11-1 instructions, where a BCOND, printed as a B-type branch,
reaches 4 KiB each way, 1024 instructions back and 1023 forward where
none is compressed). A conditional branch whose target lies more
than 4 KiB away, but fewer than 2^11-1 instructions by the estimate,
is left beyond its reach, on RISC-V, and only an assembler
that lengthens such a branch assembles the module as meant: LLVM's
(clang 18) and GNU as 2.42 lengthen such a beq, with and without
-mno-relax. This rests on master's code read and on a compiler
of master's code given a RISC-V target description through -B, which
printed such a beq past its reach, not rewritten, that both assemblers
turned into a bne over a j.
- makeFarBranches in GHC.CmmToAsm.LA64.CodeGen (BUG: replace_jump
rewrites BCOND1 alone, never BEQZ or BNEZ, which genCondJump also
emits and which reach 4 MiB each way; instr_size counts a MOV
that prints as li.d as one instruction, where the assembler expands
li.d to up to four; and replace_jump advances its position by two
for each BCOND1 it rewrites, where instr_size counted one).
The estimate of a forward branch's distance falls short by one
for each BCOND1 rewritten before its target. A conditional branch
beyond its reach can be left as it is, on LoongArch, and LLVM's
assembler (clang 18) then rejects the module, where GNU as 2.42
lengthens the branch. This rests on master's code read and
on a compiler of master's code given a LoongArch target description
through -B, which left as they were a beqz past its reach;
in a procedure of 9000 li.d and 9000 stores that the estimate put
below its threshold, a bltu past BCOND1's 128 KiB; and, at -O0, after
40 BCOND1 that it rewrote, a bltu with 32780 instructions between
it and its target, which it rewrote without the 40: LLVM's assembler
rejected all three ("fixup value out of range"), and expanded two
of the second procedure's li.d, assembled alone, to three and four
instructions; GNU as 2.42 assembled each of the three as the inverted
branch over a b.
- makeFarBranches in GHC.CmmToAsm.PPC.Instr (BUG: blockLen counts each
instruction as one, where MFOV, LDFAR, STFAR and FETCHPC print as two,
as does a BCC that makeFar turns into a BCCFAR). The estimate
of a branch's distance can fall short by more than the margin
that nearLimit, 7000 instructions less maxRetInfoTableSizeW for each
info table, keeps below bc's reach of 8192 instructions,
and a conditional branch beyond its reach is then left as it is,
on PowerPC. LLVM's assembler (clang 18) encodes such a branch without
a message, with a wrapped displacement, which is wrong code, and GNU
as 2.42 rejects the module. This rests on master's code read
(blockLen, nearLimit, makeFar, and the printing of these instructions
in GHC.CmmToAsm.PPC.Ppr) and on a compiler of master's code given
a 64-bit PowerPC target description through -B: of a Cmm procedure
that branches over 2300 stores of %mulmayoflo, it printed at -O0 a beq
with 9205 instructions between it and its target, past its reach
of 32 KiB, which LLVM's assembler encoded as a branch backwards
and GNU as 2.42 rejected ("operand out of range").
- getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG:
neither mangleIndexTree nor add_int narrows the offset
to the register's width, and cmmMachOpFoldM's folds of literals
into a CmmRegOff sum them unnarrowed). For a 16-bit register whose
offset lies outside 16 bits, add_int's LEA, printed as an ADD
of an immediate where the result takes the operand's register, makes
the assembler shorten the immediate, with a warning where
its magnitude reaches 2^16 (addw $90000,%ax for a 16-bit register plus
three times 30000); the shortened immediate gives the value meant,
so this costs at most the warning, on x86 and x86-64. An 8-bit
register's sum takes an ADD whose immediate litToImm narrows, an LEA
printed as an LEA takes the offset as a 32-bit displacement without
a warning, and a wider register holds any offset add_int is given.
This rests on master's code read (mangleIndexTree, add_code, add_int
and the printing of an LEA as an ADD in GHC.CmmToAsm.X86.Ppr),
on master's compiler, whose assembly for such a sum in Cmm made
the assembler warn so, and on GNU as given addw and leaw with such
an immediate and displacement, with and without --32: it warned
of the addw alone and assembled both.
- vector_int_broadcast_avx2 in GHC.CmmToAsm.X86.CodeGen, local
to getRegister' (BUG: for a 256-bit vector, MOVD's destination
and VPBROADCAST's source take the vector's format, so both are printed
as a ymm register). The assembler rejects the module, for every
256-bit integer broadcast under -mavx2, which -mavx512f implies;
a 128-bit broadcast takes xmm registers and assembles, and a 512-bit
one does not reach this function. This rests on master's code read
(getRegister''s cases for MO_V_Broadcast, and pprMovdOpOp
and pprBroadcast in GHC.CmmToAsm.X86.Ppr, which print each operand
at the format given) and on a compiler of master's code on x86-64:
for a module defining f (I32# a) = (# broadcastInt32X8# a #),
it printed movd %r14d,%ymm1 and vpbroadcastd %ymm1,%ymm1 at -O1
-mavx2, which GNU as 2.42 ("operand type mismatch for `movd'")
and clang-18 rejected; ghc -c failed so for each 256-bit Int and Word
broadcast at -O0 and -O1, under -mavx2 and under -mavx512f,
and compiled the 128-bit ones tried. Nothing was run on i386.
- getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64
and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap
in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps
the number of the low half's unique): a 64-bit Cmm local and a 64-bit
NCG temporary with the same number share their high half, and where
both are live, writing one overwrites the other's high 32 bits.
This is wrong code on i386 and 32-bit PowerPC. Equal numbers occur,
as the NCG's uniques count from 0 in each Haskell module
(initDUniqSupply in GHC.Driver.Main.Compile) and, in a .cmm file,
continue the supply its Cmm pipeline used: in a .cmm file, whose
parser numbers its locals from 1 on; in a Haskell module
under -fobject-determinism, which renumbers its Cmm locals from 54
on (emptyDetUFM in GHC.Cmm.UniqueRenamer); and in any other Haskell
module once the NCG's count reaches the numbers that the global unique
counter gave its Cmm locals. In genByteSwap, equal high halves
with different low halves can arise so, and the branch for that case
swaps correctly. This rests on master's code read, ISSUE 28125's
record, whose runs show all three, and runs of a compiler of master's
code given i386 and 32-bit PowerPC target descriptions through -B,
with -dcmm-lint, at -O. For i386 a .cmm procedure gave its 64-bit
local x, numbered 1, and the NCG temporary that loads its second
argument one high half, and the final assembly loaded that argument's
high half over x's before reading it as x's; for 32-bit PowerPC,
iselExpr64, which has no case for a 64-bit shift or multiply, panicked
on that procedure. For both, a procedure whose 64-bit local x,
numbered 3, is live across 64-bit loads gave x and the NCG temporary
that loads a later 64-bit value one high half, and the final assembly
stored that value's high word as x's. Nothing was assembled, linked
or run, and nothing was run on either target.
- callerSaves in compiler/CodeGen.Platform.h (BUG: no clause names
XmmReg, YmmReg or ZmmReg, though rts/include/stg/MachRegs/x86.h
defines CALLER_SAVES_XMM1 and up for x86-64, and arm64.h
CALLER_SAVES_XMM1 and XMM2; for i386, x86.h puts XMM1 to XMM4 in xmm0
to xmm3 and defines none for them). The Cmm passes treat a vector STG
register as surviving an unsafe foreign call, which clobbers
its machine register, and Cmm lint accepts one among such a call's
arguments. Where Cmm copies a vector STG register to a local before
such a call, or a callish MachOp compiled to one such as MO_F64_Sin,
and uses the local after it, as StgToCmm does with a function's vector
argument, sinking, on at -O1 and -O2, can move the copy past the call,
which is wrong code on AArch64 and i386, reached on AArch64
from Haskell that uses vector primops. On x86-64, each of XMM1 to XMM6
that x86.h makes caller-saves, XMM6 not on Windows, shares its machine
register with an F and a D register that callerSaves names,
and sinking keeps the copy before the call. This rests on master's
code read (activeCallerSavesRegs in GHC.Cmm.Node, from which sinking
takes a call's clobbers, and mayNotMentionCallerSavedRegs
in GHC.Cmm.Lint) and on a compiler of master's code given AArch64
and i386 target descriptions through -B, which at -O -dcmm-lint moved
v = XMM1 past foreign "C" foo(x) in a procedure that then sets XMM2 =
v; given the AArch64 one, at -O and -O2, it compiled Haskell functions
that add a DoubleX2# argument to itself after an unsafe foreign call,
or after sinDouble#, to a bl foo or bl sin followed by an fadd of v4,
XMM1's machine register, which the call clobbers, where at -O0,
for x86-64 at -O, and for the sinDouble# one at -O with -fno-cmm-sink,
the vector was kept on the stack across the call. Nothing was compiled
from Haskell for i386.
- verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG: nothing checks
that a block of native code ends in a transfer of control;
this checks, in a DEBUG compiler, only that nothing but jumps follows
a jump). A block that did not end in one would run on into whichever
block the layout puts after it, which is wrong code; no instruction
selector is known to make such a block. This rests on master's code
read.
- getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105:
each can emit a displacement outside the signed 32-bit range: -i where
i = -2^31; an offset left unchecked; and an offset checked only
at shift 3, as && binds tighter than ||): where the displacement does
not fit, the x86-64 assembler rejects the module. This rests
on master's code read, ISSUE 28105's record and a compiler of master's
code on x86-64, which printed, for hand-written Cmm at -O0 and -O,
movq 2147483648(%rax) for bits64[bits64[p] - (-2147483648)], and movq
4294967296(%rbx,%r14,4) for bits64[(p + 4294967296) + (i << 2)]
and for bits64[p + ((i << 2) + 4294967296)], and at -O movb
4294967296(%r14,%rsi,4) for indexWord8OffAddr# (plusAddr#
a 4294967296#) (i *# 4#) and for indexWord8OffAddr# a (i *# 4# +#
4294967296#), each of which GNU as 2.42 and clang-18 rejected.
- getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset
plus a shift (BUG: nor is the offset narrowed to the register's
width). On i386 an offset outside 32 bits reaches the assembler, which
shortens it modulo 2^32, to the address meant, warning only where
its magnitude reaches 2^32, so this costs at most the warning;
on x86-64 such an offset is the BUG of ISSUE 28105 at the same clause.
This rests on master's code read, nothing having been compiled
for i386, and on GNU as given such displacements with --32, which
it shortened, warning from a magnitude of 2^32 on, and assembled.
- genPrim in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 27694: MO_UF_Conv's
genWordToFloat does not return the last block it adds, so a later
statement of the same Cmm block that splits its current block in turn,
as a second conversion does, moves the wrong block's edges): the CFG
lacks the edges of the jumps ending the Cmm block, and where
the linear allocator puts a fixup block on one of them,
addNodesBetween panics with "Can't find weight for edge that should
have one", the panic of ISSUE 27915. Where the second conversion's
last block is a lone jump, shortcutting (-fasm-shortcutting,
on at -O2, never on Darwin) cuts it, and shortcutWeightMap drops
its out-edges, which in the CFG are the only edges into the first
conversion's blocks; the blocks stay in the CFG, unreachable
from the entry and with edges, and classifyEdges
in GHC.Data.Graph.Directed, which findBackEdges calls
for optHsPatterns, panics with "Failed to classify edge of CFG -
not not timed" on an edge out of them. Both are reached on x86-64,
the only target for which backendMaintainsCfg holds, and
not under -finfo-table-map, under which no pass after instruction
selection gets a CFG. -dasm-lint does not catch the missing edges
first, as sanityCheckCfg compares the CFG's blocks with the code's
and not its edges. This rests on master's code read, the records
of ISSUE 27694 and ISSUE 27915, a run of master's compiler on a loop
with two word2Double# in one Cmm block: it panics in addNodesBetween
at -O, at -O2 and at -O -dasm-lint, and compiles at -O0 and at -O
-fregs-graph, as the graph allocator makes no fixup blocks; and a run
of master's compiler on two word2Double# in one Cmm block ahead
of a loop: it panics in classifyEdges at -O2, at -O2 -dasm-lint,
at -O2 -fregs-graph, at -O1 -fasm-shortcutting and at -O0
-fasm-shortcutting, and compiles at -O0, at -O1 and at -O2
-fno-asm-shortcutting.
- genXchg and the cmpxchg_code of genAtomicRMW
in GHC.CmmToAsm.X86.CodeGen, one at each (BUG: where dst_r
is a register that the amode names, as in (x) = prim %xchg64(x, y)
or (x) = prim %fetch_and64(x, y) in hand-written Cmm where x
is the address after Cmm sinking (-fcmm-sink, on at -O1 and -O2),
a MOV into dst_r from another register overwrites the address before
the XCHG, or the loop's CMPXCHG, uses it). On x86-64, where
getSimpleAmode returns an amode of virtual registers as it is,
this is wrong code, for And, Nand, Or and Xor among the atomic
operations, as Add and Sub write dst_r after their XADD; on i386
getSimpleAmode computes the address into a fresh register. StgToCmm's
result local is never the address's, and the RTS's Cmm has no such
line, so only other hand-written Cmm reaches it. This rests
on master's code read and on a compiler of master's code at -O:
in a loop, (x) = prim %fetch_and64(x, y) assembled to a lock cmpxchgq
through the overwritten register, and a program calling (x) = prim
%xchg64(x, y) in a loop, whose code holds xchgq (%rbx),%rbx, crashed
with a segmentation fault, where with a fresh result local it printed
the old and new values. At -O0 the line's arguments are copied
to fresh locals first, and the code is right. Cmm sinking replaces x's
copy by x, or by the right-hand side of x's one assignment where
it moves that assignment into the line: with one assignment
from a load followed by a store, the code held xchgq (%rsi),%rsi;
with one from a load and a test of x before the line, it was wrong
also at -O0 -fcmm-sink and right at -O -fno-cmm-sink; and two
assignments that -O merges into one gave right code.
- shortcutStatic in GHC.CmmToAsm.X86.Instr (BUG, ISSUE 28138:
it retargets the first label of a CmmLabelDiffOff and keeps
the second, which its comment says works for jump tables; since
84a087d5d5 (ISSUE 24016) a position-independent table's entries
are relative to the label of the block that jumps through the table,
in the procedure's section, and no longer to the table's label).
An entry retargeted to a label in another section, an imported
procedure's or, under -fsplit-sections, another procedure's,
is a difference the assembler cannot resolve, and it rejects
the module. This is reached under -fasm-shortcutting with -fPIC, -fPIE
or -dynamic, which implies -fPIC, on x86 and x86-64, not on Darwin,
where shortcutting is off, and under -g only for a jump-only block
to which -g adds nothing. The statement stands at shortcutStatic
rather than at build_mapping in GHC.CmmToAsm, which maps a block
to its jump's target in any section, as a jump may go to any label.
This rests on master's code read (genSwitch,
generateJumpTableForInstr, shortcutStatic, and cmmNativeGen, which
runs generateJumpTables before shortcutBranches), ISSUE 28138's record
and a compiler of master's code: on x86-64, ISSUE 28138's T.hs, whose
case tail-calls three procedures of another module, made GNU as 2.42
reject the module ("can't resolve U_a4_info - .Ln1") at -O2 -fPIC, -O2
-fPIE and -O1 -fPIC -fasm-shortcutting, and assembled at -O2, -O1
-fPIC, -O2 -fPIC -fno-asm-shortcutting and -O2 -fPIC -g; a .cmm
procedure whose switch jumps to three procedures of its own file made
the assembler reject it so ("can't resolve a1 - .Lc7") at -O2 -fPIC
-fsplit-sections, for x86-64 and, given an i386 target description
through -B and assembled with --32, for i386, and assembled without
-fsplit-sections or with -fno-asm-shortcutting. -dynamic
was not tried.
- addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG: it gives every
unwinding table that does not name Sp the rule Sp has
at the procedure's entry, and the table that X86's addSpUnwindings
adds where the C stack pointer moves, as around a C call, names MachSp
alone). Up to the next table that names Sp, DWARF gives the canonical
frame address by Sp's rule at entry: rbp+0 on x86-64, where before
a call it can be another offset, such as rbp+16. A debugger unwinding
from there finds the wrong frame. This is reached under -g on ELF
targets, on x86 and x86-64, as ncgDwarfUnwindings holds on ELF targets
under -g and addSpUnwindings is X86's. This rests on master's code
read and on readelf's reading of the frame table of an object
that master's compiler made under -g.
- dwarfReturnRegNo in GHC.CmmToAsm.Dwarf.Constants (BUG, ISSUE 11261:
no case for 32-bit PowerPC or for 64-bit PowerPC with the ELFv1 ABI;
dwarfRegNo has none for 32-bit PowerPC either). ncgDwarfEnabled holds
under -g on ELF targets other than AArch64, so on these two
the compiler panics under -g on a module with code,
with "dwarfReturnRegNo: Unsupported platform!", as ISSUE 11261 reports
for 64-bit PowerPC. This rests on master's code read (initNCGConfig's
ncgDwarfEnabled, and pprDwarfFrame, which prints the return register's
number before any other register's) and on a compiler of master's code
given a 64-bit PowerPC ELFv1 target description through -B, which
panicked so on a Haskell module and on a .cmm file at -O -g,
and on the module at -O0 -g, -O -g1 and -O0 -g1, and compiled
the module at -O and, at -O -g, a module whose one binding is x = 5 ::
Int, which has no code; given an ELFv2 one, it emitted .debug_info
at -O -g, and given a 32-bit PowerPC one, it panicked so on a .cmm
file at -O -g.
The other statements:
- The comment at backendMaintainsCfg, in GHC.CmmToAsm.BlockLayout, said
that i386 should work but is untested. It now says, as WIP, that i386
is left out because it is untested and its iselExpr64 splits blocks
for 64-bit shifts without adding them to the CFG.
- genPrim's comment says that its remaining cases add no blocks, while
MO_UF_Conv's genWordToFloat adds blocks: the BUG above stands there.
- The comment at mkRegRegMoveInstr, in GHC.CmmToAsm.X86.Instr, says
that its move clears the upper part of the register. A TODO says
that for a float or a double it is MOV FF64, printed movsd, which
keeps the destination's upper half.
- invertCondBranches inverts a jump only after an integer comparison.
A TODO says that maybeInvertCond's complement on the flags is as sound
after a floating-point one.
- pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's
start, only a block with an info table (TODO, ISSUE 27668).
- condIntCode' tests a value against zero even on a path where
the instruction computing it has set ZF and SF from it, as on the back
edge of a loop that counts down: it gets only the comparison,
and another path into the test, such as the loop's entry, may set
no flags. Only a condition that reads ZF and SF alone could use
the flags of a dec, which writes OF and leaves CF where TEST clears
both (TODO, ISSUE 27738).
- The header of GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO,
that no module imports it, and that its pass, which ran before graph
allocation (-fregs-graph), has had no caller since 2007, when
it was taken out of the pipeline in favour of the coalescing
that GHC.Data.Graph.Color.colorGraph does.
- Note [Unsafe foreign calls clobber caller-save registers]
in GHC.Cmm.Node points to the BUG at callerSaves.
Assisted-by: Claude Opus 5.5
- - - - -
4d1c6d4f by Mikolaj Konarski at 2026-11-26T23:24:12+01:00
State the NCG's norms and where a branch's likely side is known
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable." and "How to write a test
for a change to the NCG: where such tests live, what hand-written Cmm
may contain, and how a test is confined to a target or a way or marked
as a known failure."
Comments only; the generated code is the same.
Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's
own documents and testsuite hold the native code generator to, and what
each means for a change. Under -fobject-determinism the output is
to be bit-for-bit the same for the same inputs, so an order taken
from uniques is a question for review. The testsuite passes -dcmm-lint
by default, so a .cmm file that a test compiles with the ghc program
must be one that Cmm lint accepts, unless the test turns the lints off.
Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says
where it is known which side of a conditional branch is likely: where
the branch is made, as for heap and stack checks; upstream,
and not carried down, for constructor-tag tests; and nowhere,
for the rest, to which static prediction applies its heuristics,
but for a branch with two back edges. It also states the trade-offs kept
with that knowledge, each with its reason: conditions inverted
so that the true side falls through even where the false side is likely,
and edges across calls left out when chains are built and when
neighbouring chains are combined.
Note [Norms of the NCG] points to it.
Assisted-by: Claude Opus 5.5
- - - - -
673551f3 by Mikolaj Konarski at 2026-11-26T23:24:13+01:00
Rewrite the NCG's overview Note
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe.", "Which targets go
through the NCG, which of its parts each target uses, and what the NCG
takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes
in the order they run, and what each requires of the one before.",
"Which dump flag shows the output of which pass, and how to read each
dump.", "The invariants the code depends on.", "What each MachOp
and each Cmm construct means, precisely enough to write a code generator
from: a shift by the width or more, the upper bits of a value narrower
than its register, what a foreign call may clobber.", "What the NCG
leaves to the assembler and the linker: which operand ranges a code
generator checks and which only the assembler rejects, which branches
the NCG lengthens, and which assemblers its output is written for.",
"How to build and test a change to the NCG: which stage's compiler runs
the changed code, which builds check the compiler's assertions,
and which test directories and testsuite ways exercise the NCG.", "Which
flags and build settings change what the NCG emits, such as `-g`,
`-fPIC`, `-dynamic` and `-fproc-alignment`, and which of them the tests
run with.", "What the tests cover and what they do not: which targets CI
runs natively, which paths have few or no tests, and which performance
test exercises which pass." and "How to measure a change to the NCG:
which benchmarks exercise which parts of the NCG and which barely
exercise it; which tools run them and compare two compilers' results,
how to set them up and where to get them; how noisy each benchmark is;
which counter to trust; and what besides the compiler moves a result,
such as the host, the environment and how the baseline was built."
Comments only; the generated code is the same.
Note [Native code generator], the module header of GHC.CmmToAsm, named
CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which
no longer exist, and machine-independent optimisations "defined below",
which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now
says:
- which targets go through cmmNativeGen, that wasm32 has a generator
of its own, and which back end the other targets get by default;
- what the Cmm pipeline returns, and what the NCG takes from StgToCmm
and the RTS;
- the interfaces through which the machine-independent parts access
a target, and what only some targets have;
- the passes, in the order cmmNativeGen runs them, with the flags
that turn them on and the dump flags that show their output, and,
at step 4, what instruction selection must ensure;
- where the NCG's uniques come from;
- what the assembler and the linker do after it;
- the flags, testsuite directories and benchmarks for working
on the NCG.
For detail it cites the Notes and labelled statements of the preceding
commits.
Assisted-by: Claude Opus 5.5
- - - - -
d4e617c3 by Mikolaj Konarski at 2026-11-26T23:24:14+01:00
Propose two principles for the NCG
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two
principles to GHC's developers, of which it says that the native code
generator does not keep the second:
- correctness first: semantic correctness is not traded for a measured
gain that an incorrect form gives by accident, until a form with both
has been looked for and the trade agreed in review;
- one TODO set: a departure from correctness that is left in place
is marked TODO, as a member of one set that is accepted for now
and re-investigated together.
No other commit cites the Note, so this commit can be dropped
on its own.
Assisted-by: Claude Opus 5.5
- - - - -
0c2285c9 by Mikolaj Konarski at 2026-11-26T23:24:14+01:00
Add a README to the NCG's directory
Of what anyone working with the NCG needs, this commit serves "An order
in which to read the NCG's Notes.", "One place where the terms the NCG's
comments use are defined.", "One small function followed through
the NCG's dumps, in the order of its passes.", "Which dump flag shows
the output of which pass, and how to read each dump.", "Which parts
of the NCG were examined for bugs, half-done work and likely changes,
and which were not.", "What to ask of a merge request that changes
the NCG, by the kind of change: which invariants it must keep, and which
tests and measurements should come with it.", "The invariants the code
depends on.", "How to find the pass at fault for a miscompilation
or a compiler panic, and how to reduce the case to a Cmm test.", "What
else must change when a MachOp, an instruction, a register
or a relocation is added or changed." and "How to write a test
for a change to the NCG: where such tests live, what hand-written Cmm
may contain, and how a test is confined to a target or a way or marked
as a known failure."
Documentation only; the generated code is the same.
compiler/GHC/CmmToAsm/README.md is a way in for anyone working
with the native code generator, whether reading its output and dumps,
tracking a fault to its pass, reviewing or making a change,
or maintaining it. It says what to read and what to do. Its sections:
- Where to start reading: three Notes of GHC.CmmToAsm, then Notes
on the passes, each with its module, in the overview's order.
- Vocabulary: the terms the NCG's comments use, each with where
it is defined or used.
- Finding the pass at fault: for a wrong result or a panic, the oracles
to compare with, the flags that switch a pass off or swap it,
the lints, and how to cut a case down to a Cmm test.
- One function through the dumps: a small loop compiled at -O on x86-64,
with an excerpt for each dump flag in the overview's list of passes
but -ddump-asm-regalloc-stages and -ddump-asm-conflicts, which print
nothing under the linear allocator.
- Reviewing a change: questions to ask of a change by its kind, each
citing the Note or comment it rests on.
- What the labelled statements cover: which parts of the NCG they
were first written from, and which were left out.
The excerpts are cut from the dumps of one compilation by a compiler
built from master at 37ad471050: each of their lines but "..." is a line
of a dump, in the dump's order, with tabs replaced by spaces. Every
Note, function, module, flag and path the README names exists
at this commit. The overview, Note [Native code generator], now ends
by pointing to the README.
Assisted-by: Claude Opus 5.5
- - - - -
8beda5a0 by Mikolaj Konarski at 2026-11-26T23:24:15+01:00
rts: run finalizers soon after the GC that finds them
Request a context switch when scheduling the finalizers that a GC finds,
so that they run at the next block boundary rather than at the RTS
timer's next context switch, and what they would free stops being live
then. That is met for nofib's maillist, the program the delay hurt,
which now keeps in most runs the residency it keeps when the scheduler
switches whenever another thread is runnable; the falls of nofib's
geometric means come from its fall.
| | against the parent |
|-----------|-------------------------------------------:|
| nofib -O2 | -0.106% (under threshold, still important) |
| nofib -O1 | -0.118% (under threshold, still important) |
| nofib -O0 | -0.122% (under threshold, still important) |
scheduleFinalizers puts the finalizer thread at the end of the run
queue, and the thread whose heap overflow caused the GC goes back
to its front unless a context switch is pending. So under the RTS timer
the finalizers wait for the next context switch, 20 ms by default,
and whatever they would free stays live until then: a program that opens
and closes handles fast keeps every closed handle's buffers. nofib's
maillist, which appends to its output a line at a time, peaks at 7.6
to 19.6 MB of residency where it keeps 1.65 MB under -V0 and -C0,
with which the scheduler switches whenever another thread is runnable.
With the context switch requested, maillist keeps 1.65 MB
under the default timer in most runs, up to 3.1 MB, and runs 11.9% fewer
instructions at -O2, 13.0% at -O1 and 12.4% built at -O0. Across nofib,
cacheprof runs 1.3% more at -O2 and 0.90% at -O1, as it does under -V0:
run promptly, the finalizers lower the residency (cacheprof's peak
0.82 MB against 0.89 MB), so the major GCs, triggered by the old
generation's size against the live data, come more often. Of the other
programs only scc moves by 0.2%, 0.22% fewer at -O2.
Containers' graphFromEdges.star with n = 100 runs 0.11% more
instructions at -O1. A2T's groups'
Shaped/force.window/large/bcast/Storable runs 0.25% more a call; two
summed cells of the groups on large strided boxed arrays,
summed:Ranked/convertE.dynamic/large/strided/boxed
and summed:Dynamic/append.emptyR/large/strided/boxed, run 4.8% more,
cells that move by as many instructions at commits that change no code.
Cells of the groups over large Unboxed and Storable arrays take up
to 0.465% fewer, Shaped/force.narrow/large/runs/Unboxed the most, a cell
that moves by as much at commits that change no code.
The test T28060 runs under +RTS -C1, which puts the next context switch
up to a second away, and checks that the finalizer of a weak pointer
found dead by a major GC runs within a thousand iterations
of an allocating loop.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Fixes ISSUE 28060.
Assisted-by: Claude Opus 5.5
- - - - -
c712c6ed by Mikolaj Konarski at 2026-11-26T23:24:16+01:00
Address a register offset directly in x86's getAmode
getAmode made the mode of CmmRegOff r n by mangleIndexTree r n, building
the sum r + n for the alternative of x + lit to take apart. It now gives
that alternative's mode directly, so that the compiler does less work
for the same code, which the stage-1 compiler's figure measures.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.295% |
The mode given is r's register with the offset n, under the same guard,
is32BitLit of n at r's width, and where r is not PicBaseReg; the other
cases go to the mangled sum as before. For the PicBaseReg condition
isPicReg moves from GHC.Cmm.Opt, which did not export it,
to GHC.Cmm.Utils, which exports it and which x86's code generator
imports already. The code generated is the same.
Measured against its parent: nofib's objects are the same size,
as are containers', megaparsec's, vector's and A2T's. Of the stage-1
compiler's compiles, T3294's at -O0 gains the most, 1.6% fewer
instructions, and those of T783 and T9961 at -O and -O2 do not move.
The stage-2 compiler runs 0.11% fewer instructions compiling nofib's
programs at -O0 and 0.039% and 0.045% fewer at -O1 and -O2, geometric
means. A2T's groups run up to 0.46% more instructions a call in some
cells of large arrays, Shaped/force.narrow/large/runs/Unboxed
the largest, a cell that moves by as much at commits that change
no code. Vector's (next|prev)Permutation baseline for *Bijective takes
0.10% fewer instructions at -O2, a benchmark that moves both ways
by as much from commit to commit; and in the groups of orthotope's A2T
benchmark summed:Dynamic/append.emptyR/large/strided/boxed takes 4.5%
fewer instructions a call, a cell that moves by as much at commits
that change no code.
The test cmm_regoff loads and stores at q + k for offsets k on both
sides of the 32-bit displacement bounds, q passed as p - k so that each
access is at a known address.
Assisted-by: Claude Opus 5.5
- - - - -
813522ba by Mikolaj Konarski at 2026-11-26T23:24:17+01:00
Gather a Cmm sum's literals into one constant, and narrow != as ==
To move into a merge request of its own, together with "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Fold cmmOffset's offset
into any sum with a constant", "Assign literals after computed values
at the end of a block" and "Drop the assignments that only a discarded
assignment read".
Put an addition or subtraction at one width into one normal form,
its literals summed into one constant, so that no literal is left
on the left of a subtraction, where x86 cannot encode it
as an immediate, and x86's code generator computes such a sum by one LEA
or addressing mode (add_int, getAmode); and narrow != against a literal,
as ==, and a comparison of two operands widened alike. Both are done,
and nofib's, containers', megaparsec's and vector's code runs fewer
instructions by them, at a cost in compiling GHC.Cmm.Opt itself.
| | against the parent |
|----------------------------|-------------------:|
| nofib -O2 | -0.221% |
| nofib -O1 | -0.211% |
| containers -O2 | -0.240% |
| containers -O1 | -0.251% |
| megaparsec -O2 | -0.873% |
| megaparsec -O1 | -0.765% |
| vector -O2 | -0.598% |
| vector -O1 | -0.594% |
| stage 1, a sample of tests | -0.447% |
| stage 2, nofib -O2 | -0.255% |
| stage 2, nofib -O1 | -0.266% |
| stage 2, nofib -O0 | -0.306% |
GHC.Cmm.Opt's special case (a - b) + c ==> a + (c - b) fired whatever b
and c were, and where c - b could not fold it put a literal on the left
of a subtraction, which x86 cannot encode as an immediate: containers'
Set.elemAt, at -O2, computed i + ((-1) - s) for its right step, a mov,
a sub and an add where a sub and a dec do. The reassociation (a + b) - c
==> a + (b - c) had the same flaw where b is a literal and c is not,
turning (x * y + 1) - w into x * y + (1 - w).
cmmMachOpFold now puts an addition or subtraction at one width
into the form of Note [Additive normal form] in GHC.Cmm.Opt,
its literals summed into one constant: e + k, k - e or e, a difference
e - k being left as it is where e has no constant. This takes the place
of the reassociations of (a + b) - c and (a - b) + c, and that of (a +
b) + c no longer moves a literal c from the top.
That reassociation, (a + b) + c ==> a + (b + c) where c is no literal,
is master's, and reassocAdd now does it: where a is neither a literal,
a register offset nor a MachOp and the folded b + c is a sum at the same
width whose right operand is no literal, it builds a + (b + c)
as it stands, since cmmMachOpFold would return that sum unchanged,
and it folds every other step by cmmMachOpFold, as master's code does.
A left-nested sum of n terms still takes n(n-1)/2 steps to become
right-nested, as in master's reassociation; each step is now cheaper.
The x86 code generator compiles the sums left this way into one LEA:
add_int computes (a + b) + k as the address of that form and (a - b) + k
as (a + k) - b, and getAmode makes a complex addressing mode of (a +
b) + k and of (a + (b << s)) + k, and of the same forms less k. One
function, x86_offset_amode, makes these modes and add_int's address
of (a + b) + k: master's clauses of getAmode for x + lit and x - lit
and add_int's default alternative, master's LEA of x's register and k,
now share it. Master's clauses below them that match a shift stay, each
still reached: x + (y << s) by a sum with no literal, the swap
of a shift and a literal by a literal that is no 32-bit displacement,
and, where nothing folds, as at -O with -fno-cmm-sink, (x + k) + (y <<
s) for a register x by array indexing and x + ((y << s) + k)
by hand-written Cmm. Master's getRegister' now makes the LEA
of a register offset r + n directly, as add_int makes it of the sum
mangleIndexTree builds, without building the sum, where r is wider
than 16 bits. It leaves W8, which LEA does not take, and W16
to mangleIndexTree and add_int, which narrows n to r's width: at W16 n,
which cmmMachOpFoldM's folds of literals into a register offset leave
unnarrowed, can be wider than r, and the LEA, printed as an ADD
of an immediate where its result takes r's register, makes the assembler
warn that it shortened the immediate (addw $90000,%ax for a 16-bit x
plus three times 30000), as compiling the same with master's compiler
does. The BUG statement at getRegister''s case for CmmRegOff, which said
that a 16-bit register offset reached the assembler unnarrowed,
is deleted. Measured at the series' end against the clause taking W16,
nofib's assembly at -O1 and -O2 and that of the compile cells T3294,
T12707, T783, T9961 and MR 16269's CmmDiamondChain is the same,
and no cell rises by 0.001% in instructions or allocation; narrowing n
in the clause itself instead, through Integer, made the cells rise by up
to 0.088% in instructions and 0.115% in allocation (CmmDiamondChain
at -O0).
The narrowing that compares a widened operand with a literal
at the operand's width listed MO_Eq but not MO_Ne, so a byte widened
to a word was tested with != after a zero extension; MO_Ne is added
beside MO_Eq. A comparison of two operands widened alike, from the same
width and both by zero extension or both by sign extension, is now done
at that width as well, under the literal case's rule for signedness
(ISSUE 2080), its tables moved to the top level to serve both. Vector's
awshcc and nofib's reverse-complement, lambda and parser gain where !=
is narrowed like ==, and the boot libraries' comparisons of two operands
widened alike, in text, bytestring and ghc-internal's eqWord32,
are narrowed too, containers running fewer instructions by them.
Gathering a sum's literals can fold a negative constant into a label's
offset, as master's own fold of a label less a literal does. AArch64's
code generator loaded a label at an offset fitting 12 signed bits
by an add whose immediate is unsigned, so an offset such as -8 made
its printer's check_off stop the compilation with an error; a negative
offset now takes the general path, which adds the offset
from a register. That is the fault ISSUE 28126 reports, so this commit
should fix it; the issue's test, which MR 16994 adds as expected broken
on AArch64, has not been run with it.
The tests cmm_fold_lit (Cmm, the reassociations and the narrowing)
and cmm_fold_elemAt (Haskell at -O2, Set.elemAt's step) fail without
these changes, and cmm_addnf compares each shape over boundary values
with the same formula computed in Haskell. cmm_fold_lit is skipped where
the word is 32 bits, where -dcmm-lint, which the testsuite passes
by default, rejects its assignments of a byte widened by %zx64 to a W_;
nothing was run on a 32-bit target. CmmRegOffW16, on x86-64 only,
compiles a 16-bit register plus three constants whose sum does not fit
16 bits, returned and assigned; the assembler's warning on its stderr
is its failure, and through the testsuite's driver, at the series' end,
it fails so with the clause taking W16 and passes without.
Measured against its parent: nofib's programs run 0.078% fewer
instructions at -O0 (geometric mean), spectral-norm 11.8% fewer at -O2
and -O1, allocating the same. The stage-1 compiler runs 2.3% fewer
instructions compiling CmmDiamondChain at -O0 and 1.8% fewer at -O1
and -O2, and no more on any compilation of T3294, T12707, T783
and T9961. Compiling a Cmm procedure that rotates N locals in a loop
and returns their sum at -O1, it runs 0.991, 0.974, 0.940 and 0.898
times the instructions at N = 50, 100, 200 and 400. Vector's
(next|prev)Permutation baseline for *Bijective runs 0.10% more
instructions at -O2, a benchmark that moves both ways by as much
from commit to commit. A2T's groups run more instructions a call in some
cells of rerank and pad on Unboxed arrays, by up to 1.7%.
Compiled by the boot compiler, GHC 9.12.4, GHC.Cmm.Opt allocates 49%
more (2.040 against 1.369 GB), the cost of addNormalise's own code;
at the series' top it allocates 1.96 GB, 43% more than master's.
Figures of variants not taken, and others that the per-commit
measurements do not cover, were measured on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
86a200a1 by Mikolaj Konarski at 2026-11-26T23:24:17+01:00
Address (i << s) + lit on x86 by a scaled index with no base
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Take
the constant out of a shifted or scaled sum in Cmm's sums", "Fold
cmmOffset's offset into any sum with a constant", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
Let getAmode's clause for x + lit take x = i << s, s at most 3,
as an index scaled by 2^s with no base register, so that the address
of an entry of a closure table, which tagToEnum# and a derived Enum's
toEnum, succ and pred load, takes one instruction where it took a shift
and a load, and (x << s) + k takes one LEA. This is done where
the table's label is a literal that x + lit takes, so the loads
under -fPIC and -dynamic and on Windows are unchanged; vector's code
gains the most.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.090% |
| vector -O1 | -0.085% |
x86's getAmode took (i << s) + lit, the address of an entry of a closure
table, which tagToEnum# and a derived Enum's toEnum, succ and pred load,
by its default branch: the shift computed into a register, which became
the base, and lit the displacement, as shlq $3,%rax then movq
tbl(%rax),%rbx. Its clause for x + lit, which takes every literal
a displacement holds (is32BitLit), now takes such an x, s at most 3,
as an index scaled by 2^s with no base register and lit
the displacement, movq tbl(,%rax,8),%rbx, with the default branch's
relocation. The clause takes it by x86_offset_amode, the function
it shares with master's clause for x - lit and add_int's default
alternative, so add_int compiles the value (x << s) + k into the same
LEA, and an address (j << s) - k, s at most 3, is made the same way, one
instruction shorter. The clause for (a << n) + lit stays,
for the literals x + lit does not take: a label on Windows (Note
[%rip-relative addressing on x86-64]) and an integer or a label's offset
wider than 32 bits, but gives the sum to x86_complex_amode itself, lit
the base, rather than turning it around; its comment says so. Master's
x86_complex_amode now takes the index term and finds the scale itself, i
<< s for s at most 3 scaled by 2^s and any other index unscaled,
so master's clause for x + (y << s) is deleted, the clause for x + y
making the same mode of such a sum. Under -fPIC and -dynamic a table's
label reaches getAmode as PicBaseReg plus the label or as a load
from the GOT, except on Windows, where it is a literal that x + lit does
not take, so those loads are unchanged.
Measured against its parent: nofib's programs run fewer instructions
at every level, 0.19% fewer at -O0 (geometric mean), and at -O2 CSD
0.52% fewer, none more by 0.2%, the geometric means of their allocation
unchanged; containers' benchmarks run fewer at -O2 and -O1, IntSet's eq
1.1% fewer at -O2, and vector's findIndexR 1.7% and 1.6% fewer at -O2
and -O1; megaparsec's geometric means fall and A2T's sample runs fewer
instructions, none of their benchmarks rising beyond its noise.
The stage-1 compiler runs at most 0.002% more instructions compiling
T3294, T12707, T783, T9961 and MR 16269's CmmDiamondChain,
and its allocation moves by 0.002% or less.
The test cmm_scaledlit loads and stores at (i << s) + lbl for s from 0
to 3 and lbl plus or minus 8, and computes (x << s) + k at 64, 32, 16
and 8 bits for s from 0 to 4, with k small or at a bound of 32 bits
or of a narrower width, and at 64 bits past the 32-bit bounds, comparing
each with the same formula computed in Haskell; ClosureTblAmode checks
that, in x86-64 assembly, tagToEnum#'s closure table is addressed
with no base register, and is skipped on Windows and where code
is position-independent by default.
Assisted-by: Claude Opus 5.5
- - - - -
4c91cbd2 by Mikolaj Konarski at 2026-11-26T23:24:18+01:00
Take the constant out of a shifted or scaled sum in Cmm's sums
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Fold cmmOffset's
offset into any sum with a constant", "Assign literals after computed
values at the end of a block" and "Drop the assignments that only
a discarded assignment read".
Take the constant k out of an operand (e + k) << s or (e + k) * c
of an addition, into the additive normal form's one constant,
so that x86 addresses an array's element after i, p + ((i + 1) << 3),
as one mode of getAmode rather than computing i + 1 and the shift before
loading. This is done where the constant narrowed to the width fits
in 32 bits and the term is added rather than subtracted; vector's code
gains the most.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.122% |
| vector -O1 | -0.117% |
The additive normal form (Note [Additive normal form] in GHC.Cmm.Opt)
gathered the constants of an addition's operands only where an operand
was a sum, a difference, a register offset or a literal, so p + ((i + 1)
<< 3), the element after i of an array, kept its constant inside
the shift, and x86 computed i + 1 and the shift before loading. addView
now views an operand (e + k) << s or (e + k) * c at width w, k
an integer and s < w, as the term e << s or e * c with the constant k <<
s or k * c, the product distributing over the sum modulo 2^w, where
that constant narrowed to w fits in 32 bits; the old view is sumView.
p + ((i + 1) << 3) becomes (p + (i << 3)) + 8, one address of x86's
getAmode, and the closure table entry ((t - 1) << 3) + lbl becomes (t
<< 3) + (lbl - 8), with one label literal. Left as they are: (k - e) <<
s, whose term e << s would be subtracted, and no x86 address subtracts
a term, while p + ((1 - j) << 3) + 24, an element of an array in nofib's
fem, gamteb and puzzle, is one address; and a constant wider than 32
bits, which x86 would move into a register where k cost nothing,
as in (x + 1) << 40.
Measured against its parent: nofib's CSD runs 0.78% and scs 0.21% fewer
instructions at -O2 and -O1, and built at -O0 dom-lt, n-body, kahan
and fannkuch-redux run 0.60% to 0.69% fewer and others by less,
no program more by 0.2%, the geometric means lower at each level;
vector's nextPermutation and prevPermutation of a small vector run 1.8%
fewer at -O2 and -O1, and A2T's sample runs fewer, none of its cells
more by 0.2%; containers' and megaparsec's geometric means move
by 0.010% or less; allocation moves by its bar in none of the packages'
benchmarks, nofib's programs and A2T's cells. The stage-1 compiler's
instructions and allocation compiling T3294, T12707, T783, T9961 and MR
16269's CmmDiamondChain change by 0.013% or less, and the stage-2
compiler's allocation compiling nofib's programs falls by 0.036% or less
at -O2, -O1 and -O0 (geometric means). Vector's (next|prev)Permutation
baseline for *Bijective takes 0.10% fewer instructions at -O2,
a benchmark that moves both ways by as much from commit to commit.
The test cmm_fold_scaled checks in the Cmm dump p + ((i + 1) << 3), q +
(i + 2) * 24 and the two shapes left as they are, and cmm_addnf now also
computes such shifts and products as operands of additions
and subtractions, and loads at them, comparing each with the same
formula computed in Haskell. cmm_fold_scaled is skipped where the word
is 32 bits, where cmmMachOpFoldM folds (i + 1) << 40 to 0, i being 32
bits wide, and i386 passes no argument in the R2 it names; nothing
was run on a 32-bit target.
Assisted-by: Claude Opus 5.5
- - - - -
72db478c by Mikolaj Konarski at 2026-11-26T23:24:19+01:00
Fold cmmOffset's offset into any sum with a constant
To move into a merge request of its own, together with "Gather a Cmm
sum's literals into one constant, and narrow != as ==", "Address (i <<
s) + lit on x86 by a scaled index with no base", "Take the constant out
of a shifted or scaled sum in Cmm's sums", "Assign literals after
computed values at the end of a block" and "Drop the assignments
that only a discarded assignment read".
Let cmmOffset fold its offset into the constant of any sum the additive
normal form views, e + k, e - k and k - e alike, rather than into e + k
alone, so that a value Sink inlines into a register offset, which
the NCG does not fold while Sink is on, loses its constant arithmetic,
as (e - 1) + 1 becomes e. It is done for every caller of cmmOffset,
but for the shifts and products that addView also takes apart; the gain,
an instruction here and there, moves no suite's figure by its threshold.
cmmOffset summed its offset into a MachOp only of the form e + k
and wrapped any other MachOp in a new addition, folding nothing. Sink's
inl_exp inlines a local's value into a register offset l + n
by cmmOffset, so that (e - 1) + 1 was left as it is: with Sink on,
the NCG never folds, ncgDoConstantFolding being not (gopt
Opt_CoreConstantFolding dflags || gopt Opt_CmmSink dflags). cmmOffset
now applies to a MachOp the additive normal form's own view, addView,
moved with sumView and their types from GHC.Cmm.Opt to GHC.Cmm.Utils,
and adds the offset to the constant of e + k, e - k and k - e alike:
a sum whose constant cancels becomes its term, a register plus
a constant a register offset. Every caller gets it, the NCG's jump-table
index among them. cmmOffset applies the view only to an addition
or a subtraction, never to the shift or product that addView takes
apart, so a local (e + k) << s inlined into an offset stays ((e + k) <<
s) + n, as before. Master's mkRODataLits tests its literals
by isLabelLit in place of its local needsRelocation.
At -O1 and -O2 a derived Enum's succ and pred each lose one instruction,
in nofib's puzzle and ben-raytrace and in ansi-terminal-types,
and dataToTag# x plus or minus a literal loses one; every other object
of nofib's programs at -O0, -O1 and -O2, of containers', megaparsec's
and vector's benchmarks at -O1 and -O2 and of their dependencies stays
the same size, and the instruction counts of puzzle and ben-raytrace
barely move. The stage-1 compiler's instructions and allocation
compiling T3294, T12707, T783, T9961 and MR 16269's CmmDiamondChain
change by 0.011% or less, and the stage-2 compiler's allocation
compiling nofib's programs rises by 0.039% or less (geometric means)
and by less than 0.2% in any program. A2T's groups run 3.7% more
instructions a call in one cell, summed:Shaped/liftA2/large/flip/boxed,
by a step that comes and goes across the series, and vector's
(next|prev)Permutation baseline for *Bijective 0.10% more at -O2,
a benchmark that moves both ways by as much from commit to commit.
Compiled by the boot compiler, GHC 9.12.4, GHC.Cmm.Utils allocates 40%
more (1.066 against 0.760 GB), sumView inlined into addView,
and GHC.Cmm.Opt 11% less (1.955 against 2.208 GB); at the series' top
Utils allocates 1.07 GB, about two fifths again master's.
The test cmm_sinkoff sinks such values into an offset at 64, 32 and 8
bits, its constants at the wrap boundaries, and compares each
with the same formula computed in Haskell; cmm_swoff switches on e - k
and k - e at 64 and 32 bits over jump tables whose range starts at 100,
beside a control whose range starts at 1. EnumTagOffset greps
the assembly of a constructor's index plus 3 and minus 1, and
of the next and the previous constructor loaded from its closure table:
the - 1 that takes the index from the pointer's tag folds
into the literal and into the table's displacement, where the parent
commit's compiler subtracts it by an instruction of its own in each
of the four.
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
- - - - -
85126314 by Mikolaj Konarski at 2026-11-26T23:24:20+01:00
Predict an inequality with a literal in static branch prediction
Let static branch prediction's opcode heuristic predict the true side
of an inequality with a literal, as it predicts the false side
of an equality, so that a test the control-flow optimisation turns
from == into != keeps its prediction; tests of a masked operand, such
as a pointer tag test, and of a constructor tag stay unpredicted.
It removes the tie that, once the later commit "Hand calcFreqs
a procedure's loops inner first" estimates the loop's edges, gives
the cold side of megaparsec's sepEndBy loop the fall-through; against
its parent megaparsec's endBy gains, at the cost of k-nucleotide's hash
table lookup.
| | against the parent |
|----------------|-------------------:|
| megaparsec -O1 | -0.103% |
ohPredicts, static branch prediction's opcode heuristic, predicts
that a comparison with a literal is unlikely to come out equal,
but it matched only MO_Eq. The control-flow optimisation turns
an equality into an inequality where that lets the test's true side fall
through (Note [Invert Cmm conditionals] in GHC.Cmm.ContFlowOpt),
and so spelt the same test went unpredicted, its two sides weighted
alike. ohPredicts now predicts the true side of an inequality
with a literal (0.7), as it predicts the false side of an equality,
except where an operand is masked by MO_And, as in a pointer tag test,
(x & 7) != 0, or a test of a bitmap's bits, or is a constructor tag: one
read from an info table, an unboxed sum's, a local register every
assignment to which is a tag, which a pass over the procedure's Cmm
finds, or one less than such a register. Whether those bits are set,
or which constructor a tag names, depends on the type or the data, which
the CFG does not record, so a test of a constructor tag is predicted
as before (Note [Static prediction of tag tests]). That pass
and ohPredicts match one less than a tag register in both its spellings,
CmmRegOff r (-1), as the sink leaves dataToTagLarge#'s r - 1 at -O1
and -O2, and the subtraction of 1, which stays under -fno-cmm-sink.
Predicting every inequality made containers' benchmarks take up to 3.1%
more instructions, through the tag tests of tree lookups; leaving out
only pointer tag tests, intmap fromSet took 1.3% to 1.8% more, through
buildTree's bitmap test.
The pass, tagRegisters, counts an unsafe foreign call's results among
a register's assignments, in a second pass over the blocks made only
where there is a candidate; no other node assigns a local register
in the code generator's input, a safe call being lowered to unsafe ones
before. It drops each candidate assigned a copy of a register that holds
no tag, or one less than such a register, once, and with
it the candidates assigned from it in turn, through a map
from a register to those (tagSource) built only where a candidate
is dropped: filtering all the candidates again until a pass dropped none
took time quadratic in the length of a chain of copies. Measured
at the series' end, each against the code without it: in a Cmm procedure
assigning r = n & 7 in one arm and (r) = ccall labs(n) in the other,
then testing r != 3, the test's edges were weighted 0.5 each without
the count of the call's result and are 0.7 and 0.3 with it;
in a procedure of N if-else diamonds in sequence, the k-th assigning xk
a copy of x(k-1) in one arm and x(k-1) & 7 in the other, then testing xN
!= 3, the compiler ran 30015211 and 2009023957 more instructions at -O1
than with the test xN > 3, for which the tag registers are not computed,
at N = 400 and 3200 (where the whole compile took 3346781123), and runs
1444374 and 13718051 more. With either change nofib's modules compile
to the same assembly at -O1 and -O2, and each compile cell stays within
0.01% of the allocation and 0.005% of the instructions it had before.
What this removes is a tie. In megaparsec's sepEndBy loop, a cold
continuation's edge into the loop's second head weighs as much
as the hot edge into it once the later commit "Hand calcFreqs
a procedure's loops inner first" estimates them, because the test before
them, written as != 0, is estimated 50/50; the tie gives the cold block
the fall-through, and every element a jump. With this commit the hot
edge is the heavier one.
The trade is k-nucleotide's hash table lookup: the exits of its bucket
loop, written as tests for zero, come out as != 0 and are now predicted
to stay in the loop, so that with the loop-exit heuristic the loop's
back edge outweighs its entry; block layout gives the back edge
the head's fall-through, and every first probe, which finds its key
about 95% of the time, takes a jump. The commit that lets a loop's back
edge outrank its entry makes this layout anyway. The gains include
containers' intmap compareSize:n (3.4% fewer instructions) and nubOrd
issue1202_repeat (0.91% fewer at -O1), and megaparsec's endBy (0.62%
to 0.64% fewer at -O2).
As a TODO at ohPredicts records, the exception goes by an operand's
form, not by what decides the test: a parity test, its mask inside
arithmetic, is predicted, and an evaluation test, (x & 7) != 0, is left
out with the constructor-tag tests; predicting evaluation tests
as evaluated, in either spelling, cost nofib 0.36% more instructions.
Leaving out as well parity tests, x rem 2^p, also as GHC.Cmm.Opt
rewrites it, x - ((x + c) & -2^p), and masks under a conversion, a shift
or the addition of a literal, leaves unpredicted 8 of the 1685
inequalities with a literal predicted in nofib at -O1 and 8 of 2282
at -O2, 220 of 21354 in the boot libraries and the ghc library
and at most 7 in each build of containers', megaparsec's and vector's
benchmarks. It moves nofib's programs by less than 0.06%
in instructions, the benchmarks of containers, megaparsec and vector
within the spread of their runs or by at most 0.016%, the cells
of orthotope's A2T benchmark by less than 0.1%, and the compiler's
instructions by at most 0.001% compiling perf/compiler's T3294, T12707,
T783 and T9961, its allocation not at all.
Measured against the parent commit, in instructions: nofib's programs
move by 0.002% or less at every level, in geometric mean, k-nucleotide
taking 0.48% more at -O2 and 0.27% at -O1; containers' benchmarks take
0.010% fewer at -O2 and 0.003% at -O1, in geometric mean,
the compareSize:2 rows of intmap and intset and intset's deleteMax
taking one instruction a call more; megaparsec's take 0.003% more
at -O2; vector's move by 0.002% or less; in orthotope's A2T benchmark
maximumA.one over small strided arrays takes two instructions a call
more (0.4% to 0.6%), and many of its cells take 0.2% to 0.4% fewer, both
by a jump in absAxesAndStartT: of the two return blocks that run back
into the tag test at its head, the layout now places before the test
the one most cells take, and maximumA.one's strided cells take
the other. A2T's groups take up to 0.71% more, Shaped's zipWithA.singleR
over empty scalar Storable arrays the largest; nofib's objects grow
by up to 0.60% at -O2 and -O1, x2n1's the largest; and the probe
of ISSUE 27742 compiles at -O2 to two instructions more, both jumps.
No benchmark's allocation moves by its bar but k-nucleotide's, 0.23%
more at -O2; the compiler allocates at most 0.021% more compiling
perf/compiler's T3294, T12707, T783 and T9961.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
5468a804 by Mikolaj Konarski at 2026-11-26T23:24:20+01:00
Find a CFG's back edges by one depth-first search
Find a CFG's back edges, which optHsPatterns computes for every
procedure at every optimisation level, by one depth-first search
that collects them as it goes, rather than by classifying every edge
of the CFG. The generated code is the same, and the compiler does less
work for it at every level.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.273% |
| stage 2, nofib -O0 | -0.250% |
findBackEdges classified every edge of the CFG (classifyEdges, which
timestamps the visits of a depth-first search from the entry) to find
the few that lead back to a block on the search's path. optHsPatterns
calls it on every procedure, at every optimisation level, to give back
edges their bonus. findBackEdges is now that depth-first search itself:
it visits the successors in the same order and collects, as it goes,
the edges into a block still on its stack, leaving out an edge
from a block to itself, which classifyEdges classifies as a self loop
rather than a back edge. classifyEdges and its EdgeType,
in GHC.Data.Graph.Directed, had no other user and are gone.
The generated code is the same: the assembly of perf/compiler's T3294,
T12707, T783 and T9961 at -O0 and -O, and the object code of nofib's
programs at -O2, are the parent's. The stage-1 compiler allocates up
to 0.95% less, compiling T783 and T9961 at -O0, and 0.19% less compiling
MR 16269's CmmDiamondChain at -O1 and -O2; and the stage-2 compiler,
compiling nofib's programs at -O2, 0.19% less in geometric mean and up
to 0.36% less (real/compress2). A2T's groups run 3.7% more instructions
a call in one cell, summed:Shaped/liftA2/large/flip/boxed, by a step
that comes and goes across the series.
Assisted-by: Claude Opus 5.5
- - - - -
69ed7efd by Mikolaj Konarski at 2026-11-26T23:24:21+01:00
Drop jumps over blocks dropJumps empties
Let dropJumps pass over the blocks that hold no code, or that it leaves
holding none, so that a jump over a jump-only block it emptied
to the block after falls through rather than staying a jump to the next
instruction. This is done on every backend, by a fold over the blocks
already processed; on x86-64 such jumps go from containers' intset
and intmap benchmarks at -O1, and the code elsewhere barely moves.
dropJumps removes a block's last jump where it can fall through
to the next block, and a jump-only block it so empties stays as a label,
so that a jump over it to the block after is left as a jump to the next
instruction (x86-64's eb 00, which master's intmap benchmarks at -O1
carry). It now passes over the blocks that hold no code or
that it leaves holding none, by a fold from the end over the blocks
it has already processed, among which a block it leaves without code
holds none already. Looking ahead over the blocks still to process
instead, as first written, took time exponential in a run of blocks
holding one jump each; the fold builds the whole list before returning
its first block, and the compiler allocates 0.081% more compiling
perf/compiler's T783 at -O0 than with that look-ahead.
A block holding no code is one with no info table that holds only meta
instructions or none: under -g a block whose jump the layout dropped
keeps its unwinding information, and without -g the only meta
instruction a block can hold is the comment that GHC.Cmm.GenericOpt
makes of an assignment of a register to itself. The test is a function
of its own beside dropJumps, fallsTo: it succeeds at a block whose label
satisfies a predicate, passes over a block holding no code, and fails
elsewhere. Its first argument is the meta test, for a code generator
where the Instruction instance is not in scope; dropJumps passes
the class's isMetaInstr, and as the predicate canFallthroughTo where
the label has no info table.
dropJumps, master's function, is generic over the backends,
so this changes it on every backend. On x86-64 isMetaInstr holds only
of instructions that emit no code, and a jump over a block whose own
jump dropJumps dropped is dropped under -g as without it. On AArch64,
RV64 and LA64 isMetaInstr holds of PUSH_STACK_FRAME and POP_STACK_FRAME
too, which emit code, so there dropJumps rests on no block holding only
those: their code generators emit the two only around a C call, in one
sequence with the call, which nothing checks, and none of the three
backends was built for this change.
Measured against its parent: built at -O1, containers' intset folds
over sparse sets run 1.5% (foldr_elem) and 0.90% (foldl_elem) fewer
instructions and intmap's fromSetA 0.50% to 1.4% fewer, and no benchmark
rises beyond its noise; at -O2 containers' benchmarks neither rise
nor fall beyond their noise. nofib's programs move by less than 0.2%
at every level, and their geometric means, megaparsec's and vector's
by 0.036% or less; no cell of A2T's sample moves by 0.2%, and of A2T's
groups only one summed cell,
summed:Dynamic/append.emptyR/large/strided/boxed, runs 4.8% more
instructions a call, a cell that moves by as much at commits that change
no code. Cells of A2T's groups over large Unboxed and Storable arrays
take up to 0.235% fewer, Shaped/force/large/window/Unboxed the most,
a cell that moves by as much at commits that change no code.
The assembly of T3294, T12707, T783, T9961 and MR 16269's
CmmDiamondChain is the parent's, and the stage-1 compiler runs at most
0.037% more instructions compiling them (T783 at -O0) and allocates up
to 0.057% less (T9961 at -O0) and up to 0.025% more (T783 at -O0).
fallsTo tests a block's instructions before it looks the block up
in the map of info tables, dropJumps' predicate looks the label up only
where the jump can fall to it, and dropJumps binds isMetaInstr strictly;
the comments there say what each other choice cost. Measured
at the series' end, against it with dropJumps passing only over blocks
with no instructions and with the x86-64 code generator's later tests
of the same question as functions of their own: at -O1 with -g nofib's
code changes in some procedures of ben-raytrace, cacheprof, fem, fluid,
hidden, scs, smallpt, minimax and simple, some losing a jump, the others
placing their blocks otherwise; several now equal their code without -g,
and none that equalled it differs. At -O2 with -g nothing changes,
nor does nofib's assembly without -g at -O1 and -O2; the code
of a constructed procedure at -O0 with a block holding only that comment
changes. The compiler runs 0.008% fewer instructions compiling T9961
at -O0, 0.052% fewer compiling T783 there and 0.010% fewer compiling
CmmDiamondChain at -O1 and -O2, and allocates at most 0.002% more,
compiling T9961 at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
2d958c9d by Mikolaj Konarski at 2026-11-26T23:24:22+01:00
Let a loop's back edge outrank its entry in block layout
Raise each loop's back edge in sequenceChain's block layout by a little
more than the heaviest other edge into its head, so that the back edge
takes the head's fall-through even where static prediction rates
it below the loop's entry, and an iteration no longer takes a jump back.
Back edges out of a jump table or out of a block with another successor,
those after a failed heap or stack check and those into the entry
block's one successor are left as they were. Vector's code gains
the most; containers' and megaparsec's rises are trades.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.405% |
sequenceChain lays the blocks out by fusing chains along the heaviest
edges first, by the final edge weights. Under -fcmm-static-pred,
on at -O1 and -O2, those are the frequencies static prediction
estimates, which can rate a loop's back edge below its entry: where
the branch that decides whether the loop goes on has no back edge among
its targets, the other heuristics predict it, and they can predict
staying in the loop to be unlikely, as in a lookup down a tree (Note
[Static prediction of tag tests]). The entry then falls through
into the loop's head, and every iteration takes a jump back.
optHsPatterns gives back edges a bonus (increaseBackEdgeWeight),
but static prediction replaces the weights of the branches
its heuristics cover with its predictions, so that the bonus counts only
at those it leaves alone, a heap or stack check's and those whose
targets are all back edges, and at a two-way branch back
into the procedure's entry, whose weights static prediction starts from.
sequenceChain now raises (preferBackEdges) each back edge by a little
more than the weight of the heaviest edge into its head that is
not a call, a back edge or a self loop, which keeps the order of several
back edges into one head; Note [Layout relevant edge weights]. A back
edge out of a jump table is not raised: it cannot fall through,
so raising it would only take the head's fall-through from an edge
that can. Nor is a back edge out of a block with another successor:
that block executes its branch whichever successor falls through,
so falling through saves nothing an iteration, while every entry takes
a jump; leaving such edges out takes 1.55% off intset folds:sparse
foldr_elem and 0.78% off foldl_elem, and 6.4% off folds:dense
foldl'_maximum, at -O2. preferBackEdges takes the back edges
from findBackEdges, now exported.
The garbage collector's return to the block that made a heap or stack
check is no such loop: a back edge leaving a block that follows a failed
check stays as it is. checkFailures, in GHC.CmmToAsm.CFG, finds
those blocks: the targets of the less likely edges of a branch
that getCfg tags HeapStackCheck, one whose condition reads SpLim, HpLim
or BaseReg, and their successors, such as the block the garbage
collector returns to, which can be a continuation that a call returns
to as well. A block that follows such a block and whose one out-edge has
the code generator as its source, such as a block the register allocator
puts there, counts as following a failed check too (coldBlocks). Raising
those back edges too makes containers' benchmarks take 0.28% more
instructions (set fromAscList:fusion 3.2%, intset fromList:worstCase
3.0%); leaving out the blocks that follow a failed check but
not the block the register allocator puts after such a block, 0.09% more
(map alter insert 0.9%). A new Note, [Frequencies before register
allocation] in GHC.CmmToAsm.CFG, names two shapes coldBlocks misses:
the block allocMoreStack splits off a block the garbage collector
returns to, and a fixup block on a failure edge, which takes the edge's
tag. A TODO at coldBlocks points there. Building the set in GHC.CmmToAsm
instead, from checkFailures' blocks, the blocks allocMoreStack splits
off a cold entry block and the fixup blocks on an edge out of or
into a cold block, changed a few procedures' layout in nofib and moved
no figure measured, while costing up to 0.03% more compile allocation
at -O0.
Nor is a back edge into the one successor of the procedure's entry block
raised: the entry would then jump to that block at every call, which
the savings of a loop that seldom iterates do not make up for. The RTS's
entry code has such loops, which retry on an indirection: raising their
back edges made stg_BLACKHOLE_info, stg_enter_info and stg_forceIO_info
begin with a jump into the loop, so that stg_BLACKHOLE_info ran
an instruction more for every blackhole entered. Where the code
generator split the entry block, as allocMoreStack does, and the block
holding the rest of its code has one successor, that successor stands
in for the entry's.
Measured against the parent commit, in instructions; sequenceChain runs
only under -fblock-layout-cfg, on at -O1 and -O2. At -O2 nofib's
programs take 0.050% fewer (queens 1.2%, wheel-sieve1 1.0%, banner
0.46%), vector's leaffix 3.4% fewer, rootfix 2.7% and listRank 2.2%,
containers' benchmarks 0.094% fewer and megaparsec's 0.093% fewer
(reachOffsetNoLine 0.78%, reachOffset 0.46% to 0.60%); at -O1 nofib's
take 0.048% fewer (knights 1.3%, wheel-sieve1 0.99%, banner 0.45%);
fannkuch-redux moves by no more than its noise.
Some of containers' and megaparsec's benchmarks rise; the rises
are trades. The rule's own is the jump a loop's entry now takes, which
its iterations' savings seldom make up for: intmap lookup_mixed 2.0%,
whose lookups gain nothing from the descent that now falls through,
and intset's intersection and difference benchmarks, up to 0.96%:
the continuation that evaluates the second set now jumps
into differenceTip's descent, a loop whose head has two back edges
and which runs no iteration where that set is a Tip, as
in these benchmarks, while IntMap's lookups, of the same shape, iterate
about sixteen times an entry and gain 2.5% to 3.0%; no static rule tells
the two apart. megaparsec's hexadecimal, decimal and octal take the same
jump at -O1 and -O2, and at -O2 so does scientific.4000, which calls
decimal's decimal_: 20 instructions more, as decimal.4000. Other rows
rise as well: IntSet's disjoint:true takes 0.93% more at -O1, graph
graphFromEdges on maxDAG n=15 0.13% at -O2, and IntMap's random
withoutKeys and restrictKeys benchmarks up to 0.24%; at -O1 megaparsec's
reachOffsetNoLine, reachOffset and errorBundlePretty take up to 0.13%
more, by the tie described below; A2T's generate over strided boxed
arrays takes up to 0.46% more on large ones and its scalar form one
or two instructions a call more on small ones; and of A2T's groups,
summed:Dynamic/stretch/large/scaled/boxed takes 10% more, a cell
that moves by as much at commits that change no code.
The fused rows, containers' map fromDistinctDescList:fusion, map and set
fromList-distinctAsc:fusion, and map fromListWith-asc:fusion
and fromListWithKey-asc:fusion, take 0.4% to 0.8% more at -O2, and set
fromDistinctDescList:fusion 0.88% more. Raising back edges only
into heads outside every enclosing loop reverts them, and with them
nubInt's noFusion_repeat, which takes the same jump into IntSet's
member, 1000 instructions a run, and issue1202_repeat, intmap
lookup_mixed and intset alterF:delete:present; but it gives back
the gains of intmap lookup_hits, lookup_most and index (2.9% to 3.0%),
lookup_misses (2.5%), intset member and alterF:member (1.0% to 1.1%),
and vector's listRank (2.2%) and awshcc (1.8%), at -O2.
Where two back edges raised alike into one head tie, the static order
breaks the tie: at -O1 megaparsec's reachOffset runs 78000 instructions
a call more, isWideChar's loop head having two back edges, tied,
and the tie going by label order to the one that ASCII input never
takes. Flipping the order takes 4.0% off intmap lookup_half, 2.0% off
lookup_mixed and 1.2% off intset alterF:delete:present, and at -O1 1.1%
off megaparsec's reachOffsetNoLine and 0.8% off errorBundlePretty,
but adds 2.5% to nofib's fasta at -O2 and 1.2% at -O1, gives back 96%
of banner's gain, and adds 5.9% to intset fromAscList:fusion, 2.3%
to fromAscList, 1.3% to mapMonotonic and, at -O1, 0.9% to vector's next
and prevPermutationBijective; the static order is kept.
No benchmark's allocation changes beyond nofib's run-to-run noise.
The stage-1 compiler allocates 0.11% and 0.14% more compiling
perf/compiler's T12707 and T783 at -O and 0.097% and 0.13% more at -O2,
and 0.22% more compiling MR 16269's CmmDiamondChain at -O1 and -O2;
elsewhere its allocation moves by less than 0.03%. The stage-2 compiler
allocates 0.24% and 0.23% more compiling nofib's reptile and puzzle
at -O2, and 0.20% more compiling primetest and clausify. Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.BlockLayout allocates 14%
more (1.143 against 1.001 GB).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
09f2c7a6 by Mikolaj Konarski at 2026-11-26T23:24:22+01:00
Hand calcFreqs a procedure's loops inner first
Hand calcFreqs a procedure's loops from inner to outer, as Wu
and Larus's algorithm takes them, by sorting them by the size of their
bodies, so that calcFreqs no longer uses an inner loop's back-edge
probability as that loop's cycle probability and estimates the inner
loop's head up to 512 times as often as it is entered. The estimates
are now the algorithm's; the code changes little, and no suite moves
by its threshold.
calcFreqs estimates block frequencies by Wu and Larus's algorithm, which
takes the loops from inner to outer, as its comment says: an enclosing
loop's frequencies use the cycle probability of each loop inside it,
computed when that loop is processed. mkGlobalWeights handed
it the loops in loopInfo's order, by back edge in the order of the CFG's
labels, so an enclosing loop could come first. calcFreqs then used
the probability of an inner loop's back edge itself, often 1.0,
as that loop's cycle probability, which calcFreqs caps at 1 - 1/512,
so the inner loop's head counted up to 512 times as often as
it was entered. The cycle a heap check makes through the garbage
collector is such an inner loop in any loop that allocates:
in containers' map benchmarks, the head of the loop that looks keys up
was estimated to run several times as often as the edges into it.
mkGlobalWeights now sorts the loops by the size of their bodies,
an inner loop's body being a proper subset of an enclosing one's.
This makes block layout depend more on the estimate. Taking
a procedure's loops in label order could make a head's frequency up
to 512 times its inflow, so that the loop's back edge won by accident;
where static prediction predicts staying in a loop over a tree
to be unlikely (Note [Static prediction of tag tests]), it is now
the rule that a back edge outranks the loop's entry ("Let a loop's back
edge outrank its entry in block layout") that keeps layout
from following the estimate.
Measured against the parent commit, in instructions; calcFreqs changes
the generated code only under -fcmm-static-pred, on at -O1 and -O2.
No nofib program moves by 0.2%, no benchmark of containers or megaparsec
rises beyond its noise at -O2, and vector's benchmarks take 0.035% fewer
at -O2 (findIndexR_manual 1.07% fewer). No benchmark's allocation
changes beyond nofib's run-to-run noise. The compiler's allocation
compiling perf/compiler's T3294, T12707, T783 and T9961 moves by 0.005%
or less. nofib's objects grow by up to 0.41%, wheel-sieve2's at -O1
the most. In the groups of orthotope's A2T benchmark
summed:Dynamic/stretch/large/scaled/boxed takes 9.1% fewer instructions
a call, a cell that moves by as much at commits that change no code,
and cells over runs and windows of large Unboxed and Storable arrays up
to 0.274% fewer, Shaped/update/large/window/Unboxed the most, a cell
that moves both ways by as much from commit to commit.
Assisted-by: Claude Opus 5.5
- - - - -
1c3c4998 by Mikolaj Konarski at 2026-11-26T23:24:23+01:00
Count self loops as loops in static branch prediction
Static branch prediction now counts a self loop as a back edge at every
block but the root of the dominator tree, where it counted one only
at a leaf of the tree. This fixes ISSUE 28093, as MR 16269 does,
and with it the frequency 0 that calcFreqs gave to the code around
the compare-and-swap loop by which x86 emulates an atomic operation.
The stage-1 compiler, whose dominator map is now built in one fold, runs
fewer instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -2.631% |
loopInfo counted an edge as a back edge where its target dominates
its source, by mkDomMap's sets, which hold a block's own label only
where the block is a leaf of the dominator tree. So a self loop counted
as a back edge only from a leaf, and the retry of an atomic operation
that x86 emulates with a compare-and-swap loop (cmpxchg_code), whose
block dominates the block after it, counted as none: calcFreqs
then treated that block as irreducible and gave frequency 0 to it,
to every block it dominates and to their edges, a surrounding loop's
back edge among them. mkDomMap's sets now hold each block's own label
but the root's, so that a self loop counts as a back edge but
at the root, which no edge enters as a back edge. mkDomMap also builds
the map in one fold over the dominator tree, inserting each block
but the root as it walks the tree, where it built a list of pairs, each
block with its dominators, and made a map of the list. The fold is taken
from Simon Jakobi's MR 16269, for ISSUE 27448, which also changes what
the sets hold. This commit takes MR 16269's regression test T28093
unchanged, which checks the final CFG weights of a self loop that
is no leaf of the dominator tree.
The retry edge cmpxchg_code adds now has a TransitionSource of its own,
AsmCodeGenRetry, which staticBranchPrediction does not count as a back
edge, so that the retry is predicted to be rare rather than to repeat
seven times in eight. Note [Static Branch Prediction] says so. Andreas
Klebinger's MR 16535 overlaps with this commit at that edge: it builds
that loop's edges by continueInNewBlock and addColdSelfLoop, and the two
changes conflict there.
The back edges staticBranchPrediction tests were a Set of pairs,
master's, looked up for each successor of each block; they are now
a LabelMap from each block to the LabelSet of the blocks its back edges
enter, looked up once a block.
Measured against the parent commit, on x86-64: the assembly
of perf/compiler's T3294, T12707, T783 and T9961 at -O0 and -O
is the same, and so are the objects of nofib's programs at -O2,
and no benchmark of containers, vector or megaparsec moves beyond
its noise. The stage-1 compiler allocates at -O 5.5% less compiling
perf/compiler's T783, at most 0.35% less compiling T12707, T3294
and T9961, and 27.6% and 27.5% less compiling MR 16269's CmmDiamondChain
at -O1 and -O2. Most of the saving is the fold's, at T783
and CmmDiamondChain. At -O0, where static prediction is off,
the allocation moves by 0.002% or less.
Assisted-by: Claude Opus 5.5
- - - - -
11146055 by Mikolaj Konarski at 2026-11-26T23:24:24+01:00
Specialise the linear allocator and liveness pass to x86-64
The linear allocator and the liveness pass are now specialised to x86's
instructions, so that on x86-64 they no longer call every instruction
method through a dictionary. Both specialisations fire, when the boot
compiler builds stage 1 and when the stage-1 compiler builds stage 2,
and only x86-64 gets a copy of the allocator. The compiler runs fewer
instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -1.072% |
| stage 2, nofib -O2 | -0.330% |
| stage 2, nofib -O1 | -0.298% |
| stage 2, nofib -O0 | -0.717% |
The linear allocator is overloaded in the instructions and in the free
registers, and the liveness pass in the instructions, so on x86-64 too
they called every instruction method through a dictionary: the code
generator is specialised for each target, but its calls of regAlloc
and cmmTopLiveness went to the overloaded functions. Both now have
a SPECIALISE pragma for x86's instructions, and NOINLINE [0], without
which neither rule fires, when the boot compiler builds stage 1 or when
the stage-1 compiler builds stage 2: cast worker/wrapper makes each
function an alias of its body, cast to UniqDSM, and the alias inlines
from the function's own phase whatever its rules' phase, so it inlines
into the code generator before the call there becomes one at x86's
instructions, which is what the rule rewrites. A phase on the SPECIALISE
pragmas alone, [0] or [2], makes neither rule fire. linearRegAlloc
passes the other targets' free registers through a NOINLINE function,
which the specialiser does not specialise, so that only x86-64's get
a copy of the allocator; Note [Specialising the linear allocator].
The allocator's constraint synonym no longer requires Outputable free
registers, which nothing prints, and is renamed
from OutputableRegConstraint to RegAllocConstraint. Liveness.hs now
imports GHC.CmmToAsm.X86 for its Instruction instance, which Linear.hs,
importing Liveness.hs, has as well, so the allocator's modules
that import either compile after the x86 code generator; this makes
no import cycle, as of the allocator's modules the x86 code generator
imports only GHC.CmmToAsm.Reg.Target.
Specialising joinToTargets as well, with NOINLINE [0], saved
the compiler less allocation than this commit does.
The idea of specialising the allocator comes from the draft MR 4764
by Ben Gamari and Andreas Klebinger, which overlaps with this commit: MR
4764 specialises the linear allocator to x86-64 and i386, by INLINEABLE
pragmas on the allocator's functions and SPECIALIZE pragmas
in GHC.CmmToAsm.X86, and this commit specialises it and the liveness
pass to x86-64, by the SPECIALISE pragmas above.
The generated code is the same: nofib's object files are the parent's
size. Of the programs, nofib's spectral/scc at -O2 runs 0.215% more
instructions, and eight cells of A2T's groups run up to 0.289% more,
Shaped/force.narrow/large/runs/Unboxed the most, a cell that moves
by as much at commits that change no code. The stage-1 compiler
allocates less at every compile of the sample, at most 1.7% less,
compiling perf/compiler's T3294 at -O0, though only 0.011% less
compiling T9961 at -O, where CI compiles it. Compiled by the boot
compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 59% more (2.590
against 1.625 GB) and GHC.CmmToAsm.Reg.Liveness 28% more (2.095 against
1.640 GB). The ghc library's objects grow by about 190 KB built
by the boot compiler and 270 KB built by the stage-1 compiler.
The series' figures for its pragmas, these among them, come from stage-1
compilers built by GHC 9.12.4; on an earlier form of the series
a stage-2 compiler with the series' pragmas, against one without them,
keeps every sign: compiling T3294, T783, T12707 and T9961 at -O0, -O
and -O2 and MR 16269's CmmDiamondChain and nofib's puzzle at -O0, -O1
and -O2, it runs fewer instructions and allocates less in every cell,
5.3% and 4.8% compiling T3294 at -O0.
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
- - - - -
d1d061a5 by Mikolaj Konarski at 2026-11-26T23:24:25+01:00
Record the linear allocator's spills only for -ddump-asm-stats
The linear allocator now records the spills and reloads it inserts only
when -ddump-asm-stats is on, the statistics that flag prints being their
only use. The statistics printed are the same, and so is the generated
code. The compiler allocates less:
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1 allocation, a sample of tests | -0.032% (under threshold, still important) |
| stage 2 allocation, a sample of tests | -0.075% (under threshold, still important) |
recordSpill kept every spill and reload the linear allocator inserts,
with its reason, in ra_spills, for the statistics -ddump-asm-stats
prints. It now keeps them only when that flag is on. The stage-1
compiler saves the most compiling perf/compiler's T3294 at -O0, where
it allocates 0.20% less.
Assisted-by: Claude Opus 5.5
- - - - -
ae6d4f4a by Mikolaj Konarski at 2026-11-26T23:24:25+01:00
Check the order of liveness SCCs where jump targets are looked up
The order of a procedure's liveness SCCs is now checked where
the liveness pass looks a jump target's live-in registers up, and
not in a walk of its own: the lookup panics where the target is missing.
The separate walk goes, the generated code is the same, and the compiler
runs fewer instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.327% |
| stage 2, nofib -O0 | -0.281% |
computeLiveness checked that a procedure's SCCs come in reverse
dependency order (checkIsReverseDependent) in a walk of its own,
gathering every instruction's jump destinations, and panicked otherwise.
The liveness pass looks every jump target's live-in registers up anyway,
using none for a target missing from its map; that lookup now panics
instead, naming the target. For this, livenessSCCs enters the blocks
of a cyclic SCC in the map before the SCC's first walk, with no register
live, which is what the lookup returned for a missing target, so
that a target can be missing only where the SCCs are out of order,
or where the CFG that gave the reachable blocks (sccBlocks) lacks it.
The separate walk goes, and with it computeLiveness, which then only
called livenessSCCs: regLiveness calls that itself.
The stage-1 compiler allocates less at every compile of the sample
but perf/compiler's T9961 at -O and -O2, where it allocates 0.006%
and 0.004% more, and saves the most compiling T9961 at -O0, 0.66%.
Assisted-by: Claude Opus 5.5
- - - - -
dbe98542 by Mikolaj Konarski at 2026-11-26T23:24:26+01:00
Keep a procedure's imports only where they are emitted
cmmNativeGens now forces and keeps a procedure's imported symbols only
where makeImportsDoc emits them, where needImportedSymbols holds.
The compiler allocates less:
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1 allocation, a sample of tests | -0.029% (under threshold, still important) |
| stage 2 allocation, a sample of tests | -0.029% (under threshold, still important) |
cmmNativeGens forced the imported symbols of each procedure, rendered
as text, to avoid a space leak, and kept them for makeImportsDoc, which
emits them only where needImportedSymbols holds; on x86-64 Linux
that takes -dynamic -fno-PIC. Where needImportedSymbols does not hold,
cmmNativeGens now neither forces nor keeps them. The generated code
is the same, also under -dynamic, -fPIC and -dynamic -fno-PIC.
The stage-1 compiler saves the most compiling perf/compiler's T9961
at -O0, where it allocates 0.16% less. Four cells of A2T's groups, all
Shaped's, run up to 0.218% more instructions,
Shaped/force/large/window/Unboxed the most, a cell that moves by as much
at commits that change no code.
Assisted-by: Claude Opus 5.5
- - - - -
51e41e72 by Mikolaj Konarski at 2026-11-26T23:24:27+01:00
Copy no register list in x86's mkRU where every register counts
x86's mkRU now returns an instruction's register list unchanged where
regUsageOfInstr's filter keeps every register in it, rather than a copy.
The generated code is the same, and the compiler runs fewer
instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.271% |
regUsageOfInstr on x86 and x86-64 filtered both of an instruction's
register lists, keeping the virtual registers and the real ones
an allocator may hand out (interesting), and so copied both lists
for every instruction. mkRU now returns a list unchanged where every
register in it is kept. Sylvain Henry's MR 16843 (ISSUE 28008) overlaps
with this commit: MR 16843's register usage DSL tests each register
as it adds it, but copies a list of registers it is given as it tests
them, where this commit returns such a list unchanged when every
register in it is kept.
The stage-1 compiler allocates less at every compile of the sample,
the most compiling MR 16269's CmmDiamondChain: 3.7% less at -O0 and 3.3%
less at -O1 and -O2. In the groups of orthotope's A2T benchmark
summed:Dynamic/append.emptyR/large/strided/boxed takes 4.5% fewer
instructions a call, a cell that moves by as much at commits that change
no code.
Assisted-by: Claude Opus 5.5
- - - - -
5d648b32 by Mikolaj Konarski at 2026-11-26T23:24:28+01:00
Mark the registers an instruction clobbers allocated, free or not
The linear allocator now marks the registers an instruction clobbers
allocated through a method of its free-register class, which on x86-64
marks every one of them, free or not, and no longer lists the free
registers of every class for each instruction that writes a real
register. The free registers after a clobber are the same on every
target, and so is the generated code on x86-64; the compiler runs fewer
instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.525% |
| stage 2, nofib -O0 | -0.204% |
clobberRegs marked allocated those of the registers an instruction
clobbers that were free, listing the free registers of every class
for each instruction that writes a real register, with its own copy
of allFreeRegs from GHC.CmmToAsm.Reg.Linear.FreeRegs, and looking each
clobbered register up in the list. The FR class now has frClobberRegs,
which marks the clobbered registers allocated: by default those of them
that are free, by allFreeRegs, as clobberRegs did, since on AArch64,
RISC-V and LoongArch allocateReg panics on a register already allocated;
on x86-64, whose allocateReg marks a register that is not free
as it marks a free one, it marks every one of them, listing nothing.
clobberRegs calls it, and GHC.CmmToAsm.Reg.Linear no longer imports
the register class modules that only the copy used.
The stage-1 compiler saves the most compiling perf/compiler's T9961
at -O0, where it allocates 1.2% less and runs 4.5% fewer instructions;
at -O and -O2 it allocates at most 0.13% less compiling the perf tests,
T12707 the most, and 0.49% less compiling MR 16269's CmmDiamondChain.
Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.FreeRegs allocates 73% more (0.489 against
0.283 GB). Of the programs, A2T's summed:Shaped/liftA2/large/flip/boxed
runs 3.7% more instructions, by a step that comes and goes across
the series. Vector's (next|prev)Permutation baseline for *Bijective
takes 0.10% fewer instructions at -O1, a benchmark that moves both ways
by as much from commit to commit.
Assisted-by: Claude Opus 5.5
- - - - -
dc18aae5 by Mikolaj Konarski at 2026-11-26T23:24:28+01:00
Keep an instruction's register usage in its liveness
The register usage the liveness pass computes for each instruction
is now kept in the instruction's liveness, and the forward walk and both
allocators, which computed it again, use the kept usage; the linear
allocator also patches an instruction's registers without building a map
for it. The generated code is the same, with the linear allocator
and with -fregs-graph, and the compiler runs fewer instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.818% |
| stage 2, nofib -O2 | -0.230% |
| stage 2, nofib -O1 | -0.214% |
| stage 2, nofib -O0 | -0.495% |
The liveness pass's backward walk computes the register usage of every
instruction it annotates (regUsageOfInstr), and its forward walk
(livenessForward), the linear allocator's genRaInsn and the graph
allocator's spill cost (slurpSpillCostInfo) and spiller (regSpill_instr)
computed it again. Liveness now keeps it (liveUsage), and those use
the kept usage instead. patchRegsLiveInstr, which only the graph
allocator reaches, computes the patched instruction's usage again,
as an instruction's usage can depend on whether its registers are equal:
x86's VXOR of a register with itself into itself reads nothing. A new
Note in GHC.CmmToAsm.X86.Instr, [What x86's regUsageOfInstr reports],
lists that case with the others where the usage differs from what
the processor reads and writes. This commit overlaps with Sylvain
Henry's MR 16843 (ISSUE 28008), which keeps the usage in the liveness
annotation too and also builds it more cheaply in every backend, but has
neither that Note nor the two changes to genRaInsn below; MR 16843
was read before this commit was written.
genRaInsn also takes the list of the virtual registers an instruction
reads as it is built, where master passed it through nubOrdOn to remove
repeats: a register read twice is found at its second lookup
in the register its first gave it, so that the instruction is patched
alike, and Data.Containers.ListUtils is no longer imported. It also
patches an instruction's registers without master's patch_map, a UniqFM
that listToUFM built for every instruction from the virtual registers
the instruction reads and writes, paired with the real registers
allocated to them: patchLookup returns, by unique, the register
of the last written pair whose vreg is the one it is given, or else
of the last read one, the entry listToUFM kept.
The stage-1 compiler allocates less at every compile of the sample,
the most compiling perf/compiler's T3294: 3.8% less at -O0 and 1.4% less
at -O. The stage-2 compiler, though it runs fewer instructions there
too, allocates 0.52% more compiling MR 16269's CmmDiamondChain at -O0
and 0.46% more at -O1 and -O2. Of the programs, vector's
(next|prev)Permutation baseline for *Bijective at -O1 runs 0.104% more
instructions, a benchmark that moves both ways by as much from commit
to commit.
Assisted-by: Claude Opus 5.5
- - - - -
bd66a1a8 by Mikolaj Konarski at 2026-11-26T23:24:29+01:00
Walk a block of a cyclic SCC again only when its successors change
A cyclic SCC's liveness now walks a block again only when the registers
live on entry to one of its successors in the SCC, or their formats,
have changed since its last walk, where it walked every block of the SCC
again until no whole block map changed, and it carries the registers'
formats through. This fixes ISSUE 27619 and does what ISSUE 27437 asks.
The generated code is the same outside SIMD code, and the stage-1
compiler runs fewer instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -12.810% |
livenessSCCs annotated the blocks of a cyclic SCC by walking all of them
again until the registers live on entry to every block stopped changing,
comparing two whole block maps as lists after each round. livenessCyclic
now walks a block again only when the registers live on entry to one
of its successors in the SCC, or their formats, have changed since
its last walk. A block walked again takes each instruction's usage
from its last walk (livenessBlockAgain), and master's liveness1 hands
the usage it computes to liveness1U, which the two share. The old loop
compared only which registers are live (the Eq of Regs ignored formats),
so it could stop before a wider format had reached every block
of the SCC, though rule (FmtBwd1) of Note [Register formats in liveness
analysis] takes the larger format going backwards; the new one carries
formats through as well, and Regs' Eq now compares them too. This fixes
ISSUE 27619 and does what ISSUE 27437 asks: the walk itself finds
the changes, and no whole block map is compared. Two vector formats
of a register are now compared by width where the liveness join keeps
the wider (compareFormats) and where a write kills a vector value
no wider than the format written. This commit overlaps with MR 16537,
Simon Jakobi's, which fixes both issues by iterating the fixpoint
over the SCC's blocks until the formats of the registers live on entry
converge. An earlier version of MR 16537 also removed the derived Ord
of formats, comparing them by width, and this commit follows
that version in comparing vector formats by width and takes
its regression test T27619 unchanged; it follows MR 16537 in carrying
the formats through, and walks again only the blocks whose successors
changed where MR 16537 walks every block of the SCC each round.
The liveness join keeps the wider of two vector formats of a register:
compareFormats, in GHC.CmmToAsm.Reg.Regs, compares two vector formats
by width, and two vectors of one width, as every other pair, by Format's
derived Ord, so that the order stays total. minusCoveredRegs lets
a write kill a vector value no wider than the format written,
and master's shrinkingRegs, which nothing calls, is deleted.
In liveness1U, delCoveredRegs, new in GHC.CmmToAsm.Reg.Regs and sharing
minusCoveredRegs' test of whether a write kills a value, takes
the registers an instruction writes out of the live set without building
their set, where master's liveness1 built it by mkRegsMaxFmt
for minusCoveredRegs. The derived Ord, which ISSUE 27619 also notes,
ranks a vector by its number of elements before their format: by it,
the join could keep a register read at two vector formats
at the narrower, and a write at the narrower kill a value live
at the wider, cases no x86 input was found to reach, and a write killed
no value live at a format of its width ranked above its own. The new
unit test testFormatWidths, in regalloc_unit_tests, checks the join both
ways and the kill between formats of different widths and of one;
it fails without the width comparison.
The generated code is the same on every program measured outside SIMD
code. Vector's (next|prev)Permutation baseline for *Bijective takes
0.067% fewer instructions at -O1, a benchmark that moves by as much
at commits that change no code. Of perf/compiler's T3294, T12707, T783
and T9961, only T9961 at -O has a cyclic SCC, and the stage-1 compiler
allocates 0.028% less compiling it; compiling nofib's programs at -O2,
the stage-2 compiler allocates 0.32% less in geometric mean and up
to 4.2% less (spectral/puzzle). Compiling MR 16269's CmmDiamondChain,
the stage-1 compiler allocates 36.3% less at -O0 and 31.9% less at -O1
and -O2. On the nest scaling probe at -O1 and -O2 the compiler allocates
less at every size, 9.6% less at N = 50, but its saving shrinks at every
doubling of N, to 5.2% at N = 400. Compiled by the boot compiler, GHC
9.12.4, GHC.CmmToAsm.Reg.Liveness allocates 23% more (2.312 against
1.886 GB) and GHC.CmmToAsm.Reg.Regs 12% more (0.208 against 0.186 GB).
In SIMD code, of the testsuite's simd tests compiled at -O1 and -O2,
with and without -mavx2, int32x4_basic and word32x4_basic,
with and without _baseline, lose a register move without -mavx2
to the width comparison: SSE2's Int32X4 insertion writes at VecFormat 4
FmtInt32 registers it reads at VecFormat 4 FmtFloat, so that
by the derived Ord the write killed nothing and those registers
were live into the procedure. int8x16_arith and word8x16_arith differ
in a symbol's name only, and every other test that compiles gives
the same code, as nofib's multiplier, primes, puzzle and para do.
Compiling perf/compiler's T3294, T783, T12707 and T9961, MR 16269's
CmmDiamondChain and nofib's puzzle at -O0, -O1 and -O2, the width
comparison changes the compiler's instructions and allocation hardly
at all.
livenessCyclic takes the blocks to walk highest position in the SCC
first. With them taken in the order queued, the compiler ran 4.3% more
instructions and allocated 5.5% more compiling CmmDiamondChain at -O0,
and 3.6% and 4.5% more at -O1 and -O2; with the lowest taken first, 5.7%
more instructions at -O0.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
40cf75ab by Mikolaj Konarski at 2026-11-26T23:24:30+01:00
Fill in liveBorn only for the graph allocator and -ddump-asm-liveness
The registers born at each instruction (liveBorn), which only the graph
allocator and -ddump-asm-liveness use, are now found by a pass of their
own that only those run, where the liveness pass found them for every
instruction of every procedure. The generated code is the same,
with the linear allocator and with -fregs-graph, and the compiler runs
fewer instructions:
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.300% |
| stage 2, nofib -O0 | -0.211% |
The liveness pass recorded, for every instruction, the registers born
there (liveBorn), which costs a forward walk over every instruction
of every block. Only the graph allocator and -ddump-asm-liveness use it.
regLivenessBorn is now a pass of its own, which the graph allocator,
its iterative variant included, runs on its input and again after
recomputing liveness, and which CmmToAsm runs only for the dump.
The stage-1 compiler allocates less at every compile of the sample,
the most compiling perf/compiler's T3294: 2.5% less at -O0 and 0.91%
less at -O; with -fregs-graph it allocates up to 0.3% more (T9961
at -O0). Of the programs, vector's (next|prev)Permutation baseline
for *Bijective at -O1 runs 0.068% more instructions and A2T's
summed:Dynamic/append.emptyR/large/strided/boxed 4.8% more, a benchmark
and a cell that move by as much at commits that change no code,
and A2T's Shaped/force.window/large/bcast/Storable 0.251% more. Cells
of A2T's groups over large Unboxed and Storable arrays take up to 0.488%
fewer, Shaped/force/large/window/Unboxed the most, a cell that moves
both ways by as much from commit to commit.
Figures that the per-commit measurements do not cover were measured
on earlier forms of the series.
Assisted-by: Claude Opus 5.5
- - - - -
249b49fb by Mikolaj Konarski at 2026-11-26T23:24:30+01:00
Prefer the register a vreg is moved into where it dies
The linear allocator now prefers, for a vreg, the real register
the current block moves it into where it dies, ahead of the register
the vreg was first recorded in on entry to a block, so that a value
computed into a vreg that the block then moves into R1 is computed in R1
and the move is dropped. This applies on every target the linear
allocator serves; the figures are x86-64's, and every benchmark suite
measured, and the stage-2 compiler, run fewer instructions:
| | against the parent |
|--------------------|-------------------:|
| nofib -O2 | -0.256% |
| nofib -O1 | -0.257% |
| nofib -O0 | -0.723% |
| containers -O2 | -0.401% |
| containers -O1 | -0.353% |
| megaparsec -O2 | -0.487% |
| megaparsec -O1 | -0.513% |
| vector -O2 | -0.267% |
| vector -O1 | -0.189% |
| A2T full | -0.550% |
| stage 2, nofib -O2 | -0.385% |
| stage 2, nofib -O1 | -0.400% |
| stage 2, nofib -O0 | -0.638% |
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.
Measured against the parent commit, in instructions: of nofib's
programs, wave4main takes 2.2% fewer at -O2 and -O1 and clausify 2.4%
fewer at -O0, none as much as 0.2% more; of vector's benchmarks, next-
and prevPermutationBijective take 1.4% and 1.0% fewer at -O2 and -O1,
none as much as 0.05% more; of containers', tree Foldable.elem.bin takes
4.1% fewer at both levels, and of megaparsec's, skipSomeTill 1.3%
and endBy1 1.2% fewer at -O2, none as much as 0.1% more beyond their
noise. In orthotope's A2T benchmark, compiled at -O1, 23172 of the 36818
cells take 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.20% more compiling T783 and 0.100% more compiling T12707 at -O0,
and 0.007%, 0.007% and 0.049% more compiling nofib's programs at -O2,
-O1 and -O0 (geometric means).
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. Between two counts of one binary, the series' end's, these six
move by more than that, so one count does not tell their rises
from the count's spread.
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
- - - - -
99bdefcd by Mikolaj Konarski at 2026-11-26T23:24:31+01:00
Prefer the register a later block moves a vreg into where it dies
The linear allocator now prefers, last, for a vreg computed blocks
earlier, the real register a block the vreg is live into moves
it into where it dies, such as R1 for a value evaluated some blocks
after it is computed. The preference is not taken from the blocks
that follow a failed heap or stack check, nor where the register is live
together with the vreg, nor where another vreg of the block claims it;
and where no preference is free, the free registers the block moves
another vreg into are left out while others remain. This applies
on every target the linear allocator serves; the figures are x86-64's.
Every suite measured runs fewer instructions, and the stage-1 compiler
runs more:
| | against the parent |
|----------------------------|-------------------:|
| nofib -O2 | -0.271% |
| nofib -O1 | -0.273% |
| nofib -O0 | -0.245% |
| containers -O2 | -0.697% |
| containers -O1 | -0.833% |
| megaparsec -O2 | -0.198% |
| megaparsec -O1 | -0.531% |
| vector -O2 | -0.260% |
| vector -O1 | -1.037% |
| A2T groups | -0.431% |
| stage 1, a sample of tests | +0.332% |
| stage 2, nofib -O2 | -0.228% |
| stage 2, nofib -O1 | -0.236% |
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 used
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 MR 16269's 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; 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.
Measured against the parent commit, in instructions: of nofib's programs
none takes as much as 0.2% more beyond their run-to-run noise,
and fannkuch-redux moves by no more than its noise, though its object
at -O2 grows 0.48%; of vector's benchmarks, generateIO takes 3.9% fewer
at -O2 and generateStateUnfold 6.3% fewer at -O1, none more but leaffix
at -O1, 0.47% more; of megaparsec's, skipCount 0.86% and choice 0.58%
fewer, none more beyond their noise at -O2; of containers', intset
fromAscList:sparse:fusion 6.1% and intmap symmetricDifference up to 5.4%
fewer at -O2, and intmap insertWith empty 7.3% fewer at -O1.
No benchmark's allocation changes beyond nofib's run-to-run noise.
Counting the failure blocks' moves, the stage-1 compiler allocates 0.26%
more compiling perf/compiler's T3294 at -O0, 0.30% more compiling
T12707, 0.25% more compiling T783, and 0.24% more compiling T9961;
leaving them out takes back half or more of each. Compiling
CmmDiamondChain at -O1 and -O2, it allocates 0.16% more.
Its instructions rise the most compiling T12707 at -O0, by 0.85%.
The stage-2 compiler allocates up to 0.33% more at the same compiles
(T12707 at -O0), 0.24% more compiling nofib's programs at -O0, up
to 0.41% more (real/parser), and 0.35% more compiling spectral/puzzle
at -O2. Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear allocates 99% more (5.100 against 2.562 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.49%
more: its loop's join fixup, a cycle through the C stack that exists
because the block the garbage collector returns to fixes 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 at -O2, 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 uses, so that moves
on every edge remain, and intmap index 0.54% more, and in orthotope's
A2T benchmark sumA 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, loading A2T's element straight into R1. vector's
listRank takes 2.0M more instructions at -O1, under vector's threshold,
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 runs more 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.86% to 1.09%
more, Shaped's by a register move more an element in OpsShaped's loop,
and convert.g and convertE.g over small strided boxed arrays, 6.0%
to 6.3% more: on an earlier form of the series, taking out both
of this commit's changes to firstFreeInOrder's choice, the last
preference and the free registers it leaves out, reverted the 14 cells
of the benchmark's sample that rose, these among them, and gave back 509
of the 569 that fell. 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.
Other rows of this change rise too. In the groups of orthotope's A2T
benchmark, fromList and fromList.map over large strided Storable arrays
take 2.2% to 2.6% more, some cells of sumA, productA, anyA, allA
and toUnorderedVectorListT over empty arrays, and Shaped's sumA
over small broadcast boxed ones, two instructions a call more, summed
generate over large strided Unboxed arrays 0.90% more, Dynamic's
rotate.inner over large bcastmid Storable arrays 0.61% more
and Dynamic's rerank2 over large dense boxed arrays 0.27% more;
containers' map fromListWithKey-asc:fusion takes 0.49% more at -O2.
In the groups of orthotope's A2T benchmark
summed:Dynamic/append.emptyR/large/strided/boxed takes 4.6% fewer
instructions a call, a cell that moves by as many instructions
at commits that change no code.
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
- - - - -
75d3bac7 by Mikolaj Konarski at 2026-11-26T23:24:32+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, stack layout now puts a proc point's reloads after the unwind
that starts the block's middle, so that they run under the block's own
Sp rule and not under that of the block laid out before it, which left
the unwind tables wrong at return points compiled at -O0. Without -g
the code is the same.
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. Vector's
(next|prev)Permutation baseline for *Bijective takes 0.068% fewer
instructions at -O2, a benchmark that moves both ways by as much
from commit to commit.
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.010%, 0.010% and 0.008% fewer
instructions; the other compile-cost cells change by at most 0.004%
in instructions, and its allocation moves by at most 0.008% in every
cell.
Assisted-by: Claude Opus 5.5
- - - - -
f462f3c1 by Mikolaj Konarski at 2026-11-26T23:24:33+01:00
Allocate the blocks the garbage collector returns to last
linearRA_SCCs now allocates the blocks the garbage collector returns
to after a failed heap or stack check, and any SCC only they lead to,
after the other blocks, so that the hot path, and not such a return
block, fixes the registers of the block that made the check.
That removes the fixup block containers' map alter ran at every level
of an insertion, and the benchmarks run fewer instructions overall;
the new order also makes some loops move values between registers where
they did not, named below. With the return blocks last, firstFreeInOrder
passes over a vreg's first-used register for a wide destination where
that register has become another value's; genRaInsn reloads a vreg
that an instruction only moves, where it dies, straight into the move's
destination where that register is free by then; and process
and genRaInsn build less.
| | against the parent |
|----------------|-------------------:|
| containers -O2 | -0.219% |
| containers -O1 | -0.271% |
| megaparsec -O2 | -3.442% |
| megaparsec -O1 | -0.850% |
| vector -O2 | -1.207% |
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, fixes
the registers and the return block's jump goes through 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
runs 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, where a block reloads a value,
the vreg's first-used register, the one the first assignment recorded
with the vreg gave it, can 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), which take each block's jump targets from a map
that linearRegAlloc' builds once for the procedure (jumpSuccs). 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 ran 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 stop after
64 blocks (liveWalk), a cap tested after whether the next block
is visited 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. Against the parent,
on the scaling probe of such branches (stale) compiled at -O0,
the compiler's allocation grows faster with N, the cost of the stale
walk: 2.3% more at N = 50 and 7.9% more at N = 400; the assembly is 100
to 170 lines smaller there, and 84 lines smaller, at every N,
on its variant with a further branch before each (staleh). 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 at -O2 (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 maximumOn 17% fewer at -O2 and minimumOn 15%;
megaparsec's endBy 22% fewer at -O2 and skipMany 16%; fannkuch-redux
moves by no more than its noise. containers' intset fromList:worstCase
takes 8.2% fewer at -O2, 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 1.6% less compiling perf/compiler's T3294
at -O0, and 0.42% and 0.31% less compiling T12707 and T9961 at -O0,
and at most 0.034% more in any cell, MR 16269's CmmDiamondChain's
included; the stage-2 compiler allocates 0.073%, 0.071% and 0.22% 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 20.6% more (6.153 against 5.100 GB)
and GHC.CmmToAsm.Reg.Linear.Base 15.6% more (0.588 against 0.508 GB).
At -O1, vector's permutation benchmarks take 4.65% to 5.26% more,
quickhull 2.3% more and nofib's knights 0.52% more, and in orthotope's
A2T benchmark reduce over small dense boxed arrays 3.4% to 6.3% more:
in their loops another predecessor now fixes 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. In A2T's groups, Ranked's
and Dynamic's summed generate.scalar over strided Storable arrays take
1.6% more, a swap through the C stack and two moves into R1's %rbx
at a join once a call, of which that commit takes back four of the six
instructions a call.
The other rises are the deferral's price, and leaving the deferral out
reverts them. The blocks the garbage collector returns to now run
the moves into the registers the hot path fixed, by design: containers'
main426, $wascLinkTop and $sgo2 run more instructions a call at -O1;
and megaparsec's many runs 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-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
fixes 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, Shaped's unravel.one and unravel
over small arrays take three instructions a call more (unravel.one
over small dense arrays 0.72%), each back at the parent's count
with the deferral left out, unravel.one storing a value to the C stack
and reloading it and moving a register once more a call; against
the deferral left out, 19 cells of the sample take more and 156 fewer.
A2T's rotate.inner over large bcastmid Storable arrays takes 1.6%
to 1.9% more, its loop reassigned. In vector's findIndexR, which takes
3.2% more at -O1, the procedure's entry now fixes 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.94% to 0.96% more, a move an element: the hot path, now allocated
before the block the garbage collector returns to, takes the first free
register for a value that the join's recorded assignment holds
in another. 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.
Other rows rise with this change too: sequence's adjust.10 1.9% at -O2
and 1.3% at -O1, and adjust.100 and adjust.1000 at -O1; map
fromDistinctAscList at -O2; in A2T's sample, Shaped's reduce over small
dense Unboxed arrays, one instruction a call more (two in the groups);
in A2T's groups, besides the rows above, many operations over boxed
arrays, most of them large, and some over Storable and Unboxed ones;
nofib's objects, paraffins's the largest, 0.83% larger at -O1 and 0.40%
at -O2; and the reproducers of ISSUE 27799, compiled to up to 3.4% more
instructions at -O1, and of ISSUE 27742, one fused latch fewer at -O1.
Vector's (next|prev)Permutation baseline for *Bijective takes 0.068%
more at -O2, a benchmark that moves both ways by as much from commit
to commit. nofib's treejoin takes 0.22% fewer instructions at -O0,
a program that moves by as much at commits that change no code.
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
- - - - -
984e6ad0 by Mikolaj Konarski at 2026-11-26T23:24:33+01:00
Allocate a loop before a continuation that enters it
A return continuation that jumps into a loop is now allocated after
the loop, where the loop calls nothing and the registers of the block
it enters are not yet recorded, so that the loop's own edges decide
those registers and the fixup goes on the continuation's edge.
That fixes the reproducer of ISSUE 27800, whose loop no longer runs
fixup moves, and gains in vector and megaparsec at -O1 and in A2T's
groups; the deferral is a bet on how often a call path runs,
and it loses where the continuation runs at every iteration of the loop,
below.
| | against the parent |
|----------------|-------------------:|
| megaparsec -O1 | -0.171% |
| vector -O1 | -0.966% |
| A2T groups | -0.298% |
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 ran 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 then cost, through the Haskell stack,
a deferred continuation that is hot (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 runs 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 at -O2, 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 running
the fixup once a call: in orthotope's A2T benchmark convert.g over empty
strided boxed arrays takes 1.5% 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, the cells that take more against
the parent, each back at the parent's count with the toggle, include
concatOuter over small dense Storable arrays, eight instructions a call
more (0.82%), rev over small strided and dense arrays, three to five
(0.42% to 0.48%), and mapA and zipWithA.singleR over small arrays, two;
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 summed generate.scalar over strided Unboxed arrays takes 2.0%
more, and generate.scalar over strided boxed ones 1.1%, a swap through
the C stack and moves into R1's %rbx at a join once a call, six
instructions a call, of which "Order x86-64 free registers around R1
and clobbers (ISSUE 27981)" takes back the six over boxed arrays
and four over Unboxed ones.
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 holds the lines of the fixup on the cold edge out
of the continuation, a swap through a spill slot.
The test T27799, ISSUE 27799's reproducer, passes from this commit on:
compiled at -O2 with -fobject-determinism, its innermost loop's latch
is a conditional jump back, where it was a conditional jump out followed
by a jump back. The general fix is the change to block layout that "Keep
Sp put across loops and tag tests in stack layout" makes.
Measured against the parent commit, in instructions: at -O1 vector's
hybcc takes 5.9% fewer, listRank 5.8%, leaffix 3.8% and awshcc 3.2%,
and at -O2 vector's benchmarks move by no more than their noise; 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 take 0.023%
fewer at -O2 and move by less than 0.01% at -O1 in geometric mean,
the fused fromAscList rows taking 1.1% to 8.1% fewer at -O2, their 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.3% to 2.5% 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.023% more compiling
perf/compiler's T3294, T12707, T783 and T9961.
Other rows rise with the deferral too: containers' map fromListWith-asc
and fromListWithKey-asc 1.3% at -O2; maillist's object 0.47% larger
at -O1; in A2T's groups, append over empty boxed arrays 2.8% and other
cells up to 1.4%; and the reproducer of ISSUE 27981 compiled with -DINL,
one instruction more at -O1 and -O2. nofib's treejoin takes 0.27% more
at -O0, a program that moves by as much at commits that change no code,
and in A2T's groups summed:Shaped/liftA2/large/flip/boxed 3.7% more,
by a step that comes and goes across the series.
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
- - - - -
fcd2e714 by Mikolaj Konarski at 2026-11-26T23:24:34+01:00
Skip registers written before a saved value's next read (ISSUE 26631)
saveClobberedTemps no longer saves a value out of a register
that an instruction clobbers into a free register that the rest
of the block writes before it next reads the value, and where every free
register is such a one, it spills the value at once. That fixes ISSUE
26631, where simd013's value live across a C call was moved twice
and then spilled, and nofib's programs run a little fewer instructions
and their objects are a little smaller; writes in later blocks
are not looked at.
| | against the parent |
|-----------------------|-------------------------------------------:|
| nofib -O2 | -0.036% (under threshold, still important) |
| nofib -O1 | -0.024% (under threshold, still important) |
| nofib object size -O2 | -0.042% (under threshold, still important) |
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.
The test T26631, simd013's source compiled at -O, checks that the value
add7 returns in %xmm0, live across the call of sub, is spilled
from %xmm0 and not first moved to %xmm1 and %xmm2.
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 k-nucleotide takes 2.0% fewer at -O2, and no program as much
as 0.2% more; fannkuch-redux 0.32% fewer at -O2 (0.35% at -O1);
containers' benchmarks move by less than 0.01% at -O2 and at -O1, none
more beyond their noise; megaparsec's take 0.014% fewer at -O2 (string
0.17%), none more beyond their noise; 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.020% or less.
In orthotope's A2T benchmark's groups,
summed:Dynamic/update2000/large/bcast/boxed takes 12.1% more, a cell
that moves both ways by as much from commit to commit,
and summed:Dynamic/append.emptyR/large/strided/boxed 4.8% more, a cell
that moves by as much at commits that change no code.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
54fd2eee by Mikolaj Konarski at 2026-11-26T23:24:35+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 now emits, at the end of a block, an assignment
of a literal to a local register after the later assignments
that compute a value from neither that register nor the literal's,
so that the constant no longer takes a register that a computed value
is to be in at the next join. Its aim is Data.Text's UTF-8 decoding
as inlined into megaparsec's benchmarks, where megaparsec's someTill
gains now and the ASCII path is to keep its join's registers once
a later commit changes x86-64's register order.
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 ran a move a character.
At the series' end the commit gains more than below in someTill.
With its code switched off there, megaparsec's benchmarks run more
instructions, among those stable across runs by up to 1.41%
(skipSomeTill) at -O2 and 1.89% (skipManyTill) at -O1, someTill 1.26%
to 1.27% at -O2, and none fewer past their noise, while a loop
of takeWhile isNumber and foldl' over digits 1 to 4 bytes wide runs
as many instructions a character, within 0.001. On an earlier form
of the series' end, the difference in the benchmark some was
in the ASCII path, which then set the width first, as above,
and the join's fixup swapped %rbx and %r14.
Measured on x86-64 against its parent: megaparsec's benchmarks at -O2
run 0.034% fewer instructions over those stable across runs (someTill
0.72% to 0.74%), none more beyond their noise. The same loop
of takeWhile isNumber and foldl' runs 2.02 fewer instructions
a character over digits 1 byte wide (2.9%) at -O1 and at -O2,
and as many over wider ones. 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; the stage-1 compiler allocates at most 0.002% more
compiling them or MR 16269's CmmDiamondChain at any level, and up
to 0.017% less (T783 at -O0). In the groups of orthotope's A2T benchmark
summed:Dynamic/append.emptyR/large/strided/boxed takes 4.5% fewer
instructions a call, a cell that moves by as much at commits that change
no code.
Figures of variants not taken, and others that the per-commit
measurements do not cover, 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
- - - - -
8351a67b by Mikolaj Konarski at 2026-11-26T23:24:35+01:00
Prefer a loop variable's register for the value moved into it
A vreg that a block moves, where it dies, into another vreg, as a loop's
next index is moved into the index variable before the jump back
to the loop's header, now prefers the register that the assignments
of the block's jump targets give that other vreg, so that the move goes
away. containers' map lookups and lookupge-map gain most; the lookup
past a jump target not yet recorded stops one jump on, a depth
that is overfitted to the benchmarks measured.
| | against the parent |
|----------------|-------------------:|
| containers -O2 | -0.122% |
| containers -O1 | -0.117% |
| megaparsec -O1 | -0.164% |
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 a target not yet recorded jumps to, give that other
vreg, as it prefers a real register the block moves it into:
processBlock adds such moves to rc_moveDests. It looks those assignments
up once, when the block starts, taking for a target not yet recorded
those of the blocks it jumps to (viaTarget), and jumpLocRegs gives
a vreg's registers in them. 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.
Past a target not yet recorded the lookup goes one jump on
and no further, a depth overfitted to the benchmarks measured: nofib's
shootout/fasta takes 5.96% more instructions at -O1 without it, while
vector's All.leaffix and All.rootfix, which take 0.63% and 0.60% more
at -O1 than with three jumps, are traded for the simpler code
and for the compiler's speed, three jumps making the compiler run 0.013%
to 0.027% more instructions compiling nofib. These figures were measured
at the end of an earlier form of the series, against three jumps.
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' map lookup absent and alterF lookup absent take 5.2% fewer,
and lookupge-map's GE Twan 2.8% to 3.4%; megaparsec's skipMany 1.9%
fewer at -O1 and word32be 1.4% at -O2; nofib's programs, fannkuch-redux
among them, 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 allocates at most 0.041% more compiling
perf/compiler's T3294, T12707, T783 and T9961 (T9961 at -O0). Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates
16.7% more (7.697 against 6.597 GB). The reproducer of ISSUE 27799
at -O1 ends with one move between registers more at a join, and one
instruction fewer. In the groups of orthotope's A2T benchmark
summed:Dynamic/update2000/large/bcast/boxed takes 10.8% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
9cf7e5f0 by Mikolaj Konarski at 2026-11-26T23:24:36+01:00
Add a union sharing the first map's subtrees to GHC.Data.Word64Map
GHC.Data.Word64Map gains unionShared, a union that returns the first
map's subtrees themselves wherever the second adds no key to them,
and GHC.Types.Unique.Set gains unionUniqSetsShared, its form
for UniqSet, so that the next commit's regClobbers can unite sets
of registers built from one another without copying the whole set
at every union.
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 returns 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.
In orthotope's A2T benchmark's groups,
summed:Shaped/liftA2/large/flip/boxed takes 3.7% more, by a step
that comes and goes across the series.
Assisted-by: Claude Opus 5.5
- - - - -
2eb5b037 by Mikolaj Konarski at 2026-11-26T23:24:37+01:00
Order x86-64 free registers around R1 and clobbers (ISSUE 27981)
On x86-64, where none of a vreg's preferences is free, the linear
allocator now orders the free registers it takes one from: R1's
register, %rbx, last, and first the registers no instruction writes
while the vreg is live past the write, so that the vreg need not move
out of an evaluation's, a return's, a C call's or a jump's way.
In the reproducer of ISSUE 27981 this already removes the back edge's
fixups; the next commit removes the cause the issue names.
| | against the parent |
|----------------------------|-------------------:|
| nofib -O2 | -0.378% |
| nofib -O1 | -0.482% |
| containers -O2 | -0.391% |
| containers -O1 | -0.414% |
| megaparsec -O2 | -1.316% |
| megaparsec -O1 | -0.350% |
| vector -O2 | -1.274% |
| vector -O1 | -2.256% |
| A2T groups | -1.263% |
| stage 1, a sample of tests | +0.763% |
| stage 2, nofib -O2 | -0.360% |
| stage 2, nofib -O1 | -0.370% |
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 T27800, the test of ISSUE 27800,
the continuation's edge into the loop no longer swaps through a spill
slot, and T27800.stderr, which held 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 uses a second time. Only x86-64's fallback uses them,
and on the other targets RA_Context's field is empty, so that no unused
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 using 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 a target not yet recorded
jumps to (rc_jumpLocs), gives another vreg, so that the vreg does
not take a register that a jump on the way there will use for another:
a part of what ISSUE 26666 asks. processBlock now keeps
those assignments, which it looks up when the block starts,
in the allocator's context (rc_jumpLocs, in RA_Context).
A look-ahead is not taken: fallbackReg also leaving out the free
registers that the blocks up to three jumps ahead move another vreg
into where it dies. Without it intmap fromAscList:fusion takes 1.17%
more instructions at -O1, and a few other rows take more too; the whole
mechanism is traded for the simpler code and for the compiler's speed.
The figure was measured at the end of an earlier form of the series,
against that form with the look-ahead.
The masks by register number this commit adds, regClobbers' and
that of the registers in the assignments in rc_jumpLocs that fallbackReg
leaves out, assert where they are built that each number they set
is below 64: setBit sets 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; 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
a target not yet recorded jumps to (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 fewer (k-nucleotide 4.3%, fasta 2.8% and bspt 2.4% at -O2; 0.096%
at -O0), none as much as 0.2% more beyond their run-to-run noise;
fannkuch-redux 0.22% fewer at -O2; vector's benchmarks fewer at -O2
(nextPermutationBijective 4.4%, findIndexR 3.4%), none more past
its bar; containers' benchmarks fewer (intset partition 6.1%, intset
filter 5.2%, graph buildG up to 3.9%); megaparsec's benchmarks fewer
at -O2 (reachOffsetNoLine 7.6%, many up to 6.8%). Past their bars,
IntMap's union-mix rows take up to 0.43% more at -O2 and megaparsec's
endBy1 rows up to 0.42% more, and nofib's object size rises only
for hartel/parstof at -O2 and -O1 and parser at -O0, by 0.35% at most.
At -O1 intset's union and unions benchmarks take up to 0.79% more,
intmap fromAscList 0.84%, and the swapped union-disj rows of IntSet
and IntMap and intset symmetricDifference-disj_nn up to 0.50%. Vector's
(next|prev)Permutation baseline for *Bijective takes 0.069% fewer
instructions at -O1, a benchmark that moves by as much at commits
that change no code. No benchmark's allocation changes beyond nofib's
run-to-run noise. The stage-1 compiler allocates more compiling every
test of the sample: at -O0 up to 0.31% more compiling perf/compiler's
tests (T9961), and at most 0.039% more at -O and -O2. Compiling MR
16269's CmmDiamondChain, it allocates 1.4% more at -O0 and 1.2% more
at -O1 and -O2. A stage-1 compiler runs 3.0% more instructions
than the parent's compiling CmmDiamondChain at -O0 and 2.4% more at -O1
and -O2, and 1.1% more compiling T9961 at -O0, every other cell
under 1%. The stage-2 compiler likewise allocates more compiling nofib's
programs, the most compiling parser at -O0, 0.71% more. Compiled
by the boot compiler, GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 14%
more (8.79 against 7.70 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; the look-ahead
above took back intmap fromAscList's at -O1 on an earlier form
of the series. 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.14% 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. Measured with the look-ahead still
in place, before its removal, 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.95% 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.29% 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.54%
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.043%
more at -O2 by the geometric mean, 114 rising and 46 falling by 0.1%
beyond their noise (graph dfs, dff and topSort on maxDAG n=1500 1.8%).
In the sample of orthotope's A2T benchmark eight cells over small arrays
take one to five instructions a call more (0.23% to 0.56%). 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 five, Shaped's unravel.one, unravel and index,
were not traced. Of the benchmark's groups, some cells rise,
Dynamic/rerank.one/large/bcast/boxed the most, by 0.95%. 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 fallbackReg leaving out, for a vreg with preferences,
the registers the assignments in rc_jumpLocs give other vregs, a trade:
at -O0 and N=400 the stage-1 compiler allocates 3.7% more
than the parent's and runs 2.2% more instructions, 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
- - - - -
7e7d2339 by Mikolaj Konarski at 2026-11-26T23:24:37+01:00
Free every register not live into a newly reached block (ISSUE 27981)
A block reached by a first jump started with the free registers
of the jump's source block, less those of the vregs not live into it,
so that a real register still allocated at the jump and not live
into the block, R1 above all where it is allocatable, stayed allocated
there until the block wrote it and that value died: the cause ISSUE
27981 names. initBlock now derives the free registers on entry to every
block. In the issue's 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.
| | against the parent |
|----------------------------|-------------------:|
| megaparsec -O2 | -0.319% |
| megaparsec -O1 | -0.186% |
| stage 1, a sample of tests | -0.956% |
| stage 2, nofib -O0 | -0.300% |
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 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. 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, but for vector's (next|prev)Permutation baseline
for *Bijective at -O1, 0.068% more, a benchmark that moves by as much
at commits that change no code; containers' benchmarks take 0.026% fewer
at -O2 (tree edges 1.4%, graph transposeG 1.3% and buildG 1.1%), none
more beyond their noise, and megaparsec's fewer (many 1.2%), none more
beyond their noise. Of the groups of orthotope's A2T benchmark three
summed cells over large boxed arrays take more:
summed:Dynamic/update2000/large/bcast/boxed 12.7% more, a cell
that moves both ways by as much from commit to commit;
summed:Dynamic/append.emptyR/large/strided/boxed, a cell that moves
by as many instructions at commits that change no code;
and summed:Shaped/liftA2/large/flip/boxed, by a step that comes and goes
across the series. No benchmark's allocation changes beyond nofib's
run-to-run noise. The stage-1 compiler allocates less compiling every
test of the sample, of perf/compiler's tests the most compiling T9961
at -O0, 1.1% less; compiling CmmDiamondChain, it allocates 4.3% less
at -O0 and 3.6% less at -O1 and -O2.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
c1ba4245 by Mikolaj Konarski at 2026-11-26T23:24:38+01:00
Write the linear allocator's state only where it changes
The linear allocator wrote its state back, building a new RA_State, even
where nothing in it had changed: releaseRegs at every instruction,
with or without a register to release, and saveClobberedTemps at every
instruction that writes a real register, with or without a value
to save. Both now write the state only where it changes. The generated
code is the same.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -1.938% |
| stage 2, nofib -O0 | -0.289% |
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 stage-1 compiler allocates less compiling every test of the sample,
from 9.1% less (MR 16269's CmmDiamondChain at -O0) to 0.013% less
(perf/compiler's T9961 at -O). In the groups of orthotope's A2T
benchmark summed:Dynamic/update2000/large/bcast/boxed takes 11.3% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit, and summed:Dynamic/append.emptyR/large/strided/boxed takes
4.8% fewer instructions a call, a cell that moves by as many
instructions at commits that change no code.
Assisted-by: Claude Opus 5.5
- - - - -
c8e316c0 by Mikolaj Konarski at 2026-11-26T23:24:39+01:00
Find the linear allocator's spill candidates in one fold
Where no register of a vreg's class is free, allocRegsAndSpill_spill
chooses a vreg to spill by searching the assignment; it built
and searched lists for it, and now finds its candidates in one fold
over the assignment, choosing the same vreg. The generated code
is the same.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.816% |
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 stage-1 compiler allocates 9.3% less compiling perf/compiler's T3294
at -O0 and 4.0% less at -O, and less compiling T12707 and MR 16269's
CmmDiamondChain at every level; its allocation compiling T783 and T9961
moves by 0.004% or less. Though the generated code is the same, two
summed cells over large boxed arrays in the groups of orthotope's A2T
benchmark take more: summed:Dynamic/update2000/large/bcast/boxed 12.7%
more, a cell that moves both ways by as much from commit to commit,
and summed:Dynamic/append.emptyR/large/strided/boxed 5.1% more, a cell
that moves by as many instructions at commits that change no code. Cells
over large Unboxed and Storable arrays take up to 0.268% fewer,
Shaped/force/large/window/Unboxed the most.
Assisted-by: Claude Opus 5.5
- - - - -
ad992d88 by Mikolaj Konarski at 2026-11-26T23:24:40+01:00
Walk register assignments without listing them
Two walks over register assignments listed them first: clobberRegs'
over the whole assignment, at every instruction that writes a real
register, and joinToTargets_again's over a jump target's recorded
assignment and the current one. Both now work on the maps themselves,
and the generated code is the same but for the numbering of some fixup
labels.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.990% |
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 now 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 less compiling every test of the sample:
up to 0.11% less compiling perf/compiler's T3294, T12707, T783 and T9961
(T9961 at -O0), and compiling MR 16269's CmmDiamondChain 6.9% less
at -O0 and 5.6% and 5.5% less at -O1 and -O2. In the groups
of orthotope's A2T benchmark summed:Dynamic/update2000/large/bcast/boxed
takes 11.3% fewer instructions a call, a cell that moves both ways
by as much from commit to commit, and Dynamic/rerank2/large/dense/boxed
0.200% fewer, a cell that moves by as much at commits that change
no code.
Assisted-by: Claude Opus 5.5
- - - - -
e4aeddeb by Mikolaj Konarski at 2026-11-26T23:24:40+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.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.110% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.145% |
| stage 2 allocation, a sample of tests | -0.124% |
The stage-1 compiler's allocation falls the most compiling
perf/compiler's T9961 at -O0, by 0.50%, and moves by 0.001% or less
compiling T9961 at -O and -O2. Though the generated code is the same,
two cells of the groups of orthotope's A2T benchmark take more:
summed:Dynamic/update2000/large/bcast/boxed 12.7% more, a cell
that moves both ways by as much from commit to commit,
and Dynamic/rerank2/large/dense/boxed 0.20% more, a cell that moves
by as much at commits that change no code. Vector's
(next|prev)Permutation baseline for *Bijective takes 0.10% fewer
instructions at -O1, a benchmark that moves both ways by as much
from commit to commit.
Assisted-by: Claude Opus 5.5
- - - - -
fef1a657 by Mikolaj Konarski at 2026-11-26T23:24:41+01:00
Compute the dying registers and the live-in map of liveness strictly
The liveness pass left the registers that die at each instruction, which
the linear allocator forces at every instruction, and the map
of the registers live into each block as thunks; it now computes them
as it goes, but for the registers that die at a branch because they
are live into its targets only. The generated code is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.128% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.283% |
| stage 2 allocation, a sample of tests | -0.283% |
| stage 2 allocation, nofib -O0 | -0.293% |
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. The registers that die
at a branch because they are live into its targets only stay lazy:
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 stage-1 compiler's allocation falls the most compiling
perf/compiler's T3294 at -O0, by 0.77%, and rises by 0.006% or less
compiling T9961 at -O and -O2. Though the generated code is the same,
vector's (next|prev)Permutation baseline for *Bijective takes 0.10% more
instructions at -O1, a benchmark that moves both ways by as much
from commit to commit. In the groups of orthotope's A2T benchmark
summed:Dynamic/update2000/large/bcast/boxed takes 11.3% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
4d24b578 by Mikolaj Konarski at 2026-11-26T23:24:42+01:00
Skip the address registers x86's mkRU would drop
On x86 and x86-64, regUsageOfInstr listed every register an address
names, and mkRU then copied each list that held a register
the allocators do not manage, to drop it; such registers are now left
out where an address's registers are added, so that no list is copied
for them. The generated code is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.183% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.179% |
| stage 2 allocation, a sample of tests | -0.181% |
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 stage-1 compiler's allocation falls the most compiling
perf/compiler's T3294 at -O0, by 0.84%, and moves by 0.003% or less
compiling MR 16269's CmmDiamondChain.
Assisted-by: Claude Opus 5.5
- - - - -
02320d90 by Mikolaj Konarski at 2026-11-26T23:24:42+01:00
List a CFG's edges once in block layout
Block layout listed the edges of a procedure's CFG twice and kept
the edges it fuses as Sets of pairs; it now lists them once and keeps
the fused edges as LabelMaps of LabelSets. The generated code
is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.152% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.082% (under threshold, still important) |
| stage 2 allocation, nofib -O2 | -0.071% (under threshold, still important) |
| stage 2 allocation, nofib -O1 | -0.070% (under threshold, still important) |
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.
At -O and -O2 the stage-1 compiler's allocation falls the most compiling
MR 16269's CmmDiamondChain, by 0.30%; at -O0 it rises by 0.001% or less.
Though the generated code is the same, cells of the groups
of orthotope's A2T benchmark take more:
summed:Dynamic/update2000/large/bcast/boxed 12.7% more, and four large
cells over Unboxed and Storable arrays, the most
Ranked/force.rank5/large/window/Unboxed, 0.26% more, cells that move
both ways by as much from commit to commit. In the groups of orthotope's
A2T benchmark summed:Dynamic/append.emptyR/large/strided/boxed takes
4.8% fewer instructions a call, a cell that moves by as many
instructions at commits that change no code.
Assisted-by: Claude Opus 5.5
- - - - -
6800503c by Mikolaj Konarski at 2026-11-26T23:24:43+01:00
Build no lists of results in calcFreqs
calcFreqs, which static prediction runs for every procedure, built lists
of results it did not use; it now builds none, computing the same
frequencies, so that the generated code is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.072% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.065% (under threshold, still important) |
| stage 2 allocation, nofib -O2 | -0.078% (under threshold, still important) |
| stage 2 allocation, nofib -O1 | -0.075% (under threshold, still important) |
calcFreqs 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, now 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.098% less compiling
perf/compiler's T3294, T12707, T783 and T9961 (T12707); at -O0, where
static prediction is off, its allocation moves by 0.003% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.31%
less. In the groups of orthotope's A2T benchmark
summed:Dynamic/update2000/large/bcast/boxed takes 11.3% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit.
Assisted-by: Claude Opus 5.5
- - - - -
5f30e2bb by Mikolaj Konarski at 2026-11-26T23:24:44+01:00
Give back edges no bonus where static prediction estimates the weights
Under -fcmm-static-pred, on at -O1 and -O2, optHsPatterns no longer
raises the weights of back edges by backEdgeBonus, saving
the depth-first search for them: static prediction replaces
those weights where its heuristics cover a branch, and leaving the bonus
out where they do not changed no code measured.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.083% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.100% (under threshold, still important) |
| stage 2 allocation, a sample of tests | -0.121% |
| stage 2 allocation, nofib -O2 | -0.087% (under threshold, still important) |
| stage 2 allocation, nofib -O1 | -0.081% (under threshold, still important) |
optHsPatterns raised every back edge of positive weight by backEdgeBonus
(increaseBackEdgeWeight), after a depth-first search for them;
under -fcmm-static-pred 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.002% or less.
Compiling MR 16269's CmmDiamondChain at -O1 and -O2, it allocates 0.47%
less. Containers' intset union-common_ns takes 0.38% more instructions
at -O1, and summed:Dynamic/update2000/large/bcast/boxed of the groups
of orthotope's A2T benchmark 12.7% more, a cell that moves both ways
by as much from commit to commit.
Assisted-by: Claude Opus 5.5
- - - - -
bc2ab53b by Mikolaj Konarski at 2026-11-26T23:24:45+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,
building no set. The generated code is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.015% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.071% (under threshold, still important) |
| stage 2 allocation, a sample of tests | -0.072% (under threshold, still important) |
The stage-1 compiler allocates up to 0.25% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T783), and up
to 0.071% less at -O (T783). Compiling MR 16269's CmmDiamondChain at -O1
and -O2, it allocates 0.12% less.
Assisted-by: Claude Opus 5.5
- - - - -
af8a7c03 by Mikolaj Konarski at 2026-11-26T23:24:45+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, which most callers take
apart at once; inlined, it builds neither where its caller takes them
apart. The generated code is the same.
| | against the parent |
|---------------------------------------|-------------------------------------------:|
| stage 1, a sample of tests | -0.084% (under threshold, still important) |
| stage 1 allocation, a sample of tests | -0.017% (under threshold, still important) |
| stage 2 allocation, a sample of tests | -0.176% |
| stage 2 allocation, nofib -O0 | -0.164% (under threshold, still important) |
The stage-1 compiler allocates up to 0.12% less compiling
perf/compiler's T3294, T12707, T783 and T9961 at -O0 (T9961); at -O
its allocation moves by 0.017% or less. Compiled by the boot compiler,
GHC 9.12.4, GHC.CmmToAsm.Reg.Linear allocates 13% more (8.83 against
7.80 GB). In the groups of orthotope's A2T benchmark
summed:Dynamic/update2000/large/bcast/boxed takes 11.3% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit.
Assisted-by: Claude Opus 5.5
- - - - -
3a1442ed by Mikolaj Konarski at 2026-11-26T23:24:46+01:00
Swap the registers of a cyclic join fixup where one instruction can
Where the moves of a join's fixup form a cycle, handleComponent broke
it through a stack slot, with a store and a load. Where the target has
an instruction that swaps two registers of the format, on x86 and x86-64
xchg for the general-purpose registers, it now swaps them instead,
so that a cycle of n moves takes n - 1 swaps; cycles of floating-point
and vector registers still go through a stack slot.
| | against the parent |
|----------------|-------------------:|
| megaparsec -O2 | -0.382% |
| megaparsec -O1 | -0.386% |
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.007% 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. containers' benchmarks move by less than 0.1% beyond their
noise but for sequence adjust, up to 0.59% fewer (adjust.10), and graph
bcc.star,n=100, which runs 0.23% fewer at -O2; vector's quickhull runs
0.97% fewer at -O1, none of its other benchmarks moving past its bar,
and megaparsec's run fewer (skipManyTill 4.0% at -O2, endBy1 2.4%
at -O1), none more beyond their noise. In megaparsec's count, sepBy
and sepEndBy and in vector's quickhull, cycles through stack slots
become xchg instructions. Of the groups of orthotope's A2T benchmark,
305 cells take fewer instructions by 0.2% or more, the ==, /=
and compare cells over large boxed arrays the most, by 3.1% to 3.2%,
and two summed cells over large boxed arrays take more:
summed:Dynamic/append.emptyR/large/strided/boxed 5.1% more, a cell
that moves by as many instructions at commits that change no code,
and summed:Shaped/liftA2/large/flip/boxed 3.8% more, by a step
that comes and goes across the series.
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
- - - - -
6f560118 by Mikolaj Konarski at 2026-11-26T23:24:47+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.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.277% |
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 leaffix takes 5.26% fewer
at -O2 and rootfix 2.82% fewer; 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, while
summed:Dynamic/update2000/large/bcast/boxed of the groups of orthotope's
A2T benchmark takes 12.7% more, a cell that moves both ways by as much
from commit to commit. The stage-1 compiler's allocation compiling
perf/compiler's T3294, T12707, T783 and T9961 and MR 16269's
CmmDiamondChain moves by 0.005% at most. In the groups of orthotope's
A2T benchmark summed:Dynamic/append.emptyR/large/strided/boxed takes
4.8% fewer instructions a call, a cell that moves by as many
instructions at commits that change no code.
Assisted-by: Claude Opus 5.5
- - - - -
a25e58eb by Mikolaj Konarski at 2026-11-26T23:24:47+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 makes
that move through a register free at the jump, and on x86 and x86-64
also where none is free; on the other targets it still panics there,
with a message of its own.
makeMove moves the value 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 records it in the unwinding tables, which get a row at each
DELTA from an UNWIND whose label the method cannot make. The move
is rare: compiled at the series' end with one of two changes elsewhere
in the compiler, nofib's modules at -O1 and -O2 hold no XCHG
with a memory operand.
Where the jump's target holds 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
holds 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 use, 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 holds 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 end of an earlier form
of the series 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.014% more instructions (T783 at -O2) and allocates at most
0.007% more (T783 and T9961 at -O), the assembly the same in every cell;
the stage-2 compiler runs up to 0.012% more instructions compiling
nofib's puzzle (at -O2), its allocation moving by 0.0023% or less.
Compiled by the boot compiler, GHC 9.12.4,
GHC.CmmToAsm.Reg.Linear.JoinToTargets allocates 29% more (0.683 against
0.529 GB) and its object is 36% larger, the cost of makeMove's
slot-to-slot clause. The parent commit's compiler panics compiling
the battery's scaling program join at -O1 and -O2, at every size,
and this commit's compiles it. Of the groups of orthotope's A2T
benchmark, summed:Shaped/liftA2/large/flip/boxed takes 3.8% more
instructions, by a step that comes and goes across the series.
In the groups of orthotope's A2T benchmark
summed:Dynamic/update2000/large/bcast/boxed takes 11.3% fewer
instructions a call, a cell that moves both ways by as much from commit
to commit.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
ecea6fec by Mikolaj Konarski at 2026-11-26T23:24:48+01:00
Predict branches into loop heads that only a heap or stack check makes
staticBranchPrediction's loop exit heuristic, lehPredicts, returned
Nothing for a branch into a loop head that only a heap or stack check
makes, the failed check's call to the garbage collector closing
the loop; loopHeads now leaves out such heads, so that the heuristic
predicts a branch that stays in the loop by going to such a check.
As committed, with the levels limited, this shows no saving in cycles:
nofib's programs ran 0.3% more in geometric mean (below).
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.343% |
staticBranchPrediction's loop exit heuristic, lehPredicts, returns
Nothing for a branch either of whose successors is 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 lehPredicts returned Nothing for 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.
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.009% or less in geometric mean, and only intmap
fromSet past its bar beyond its noise, 1.0% fewer at -O1; object size
rises past its bar only in nofib's cse at -O2 and clausify and eliza
at -O1, by 0.24% at most, and ISSUE 27742's reproducer at -O1 has one
fused latch fewer and one latch more closed by a jump. 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.12% less compiling perf/compiler's T783
at -O and 0.062% less compiling T12707, its allocation compiling T3294
and T9961 moving by 0.012% or less; at -O0 its allocation moves
by 0.006% 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
- - - - -
cce40af4 by Mikolaj Konarski at 2026-11-26T23:24:49+01:00
NCG: invert floating-point conditional branches too
invertCondBranches turned a block's jcc next; jmp other into jncc other
only where the condition comes from an integer comparison; it now does
so where it comes from a floating-point comparison too.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.120% |
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%. vector's quickhull
runs 3.7% fewer at -O2, and in the groups of orthotope's A2T benchmark
cells take up to 11% fewer (Shaped/anyA/large/flip/Unboxed).
Assisted-by: Claude Opus 5.5
- - - - -
d502570b by Mikolaj Konarski at 2026-11-26T23:24:49+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, and sinking drops a chain of assignments that only one another
read in one pass, across blocks and loops. Nothing is folded or inlined
again.
| | against the parent |
|------------|-------------------:|
| vector -O1 | -2.065% |
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;
master's shouldDiscard, the walk's test for such an assignment,
is deleted, the walk testing its other case, r = r, by noOpAssignment.
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: at -O1 vector's sum[base]
runs 14.3% fewer instructions, map[base] 9.1% and spectral 5.0%,
and no benchmark runs more past its threshold; 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 past
its threshold, and the objects of those that move most keep their size.
containers' benchmarks at -O2 run up to 9.5% fewer, nubOrd
noFusion_repeat, issue1202_repeat 4.7%, set alterF:insert:present 2.9%
and lookupge-map GE split 0.61%, none more beyond their noise; at -O1,
of containers' objects only Data.Sequence's changes size, and two
of IntSet's benchmarks run more beyond their noise, difference-block_ns
3.2% and difference-mix_ns 0.33%. megaparsec's benchmarks at -O2 run up
to 1.0% fewer, skipManyTill, and manyTill 0.68% to 0.69%, none more
beyond their noise, and at -O1 none moves beyond its noise. Of nofib's
programs only rewrite's objects change, and no program moves past
its threshold; fannkuch-redux does not change. The stage-1 compiler
allocates up to 0.13% less compiling the sample of tests, the most
compiling MR 16269's CmmDiamondChain at -O1, and 0.11% less compiling
perf/compiler's T12707 at -O; at -O0, and compiling T9961, within 0.007%
of what it allocates at the parent commit.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
8ee30011 by Mikolaj Konarski at 2026-11-26T23:24:50+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. Keeping Sp and the slots put 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 below, the others keeping
the stores and reloads it describes. Changes to block layout's chains,
to MAYBE_GC's test in rts/include/Cmm.h, to cafAnal, to stack layout's
local liveness and to emitMultiAssign go with these, below.
| | against the parent |
|----------------------------|-------------------:|
| nofib -O2 | -3.730% |
| nofib -O1 | -4.485% |
| nofib -O0 | -0.714% |
| containers -O2 | -6.294% |
| containers -O1 | -6.801% |
| megaparsec -O2 | -6.540% |
| megaparsec -O1 | -4.871% |
| vector -O2 | -4.302% |
| vector -O1 | -10.573% |
| A2T groups | -10.051% |
| stage 1, a sample of tests | -0.253% |
| stage 2, nofib -O2 | -0.800% |
| stage 2, nofib -O1 | -1.008% |
| stage 2, nofib -O0 | -1.481% |
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 its back edges need a fixup,
and the fixup for the difference runs once, on the edge
into the loop (Note [Loop head stack maps]); a back edge reached
only through unlikely branches counts for 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, but
in the cases below, 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 Sp move and the invariants'
stores run once, on the edge into the loop (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, where for them the reloads stay
as few, 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 those stored before the test and live
across an inner loop that does not read them, 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).
The reservation leaves these cases out, each having cost 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 set up
or drop 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 advances none of the variables live at its head (assigns
none from a load, arithmetic, a literal or a foreign call's result,
or a copy of such), 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 has
its variables in other slots than the reserved frame gives them
(nofib's puzzle, 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
rejects 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
been laid out with each variable of its frame in its slot. No input
was found that lays a diamond out so. At the series' end the guard costs
the stage-1 compiler 0.0064% more instructions compiling T3294 at -O0.
Testing instead whether the continuation has a stack map, laid out
or not, changed 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 reload analyses only where the bound exceeds
the limit; 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 testing whether its continuation is on a 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 counts 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
MR 16269's CmmDiamondChain 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 loses
the retry's 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 took 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, matches exactly 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 more, as does this commit's without
the loop-head seeds or without a diamond's kept depth.
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 fails 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.8% 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.13% 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 3.3% more with boxed
elements and 1.55% to 1.56% 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
on an earlier form of the series. The trade's toggle, 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 running 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 tested 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 boxed ones 6 to 11 more and, summed,
over Storable ones 5 more, and Shaped's empty toVector
and toUnorderedVectorT cells 1 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.94% and 0.85% at -O and -O2),
0.88% and 0.56% more compiling T9961 and T783 at -O0, 0.11% more
compiling T9961 at -O and -O2, and 1.9% less compiling T3294 at -O0;
over nofib's compilations the stage-2 compiler allocates 1.8%, 1.6%
and 0.81% more in geometric mean at -O2, -O1 and -O0. Of the testsuite's
perf tests, T13960 allocates 3.16% more, T18304 2.93%, T9630 2.11%,
T18698b 1.58%, T18698a 1.47% and T12707 1.30%, past CI's windows,
and T3294 1.96% less, past its window too. Compiling CmmDiamondChain,
the stage-1 compiler allocates up to 0.060% less and runs 0.85% to 0.89%
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 9.0% more
compiling puzzle at -O2), goes with the size trade, the passes after
layout working on the larger code. Over nofib the stage-2 compiler runs
fewer instructions, but more compiling some programs, puzzle the most,
5.9% more at -O2, and sphere and fluid next.
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 and no third runs,
or the third's do not, the heads whose seeds held in that run 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
treats 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:
of nofib's programs gen_regexps takes 34% fewer, queens 24% and bspt 20%
at -O2, and k-nucleotide 40% at -O1, and some take more, tak the most,
1.45% at -O0, and life 1.31% at -O0 and 1.32% at -O1 and -O2, with ansi
and atom at -O1 and -O2 and multiplier at -O1. containers' graph
dfs.maxDAG,n=15 takes 36% fewer, and intmap's cps folds take 0.94%
to 1.01% more at -O2 and -O1, and sequence fromFunction.ix10000/5000
0.99% more at -O2 and -O1. megaparsec's reachOffsetNoLine takes 23%
fewer at -O2 and string' 13% at -O1, and vector's minimumOn 31%,
no benchmark of either package more beyond its noise. 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. Of A2T's groups, besides
those and window.zero, Shaped's toUnorderedVectorListT over empty arrays
takes 2 to 3 more a call, and summed, it and Shaped's sumA, productA,
anyA and allA over empty arrays 1 more; and a few cells over large boxed
arrays take more, convertE.unboxed over flipped and broadcast ones 3.6%
and 3.1%, and summed:Dynamic/stretch/large/scaled/boxed 10.6%
and summed:Dynamic/append.emptyR/large/strided/boxed 5.0%, cells
that move by as many instructions at commits that change no code,
and summed:Shaped/liftA2/large/flip/boxed 3.4%. 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 323% more (7.98 against 1.89 GB) and GHC.Cmm.Pipeline 55% more
(0.770 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.8%, 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. Of the battery's
issue reproducers, the assembly of ISSUE 8905's, ISSUE 10606's, ISSUE
21084's and ISSUE 26433's now has an inner loop, closed by a jump, where
it had none, and the code of most of those whose code changes grows,
by up to 49 instructions in ISSUE 27742's at -O1; each of their loops
whose instructions an element move takes 31% to 58% fewer. Vector's
(next|prev)Permutation baseline for *Bijective takes 0.10% fewer
instructions at -O2, a benchmark that moves both ways by as much
from commit to commit.
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
- - - - -
7a16ce85 by Mikolaj Konarski at 2026-11-26T23:24:51+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".
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. Where the variable is dead, it is saved
in place of the fields only under the rules below, and a function
closure's free variables count as an alternative's fields. None
of it runs but under -fcmm-sink and over Cmm generated from STG.
| | against the parent |
|--------------------|-------------------:|
| nofib -O2 | -0.397% |
| nofib -O1 | -0.527% |
| containers -O2 | -0.673% |
| containers -O1 | -0.899% |
| megaparsec -O2 | -1.326% |
| megaparsec -O1 | -2.220% |
| stage 2, nofib -O2 | -0.379% |
| stage 2, nofib -O1 | -0.399% |
| stage 2, nofib -O0 | -0.377% |
This commit's code lies outside GHC.CmmToAsm, which it changes only
in a comment and in its README: among what it changes are 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.
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 needed 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.2% fewer instructions
and 0.46% less allocation compiling puzzle at -O1. 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; the intmap fromList and fromListWith
benchmarks over random duplicate keys, 0.14% to 0.23% more at -O2
and 0.17% to 0.21% more at -O1, the trade of sinking below; megaparsec's
scientific benchmarks, 0.17% to 0.24% more at -O2 and 0.11% to 0.86%
more at -O1, and reachOffsetNoLine 0.49% more at -O1; in orthotope's A2T
benchmark, reshape cells of 316 to 1275 instructions a call, two to six
more (0.28% to 1.9%), stretchOuter cells one more (0.23% to 0.25%),
and two small update2000 cells six more; and the stage-2 compiler's
allocation compiling nofib's sphere and sorting at -O2, 0.24% and 0.22%
more. Vector's (next|prev)Permutation baseline for *Bijective takes
0.10% more at -O2, a benchmark that moves both ways by as much
from commit to commit, and A2T's large cells over runs, window
and bcastmid views, some of them reshape's, 75 to 162 more a call (0.22%
to 0.57%), are, but for Dynamic's force.narrow over runs, cells
that move by as much at commits that change no code or both ways
by as much from commit to commit.
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 allocated within 0.03% of what
the series' end then allocated 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: not saving the constructor in place
of its fields where a loop before the call used three of four fields
cost two instructions a call, and in loop-free code not saving it 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 MR 16269's 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.073% more instructions and allocates 0.020% less compiling
perf/compiler's T12707 at -O, whose assembly changes, and 0.067% more
and 0.021% less at -O2; compiling T3294 it runs 0.003% fewer
instructions at -O and 0.001% more at -O2 and allocates 0.025%
and 0.022% less, and it runs 0.15% fewer instructions compiling
CmmDiamondChain at -O1 and -O2, their assembly unchanged; and for T9961
at -O and -O2 its instructions and allocation move by 0.005% or less,
while it runs 0.079% to 0.091% fewer instructions and allocates 0.13%
to 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.45 against 7.98 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 its figures with the analysis, 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.29% fewer instructions
compiling T9961, 0.14% fewer for T12707, 0.29% fewer for T783, 0.17%
fewer for CmmDiamondChain and 0.025% fewer for T3294, and allocates
0.087% to 0.55% 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
- - - - -
13bb0647 by Mikolaj Konarski at 2026-11-26T23:24:51+01:00
Jump conditionally to a likely false comparison's false target
Where neither jump of an integer comparison likely false falls through,
the conditional jump now goes to the false target and the unconditional
one to the true target. Containers' IntMap fromSet rows take fewer
instructions, and no total of a suite moves by its threshold.
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 passes over 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.054% 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
- - - - -
03011e26 by Mikolaj Konarski at 2026-11-26T23:24:52+01:00
Add an estimate of block frequencies for the linear allocator
The linear allocator gets an estimate of how often each block
of a procedure runs, made from the native CFG before allocation.
This commit only adds it, as blockFrequencies, which nothing calls yet,
and no total of a suite moves by its threshold.
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 require every edge's target to be a node of the CFG, which
a debug compiler asserts: getCfg makes a node of every block it reaches,
and later code 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
- - - - -
15c2091f by Mikolaj Konarski at 2026-11-26T23:24:53+01:00
Use block frequencies to order the linear allocator's SCCs
Where block frequencies are estimated, as on x86-64
under -fcmm-static-pred, the linear allocator now allocates
a procedure's SCCs in an order computed from the estimate and the jumps,
so that a hotter block, allocated earlier, fixes the registers at a join
and a colder one runs the moves. Instructions fall past their thresholds
in every benchmark suite, at the cost of rises at some joins
and in loops closed through a call, a trade described below.
| | against the parent |
|----------------|-------------------:|
| nofib -O2 | -0.330% |
| nofib -O1 | -0.285% |
| nofib -O0 | -0.532% |
| containers -O2 | -0.463% |
| containers -O1 | -0.505% |
| megaparsec -O2 | -0.399% |
| megaparsec -O1 | -0.241% |
| vector -O2 | -0.357% |
| vector -O1 | -0.572% |
| A2T groups | -0.838% |
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 is hottest by the estimate 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 set aside, 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 goes through 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 that branch compiling the test's procedure
and never 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.33 and 2.23, 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 runs 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 value 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.
Against its parent, the largest falls are in orthotope's A2T benchmark,
whose convert.unboxed and convertE.unboxed cells over boxed arrays take
up to 22% fewer instructions a call in its sample and 63% fewer
in its groups; in the groups summed:Dynamic/stretch/large/scaled/boxed
takes 9.6% fewer instructions a call, a cell that moves by as many
instructions at commits that change no code. No program's allocation
moves by 0.2%, and nofib's objects take 0.35% and 0.37% fewer bytes
at -O2 and -O1, puzzle's 0.36% 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.3% 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.21% to 0.90% more at -O1 and -O2, a continuation's reloads
landing in other registers, and containers' fromAscListWithKey
and fromDescListWithKey, 0.37% more at -O2, and map alterF's lookup
present, 0.79% and 0.39% more at -O2 and -O1, and lookup absent, 0.36%
more at -O1, take a move or a shuffle more at a join. Containers' map
fromListWith-asc:fusion and fromListWithKey-asc:fusion take 1.5% more
at -O2 and map fromDistinctDescList:fusion 0.85% more there,
megaparsec's sepBy and sepBy1 0.37% to 0.40% more at -O1 and reachOffset
0.67% to 0.94% more at -O2, vector's hybcc 0.11% more at -O2, nofib's
puzzle 0.60% and mandel2 0.37% more at -O2 and cacheprof 0.39% more
at -O1, the stage-2 compiler's allocation 0.37% more compiling puzzle
and 0.22% more compiling clausify at -O2, and cells of orthotope's A2T
benchmark, up to 1.0% more in its sample (Dynamic's ==.units over small
strided Unboxed arrays) and up to 1.8% in its groups (append over empty
strided Unboxed arrays), where most are comparisons by == and /=.
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.2% more at -O2 and -O1, 1.3% with the SCCs
hotter first, fasta 1.5% more at -O1 and cacheprof 0.40% more at -O2,
neither rising with them, containers' intset fromList:asc:sparse:fusion
1.9% more at -O2, not moving with them, and megaparsec's scientific
1.32% to 1.64% more at -O1 and 0.98% to 1.53% at -O2, 0.10% to 0.43%
and 0.64% to 1.19% with them, and on an earlier form of the series
the compiler ran 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, on an earlier form of the series 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 Note [Frequencies before register
allocation] names, were refuted. Taking at wideMoveDests the destination
of the hottest of the blocks that give a vreg one moved containers'
benchmarks both ways (intersection-mix taking fewer instructions,
symmetricDifference-common more), 0.081% fewer at -O2 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 and 0.170% more at -O2, and the compiler
allocate 14% to 17% more compiling MR 16269's CmmDiamondChain.
The estimate and the order are the compile cost: the stage-1 compiler
allocates at most 0.053% more at -O0 (T9961) and 0.071% 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 CmmDiamondChain at -O1 and -O2 it runs 0.57% and 0.58% more
instructions and allocates 0.069% and 0.068% 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.30 against 8.83 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
- - - - -
00e1728c by Mikolaj Konarski at 2026-11-26T23:24:54+01:00
Propagate wide move destinations back, preferring the target's register
A vreg moved, where it dies in a warm block, into a vreg that has a wide
destination now gets that destination too, up to four moves back,
and first takes the first-used register of the vreg it is moved into.
Vector's benchmarks fall past their threshold, maximumOn the most,
and containers' tree PostOrder folds fall, at the cost of rises in a few
rows, a trade described below.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.535% |
| vector -O1 | -0.581% |
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 third, 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 a target not yet recorded jumps to, gives another
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.30% to 4.4% fewer, nofib's k-nucleotide 0.57% fewer
at -O2, and clausify 0.39% and 0.38% fewer at -O2 and -O1.
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.17% more at -O1 against the parent.
Against the parent too, nofib's digits-of-e2 takes 0.32% more at -O2
and -O1, pidigits' object is 0.30% larger at -O2, and in orthotope's A2T
groups summed:Dynamic/zipWith3A.singleR/small/scalar/Storable takes two
instructions a call more (0.23%). A propagated destination yields
to a vreg directly destined for that register and born while
the propagated one is live only where, by the estimate of "Add
an estimate of block frequencies for the linear allocator", that vreg's
own move into the register runs 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
in every compile cell (perf/compiler's T3294, T12707, T783 and T9961
and MR 16269's CmmDiamondChain, each at -O0, -O1 and -O2) but T9961
at -O, by up to 0.092% (T783 at -O0), and runs up to 0.051% fewer
instructions (T783 at -O0) and at most 0.026% more (T3294 at -O0);
the stage-2 compiler allocates 0.16% less compiling T9961 at -O0
(392738008 against 393384656 bytes), and less in every other cell
but T9961 at -O, where it allocates 0.001% more, all 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
- - - - -
bc125e77 by Mikolaj Konarski at 2026-11-26T23:24:54+01:00
Give a vreg the register a recorded join holds it in
Where the register that an assignment recorded at a join gives a vreg
is held by a vreg the block reads no more, the linear allocator now
spills the holder and gives the vreg that register rather than a free
one; where that register is free, the vreg takes it ahead of its other
preferences, which fixes ISSUE 27980. Orthotope's A2T total falls,
by less than its threshold.
| | against the parent |
|------------|-------------------------------------------:|
| A2T groups | -0.056% (under threshold, still important) |
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 a target not yet recorded jumps to (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 uses them. joinToTargets' now takes 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.
Where the first register the assignments in rc_jumpLocs give the vreg
is free, the vreg now takes it, ahead of the preferences
of firstFreeInOrder. This fixes ISSUE 27980, not because the issue
matters much for performance, but because the fix is four lines of code
that use rc_jumpLocs, whose cost the allocator already incurs.
Measured on x86-64 against its parent, in instructions: megaparsec's
manyTill benchmarks take 0.11% to 0.16% fewer at -O2, nofib's puzzle
0.34% fewer at -O2, orthotope's A2T groups' zipWith3A.singleR cells
over large Unboxed arrays up to 4.1% fewer, and ISSUE 27980's example
compiles at -O to one instruction fewer (45 against 46); no benchmark
takes more beyond its threshold but Dynamic/rerank2/large/dense/boxed
in the A2T groups, 0.21% more, a cell that moves by as much at commits
that change no code. The stage-1 compiler allocates 0.072% to 0.13% more
compiling at -O0, and the stage-2 compiler 0.12% more compiling T3294
and T9961 at -O0.
Assisted-by: Claude Opus 5.5
- - - - -
9437159c by Mikolaj Konarski at 2026-11-26T23:24:55+01:00
Spill a vreg its block reads no more
Where no register is free, allocRegsAndSpill_spill now evicts a vreg
that no instruction left in the block reads, so that a vreg the block
still reads is not stored and reloaded, 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; and before that choice the previous commit's rule, giving
a vreg the register a recorded join holds it in, applies there too,
sending that register's holder to its slot where the block reads
it no more. Instructions fall past their thresholds in vector at -O2
and in A2T's groups, and by less in nofib at -O2 and -O1, containers
and megaparsec, at a cost in comparisons over large Storable arrays,
a trade described below.
| | against the parent |
|------------|-------------------:|
| vector -O2 | -0.264% |
| A2T groups | -0.484% |
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 recorded for the join at the block's
jump, 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 used, and a procedure's joins outside
cycles once, where building a block's last reads first uses 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 a target
not yet recorded jumps to, 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 use 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's
eviction goes through it, and so does the victim's, 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
MR 16269's CmmDiamondChain 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: vector's awshcc
takes 4.7% fewer at -O2 and nofib's puzzle 1.1% fewer at -O2,
the largest falls of those suites, and containers' IntSet and IntMap
union and symmetricDifference benchmarks and megaparsec's scientific
benchmarks fall at -O2, no benchmark of those suites taking more beyond
its noise. The stage-1 compiler allocates 0.86% less compiling
perf/compiler's T3294 at -O0, and compiling CmmDiamondChain it runs
0.43% to 0.53% more instructions and allocates 0.22% to 0.28% 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 5.9%
to 7.1% more instructions, and over small ones up to 1.4% more,
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 ==
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
- - - - -
acc25bd2 by Mikolaj Konarski at 2026-11-26T23:24:56+01:00
Copy small loop heads over the jumps to them after block layout
On x86-64 at -O1 and -O2, after block layout, a loop head of at most
eight instructions and a conditional branch is copied over each jump
to it that the layout left, so that a loop's entry and its back edges
other than the one that falls through no longer jump to the head.
This takes instructions off every suite of the battery, past each
threshold, at a cost in code size.
| | against the parent |
|--------------------|-------------------:|
| nofib -O2 | -0.239% |
| nofib -O1 | -0.218% |
| containers -O2 | -0.513% |
| containers -O1 | -0.570% |
| megaparsec -O2 | -0.363% |
| megaparsec -O1 | -0.307% |
| vector -O2 | -1.312% |
| vector -O1 | -1.063% |
| A2T groups | -0.629% |
| stage 2, nofib -O2 | -0.372% |
| stage 2, nofib -O1 | -0.375% |
| stage 2, nofib -O0 | -0.375% |
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 uses
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 uses 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.
In a map from the last run of each chain of moved runs to its first,
kept with the map back by one insertion in each at a move, pullRuns
finds the first run of the chain that the run being processed ends:
walking up the chain run by run instead, measured on a harness calling
copyLoopHeads on loops in sequence whose moves chain through them,
it ran 103.5e9 instructions at 16000 loops where the maps ran 4.0e9,
growing 3.5 to 4.1 times at each doubling where they grew 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
marks no 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 taking 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, the largest falls
are nofib's fannkuch-redux, 2.2% at -O2 and 1.9% at -O1, containers'
intmap lookup_half, 7.2% at -O2, and lookup_mixed, 7.5% at -O1,
megaparsec's string', 1.2% at -O2, and reachOffsetNoLine, 1.6% at -O1,
and vector's nextPermutation, 5.3% at -O2; at -O0, where it does
not run, nofib's programs take 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 benchmark takes 0.85%
and 0.86% fewer instructions than at the parent at -O2 and -O1
and its intersection 0.87% fewer at -O2, 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.67% at -O2 and 0.54% at -O1, x2n1's the most,
by 4.0% and 4.1%, and the objects of the stage-2 compiler's modules
by 0.17%; the tickets' procedures hold more instructions and conditional
jumps and fewer jumps, ISSUE 27742's at -O2 2.7% more instructions
and 13% more conditional jumps. The stage-1 compiler runs 0.015%
and 0.014% more instructions and allocates 0.014% and 0.009% less
compiling perf/compiler's T9961 at -O and -O2 (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.058% 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 allocates 0.04% more compiling nofib
at -O2 and at -O1, 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 MR 16269's CmmDiamondChain 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 end of an earlier form of the series
against the form before layout, containers' Set and Map
fromDistinctAscList:fusion benchmarks run 0.85% and 0.73% more
instructions at both -O2 and -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 counted the two other edges
into that block as 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
- - - - -
76908974 by Mikolaj Konarski at 2026-11-26T23:24:56+01:00
Use one estimator of block frequencies for the layout and the allocator
The layout's estimate of block frequencies, which static prediction made
over LabelMaps, and the linear allocator's, made in arrays by the same
rules, now come from one estimator, the allocator's array code,
and the LabelMap code is deleted. The compiler runs fewer instructions,
while the generated code moves only by rounding, by the allocator's
estimate taking the layout's loops (one procedure of spectral/para
at -O2), and where the side of a branch, now recorded on its edge, had
been taken from a stale label.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -1.909% |
| stage 2, nofib -O2 | -1.465% |
| stage 2, nofib -O1 | -1.342% |
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 uses: 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,
took which side of a two-way branch an edge is on from 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 swapped the likely side
and 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 matches 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 taken from the label, the layout put
the true target's first.
Measured against its parent. Compiling, the stage-1 compiler runs 8.10%
and 8.07% fewer instructions and allocates 9.0% and 8.9% less on MR
16269's CmmDiamondChain at -O1 and -O2, 2.8% and 2.7% fewer instructions
on T783 at -O and -O2, 2.5% and 2.3% on T12707, 0.71% and 0.70% on T3294
and 0.049% and 0.068% on T9961, and moves by 0.028% or less at -O0;
the stage-2 compiler runs 2.3% and 3.4% fewer instructions on nofib's
puzzle at -O1 and -O2 and, over nofib's modules, allocates 2.0% and 2.1%
less 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
at -O1 and -O2, and at -O0 only treejoin does, running 0.27% more
instructions, a program that moves by as much at commits that change
no code; containers', megaparsec's and vector's benchmarks move
by no more than their noise. In A2T's groups
summed:Dynamic/stretch/large/scaled/boxed runs 10.6% more instructions
a call, a cell that moves by as many instructions at commits that change
no code; cells over large Unboxed and Storable arrays run up to 0.301%
more and 0.233% fewer, Shaped/update/large/window/Unboxed
and Dynamic/force.rank5/large/runs/Storable the most, cells that move
both ways by as much from commit to commit,
and Dynamic/rerank2/large/dense/boxed 0.289% more. 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 side taken from the label on every other; the side
taken from the label 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 CmmDiamondChain 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
- - - - -
75e980ef by Mikolaj Konarski at 2026-11-26T23:24:57+01:00
Count irreducible regions in layout frequencies and duplicate small runs
The layout's estimate of block frequencies now counts the blocks
of an irreducible region by their inflow, as the allocator's estimate
does, where it skipped them, and a copy of a loop head left ending
in a jump to a small run that another copy took now ends in a duplicate
of that run, made for a jump that the counting adds to a loop
of orthotope's A2T benchmark. A2T's groups take fewer instructions,
by less than their threshold.
| | against the parent |
|------------|-------------------------------------------:|
| A2T groups | -0.018% (under threshold, still important) |
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, a successor of more
than one copy of the loop's head, 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 has it as a successor,
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, the duplication included, in instructions:
in A2T's groups 116 cells fall by more than 0.2% and none rises,
generate over large strided boxed arrays the most, by 0.52%;
megaparsec's benchmarks at -O1 have 11 falling by 0.1% beyond their
noise and none rising beyond it, reachOffsetNoLine the most, by 0.33%,
and at -O2 none rises or falls beyond its noise; containers' fall by up
to 0.42% at -O2 beyond their noise, in tree's foldl'_maximum, none
rising beyond it; none of vector's moves by 0.05%; no nofib program
at -O1 or -O2 moves by 0.2% in instructions or allocation, and at -O0
treejoin runs 0.27% fewer, a program that moves by as much at commits
that change no code. Compiling, the stage-1 compiler runs 0.012% fewer
instructions on MR 16269's CmmDiamondChain at -O2 and moves by 0.009%
or less elsewhere, its assembly the same in every cell. nofib's objects
grow by 0.146% in total at -O2, fannkuch-redux's the most, by 1.64%,
and by 0.085% at -O1, pidigits' the most, by 1.30%, and ISSUE 27742's
procedure at -O2 holds 0.46% more instructions and 0.87% more that read
or write the stack.
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, and none of vector's by 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, 11 falling by 0.1% beyond their noise and none
rising, and at -O2 none rises or falls beyond its noise; at -O2 five
of containers' benchmarks fall by 0.1% beyond their noise and none rises
beyond it; none of vector's moves by 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.
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
- - - - -
2207ee2a by Mikolaj Konarski at 2026-11-26T23:24:58+01:00
Walk liveness first over instructions as the code generator gives them
The first liveness walk now takes the instructions as the code generator
gives them, where natCmmTopToLive wrapped each in a LiveInstr in a list
of its own that the walk dropped at once, and the liveness pass is pure.
The compiler allocates less and runs fewer instructions, its assembly
byte-identical.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.410% |
| stage 2, nofib -O0 | -0.247% |
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 MR 16269's
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 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.77% less
compiling T3294 at -O0, 1.58% less for T9961, 1.18% for T12707 and 1.03%
for T783, 0.065% to 0.57% less at -O and -O2, and 0.64% to 0.73% less
for CmmDiamondChain, and runs 0.055% to 1.05% fewer instructions,
counted with an allocation area larger than all a compilation allocates;
the stage-2 compiler allocates 0.72% less over nofib's modules at -O0
(geometric mean).
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
49d347d7 by Mikolaj Konarski at 2026-11-26T23:24:58+01:00
Lower master's NCG helpers' compile cost and drop needless blocks
Master's NCG helpers do less work: the CFG's weights are mapped
and adjusted in place, favourFewerPreds counts predecessors once
a procedure, block layout's search for unplaced blocks runs only where
one can be missing and takes chains' ends without building lists,
and shortcutBranches leaves the procedures alone where it shorts
nothing. Blocks that do nothing are dropped: under -g on ELF targets
a block holding only its jump is shorted as without -g, and a jump
table's later entries for a target that needs a fixup block make
no second one. The compiler runs fewer instructions and allocates less,
the assembly of its compile cells the same.
| | against the parent |
|----------------------------|-------------------:|
| stage 1, a sample of tests | -0.830% |
| stage 2, nofib -O2 | -0.364% |
| stage 2, nofib -O1 | -0.236% |
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 MR 16269's CmmDiamondChain 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 ran on 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 use; 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 at most 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.
Measured against its parent, the commit whole: the stage-1 compiler
allocates 8.3% and 8.7% less compiling T3294 at -O and -O2 and 3.0% less
compiling T783 at -O0, the stage-2 compiler 11.0% less in the perf test
T17836, and the assembly of every compile cell and every scaling probe
is the same, as is the size of every nofib object; which of the changes
above makes T3294's fall was not traced.
Figures of variants not taken were measured on earlier forms
of the series.
Assisted-by: Claude Opus 5.5
- - - - -
183 changed files:
- compiler/CodeGen.Platform.h
- compiler/GHC/Cmm.hs
- compiler/GHC/Cmm/CLabel.hs
- compiler/GHC/Cmm/Config.hs
- compiler/GHC/Cmm/ContFlowOpt.hs
- compiler/GHC/Cmm/DebugBlock.hs
- compiler/GHC/Cmm/Graph.hs
- compiler/GHC/Cmm/Info.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/Node.hs
- compiler/GHC/Cmm/Opt.hs
- compiler/GHC/Cmm/Parser.y
- compiler/GHC/Cmm/Pipeline.hs
- compiler/GHC/Cmm/ProcPoint.hs
- compiler/GHC/Cmm/Reg.hs
- compiler/GHC/Cmm/Sink.hs
- compiler/GHC/Cmm/UniqueRenamer.hs
- compiler/GHC/Cmm/Utils.hs
- compiler/GHC/CmmToAsm.hs
- compiler/GHC/CmmToAsm/AArch64.hs
- compiler/GHC/CmmToAsm/AArch64/CodeGen.hs
- compiler/GHC/CmmToAsm/BlockLayout.hs
- compiler/GHC/CmmToAsm/CFG.hs
- compiler/GHC/CmmToAsm/Config.hs
- compiler/GHC/CmmToAsm/Dwarf.hs
- compiler/GHC/CmmToAsm/Dwarf/Constants.hs
- compiler/GHC/CmmToAsm/Format.hs
- compiler/GHC/CmmToAsm/Instr.hs
- compiler/GHC/CmmToAsm/LA64.hs
- compiler/GHC/CmmToAsm/LA64/CodeGen.hs
- compiler/GHC/CmmToAsm/Monad.hs
- compiler/GHC/CmmToAsm/PIC.hs
- compiler/GHC/CmmToAsm/PPC.hs
- compiler/GHC/CmmToAsm/PPC/CodeGen.hs
- compiler/GHC/CmmToAsm/PPC/Instr.hs
- + compiler/GHC/CmmToAsm/README.md
- compiler/GHC/CmmToAsm/RV64.hs
- compiler/GHC/CmmToAsm/RV64/CodeGen.hs
- compiler/GHC/CmmToAsm/Reg/Graph.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Base.hs
- compiler/GHC/CmmToAsm/Reg/Graph/Coalesce.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/Graph/TrivColorable.hs
- compiler/GHC/CmmToAsm/Reg/Graph/X86.hs
- compiler/GHC/CmmToAsm/Reg/Linear.hs
- compiler/GHC/CmmToAsm/Reg/Linear/AArch64.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/Reg/Regs.hs
- compiler/GHC/CmmToAsm/Reg/Target.hs
- compiler/GHC/CmmToAsm/Wasm/FromCmm.hs
- compiler/GHC/CmmToAsm/X86.hs
- compiler/GHC/CmmToAsm/X86/CodeGen.hs
- compiler/GHC/CmmToAsm/X86/Instr.hs
- compiler/GHC/CmmToAsm/X86/Ppr.hs
- compiler/GHC/CmmToAsm/X86/Regs.hs
- compiler/GHC/Data/Graph/Directed.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/Platform/Reg.hs
- compiler/GHC/Platform/Reg/Class.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/debug-info.rst
- docs/users_guide/phases.rst
- docs/users_guide/using-optimisation.rst
- rts/Weak.c
- rts/include/Cmm.h
- + testsuite/tests/cmm/should_compile/CmmRegOffW16.cmm
- + 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/T28093.cmm
- + testsuite/tests/cmm/should_compile/T28093.stderr
- + testsuite/tests/cmm/should_compile/T8327.cmm
- testsuite/tests/cmm/should_compile/all.T
- + testsuite/tests/cmm/should_compile/cmm_fold_elemAt.hs
- + testsuite/tests/cmm/should_compile/cmm_fold_lit.cmm
- + testsuite/tests/cmm/should_compile/cmm_fold_scaled.cmm
- + testsuite/tests/cmm/should_compile/cmm_fold_scaled.stderr
- testsuite/tests/cmm/should_run/all.T
- + testsuite/tests/cmm/should_run/cmm_addnf.hs
- + testsuite/tests/cmm/should_run/cmm_addnf.stdout
- + testsuite/tests/cmm/should_run/cmm_addnf_cmm.cmm
- + 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_regoff.hs
- + testsuite/tests/cmm/should_run/cmm_regoff.stdout
- + testsuite/tests/cmm/should_run/cmm_regoff_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/cmm/should_run/cmm_scaledlit.hs
- + testsuite/tests/cmm/should_run/cmm_scaledlit.stdout
- + testsuite/tests/cmm/should_run/cmm_scaledlit_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_sinkoff.hs
- + testsuite/tests/cmm/should_run/cmm_sinkoff.stdout
- + testsuite/tests/cmm/should_run/cmm_sinkoff_cmm.cmm
- + testsuite/tests/cmm/should_run/cmm_swoff.hs
- + testsuite/tests/cmm/should_run/cmm_swoff.stdout
- + testsuite/tests/cmm/should_run/cmm_swoff_cmm.cmm
- + testsuite/tests/codeGen/should_compile/ClosureTblAmode.hs
- + testsuite/tests/codeGen/should_compile/ClosureTblAmode.stderr
- + 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/EnumTagOffset.hs
- + testsuite/tests/codeGen/should_compile/EnumTagOffset.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/T27799.hs
- + testsuite/tests/codeGen/should_compile/T27799.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/T26631.hs
- + testsuite/tests/regalloc/T26631.stderr
- + testsuite/tests/regalloc/T27619.hs
- + testsuite/tests/regalloc/T27800_itm.cmm
- + testsuite/tests/regalloc/T27981.hs
- testsuite/tests/regalloc/all.T
- testsuite/tests/regalloc/regalloc_unit_tests.hs
- + testsuite/tests/rts/T28060.hs
- + testsuite/tests/rts/T28060.stdout
- testsuite/tests/rts/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/6b8479b2b153a035fbd6dd5fd9188f…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/6b8479b2b153a035fbd6dd5fd9188f…
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
1
0
[Git][ghc/ghc][wip/romes/global-break-action] ci: unset CI_COMMIT_MESSAGE to avoid Windows environment length limits
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
26 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/global-break-action at Glasgow Haskell Compiler / GHC
Commits:
55c57d76 by Rodrigo Mesquita at 2026-11-26T18:12:13+00:00
ci: unset CI_COMMIT_MESSAGE to avoid Windows environment length limits
The previous commit consistently made the Windows runner fail with:
> find: The environment is too large for exec().
GitLab sets these environment variables by default, but we never read
them. Just unset them at the start.
- - - - -
1 changed file:
- .gitlab/ci.sh
Changes:
=====================================
.gitlab/ci.sh
=====================================
@@ -6,6 +6,10 @@
# Run `ci.sh usage` for usage information.
set -Eeuo pipefail
+# Unset some of GitLab's pre-defined CI variables to avoid running into issues
+# with Windows environment length restrictions when the commit message is too large.
+unset CI_COMMIT_MESSAGE CI_COMMIT_DESCRIPTION CI_MERGE_REQUEST_DESCRIPTION
+
# Configuration:
# N.B. You may want to also update the index-state in hadrian/cabal.project.
HACKAGE_INDEX_STATE="2026-03-10T17:36:36Z"
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/55c57d76b2ed924606a6c9678f5a4de…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/55c57d76b2ed924606a6c9678f5a4de…
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
1
0
[Git][ghc/ghc][wip/davide/rts-public] RTS: Remove Begin/EndPrivate.h
by David Eichmann (@DavidEichmann) 26 Nov '26
by David Eichmann (@DavidEichmann) 26 Nov '26
26 Nov '26
David Eichmann pushed to branch wip/davide/rts-public at Glasgow Haskell Compiler / GHC
Commits:
2685264e by David Eichmann at 2026-11-26T16:17:57+00:00
RTS: Remove Begin/EndPrivate.h
Also remove PrivateIncludeLinter from the testsuite as it is nolonger
needed.
- - - - -
103 changed files:
- rts/AllocArray.h
- − rts/BeginPrivate.h
- rts/BuiltinClosures.h
- rts/Capability.h
- rts/CheckUnload.h
- rts/CloneStack.h
- rts/ClosureTable.h
- rts/Continuation.h
- − rts/EndPrivate.h
- rts/ForeignExports.h
- rts/GetEnv.h
- rts/GetTime.h
- rts/Hash.h
- rts/IOManager.h
- rts/IOManagerInternals.h
- rts/IPE.h
- rts/Libdw.h
- rts/LibdwPool.h
- rts/LinkerInternals.h
- rts/Messages.h
- rts/PathUtils.h
- rts/Printer.h
- rts/ProfHeap.h
- rts/ProfHeapInternal.h
- rts/ProfilerReport.h
- rts/ProfilerReportJson.h
- rts/Profiling.h
- rts/Proftimer.h
- rts/RaiseAsync.h
- rts/RetainerProfile.h
- rts/RetainerSet.h
- rts/RtsFlags.h
- rts/RtsSignals.h
- rts/RtsUtils.h
- rts/SMPClosureOps.h
- rts/STM.h
- rts/Schedule.h
- rts/Sparks.h
- rts/StableName.h
- rts/StablePtr.h
- rts/StaticPtrTable.h
- rts/Stats.h
- rts/StgPrimFloat.h
- rts/Task.h
- rts/ThreadLabels.h
- rts/ThreadPaused.h
- rts/Threads.h
- rts/Ticker.h
- rts/Ticky.h
- rts/TimeoutQueue.h
- rts/Timer.h
- rts/TopHandler.h
- rts/Trace.h
- rts/TraverseHeap.h
- rts/Updates.h
- rts/Weak.h
- rts/adjustor/AdjustorPool.h
- rts/eventlog/EventLog.h
- rts/hooks/Hooks.h
- rts/include/RtsPublic.h
- rts/linker/CacheFlush.h
- rts/linker/Elf.h
- rts/linker/LoadNativeObjPosix.h
- rts/linker/M32Alloc.h
- rts/linker/MMap.h
- rts/linker/MachO.h
- rts/linker/PEi386.h
- rts/linker/SymbolExtras.h
- rts/posix/FdWakeup.h
- rts/posix/MIO.h
- rts/posix/Poll.h
- rts/posix/Select.h
- rts/posix/SelectBis.h
- rts/posix/Signals.h
- rts/posix/Timeout.h
- rts/sm/BlockAlloc.h
- rts/sm/CNF.h
- rts/sm/Compact.h
- rts/sm/Evac.h
- rts/sm/GC.h
- rts/sm/GCTDecl.h
- rts/sm/GCThread.h
- rts/sm/GCUtils.h
- rts/sm/MarkStack.h
- rts/sm/MarkWeak.h
- rts/sm/NonMoving.h
- rts/sm/NonMovingAllocate.h
- rts/sm/NonMovingMark.h
- rts/sm/NonMovingScav.h
- rts/sm/NonMovingShortcut.h
- rts/sm/OSMem.h
- rts/sm/Sanity.h
- rts/sm/Scav.h
- rts/sm/Storage.h
- rts/win32/AsyncMIO.h
- rts/win32/AsyncWinIO.h
- rts/win32/AwaitEvent.h
- rts/win32/ConsoleHandler.h
- rts/win32/MIOManager.h
- rts/win32/ThrIOManager.h
- rts/win32/WorkQueue.h
- rts/win32/veh_excn.h
- testsuite/tests/linters/regex-linters/check-rts-includes.py
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/2685264e5bdce0b20618c08741ed54a…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/2685264e5bdce0b20618c08741ed54a…
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
1
0
[Git][ghc/ghc][wip/davide/rts-public] 2 commits: RTS: tag all exported symbols with RTS_PUBLIC
by David Eichmann (@DavidEichmann) 26 Nov '26
by David Eichmann (@DavidEichmann) 26 Nov '26
26 Nov '26
David Eichmann pushed to branch wip/davide/rts-public at Glasgow Haskell Compiler / GHC
Commits:
871ab331 by David Eichmann at 2026-11-26T16:15:25+00:00
RTS: tag all exported symbols with RTS_PUBLIC
- - - - -
f129d9b8 by David Eichmann at 2026-11-26T16:15:25+00:00
RTS: Remove Begin/EndPrivate.h
Also remove PrivateIncludeLinter from the testsuite as it is nolonger
needed.
- - - - -
225 changed files:
- rts/ARMOutlineAtomicsSymbols.h
- rts/Adjustor.h
- rts/AllocArray.h
- rts/Arena.h
- − rts/BeginPrivate.h
- rts/BuiltinClosures.h
- rts/Capability.h
- rts/CheckUnload.h
- rts/CheckVectorSupport.h
- rts/CloneStack.h
- rts/ClosureTable.h
- rts/Continuation.h
- − rts/EndPrivate.h
- rts/ForeignExports.h
- rts/GetEnv.h
- rts/GetTime.h
- rts/Globals.c
- rts/Hash.h
- rts/Hpc.c
- rts/IOManager.h
- rts/IOManagerInternals.h
- rts/IPE.h
- rts/Interpreter.c
- rts/Interpreter.h
- rts/Libdw.h
- rts/LibdwPool.h
- rts/Linker.c
- rts/LinkerInternals.h
- rts/Messages.h
- rts/PathUtils.h
- rts/Pool.h
- rts/Printer.c
- rts/Printer.h
- rts/ProfHeap.c
- rts/ProfHeap.h
- rts/ProfHeapInternal.h
- rts/ProfilerReport.h
- rts/ProfilerReportJson.h
- rts/Profiling.h
- rts/Proftimer.c
- rts/Proftimer.h
- rts/RaiseAsync.h
- rts/ReportMemoryMap.h
- rts/RetainerProfile.h
- rts/RetainerSet.h
- rts/RtsAPI.c
- rts/RtsFlags.c
- rts/RtsFlags.h
- rts/RtsMessages.c
- rts/RtsSignals.h
- rts/RtsSymbolInfo.h
- rts/RtsSymbols.c
- rts/RtsSymbols.h
- rts/RtsUtils.h
- rts/SMPClosureOps.h
- rts/STM.c
- rts/STM.h
- rts/Schedule.c
- rts/Schedule.h
- rts/Sparks.h
- rts/StableName.h
- rts/StablePtr.h
- rts/StaticPtrTable.h
- rts/Stats.c
- rts/Stats.h
- rts/StgPrimFloat.h
- rts/Task.c
- rts/Task.h
- rts/ThreadLabels.h
- rts/ThreadPaused.h
- rts/Threads.h
- rts/Ticker.h
- rts/Ticky.c
- rts/Ticky.h
- rts/TimeoutQueue.c
- rts/TimeoutQueue.h
- rts/Timer.h
- rts/TopHandler.h
- rts/Trace.h
- rts/TraverseHeap.c
- rts/TraverseHeap.h
- rts/TraverseHeapTest.c
- rts/Updates.h
- rts/WSDeque.h
- rts/Weak.h
- rts/adjustor/AdjustorPool.h
- rts/adjustor/NativeAmd64.c
- rts/eventlog/EventLog.c
- rts/eventlog/EventLog.h
- rts/gen_event_types.py
- rts/hooks/Hooks.h
- rts/include/HsFFI.h
- rts/include/Rts.h
- rts/include/RtsAPI.h
- rts/include/RtsPublic.h
- rts/include/Stg.h
- rts/include/rts/Adjustor.h
- rts/include/rts/BlockSignals.h
- rts/include/rts/EventLogWriter.h
- rts/include/rts/ExecPage.h
- rts/include/rts/FileLock.h
- rts/include/rts/Flags.h
- rts/include/rts/ForeignExports.h
- rts/include/rts/GetTime.h
- rts/include/rts/Globals.h
- rts/include/rts/Hpc.h
- rts/include/rts/IOInterface.h
- rts/include/rts/IPE.h
- rts/include/rts/Libdw.h
- rts/include/rts/LibdwPool.h
- rts/include/rts/Linker.h
- rts/include/rts/Main.h
- rts/include/rts/Messages.h
- rts/include/rts/NonMoving.h
- rts/include/rts/OSThreads.h
- rts/include/rts/Parallel.h
- rts/include/rts/PrimFloat.h
- rts/include/rts/Profiling.h
- rts/include/rts/RtsSymbols.h
- rts/include/rts/RtsToHsIface.h
- rts/include/rts/SpinLock.h
- rts/include/rts/StableName.h
- rts/include/rts/StablePtr.h
- rts/include/rts/StaticPtrTable.h
- rts/include/rts/TTY.h
- rts/include/rts/Threads.h
- rts/include/rts/Ticky.h
- rts/include/rts/Time.h
- rts/include/rts/Timer.h
- rts/include/rts/Utils.h
- rts/include/rts/prof/CCS.h
- rts/include/rts/prof/Heap.h
- rts/include/rts/storage/Block.h
- rts/include/rts/storage/ClosureMacros.h
- rts/include/rts/storage/GC.h
- rts/include/rts/storage/Heap.h
- rts/include/rts/storage/HeapAlloc.h
- rts/include/rts/storage/InfoTables.h
- rts/include/rts/storage/MBlock.h
- rts/include/rts/storage/TSO.h
- rts/include/stg/MiscClosures.h
- rts/include/stg/Prim.h
- rts/include/stg/Regs.h
- rts/include/stg/SMP.h
- rts/include/stg/Ticky.h
- rts/linker/CacheFlush.h
- rts/linker/Elf.h
- rts/linker/InitFini.h
- rts/linker/LoadNativeObjPosix.h
- rts/linker/M32Alloc.c
- rts/linker/M32Alloc.h
- rts/linker/MMap.h
- rts/linker/MachO.h
- rts/linker/PEi386.h
- rts/linker/ProddableBlocks.h
- rts/linker/SymbolExtras.h
- rts/linker/elf_got.h
- rts/linker/elf_plt.h
- rts/linker/elf_plt_aarch64.c
- rts/linker/elf_plt_aarch64.h
- rts/linker/elf_plt_riscv64.c
- rts/linker/elf_plt_riscv64.h
- rts/linker/elf_reloc.h
- rts/linker/elf_reloc_aarch64.c
- rts/linker/elf_reloc_aarch64.h
- rts/linker/elf_reloc_riscv64.c
- rts/linker/elf_reloc_riscv64.h
- rts/linker/elf_util.h
- rts/linker/macho/plt.h
- rts/linker/macho/plt_aarch64.c
- rts/linker/macho/plt_aarch64.h
- rts/posix/FdWakeup.h
- rts/posix/MIO.h
- rts/posix/Poll.h
- rts/posix/Select.h
- rts/posix/SelectBis.h
- rts/posix/Signals.c
- rts/posix/Signals.h
- rts/posix/Timeout.h
- rts/rts.cabal
- rts/sm/BlockAlloc.c
- rts/sm/BlockAlloc.h
- rts/sm/CNF.h
- rts/sm/Compact.h
- rts/sm/Evac.h
- rts/sm/GC.h
- rts/sm/GCTDecl.h
- rts/sm/GCThread.h
- rts/sm/GCUtils.h
- rts/sm/MBlock.c
- rts/sm/MarkStack.h
- rts/sm/MarkWeak.h
- rts/sm/NonMoving.c
- rts/sm/NonMoving.h
- rts/sm/NonMovingAllocate.h
- rts/sm/NonMovingCensus.h
- rts/sm/NonMovingMark.h
- rts/sm/NonMovingScav.h
- rts/sm/NonMovingShortcut.h
- rts/sm/NonMovingSweep.h
- rts/sm/OSMem.h
- rts/sm/Sanity.c
- rts/sm/Sanity.h
- rts/sm/Scav.h
- rts/sm/ShouldCompact.h
- rts/sm/Storage.c
- rts/sm/Storage.h
- rts/wasm/JSFFI.c
- rts/wasm/JSFFIGlobals.c
- rts/wasm/StgRun.c
- rts/win32/AsyncMIO.h
- rts/win32/AsyncWinIO.h
- rts/win32/AwaitEvent.h
- rts/win32/ConsoleHandler.h
- rts/win32/MIOManager.h
- rts/win32/ThrIOManager.h
- rts/win32/WorkQueue.h
- rts/win32/veh_excn.h
- testsuite/tests/ghci/linking/dyn/A.c
- testsuite/tests/ghci/linking/dyn/B.c
- testsuite/tests/linters/regex-linters/check-rts-includes.py
- testsuite/tests/rts/T12771/foo_dll.c
- testsuite/tests/rts/T13082/foo_dll.c
- testsuite/tests/rts/T14611/foo_dll.c
- utils/fs/fs.h
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1dee77235184a5db6a55961ea84d21…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/1dee77235184a5db6a55961ea84d21…
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
1
0
[Git][ghc/ghc][wip/romes/async-eval-resume] 12 commits: test case for #28104
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
by Rodrigo Mesquita (@alt-romes) 26 Nov '26
26 Nov '26
Rodrigo Mesquita pushed to branch wip/romes/async-eval-resume at Glasgow Haskell Compiler / GHC
Commits:
3e66b59c by Andrea Vezzosi at 2026-11-23T12:52:30+05:30
test case for #28104
(cherry picked from commit c032076a9cd2a6ce2fea66df98fd5f5c85e81aac)
- - - - -
d991ab3c by Zubin Duggal at 2026-11-23T14:02:49+05:30
loader: fix #28104
Ensure LoaderState is recorded accurately and consistent in the presence of failures
* loadObjects: when resolveObjs fails, unload only the objects freshly loaded
and return the old LoaderState. Before this we used to unload every home module with
unload_wkr, but then its callers threw inside `modifyLoaderState`, which
restored the old state, which contained objects that were already unloaded.
The objects loaded by `loadObjects` are also unloaded if loading or
resolving fails.
* loadName, loadDecls, loadModule: report failure after the transaction
has committed, so we don't mangle the loader state by restoring the old
state.
* unload: Keep track of things that were succefully unloaded on exception
and unload each object of a module only once. The foreign stub
objects of a bytecode module are recorded in both objs_loaded and
bcos_loaded, so with a non-dynamic interpreter unloading such a module
called unloadObj twice on the same object and failed.
Fixes #28104
- - - - -
19a4dfcd by Zubin Duggal at 2026-11-23T14:02:49+05:30
loader: make crucial sequences uninterruptible
Add masks so that we don't observe async exceptions
during sequences that can't deal with them.
- - - - -
0c095fa9 by Andrea Vezzosi at 2026-11-23T10:39:42+01:00
interp: close Mailbox when exiting sendTHComputation
- - - - -
8a15b532 by Andrea Vezzosi at 2026-11-23T10:39:42+01:00
Revert "template-haskell: force arguments of Q primitives up front."
This reverts commit 653e4ffcbf807f7a8268d7d0d9f5b710f8d73906.
- - - - -
5216cfd0 by Andrea Vezzosi at 2026-11-23T10:39:42+01:00
Revert "Follow `Note [Exceptions in TH]` in `qReport` implementation"
This reverts commit 95bf64567e373d9c3607c250469c171fdc876c7b.
- - - - -
c6c1dbae by Andrea Vezzosi at 2026-11-23T14:16:06+01:00
TH: force arguments of MetaHandlers up front
Fixes #28112
- - - - -
bad96e95 by Rodrigo Mesquita at 2026-11-23T17:27:00+00:00
Clean up GHCi.Message.Async lower-level interface
- - - - -
8267a65b by Andrea Vezzosi at 2026-11-24T16:06:42+01:00
ghc-boot-th: avoid orphan NFData instances
we define rnf<Foo> functions instead.
Also, ghc-boot-th now exports forceMetaHandlersArgs instead of GHCi.TH.
- - - - -
027084d2 by Rodrigo Mesquita at 2026-11-24T16:30:47+00:00
Global break action which uses a per-thread context map
Previously, everytime an expression was run in the interpreter (`sandboxIO`):
1) the RTS global variable `rts_breakpoint_io_action`, which is run
anytime any thread hits a breakpoint, got set to a new action that:
a) Wrote the breakpoint hit by the thread to the `statusMVar`
b) Blocked waiting on a newly created MVar `breakMVar` for a `resumeStmt` to
signal it.
2) Start the expression evaluation on a new "sandbox" thread
3) Block waiting on `statusMVar` for a breakpoint to be hit, and we'd
return the read `EvalBreak`
4) Set the `rts_breakpoint_io_action` to a no-op which prints "Ignored breakpoint..."
At some later point, we could `resumeStmt` with the `EvalBreak` context
by signaling the `breakMVar` on which the thread that hit the breakpoint
is blocked.
However, if you consider an expression which forks off threads which hit
breakpoints, surprising things may happen:
main = do
-- the `worker` code has a breakpoint
mapM (forkIO . worker) [1..10]
forever $ threadDelay 10000000
Interpreting this program, we'll do (1,2,3), and all workers will hit
their breakpoint and run `rts_breakpoint_io_action`. Here's a first
issue:
1. The first worker succeeds in `putMVar statusMVar`
2. The interpreter will read `takeMVar statusMVar` (3) and then (4)
3. The remaining workers are hitting the breakpoint concurrently:
- Some may block trying to `putMVar statusMVar`
- Some may run the no-op action which discards the breakpoint
Depending on whether the remaining workers hit the breakpoint or (4)
happens first, some workers will skip their breakpoint.
Now, let's pretend all workers can block on `putMVar statusMVar`. Since
the interpreter will take the breakpoints one by one, and resume them
one by one, it seemingly works. However, that's only fine when we assume
only one expression is evaluated at once. As soon as multiple
expressions can be evaluated at once (a desireable property of a
debugger, as well as something that can already happen today in some
scenarios (see `break049`)), it becomes madness:
The second issue comes the global break action being swapped by a second
evaluation and threads from the first evaluation running the "wrong" action.
Consider:
1. eval `expr_A` installs a break action that puts on `statusMVar_A`
2. `expr_A` forks off a few threads, they're running in the background
3. eval `expr_B` sets the break action to put on `statusMVar_B`
4. the `expr_A` forked threads hit a breakpoint and put `statusMVar_B`
5. `expr_B` returns with a breakpoint of `expr_A`, `resume expr_B` would
resume `expr_A`, etc...
A third issue with having a single MVar for all threads of an execution
is that there is no way to have fine-grained control over which threads
are resumed and which are stopped. This is often necessary to debug
multi-threaded programs too.
Therefore, it is imperative that the global break action does not
capture a global single MVar when many expressions with many
corresponding threads can be running in the interpreter/debugger at
once, if we want to support debugging multi-threaded programs at all.
---
This commit fixes these foundational issues by making the global break
action truly global (i.e. never modified and never capturing any locals).
The global break action is installed once in `sandboxIO` and never
removed (`withBreakAciton` and `noBreakAction` were killed). Subsequent
runs of `sandboxIO` re-rewrite the same break action (a no-op).
When any thread hits the global break action, it looks its `ThreadId` up
in the global per-thread context mapping, returning a `ResumeContext`
which contains that thread's `breakMVar` (now `resumeBreakVar`) and
`statusMVar` (now `resumeEvalStatus`). Each thread blocks on its own
MVar and replies on its own TVar. There is no longer one global status
nor break MVar.
To resume a thread by its `ThreadId`, we can simply fetch its
`ResumeContext` and signal the corresponding `resumeBreakMVar`
To wait for a result or for a breakpoint in a specific thread, we do
`readThreadEvalStatus`. To wait for any breakpoint hit in any thread at
all, we have `readAnyThreadEvalBreak`.
Some evaluations will only care to look at their own result and breaks
(so they run with `readAllBreaks` `= False`); and the main thread of an
evaluation should not be read by other evaluations. In short, only
threads forked off by the main thread of evaluations get read with
`readAnyThreadEvalBreak`. If two evaluations fork off threads in the
background, `readAnyThreadEvalBreak` may return threads from any of
them. There is no just way to distinguish their "parents" at runtime.
For instance, `compileParsedExprRemote` should run an expression until
completion without any existing threads interfering with its execution,
so it runs with `readAllBreaks = False`. Otherwise, by default, running
`main` on the REPL, we'll want to stop at any break any forked thread
hits, just like we did before.
P.S. Currently, we need to keep track of the "main expression thread"
being currently evaluated to fetch its result, but, when `evalStmt`
becomes asynchronous by returning the `ThreadId` of the "sandbox"
thread, the whole `evaluationMainThreadGlobalVar` hack can be deleted.
---
New tests observing behavior that we don't want to break (which I broke
at some point while developing this patch):
- break032: we don't stop at breakpoints in TH
- break033: :continue after -fbreak-on-exception doesn't hit exception breakpoint
- break034: test :abandon doesn't hang with -fbreak-on-error
- conc033: also run with the external interpreter
- ForceInterrupt(Ext): ^C during :force interrupts the forced expression
- break043: :continue of a forked thread reads main thread breaks/results too
- break046: evaluating expr while stopped doesn't change what :continue resumes
- break048: evaluating expr while forked thread is stopped doesn't hit again current breakpoint
New tests that failed before this commit:
- T3171(ext)nosandbox: T3171 with -fno-ghci-sandbox (T3171extnosandbox still fails)
- break050(ext): ^C during :continue of a forked thread interrupts that thread
Fixed ext-interp bc. resumeStmt now does unsafeUnmask, just like
sandboxIO, so the UserInterrupt reaches the resume.
- break049: breakpoints in forked threads don't get mixed up with other evaluations
This test demonstrates one way multi-threaded debugging can go wrong
bc the global break action used to capture a break MVar for a
specific thread that is shared by all threads (described above as
"the second issue"). Here is the annotated execution of the test
*before this commit*:
```haskell
ghci> main
Stopped in Main.inMain, break049.hs:30:12-18
_result :: IO () = _
[break049.hs:30:12-18] ghci> :force slow
-- ANN: the breakpoint we're ignoring on :force is the worker's
-- breakpoint, and it's just discarded
*** Ignoring breakpoint [break049.hs:27:14-20]
slow = 5
[break049.hs:30:12-18] ghci> :cmd return ""
-- ANN: we :continue `main`, but the worker should still be blocked
-- so `main` should block.
[break049.hs:30:12-18] ghci> :continue
-- ANN: however, it completes; recall the worker break was ignored
-- instead of stopping there
main done
-- ANN: after this commit, the worker break wouldn't have been read
-- by `:force`, and we'd see it when resuming `:main`, and
-- `:continue` here would resume the worker and only then main would
-- complete.
ghci> :continue
-- ANN: bc this is ghci before the commit, we see:
not stopped at a breakpoint
ghci>
```
- break042: main forks workers and all workers hit a breakpoint
This test witnesses "the first issue" described above, where the
workers hit breaks after the global break action was already removed
and so are lost.
Fixes #28124
- - - - -
61f11e2f by Rodrigo Mesquita at 2026-11-24T16:30:47+00:00
disable breakpoints in forked threads to run TH in ext interp
and other merge artifacts that do not come from conflict
TODO: fix up to either the async rpc or to the global break changes,
depending on who lands first
the new tests pass; and we even observed that break032 fails without disableThreadBreakpoints
- - - - -
91bb01a4 by Rodrigo Mesquita at 2026-11-26T16:04:36+00:00
WIP: Start Async Eval/Resume
- - - - -
109 changed files:
- + changelog.d/28124
- compiler/GHC/Driver/Config.hs
- compiler/GHC/Linker/Loader.hs
- compiler/GHC/Runtime/Context.hs
- compiler/GHC/Runtime/Eval.hs
- compiler/GHC/Runtime/Eval/Types.hs
- compiler/GHC/Runtime/Interpreter.hs
- compiler/GHC/Runtime/Interpreter/Process.hs
- compiler/GHC/Tc/Errors/Types.hs
- compiler/GHC/Tc/Gen/Splice.hs
- ghc/GHCi/UI/Monad.hs
- libraries/ghc-boot-th/GHC/Boot/TH/Monad.hs
- libraries/ghc-boot-th/GHC/Boot/TH/Syntax.hs
- libraries/ghc-boot-th/ghc-boot-th.cabal.in
- libraries/ghc-internal/src/GHC/Internal/TH/Monad.hs
- libraries/ghci/GHCi/Message.hs
- libraries/ghci/GHCi/Message/Async.hs
- libraries/ghci/GHCi/Run.hs
- + libraries/ghci/GHCi/Run/Breakpoints.hs
- libraries/ghci/GHCi/Server.hs
- libraries/ghci/GHCi/Signals.hs
- libraries/ghci/GHCi/TH.hs
- libraries/ghci/ghci.cabal.in
- libraries/template-haskell/Language/Haskell/TH/Syntax.hs
- libraries/template-haskell/template-haskell.cabal.in
- rts/Interpreter.c
- testsuite/tests/concurrent/should_run/all.T
- testsuite/tests/ghci.debugger/scripts/Makefile
- testsuite/tests/ghci.debugger/scripts/T14690.stdout
- testsuite/tests/ghci.debugger/scripts/all.T
- testsuite/tests/ghci.debugger/scripts/break024.stdout
- + testsuite/tests/ghci.debugger/scripts/break032.hs
- + testsuite/tests/ghci.debugger/scripts/break032.script
- + testsuite/tests/ghci.debugger/scripts/break032.stdout
- + testsuite/tests/ghci.debugger/scripts/break033.hs
- + testsuite/tests/ghci.debugger/scripts/break033.script
- + testsuite/tests/ghci.debugger/scripts/break033.stdout
- + testsuite/tests/ghci.debugger/scripts/break034.hs
- + testsuite/tests/ghci.debugger/scripts/break034.script
- + testsuite/tests/ghci.debugger/scripts/break034.stdout
- + testsuite/tests/ghci.debugger/scripts/break042.hs
- + testsuite/tests/ghci.debugger/scripts/break042.script
- + testsuite/tests/ghci.debugger/scripts/break042.stderr
- + testsuite/tests/ghci.debugger/scripts/break042.stdout
- + testsuite/tests/ghci.debugger/scripts/break043.hs
- + testsuite/tests/ghci.debugger/scripts/break043.script
- + testsuite/tests/ghci.debugger/scripts/break043.stdout
- + testsuite/tests/ghci.debugger/scripts/break046.hs
- + testsuite/tests/ghci.debugger/scripts/break046.script
- + testsuite/tests/ghci.debugger/scripts/break046.stdout
- + testsuite/tests/ghci.debugger/scripts/break048.hs
- + testsuite/tests/ghci.debugger/scripts/break048.script
- + testsuite/tests/ghci.debugger/scripts/break048.stdout
- + testsuite/tests/ghci.debugger/scripts/break049.hs
- + testsuite/tests/ghci.debugger/scripts/break049.script
- + testsuite/tests/ghci.debugger/scripts/break049.stdout
- + testsuite/tests/ghci.debugger/scripts/break050.hs
- + testsuite/tests/ghci.debugger/scripts/break050.script
- + testsuite/tests/ghci.debugger/scripts/break050.stdout
- + testsuite/tests/ghci.debugger/scripts/break050ext.stdout
- + testsuite/tests/ghci/linking/UnloadWkrA.hs
- + testsuite/tests/ghci/linking/UnloadWkrB.hs
- testsuite/tests/ghci/linking/all.T
- + testsuite/tests/ghci/linking/unload_wkr-throw-ext.stderr
- + testsuite/tests/ghci/linking/unload_wkr-throw-ext.stdout
- + testsuite/tests/ghci/linking/unload_wkr-throw.script
- + testsuite/tests/ghci/linking/unload_wkr-throw.stderr
- + testsuite/tests/ghci/linking/unload_wkr-throw.stdout
- + testsuite/tests/ghci/should_run/ForceInterrupt.script
- + testsuite/tests/ghci/should_run/ForceInterrupt.stdout
- + testsuite/tests/ghci/should_run/ForceInterruptExt.stdout
- testsuite/tests/ghci/should_run/Makefile
- + testsuite/tests/ghci/should_run/T3171extnosandbox.stdout
- + testsuite/tests/ghci/should_run/T3171nosandbox.stdout
- testsuite/tests/ghci/should_run/all.T
- testsuite/tests/interface-stability/template-haskell-exports.stdout
- testsuite/tests/plugins/plugins10.stdout
- testsuite/tests/th/T8987d.hs
- + testsuite/tests/th/T8987d14.stderr
- + testsuite/tests/th/T8987d15.stderr
- + testsuite/tests/th/T8987d16.stderr
- + testsuite/tests/th/T8987d17.stderr
- + testsuite/tests/th/T8987d18.stderr
- + testsuite/tests/th/T8987d19.stderr
- + testsuite/tests/th/T8987d20.stderr
- + testsuite/tests/th/T8987d21.stderr
- + testsuite/tests/th/T8987d22.stderr
- + testsuite/tests/th/T8987d23.stderr
- + testsuite/tests/th/T8987d24.stderr
- + testsuite/tests/th/T8987d25.stderr
- + testsuite/tests/th/T8987d26.stderr
- + testsuite/tests/th/T8987d27.stderr
- + testsuite/tests/th/T8987d28.stderr
- + testsuite/tests/th/T8987d29.stderr
- + testsuite/tests/th/T8987d30.stderr
- + testsuite/tests/th/T8987d31.stderr
- + testsuite/tests/th/T8987d32.stderr
- + testsuite/tests/th/T8987d33.stderr
- + testsuite/tests/th/T8987d34.stderr
- + testsuite/tests/th/T8987d35.stderr
- + testsuite/tests/th/T8987d36.stderr
- + testsuite/tests/th/T8987d37.stderr
- + testsuite/tests/th/T8987d38.stderr
- + testsuite/tests/th/T8987d39.stderr
- + testsuite/tests/th/T8987d40.stderr
- + testsuite/tests/th/T8987d41.stderr
- + testsuite/tests/th/T8987d42.stderr
- + testsuite/tests/th/T8987d43.stderr
- testsuite/tests/th/all.T
The diff was not included because it is too large.
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0901ae77c768d2477ac84ffae36980…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/0901ae77c768d2477ac84ffae36980…
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
1
0
[Git][ghc/ghc][wip/jeltsch/portable-bco-byte-array-serialization] Switch from boolean to definedness test for `LITTLE_ENDIAN_64_BITS`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
773f0fda by Wolfgang Jeltsch at 2026-11-26T17:28:30+02:00
Switch from boolean to definedness test for `LITTLE_ENDIAN_64_BITS`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -20,7 +20,9 @@ module GHCi.ResolvedBCO
#error Bytecode serialization works only on 32- and 64-bit platforms.
#endif
-#define LITTLE_ENDIAN_64_BITS (!defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8)
+#if !defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8
+#define LITTLE_ENDIAN_64_BITS
+#endif
import Prelude -- See note [Why do we import Prelude here?]
@@ -41,7 +43,7 @@ import Foreign.Storable (Storable, sizeOf)
import GHC.Data.SmallArray (SmallArray)
import GHC.Generics (Generic)
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
import Control.Monad (replicateM)
#endif
@@ -100,7 +102,7 @@ data BCOByteArray a
getBCOByteArray :: !ByteArray#
}
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a
fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
@@ -148,7 +150,7 @@ instance Binary ResolvedBCO where
1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get
_ -> error "Binary ResolvedBCO: invalid byte"
-#if !LITTLE_ENDIAN_64_BITS
+#ifndef LITTLE_ENDIAN_64_BITS
-- | Serialize a 'BCOByteArray', not writing the payload verbatim but
-- serializing the individual elements. This can be used with any host
@@ -225,7 +227,7 @@ instance Binary (BCOByteArray Word16) where
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word) where
-#if LITTLE_ENDIAN_64_BITS
+#ifdef LITTLE_ENDIAN_64_BITS
put = putBCOByteArrayDirectly
get = getBCOByteArrayDirectly
#else
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/773f0fdac74241a9f96b5598eb26d76…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/773f0fdac74241a9f96b5598eb26d76…
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
1
0
[Git][ghc/ghc][wip/jeltsch/portable-bco-byte-array-serialization] Switch to using `#ifdef` and `#ifndef`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
fce533d8 by Wolfgang Jeltsch at 2026-11-26T17:26:05+02:00
Switch to using `#ifdef` and `#ifndef`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -46,7 +46,7 @@ import Control.Monad (replicateM)
#endif
isLittleEndian :: Bool
-#if defined(WORDS_BIGENDIAN)
+#ifdef WORDS_BIGENDIAN
isLittleEndian = False
#else
isLittleEndian = True
@@ -183,7 +183,7 @@ getBCOByteArrayPortably getElement = do
#endif
-#if !defined(WORDS_BIGENDIAN)
+#ifndef WORDS_BIGENDIAN
-- | Serialize a 'BCOByteArray', writing the payload verbatim instead of
-- serializing the individual elements. This must only be used when the host
@@ -214,7 +214,7 @@ getBCOByteArrayDirectly @a = do
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word16) where
-#if defined(WORDS_BIGENDIAN)
+#ifdef WORDS_BIGENDIAN
put = putBCOByteArrayPortably putWord16le
get = getBCOByteArrayPortably getWord16le
#else
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fce533d895359134b292f0f31a0918c…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/fce533d895359134b292f0f31a0918c…
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
1
0
[Git][ghc/ghc][wip/jeltsch/portable-bco-byte-array-serialization] Introduce and use a macro `LITTLE_ENDIAN_64_BITS`
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
by Wolfgang Jeltsch (@jeltsch) 26 Nov '26
26 Nov '26
Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC
Commits:
4a46820f by Wolfgang Jeltsch at 2026-11-26T17:20:30+02:00
Introduce and use a macro `LITTLE_ENDIAN_64_BITS`
- - - - -
1 changed file:
- libraries/ghci/GHCi/ResolvedBCO.hs
Changes:
=====================================
libraries/ghci/GHCi/ResolvedBCO.hs
=====================================
@@ -20,6 +20,8 @@ module GHCi.ResolvedBCO
#error Bytecode serialization works only on 32- and 64-bit platforms.
#endif
+#define LITTLE_ENDIAN_64_BITS (!defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8)
+
import Prelude -- See note [Why do we import Prelude here?]
import GHCi.RemoteTypes
@@ -39,7 +41,7 @@ import Foreign.Storable (Storable, sizeOf)
import GHC.Data.SmallArray (SmallArray)
import GHC.Generics (Generic)
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
import Control.Monad (replicateM)
#endif
@@ -98,7 +100,7 @@ data BCOByteArray a
getBCOByteArray :: !ByteArray#
}
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a
fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
@@ -146,7 +148,7 @@ instance Binary ResolvedBCO where
1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get
_ -> error "Binary ResolvedBCO: invalid byte"
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
+#if !LITTLE_ENDIAN_64_BITS
-- | Serialize a 'BCOByteArray', not writing the payload verbatim but
-- serializing the individual elements. This can be used with any host
@@ -223,12 +225,12 @@ instance Binary (BCOByteArray Word16) where
-- See Note [BCOByteArray serialization].
instance Binary (BCOByteArray Word) where
-#if defined(WORDS_BIGENDIAN) || SIZEOF_HSWORD == 4
- put = putBCOByteArrayPortably (putWord64le . fromIntegral)
- get = getBCOByteArrayPortably (fromIntegral <$> getWord64le)
-#else
+#if LITTLE_ENDIAN_64_BITS
put = putBCOByteArrayDirectly
get = getBCOByteArrayDirectly
+#else
+ put = putBCOByteArrayPortably (putWord64le . fromIntegral)
+ get = getBCOByteArrayPortably (fromIntegral <$> getWord64le)
#endif
-- Note [BCOByteArray serialization]
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a46820fb7cea7a57869a071729b605…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/4a46820fb7cea7a57869a071729b605…
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
1
0
[Git][ghc/ghc][wip/T28169] Simplifier: treat unlifted data-con fields as strict (#28169)
by Simon Peyton Jones (@simonpj) 26 Nov '26
by Simon Peyton Jones (@simonpj) 26 Nov '26
26 Nov '26
Simon Peyton Jones pushed to branch wip/T28169 at Glasgow Haskell Compiler / GHC
Commits:
750032e3 by Simon Peyton Jones at 2026-11-26T14:52:56+00:00
Simplifier: treat unlifted data-con fields as strict (#28169)
The Simplifier's fast path for "lazy" data constructors (no bangs) also
caught constructors with /unlifted/ fields, such as I# or (#,#). So
I# (case x of (a,b) -> a#)
did not get the StrictArg treatment, and the case was not floated out
to give (case x of (a,b) -> I# a#). This patch fixes that, and tidies
up quite a bit along the way.
* GHC.Core.DataCon
- `dcStricts` now always lines up 1-1 with `dataConRepArgTys`
(it used to be [] for an all-lazy constructor).
- New field `dcArgCbvInfos :: [ArgCbvInfo]`, one per /value/ argument of
the worker, /including/ existential coercion variables:
data ArgCbvInfo = ArgCbv | ArgCbn | ArgRepPoly
ArgCbv means "certainly evaluated" (a bang, or an unlifted type).
See Note [ArgCbvInfo], which explains why consumers treat ArgRepPoly
conservatively, but in opposite directions.
- Including the existential CoVars fixes a latent misalignment between
the strictness marks and the worker's value arguments; see (EXCO1) in
Note [Existential coercion variables].
- New field `dcIsLazy`: all arguments are ArgCbn.
The consumers (the worker's demand signature, dmdTransformDataConSig,
exprIsHNF, exprOkForSpeculation, SpecConstr, adjustFieldsIdInfo,
mkDupableAlt) now use `dataConRepArgCbvInfos`, or `dataConRepStrictness`
where the CoVars have already been dropped.
* Unary classes (#28183). (MkC e) is just `e`, so it is a value, or
ok-for-speculation, only if `e` is. exprIsHNF had a special case for
this, but app_ok did not, and so claimed that (MkC e) was always
ok-for-speculation. Now both have a special case. We do /not/ achieve
this by giving MkC a strict field: that leaks into DmdAnal, StrictArg
and the field seqs of Note [Strict fields in Core], and made T5321FD
allocate 10% more. See (UCM3b) in Note [Unary class magic].
* Simplifier: see Note [Simplifying data constructor applications]
- (SDC1) A completely lazy constructor still zooms straight to `rebuild`.
- (SDC2) Any other constructor goes straight to `rebuildCall`, skipping
simplOutId, with a new, much smaller, form of ArgInfo:
DataConArgInfo { ai_dc_app :: OutExpr, ai_dc_args :: [ArgCbvInfo] }
which has its own, much simpler, equation in `rebuildCall`. It needs
no rules, discounts, bottoming check or ArgSpec list. It is never
duplicated by Plan A of Note [Duplicating StrictArg]; see (DJ4).
* Making rebuildCall cheaper (it handles every function application, so
this benefits all programs):
- The general case of `rebuildCall` takes the ArgInfo apart once and
loops over the pieces that change, rather than allocating a fresh
ArgInfo for every argument.
- `ai_dmds` is now a `DmdType` rather than an infinite list of demands;
use the new `GHC.Types.Demand.splitArgDmd`. So we never build
(demands ++ repeat topDmd); and for a data constructor we can use the
worker's demand signature directly.
- `simplArg` no longer takes a `Maybe ArgInfo`; the one caller that
wanted an informative Stop continuation (rebuildCall) does it itself.
- The CallCtxt and SubDemand fields of `Stop` are strict.
- Rename `ai_fun` to `ai_fun_id`.
* Add `GHC.Utils.Misc.mapConst`, and use it for the many (map (const x) xs).
Compile-time allocation, relative to master, measured locally with stage-1
compilers (before the Simplifier improvements, CI showed T5321FD +10.5%,
T9961 +4.7%, T9020 +2.4%, T15164 +2.4%):
T5321FD -0.1%
T9961 -0.3%
T9020 +0.6%
T15164 -0.6%
Test: simplCore/should_compile/T28169
Co-Authored-By: Claude Opus 5.5 <noreply(a)anthropic.com>
- - - - -
23 changed files:
- compiler/GHC/Builtin/WiredIn/Types.hs
- compiler/GHC/Core/DataCon.hs
- compiler/GHC/Core/FamInstEnv.hs
- compiler/GHC/Core/Opt/DmdAnal.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/Simplify/Utils.hs
- compiler/GHC/Core/Opt/SpecConstr.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/Core/SimpleOpt.hs
- compiler/GHC/Core/TyCon.hs
- compiler/GHC/Core/Type.hs
- compiler/GHC/Core/Utils.hs
- compiler/GHC/Tc/Gen/HsType.hs
- compiler/GHC/Tc/Gen/Pat.hs
- compiler/GHC/Tc/TyCl.hs
- compiler/GHC/Tc/TyCl/Build.hs
- compiler/GHC/Tc/TyCl/Instance.hs
- compiler/GHC/Tc/TyCl/Utils.hs
- compiler/GHC/Types/Demand.hs
- compiler/GHC/Types/Id/Make.hs
- compiler/GHC/Utils/Misc.hs
- + testsuite/tests/simplCore/should_compile/T28169.hs
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Builtin/WiredIn/Types.hs
=====================================
@@ -626,7 +626,7 @@ typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol")
pcTyCon :: Name -> Maybe (CType GhcTc) -> [TyVar] -> [DataCon] -> TyCon
pcTyCon name cType tyvars cons
= mkAlgTyCon name (mkTyConKind bndrs res_kind) bndrs 0 res_kind
- (map (const Representational) tyvars)
+ (mapConst Representational tyvars)
cType
[] -- No stupid theta
(mkDataTyConRhs cons)
@@ -717,9 +717,10 @@ pcDataConWithFixity' declared_infix dc_name wrk_key rri
-- we call pcDataConWithFixity' with static TyCons in the same module.
-- See Note [Constructor tag allocation] and #14657
data_con = mkDataCon dc_name declared_infix prom_info
- (map (const no_bang) arg_tys)
- (map (const HsLazy) arg_tys)
- (map (const NotMarkedStrict) arg_tys)
+ (mapConst no_bang arg_tys)
+ (mapConst HsLazy arg_tys)
+ (mapConst NotMarkedStrict theta ++
+ mapConst NotMarkedStrict arg_tys)
[] -- No labelled fields
tyvars ex_tyvars
conc_tyvars
=====================================
compiler/GHC/Core/DataCon.hs
=====================================
@@ -44,14 +44,15 @@ module GHC.Core.DataCon (
dataConIsInfix,
dataConWorkId, dataConWrapId, dataConWrapId_maybe,
dataConImplicitTyThings,
- dataConRepStrictness,
+ dataConRepStrictness, dataConRepArgCbvInfos,
+ ArgCbvInfo(..), argCbvInfoStrictnessMark,
dataConImplBangs, dataConBoxer,
+ dataConRepIsLazy,
splitDataProductType_maybe,
-- ** Predicates on DataCons
isNullarySrcDataCon, isNullaryRepDataCon,
- isLazyDataConRep,
isTupleDataCon, isBoxedTupleDataCon, isUnboxedTupleDataCon,
isUnboxedSumDataCon, isCovertGadtDataCon, isUnaryClassDataCon,
isVanillaDataCon, isNewDataCon, isTypeDataCon, isBoxingDataCon,
@@ -523,17 +524,37 @@ data DataCon
-- See Note [Bangs on data constructor arguments]
dcStricts :: [StrictnessMark],
- -- One mark for every field of the DataCon worker;
- -- if it's empty, then all fields are lazy,
- -- otherwise 1-1 with dataConRepArgTys.
+ -- One mark for every field of the DataCon /worker/
+ -- INVARIANT: length dcStricts = length dataConRepArgTys
+ -- Relates only to user-specified strictness annotations,
+ -- not to liftedness or otherwise
+ -- E.g. data T a = MkT {-# UNPACK #-} !(S a) Int# !a
+ -- data S a = MkS a !a
+ -- Then the worker for MkT has four fields, the first two arising from
+ -- unpacking S. The corresponding strictness marks are [-,!,-,!]; again
+ -- the first two come from MkS
-- See also Note [Strict fields in Core] in GHC.Core
- -- for the effect on the strictness signature
+ -- for the effect on the strictness signature
+
+ dcArgCbvInfos :: [ArgCbvInfo],
+ -- One entry for each /value/ argument of the worker,
+ -- /including/ each CoVar in dcExTyCoVars
+ -- Unlike dcStricts, takes account of liftedness
+ -- INVARIANT: length dcArgCbvInfos = dataConRepArity
+ -- See (EXCO1) Note [Existential coercion variables]
+ -- and Note [ArgCbvInfo]
dcFields :: [FieldLabel],
-- Field labels for this constructor, in the
-- same order as the dcOrigArgTys;
-- length = 0 (if not a record) or dataConSourceArity.
+ dcIsLazy :: Bool,
+ -- True <=> all of dcArgCbvInfos are ArgCbn; that is
+ -- (a) all fields of the data con /worker/ are definitely lifted
+ -- (b) no field has a `StrictnessMark` that forces evaluation
+ -- So if `dcIsLazy` is True then all fields of the worker are lazy thunks
+
-- The curried worker function that corresponds to the constructor:
-- It doesn't have an unfolding; the code generator saturates these Ids
-- and allocates a real constructor when it finds one.
@@ -582,18 +603,30 @@ we can in Core. Consider having:
data T :: forall k. k -> k -> Constraint where
MkT :: forall k (a::k) (b::k).
- forall k' (c::k') (co::k'~k).
- (b ~# (c|>co)) => T k a b
+ forall k' (c::k') (co::k'~#k).
+ (b ~# (c|>co)) => !a -> T k a b
dcUnivTyVars = [k,a,b]
dcExTyCoVars = [k',c,co]
dcUserTyVarBinders = [k,a,k',c]
dcEqSpec = [b ~# (c|>co)]
dcOtherTheta = []
- dcOrigArgTys = []
+ dcOrigArgTys = [a]
dcRepTyCon = T
+ dcStricts = [NotMarkedStrict, MarkedStrict]
+ dcArgCbvInfos = [ArgCbv, ArgCbv, ArgCbv] -- (EXCO1)
+
+* `dataConKindEqSpec` returns [k'~k].
+* `dataConRepArgTys` returns [ b~#(c|>co), a ]
+
+(EXCO1) In a call of the data constructor worker we will see
+ MkT tk ta tb tk' tc (co1::tk'~#tk) (co2::tb~#(tc |> co1))
+ dcArgCbvInfos returns a [ArgCbvInfo] that lines up with all the
+ value arguments, /including/ co1. (Coercion arguments are unlifted,
+ hence ArgCbv; see Note [ArgCbvInfo].)
-Function call 'dataConKindEqSpec' returns [k'~k]
+ dcArgCbvInfos lines up with dcStricts almost always; they differ in length
+ only in the rare case that we have existential coercion variables
Note [DataCon arities]
~~~~~~~~~~~~~~~~~~~~~~
@@ -830,7 +863,7 @@ data DataConRep
, dcr_boxer :: DataConBoxer
- , dcr_arg_tys :: [Scaled Type] -- Final, representation argument types,
+ , dcr_arg_tys :: [Scaled Type] -- Final, representation /value/ argument types,
-- after unboxing and flattening,
-- and *including* all evidence args
@@ -853,7 +886,8 @@ type DataConEnv a = UniqFM DataCon a -- Keyed by DataCon
-- In the AST, the @SourceText@ is hidden inside the extension point
-- 'Language.Haskell.Syntax.Extension.XConDeclField'.
data HsSrcBang
- = HsSrcBang SourceText SrcUnpackedness SrcStrictness -- See Note [Pragma source text] in "GHC.Types.SourceText"
+ = HsSrcBang SourceText SrcUnpackedness SrcStrictness
+ -- See Note [Pragma source text] in "GHC.Types.SourceText"
deriving Data.Data
-- | Haskell Implementation Bang
@@ -861,14 +895,14 @@ data HsSrcBang
-- Bangs of data constructor arguments as generated by the compiler
-- after consulting HsSrcBang, flags, etc.
data HsImplBang
- = HsLazy -- ^ Lazy field, or one with an unlifted type
+ = HsLazy -- ^ Lazy field, or one with an unlifted type
+
| HsStrict Bool -- ^ Strict but not unpacked field
- -- True <=> we could have unpacked, but opted not to
- -- because of -O0.
- -- See Note [Detecting useless UNPACK pragmas]
- | HsUnpack (Maybe Coercion)
- -- ^ Strict and unpacked field
- -- co :: arg-ty ~ product-ty HsBang
+ -- True <=> we could have unpacked, but opted not to because of -O0
+ -- See Note [Detecting useless UNPACK pragmas]
+
+ | HsUnpack (Maybe Coercion) -- ^ Strict and unpacked field
+ -- co :: arg-ty ~ product-ty HsBang
deriving Data.Data
@@ -879,6 +913,51 @@ data HsImplBang
data StrictnessMark = MarkedStrict | NotMarkedStrict
deriving Eq
+-- | How a data constructor worker treats one of its value arguments
+-- See Note [ArgCbvInfo]
+data ArgCbvInfo
+ = ArgCbn -- ^ Call-by-need: definitely lifted, and no bang:
+ -- the worker does not evaluate the argument
+ | ArgCbv -- ^ Call-by-value: definitely unlifted, or has a bang
+ -- (MarkedStrict): the argument is certainly evaluated
+ | ArgRepPoly -- ^ No bang, but representation-polymorphic,
+ -- so we don't know whether it is lifted or not
+ deriving Eq
+
+argCbvInfoStrictnessMark :: ArgCbvInfo -> StrictnessMark
+-- Conservative: ArgRepPoly might be lifted, so NotMarkedStrict
+argCbvInfoStrictnessMark ArgCbv = MarkedStrict
+argCbvInfoStrictnessMark ArgCbn = NotMarkedStrict
+argCbvInfoStrictnessMark ArgRepPoly = NotMarkedStrict
+
+{- Note [ArgCbvInfo]
+~~~~~~~~~~~~~~~~~~~~
+`dcArgCbvInfos :: [ArgCbvInfo]` tells, for each value argument of a data
+constructor worker, whether that argument is certainly evaluated
+(ArgCbv), certainly not evaluated (ArgCbn), or we don't know
+(ArgRepPoly, e.g. the fields of an unboxed tuple (#,#), whose types
+are representation-polymorphic until instantiated).
+
+An argument is evaluated if it has an unlifted type, or if it is a strict
+field (see Note [Strict fields in Core] in GHC.Core). For many purposes
+these are the same thing, so we combine them here; e.g. both
+ K (case x of (a,b) -> a) where K has a strict field
+ I# (case x of (a,b) -> a#)
+should become (case x of (a,b) -> K a) in the Simplifier (#28169).
+
+Consumers must decide what to do with ArgRepPoly, and the right choice
+depends on the consumer, in opposite directions:
+
+* `GHC.Core.Opt.Simplify.Utils.dataConArgInfo` treats ArgRepPoly as /lazy/.
+ There "strict" licenses the StrictArg transformation, which is only an
+ optimisation; claiming laziness is always safe.
+
+* `exprIsHNF` (check_field) and `exprOkForSpeculation` (field_ok) in
+ GHC.Core.Utils treat ArgRepPoly as /possibly strict/. There, wrongly
+ claiming laziness would wrongly say that (K e) is a value even if `e`
+ is an unlifted expression that might diverge.
+-}
+
-- | An 'EqSpec' is a tyvar/type pair representing an equality made in
-- rejigging a GADT constructor
data EqSpec = EqSpec TyVar Type
@@ -950,9 +1029,8 @@ Terminology:
you the demand signature of the wrapper, if it exists.
These demand signatures are set in GHC.Types.Id.Make.mkDataConWorkId,
- computed from the single source of truth `dataConRepStrictness`, which is
- generated from `dcStricts`.
- Note that `dataConRepStrictness` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
+ computed from the single source of truth `dataConRepArgCbvInfos`.
+ So `dataConRepArgCbvInfos` lines up 1-1 with `idDmdSig (dataConWorkId dc)`.
Note [Detecting useless UNPACK pragmas]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1032,6 +1110,11 @@ instance Outputable StrictnessMark where
ppr MarkedStrict = text "!"
ppr NotMarkedStrict = empty
+instance Outputable ArgCbvInfo where
+ ppr ArgCbn = text "cbn"
+ ppr ArgCbv = text "cbv"
+ ppr ArgRepPoly = text "rep-poly"
+
instance Binary StrictnessMark where
put_ bh NotMarkedStrict = putByte bh 0
put_ bh MarkedStrict = putByte bh 1
@@ -1118,7 +1201,7 @@ mkDataCon name declared_infix prom_info
impl_bangs -- Must match orig_arg_tys 1-1
str_marks -- Must be empty or match dataConRepArgTys 1-1
fields
- univ_tvs ex_tvs conc_tvs user_tvbs
+ univ_tvs ex_tcvs conc_tvs user_tvbs
eq_spec theta
orig_arg_tys orig_res_ty rep_info rep_tycon tag
stupid_theta work_id rep
@@ -1132,44 +1215,62 @@ mkDataCon name declared_infix prom_info
= con
where
- is_vanilla = null ex_tvs && null eq_spec && null theta
- str_marks' | not $ any isMarkedStrict str_marks = []
- | otherwise = str_marks
-
- con = MkData {dcName = name, dcUnique = nameUnique name,
- dcVanilla = is_vanilla, dcInfix = declared_infix,
- dcUnivTyVars = univ_tvs,
- dcExTyCoVars = ex_tvs,
- dcConcreteTyVars = conc_tvs,
- dcUserTyVarBinders = user_tvbs,
- dcEqSpec = eq_spec,
- dcOtherTheta = theta,
- dcStupidTheta = stupid_theta,
- dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
- dcRepTyCon = rep_tycon,
- dcSrcBangs = arg_stricts, dcImplBangs = impl_bangs,
- dcStricts = str_marks',
- dcFields = fields, dcTag = tag, dcRepType = rep_ty,
- dcWorkId = work_id,
- dcRep = rep,
- dcSourceArity = length orig_arg_tys,
- dcRepArity = length rep_arg_tys + count isCoVar ex_tvs,
- dcPromoted = promoted }
+ is_vanilla = null ex_tcvs && null eq_spec && null theta
+ full_arg_info = replicate n_ex_co_vars ArgCbv -- Coercions are unlifted
+ ++ zipWith mk_arg_info str_marks rep_arg_tys
+ mk_arg_info str (Scaled _ ty)
+ | isMarkedStrict str = ArgCbv
+ | definitelyLiftedType ty = ArgCbn
+ | definitelyUnliftedType ty = ArgCbv
+ | otherwise = ArgRepPoly
+ is_lazy = all (== ArgCbn) full_arg_info
+
+ con = MkData { dcName = name
+ , dcUnique = nameUnique name
+ , dcInfix = declared_infix
+ , dcTag = tag
+ , dcVanilla = is_vanilla
+
+ , dcUnivTyVars = univ_tvs
+ , dcExTyCoVars = ex_tcvs
+ , dcConcreteTyVars = conc_tvs
+ , dcUserTyVarBinders = user_tvbs
+ , dcEqSpec = eq_spec
+ , dcOtherTheta = theta
+ , dcStupidTheta = stupid_theta
+ , dcOrigArgTys = orig_arg_tys
+ , dcOrigResTy = orig_res_ty
+
+ , dcRep = rep
+ , dcRepType = rep_ty
+ , dcRepTyCon = rep_tycon
+ , dcSrcBangs = arg_stricts
+ , dcImplBangs = impl_bangs
+ , dcStricts = assertPpr (equalLength str_marks rep_arg_tys)
+ (ppr name <+> ppr str_marks)
+ str_marks
+ , dcArgCbvInfos = full_arg_info
+ , dcIsLazy = is_lazy
+ , dcFields = fields
+ , dcWorkId = work_id
+ , dcSourceArity = length orig_arg_tys
+ , dcRepArity = n_ex_co_vars + length rep_arg_tys
+ , dcPromoted = promoted }
-- The 'arg_stricts' passed to mkDataCon are simply those for the
-- source-language arguments. We add extra ones for the
-- dictionary arguments right here.
- rep_arg_tys = dataConRepArgTys con
+ n_ex_co_vars = count isCoVar ex_tcvs
+ rep_arg_tys = dataConRepArgTys con
- rep_ty =
- case rep of
+ rep_ty = case rep of
-- If the DataCon has no wrapper, then the worker's type *is* the
-- user-facing type, so we can simply use dataConWrapperType.
NoDataConRep -> dataConWrapperType con
-- If the DataCon has a wrapper, then the worker's type is never seen
-- by the user. The visibilities we pick do not matter here.
- DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tvs $
+ DCR{} -> mkInfForAllTys univ_tvs $ mkTyCoInvForAllTys ex_tcvs $
mkScaledFunctionTys rep_arg_tys $
mkTyConApp rep_tycon (mkTyVarTys univ_tvs)
-- res_arg_tys is a mixture of TypeLike and ConstraintLike,
@@ -1192,8 +1293,8 @@ mkDataCon name declared_infix prom_info
prom_res_kind roles rep_info
roles = map (\tv -> if isTyVar tv then Nominal else Phantom)
- (univ_tvs ++ ex_tvs)
- ++ map (const Representational) (theta ++ map scaledThing orig_arg_tys)
+ (univ_tvs ++ ex_tcvs)
+ ++ mapConst Representational (theta ++ map scaledThing orig_arg_tys)
freshNames :: [Name] -> [Name]
-- Make an infinite list of Names whose Uniques and OccNames
@@ -1399,20 +1500,19 @@ isNullarySrcDataCon dc = dataConSourceArity dc == 0
isNullaryRepDataCon :: DataCon -> Bool
isNullaryRepDataCon dc = dataConRepArity dc == 0
-isLazyDataConRep :: DataCon -> Bool
--- ^ True <==> All fields are lazy
-isLazyDataConRep dc = null (dcStricts dc)
-
dataConRepStrictness :: DataCon -> [StrictnessMark]
-- ^ Give the demands on the runtime arguments of a Core DataCon worker
--- application.
--- The length of the list matches `dataConRepArgTys` (e.g., the number
--- of runtime arguments).
-dataConRepStrictness dc
- | isLazyDataConRep dc
- = replicate (dataConRepArity dc) NotMarkedStrict
- | otherwise
- = dcStricts dc
+-- application. Matches 1-1 with `dataConRepArgTys`
+dataConRepStrictness = dcStricts
+
+dataConRepArgCbvInfos :: DataCon -> [ArgCbvInfo]
+-- ^ Describes each value argument of a Core DataCon worker
+-- application, /including/ any existential CoVar args
+-- See Note [ArgCbvInfo] and (EXCO1) in Note [Existential coercion variables]
+dataConRepArgCbvInfos = dcArgCbvInfos
+
+dataConRepIsLazy :: DataCon -> Bool
+dataConRepIsLazy = dcIsLazy
dataConImplBangs :: DataCon -> [HsImplBang]
-- The implementation decisions about the strictness/unpack of each
@@ -1523,10 +1623,11 @@ dataConWrapperType (MkData { dcUserTyVarBinders = user_tvbs,
res_ty
-- | Finds the instantiated types of the arguments required to construct a
--- 'DataCon' representation
+-- data constructor worker application
-- NB: these INCLUDE any dictionary args
--- but EXCLUDE the data-declaration context, which is discarded
--- It's all post-flattening etc; this is a representation type
+-- but EXCLUDE the "stupid theta" data-declaration context, which is discarded
+--
+-- Result list is 1-1 with dataConRepArgTys, and dataConRepStrictness
dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints
-- However, it can have a dcTheta (notably it can be a
-- class dictionary, with superclasses)
@@ -1621,9 +1722,10 @@ dataConOrigArgTys dc = dcOrigArgTys dc
dataConOtherTheta :: DataCon -> ThetaType
dataConOtherTheta dc = dcOtherTheta dc
--- | Returns the arg types of the worker, including *all* non-dependent
--- evidence, after any flattening has been done and without substituting for
--- any type variables
+-- | Returns the arg types of the worker, after any flattening has been done and
+-- without substituting for any type variables
+--
+-- Includes evidence, namely `dcEqSpec` and `dcOtherTheta`
dataConRepArgTys :: DataCon -> [Scaled Type]
dataConRepArgTys (MkData { dcRep = rep
, dcEqSpec = eq_spec
@@ -1642,8 +1744,10 @@ dataConRepArgTys (MkData { dcRep = rep
-- I think it's because of the call in mkDataCon, which in turn feeds
-- into dcRepArity, which in turn is used in mkDataConWorkId.
-- c.f. #23022
- | otherwise -> assert (null eq_spec) $
- map unrestricted theta ++ orig_arg_tys
+ | otherwise -> assert (null eq_spec) $
+ -- null eq_spec: all GADTs go via DCR
+ -- See `dataConUserTyVarsNeedWrapper`
+ map unrestricted theta ++ orig_arg_tys
-- | The string @package:module.name@ identifying a constructor, which is attached
-- to its info table and used by the GHCi debugger and the heap profiler
=====================================
compiler/GHC/Core/FamInstEnv.hs
=====================================
@@ -828,7 +828,7 @@ mkSingleCoAxiom role ax_name tvs eta_tvs cvs fam_tc lhs_tys rhs_ty
-- Note [Storing compatibility]
where
branch = mkCoAxBranch tvs eta_tvs cvs lhs_tys rhs_ty
- (map (const Nominal) tvs)
+ (mapConst Nominal tvs)
(getSrcSpan ax_name)
-- | Create a coercion constructor (axiom) suitable for the given
=====================================
compiler/GHC/Core/Opt/DmdAnal.hs
=====================================
@@ -1020,15 +1020,16 @@ dmdTransform :: AnalEnv -- ^ The analysis environment
-- this function plus demand on its free variables
-- See Note [DmdSig: demand signatures, and demand-sig arity] in "GHC.Types.Demand"
dmdTransform env var sd
- -- Data constructors
+ -- Data constructor workers
| Just con <- isDataConWorkId_maybe var
= -- pprTraceWith "dmdTransform:DataCon" (\ty -> ppr con $$ ppr sd $$ ppr ty) $
- dmdTransformDataConSig (dataConRepStrictness con) sd
- -- See Note [DmdAnal for DataCon wrappers]
+ dmdTransformDataConSig (dataConRepArgCbvInfos con) sd
+ -- See Note [DmdAnal for DataCon wrappers]
| Just rhs <- dataConWrapUnfolding_maybe var
, WithDmdType dmd_ty _rhs' <- dmdAnal env sd rhs
= dmd_ty
+
-- Dictionary component selectors
-- Used to be controlled by a flag.
-- See #18429 for some perf measurements.
@@ -1036,10 +1037,12 @@ dmdTransform env var sd
= -- pprTrace "dmdTransform:DictSel" (ppr var $$ ppr (idDmdSig var) $$ ppr sd) $
dmdTransformDictSelSig (idDmdSig var) sd
-- Imported functions
+
| isGlobalId var
, let res = dmdTransformSig (idDmdSig var) sd
= -- pprTrace "dmdTransform:import" (vcat [ppr var, ppr (idDmdSig var), ppr sd, ppr res])
res
+
-- Top-level or local let-bound thing for which we use LetDown ('useLetUp').
-- In that case, we have a strictness signature to unleash in our AnalEnv.
| Just (sig, top_lvl) <- lookupSigEnv env var
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -64,6 +64,7 @@ import GHC.Builtin.KnownKeys( runRWKey, seqHashKey )
import GHC.Builtin.WiredIn.Ids( seqId )
import qualified GHC.Data.List.Infinite as Inf
+import GHC.Data.List.Infinite ( Infinite(..) )
import GHC.Data.Maybe ( isNothing, orElse, mapMaybe )
import GHC.Data.FastString
import GHC.Unit.Module ( moduleName )
@@ -75,7 +76,6 @@ import GHC.Utils.Logger
import GHC.Utils.Misc
import Control.Monad
-import Data.List.NonEmpty (NonEmpty (..))
{-
The guts of the simplifier is in this module, but the driver loop for
@@ -1639,7 +1639,7 @@ rebuild_go env expr cont
ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
, sc_cont = cont, sc_hole_ty = fun_ty }
- -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
; rebuild_go env (App expr arg') cont }
completeBindX :: SimplEnv
@@ -1841,27 +1841,21 @@ pushCast env co cont
go_mco (MCo co) opt cont = go co opt cont
simplArg :: SimplEnvIS -- ^ Used only for its InScopeSet
- -> Maybe ArgInfo -- ^ Just <=> This arg `ai` occurs in an app
- -- `f a1 ... an` where we have ArgInfo on
- -- how `f` uses `ai`, affecting the Stop
- -- continuation passed to 'simplExprC'
-> OutType -- ^ Type of the function applied to this arg
-> StaticEnv -> CoreExpr -- ^ Expression with its static envt
-> MOutCoercion -- Wrap this around the result
-> SimplM OutExpr
-simplArg _ _ _ (Simplified {}) arg mco
+-- Simplify an argument in a boring context
+-- c.f. the lazy-argument case of `rebuildCall`, which does the same,
+-- but with a more informative Stop continuation
+simplArg _ _ (Simplified {}) arg mco
= -- See Note [Avoid repeated simplification]
case mco of
MRefl -> return arg -- Vastly common case
MCo co -> return (mkCast arg co)
-simplArg env mb_arg_info fun_ty (UnSimplified arg_se) arg mco
- = do { let arg_env' = arg_se `setInScopeFromE` env
- arg_ty = funArgTy fun_ty
- stop = case mb_arg_info of
- Nothing -> mkBoringStop arg_ty
- Just ai -> mkLazyArgStop arg_ty ai
- cont = addCastMCo mco stop
- ; simplExprC arg_env' arg cont }
+simplArg env fun_ty (UnSimplified arg_se) arg mco
+ = simplExprC (arg_se `setInScopeFromE` env) arg $
+ addCastMCo mco (mkBoringStop (funArgTy fun_ty))
{-
************************************************************************
@@ -1920,7 +1914,7 @@ simpl_lam env bndr body (ApplyToVal { sc_arg = arg, sc_env = arg_se
-- in this round of the Simplifier
-> simplNonRecE env from_what bndr (arg, arg_env) body cont
- _ -> do { arg' <- simplArg env Nothing fun_ty arg_se arg arg_mco
+ _ -> do { arg' <- simplArg env fun_ty arg_se arg arg_mco
; completeBindX env from_what bndr arg' body cont }
}
where
@@ -2255,31 +2249,49 @@ zap the SubstEnv. This is VITAL. Consider
We'll clone the inner \x, adding x->x' in the id_subst Then when we
inline y, we must *not* replace x by x' in the inlined copy!!
-Note [Fast path for lazy data constructors]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-For applications of a /lazy/ data constructor worker, the full glory of
-rebuildCall is a waste of effort;
+Note [Simplifying data constructor applications]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+For applications of a data constructor worker, much of the work done for
+an ordinary function application is a waste of effort:
+* Workers are global, so there is no need to look in the substitution
* They never inline, obviously
* They have no rewrite rules
-* Lazy constructors don't need the `StrictArg` treatment.
-So it's fine to zoom straight to `rebuild` which just rebuilds the
-call in a very straightforward way.
-
-For a data constructor worker that is strict (see Note [Strict fields in Core])
-we take the slow path, so that we'll transform
- K (case x of (a,b) -> a) --> case x of (a,b) -> K a
-via the StrictArg case of rebuildCall
-
-Some programs have a /lot/ of data constructors in the source program
-(compiler/perf/T9961 is an example), so this fast path can be very
-valuable.
+* We know their argument strictness without looking at their type
+So `simplInId` takes a short cut:
+
+(SDC1) If the constructor is completely lazy (`dataConRepIsLazy`: all
+ arguments are lifted and none has a bang), there is nothing for
+ `rebuildCall` to do, so we zoom straight to `rebuild`, which just
+ rebuilds the call in a very straightforward way.
+
+ This is not just a nicety: `rebuildCall` costs noticeably more per
+ argument than `rebuild` (ArgInfo, ArgSpecs, argInfoExpr, closures), and
+ some programs have a /lot/ of data constructors (compiler/perf/T9961 is
+ an example). Sending lazy constructors through `rebuildCall` made T9961
+ allocate about 3% more, even with the specialised DataConArgInfo of (SDC2).
+
+(SDC2) Otherwise we go straight to `rebuildCall`, skipping `simplOutId`,
+ with a `DataConArgInfo` built by `dataConArgInfo`. `DataConArgInfo` is a
+ specialised form of `ArgInfo`, with far fewer fields: a worker has no
+ rules, no unfolding discounts, never diverges, and its argument strictness
+ is given by `dataConRepArgCbvInfos`. `rebuildCall` has a separate, much
+ simpler, equation for it.
+
+ We want `rebuildCall`, rather than `rebuild`, for its StrictArg treatment
+ of arguments that are evaluated: strict fields (see Note [Strict fields
+ in Core]), and unlifted arguments (#28169). E.g. we want
+ K (case x of (a,b) -> a) --> case x of (a,b) -> K a
+ I# (case x of (a,b) -> a#) --> case x of (a,b) -> I# a#
+ See Note [ArgCbvInfo] in GHC.Core.DataCon.
-}
simplInId :: SimplEnv -> InId -> SimplCont -> SimplM (SimplFloats, OutExpr)
simplInId env var cont
- | Just dc <- isDataConWorkId_maybe var
- , isLazyDataConRep dc -- See Note [Fast path for lazy data constructors]
- = rebuild env (Var var) cont
+ | Just dc <- isDataConWorkId_maybe var -- See Note [Simplifying data constructor applications]
+ = if dataConRepIsLazy dc
+ then rebuild env (Var var) cont -- (SDC1)
+ else rebuildCall (zapSubstEnv env) (dataConArgInfo dc) cont -- (SDC2)
+
| otherwise
= assertPpr (not (isCoVar var)) (ppr var) $
case substId env var of
@@ -2439,54 +2451,123 @@ rebuildCall :: SimplEnvIS -> ArgInfo -> SimplCont
-- it is usually empty, and regardless should be ignored.
-- Only the in-scope set matters, plus the seMode flags
--- Check the invariant
-rebuildCall env arg_info _cont
- | assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr arg_info) False
- = pprPanic "rebuildCall" empty
-
----------- Bottoming applications --------------
-rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_dmds = [] }) cont
- -- When we run out of demands, it means that the call is definitely bottom.
- -- See (TC2) in Note [Trimming the continuation for bottoming functions]
- = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
-
----------- Simplify type applications --------------
-rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
- = rebuildCall env (addTyArgTo info arg_ty hole_ty) cont
-
----------- Simplify value arguments --------------------
-rebuildCall env fun_info
- (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
- , sc_hole_ty = fun_ty, sc_cont = cont })
- | UnSimplified arg_env <- arg_se
- , isStrictArgInfo fun_info -- Strict arguments
- , seCaseCase env -- But only when case-of-case is on.
- -- See Note [Case-of-case and full laziness]
- = simplExprF (arg_env `setInScopeFromE` env) arg $
- addCastMCo arg_mco $
- StrictArg { sc_fun = fun_info, sc_fun_ty = fun_ty
- , sc_dup = NoDup
- , sc_cont = cont }
- -- Note [Shadowing in the Simplifier]
-
- | otherwise -- Lazy, or already simplified arguments
- -- DO NOT float anything outside, hence simplExprC
- -- There is no benefit (unlike in a let-binding), and we'd
- -- have to be very careful about bogus strictness through
- -- floating a demanded let.
- = do { arg' <- simplArg env (Just fun_info) fun_ty arg_se arg arg_mco
- ; rebuildCall env (addValArgTo fun_info arg' fun_ty) cont }
-
----------- No further useful info, revert to generic rebuild ------------
-rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_arg_specs, ai_rules = rules }) cont
- | null rules
- = rebuild env (argInfoExpr fun rev_arg_specs) cont
- | otherwise -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
- = do { let arg_specs = reverse rev_arg_specs
- ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
- ; case mb_match of
- Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
- Nothing -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
+-- NB: rebuildCall takes the ArgInfo apart once, and then loops with `go`,
+-- passing only the pieces that change from one argument to the next.
+-- We only re-package an ArgInfo when we need one, for a StrictArg
+-- continuation. This saves allocating a fresh ArgInfo record for every
+-- argument, which is measurable (e.g. compiler/perf/T9961).
+-- Similarly `go` loops over the [Demand] in the RemainingArgDmds; the
+-- Divergence (which says what happens when they run out) does not change.
+---------- Data constructor workers ------------
+-- A specialised, much simpler, version of the general case below
+-- See (SDC2) in Note [Simplifying data constructor applications]
+rebuildCall env (DataConArgInfo { ai_dc_app = app0, ai_dc_args = dc_args0 })
+ cont0
+ = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env) $
+ go app0 dc_args0 cont0
+ where
+ -- `app` is the data constructor applied to the arguments so far
+ go :: OutExpr -> [ArgCbvInfo] -> SimplCont -> SimplM (SimplFloats, OutExpr)
+ go app dc_args (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
+ = go (App app (Type arg_ty)) dc_args cont
+
+ go app (dc_arg : dc_args)
+ (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
+ , sc_hole_ty = fun_ty, sc_cont = cont })
+ | ArgCbv <- dc_arg -- Strict (or unlifted) field; ArgRepPoly is lazy
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ , UnSimplified arg_env <- arg_se
+ , seCaseCase env -- Only when case-of-case is on.
+ -- See Note [Case-of-case and full laziness]
+ = simplExprF (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ StrictArg { sc_fun = DataConArgInfo { ai_dc_app = app
+ , ai_dc_args = dc_arg : dc_args }
+ , sc_fun_ty = fun_ty
+ , sc_dup = NoDup
+ , sc_cont = cont }
+
+ | otherwise
+ = do { arg' <- simplArg env fun_ty arg_se arg arg_mco
+ ; go (App app arg') dc_args cont }
+
+ go app _ cont -- No rules for data constructors
+ = rebuild env app cont
+
+---------- The general case ------------
+rebuildCall env info@(ArgInfo { ai_fun_id = fun, ai_args = rev_args0, ai_rules = rules
+ , ai_encl = encl, ai_discs = discs0
+ , ai_dmds = dmd_ty0@(DmdType { dt_env = dmd_env0
+ , dt_args = dmds0 }) })
+ cont0
+ = assertPpr (checkSimplEnvIS env) (pprBadSimplEnvIS env $$ ppr info) $
+ go rev_args0 dmds0 discs0 cont0
+ where
+ go :: [ArgSpec] -> [Demand] -> Infinite Int -> SimplCont
+ -> SimplM (SimplFloats, OutExpr)
+
+ ---------- Bottoming applications --------------
+ go rev_args [] _ cont
+ | isDeadEndDiv (de_div dmd_env0) -- c.f. splitArgDmd
+ -- When we run out of demands, it means that the call is definitely bottom.
+ -- See (TC2) in Note [Trimming the continuation for bottoming functions]
+ = rebuild env (argInfoExpr fun rev_args) (mkBottomCont cont)
+
+ ---------- Simplify type applications --------------
+ go rev_args dmds discs (ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = cont })
+ = go (TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : rev_args) dmds discs cont
+
+ ---------- Simplify value arguments --------------------
+ go rev_args dmds discs@(Inf _ discs')
+ (ApplyToVal { sc_arg = arg, sc_env = arg_se, sc_cast = arg_mco
+ , sc_hole_ty = fun_ty, sc_cont = cont })
+ | UnSimplified arg_env <- arg_se
+ , seCaseCase env -- Only when case-of-case is on.
+ -- See Note [Case-of-case and full laziness]
+ , isStrUsedDmd dmd -- Strict arguments; c.f. isStrictArgInfo
+ -- NB: mkArgInfo makes unlifted args strict
+ = simplExprF (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ StrictArg { sc_fun = info { ai_args = rev_args, ai_discs = discs
+ , ai_dmds = dmd_ty0 { dt_args = dmds } }
+ , sc_fun_ty = fun_ty
+ , sc_dup = NoDup
+ , sc_cont = cont }
+ -- Note [Shadowing in the Simplifier]
+
+ | otherwise -- Lazy, or already simplified arguments
+ -- DO NOT float anything outside, hence simplExprC
+ -- There is no benefit (unlike in a let-binding), and we'd
+ -- have to be very careful about bogus strictness through
+ -- floating a demanded let.
+ = do { arg' <- case arg_se of
+ Simplified {} -- See Note [Avoid repeated simplification]
+ -> return (mkCastMCo arg arg_mco)
+ UnSimplified arg_env
+ -> simplExprC (arg_env `setInScopeFromE` env) arg $
+ addCastMCo arg_mco $
+ Stop (funArgTy fun_ty) (lazyArgCallCtxt encl discs)
+ (subDemandIfEvaluated dmd) -- c.f. mkLazyArgStop
+ ; go (ValArg { as_arg = arg', as_hole_ty = fun_ty, as_dmd = dmd } : rev_args)
+ dmds' discs' cont }
+ where
+ !(dmd, dmds') = case dmds of
+ dmd : dmds' -> (dmd, dmds')
+ [] -> (topDmd, [])
+ -- Not bottoming (see first equation of `go`),
+ -- so the default demand is topDmd
+ -- Bang: avoid allocating thunks for dmd and dmds'
+
+ ---------- No further useful info, revert to generic rebuild ------------
+ go rev_arg_specs _ _ cont
+ | null rules
+ = rebuild env (argInfoExpr fun rev_arg_specs) cont
+ | otherwise -- Try rules again: Plan (AFTER) in Note [When to apply rewrite rules]
+ = do { let arg_specs = reverse rev_arg_specs
+ ; mb_match <- tryRules env rules fun (map argSpecArg arg_specs)
+ ; case mb_match of
+ Just rule_match -> fireRuleAFTER env rule_match arg_specs cont
+ Nothing -> rebuild env (argInfoExpr fun rev_arg_specs) cont }
-----------------------------------
tryInlining :: SimplEnv -> Logger -> OutId -> SimplCont -> SimplM (Maybe OutExpr)
@@ -3649,7 +3730,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
| otherwise
= go vs the_strs
where
- the_strs = dataConRepStrictness con
+ the_strs = map argCbvInfoStrictnessMark (dataConRepArgCbvInfos con)
go [] [] = []
go (v:vs') strs | isTyVar v = v : go vs' strs
@@ -3659,7 +3740,7 @@ adjustFieldsIdInfo _scrut case_bndr bndr_swap con vs
ppr vs $$
ppr_with_length (map strdisp the_strs) $$
ppr_with_length (dataConRepArgTys con) $$
- ppr_with_length (dataConRepStrictness con))
+ ppr_with_length (dataConRepArgCbvInfos con))
where
ppr_with_length list
= ppr list <+> parens (text "length =" <+> ppr (length list))
@@ -4053,20 +4134,22 @@ This trimming can also be done with other continuations:
We implement the trimming in three parts:
-(TC1) In `mkArgInfo`, for a bottoming function, we make a list of `RemainingArgDmds`
- with a finite list of elements (in the example above, just one).
+(TC1) In `mkArgInfo`, for a bottoming function, we use its `DmdType` as the
+ `RemainingArgDmds`. It has a finite list of argument demands (in the example
+ above, just one), and a divergence that `isDeadEndDiv`.
- For comparison, note that, for non-bottoming functions, the `RemainingArgDmds`
- always finishes with an infinite list of `topDmd`.
+ For comparison, note that, for non-bottoming functions, the divergence is
+ not `isDeadEndDiv`, so `splitArgDmd` yields `topDmd` once the argument
+ demands run out.
-(TC2) In `rebuildCall`, when we run out of `RemainingArgDmds` we discard the
+(TC2) In `rebuildCall`, when `splitArgDmd` returns Nothing we discard the
remaining continuation.
After discarding the continuation, the types might not match, in which case
we leave behind a (case <hole> of {}) wrapper. See the call to `mkBottomCont`.
(TC3) In `mkDupableContWithDmds`, we similarly discard the continuation when
- we run out of `RemainingArgDmds`.
+ `splitArgDmd` returns Nothing.
-}
--------------------
@@ -4098,7 +4181,7 @@ mkDupableCont :: SimplEnvIS
-- extra let/join-floats and in-scope variables
, SimplCont) -- dup_cont: duplicable continuation
mkDupableCont env cont
- = mkDupableContWithDmds (zapSubstEnv env) (repeat topDmd) cont
+ = mkDupableContWithDmds (zapSubstEnv env) nopDmdType cont
mkDupableContWithDmds
:: SimplEnvIS -> RemainingArgDmds
@@ -4116,7 +4199,7 @@ mkDupableContWithDmds env remaining_dmds cont
-- => simply trim the continuation
-- c.f. the null-demands case in `rebuildCall`
-- See (TC3) in Note [Trimming the continuation for bottoming functions]
- | null remaining_dmds
+ | Nothing <- splitArgDmd remaining_dmds
= return (emptyFloats env, mkBottomCont cont)
mkDupableContWithDmds _ _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
@@ -4158,18 +4241,24 @@ mkDupableContWithDmds env _
(StrictArg { sc_fun = fun, sc_cont = cont
, sc_fun_ty = fun_ty })
-- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
- | isNothing (isDataConId_maybe (ai_fun fun))
+ | ArgInfo { ai_fun_id = fun_id, ai_dmds = fun_dmds, ai_args = args } <- fun
+ -- Not a DataConArgInfo: these always use Plan B, which is just as well,
+ -- because a DataConArgInfo does not record its arguments separately
+ , isNothing (isDataConId_maybe fun_id)
-- isDataConId: see point (DJ4) of Note [Duplicating join points]
+ -- NB: fun_id is never a data constructor /worker/ (they use
+ -- DataConArgInfo), but it can be a data constructor /wrapper/
, thumbsUpPlanA cont
= -- Use Plan A of Note [Duplicating StrictArg]
--- pprTrace "Using plan A" (ppr (ai_fun fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
- do { let _ :| dmds = expectNonEmpty (ai_dmds fun) -- See Invariant of StrictArg;
- -- ai_dmds is never empty
+-- pprTrace "Using plan A" (ppr (ai_fun_id fun) $$ text "args" <+> ppr (ai_args fun) $$ text "cont" <+> ppr cont) $
+ do { let dmds = case splitArgDmd fun_dmds of
+ Just (_, dmds) -> dmds
+ Nothing -> pprPanic "mkDupableContWithDmds" (ppr fun)
+ -- See Invariant of StrictArg
; (floats1, cont') <- mkDupableContWithDmds env dmds cont
-- Use the demands from the function to add the right
-- demand info on any bindings we make for further args
- ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env)
- (ai_args fun)
+ ; (floats_s, args') <- mapAndUnzipM (makeTrivialArg env) args
; return ( foldl' addLetFloats floats1 floats_s
, StrictArg { sc_fun = fun { ai_args = args' }
, sc_cont = cont'
@@ -4210,13 +4299,14 @@ mkDupableContWithDmds env dmds
-- let a = ...arg...
-- in [...hole...] a
-- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
- do { let dmd:|cont_dmds =
- -- We took care to handle an empty demand list at the start,
- -- ensuring this call to 'expectNonEmpty' does not panic (#27261).
- expectNonEmpty dmds
+ do { let (dmd, cont_dmds) = case splitArgDmd dmds of
+ Just prs -> prs
+ Nothing -> pprPanic "mkDupableContWithDmds:ApplyToVal" (ppr cont)
+ -- We took care to handle bottoming demands at the start,
+ -- ensuring this does not panic (#27261).
; (floats1, cont') <- mkDupableContWithDmds env cont_dmds cont
; let env' = env `setInScopeFromF` floats1
- ; arg' <- simplArg env' Nothing hole_ty se arg arg_mco
+ ; arg' <- simplArg env' hole_ty se arg arg_mco
; (let_floats2, triv_arg) <- makeTrivial env' NotTopLevel dmd (fsLit "karg") arg'
; let all_floats = floats1 `addLetFloats` let_floats2
; return ( all_floats
@@ -4281,10 +4371,10 @@ mkDupableStrictBind env arg_bndr join_rhs res_ty
, sc_cont = mkBoringStop res_ty } )
| otherwise
= do { join_bndr <- newJoinId [arg_bndr] res_ty
- ; let arg_info = ArgInfo { ai_fun = join_bndr
- , ai_rules = [], ai_args = []
- , ai_encl = False, ai_dmds = repeat topDmd
- , ai_discs = Inf.repeat 0 }
+ ; let arg_info = ArgInfo { ai_fun_id = join_bndr
+ , ai_rules = [], ai_args = []
+ , ai_encl = False, ai_dmds = nopDmdType
+ , ai_discs = Inf.repeat 0 }
; return ( addJoinFloats (emptyFloats env) $
unitJoinFloat $
NonRec join_bndr $
@@ -4306,10 +4396,9 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
| otherwise
= do { let rhs_ty' = exprType alt_rhs_in
- bangs
- | DataAlt c <- con
- = dataConRepStrictness c
- | otherwise = []
+ bangs = case con of
+ DataAlt dc -> map argCbvInfoStrictnessMark (dataConRepArgCbvInfos dc)
+ _ -> []
abstracted_binders = abstract_binders alt_bndrs bangs
=====================================
compiler/GHC/Core/Opt/Simplify/Utils.hs
=====================================
@@ -31,11 +31,11 @@ module GHC.Core.Opt.Simplify.Utils (
interestingCallContext,
-- ArgInfo
- ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo,
+ ArgInfo(..), ArgSpec(..), RemainingArgDmds, mkArgInfo, dataConArgInfo,
addValArgTo, addTyArgTo,
argInfoExpr, argSpecArg,
pushOutArgs, pushArgSpecs,
- isStrictArgInfo, lazyArgContext,
+ isStrictArgInfo, lazyArgContext, lazyArgCallCtxt,
abstractFloats,
@@ -44,7 +44,6 @@ module GHC.Core.Opt.Simplify.Utils (
) where
import GHC.Prelude hiding (head, init, last, tail)
-import qualified GHC.Prelude as Partial (head)
import GHC.Core
import GHC.Types.Literal ( isLitRubbish )
@@ -64,7 +63,8 @@ import GHC.Core.Unfold.Make
import GHC.Core.Opt.Simplify.Monad
import GHC.Core.Type hiding( substTy )
import GHC.Core.Coercion hiding( substCo )
-import GHC.Core.DataCon ( dataConWorkId, isNullaryRepDataCon )
+import GHC.Core.DataCon ( DataCon, ArgCbvInfo(..), dataConWorkId, isNullaryRepDataCon
+ , dataConRepArgCbvInfos )
import GHC.Core.Multiplicity
import GHC.Core.Opt.ConstantFold
@@ -150,7 +150,7 @@ Key points:
data SimplCont
= Stop -- ^ Stop[e] = e
OutType -- ^ Type of the <hole>
- CallCtxt -- ^ Tells if there is something interesting about
+ !CallCtxt -- ^ Tells if there is something interesting about
-- the syntactic context, and hence the inliner
-- should be a bit keener (see interestingCallContext)
-- Specifically:
@@ -158,7 +158,7 @@ data SimplCont
-- Inlining the call might allow the rule to fire
-- Never ValAppCxt (use ApplyToVal instead)
-- or CaseCtxt (use Select instead)
- SubDemand -- ^ The evaluation context of e. Tells how e is evaluated.
+ !SubDemand -- ^ The evaluation context of e. Tells how e is evaluated.
-- This fuels eta-expansion or eta-reduction without looking
-- at lambda bodies, for example.
--
@@ -212,7 +212,7 @@ data SimplCont
, sc_fun :: ArgInfo -- Specifies f, e1..en, whether f has rules, etc
-- plus demands and discount flags for *this* arg
-- and further args
- -- Invariant: ai_dmds and ai_discs are never empty
+ -- Invariant: (splitArgDmd ai_dmds) is never Nothing
, sc_fun_ty :: OutType -- Type of the function (f e1 .. en),
-- presumably (arg_ty -> res_ty)
-- where res_ty is expected by sc_cont
@@ -317,7 +317,10 @@ instance Outputable SimplCont where
ppr (StrictBind { sc_bndr = b, sc_cont = cont })
= (text "StrictBind" <+> ppr b) $$ ppr cont
ppr (StrictArg { sc_fun = ai, sc_cont = cont })
- = (text "StrictArg" <+> ppr (ai_fun ai)) $$ ppr cont
+ = (text "StrictArg" <+> pp_fun ai) $$ ppr cont
+ where
+ pp_fun (ArgInfo { ai_fun_id = fun }) = ppr fun
+ pp_fun (DataConArgInfo { ai_dc_app = app }) = ppr app
ppr (Select { sc_env = env, sc_bndr = bndr, sc_alts = alts, sc_cont = cont })
= (text "Select" <> braces (ppr env) <+> ppr bndr) $$
whenPprDebug (nest 2 $ ppr alts) $$ ppr cont
@@ -352,9 +355,9 @@ doesn't matter because we'll never compute them all.
data ArgInfo
= ArgInfo {
- ai_fun :: OutId, -- ^ The function
- ai_args :: [ArgSpec], -- ^ ...applied to these args (which are in *reverse* order)
- -- NB: all these argumennts are already simplified
+ ai_fun_id :: OutId, -- ^ The function
+ ai_args :: [ArgSpec], -- ^ ...applied to these args (which are in *reverse* order)
+ -- NB: all these argumennts are already simplified
ai_rules :: [CoreRule], -- ^ Rules for this function
ai_encl :: Bool,
@@ -365,6 +368,7 @@ data ArgInfo
ai_dmds :: RemainingArgDmds,
-- ^ Demands on remaining value arguments (beyond 'ai_args')
+ -- Take it apart with 'splitArgDmd'
ai_discs :: Infinite Int
-- ^ Discounts for remaining value arguments (beyond 'ai_args')
@@ -372,12 +376,32 @@ data ArgInfo
-- A non-zero value means: be keener to inline
}
+ -- | A specialised ArgInfo for a data constructor /worker/;
+ -- see Note [Simplifying data constructor applications]
+ -- in GHC.Core.Opt.Simplify.Iteration.
+ -- A worker has no rules, no unfolding discounts, never diverges, and
+ -- its argument strictness is fixed; so we need many fewer fields.
+ | DataConArgInfo {
+ ai_dc_app :: OutExpr, -- ^ The data constructor worker, applied to
+ -- the (simplified) arguments so far
+ -- NB: we never need to duplicate a StrictArg
+ -- whose sc_fun is a DataConArgInfo, so we do
+ -- not need the args separately; see point
+ -- (DJ4) of Note [Duplicating join points]
+ ai_dc_args :: [ArgCbvInfo] -- ^ Info about the remaining value arguments
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ }
+
-- | 'RemainingArgDmds' gives the demands on any remaining value arguments.
--
--- It is usually infinite (with 'topDmd's in the tail), but if it is finite it
--- guarantees that the function diverges after being applied to that number
--- of arguments.
-type RemainingArgDmds = [Demand]
+-- Take it apart with 'splitArgDmd'. When its 'dt_args' run out, the
+-- Divergence in its 'dt_env' says what happens next:
+-- * if 'isDeadEndDiv', the function diverges after being applied to that
+-- number of arguments; 'splitArgDmd' returns Nothing.
+-- * otherwise all further arguments have demand 'topDmd'
+-- See Note [Trimming the continuation for bottoming functions]
+-- in GHC.Core.Opt.Simplify.Iteration
+type RemainingArgDmds = DmdType
data ArgSpec
-- | A value argument
@@ -389,20 +413,31 @@ data ArgSpec
, as_hole_ty :: OutType } -- ^ Type of the function (presumably @t1 -> t2@ for 'ValArg' or @forall a. blah@ for 'TyArg')
instance Outputable ArgInfo where
- ppr (ArgInfo { ai_fun = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
+ ppr (ArgInfo { ai_fun_id = fun, ai_args = args, ai_dmds = dmds, ai_rules = rules })
= text "ArgInfo" <+> braces
(sep [ text "fun =" <+> ppr fun
- , text "dmds(first 10) =" <+> ppr (take 10 dmds)
+ , text "dmds =" <+> ppr dmds
, text "args =" <+> ppr args
, text "rewrite =" <+> ppr rules ])
+ ppr (DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args })
+ = text "DataConArgInfo" <+> braces
+ (sep [ text "app =" <+> ppr app
+ , text "dc_args =" <+> ppr dc_args ])
instance Outputable ArgSpec where
ppr (ValArg { as_arg = arg }) = text "ValArg" <+> ppr arg
ppr (TyArg { as_arg_ty = ty }) = text "TyArg" <+> ppr ty
addValArgTo :: ArgInfo -> OutExpr -> OutType -> ArgInfo
+addValArgTo ai@(DataConArgInfo { ai_dc_app = app, ai_dc_args = dc_args }) arg _hole_ty
+ | _ : dc_args' <- dc_args
+ = DataConArgInfo { ai_dc_app = App app arg, ai_dc_args = dc_args' }
+ | otherwise
+ = pprPanic "addValArgTo:DataConArgInfo" (ppr ai $$ ppr arg)
+
addValArgTo ai arg hole_ty
- | ArgInfo { ai_dmds = dmd:dmds, ai_discs = Inf _ discs } <- ai
+ | ArgInfo { ai_dmds = dmds0, ai_discs = Inf _ discs } <- ai
+ , Just (dmd, dmds) <- splitArgDmd dmds0
-- Pop the top demand and and discounts off
, let arg_spec = ValArg { as_arg = arg, as_hole_ty = hole_ty, as_dmd = dmd }
= ai { ai_args = arg_spec : ai_args ai
@@ -413,15 +448,40 @@ addValArgTo ai arg hole_ty
-- There should always be enough demands and discounts
addTyArgTo :: ArgInfo -> OutType -> OutType -> ArgInfo
-addTyArgTo ai arg_ty hole_ty = ai { ai_args = arg_spec : ai_args ai }
- where
- arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty }
+addTyArgTo ai@(DataConArgInfo { ai_dc_app = app }) arg_ty _hole_ty
+ = ai { ai_dc_app = App app (Type arg_ty) }
+addTyArgTo ai arg_ty hole_ty
+ = ai { ai_args = TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } : ai_args ai }
+
+argCbvInfoDmd :: ArgCbvInfo -> Demand
+-- The demand that a data constructor worker places on an argument
+-- Treat ArgRepPoly as lazy; see Note [ArgCbvInfo] in GHC.Core.DataCon
+-- c.f. GHC.Types.Id.Make.mkDataConWorkId, which makes the same choice
+argCbvInfoDmd ArgCbv = evalDmd
+argCbvInfoDmd ArgCbn = topDmd
+argCbvInfoDmd ArgRepPoly = topDmd
isStrictArgInfo :: ArgInfo -> Bool
-- True if the function is strict in the next argument
+isStrictArgInfo (DataConArgInfo { ai_dc_args = dc_args })
+ = case dc_args of { ArgCbv : _ -> True; _ -> False }
isStrictArgInfo (ArgInfo { ai_dmds = dmds })
- | dmd:_ <- dmds = isStrUsedDmd dmd
- | otherwise = False
+ | Just (dmd,_) <- splitArgDmd dmds = isStrUsedDmd dmd
+ | otherwise = False
+
+argInfoNextDmd :: ArgInfo -> Demand
+-- The demand on the next argument; the call should not be bottoming
+argInfoNextDmd ai@(DataConArgInfo { ai_dc_args = dc_args })
+ | dc_arg : _ <- dc_args = argCbvInfoDmd dc_arg
+ | otherwise = pprPanic "argInfoNextDmd" (ppr ai)
+argInfoNextDmd ai@(ArgInfo { ai_dmds = dmds })
+ | Just (dmd,_) <- splitArgDmd dmds = dmd
+ | otherwise = pprPanic "argInfoNextDmd" (ppr ai)
+
+argInfoHasRules :: ArgInfo -> Bool
+-- True <=> this function, or an enclosing one, has rules; see ai_encl
+argInfoHasRules (DataConArgInfo {}) = False
+argInfoHasRules (ArgInfo { ai_encl = encl }) = encl
pushOutArgs :: Type -> [OutExpr] -> SimplCont -> SimplCont
pushOutArgs _fun_ty [] cont
@@ -478,7 +538,7 @@ mkRhsStop ty is_rec bndr_dmd = Stop ty (RhsCtxt is_rec) (subDemandIfEvaluated bn
mkLazyArgStop :: OutType -> ArgInfo -> SimplCont
mkLazyArgStop ty fun_info = Stop ty (lazyArgContext fun_info) arg_sd
where
- arg_sd = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
+ arg_sd = subDemandIfEvaluated (argInfoNextDmd fun_info)
-------------------
contIsRhs :: SimplCont -> Maybe RecFlag
@@ -669,7 +729,7 @@ contEvalContext bndrs cont = go cont
, text "cont:" <+> ppr cont ])
topSubDmd
- go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (Partial.head (ai_dmds fun_info))
+ go (StrictArg{sc_fun=fun_info}) = subDemandIfEvaluated (argInfoNextDmd fun_info)
go (StrictBind{sc_bndr=bndr}) = subDemandIfEvaluated (idDemandInfo bndr)
go (Select{}) = topSubDmd
-- Perhaps reconstruct the demand on the scrutinee by looking at field
@@ -705,21 +765,29 @@ mkBottomCont cont = go cont
stop_cont = contStop k
-------------------
+dataConArgInfo :: DataCon -> ArgInfo
+-- Like mkArgInfo, but specialised for a data constructor worker
+-- See Note [Simplifying data constructor applications]
+-- in GHC.Core.Opt.Simplify.Iteration
+dataConArgInfo dc
+ = DataConArgInfo { ai_dc_app = Var (dataConWorkId dc)
+ , ai_dc_args = dataConRepArgCbvInfos dc }
+
mkArgInfo :: SimplEnv -> Id -> [CoreRule] -> SimplCont -> ArgInfo
mkArgInfo env fun rules_for_fun cont
| n_val_args < idArity fun -- Note [Unsaturated functions]
- = ArgInfo { ai_fun = fun, ai_args = []
+ = ArgInfo { ai_fun_id = fun, ai_args = []
, ai_rules = rules_for_fun
, ai_encl = False
- , ai_dmds = vanilla_dmds
+ , ai_dmds = nopDmdType
, ai_discs = vanilla_discounts }
| otherwise
- = ArgInfo { ai_fun = fun
- , ai_args = []
- , ai_rules = rules_for_fun
- , ai_encl = fun_has_rules || contHasRules cont
- , ai_dmds = add_type_strictness (idType fun) arg_dmds
- , ai_discs = arg_discounts }
+ = ArgInfo { ai_fun_id = fun
+ , ai_args = []
+ , ai_rules = rules_for_fun
+ , ai_encl = fun_has_rules || contHasRules cont
+ , ai_dmds = add_type_strictness (idType fun) arg_dmd_ty
+ , ai_discs = arg_discounts }
where
n_val_args = countValArgs cont
@@ -732,30 +800,19 @@ mkArgInfo env fun rules_for_fun cont
-> discounts Inf.++ vanilla_discounts
_ -> vanilla_discounts
- vanilla_dmds :: RemainingArgDmds
- vanilla_dmds = repeat topDmd
-
- arg_dmds :: RemainingArgDmds
- arg_dmds
+ arg_dmd_ty :: RemainingArgDmds
+ arg_dmd_ty
| not (seInline env)
- = vanilla_dmds -- See Note [Do not expose strictness if sm_inline=False]
- | otherwise
- = -- add_type_str fun_ty $
- case splitDmdSig (idDmdSig fun) of
- (demands, result_info)
- | not (demands `lengthExceeds` n_val_args)
- -> remaining_dmds -- Enough args, use the strictness given.
- | otherwise
- -> warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
+ = nopDmdType -- See Note [Do not expose strictness if sm_inline=False]
+ | DmdSig dmd_ty@(DmdType { dt_args = demands }) <- idDmdSig fun
+ = if not (demands `lengthExceeds` n_val_args)
+ then dmd_ty -- Enough args, use the strictness given.
+ -- If the divergence isDeadEndDiv, the result is bottom
+ -- after (length demands) args; see (TC1) in
+ -- Note [Trimming the continuation for bottoming functions]
+ else warnPprTrace True "More demands than arity" (ppr fun <+> ppr (idArity fun)
<+> ppr n_val_args <+> ppr demands) $
- vanilla_dmds -- Not enough args, or no strictness
-
- where
- remaining_dmds :: RemainingArgDmds
- -- isDeadEndDiv: if remaining_dmds is finite, result is bottom
- -- See (TC1) in Note [Trimming the continuation for bottoming functions]
- remaining_dmds | isDeadEndDiv result_info = demands
- | otherwise = demands ++ vanilla_dmds
+ nopDmdType -- Not enough args, or no strictness
add_type_strictness :: Type -> RemainingArgDmds -> RemainingArgDmds
-- If the function arg /types/ are strict, record that in the RemainingArgDmds
@@ -764,27 +821,35 @@ mkArgInfo env fun rules_for_fun cont
-- add_type_strictness is done repeatedly (for each call);
-- might be better once-for-all in the function
-- But beware primops/datacons with no strictness
-
- add_type_strictness fun_ty dmds
- | null dmds = []
-
- | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
- = add_type_strictness fun_ty' dmds -- Look through foralls
-
- | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty -- Add strict-type info
- , dmd : rest_dmds <- dmds
- , let dmd'
- | definitelyUnliftedType arg_ty
- = strictifyDmd dmd
- | otherwise
- -- Something that's not definitely unlifted.
- -- If the type is representation-polymorphic, we can't know whether
- -- it's strict.
- = dmd
- = dmd' : add_type_strictness fun_ty' rest_dmds
-
- | otherwise
- = dmds
+ add_type_strictness fun_ty dmd_ty@(DmdType { dt_env = dmd_env, dt_args = dmds0 })
+ = dmd_ty { dt_args = go fun_ty dmds0 }
+ where
+ -- NB: when the dt_args run out we must carry on (with the default
+ -- demand, topDmd) as long as there are more argument types, unless
+ -- the call is bottoming. c.f. splitArgDmd
+ is_bottoming = isDeadEndDiv (de_div dmd_env)
+ next_dmd (dmd : dmds) = Just (dmd, dmds)
+ next_dmd [] | is_bottoming = Nothing
+ | otherwise = Just (topDmd, [])
+
+ go fun_ty dmds
+ | Just (_, fun_ty') <- splitForAllTyCoVar_maybe fun_ty
+ = go fun_ty' dmds -- Look through foralls
+
+ | Just (_, _, arg_ty, fun_ty') <- splitFunTy_maybe fun_ty -- Add strict-type info
+ , Just (dmd, rest_dmds) <- next_dmd dmds
+ , let dmd'
+ | definitelyUnliftedType arg_ty
+ = strictifyDmd dmd
+ | otherwise
+ -- Something that's not definitely unlifted.
+ -- If the type is representation-polymorphic, we can't know whether
+ -- it's strict.
+ = dmd
+ = dmd' : go fun_ty' rest_dmds
+
+ | otherwise
+ = dmds
{- Note [Unsaturated functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -964,12 +1029,19 @@ the incentive to disappear when we inline `f`!
lazyArgContext :: ArgInfo -> CallCtxt
-- Use this for lazy arguments
+lazyArgContext (DataConArgInfo {}) = BoringCtxt
lazyArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
+ = lazyArgCallCtxt encl_rules discs
+
+lazyArgCallCtxt :: Bool -> Infinite Int -> CallCtxt
+-- Same as lazyArgContext, but taking the relevant pieces of the ArgInfo
+lazyArgCallCtxt encl_rules discs
| encl_rules = RuleArgCtxt
| Inf disc _ <- discs, disc > 0 = DiscArgCtxt -- Be keener here
| otherwise = BoringCtxt -- Nothing interesting
strictArgContext :: ArgInfo -> CallCtxt
+strictArgContext (DataConArgInfo {}) = RhsCtxt NonRecursive -- See comments below
strictArgContext (ArgInfo { ai_encl = encl_rules, ai_discs = discs })
-- Use this for strict arguments
| encl_rules = RuleArgCtxt
@@ -1050,7 +1122,7 @@ contHasRules cont
go (ApplyToVal { sc_cont = cont }) = go cont
go (ApplyToTy { sc_cont = cont }) = go cont
go (CastIt { sc_cont = cont }) = go cont
- go (StrictArg { sc_fun = fun }) = ai_encl fun
+ go (StrictArg { sc_fun = fun }) = argInfoHasRules fun
go (Stop _ RuleArgCtxt _) = True
go (TickIt _ c) = go c
go (Select {}) = False
=====================================
compiler/GHC/Core/Opt/SpecConstr.hs
=====================================
@@ -2605,7 +2605,7 @@ callToPat env bndr_occs call@(Call fn args con_env)
= do { let in_scope = substInScopeSet (sc_subst env)
; arg_triples <- argsToPats env in_scope con_env (idType fn) args bndr_occs
- (repeat NotMarkedStrict)
+ (repeat ArgCbn)
-- This trims the args to be no longer than
-- the lambdas in the function definition (bndr_occs)
@@ -2666,7 +2666,7 @@ argsToPats :: ScEnv
-> Type -- ^ type of the head (function or data constructor)
-> [CoreArg] -- ^ arguments of the head
-> [ArgOcc] -- ^ occurrence info, one per argument; the result is trimmed to this length
- -> [StrictnessMark] -- ^ strictness info, one per value argument
+ -> [ArgCbvInfo] -- ^ strictness info, one per value argument
-> UniqSM [(Bool, CoreArg, [Id])]
argsToPats env in_scope val_env = go
where
@@ -2674,7 +2674,7 @@ argsToPats env in_scope val_env = go
go _ _ [] _ = return []
go fun_ty (arg : args) (occ : occs) strs
= do { (pat, strs') <- case arg of
- Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ NotMarkedStrict
+ Type {} -> do { pat <- argToPat env in_scope val_env arg_ty arg occ ArgCbn
; return (pat, strs) }
_ | str : strs' <- strs
-> do { pat <- argToPat env in_scope val_env arg_ty arg occ str
@@ -2699,7 +2699,7 @@ argToPat :: ScEnv
-> Type -- ^ type for this argument
-> CoreArg -- ^ A call arg (or component thereof)
-> ArgOcc -- ^ occurrence info for the argument
- -> StrictnessMark -- ^ Tells us if this argument is a strict field of a data constructor
+ -> ArgCbvInfo -- ^ Tells us if this argument is a strict field of a data constructor
-- See Note [SpecConstr and strict fields]
-> UniqSM (Bool, CoreArg, [Id])
@@ -2726,7 +2726,7 @@ argToPat1 :: ScEnv
-> Type
-> Expr CoreBndr
-> ArgOcc
- -> StrictnessMark
+ -> ArgCbvInfo
-> UniqSM (Bool, Expr CoreBndr, [Id])
argToPat1 _env _in_scope _val_env _pat_ty arg@(Type {}) _arg_occ _arg_str
= return (False, arg, [])
@@ -2767,9 +2767,9 @@ argToPat1 env in_scope val_env _pat_ty arg arg_occ _arg_str
, not (ignoreDataCon env dc) -- See Note [NoSpecConstr]
, Just arg_occs <- mb_scrut dc
= do { let (ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) args
- con_str :: [StrictnessMark]
+ con_str :: [ArgCbvInfo]
-- con_str corresponds 1-1 with the /value/ arguments
- con_str = dataConRepStrictness dc
+ con_str = dataConRepArgCbvInfos dc
con_ty = applyTypeToArgs (dataConRepType dc) ty_args
-- ; pprTraceM "bangs" (ppr (length rest_args == length con_str) $$
-- ppr dc $$
@@ -2808,7 +2808,7 @@ argToPat1 env in_scope val_env _pat_ty (Var v) arg_occ arg_str
-- box that we can eliminate in the caller
, not (ignoreType env (varType v))
-- See Note [SpecConstr and strict fields]
- = return (True, Var v, if isMarkedStrict arg_str then [v] else mempty)
+ = return (True, Var v, if arg_str == ArgCbv then [v] else mempty)
where
is_value
| isLocalId v = v `elemInScopeSet` in_scope
@@ -2860,11 +2860,13 @@ argToPat1 _env _in_scope _val_env pat_ty _arg _arg_occ arg_str
= wildCardPat pat_ty arg_str
-- | wildCardPats are always boring
-wildCardPat :: Type -> StrictnessMark -> UniqSM (Bool, CoreArg, [Id])
+wildCardPat :: Type -> ArgCbvInfo -> UniqSM (Bool, CoreArg, [Id])
wildCardPat ty str
= do { id <- mkSysLocalOrCoVarM (fsLit "sc") ManyTy ty
-- ; pprTraceM "wildCardPat" (ppr id' <+> ppr (idUnfolding id'))
- ; return (False, varToCoreExpr id, if isMarkedStrict str then [id] else []) }
+ ; return (False, varToCoreExpr id, if str == ArgCbv then [id] else []) }
+ -- NB: unlifted (ArgCbv) args will be filtered out by
+ -- wantCbvForId in mkSeqs; see Note [SpecConstr and strict fields]
isValue :: ValueEnv -> CoreExpr -> Maybe Value
isValue _env (Lit lit)
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -221,7 +221,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
zapped_arg_vars = map zap_var arg_vars
; (subst, cloned_arg_vars) <- cloneBndrsM empty_subst zapped_arg_vars
; let res_ty' = substTyUnchecked subst res_ty
- init_str_marks = map (const NotMarkedStrict) cloned_arg_vars
+ init_str_marks = mapConst NotMarkedStrict cloned_arg_vars
; (useful1, work_args_str, wrap_fn_str, fn_args)
<- -- pprTrace "mkWWbodies" (ppr fun_id $$ ppr (arg_vars `zip` cloned_arg_vars) $$ ppr demands) $
@@ -1050,7 +1050,7 @@ unbox_one_arg opts arg_var
-- Mark arguments coming out of strict fields so we can seq them in the worker
-- See Note [Call-by-value for worker args]
- all_str_marks = (map (const NotMarkedStrict) ex_tvs') ++ con_str_marks
+ all_str_marks = mapConst NotMarkedStrict ex_tvs' ++ con_str_marks
; (nested_useful, worker_args, wrap_fn, wrap_args)
<- mkWWstr opts (ex_tvs' ++ arg_ids') all_str_marks
=====================================
compiler/GHC/Core/SimpleOpt.hs
=====================================
@@ -1726,12 +1726,10 @@ exprIsConApp_maybe ise@(ISE in_scope id_unf) expr
-- See Note [Strict fields in Core] for what a field seq is and (SFC2) for
-- why we insert them
mkFieldSeqFloats in_scope dc args
- | isLazyDataConRep dc
- = (in_scope, nilOL, args)
- | otherwise
- = (in_scope', floats', ty_args ++ val_args')
+ | dataConRepIsLazy dc = (in_scope, nilOL, args) -- Short cut in common case
+ | otherwise = (in_scope', floats', tyco_args ++ val_args')
where
- (ty_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
+ (tyco_args, val_args) = splitAtList (dataConUnivAndExTyCoVars dc) args
(in_scope', floats', val_args') = foldr do_one (in_scope, nilOL, []) $
zipEqual str_marks val_args
str_marks = dataConRepStrictness dc
=====================================
compiler/GHC/Core/TyCon.hs
=====================================
@@ -1504,16 +1504,27 @@ There are a number of wrinkles
(UCM2) The TyCon for a unary class is /not/ identified as a newtype.
Rather, it has its own AlgTyConRhs, namely `UnaryClassTyCon`
-(UCM3) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
+(UCM3a) Unlike non-unary classes, a value of type (C ty), where `C` is a unary
class, might be bottom, because it is represented by the method type alone.
See GHC.Core.Type.isTerminatingType, and Note [NON-BOTTOM-DICTS invariant]
in GHC.Core
- Similarly in exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval,
- in GHC.Core.Utils. In the utility funcion `app_ok` we need a special
- case for the DFunIds; they generally terminate, but not for unary classes.
-
-(UMC4) To avoid regressions, in Core we want to remember that
+(UCM3b) Following (UCM3a), (MkC e) is a value, or ok-for-speculation, only if
+ `e` is. So `GHC.Core.Utils.exprIsHNF`, `exprIsConLike`, and `app_ok`
+ (used by exprOkForSpeculation/exprOkToDiscard/exprOkForSpecEval) have a
+ special case for unary-class data constructors. (#28183 shows why this
+ matters.)
+
+ We do /not/ achieve this by giving the data constructor a strict field
+ data C a = MkC !(a->a)
+ That would be semantically fine, but it leaks into DmdAnal, the StrictArg
+ treatment in the Simplifier, and the field seqs of (SFC2) in Note [Strict
+ fields in Core]; for example (op dict x) would become
+ case $cop of m { __DEFAULT -> m x }
+ which bloats code (T5321FD got 10% worse). Those field seqs are pointless
+ for unary classes anyway, because of (UCM13).
+
+(UCM4) To avoid regressions, in Core we want to remember that
(MkUC x) is really just x
(op d) is really just d
We account for this in several places:
@@ -3065,8 +3076,8 @@ isUnaryClassTyCon tc@(TyCon { tyConDetails = details })
isTerminatingTyCon :: TyCon -> Bool
-- ^ True <=> a value of type (T t1..tn), where `T` is this TyCon, cannot be bottom.
--- The only TyCons that satisfy `isTerminatingTyCon` are non-unary class TyCons.
--- See (UCM3) in Note [Unary class magic], and
+-- The only TyCons that satisfy `isTerminatingTyCon` are /non-unary/ class TyCons.
+-- See (UCM3a) in Note [Unary class magic], and
-- Note [NON-BOTTOM-DICTS invariant] in GHC.Core.
-- An AbstractTyCon returns False: it comes from an hs-boot file, and the real
-- declaration may turn out to be a unary class. See (NBD2) in that Note.
=====================================
compiler/GHC/Core/Type.hs
=====================================
@@ -1781,7 +1781,7 @@ fun_kind_arg_flags = go emptySubst
where
argf | isVisibleFunArg af = Required
| otherwise = Inferred
- go _ _ arg_tys = map (const Required) arg_tys
+ go _ _ arg_tys = mapConst Required arg_tys
-- something is ill-kinded. But this can happen
-- when printing errors. Assume everything is Required.
=====================================
compiler/GHC/Core/Utils.hs
=====================================
@@ -2271,15 +2271,14 @@ app_ok fun_ok primop_ok fun val_args
| otherwise
= case idDetails fun of
DFunId terminating -> terminating
- -- DFuns terminate, unless the dict is implemented
- -- by a no-op in which case they may not
- -- See (UCM3) in Note [Unary class magic] in GHC.Core.TyCon
+ -- DFuns terminate, except for unary classes
+ -- See (UCM3a) in Note [Unary class magic] in GHC.Core.TyCon
DataConWorkId dc
- | isLazyDataConRep dc
- -> args_ok
- | otherwise
- -> fields_ok (dataConRepStrictness dc)
+ | isUnaryClassDataCon dc -> all ok_for_spec val_args
+ -- (MkC e) is just e; see (UCM3b) in Note [Unary class magic]
+ | dataConRepIsLazy dc -> True -- Args are all thunks
+ | otherwise -> fields_ok (dataConRepArgCbvInfos dc)
ClassOpId _ is_terminating_result
| is_terminating_result -- See Note [exprOkForSpeculation and type classes]
@@ -2344,13 +2343,16 @@ app_ok fun_ok primop_ok fun val_args
-- Used for strict DataCon worker arguments
-- See (SFC1) of Note [Strict fields in Core]
-- See Note [exprOkForSpeculation] (a,b)
- fields_ok str_marks = all3Prefix field_ok val_arg_tys str_marks val_args
- field_ok :: Type -> StrictnessMark -> CoreExpr -> Bool
- field_ok arg_ty str arg
- = ok_for_spec arg || (definitely_lifted arg_ty arg && str==NotMarkedStrict)
+ fields_ok arg_infos = all3Prefix field_ok val_arg_tys arg_infos val_args
+ field_ok :: Type -> ArgCbvInfo -> CoreExpr -> Bool
+ -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
+ field_ok _ ArgCbn _ = True
+ field_ok _ ArgCbv arg = ok_for_spec arg
+ field_ok arg_ty ArgRepPoly arg = arg_ok arg_ty arg
-- The (ok_for_spec arg) test works for /both/ for unlifted types, /and/
-- for lifted but strict fields. E.g. K (I# 3) is ok-for-spec,
-- even if K is strict
+ -- For ArgRepPoly, arg_ok looks at the type of the argument itself
-- We want to see if the argument type is definitely lifted.
-- But consider
@@ -2650,9 +2652,9 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
is_hnf_like e
where
is_hnf_like (Var v) -- NB: There are no value args at this point
- = id_app_is_value v [] -- Catches nullary constructors,
- -- so that [] and () are values, for example
- -- and (e.g.) primops that don't have unfoldings
+ = check_app v [] -- Catches nullary constructors,
+ -- so that [] and () are values, for example
+ -- and (e.g.) primops that don't have unfoldings
|| is_con_unf (idUnfolding v)
-- Check the thing's unfolding; it might be bound to a value
-- or to a guaranteed-evaluated variable (isEvaldUnfolding)
@@ -2687,67 +2689,75 @@ exprIsHNFlike is_con is_con_unf rubbish_lit_result e
= is_hnf_like rhs
is_hnf_like _ = False
- -- Collect arguments through Casts and Ticks and call id_app_is_value
+ -- Collect arguments through Casts and Ticks and call check_app
app_is_value :: CoreExpr -> [CoreArg] -> Bool
- app_is_value (Var f) as = id_app_is_value f as
+ app_is_value (Var f) as = check_app f as
app_is_value (Tick _ f) as = app_is_value f as
app_is_value (Cast f _) as = app_is_value f as
app_is_value (App f a) as | isValArg a = app_is_value f (a:as)
| otherwise = app_is_value f as
app_is_value _ _ = False
- id_app_is_value id val_args
- | Just dc <- isDataConWorkId_maybe id
- , isUnaryClassDataCon dc
- = all is_hnf_like val_args -- Look through unary class data cons
- | otherwise
- -- See Note [exprIsHNF for function applications]
- -- for the specification and examples
+ -- check_app: See Note [exprIsHNF for function applications]
+ -- for the specification and examples
+ -- We check arity (and CONLIKEness) first because it's cheaper
+ -- and we reject quickly on saturated apps.
+ check_app :: Id -> [CoreArg] -> Bool
+ check_app id val_args
= case compare (idArity id) (length val_args) of
- EQ | is_con id -> -- Saturated app of a DataCon/CONLIKE Id
- case mb_str_marks id of
- Just str_marks -> -- with strict fields; see (SFC1) of Note [Strict fields in Core]
- assert (val_args `equalLength` str_marks) $
- fields_hnf str_marks
- Nothing -> -- without strict fields: like PAP
- args_hnf -- NB: CONLIKEs are lazy!
-
- GT -> -- PAP: Check unlifted val_args
- args_hnf
+ EQ -> check_saturated id val_args -- Saturated application
+ GT -> check_args id val_args -- Partial application
+ LT -> False -- Over-saturated
- _ -> False
+ check_saturated :: Id -> [CoreArg] -> Bool
+ check_saturated id val_args
+ | Just dc <- isDataConWorkId_maybe id
+ , isUnaryClassDataCon dc -- (MkC e) is just e
+ = all is_hnf_like val_args -- See (UCM3b) in Note [Unary class magic]
+ | Just dc <- isDataConWorkId_maybe id
+ , let arg_infos = dataConRepArgCbvInfos dc
+ = -- Saturated data constructors; use `check_field`
+ -- to ensure we account for strict and unlifted fields
+ assertPpr (equalLength val_args arg_infos)
+ (ppr dc $$ ppr val_args $$ ppr arg_infos) $
+ all2Prefix check_field val_args arg_infos
+
+ | is_con id -- Saturated CONLIKE: check the arguments
+ = check_args id val_args
+
+ | otherwise -- Saturated function, not a constructor => not HNF
+ = False
+
+ -- check_args: check that any unlifted args are hnf-like
+ -- NB: there may be fewer val_args than arg_tys (e.g. (map f))
+ check_args :: Id -> [CoreArg] -> Bool
+ check_args id val_args = all2Prefix check_arg val_args arg_tys
where
- -- Saturated, Strict DataCon: Check unlifted val_args and strict fields
- fields_hnf str_marks = all3Prefix check_field val_arg_tys str_marks val_args
-
- -- PAP: Check unlifted val_args
- args_hnf = all2Prefix check_arg val_arg_tys val_args
-
- val_arg_tys = splitUninstantiatedValArgTys (idType id)
- -- val_arg_tys = map exprType val_args, but much less costly.
- -- The obvious definition regresses T16577 by 30% so we don't do it.
-
- check_arg a_ty a
- | mightBeUnliftedType a_ty = is_hnf_like a
- | otherwise = True
- -- Check unliftedness; for example f (x /# 12#) where f has arity two,
- -- and the first argument is unboxed. This is not a value!
- -- But f 34# is a value, so check args for HNFs.
- -- NB: We check arity (and CONLIKEness) first because it's cheaper
- -- and we reject quickly on saturated apps.
- check_field a_ty str a
- | mightBeUnliftedType a_ty = is_hnf_like a
- | isMarkedStrict str = is_hnf_like a
- | otherwise = True
- -- isMarkedStrict: Respect Note [Strict fields in Core]
-
- mb_str_marks id
- | Just dc <- isDataConWorkId_maybe id
- , not (isLazyDataConRep dc)
- = Just (dataConRepStrictness dc)
- | otherwise
- = Nothing
+ arg_tys = get_val_arg_tys id
+
+ -- check_arg: check unliftedness; for example f (x /# 12#) where f
+ -- has arity two, and the first argument is unboxed. This is not a value!
+ -- But f 34# is a value, so check unlifted args for HNFs.
+ check_arg arg arg_ty
+ | mightBeUnliftedType arg_ty = is_hnf_like arg
+ | otherwise = True
+
+ -- check_field: used for a data constructor worker:
+ -- check unlifted val_args /and/ strict fields
+ -- See (SFC1) of Note [Strict fields in Core]
+ -- Conservative: treat ArgRepPoly as possibly strict; see Note [ArgCbvInfo]
+ -- (check_arg would do the same, because the uninstantiated type of a
+ -- rep-poly field might be unlifted.)
+ check_field :: CoreArg -> ArgCbvInfo -> Bool
+ check_field _ ArgCbn = True
+ check_field arg ArgCbv = is_hnf_like arg
+ check_field arg ArgRepPoly = is_hnf_like arg
+
+ get_val_arg_tys id = splitUninstantiatedValArgTys (idType id)
+ -- val_arg_tys = map exprType val_args, but much less costly.
+ -- The obvious definition regresses T16577 by 30% so we don't do it.
+
{-
Note [exprIsHNF Tick]
@@ -2903,7 +2913,7 @@ dataConInstPat fss uniqs mult con inst_tys
ex_tvs = dataConExTyCoVars con
arg_tys = dataConRepArgTys con
arg_strs = dataConRepStrictness con -- 1-1 with arg_tys
- n_ex = length ex_tvs
+ n_ex = length ex_tvs
-- split the Uniques and FastStrings
(ex_uniqs, id_uniqs) = splitAt n_ex uniqs
=====================================
compiler/GHC/Tc/Gen/HsType.hs
=====================================
@@ -1369,7 +1369,7 @@ tc_hs_tuple_ty rn_ty mode HsBoxedOrConstraintTuple hs_tys exp_kind
checkExpectedKind hs_ty ty kind arg_kind
| ((L loc hs_ty),ty,kind) <- zip3 hs_tys tys kinds ]
- ; finish_tuple rn_ty tup_sort tys' (map (const arg_kind) tys') exp_kind }
+ ; finish_tuple rn_ty tup_sort tys' (mapConst arg_kind tys') exp_kind }
tc_hs_tuple_ty rn_ty mode HsUnboxedTuple tys exp_kind =
tc_tuple rn_ty mode UnboxedTuple tys exp_kind
=====================================
compiler/GHC/Tc/Gen/Pat.hs
=====================================
@@ -655,7 +655,7 @@ tc_pat scaled_exp_pat_ty@(Scaled w_pat exp_pat_ty) penv ps_pat thing_inside =
OrPat _ pats -> do -- See Note [Implementation of OrPatterns], Typechecker (1)
{ let pats_list = NE.toList pats
- pat_exp_tys = map (const scaled_exp_pat_ty) pats_list
+ pat_exp_tys = mapConst scaled_exp_pat_ty pats_list
; (pats_list', (res, pat_ct)) <- tc_lpats pat_exp_tys penv pats_list (captureConstraints thing_inside)
; let pats' = NE.fromList pats_list' -- tc_lpats preserves non-emptiness
; emitConstraints pat_ct
=====================================
compiler/GHC/Tc/TyCl.hs
=====================================
@@ -3713,7 +3713,7 @@ tcTyFamInstEqn fam_tc mb_clsinfo
-- (tcFamInstEqnGuts zonks to Type)
; let ax = mkCoAxBranch qtvs [] [] pats rhs_ty
- (map (const Nominal) qtvs)
+ (mapConst Nominal qtvs)
(locA loc)
vi = VI { vi_loc = locA loc
, vi_qtvs = qtvs
=====================================
compiler/GHC/Tc/TyCl/Build.hs
=====================================
@@ -291,9 +291,9 @@ type MethInfo -- A temporary intermediate, to communicate
buildClass :: Name -- Name of the class/tycon (they have the same Name)
-> Kind
- -> [TyConBinder] -- Of the tycon
+ -> [TyConBinder] -- Of the tycon
-> [Role]
- -> [FunDep TyVar] -- Functional dependencies
+ -> [FunDep TyVar] -- Functional dependencies
-> KnotTied ThetaType -- Superclasess
-> [ClassATItem] -- Associated types
-> [KnotTied MethInfo] -- Methods
@@ -330,7 +330,9 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
rec_tycon = classTyCon rec_clas
univ_bndrs = tyVarSpecToBinders $ tyConInvisTVBinders binders
univ_tvs = binderVars univ_bndrs
- bang_opts = FixedBangOpts (map (const HsLazy) args)
+ bang_opts = FixedBangOpts (mapConst HsLazy args)
+ -- NB: even for unary classes the field is lazy;
+ -- see (UCM3b) in Note [Unary class magic]
; rep_nm <- newTyConRepName datacon_name
; dict_con <- buildDataCon (panic "buildClass: FamInstEnvs")
@@ -338,7 +340,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
datacon_name
False -- Not declared infix
rep_nm
- (map (const no_bang) args)
+ (mapConst no_bang args)
[{- No fields -}]
univ_tvs
[{- no existentials -}]
@@ -353,8 +355,7 @@ buildClass tycon_name kind binders roles fds sc_theta at_items sig_stuff mindef
; let rhs | unary_class
= UnaryClassTyCon dict_con
| isCTupleTyConName tycon_name
- = TupleTyCon { data_con = dict_con
- , tup_sort = ConstraintTuple }
+ = TupleTyCon { data_con = dict_con, tup_sort = ConstraintTuple }
| otherwise
= mkDataTyConRhs [dict_con]
=====================================
compiler/GHC/Tc/TyCl/Instance.hs
=====================================
@@ -837,7 +837,7 @@ tcDataFamInstDecl mb_clsinfo tv_skol_env
rep_tc = mkAlgTyCon rep_tc_name user_kind
ty_binders (length extra_tcbs)
res_kind
- (map (const Nominal) ty_binders)
+ (mapConst Nominal ty_binders)
(fmap (typeCheckCType . unLoc) cType) stupid_theta
tc_rhs parent
gadt_syntax
=====================================
compiler/GHC/Tc/TyCl/Utils.hs
=====================================
@@ -471,7 +471,7 @@ initialRoleEnv hsc_src annots = extendNameEnvList emptyNameEnv .
initialRoleEnv1 :: HscSource -> RoleAnnotEnv -> TyCon -> (Name, [Role])
initialRoleEnv1 hsc_src annots_env tc
- | isFamilyTyCon tc = (name, map (const Nominal) bndrs)
+ | isFamilyTyCon tc = (name, mapConst Nominal bndrs)
| isAlgTyCon tc = (name, default_roles)
| isTypeSynonymTyCon tc = (name, default_roles)
| otherwise = pprPanic "initialRoleEnv1" (ppr tc)
=====================================
compiler/GHC/Types/Demand.hs
=====================================
@@ -59,7 +59,7 @@ module GHC.Types.Demand (
nopDmdType, botDmdType,
lubDmdType, maxDmdType, plusDmdType, multDmdType, discardArgDmds,
-- ** Other operations
- peelFV, findIdDemand, addDemand, splitDmdTy, deferAfterPreciseException,
+ peelFV, findIdDemand, addDemand, splitDmdTy, splitArgDmd, deferAfterPreciseException,
-- * Demand signatures
DmdSig(..), mkDmdSigForArity, mkClosedDmdSig, mkVanillaDmdSig,
@@ -92,7 +92,7 @@ import GHC.Types.Basic
import GHC.Data.Maybe ( orElse )
import GHC.Core.Type ( Type, isTerminatingType )
-import GHC.Core.DataCon ( splitDataProductType_maybe, StrictnessMark, isMarkedStrict )
+import GHC.Core.DataCon ( splitDataProductType_maybe, ArgCbvInfo(..) )
import GHC.Core.Multiplicity ( scaledThing )
import GHC.Utils.Binary
@@ -1996,6 +1996,24 @@ splitDmdTy :: DmdType -> (Demand, DmdType)
splitDmdTy ty@DmdType{dt_args=dmd:args} = (dmd, ty{dt_args=args})
splitDmdTy ty@DmdType{dt_env=env} = (defaultArgDmd (de_div env), ty)
+splitArgDmd :: DmdType -> Maybe (Demand, DmdType)
+-- ^ Split off the demand on the next argument of a function with this DmdType
+-- * Nothing <=> the call is definitely bottom; that is, we have run
+-- out of argument demands, and the divergence isDeadEndDiv
+-- * Just (d, ty') <=> d is the demand on the next argument
+-- Contrast `splitDmdTy`, which returns the default argument demand when
+-- we run out, rather than Nothing.
+-- Used in the Simplifier; see Note [Trimming the continuation for bottoming functions]
+-- in GHC.Core.Opt.Simplify.Iteration
+{-# INLINE splitArgDmd #-}
+splitArgDmd ty@(DmdType { dt_args = dmd : dmds })
+ = Just (dmd, ty { dt_args = dmds })
+splitArgDmd ty@(DmdType { dt_env = env })
+ | isDeadEndDiv div = Nothing
+ | otherwise = Just (defaultArgDmd div, ty)
+ where
+ div = de_div env
+
multDmdType :: Card -> DmdType -> DmdType
multDmdType C_11 dmd_ty = dmd_ty -- a vital optimisation for T25196
multDmdType n (DmdType fv args)
@@ -2487,17 +2505,19 @@ dmdTransformSig (DmdSig dmd_ty@(DmdType _ arg_ds)) sd
-- | A special 'DmdTransformer' for data constructors that feeds product
-- demands into the constructor arguments.
-dmdTransformDataConSig :: [StrictnessMark] -> DmdTransformer
+dmdTransformDataConSig :: [ArgCbvInfo] -> DmdTransformer
-- See Note [Demand transformer for data constructors]
-dmdTransformDataConSig str_marks sd = case viewProd arity body_sd of
+dmdTransformDataConSig arg_infos sd = case viewProd arity body_sd of
Just (_, dmds) -> mk_body_ty n dmds
Nothing -> nopDmdType
where
- arity = length str_marks
+ arity = length arg_infos
(n, body_sd) = peelManyCalls arity sd
- mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) str_marks dmds)
- bump n str dmd | isMarkedStrict str = multDmd n (plusDmd str_field_dmd dmd)
- | otherwise = multDmd n dmd
+ mk_body_ty n dmds = DmdType nopDmdEnv (zipWith (bump n) arg_infos dmds)
+ -- ArgRepPoly: treat as lazy, which is the conservative choice here
+ -- See Note [ArgCbvInfo] in GHC.Core.DataCon
+ bump n ArgCbv dmd = multDmd n (plusDmd str_field_dmd dmd)
+ bump n _ dmd = multDmd n dmd
str_field_dmd = seqDmd -- See the bit about strict fields
-- in Note [Demand transformer for data constructors]
=====================================
compiler/GHC/Types/Id/Make.hs
=====================================
@@ -541,7 +541,6 @@ mkDataConWorkId wkr_name data_con
univ_tvs = dataConUnivTyVars data_con
ex_tcvs = dataConExTyCoVars data_con
arg_tys = dataConRepArgTys data_con -- Should be same as dataConOrigArgTys
- str_marks = dataConRepStrictness data_con
----------- Workers for data types --------------
alg_wkr_info = noCafIdInfo
@@ -555,12 +554,22 @@ mkDataConWorkId wkr_name data_con
`setLFInfo` wkr_lf_info
wkr_inline_prag = alwaysConLikePragma
- wkr_arity = dataConRepArity data_con
- wkr_sig = mkClosedDmdSig wkr_dmds topDiv
- wkr_dmds = map mk_dmd str_marks
- mk_dmd MarkedStrict = evalDmd
- mk_dmd NotMarkedStrict = topDmd
+ -- Strictness signature has arity = wkr_arity
+ -- i.e. including any existential CoVars
+ -- See (EXCO1) in Note [Existential coercion variables]
+ wkr_arity = dataConRepArity data_con
+ arg_infos = dataConRepArgCbvInfos data_con
+ wkr_dmds = map mk_dmd arg_infos
+ wkr_sig = assertPpr (arg_infos `lengthIs` wkr_arity &&
+ splitUninstantiatedValArgTys wkr_ty `lengthIs` wkr_arity)
+ (ppr data_con $$ ppr arg_infos $$ ppr wkr_ty) $
+ mkClosedDmdSig wkr_dmds topDiv
+ -- NB: GHC.Core.Opt.Simplify.Utils.dataConArgInfo uses this signature,
+ -- and relies on ArgRepPoly being treated as lazy; see Note [ArgCbvInfo]
+ mk_dmd ArgCbv = evalDmd
+ mk_dmd ArgCbn = topDmd
+ mk_dmd ArgRepPoly = topDmd
-- See Note [LFInfo of DataCon workers and wrappers]
wkr_lf_info
@@ -824,7 +833,7 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
wrap_ty = dataConWrapperType data_con
ev_tys = eqSpecPreds eq_spec ++ theta
all_arg_tys = map unrestricted ev_tys ++ orig_arg_tys
- ev_ibangs = map (const HsLazy) ev_tys
+ ev_ibangs = mapConst HsLazy ev_tys
orig_bangs = dataConSrcBangs data_con
wrap_arg_tys
@@ -852,14 +861,14 @@ mkDataConRep platform dc_bang_opts fam_envs wrap_name data_con
arg_ibangs
| new_tycon
- = map (const HsLazy) orig_arg_tys -- See Note [HsImplBangs for newtypes]
- -- orig_arg_tys should be a singleton, but
- -- if a user declared a wrong newtype we
- -- detect this later (see test T2334A)
+ = mapConst HsLazy orig_arg_tys -- See Note [HsImplBangs for newtypes]
+ -- orig_arg_tys should be a singleton, but
+ -- if a user declared a wrong newtype we
+ -- detect this later (see test T2334A)
| otherwise
= case dc_bang_opts of
SrcBangOpts bang_opts -> zipWith (dataConSrcToImplBang platform bang_opts fam_envs)
- orig_arg_tys orig_bangs
+ orig_arg_tys orig_bangs
FixedBangOpts bangs -> bangs
(rep_tys_w_strs, wrappers)
@@ -999,11 +1008,11 @@ For further reading, see:
Note [Bangs on imported data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs
+We pass `DataConBangOpts` to `mkDataConRep` to make use of `HsImplBangs`
from imported modules.
-- Nothing <=> use HsSrcBangs
-- Just bangs <=> use HsImplBangs
+- SrcBangOpts opts <=> use HsSrcBangs
+- FixedBangOpts impl_bangs <=> use impl_bangs
For imported types we can't work it all out from the HsSrcBangs,
because we want to be very sure to follow what the original module
@@ -1011,8 +1020,8 @@ because we want to be very sure to follow what the original module
flags were enabled when it was compiled. So we record the decisions in
the interface file.
-The HsImplBangs passed are in 1-1 correspondence with the
-dataConOrigArgTys of the DataCon.
+The `HsImplBangs` passed are in 1-1 correspondence with the
+`dataConOrigArgTys` of the DataCon.
Note [Data con wrappers and unlifted types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Utils/Misc.hs
=====================================
@@ -18,7 +18,7 @@ module GHC.Utils.Misc (
unzipWith,
- mapFst, mapSnd, chkAppend,
+ mapFst, mapSnd, mapConst, chkAppend,
mapAndUnzip, mapAndUnzip3, mapAndUnzip4,
filterOut, partitionWith, partitionWithM,
@@ -329,6 +329,10 @@ mapSnd :: Functor f => (b->c) -> f(a,b) -> f(a,c)
mapFst = fmap . first
mapSnd = fmap . second
+mapConst :: a -> [b] -> [a]
+-- (mapConst k [a,b,c]) returns [k,k,k]
+mapConst k xs = [ k | _ <- xs ]
+
zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
zipWithAndUnzip f (a:as) (b:bs)
= let (r1, r2) = f a b
=====================================
testsuite/tests/simplCore/should_compile/T28169.hs
=====================================
@@ -0,0 +1,8 @@
+{-# LANGUAGE MagicHash #-}
+
+module T28169 where
+import GHC.Exts
+
+f :: Int# -> (Int,Int)
+f x = let y = I# (let z = x +# 1# in z *# z)
+ in (y + y, y * y)
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -631,3 +631,6 @@ test('T27936', normal, compile, [''])
test('T27910', grep_errmsg(r'KnownBranch'), compile, ['-O -dno-typeable-binds -ddump-simpl-stats -dsuppress-uniques'])
test('T27892', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
test('T28095a', grep_errmsg(r'^f = g$'), compile, ['-O -ddump-cse -dsuppress-all -dsuppress-uniques'])
+
+# T28169: test that there are no calls to boxed arithmetic,e.g. GHC.Internal.Num.$fNumInt_$c+
+test('T28169', grep_errmsg(r'\$c'), compile, ['-O -ddump-simpl -dsuppress-uniques'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/750032e34ac16192323604eed84a1b6…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/750032e34ac16192323604eed84a1b6…
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
1
0
26 Nov '26
Simon Peyton Jones pushed to branch wip/case-bndr-unf at Glasgow Haskell Compiler / GHC
Commits:
694da176 by Simon Peyton Jones at 2026-11-26T13:47:42+00:00
Add splitThunkCpr
This commit adds GHC.Core.Opt.WorkWrap.splitThunkCpr, which adds a form
of "thunk splitting" for strict bindings that have CPR information.
See Note [Thunk splitting] in WorkWrap.hs for the details.
It catches a previously-unrecognised optimisation opportunity
(see #28158) but it only helps in fairly obscure cases, so
I don't expect a big impact in practice.
As usually I did lots of refactoring along the way.
LLM disclosure: lots of interaction with Claude, but I wrote all the
code and comments.
- - - - -
11 changed files:
- compiler/GHC/Core/Opt/CprAnal.hs
- compiler/GHC/Core/Opt/Simplify/Iteration.hs
- compiler/GHC/Core/Opt/WorkWrap.hs
- compiler/GHC/Core/Opt/WorkWrap/Utils.hs
- compiler/GHC/HsToCore/Utils.hs
- compiler/GHC/Types/Cpr.hs
- compiler/GHC/Types/Id/Info.hs
- compiler/GHC/Utils/Monad.hs
- + testsuite/tests/simplCore/should_compile/T28158.hs
- + testsuite/tests/simplCore/should_compile/T28158.stderr
- testsuite/tests/simplCore/should_compile/all.T
Changes:
=====================================
compiler/GHC/Core/Opt/CprAnal.hs
=====================================
@@ -173,6 +173,25 @@ So currently we have
1. Strictness
2. CPR
3. worker/wrapper (for strictness and CPR)
+
+Wrinkles
+
+(CPR1) We have a flag `-fcpr-anal`, which sets `Opt_CprAnal`, enabled in -O1 and
+ -O1. Strangely, it does /not/ switch off CPR analysis! Rather, it just
+ switches off the worker/wrapper exploitation of CPR analysis, in `mkWWcpr_entry`.
+ The analysis itself runes whenever `-fstrictness` is on.
+
+ This is peculiar and, I suspect accidental. It would make more sense to switch
+ off the analysis itself with `-fno-cpr-anal`.
+
+ It goes back to at least
+ commit ecb1752ffa12dfa71053f640e6cce64d15e47e8f
+ Author: Christiaan Baaij <christiaan.baaij(a)gmail.com>
+ Date: Wed Aug 5 14:22:14 2015 +0200
+
+ Make -fcpr-off a dynamic flag
+
+ This note is just a breadcrumb to inform the next person who trips over this.
-}
--
@@ -343,7 +362,7 @@ cprTransform env id args
-- Any local binding, except for data structure bindings
-- See Note [Efficient Top sigs in SigEnv]
| Just sig <- lookupSigEnv env id
- = applyCprTy (getCprSig sig) (length args)
+ = applyCprTy (cprSigType sig) (length args)
-- See Note [CPR for data structures]
| Just rhs <- cprDataStructureUnfolding_maybe id
= fst $ cprAnal env rhs
@@ -362,7 +381,7 @@ cprTransform env id args
= cprTransformDataConWork env con args
-- Imported function
| otherwise
- = applyCprTy (getCprSig (idCprSig id)) (length args)
+ = applyCprTy (cprSigType (idCprSig id)) (length args)
-- | Precise, hand-written CPR transformers for select Ids
cprTransformBespoke :: Id -> [(CprType, CoreArg)] -> Maybe CprType
@@ -870,27 +889,42 @@ Does f have the CPR property? Well, no.
However, if the strictness analyser has figured out (in a previous
iteration) that it's strict, then we DON'T need to forget the CPR info.
Instead we can retain the CPR info and do the thunk-splitting transform
-(see WorkWrap.splitThunk).
+(see Note [Thunk splitting] esp (B) CPR-led thunk splitting).
This made a big difference to PrelBase.modInt, which had something like
modInt = \ x -> let r = ... -> I# v in
...body strict in r...
-r's RHS isn't a value yet; but modInt returns r in various branches, so
-if r doesn't have the CPR property then neither does modInt
+r's RHS isn't a value yet; but `modInt` returns `r` in various branches, so
+if `r` doesn't have the CPR property then neither does `modInt`
+
Another case I found in practice (in Complex.magnitude), looks like this:
- let k = if ... then I# a else I# b
- in ... body strict in k ....
+ let k* = if ... then I# a else I# b
+ in ... body strict in k ....
(For this example, it doesn't matter whether k is returned as part of
the overall result; but it does matter that k's RHS has the CPR property.)
+
Left to itself, the simplifier will make a join point thus:
- let $j k = ...body strict in k...
- if ... then $j (I# a) else $j (I# b)
+ let $j k = ...body strict in k...
+ if ... then $j (I# a) else $j (I# b)
+
With thunk-splitting, we get instead
- let $j x = let k = I#x in ...body strict in k...
- in if ... then $j a else $j b
+ let k* = case (if ... then I# a else I# b) of I# z -> I# z
+ in ... body strict in k ....
+Now the simplifier should pull out the `case` to give
+ case (if ... then I# a else I# b) of I# z ->
+ let k = I# z in ... body strict in k ...
+Now case-of-if will give
+ let $j z = let k = I# z in ...body strict in k... in
+ if ... then $j a else $j b
This is much better; there's a good chance the I# won't get allocated.
+TL'DR: During CPR analysis we want to give `k` the CPR property in `body`.
+
+What if the type involved has more than one constructor? E.g.
+ let k* = if ... then Just a else Just b
+ in ... body strict in k ....
+That is good too: see (TS5) in Note [Thunk splitting]
-But what about botCpr? Consider
+Finally, what about botCpr? Consider
lvl = error "boom"
fac -1 = lvl
fac 0 = 1
=====================================
compiler/GHC/Core/Opt/Simplify/Iteration.hs
=====================================
@@ -51,7 +51,6 @@ import GHC.Types.Literal ( litIsLifted ) --, mkLitInt ) -- temporarily comment
import GHC.Types.SourceText
import GHC.Types.Id
import GHC.Types.Id.Info
-import GHC.Types.Cpr( isTopCprSig )
import GHC.Types.InlinePragma
import GHC.Types.Name ( mkSystemVarName, isExternalName, getOccFS )
import GHC.Types.Demand
@@ -1830,7 +1829,7 @@ simplNonRecE :: HasDebugCallStack
simplNonRecE env from_what bndr (rhs, rhs_se) body cont
| assertPpr (isId bndr && not (isJoinId bndr)) (ppr bndr) True
- , useStrictBind env from_what bndr
+ , useStrictBind env from_what bndr rhs
= -- Evaluate RHS strictly
simplExprF (rhs_se `setInScopeFromE` env) rhs
(StrictBind { sc_bndr = bndr, sc_body = body, sc_from = from_what
@@ -1865,11 +1864,10 @@ simplRecE env pairs body cont
; return (floats1 `addFloats` floats2, expr') }
-useStrictBind :: SimplEnv -> FromWhat -> InId -> Bool
+useStrictBind :: SimplEnv -> FromWhat -> InId -> InExpr -> Bool
-- Can we use a StrictBind continuation for this let-binding?
--- If so, return a binder that is suitable to become a lambda binder,
--- i.e. one satisfying `lamBndrInfoOK`; see (SB3) in Note [StrictBind]
-useStrictBind env from_what bndr
+-- See (SB3) in Note [StrictBind]
+useStrictBind env from_what bndr rhs
-- If we are coming from a beta-reduction (FromBeta) we must
-- establish the let-can-float invariant, so we must go via StrictBind
-- If not, the invariant holds already, and it's optional.
@@ -1880,6 +1878,11 @@ useStrictBind env from_what bndr
| not (isStrUsedDmd dmd_info)
= False
+ -- Not if the RHS is ok-for-spec; no benefit. In particular if the RHS is a
+ -- value lambda, we return False: only thunks use StrictBind
+ | exprOkForSpeculation rhs
+ = False
+
-- Not if case-of-case is off
-- See (SB1) in Note [StrictBind]
| not (seCaseCase env)
@@ -1889,13 +1892,8 @@ useStrictBind env from_what bndr
= True
-- Not for things with RULES or INLINE or NOINLINE
- -- or with a strictnes or CPR signature -- all things we might lose
-- See (SB3) in Note [StrictBind]
- | isStableUnfolding (unfoldingInfo info)
- || not (isEmptyRuleInfo (ruleInfo info))
- || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
- || not (isNopSig (dmdSigInfo info))
- || not (isTopCprSig (cprSigInfo info))
+ | hasRulesOrInline info
= False
| otherwise
@@ -4243,9 +4241,8 @@ mkDupableAlt _env case_bndr jfloats (Alt con alt_bndrs alt_rhs_in)
, alt') }
-- See Note [Duplicated env]
-{-
-Note [Do not add unfoldings to join points at birth]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+{- Note [Do not add unfoldings to join points at birth]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this (#15360)
case (case (case (case ...))) of
@@ -4316,7 +4313,7 @@ The simplifier will find
(Var v) with continuation
Select (pn -> rn) (
Select [I# a -> I# a] (
- StrictBind body Stop
+ StrictBind body Stop))
So we'll call mkDupableCont on
Select [I# a -> I# a] (StrictBind body Stop)
@@ -4455,7 +4452,7 @@ hack and bit us in multiple small and not-so-small ways
Consider this
case (case .. ) of c {
- I# c# -> ....c....
+ I# c# -> ....c.... }
If we make a join point with c but not c# we get
$j = \c -> ....c....
@@ -4655,30 +4652,56 @@ We simplify `rhs` with a StrictBind continuation that continues with
invariants] in GHC.Core. But a let-binder `x` usually has IdInfo that a
lambda binder may not have (an unfolding, arity, a demand signature...).
- So `useStrictBind_maybe` zaps that info, keeping only the occurrence info
- and the demand info. If it happens to stay as a let-binding arity info will
- be re-derived, so nothing is lost.
+ So when we duplicate StrictBind, in `mkDupableContWithDmds`, we use
+ `mkLamBndrFromLetBndr` to zap that info, keeping only the occurrence
+ info and the demand info.
- The exceptions are RULES, a stable unfolding, and a non-default inlining
- activation: these cannot be re-derived, and we have nowhere convenient to
- put them if `x` becomes a lambda binder. For example:
+ However, if the let-binder has
+ * RULES
+ * a stable unfolding
+ * a non-default inlining activation
+ we'd permanently lose these things if we lambda-bind it. For example:
let {-# NOINLINE x #-}
x! = case y of { ... }
in blah
- If we make a join point j x = blah, we have nowhere convenient
- to put that NOINLINE. Ditto INLINE or RULES. So in these cases we
- simply don't use StrictBind. It's very unusual, so no harm done.
- But it does happen; one example is this, in the Applicative (ST s)
- instance in GHC.Internal.Control.Monad.St.Lazy.Imp
+ If we make a join point j x = blah, we have nowhere convenient to put that
+ NOINLINE. Ditto INLINE or RULES. It's unusual. But it happens; one example
+ is the Applicative (ST s) instance in GHC.Internal.Control.Monad.St.Lazy.Imp
{-# NOINLINE res1 #-}
!res1 = unST fm s
- TL;DR: the sc_bndr::Id field in StrictBind always satisfies `lamBndrInfoOK`.
- This means that in the above example { x! = case y of ... } we won't
- float the `case y` out. And perhaps that's fine because of the NOINLNE.
- We could imagine instead imposing these conditions only when we /duplicate/
- the StrictBind, rather than when we /create/ it, but that would require a
- bigger refactor.
+ So in these cases we simply don't use StrictBind -- see `useStrictBind`. We
+ could imagine instead imposing these conditions only when we /duplicate/ the
+ StrictBind, rather than when we /create/ it, but that would require a bigger
+ refactor. See (SB5) for why we don't worry if the binder has strictness or
+ CPR information.
+
+(SB4) Shortcoming: not using StrictBind has a cost. If we have
+ {-# NOINLINE x #-}
+ x! = case y of (a,b) -> a
+ then isnce x is used strictly, we'd usually float that `case y` outwards -- but
+ we do so precisely by using StrictBind. But since the NOINLINE stops us using
+ StrictBind we won't float out the case.
+
+ Fixing this would require `mkDupableCont` to return a non-duplicable tail of
+ the continuation (declining to duplicate a StrictBind with a NOINLINE, say).
+ But that's a lot of plumbing for a very narrow case. Who writes INLINE or NOINLINE
+ or RULES for a thunk? So we just accept the shortcoming.
+
+(SB5) What if a thunk has a strictness signature, or CPR information? We
+ could make `useStrictBind` say False in these cases too, but that turns
+ out to be a net loss: keeping a thunk is worse than losing the strictness
+ information. Example, where f1,f2 are both strict:
+ let f* {- Str=<S> -} = case x of { True -> f1; False -> f2 }
+ in body
+ Keeping it as-is would use CBV for calls of `f` in `body`. But
+ allowing StrictBind would give us
+ join j f* = body
+ in case x of { True -> j f1; False -> j f2 }
+ which avoids the thunk. It's a trade-off.
+
+ For CPR info, see Note [Thunk splitting] in GHC.Core.Opt.WorkWrap,
+ especially (B) CPR-led thunk splitting.
Note [Join point abstraction] Historical note
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
=====================================
compiler/GHC/Core/Opt/WorkWrap.hs
=====================================
@@ -598,13 +598,20 @@ tryWW ww_opts is_rec fn_id rhs
= splitFun ww_opts new_fn_id rhs
-- See Note [Thunk splitting]
- | isNonRec is_rec, is_thunk
- = splitThunk ww_opts is_rec new_fn_id rhs
+ | isNonRec is_rec -- See (TS4)
+ , is_thunk -- All join points go via splitFun
+ , not (hasRulesOrInline (fn_info)) -- See (TS9)
+ = do { -- Try strictness then CPR; see (TS5)
+ rhs' <- splitThunkStr ww_opts new_fn_id rhs `orElseM`
+ splitThunkCpr ww_opts new_fn_id rhs `orElseM`
+ return rhs
+ ; return [ (new_fn_id, rhs') ] }
| otherwise
= return [ (new_fn_id, rhs) ]
where
+ is_join = isJoinId fn_id
fn_info = idInfo fn_id
(wrap_dmds, _) = splitDmdSig (dmdSigInfo fn_info)
new_fn_id = zap_join_cpr $ zap_usage fn_id
@@ -613,14 +620,13 @@ tryWW ww_opts is_rec fn_id rhs
-- See Note [Zapping DmdEnv after Demand Analyzer] and
-- See Note [Zapping Used Once info in WorkWrap]
- zap_join_cpr id
- | isJoinId id = id `setIdCprSig` topCprSig
- | otherwise = id
+ zap_join_cpr id | is_join = id `setIdCprSig` topCprSig
+ | otherwise = id
-- See Note [Don't w/w join points for CPR]
- is_fun = notNull wrap_dmds || isJoinId fn_id
- is_thunk = not is_fun && not (exprIsHNF rhs) && not (isJoinId fn_id)
- && not (isUnliftedType (idType fn_id))
+ is_fun = notNull wrap_dmds || is_join
+ is_thunk = not (exprIsHNF rhs)
+ && not (isUnliftedType (idType fn_id))
{-
Note [Zapping DmdEnv after Demand Analyzer]
@@ -806,7 +812,7 @@ splitFun ww_opts fn_id rhs
(wrap_dmds, div) = splitDmdSig (dmdSigInfo fn_info)
- cpr_ty = getCprSig (cprSigInfo fn_info)
+ cpr_ty = cprSigType (cprSigInfo fn_info)
-- Arity of the CPR sig should match idArity when it's not a join point.
-- See Note [Arity trimming for CPR signatures] in GHC.Core.Opt.CprAnal
cpr = assertPpr (isJoinId fn_id || cpr_ty == topCprType || ct_arty cpr_ty == arityInfo fn_info)
@@ -957,114 +963,182 @@ the form [Demand=<L,1*(C(1,...(C(1,U))))>]
Note [Thunk splitting]
~~~~~~~~~~~~~~~~~~~~~~
-Suppose x is used strictly; never mind whether it has the CPR
-property. I'll use a '*' to mean "x* is demanded strictly".
-
- let
- x* = x-rhs
+The worker/wrapper split mainly affects let-bound /functions/. But we can also use
+demand and CPR information to improve let-bound /thunks/. Specifically:
+
+* (A) Demand-led thunk splitting:
+ If a thunk is demanded strictly, perhaps nestedly, we can turn it into a
+ case, perhaps nestedly. For example
+ let x :: (Int, Int)
+ {- Dmd = SP(S,L) -}
+ x = rhs
+ in body
+ We would ultimately like to get
+ case rhs of x { (a,b) ->
+ case a of { I# a# ->
+ body
+
+ This is much better: no thunk for `rhs`; and known-data-con unfoldings for `x`
+ and `a` inside `body`.
+
+* (B) CPR-led thunk splitting:
+ If a thunk has the (possibly-nested) CPR property /and/ is demanded strictly
+ at top level, we can again generate a case
+ let x :: (Int, Int)
+ {- Dmd = S, Cpr = (_, I# _) -}
+ x = rhs
+ in body
+ The CPR info says that if `x` is evaluated (which it is), it'll return a pair,
+ whose second component can very cheaply be evaluated to a (I# b#). We would
+ like to end up with
+ case rhs of x { (a,b) ->
+ case b of { I# b# ->
+ body
+ which is good for the same reasons as before. See (TS3) for an example.
+
+Implementation
+~~~~~~~~~~~~~~
+The worker/wrapper pass does not generate these nested case expressions directly.
+Instead it generates a regular let-binding but, since the binder is marked as
+strict, any `case` expressions in the RHS will float out. Specifically:
+
+(TS1) For (A), `splitThunkStr` generates the binding
+ let x! = case rhs of { (a,b) ->
+ case a of { I# a# ->
+ (I# a, b)
+ Now when the Simplifier floats the `case` expressions out, we get
+ case rhs of { (a,b) ->
+ case a of { I# a# ->
+ let x = (I# a, b)
in body
+ which is equivalent to the expression in (A) above.
-splitThunk transforms like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> I# a }
- in body
+ `splitThunkStr` also works on /absent/ thunks: see (TS6).
-This is a little strange: we are re-using the same `x` in the RHS; and
-the RHS takes `x` apart and reboxes it. But because the outer 'let' is
-strict, and the inner let mentions `x` only once, the simplifier
-transform it to
- case x-rhs of
- I# a -> let x* = I# a
- in body
-
-That is good: in `body` we know the form of `x`, which
- * gives the CPR property, and
- * allows case-of-case to happen on x
-
-Notes
-* I tried transforming like this:
- let
- x* = let x = x-rhs in
- case x of { I# a -> x }
- in body
- where I return `x` itself, rather than reboxing it. But this
- turned out to cause some regressions, which I never fully
- investigated.
-
-* Suppose x-rhs is itself a case:
- x-rhs = case e of { T -> I# e1; F -> I# e2 }
- Then we'll get
- join j a = let x* = I# a in body
- in case e of { T -> j e1; F -> j e2 }
- which is good (no boxing). But in the original, unsplit program
- we would transform
- let x* = case e of ... in body
- ==> join j2 x = body
- in case e of { T -> j2 (I# e1); F -> j (I# e2) }
- which is not good (boxing).
+ Rather cleverly, `splitThunkStr` uses `mkWWstr_one`, the /existing/ function
+ argument w/w splitting function, to do the unpacking. This automatically
+ deals with nested strictness.
-* In fact, splitThunk uses the function argument w/w splitting
- function, mkWWstr_one, so that if x's demand is deeper (say U(U(L,L),L))
- then the splitting will go deeper too.
+(TS2) For (B), `splitThunkCpr` behaves exactly analogously, again
+ using `mkWWcpr_one` to do the unpacking. It works only for /demanded/ thunks.
-* For recursive thunks, the Simplifier is unable to float `x-rhs` out of
- `x*`'s RHS, because `x*` occurs freely in `x-rhs`, and will just change it
- back to the original definition, so we just split non-recursive thunks.
+Wrinkles:
-Note [Thunk splitting for top-level binders]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Top-level bindings are never strict. Yet they can be absent, as T14270 shows:
-
- module T14270 (mkTrApp) where
- mkTrApp x y
- | Just ... <- ... typeRepKind x ...
- = undefined
- | otherwise
- = undefined
- typeRepKind = Tick scc undefined
-
-(T19180 is a profiling-free test case for this)
-Note that `typeRepKind` is not exported and its only use site in
-`mkTrApp` guards a bottoming expression. Thus, demand analysis
-figures out that `typeRepKind` is absent and splits the thunk to
-
- typeRepKind =
- let typeRepKind = Tick scc undefined in
- let typeRepKind = absentError in
- typeRepKind
-
-But now we have a local binding with an External Name
-(See Note [About the NameSorts]). That will trigger a CoreLint error, which we
-get around by localising the Id for the auxiliary bindings in 'splitThunk'.
+(TS3) Here's an example of (B), thunk-splitting based on CPR information.
+ Suppose we have
+ let x! = case e of { T -> Just e1; F -> Just e2 }
+ in body
+ If the Simplifier floats the `case` out, we get
+ join j2 x = body
+ in case e of { T -> j2 (Just e1); F -> j2 (Just e2) }
+ which is not good (boxing).
+
+ If we first do the thunk-splitting transformation, we get
+ let x! = case (case e of { T -> Just e1; F -> Just e2 }) of
+ Just a -> Just a
+ in body
+
+ Now when the Simplifier floats we will get:
+ join j a = let x = Just a in body
+ in case e of { T -> j e1; F -> j e2 }
+ which is much better (no boxing). But see (TS9).
+
+(TS4) We only do thunk-splitting for thunks that are non-recursive
+ For recursive thunks, the Simplifier is unable to float `rhs` out of
+ x's RHS, because `x` occurs freely in `rhs`, and will just change it
+ back to the original definition.
+
+(TS5) Notice that (B) CPR-led thunk splitting can be useful:
+ * when multi-constructor data types are involved, so that the argument-unboxing
+ mechanism (A) is impotent. See the example in (TS3), which uses `Maybe`.
+ * when the binder is only demanded head-strictly, but CPR has nested information.
+
+ So (A) and (B) have complementary benefits. We might do even better by
+ /combining/ (A) and (B), but at the moment we try (A) first, and then try (B)
+ if (A) is impotent. Combining them would be more work.
+
+(TS6) We can also exploit /absence/. Consider
+ let x {-# Dmd = A #-} = rhs
+ in body
+ Generally speaking `x` will be absent becuase it is passed to functions that
+ don't use it, in which case worker/wrapper on those calls will make `x` unused.
+ But suppose `x` is absent inside a /lazy/ argument:
+ let f p = (fst p, 99) in
+ let x = rhs in
+ f (True, x)
+ Here f's argument is lazy, but `x` is definitely absent, and we could replace
+ `x` with an absent filler. Using (TS1) would give us
+ let x = absentError "urk" in ...
+ which is great.
+
+ So `splitThunkStr` works /regardless/ of the demand on `x`; whether it fires is
+ determined only by the `useful` flag returned by `mkWWstr_one`.
+
+(TS7) Adopting (TS6) leads to one other complication: a top-level binder with
+ an External Name (see Note [About the NameSorts]) can be Absent. If so,
+ it must not be used as a local binder in the `Let` created by `splitThunkStr`.
+ T19180 is a test case for this rather obscure situation.
+
+ Solution: use `localiseId` to localise the binder for the `Let`.
+
+(TS8) Consider out poster child test case for `splitThunkCpr`, in (TS3).
+ x! = case e of { True -> Just 1; False -> Just 2 }
+ But suppose we have `-fworker-wrapper-cbv` enabled (reminder: see
+ Note [Worker/wrapper for strict arguments]). Then alas `splitThunkStr`
+ will fire, but it'll be a no-op in this case. But since it fires, `splitThunkCpr`
+ never gets a chance.
+
+ Hacky but effective solution: switch off `wo_unlift_strict` locally in `splitThunkStr`.
+
+(TS9) `splitThunkStr` implicitly relies on floating a case out of a strict binding.
+ But if the thunk has a RULE or INLINE/NOINLINE pragma that won't happen; see
+ (SB4) in Note [StrictBind] in GHC.Core.Opt.Simplify.Iteration. So we test
+ these things before applying thunk splitting.
-}
--- | See Note [Thunk splitting].
---
--- splitThunk converts the *non-recursive* binding
+-- | splitThunkStr converts the *non-recursive* binding
-- x = e
-- into
--- x = let x' = e in
--- case x' of I# y -> let x' = I# y in x'
--- See comments above. Is it not beautifully short?
--- Moreover, it works just as well when there are
--- several binders, and if the binders are lifted
--- E.g. x = e
--- --> x = let x' = e in
--- case x' of (a,b) -> let x' = (a,b) in x'
--- Here, x' is a localised version of x, in case x is a
--- top-level Id with an External Name, because Lint rejects local binders with
--- External Names; see Note [About the NameSorts] in GHC.Types.Name.
---
--- How can we do thunk-splitting on a top-level binder? See
--- Note [Thunk splitting for top-level binders].
-splitThunk :: WwOpts -> RecFlag -> Var -> Expr Var -> UniqSM [(Var, Expr Var)]
-splitThunk ww_opts is_rec x rhs
- = assert (not (isJoinId x)) $
- do { let x' = localiseId x -- See comment above
- ; (useful,_args, wrap_fn, fn_arg)
- <- mkWWstr_one ww_opts x' NotMarkedStrict
- ; let res = [ (x, Let (NonRec x' rhs) (wrap_fn fn_arg)) ]
- ; if useful then assertPpr (isNonRec is_rec) (ppr x) -- The thunk must be non-recursive
- return res
- else return [(x, rhs)] }
+-- x = let x = e in
+-- case x of I# y -> I# y
+-- See Note [Thunk splitting].
+splitThunkStr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+splitThunkStr ww_opts x rhs
+ = -- NB: does not depend on x's demand being strict; it might be absent, see (TS6)
+ do { let x' = localiseId x -- See (TS7)
+ ww_opts' = ww_opts { wo_unlift_strict = False } -- See (TS8)
+ ; (useful, _transit_vars, wrap_fn, fn_arg) <- mkWWstr_one ww_opts' x' NotMarkedStrict
+ -- Use mkWWstr_one: see (TS1) in Note [Thunk splitting]
+
+ ; if useful
+ then return (Just (Let (NonRec x' rhs) $
+ wrap_fn fn_arg))
+ else return Nothing }
+
+splitThunkCpr :: WwOpts -> Var -> CoreExpr -> UniqSM (Maybe CoreExpr)
+-- See Note [Thunk splitting]
+-- Given x* = rhs, where x* is used outermost-strictly, and x* has a (nested) CPR
+-- property, say Just (Just _), return this new RHS:
+-- let x' = rhs in
+-- case x' of { Just p -> case p of { Just q -> -- Unpacking code
+-- Just (Just q) }} -- Repacking code
+-- Works for multi-constructor data types, where splitThunkStr will fail
+splitThunkCpr ww_opts x rhs
+ | wo_cpr_anal ww_opts -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
+ , isStrUsedDmd (idDemandInfo x) -- See (TS2)
+ = assertPpr (cprTypeArity cpr_type == 0) (ppr x) $ -- It's a thunk
+ do { (useful, _transit_vars, rebuild_result, unpacker) <- mkWWcpr_one ww_opts x cpr
+ -- Use mkWWcpr_one: see (TS2) in Note [Thunk splitting]
+ ; if useful
+ then return (Just (Let (NonRec x rhs) $
+ unpacker rebuild_result))
+ else return Nothing }
+
+ | otherwise
+ = return Nothing
+ where
+ cpr_type :: CprType
+ cpr_type = cprSigType (idCprSig x)
+ cpr :: Cpr
+ cpr = cprTypeCpr cpr_type
+
=====================================
compiler/GHC/Core/Opt/WorkWrap/Utils.hs
=====================================
@@ -8,7 +8,7 @@ A library for the ``worker\/wrapper'' back-end to the strictness analyser
{-# LANGUAGE ViewPatterns #-}
module GHC.Core.Opt.WorkWrap.Utils
- ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one
+ ( WwOpts(..), mkWwBodies, mkWWstr, mkWWstr_one, mkWWcpr_one
, needsVoidWorkerArg
, DataConPatContext(..)
, UnboxingDecision(..), canUnboxArg
@@ -139,13 +139,18 @@ data WwOpts
= MkWwOpts
{ -- | Environment of type/data family instances
wo_fam_envs :: !FamInstEnvs
+
, -- | Options for the "Simple optimiser"
wo_simple_opts :: !SimpleOpts
+
, -- | Whether to enable "Constructed Product Result" analysis.
-- (Originally from DOI: 10.1017/S0956796803004751)
+ -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
wo_cpr_anal :: !Bool
+
, -- | Used for absent argument error message
wo_module :: !Module
+
, -- | Generate workers even if the only effect is some args get passed
-- unlifted. See Note [WW for calling convention]
wo_unlift_strict :: !Bool }
@@ -230,8 +235,7 @@ mkWwBodies opts fun_id ww_arity arg_vars res_ty demands res_cpr
; let (work_args, work_marks) = unzip work_args_str
-- Do CPR w/w. See Note [Always do CPR w/w]
- ; (useful2, wrap_fn_cpr, work_fn_cpr)
- <- mkWWcpr_entry opts res_ty' res_cpr
+ ; (useful2, wrap_fn_cpr, work_fn_cpr) <- mkWWcpr_entry opts res_ty' res_cpr
; let (work_lam_args, work_call_args, work_call_str)
| needsVoidWorkerArg fun_id arg_vars work_args
@@ -662,8 +666,10 @@ canUnboxResult fam_envs ty cpr
= DontUnbox
where
- -- See Note [non-algebraic or open body type warning]
- open_body_ty_warning = warnPprTrace True "canUnboxResult: non-algebraic or open body type" (ppr ty) Nothing
+ -- See Note [Non-algebraic or open body type warning]
+ open_body_ty_warning
+ = warnPprTrace True "canUnboxResult: non-algebraic or open body type"
+ (ppr ty) Nothing
@@ -808,7 +814,7 @@ match the number of constructor arguments; this happened in #8037.
If so, the worker/wrapper split doesn't work right and we get a Core Lint
bug. The fix here is simply to decline to do w/w if that happens.
-Note [non-algebraic or open body type warning]
+Note [Non-algebraic or open body type warning]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are a few cases where the W/W transformation is told that something
returns a constructor, but the type at hand doesn't really match this. One
@@ -829,8 +835,60 @@ This warning also triggers for the stream fusion library within `text`.
We can't easily W/W constructed results like `Stream` because we have no simple
way to express existential types in the worker's type signature.
+Note [Worker/wrapper for strict arguments]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Consider
+ f x = case x of
+ [] -> blah
+ (y:ys) -> f ys
+
+Clearly `f` is strict, but its argument is not a product type, so by default
+we don't worker/wrapper it. But it is arguably valuable to do so. We could
+do this:
+
+ f x = case x of xx { DEFAULT -> $wf xx }
+ $wf xx = case xx of
+ [] -> blah
+ (y:ys) -> f ys
+
+Now the worker `$wf` knows that its argument `xx` will be evaluated
+and properly tagged, so the code for the `case xx` does not need to do
+an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will
+have the wrapper inlined, and will drop the `case x`, so no eval
+happens at all.
+
+The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
+in GHC.Types.Id.Info) and the code generator guarantees that every
+call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
+
+Is this a win? Not always:
+* It can cause slight code size increases. This is since we push evals to every
+ call sites which there might be many. And the evals will only disappear at
+ call sites where we already known that the argument is evaluated.
+
+* It will also cause many more functions to get a worker/wrapper split
+ which can play badly with rules (see Ticket #20364). In particular
+ if you depend on rules firing on functions marked as NOINLINE
+ without marking use sites of these functions as INLINE or INLINEABLE
+ then things will break.
+
+ But if you want a function to match in a RULE, it is /in any case/ good
+ practice to have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it
+ doesn't inline until the rule has had a chance to fire.
+
+So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
+w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The
+flag is off by default. The choice is made in
+GHC.Core.Opt.WorkWrap.Utils.wwUseForUnlifting
+
+See also `Note [WW for calling convention]`
+
Note [WW for calling convention]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ NB: This Note is more of a discussion.
+ Read Note [Worker/wrapper for strict arguments] first,
+ which covers the same ground with more precision
+
If we know a function f will always evaluate a particular argument
we might decide that it should rather get evaluated by the caller.
We call this "unlifting" the argument.
@@ -856,10 +914,9 @@ Hence we have the following strategies with different trade-offs:
A) Never do W/W *just* for unlifting of arguments.
+ Very conservative - doesn't break any rules
- - Lot's of performance left on the table
+ - Lots of performance left on the table
-B) Do W/W on just about anything where it might be
- beneficial.
+B) Do W/W on just about anything where it might be beneficial.
+ Exploits pretty much every opportunity for unlifting.
- A bit of compile time/code size cost for all the wrappers.
- Can break rules which would otherwise fire. See #20364.
@@ -883,10 +940,10 @@ C) Unlift *any* (non-boot exported) functions arguments if they are strict.
functionality. I haven't tried this approach because it's not trivial to
implement and doing W/W splits seems to work well enough.
-Currently we use the first approach A) by default, with a flag that allows users
-to fall back to the more aggressive approach B).
+Currently we use the first approach (A) by default, with a flag `-fworker-wrapper-cbv`
+that allows users to fall back to the more aggressive approach (B).
-I also tried the third approach C) using eta-expansion at call sites to avoid
+I also tried the third approach (C) using eta-expansion at call sites to avoid
modifying the PAP-handling code which wasn't fruitful. See
https://gitlab.haskell.org/ghc/ghc/-/merge_requests/5614#note_389903. We could
still try to do C) in the future by having PAP calls which will evaluate the
@@ -895,53 +952,6 @@ be neither a small nor simple change so we stick with A) and a flag for B) for
now.
See also Note [EPT enforcement] and Note [CBV Function Ids: overview]
-
-Note [Worker/wrapper for strict arguments]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Consider
- f x = case x of
- [] -> blah
- (y:ys) -> f ys
-
-Clearly `f` is strict, but its argument is not a product type, so by default
-we don't worker/wrapper it. But it is arguably valuable to do so. We could
-do this:
-
- f x = case x of xx { DEFAULT -> $wf xx }
- $wf xx = case xx of
- [] -> blah
- (y:ys) -> f ys
-
-Now the worker `$wf` knows that its argument `xx` will be evaluated
-and properly tagged, so the code for the `case xx` does not need to do
-an "eval" (see `GHC.StgToCmm.Expr.cgCase`). A call (f (a:as)) will
-have the wrapper inlined, and will drop the `case x`, so no eval
-happens at all.
-
-The worker `$wf` is a CBV function (see `Note [CBV Function Ids: overview]`
-in GHC.Types.Id.Info) and the code generator guarantees that every
-call to `$wf` has a properly tagged argument (see `GHC.Stg.EnforceEpt.Rewrite`).
-
-Is this a win? Not always:
-* It can cause slight codesize increases. This is since we push evals to every
- call sites which there might be many. And the evals will only disappear at
- call sites where we already known that the argument is evaluated.
-
-* It will also cause many more functions to get a worker/wrapper split
- which can play badly with rules (see Ticket #20364). In particular
- if you depend on rules firing on functions marked as NOINLINE
- without marking use sites of these functions as INLINE or INLINEABLE
- then things will break.
- But if you want a function to match in a RULE, it is /in any case/ good practice to
- have a `INLINE[1]` or `NOINLNE[1]` pragma, to ensure that it doesn't inline until
- the rule has had a chance to fire.
-
-So there is a flag, `-fworker-wrapper-cbv`, to control whether we do
-w/w on strict arguments (internally `Opt_WorkerWrapperUnlift`). The
-flag is off by default. The choice is made in
-GHC.Core.Opt.WorkWrape.Utils.wwUseForUnlifting
-
-See also `Note [WW for calling convention]` in GHC.Core.Opt.WorkWrap.Utils
-}
{-
@@ -985,6 +995,12 @@ mkWWstr opts args str_marks
-- * wrap_arg assumes work_args are in scope, and builds a ConApp that
-- reconstructs the RHS of wrap_var that we pass to the original RHS
-- See Note [Worker/wrapper for Strictness and Absence]
+--
+-- E.g. mkWWstr_one (x :: (Int,Int) with strictess saying to unbox the pair and second Int
+-- = ( True -- useful
+-- , [p,q#], -- work_args
+-- , \e -> case x of (p,q) -> case q of I# q# -> e -- wrap_fn
+-- , (p, I# q) ) -- wrap_arg
mkWWstr_one :: WwOpts
-> Var
-> StrictnessMark
@@ -1008,7 +1024,7 @@ mkWWstr_one opts arg str_mark =
DontUnbox
| isStrictDmd arg_dmd || isMarkedStrict str_mark
- , wwUseForUnlifting opts -- See Note [WW for calling convention]
+ , wwUseForUnlifting opts -- See Note [Worker/wrapper for strict arguments]
, not (isFunTy arg_ty)
, not (isUnliftedType arg_ty) -- Already unlifted!
-- NB: function arguments have a fixed RuntimeRep,
@@ -1163,7 +1179,7 @@ function is worthy for splitting:
2b But if e.g. a large tuple or product type is always demanded we might
decide to "unlift" it. That is tighten the calling convention for that
argument to require it to be passed as a pointer to the value itself.
- See Note [WW for calling convention].
+ See Note [Worker/wrapper for strict arguments]
3. In all other cases (e.g., lazy, used demand and not eval'd),
'finaliseArgBoxities' will have cleared the Boxity flag to 'Boxed'
@@ -1604,7 +1620,9 @@ mkWWcpr_entry
CoreExpr -> CoreExpr) -- New worker. 'nop_fn' if not useful
-- ^ Entrypoint to CPR W/W. See Note [Worker/wrapper for CPR] for an overview.
mkWWcpr_entry opts body_ty body_cpr
- | not (wo_cpr_anal opts) = return (boringSplit, nop_fn, nop_fn)
+ | not (wo_cpr_anal opts) -- See (CPR1) in Note [Phase ordering] on GHC.Opt.CprAnal
+ = return (boringSplit, nop_fn, nop_fn)
+
| otherwise = do
-- Part (1)
res_bndr <- mk_res_bndr body_ty
@@ -1637,7 +1655,9 @@ mk_res_bndr body_ty = do
-- 1. A 'WwUse' capturing whether the split does anything useful.
-- 2. The list of transit variables (see the Note).
-- 3. The result builder expression for the wrapper. The original case binder if not useful.
--- 4. The result unpacking expression for the worker. 'nop_fn' if not useful.
+-- Assumes that the transit vars are in scope
+-- 4. The result unpacking expression for the worker. 'nop_fn' if not useful
+-- Brings the transit vars into scope
type CprWwResultOne = (WwUse, OrdList Var, CoreExpr , CoreExpr -> CoreExpr)
type CprWwResultMany = (WwUse, OrdList Var, [CoreExpr], CoreExpr -> CoreExpr)
@@ -1768,7 +1788,7 @@ To achieve said transformation, 'mkWWcpr_entry'
what belongs in the case scrutinee of the unpacker through the communicated
Id `r`: The unpacking expression will be free in that variable.
(This is a similar contract as that of 'mkWWstr_one' for strict args.)
- 3. 'mkWWstr_one' produces a bunch of *transit vars*: Those result variables
+ 3. 'mkWWcpr_one' produces a bunch of *transit vars*: Those result variables
that have to be transferred from the worker to the wrapper, where the
constructed result can be rebuilt, `a` and `b` above. Part (3) is
responsible for tupling them up in the worker and taking the tuple apart
=====================================
compiler/GHC/HsToCore/Utils.hs
=====================================
@@ -147,8 +147,7 @@ selectMatchVar w pat = go pat
go_leaf var
| not (hasRulesOrInline (idInfo var))
- = assert (isManyTy w) $
- return (mkLamBndrFromLetBndr var)
+ = return (mkLamBndrFromLetBndr var)
| otherwise
= new_match_var (idType var)
=====================================
compiler/GHC/Types/Cpr.hs
=====================================
@@ -8,6 +8,7 @@
module GHC.Types.Cpr (
Cpr (ConCpr), topCpr, botCpr, flatConCpr, asConCpr,
CprType (..), topCprType, botCprType, flatConCprType,
+ cprTypeArity, cprTypeCpr,
lubCprType, applyCprTy, abstractCprTy, trimCprTy,
UnpackConFieldsResult (..), unpackConFieldsCpr,
CprSig (..), topCprSig, isTopCprSig, mkCprSigForArity, mkCprSig,
@@ -106,6 +107,12 @@ data CprType
-- 'ct_arty' arguments
}
+cprTypeArity :: CprType -> Arity
+cprTypeArity = ct_arty
+
+cprTypeCpr :: CprType -> Cpr
+cprTypeCpr = ct_cpr
+
instance Eq CprType where
a == b = ct_cpr a == ct_cpr b
&& (ct_arty a == ct_arty b || ct_cpr a == topCpr)
@@ -167,7 +174,7 @@ seqCprTy (CprType _ cpr) = seqCpr cpr
-- | The arity of the wrapped 'CprType' is the arity at which it is safe
-- to unleash. See Note [Understanding DmdType and DmdSig] in "GHC.Types.Demand"
-newtype CprSig = CprSig { getCprSig :: CprType }
+newtype CprSig = CprSig { cprSigType :: CprType }
deriving (Eq, Binary)
-- | Turns a 'CprType' computed for the particular 'Arity' into a 'CprSig'
=====================================
compiler/GHC/Types/Id/Info.hs
=====================================
@@ -32,7 +32,7 @@ module GHC.Types.Id.Info (
setOneShotInfo,
-- ** Zapping various forms of Info
- zapLamInfo, zapFragileInfo,
+ zapLamInfo, zapFragileInfo, hasRulesOrInline,
lazifyDemandInfo, floatifyDemandInfo,
zapUsageInfo, zapUsageEnvInfo, zapUsedOnceInfo,
zapTailCallInfo, zapCallArityInfo, trimUnfolding,
@@ -963,3 +963,10 @@ zapTailCallInfo info
zapCallArityInfo :: IdInfo -> IdInfo
zapCallArityInfo info = setCallArityInfo info 0
+
+hasRulesOrInline :: IdInfo -> Bool
+-- See (SB3) of Note [StrictBind]
+hasRulesOrInline info
+ = isStableUnfolding (unfoldingInfo info)
+ || not (isEmptyRuleInfo (ruleInfo info))
+ || not (isAlwaysActive (inlinePragmaActivation (inlinePragInfo info)))
=====================================
compiler/GHC/Utils/Monad.hs
=====================================
@@ -16,7 +16,7 @@ module GHC.Utils.Monad
, mapAccumLM
, mapSndM
, concatMapM
- , mapMaybeM
+ , mapMaybeM, orElseM
, anyM, allM, orM
, foldlM, foldlM_, foldrM, foldMapM
, whenM, unlessM
@@ -250,6 +250,14 @@ unlessM :: Monad m => m Bool -> m () -> m ()
unlessM condM acc = do { cond <- condM
; unless cond acc }
+-- | Monadic version of @orElse@
+infixr 4 `orElseM`
+orElseM :: Monad m => m (Maybe a) -> m a -> m a
+orElseM ma def = do { mb_r <- ma
+ ; case mb_r of
+ Just x -> return x
+ Nothing -> def }
+
-- | Like 'filterM', only it reverses the sense of the test.
filterOutM :: (Applicative m) => (a -> m Bool) -> [a] -> m [a]
filterOutM p =
=====================================
testsuite/tests/simplCore/should_compile/T28158.hs
=====================================
@@ -0,0 +1,22 @@
+{-# OPTIONS_GHC -fworker-wrapper-cbv #-}
+-- Adding this option makes things harder for splitThunkCpr, which
+-- this test is testing. See (TS8) in Note [Thunk splitting]
+
+module T28158 where
+
+-- Here we miss CPR on y
+-- It's a bit of an obscure example, but still; see #28158
+f :: a -> a -> a -> [Int] -> [Int]
+f a b c xs = let y = case xs of
+ [0] -> Just a
+ [1] -> Just b
+ _ -> Just c
+ in h y (case y of
+ Just z -> reverse (reverse (reverse (
+ reverse (reverse (reverse (
+ reverse (reverse xs)))))))
+ Nothing -> xs++xs)
+
+h :: Maybe a -> b -> b
+h (Just y) e = h Nothing e
+h Nothing e = e
=====================================
testsuite/tests/simplCore/should_compile/T28158.stderr
=====================================
@@ -0,0 +1,58 @@
+
+==================== Tidy Core ====================
+Result size of Tidy Core
+ = {terms: 98, types: 108, coercions: 0, joins: 1/1}
+
+Rec {
+$wh
+ = \ @a @b ds e ->
+ case ds of ds1 { __DEFAULT ->
+ case e of e1 { __DEFAULT ->
+ case ds1 of {
+ Nothing -> e1;
+ Just y -> $wh Nothing e1
+ }
+ }
+ }
+end Rec }
+
+h = \ @a @b ds e -> $wh ds e
+
+$wf
+ = \ @a a1 b c xs ->
+ join {
+ $j ww
+ = $wh
+ (Just ww)
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1
+ (reverse1 (reverse1 (reverse1 (reverse1 xs []) []) []) []) [])
+ [])
+ [])
+ []) } in
+ case xs of {
+ [] -> jump $j c;
+ : ds ds1 ->
+ case ds of { I# ds2 ->
+ case ds2 of {
+ __DEFAULT -> jump $j c;
+ 0# ->
+ case ds1 of {
+ [] -> jump $j a1;
+ : ipv ipv1 -> jump $j c
+ };
+ 1# ->
+ case ds1 of {
+ [] -> jump $j b;
+ : ipv ipv1 -> jump $j c
+ }
+ }
+ }
+ }
+
+f = \ @a a1 b c xs -> $wf a1 b c xs
+
+
+
=====================================
testsuite/tests/simplCore/should_compile/all.T
=====================================
@@ -637,5 +637,5 @@ test('T27963', [grep_errmsg(r'f/42')], compile, ['-O -ddump-rule-firings'])
test('T27965', normal, compile, ['-O'])
test('T27965a', normal, compile, ['-O'])
test('T27965b', normal, compile, ['-O'])
-
+test('T28158', normal, compile, ['-O -dno-typeable-binds -dsuppress-all -dsuppress-uniques -ddump-simpl'])
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/694da176149247fc98666f26a632293…
--
View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/694da176149247fc98666f26a632293…
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
1
0