-
5412ba62
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Fix stale and false comments in the NCG
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe."
Comments and documentation only: the generated code is the same. Each
item names a comment, says what it said, and says what holds instead.
- The comment above genMachCode in GHC.CmmToAsm named stix code
and the UniqSM monad. The code is Cmm, and genMachCode switches
from the UniqDSM monad to NatM.
- NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed
Note [Unwinding information in the NCG] in that module. The Note
is in GHC.CmmToAsm.
- The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm,
AsmCodeGen and MachCodeGen. It now names the modules and functions
that do what it lists. Two comments further down named MachCodeGen:
as calling cmmMakeDynamicReference for static data, which
the instruction selectors do, and as calling the initialization
of the PIC base register for every procedure that accessed it, which
cmmTopCodeGen in the x86 and PowerPC instruction selectors does,
but not on AIX. They now say so.
- The header of GHC.CmmToAsm.Reg.Target said that the module keeps
the NCG from emitting code for an architecture other than the host's.
Each of its functions dispatches on the target platform's
architecture, and the sentence is deleted.
- Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout ran
optimizeCFG right after instruction selection. cmmNativeGen runs
it after register allocation and shortcutting. The Note presented
the next two steps, loopInfo's loop analysis and mkGlobalWeights'
refinement of the edge weights, as unconditional; optimizeCFG takes
them only under -fcmm-static-pred, which -O implies, and the Note now
says so. It said that the refined weights are normalized relative
to the most often visited node; they are relative to the entry node,
to which calcFreqs gives frequency 1.
- Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight
as 20k; defaultWeights has 1000. It said that likely branches
are taken more than 80% of the time and unlikely ones less than 20%;
the default weights give 75% and 25%. It said that the false side
of a regular branch is preferred; getCfg gives both sides the same
weight, the x86-64 instruction selector adds 3 to the false side
of a floating-point comparison, and optHsPatterns' favourFewerPreds
may then prefer one side by its predecessors. It said that calls
are ignored completely; the layout leaves a call's edge out while
it builds chains and while it combines neighbouring chains,
and divides its weight by 64 when it merges the chains.
- Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also
said that edges constituted by a call are ignored. The layout ignores
them while it builds the chains and while it combines neighbouring
chains, and counts a 64th of their weight when it merges the chains.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two
heuristics where staticBranchPrediction applies three, ohPredicts
being the third.
- In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1
is the branch in the true case; s1 is the successor with the smaller
label. The guard commented "Only backedges" is also reached by a back
edge beside a heap or stack check's edge, and its comment now says so.
- The comment above findBackEdges, in GHC.CmmToAsm.CFG, said
that it finds back edges by BFS. It finds them by a depth-first search
(classifyEdges in GHC.Data.Graph.Directed).
- The Instruction class asked regUsageOfInstr to state precisely
the registers an instruction reads and writes. x86's states them
as the register allocators are to see them, and the comment now says
so, with examples of where that departs from what the hardware does.
- The comment at the last arm of regUsageOfInstr's MOV case,
in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching
it zero any remaining upper part of the destination. Some do, such
as a 32-bit MOV into a general register and a load at FF32 or FF64;
others keep it, such as a MOV between registers at FF32 or FF64,
printed movss or movsd, and an 8-bit or 16-bit MOV into a general
register. The comment now also says that the usage of the other MOV
instructions has a register destination written, not read.
- Comments in the liveness pass, in both register allocators and
at the Ord instances of CmmTickScope, LocalReg and VirtualReg said
that deterministic code generation is not supported, which
-fobject-determinism provides. In the liveness pass
and the allocators, each now says whether the order at hand matters
and, where it does, what it decides; at the Ord instances,
that the order compares uniques and so is deterministic only
if the uniques are.
- In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there
are no loops in the code, so that the block frequencies can be 1.
Given a CFG, slurpSpillCostInfo scales the uses and definitions
it counts by the CFG's block frequencies; the comment is deleted.
- linearRegAlloc's haddock and the comment over process said
that a block of an SCC is allocated before a jump into it only
if it is the procedure's first block; any of its entry blocks is.
The comment over process also said that process loops where a block's
assignment never gets set. It stops after a round that allocates
no block, and so drops such a block.
- findPrefRealReg's comment said that the preferred register
is the first one the variable was assigned to. It is the variable's
register in the first entry assignment, in allocation order, that maps
it to a register; a block's entry assignment is recorded at the first
jump into it.
- Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint,
which is -dasm-lint.
- Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag
-ddrop-asm-stats, which is -ddump-asm-stats.
- The executable specification of FreeRegs,
in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently
released registers first. It now gives noFreeRegs as [] and has
getFreeRegs hand out the registers in each instance's fixed order.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays
associated with its register to the end of the procedure. A register
that outgrows its slot moves to new ones; what holds is that no other
register gets the old slot.
- The comment at handleComponent's case for a cycle of moves,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that it spills all
the cycle's source registers. It spills one.
- makeRegMovementGraph's comment said that cyclic components seem
to occur only very rarely. They are frequent in some code:
in the benchmark of orthotope, a Haskell array library on Hackage,
compiled by a GHC build of 2026-10 whose linear allocator
was master's, the fixup code breaks 39 register cycles through a stack
slot in $w$s$wequalT1 and 59 in $w$s$w$ccompare1. The two counts
were not taken again on master. The sentence is deleted.
- A comment at expandNode's case for a move from InBoth to InMem,
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that the source's slot
is guaranteed to be the destination's. They can differ where
the virtual register has more than one slot, and the value
is then stored from its register; the comment now says that the guard
fails only there.
- GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels]
in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel,
and the citation is now on one line.
- A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs
scans the integer registers from 28 down. It starts from x18,
and the comment now also says that it starts from v31 among the v
registers.
- The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86"
of what holds on i386 alone, and numbered the registers with 8-bit
versions 1-4, and the allocatable ones among them 1, 3 and 4. It now
says "On i386", and they are 0-3, and 0, 2 and 3.
- The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave
RISC-V as an example. registerArch gives RISC-V NoVectors
and no architecture Separate.
- The stmtToInstrs of X86, AArch64, LA64 and RV64 took the condition
of a conditional branch to be likely false, GHC.Cmm.ContFlowOpt having
arranged for the likely side to fall through. ContFlowOpt also inverts
a condition whatever its likelihood where the condition can
be inverted, the true target has one predecessor and the false target
more than one, so the condition may be likely true; none of the four
genCondBranch functions reads the likelihood.
- mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does
not know about likely annotations. The PowerPC code generator has
printed them as branch hints since 2017, and since 2018 getCfg has
weighted the CFG's edges by them, which on x86-64 the block layout
and the order of some conditional branches' jumps (invertCondBranches)
follow. Its clause on a fallthrough is replaced by what the swap does:
where the test can be inverted it becomes a likely-true test
of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where
the true target, after shortcutting, has one predecessor.
- The users' guide said that -fcmm-static-pred's prediction is used
by the register allocation and code layout passes. The prediction
is made only in the x86-64 native code generator, and is used, after
register allocation and without -finfo-table-map, for the layout
and for the order of some conditional branches' jumps
(invertCondBranches). The entry now also says that on x86-64 the graph
colouring allocators (-fregs-graph, -fregs-iterative) weight the uses
and definitions they count by the same heuristics whatever the flag
says, without -finfo-table-map (slurpSpillCostInfo, mkGlobalWeights),
but choose what to spill by live range length alone (chooseSpill,
spillCost_length), so that the flag does not change their allocation.
- The users' guide's entry of -fcmm-sink said that the sinking pass
attempts to find identical Cmm blocks and eliminate the duplicates.
Those are words of the -fcmm-elim-common-blocks entry, run
into this entry's sentence since the two entries were written;
the sentence now says only that the pass attempts to move variable
bindings closer to their usage sites.
Assisted-by: Claude Opus 5.5
-
f17564ed
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Define the labels of the NCG's comments
Of what anyone working with the NCG needs, this commit serves "The kind
of each statement in the NCG's comments, shown at the statement: a bug,
half-done work, a likely change or code meant to stay.", "What a comment
that does not show the kind of its statements does and does not claim."
and "How the statements on bugs, half-done work and likely changes
are kept true as the code changes."
Comments only; the generated code is the same.
Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels
that the native code generator's comments put at the head
of a statement. The commits that follow label each statement they add,
and are read under this Note:
BUG wrong behaviour, a missing check or misleading code;
the statement says in short what it leads to and where
it is reached
WIP half-done work
TODO what is likely to change, correct or buggy; a bug marked
TODO alone is accepted for now and worked around
BUG TODO both, where both are to be stressed
no label what is meant to stay; a kept trade-off says why
A BUG statement names its consequence: wrong code, wrong debugging
information, a panic or another failed compilation, assembly
the assembler rejects, only slower or larger code, only a warning
from the assembler, only more C stack space, or only a misled reader.
The Note does not reach back to older comments: their TODO, ToDo, FIXME
and XXX predate its meanings, and an older comment that carries no label
makes no claim that the code is meant to stay.
The Note also says how the labels are kept true. A change to what
a labelled statement describes removes or rewrites the statement
in the same change; BUG and TODO gain the issue's number when the issue
is filed; and a git grep given in the Note lists the labelled lines.
Assisted-by: Claude Opus 5.5
-
ae1de387
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Document bugs and TODOs in the NCG's CFG and block layout
Of what anyone working with the NCG needs, this commit serves "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- postRegCFG in GHC.CmmToAsm (BUG: X86's allocMoreStack retargets every
jump into an entry block to the block it adds after it,
but addImmediateSuccessor moves only the entry block's own edges).
The CFG keeps an edge into the entry block from each block that jumps
there, though the code now jumps to the added block, and lacks
those blocks' edges to the added block. This costs only speed.
It is reached on x86-64, the only target with a CFG after register
allocation, where ncgAllocMoreStack adds blocks, that is, where
allocation needs more spill slots than maxSpillSlots. This rests
on master's code read. The linear allocator's fixup blocks were added
to the CFG before postRegCFG, and the added block is reachable,
through the entry block's edge to it. No reader of the CFG after
postRegCFG panics on these edges: shortcutWeightMap has no lookup
that panics; optimizeCFG's lookups take their blocks and edges
from the CFG itself; sanityCheckCfg compares blocks only; sequenceTop
looks up only the blocks the CFG's edges name, all of them blocks
of the code; and invertCondBranches takes an edge's information
as a Maybe and leaves a jump without it alone.
- build_mapping in shortcutBranches, GHC.CmmToAsm (BUG: under -g a block
that holds only its jump also holds the location and unwinding
information that -g adds, so it is kept where without -g
it is shorted). The code under -g jumps through the kept block,
and on x86-64 static prediction and block layout get another CFG
than without -g. This costs only speed and code size, under -g
and -fasm-shortcutting, on x86 and x86-64, not on Darwin. This rests
on master's code read: split matches a block of exactly one
instruction, and under -g on ELF targets other than AArch64
the instruction selectors put a LOCATION at the head of a block
with a source note, and under -g x86's gives a CmmUnwind an UNWIND,
neither of which emits code. On a development branch whose block
layout differed from master's, this changed the code of a probe
under -g.
- Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG (BUG:
with tables next to code too, a block that is only a tail call's jump
to a label is shortcut away, and with it the edge A -> B). A's branch
has one target fewer in the CFG than in the code, and a loop whose
only exit was the lost edge has no exit in the CFG, so calcFreqs caps
its cycle probability. This costs only speed. It is reached on x86-64,
the only target with a CFG after register allocation,
under -fasm-shortcutting, not on Darwin. This rests on master's code
read: the removed block ends in a tail call and has no edges out
in the CFG; it leaves the code and the CFG together, and no block
becomes unreachable; and the readers of the CFG after
shortcutWeightMap, listed above for postRegCFG, do not panic
on a missing edge.
- getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only
the blocks reachable from the entry, while instruction selection still
covers the blocks that cmmToCmm makes unreachable when, after the Cmm
pipeline has removed the unreachable blocks, it turns a branch
on a constant into a jump). Where such a block updates the CFG
at its current block, as X86's cmpxchg loop for an atomic and, or, xor
or nand does, the compiler panics with "getSuccessorEdges: Block does
not exist". This is reached on x86 and x86-64, at any optimisation
level: cmmToCmm turns a branch on a literal into a jump under every
flag, and the literal comes at -O0 from cmmToCmm's own constant
folding and at -O from sinking's. For x86-64 this rests on master's
code read and on runs of master's compiler under -dcmm-lint.
A procedure whose if (1 != 0) leaves a block with a fetch-and-and
unreachable panics with that message at -O0 and at -O, and also
at both with -finfo-table-map added, under which no CFG is kept after
instruction selection, as on i386. Where the branch tests a local set
to 1 instead, the procedure panics at -O and compiles at -O0. For i386
it rests on master's code read alone, no i386 compiler having
been run: getCfgProc builds the CFG for every target, i386 runs
the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each
update, so addImmediateSuccessor's call of getSuccessorEdges panics
during instruction selection whether or not a CFG is kept after it.
It rests also on ISSUE 28088's record.
A TODO citing ISSUE 20428, at livenessCfg
and at ncgEnableDeadCodeElimination, says that -finfo-table-map turns
dead code elimination off, and with it every use of the CFG
from the liveness pass on. No CFG is then kept after register
allocation, so the layout has neither static prediction nor the chains
of -fblock-layout-cfg, and lays the blocks out without weights.
Note [CFG Edge Weights] now says what -fcmm-static-pred changes:
that under it the weights become estimated frequencies before the layout
uses them.
A TODO in Note [Layout relevant edge weights],
in GHC.CmmToAsm.BlockLayout, citing ISSUE 27799, says that the modifier
on the edges of a conditional branch under-prices such an edge where
buildChains skips the branch's other edge because it would close
a cycle, as it can skip a loop latch's back edge.
At getCfg's case for a switch, master's comment says that the weight -1
given to every target of a switch with more than ten targets, a compiler
performance hack, keeps the layout from considering them. A TODO there
now says that the layout considers them nonetheless, and that what
the hack saves has not been measured.
Other TODOs say:
- at the Ord instance of CfgEdge, that edges of equal weight are ordered
by their labels, which carry no meaning for the layout;
- in Note [Updating the CFG during shortcutting], that where
shortcutting redirects an edge onto one already there, only one
EdgeInfo is kept and the weights are not summed;
- at allEdges' relevantWeight in sequenceChain, that it differs
from directEdges';
- at dropJumps, that a block that only jumps to the next one is left
as an empty label and a jump over it is kept.
In X86's genCondBranch', a comment says that the 3 added to the weight
of a floating-point comparison's false edge breaks layout ties toward
the side GHC.Cmm.ContFlowOpt arranges to fall through.
Assisted-by: Claude Opus 5.5
-
10b1d84c
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Document bugs and TODOs in static branch prediction and loop analysis
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments]: BUG
for wrong behaviour, BUG TODO for a bug that is also likely to change,
WIP for half-done work, TODO for what is likely to change, none for what
is meant to stay.
What each BUG leads to, where it is reached and what that rests on:
- getCfg in GHC.CmmToAsm.CFG (BUG: after fixStgRegisters, a test
of CurrentTSO or CurrentNursery reads BaseReg and is tagged
HeapStackCheck). The exemptions of Note [Static Branch Prediction]
for heap and stack checks then apply to such a test, so its weights
are left unpredicted. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read. The tag
decides the code only through isHeapOrStackCheck, all of whose callers
are in staticBranchPrediction, which runs inside mkGlobalWeights.
mkGlobalWeights reaches the code through staticPredCfg, only
under -fcmm-static-pred, and otherwise only through the graph
allocator's spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28083 (an edge into the entry block is never a back edge,
as mkDomMap leaves the root out of every dominator set). A loop whose
head is the entry block is not found. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read
and ISSUE 28083's record. loopInfo's result reaches the code only
through static prediction and block layout: of its two callers,
loopLevels is never called, and mkGlobalWeights serves staticPredCfg,
under -fcmm-static-pred, and otherwise only the graph allocator's
spill costs, whose frequencies no spill choice reads.
- Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing
ISSUE 28093 (a self loop is a back edge only where its block dominates
no other block). A block that jumps to itself and to an exit
it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen
does, is not a loop. calcFreqs then takes the block for irreducible
and gives frequency 0 to it and to every block it dominates.
This costs only speed, on x86-64 under -fcmm-static-pred, by the same
path as the BUG of ISSUE 28083. This rests on master's code read,
on the record of ISSUE 28093, and on -ddump-cfg-weights of a loop
calling fetchOrIntArray#, compiled by a GHC built from 3d326d7d28
with changes outside the native code generator: the retry block's
edges and the loop's back edge weigh 0. Between 3d326d7d28
and the master commit this branch starts from, GHC.CmmToAsm.CFG
and cmpxchg_code are unchanged, and the dominator code loses only
a `return = pure`.
- Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG: the back
edge rule supersedes a likely annotation in the Cmm as well). A branch
with both a back edge and another edge is predicted to take the back
edge, whatever its annotation says. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read:
staticBranchPrediction's case for a mix of back edges and other edges
reads no annotation.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO:
a constructor-tag test is predicted like any other comparison,
its equal side unlikely). The prediction is wrong for the trees
of Data.Map and Data.Set, which declare Bin first: in a lookup,
the side that stays in the loop is predicted unlikely. This costs only
speed, on x86-64 under -fcmm-static-pred. It is accepted until
the knowledge of the likely side reaches the CFG, hence TODO as well.
This rests on master's code read.
- ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG (s1
is taken for the true side only where it is ltrue, the label
the branch was made with, which an edge no longer ends at once
the linear allocator's fixup block, by addNodesBetween,
or shortcutting, by shortcutWeightMap, has redirected it). Where
the redirected true edge's new target has the smaller label
of the two, each side gets the other's prediction, and the layout's
estimate takes the likely side for the unlikely one. This costs only
speed, on x86-64 under -fcmm-static-pred. This rests on master's code
read, and on a count over nofib's modules on a development branch
whose static prediction also predicts an inequality with a literal,
which found such branches inverted at -O2 and none at -O1.
- calcFreqs in GHC.CmmToAsm.CFG (BUG: mkGlobalWeights passes the loops
in the order of loopInfo's back edges, by label, and not by nesting).
An enclosing loop's pass can come before an inner loop's and read
the branch probability of an inner back edge where its cycle
probability belongs, which gives nested loops wrong cycle
probabilities. This costs only speed, on x86-64
under -fcmm-static-pred. This rests on master's code read.
A WIP in Note [Static Branch Prediction] says that the paper's other
heuristics are stubs.
calcFreqs' comment on an irreducible block, "Rare we don't care", now
says what frequency such a block keeps and, as a TODO, that such blocks
are not rare, that the layout then ranks edges by frequencies that do
not add up, with a loop calling fetchOrIntArray#, compiled by the GHC
named under ISSUE 28093 above, for a case, and what summing their inflow
measured on a development branch.
Other TODOs say:
- in Note [Back edges in loopInfo], that findBackEdges, which
optHsPatterns uses for the back edge bonus, disagrees with loopInfo
on edges into the entry block, on back edges of irreducible cycles
and on self loops;
- at ohPredicts, that only MO_Eq is read, so the spelling
GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted,
and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq
spelling is predicted was tried on a development branch and gained
nothing;
- at lehPredicts, that where a heap or stack check's call to the garbage
collector returns into the procedure, loopInfo takes the cycle through
that call for a loop: the heuristic then says nothing about a branch
into the checking block where that block is the loop's head, and takes
a branch towards a case alternative without such a check for a loop
exit where the head is the block choosing the alternative;
- at calcFreqs, that nothing checks its result, and that a check could
compare each block's frequency with the sum of the frequencies
on its in-edges, which the propagation departs from at some blocks,
among them an irreducible block, a loop head whose cycle probability
is capped, and the entry block;
- at loopMembers, that neither it nor loopLevels has a caller in GHC:
loopMembers since the graph allocator's spill costs, for which
it was added early in 2019, began that year to weight by block
frequencies instead, and loopLevels since it came with the loop
analysis that year.
A comment at optimizeCFG says that static prediction starts
from the weights optHsPatterns leaves, so that their adjustments carry
into the predicted probabilities, except where the back edge rule
replaces them.
Assisted-by: Claude Opus 5.5
-
5a5fe67b
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Document bugs and TODOs in liveness and the register allocators
Of what anyone working with the NCG needs, this commit serves
"The invariants the code depends on.", "Where the code does something
other than what reading it suggests.", "Where the code is known
to behave wrongly or is half done.", "What each known bug leads to, such
as wrong code, a compiler panic or only slower code, and under which
flags and on which targets it is reached." and "Where the code is likely
to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- regAlloc in GHC.CmmToAsm.Reg.Graph (BUG: it hands ncgAllocMoreStack
slotsCount', the highest slot number, which counts the preallocated
slots, where the linear allocator gives only the slots beyond
maxSpillSlots): the preallocated slots are reserved a second time.
This costs C stack space, under -fregs-graph or -fregs-iterative,
on every target, and where a target's mkStackAllocInstr needs more
instructions for a larger amount, code at entry and exit: on AArch64
one instruction more for each 4095 bytes, on RISC-V, LoongArch
and PowerPC more past the range of an immediate, and on Windows x86-64
a call of ___chkstk_ms past 4 KB. This rests on master's code read.
Every target's allocMoreStack moves the stack pointer by the slots
it is given times spillSlotSize. The graph allocator can be chosen
for any target, and trivColorable covers x86, x86-64, PowerPC,
AArch64, RISC-V and LoongArch.
- pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG: it binds
a SpillCostRecord as (reg, uses, defs, life), where the type's
comments give its fields as the writes, the reads and the lifetime).
Only the names are wrong: it prints the two counts in the record's
order, under no names, and their sum divided by the register's node
degree, and nothing in GHC calls it. This rests on master's code read:
slurpSpillCostInfo's incDefs fills the second field and incUses
the third.
- joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG: on x86
a floating-point == or /= test's block ends in two jumps that name one
target, genCondBranch's parity jump and a conditional or unconditional
one, and each is joined on its own). Where that target needs a fixup
block, each of the two jumps gets one, with the same moves, and both
are reachable. This costs only code size, on x86 and x86-64
under the linear allocator. This rests on master's code read
and on constructed Cmm compiled by master's compiler; no module
of nofib or of the compile benchmarks was found to show it. A fix
that shares the block where the two jumps' stack deltas agree,
the target's vregs have the same locations at both and no value moves
between two slots was written on a development branch and is left out.
- joinToTargets_again in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG:
once it has made a fixup block for a target and patched the jump to go
there, the destinations still to consider keep the target's later
occurrences, as a jump table lists a target once for each entry naming
it). Each later occurrence makes the same moves again, into a block
nothing jumps to, which is given an edge in the CFG, laid out
and emitted: dead code. This costs only code size, under the linear
allocator. This rests on master's code read: x86's jumpDestsOfInstr
lists a jump table's targets with their repetitions, and the other
targets with jump tables do likewise. Such a block was found in GHC's
own GHC.CmmToAsm.Dwarf.Constants and in none of nofib's
or the testsuite's modules.
- makeRegMovementGraph, handleComponent and makeMove
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, and the header
of GHC.CmmToAsm.Reg.Linear.StackMap (BUG, ISSUE 27638: since
ISSUE 26668 a virtual register whose format has outgrown its slot gets
new slots, so a jump can need a move between two slots of one
register): such a move ends in makeMove's panic, "makeMove: we don't
handle mem->mem moves". And where handleComponent's cyclic case moves
to an InBoth destination (BUG, a statement of its own, ISSUE 27638
reporting only the panic), the destination's slot is written only
if it is the slot spillR picks; otherwise it keeps a stale value,
which is wrong code where the slot is reloaded. Both are reached
under the linear allocator, where a virtual register's format grows
past 8 bytes, which only a vector format does, and so only on i386,
x86-64 and AArch64, the targets whose code generators take vectors
(checkVecCompatibility in GHC.StgToCmm.Prim; PowerPC's, RV64's
and LA64's stop with sorry on vectors). The first is reached on x86-64
at -O1 and -O2: master's compiler panics so on a function in which
a Double, also broadcast to a DoubleX2#, is live at a join of two arms
of a case that both load eleven Int#s and seventeen Doubles.
No program reaching the second is known. The first can be reached two
ways, by expandNode, both from a jump at which the virtual register
is in one of its slots only: into a block that holds it in another
of its slots only, and into a block that holds it in a register
and another slot, where makeMove loads the register first. A fix
cannot count on a spare register: nothing keeps one free at a jump,
and the block's entry assignment can hold every allocatable register,
on x86-64 the eleven integer registers (rax, rbx, rcx, rdx, rsi, rdi,
r8 to r11 and r14) and the sixteen vector registers, the others being
the stack pointer and those of STG's Base, Sp, Hp and SpLim (freeReg
in compiler/CodeGen.Platform.h). This rests on master's code read,
ISSUE 27638's record and a run of master's compiler. The cyclic case
drops the InMem half of an InBoth destination (expandNode lists InReg
first) and writes only spillR's slot, which is getStackSlotFor's
newest slot of the virtual register and differs from the destination's
only after the register grew. And allocateRegsAndSpill frees
the register of an InBoth virtual register without a store,
so that its next use reloads the slot.
- livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq
compares the registers and not their formats, so the fixpoint can stop
before the formats recorded for a cycle's blocks converge): a vector
register can be recorded live at a format narrower than the value
it holds, and a write at that format then kills
it in minusCoveredRegs, which is wrong code. No program giving a wrong
result is known. This rests on master's code read and ISSUE 27619's
record, whose program shows a register recorded so.
- getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG:
it folds the slot maps of a block's predecessors from the empty map
with mergeSlotMaps, which keeps only the slots both maps hold).
The slot map on entry to a block is always empty, so a reload
is coalesced with a spill only inside one block. This costs only speed
and code size, under -fregs-graph or -fregs-iterative, on every
target. This rests on master's code read; buildGraph
in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce.
- maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's
derived Ord compares a VecFormat's number of elements before their
format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4
FmtDouble, 256 bits): it can keep the narrower of two formats.
Were one register read at both, a write at the narrower would kill
it in minusCoveredRegs, which is wrong code; whether any register
is read so is not known. This rests on master's code read
and ISSUE 27619's record.
The other statements, by part.
The linear allocator:
- Note [The first jump into a block fixes its entry assignment],
in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump
into a block that the allocator processes records the block's entry
assignment, spilled values included, and that every later jump
conforms to it by fixup code. Its three TODOs are what follows
from that: a loop head recorded from a preheader that spilled
a loop-carried value has the value reloaded on every iteration,
and stored again by every back edge once the body has written it;
a return continuation and the procedure's entry that enter one loop
at two blocks record incompatible assignments (ISSUE 27800);
and the block that a failed heap or stack check returns to
from the garbage collector can be allocated before the hot path's jump
into the checking block and record that block's entry assignment,
as the order of allocation depends on no frequency. process' comment
cites the Note.
- Note [Unique order in the linear allocator],
in GHC.CmmToAsm.Reg.Linear, says, as a TODO, which decisions take
the order of the vregs' uniques as a ranking: the spill victim,
and the order in which saveClobberedTemps moves values out
of clobbered registers. It also says that the order decides
joinToTargets' fixup moves. The comments at those three folds cite it.
- Issues get labels where the code behaves as they report: TODO
for ISSUE 27980, closed as a duplicate of ISSUE 27800,
at findPrefRealReg, for ISSUE 27981 at joinToTargets_first's release
of registers, and for ISSUE 26631 at saveClobberedTemps' choice
of a register; BUG for ISSUE 27638 at handleComponent, makeMove,
makeRegMovementGraph and StackMap's header, whose comments ruled out
a move between two stack slots, which ISSUE 26668 made possible.
- TODOs without an issue: raInsn's elimination of a move gives
the destination the source's register, whatever register an entry
assignment recorded for a block it is live into expects;
findPrefRealReg's preference is keyed by virtual register, while a Cmm
local is one virtual register over all its live ranges; and expandNode
stores a value InBoth at both ends of a jump into the slot
that already holds it.
- The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot
belongs to one virtual register for the whole procedure,
as getStackSlotFor takes new slots only at the next free one, which
only grows, and a register that outgrows its slot gets another,
keeping the first; that the fixups at a jump rely on this; and
that it costs stack, the slots of a procedure adding up over every
register spilled in it.
- Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear,
re-adding a dead spilled register's stack slot to the free list,
is marked WIP: it is not done, as a StackMap never frees a slot.
- A comment at clobberRegs' filter says that frAllocateReg panics
on a register already allocated on AArch64, RISC-V and LoongArch.
- Three designs that a trial on a development branch found no gain
in are recorded beside the code they would change: handing out
the floating-point registers in descending order (at the TODO
for ISSUE 26631 in saveClobberedTemps), taking the entry block first
and then, after each SCC, an SCC holding a block whose entry
assignment is recorded (at the TODO for ISSUE 27800), and putting
fixup moves before an unconditional jump rather than in a block
of their own (in joinToTargets_again).
Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs:
- The fixpoint of livenessSCCs says that it compares the whole map
at every round (TODO, ISSUE 27437), and that its steps are monotone,
so that a test comparing the formats too would reach a result
independent of the order in which the blocks are walked. Regs' Eq says
that it ignores formats (TODO, ISSUE 27619).
- The comment on the SCCs' order says that no block may fall through
before allocation, and liveDieRead's haddock that at a branch it also
holds the registers live into its targets only.
- A comment at computeLiveness' panic on SCCs out of reverse dependent
order says that, where sccBlocks has a CFG, a jump to a block missing
from the CFG reaches it too.
The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment
says that the block frequencies scale only the counts of uses
and definitions, on which no spill choice depends, as spillCost_chaitin,
which would read them, is commented out.
Both allocators: a TODO at patchRegsOfInstr says that, as it maps
a register to a register, both allocators reload a spilled value
into a register for an instruction that reads it, even at its last read,
where an x86 instruction could read the stack slot.
Assisted-by: Claude Opus 5.5
-
b9c33777
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Document bugs and TODOs in code generators, DWARF and an unused module
Of what anyone working with the NCG needs, this commit serves "The paper
or earlier design each part of the NCG is based on, where there is one,
and which code is no longer used and since which change.", "Where
the code does something other than what reading it suggests.", "Where
the code is known to behave wrongly or is half done.", "What each known
bug leads to, such as wrong code, a compiler panic or only slower code,
and under which flags and on which targets it is reached." and "Where
the code is likely to change, and how."
Comments only; the generated code is the same.
The statements carry the labels of Note [Labels in NCG comments].
What each BUG leads to, where it is reached and what that rests on:
- getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126:
isNbitEncodeable 12 admits label offsets from -2048 to 2047, while
check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095):
on AArch64, compiling a label at an offset from -2048 to -1 stops
with check_off's error, a pgmError,
"GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit"
for an offset of -8. Below -2048 the guard fails, and the next clause
adds the offset through a register. This rests on master's code read
(litToImm', ImmIndex, check_off), ISSUE 28126's record and a run
of master's x86-64 compiler given an AArch64 target description,
in which a Cmm load from a label less 8, at -O0 and at -O,
and plusAddr# of a string literal and -1#, at -O, stop
with check_off's error; nothing was run on AArch64.
- lower_CmmRegOff in GHC.CmmToAsm.Wasm.FromCmm and the cases
for CmmRegOff of getRegister' in GHC.CmmToAsm.RV64.CodeGen
and GHC.CmmToAsm.LA64.CodeGen, one BUG at each (the sum
is not truncated to a sub-word register's width, as each target's
general lowering of a sub-word MO_Add truncates its result,
and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus
a literal into a CmmRegOff at any width validOffsetRep allows). Where
an operation reads the bits above the width, this is wrong code:
on wasm32 a widening MO_UU_Conv of a sub-word value masks nothing,
and on RV64 and LA64 Note [Signed arithmetic on RISCV64] and LA64's
comment "Signed arithmetic on LoongArch64" keep a sub-word value
zero-extended between operations. This rests on master's code read
alone; nothing was run on these targets. On RV64 and LA64 an offset
that fits in 12 bits goes to the case of MO_Add for such a literal,
or on RV64 for an offset from -2047 to -1 to that of MO_Sub, which
does not truncate either (on RV64 ISSUE 28133); on RV64 an offset
of -2048 goes to MO_Sub's general case, which truncates.
- getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG:
neither mangleIndexTree nor add_int narrows the offset
to the register's width, and cmmMachOpFoldM's folds of literals
into a CmmRegOff sum them unnarrowed). For a 16-bit register whose
offset lies outside 16 bits, add_int's LEA, printed as an ADD
of an immediate where the result takes the operand's register, makes
the assembler warn that it shortened the immediate (addw $90000,%ax
for a 16-bit register plus three times 30000); the shortened immediate
gives the value meant, so this costs only the warning, on x86
and x86-64. An 8-bit register's sum takes an ADD whose immediate
litToImm narrows, an LEA printed as an LEA takes the offset
as a 32-bit displacement without a warning, and a wider register holds
any offset add_int is given. This rests on master's code read
(mangleIndexTree, add_code, add_int and the printing of an LEA
as an ADD in GHC.CmmToAsm.X86.Ppr), on master's compiler, whose
assembly for such a sum in Cmm made the assembler warn so, and on GNU
as given addw and leaw with such an immediate and displacement,
with and without --32: it warned of the addw alone and assembled both.
- getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64
and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap
in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps
the number of the low half's unique): a 64-bit Cmm local and a 64-bit
NCG temporary with the same number share their high half, and where
both are live, writing one overwrites the other's high 32 bits.
This is wrong code on i386; 32-bit PowerPC, which uses the same
functions, was not tried. Equal numbers occur, as the NCG's uniques
count from 0 in each Haskell module (initDUniqSupply 'n' 0
in GHC.Driver.Main.Compile). In genByteSwap, equal high halves
with different low halves can arise so, and the branch for that case
swaps correctly. This rests on master's code read and ISSUE 28125's
record.
- verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG: nothing checks
that a block of native code ends in a transfer of control;
this checks, in a DEBUG compiler, only that nothing but jumps follows
a jump). A block that did not end in one would run on into whichever
block the layout puts after it, which is wrong code; no instruction
selector is known to make such a block. This rests on master's code
read.
- getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105:
each can emit a displacement outside the signed 32-bit range: -i where
i = -2^31; an offset left unchecked; and an offset checked only
at shift 3, as && binds tighter than ||): where the displacement does
not fit, the x86-64 assembler rejects the module. This rests
on master's code read and ISSUE 28105's record.
- getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset
plus a shift (BUG: nor is the offset narrowed to the register's
width). On i386 an offset outside 32 bits reaches the assembler, which
warns and shortens it modulo 2^32, to the address meant, so this costs
only the warning; on x86-64 such an offset is the BUG of ISSUE 28105
at the same clause. This rests on master's code read, nothing having
been compiled for i386, and on GNU as given such displacements
with --32, which it shortened with a warning and assembled.
- genPrim in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 27694: MO_UF_Conv's
genWordToFloat does not return the last block it adds, so a later
statement of the same Cmm block that splits its current block in turn,
as a second conversion does, moves the wrong block's edges): the CFG
lacks the edges of the jumps ending the Cmm block, and where
the linear allocator puts a fixup block on one of them,
addNodesBetween panics with "Can't find weight for edge that should
have one", the panic of ISSUE 27915. Where the second conversion's
last block is a lone jump, shortcutting (-fasm-shortcutting,
on at -O2, never on Darwin) cuts it, and shortcutWeightMap drops
its out-edges, which in the CFG are the only edges into the first
conversion's blocks; the blocks stay in the CFG, unreachable
from the entry and with edges, and classifyEdges
in GHC.Data.Graph.Directed, which findBackEdges calls
for optHsPatterns, panics with "Failed to classify edge of CFG -
not not timed" on an edge out of them. Both are reached on x86-64,
the only target for which backendMaintainsCfg holds, and
not under -finfo-table-map, under which no pass after instruction
selection gets a CFG. -dasm-lint does not catch the missing edges
first, as sanityCheckCfg compares the CFG's blocks with the code's
and not its edges. This rests on master's code read, the records
of ISSUE 27694 and ISSUE 27915, a run of master's compiler on a loop
with two word2Double# in one Cmm block: it panics in addNodesBetween
at -O, at -O2 and at -O -dasm-lint, and compiles at -O0
and at -O -fregs-graph, as the graph allocator makes no fixup blocks;
and a run of master's compiler on two word2Double# in one Cmm block
ahead of a loop: it panics in classifyEdges at -O2, at -O2 -dasm-lint,
at -O2 -fregs-graph, at -O1 -fasm-shortcutting
and at -O0 -fasm-shortcutting, and compiles at -O0, at -O1
and at -O2 -fno-asm-shortcutting.
- addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG: it gives every
unwinding table that does not name Sp the rule Sp has
at the procedure's entry, and the table that X86's addSpUnwindings
adds where the C stack pointer moves, as around a C call, names MachSp
alone). Up to the next table that names Sp, DWARF gives the canonical
frame address by Sp's rule at entry: after a C call, rbp+0 on x86-64,
where before the call it can be another offset, such as rbp+16.
A debugger unwinding from there finds the wrong frame. This is reached
under -g on ELF targets, on x86 and x86-64, as ncgDwarfUnwindings
holds on ELF targets under -g and addSpUnwindings is X86's. This rests
on master's code read and on readelf's reading of the frame table
of an object that master's compiler made under -g.
The other statements:
- backendMaintainsCfg in GHC.CmmToAsm.BlockLayout said that i386 should
work but is untested. It now says, as WIP, that i386 is left out
because it is untested and its iselExpr64 splits blocks for 64-bit
shifts without adding them to the CFG.
- genPrim's comment says that its remaining cases add no blocks, while
MO_UF_Conv's genWordToFloat adds blocks: the BUG above stands there.
- mkRegRegMoveInstr in GHC.CmmToAsm.X86.Instr says that its move clears
the upper part of the register. A TODO says that for a float
or a double it is MOV FF64, printed movsd, which keeps
the destination's upper half.
- invertCondBranches inverts a jump only after an integer comparison.
A TODO says that maybeInvertCond's complement on the flags is as sound
after a floating-point one.
- pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's
start, only a block with an info table (TODO, ISSUE 27668).
- condIntCode' tests a value against zero even on a path where
the instruction computing it has set ZF and SF from it, as on the back
edge of a loop that counts down: it sees only the comparison,
and another path into the test, such as the loop's entry, may set
no flags. Only a condition that reads ZF and SF alone could use
the flags of a dec, which writes OF and leaves CF where TEST clears
both (TODO, ISSUE 27738).
- GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO, that no module
imports it, and that its pass, which ran before allocation, has had
no caller since 2007, when it was taken out of the pipeline in favour
of the coalescing that GHC.Data.Graph.Color.colorGraph does.
Assisted-by: Claude Opus 5.5
-
a369ecae
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
State the NCG's norms and where a branch's likely side is known
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's
own documents and testsuite hold the native code generator to, and what
each means for a change. Under -fobject-determinism the output
is bit-for-bit the same for the same inputs, so an order taken
from uniques is a question for review. The testsuite passes -dcmm-lint
by default, so a test written in Cmm must be one that Cmm lint accepts.
Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says
where the code generator learns which side of a conditional branch
is likely: where the branch is made, as for heap and stack checks;
upstream, and not carried down, for constructor-tag tests; and nowhere,
for the rest, to which static prediction applies its heuristics. It also
states the trade-offs kept with that knowledge, each with its reason:
conditions inverted so that the true side falls through even where
the false side is likely, and edges across calls left out when chains
are built and when neighbouring chains are combined.
Note [Norms of the NCG] points to it.
Assisted-by: Claude Opus 5.5
-
d4eb261a
by Mikolaj Konarski at 2026-11-20T00:02:39+01:00
Rewrite the NCG's overview Note
Of what anyone working with the NCG needs, this commit serves "Comments
and Notes that are true of the code they describe.", "Which targets go
through the NCG, which of its parts each target uses, and what the NCG
takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes
in the order they run, and what each requires of the one before.",
"The invariants the code depends on." and "What the tests cover and what
they do not: which targets CI runs natively, which paths have few
or no tests, and which performance test exercises which pass."
Comments only; the generated code is the same.
Note [Native code generator], the module header of GHC.CmmToAsm, named
CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which
no longer exist, and machine-independent optimisations "defined below",
which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now
says:
- which targets go through cmmNativeGen, that wasm32 has a generator
of its own, and which back end the other targets get by default;
- what the Cmm pipeline hands over, and what the NCG takes from StgToCmm
and the RTS;
- the interfaces through which the machine-independent parts access
a target, and what only some targets have;
- the passes, in the order cmmNativeGen runs them, with the flags
that turn them on and the dump flags that show their output, and,
at step 4, what instruction selection must ensure;
- where the NCG's uniques come from;
- what the assembler and the linker do after it;
- the flags, testsuite directories and benchmarks for working
on the NCG.
For detail it cites the Notes and labelled statements of the preceding
commits.
Assisted-by: Claude Opus 5.5
-
8b600b3e
by Mikolaj Konarski at 2026-11-20T00:02:40+01:00
Propose two principles for the NCG
Of what anyone working with the NCG needs, this commit serves "The norms
and principles that apply to the NCG, whether each is agreed or only
proposed, and which trade-offs are acceptable."
Comments only; the generated code is the same.
Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two
principles to GHC's developers and says that the native code generator
does not keep them yet:
- correctness first: semantic correctness is not traded for a measured
gain that an incorrect form gives by accident, until a form with both
has been looked for and the trade agreed in review;
- one TODO set: a departure from correctness that is left in place
is marked TODO, as a member of one set that is accepted for now
and re-investigated together.
No other commit cites the Note, so this commit can be dropped
on its own.
Assisted-by: Claude Opus 5.5
-
273bc4b2
by Mikolaj Konarski at 2026-11-20T00:02:40+01:00
Add a README to the NCG's directory
Of what anyone working with the NCG needs, this commit serves "An order
in which to read the NCG's Notes.", "One place where the terms the NCG's
comments use are defined.", "One small function followed through
the NCG's dumps, in the order of its passes.", "Which parts of the NCG
were examined for bugs, half-done work and likely changes, and which
were not.", "The invariants the code depends on." and "How to find
the pass at fault for a miscompilation or a compiler panic, and how
to reduce the case to a Cmm test."
Documentation only; the generated code is the same.
compiler/GHC/CmmToAsm/README.md is a way in for anyone working
with the native code generator, whether reading its output and dumps,
tracking a fault to its pass, reviewing or making a change,
or maintaining it. It says what to read and what to do, and for each
fact about the code it cites a Note or a comment by name. Its sections:
- Where to start reading: three Notes of GHC.CmmToAsm, then Notes
on the passes, each with its module, in the overview's order.
- Vocabulary: the terms the NCG's comments use without defining them,
each with where it is defined or used.
- Finding the pass at fault for a wrong result or a panic: the oracles
to compare with, the flags that switch a pass off or swap it,
the lints, and how to cut a case down to a Cmm test.
- One function through the dumps: a small loop compiled at -O on x86-64,
with an excerpt for each dump flag in the overview's list of passes
but -ddump-asm-regalloc-stages, which prints nothing under the linear
allocator.
- Reviewing a change: the invariants the code depends on, as questions
by kind of change, each citing the Note or comment that states it.
- What the labelled statements cover: which parts of the NCG they
were first written from, and which were left out.
The excerpts are cut from the dumps of one compilation by a compiler
built from master: each of their lines but "..." is a line of a dump,
in the dump's order, with tabs replaced by spaces. Every Note, function,
module, flag and path the README names exists at this commit.
The overview, Note [Native code generator], now ends by pointing
to the README.
Assisted-by: Claude Opus 5.5