[Git][ghc/ghc][wip/ncg-comment-fixes] Fix stale and false comments in the NCG
Mikolaj Konarski pushed to branch wip/ncg-comment-fixes at Glasgow Haskell Compiler / GHC Commits: 5b2bbcc8 by Mikolaj Konarski at 2026-11-18T20:57:28+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. - 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. - 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 only while it builds chains, and divides its weight by 64 when it merges them. - Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout also said that edges constituted by a call are ignored. The layout ignores them only while it builds the 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. - 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. - X86's stmtToInstrs 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; genCondBranch does not read 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 - - - - - 28 changed files: - compiler/GHC/Cmm/Node.hs - compiler/GHC/Cmm/Reg.hs - compiler/GHC/CmmToAsm.hs - compiler/GHC/CmmToAsm/BlockLayout.hs - compiler/GHC/CmmToAsm/CFG.hs - compiler/GHC/CmmToAsm/Instr.hs - compiler/GHC/CmmToAsm/Monad.hs - compiler/GHC/CmmToAsm/PIC.hs - compiler/GHC/CmmToAsm/Reg/Graph.hs - compiler/GHC/CmmToAsm/Reg/Graph/Base.hs - compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.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/Liveness.hs - compiler/GHC/CmmToAsm/Reg/Target.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/Platform/Reg.hs - compiler/GHC/Platform/Reg/Class.hs - compiler/GHC/StgToCmm/Monad.hs - docs/users_guide/using-optimisation.rst Changes: ===================================== compiler/GHC/Cmm/Node.hs ===================================== @@ -894,8 +894,8 @@ instance Eq CmmTickScope where -- This is still deterministic because -- the order is the same for equal lists --- This is non-deterministic but we do not currently support deterministic --- code-generation. See Note [Unique Determinism and code generation] +-- This compares uniques, so the order is deterministic only if the uniques are: +-- see Note [Unique Determinism and code generation]. -- See Note [No Ord for Unique] instance Ord CmmTickScope where compare GlobalScope GlobalScope = EQ ===================================== compiler/GHC/Cmm/Reg.hs ===================================== @@ -121,8 +121,8 @@ instance Eq LocalReg where instance Outputable LocalReg where ppr e = pprLocalReg e --- This is non-deterministic but we do not currently support deterministic --- code-generation. See Note [Unique Determinism and code generation] +-- This compares uniques, so the order is deterministic only if the uniques are: +-- see Note [Unique Determinism and code generation]. -- See Note [No Ord for Unique] instance Ord LocalReg where compare (LocalReg u1 _) (LocalReg u2 _) = nonDetCmpUnique u1 u2 ===================================== compiler/GHC/CmmToAsm.hs ===================================== @@ -890,8 +890,8 @@ apply_mapping ncgImpl ufm (CmmProc info lbl live (ListGraph blocks)) -- ----------------------------------------------------------------------------- -- Instruction selection --- Native code instruction selection for a chunk of stix code. For --- this part of the computation, we switch from the UniqSM monad to +-- Native code instruction selection for a chunk of Cmm. For +-- this part of the computation, we switch from the UniqDSM monad to -- the NatM monad. The latter carries not only a Unique, but also an -- Int denoting the current C stack pointer offset in the generated -- code; this is needed for creating correct spill offsets on ===================================== compiler/GHC/CmmToAsm/BlockLayout.hs ===================================== @@ -56,7 +56,7 @@ import GHC.Types.Unique.DSM (UniqDSM) * Compute a CFG based on the Cmm AST, see getCfgProc. This CFG will have edge weights representing a guess on how important they are. - * After we convert Cmm to Asm we run `optimizeCFG` which + * After register allocation and shortcutting we run `optimizeCFG` which adds a few more "educated guesses" to the equation. * Then we run loop analysis on the CFG (`loopInfo`) which tells us about loop headers, loop nesting levels and the sort. @@ -265,7 +265,8 @@ import GHC.Types.Unique.DSM (UniqDSM) We apply a small modifier to them to ensure edges for which we can eliminate the overhead completely are considered first. See also #18053. - * Edges constituted by a call are ignored. + * Edges constituted by a call are ignored while the chains are built, and + count a 64th of their weight when the chains are merged at the end. Considering these hardly helped with performance and ignoring them helps quite a bit to improve compiler performance. ===================================== compiler/GHC/CmmToAsm/CFG.hs ===================================== @@ -560,22 +560,29 @@ addNodesBetween weights m updates = * Unconditional Control Transfer - They will always transfer control to their target. Unless there is a info table we can turn the jump into a fallthrough as well. - We use 20k as default, so it's easy to spot if values have been - modified but unlikely that we run into issues with overflow. + We use 1000 as default ('defaultWeights' in GHC.CmmToAsm.CFG.Weight). * If branches (likely) - We assume branches marked as likely - are taken more than 80% of the time. + are taken 75% of the time: the default weights give the likely side 900 and + the other side 300. By ranking them below unconditional jumps we make sure we prefer the unconditional if there is a conditional and unconditional edge towards a block. - * If branches (regular) - The false branch can potentially be turned - into a fallthrough so we prefer it slightly over the true branch. - * Unlikely branches - These can be assumed to be taken less than 20% - of the time. So we given them one of the lowest priorities. + * If branches (regular) - Both sides get the same weight, but on x86-64 the + instruction selector adds 3 to the weight of a floating-point comparison's + false edge (genCondBranch' in GHC.CmmToAsm.X86.CodeGen). If the weights are + still equal after optHsPatterns' other adjustments, favourFewerPreds adds + one to the side with fewer predecessors that could fall through into it, and + subtracts one from the other side. + * Unlikely branches - By the same weights we assume that these are taken 25% + of the time. So we give them one of the lowest priorities. * Switches - Switches at this level are implemented as jump tables so have a larger number of successors. So without more information we can only say that each individual successor is unlikely to be jumped to and we rank them accordingly. - * Calls - We currently ignore calls completely: + * Calls - A call's edge to its continuation gets callWeight. The + layout leaves these edges out when it builds chains (directEdges in + GHC.CmmToAsm.BlockLayout), and divides their weight by 64 when it merges the + chains at the end: * By the time we return from a call there is a good chance that the address we return to has already been evicted from cache eliminating a main advantage sequential placement brings. @@ -659,7 +666,7 @@ getCfg platform weights graph = blocks = revPostorder graph :: [CmmBlock] ---Find back edges by BFS +--Find back edges by a depth-first search (classifyEdges) findBackEdges :: HasDebugCallStack => BlockId -> CFG -> Edges findBackEdges root cfg = --pprTraceIt "Backedges:" $ @@ -991,9 +998,9 @@ check we do not apply any of the heuristics. The reason is simple: They look like loops in the control flow graph but are usually never entered, and if at most once. -Currently implemented is a heuristic to predict that we do not exit -loops (lehPredicts) and one to predict that backedges are more likely -than any other edge. +Three heuristics are implemented: that we do not exit loops (lehPredicts), that +a comparison with a literal is unequal (ohPredicts), and that a back edge is +more likely than any other edge. The back edge case is special as it supersedes any other heuristic if it applies. @@ -1055,7 +1062,9 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg = | length successors /= 2 = cfg - -- Only backedges - no need to adjust + -- Only backedges - no need to adjust. This case also keeps the weights + -- of a back edge beside a heap or stack check's edge, which the mix + -- case above excludes. | length m > 0 = cfg @@ -1116,7 +1125,9 @@ staticBranchPrediction _root (LoopInfo l_backEdges loopLevels l_loops) cfg = -- Heuristics return nothing if they don't say anything about this branch -- or Just (prob_s1) where prob_s1 is the likelihood for s1 to be the - -- taken branch. s1 is the branch in the true case. + -- taken branch. s1 is the successor with the smaller label, as + -- getSuccessorEdges orders them, and need not be the true branch: a + -- heuristic that needs the true branch looks it up, as ohPredicts does. -- Loop exit heuristic. -- We are unlikely to leave a loop unless it's to enter another one. ===================================== compiler/GHC/CmmToAsm/Instr.hs ===================================== @@ -29,7 +29,15 @@ class Instruction instr where -- | Get the registers that are being used by this instruction. -- regUsage doesn't need to do any trickery for jumps and such. - -- Just state precisely the regs read and written by that insn. + -- State the regs read and written by that insn as the register + -- allocators are to see them, which need not be what the hardware + -- does. Among other things, x86's regUsageOfInstr says that a + -- zeroing XOR, VXOR, PXOR or VPXOR reads nothing, and that at the + -- format FF32 or FF64 a MOV between registers or a MOVHLPS does + -- not read its destination, whose upper part the hardware keeps; + -- it records the float and vector registers a call clobbers at + -- the format FF64 whatever their width, and leaves out the real + -- registers the allocators do not hand out. -- The consequences of control flow transfers, as far as register -- allocation goes, are taken care of by the register allocator. -- ===================================== compiler/GHC/CmmToAsm/Monad.hs ===================================== @@ -117,7 +117,7 @@ data NcgImpl statics instr jumpDest = NcgImpl { -- ^ given the instruction sequence of a block, produce a list of -- the block's 'UnwindPoint's -- See Note [What is this unwinding business?] in "GHC.Cmm.DebugBlock" - -- and Note [Unwinding information in the NCG] in this module. + -- and Note [Unwinding information in the NCG] in "GHC.CmmToAsm". invertCondBranches :: Maybe CFG -> LabelMap RawCmmStatics -> [NatBasicBlock instr] -> [NatBasicBlock instr] -- ^ Turn the sequence of @jcc l1; jmp l2@ into @jncc l2; \<block_l1>@ ===================================== compiler/GHC/CmmToAsm/PIC.hs ===================================== @@ -7,12 +7,12 @@ Things outside this module which are related to this: - + module CLabel + + GHC.Cmm.CLabel - PIC base label (pretty printed as local label 1) - DynamicLinkerLabels - several kinds: CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset - labelDynamic predicate - + module Cmm + + GHC.Cmm.Reg and GHC.Cmm.Expr - The GlobalReg datatype has a PicBaseReg constructor - The CmmLit datatype has a CmmLabelDiffOff constructor + codeGen & RTS @@ -22,15 +22,18 @@ because Win32 doesn't support external references in data sections. TODO: make sure this still works, it might be bitrotted + NCG - - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all + - cmmToCmm in GHC.Cmm.GenericOpt calls cmmMakeDynamicReference for all labels. - - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output - all the necessary stuff for imported symbols. + - makeImportsDoc in GHC.CmmToAsm calls pprImportedSymbol and + pprGotDeclaration to output all the necessary stuff for imported + symbols. - The NCG monad keeps track of a list of imported symbols. - - MachCodeGen invokes initializePicBase to generate code to initialize - the PIC base register when needed. - - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel - that wasn't in the original Cmm code (e.g. floating point literals). + - The x86 and PowerPC instruction selectors invoke initializePicBase_x86 + and initializePicBase_ppc to generate code to initialize the PIC base + register when needed. + - The instruction selectors call cmmMakeDynamicReference whenever they + use a CLabel that wasn't in the original Cmm code (e.g. floating point + literals). -} module GHC.CmmToAsm.PIC ( ===================================== compiler/GHC/CmmToAsm/Reg/Graph.hs ===================================== @@ -131,9 +131,8 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap $$ text "regsFree = " <> (hcat $ punctuate space $ map ppr $ nonDetEltsUniqSet $ unionManyUniqSets $ nonDetEltsUFM regsFree) - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- The order decides only how the panic message lists the free + -- registers (Note [Unique Determinism and code generation]) $$ text "slotsFree = " <> ppr (sizeUniqSet slotsFree)) -- Build the register conflict graph from the cmm code. @@ -193,7 +192,7 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap -- Coloring was successful because no registers needed to be spilled. then do - -- if -fasm-lint is turned on then validate the graph. + -- if -dasm-lint is turned on then validate the graph. -- This checks for bugs in the graph allocator itself. let graph_colored_lint = if ncgAsmLinting config @@ -254,7 +253,7 @@ regAlloc_spin config spinCount triv regsFree slotsFree slotsCount debug_codeGrap -- Coloring was unsuccessful. We need to spill some register to the -- stack, make a new graph, and try to color it again. else do - -- if -fasm-lint is turned on then validate the graph + -- if -dasm-lint is turned on then validate the graph let graph_colored_lint = if ncgAsmLinting config then Color.validateGraph (text "") ===================================== compiler/GHC/CmmToAsm/Reg/Graph/Base.hs ===================================== @@ -96,9 +96,8 @@ worst regsOfClass regAlias neighbors classN classC = let regAliasS regs = unionManyUniqSets $ map regAlias $ nonDetEltsUniqSet regs - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- The union does not depend on the order + -- (Note [Unique Determinism and code generation]) -- all the regs in classes N, C regsN = regsOfClass classN ===================================== compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs ===================================== @@ -79,9 +79,9 @@ regSpill platform code slotsFree slotCount regs -- See Note [UniqFM and the register allocator] $ listToUFM $ zip (nonDetEltsUniqSet regs) slots :: UniqFM Reg Int - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- The order of both lists decides which free slots + -- are taken and which spilled vreg gets each + -- (Note [Unique Determinism and code generation]) -- Grab the unique supply from the monad. UDSM $ \us -> ===================================== compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs ===================================== @@ -122,9 +122,9 @@ slurpSpillCostInfo platform cfg cmm = do -- Increment the lifetime counts for regs live on entry to this instr. mapM_ incLifetime $ nonDetEltsUniqSet rsLiveEntry - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- Each vreg's lifetime is counted on + -- its own, so the order does not matter + -- (Note [Unique Determinism and code generation]) -- Increment counts for what regs were read/written from. -- See Note [Cached register usage in liveness annotations] in GHC.CmmToAsm.Reg.Liveness @@ -178,8 +178,6 @@ chooseSpill info graph -- cost = sum loadCost * freq (u) + sum storeCost * freq (d) -- u <- uses (v) d <- defs (v) -- --- There are no loops in our code at the moment, so we can set the freq's to 1. --- -- If we don't have live range splitting then Chaitins function performs badly -- if we have lots of nested live ranges and very few registers. -- ===================================== compiler/GHC/CmmToAsm/Reg/Linear.hs ===================================== @@ -201,7 +201,7 @@ regAlloc _ (CmmProc _ _ _ _) -- | Do register allocation on some basic blocks. -- But be careful to allocate a block in an SCC only if it has --- an entry in the block map or it is the first block. +-- an entry in the block map or it is an entry block of the procedure. -- linearRegAlloc :: forall instr. (Instruction instr) @@ -286,11 +286,10 @@ linearRA_SCCs entry_ids block_live blocksAcc (CyclicSCC blocks : sccs) before allocating one of its predecessors, which could lead to inconsistent allocations. Make it so a block is only allocated if a predecessor has set the "incoming" assignments for the block, or - if it's the procedure's entry block. + if it is one of the procedure's entry blocks. - BL 2009/02: Careful. If the assignment for a block doesn't get set for - some reason then this function will loop. We should probably do some - more sanity checking to guard against this eventuality. + A block whose assignment never gets set is dropped: process stops after + a round in which it allocates no block. -} process :: forall freeRegs instr. (OutputableRegConstraint freeRegs instr) @@ -701,9 +700,10 @@ saveClobberedTemps clobbered dying -> RegM freeRegs (RegMap Loc,[instr]) maybe_spill !temp !(assig,instrs) !loc = case loc of - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- saveClobberedTemps folds maybe_spill over the vregs in the + -- order of their uniques, so the order decides which clobbered + -- values move to free registers and which are spilled once + -- those run out (Note [Unique Determinism and code generation]) Loc (InReg reg) fmt | any (realRegsAlias reg) clobbered , temp `notElem` map getUnique dying @@ -775,9 +775,8 @@ clobberRegs clobbered assig <- getAssigR setAssigR $! clobber assig (nonDetUFMToList assig) - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- Each vreg is updated on its own, so the list's order does + -- not matter (Note [Unique Determinism and code generation]) where -- if the temp was InReg and clobbered, then we will have @@ -871,8 +870,13 @@ allocateRegsAndSpill reading keep spills alloc (r@(VirtualRegWithFormat vr vrFmt | otherwise -> doSpill WriteNew -- | Given a virtual reg find a preferred real register. --- The preferred register is simply the first one the variable --- was assigned to (if any). This way when we allocate for a loop +-- A block's entry assignment is recorded at the first jump into it, and the +-- preferred register is the variable's register in the first entry assignment, +-- in allocation order, that maps it to a register ('updateBlockAssignment' +-- keeps the first). That need not be the first register the variable was +-- assigned to, and a variable that no entry assignment maps to a register has +-- none. +-- This way when we allocate for a loop -- variables are likely to end up in the same registers at the -- end and start of the loop, avoiding redundant reg-reg moves. -- Note: I tried returning a list of past assignments, but that @@ -932,9 +936,12 @@ allocRegsAndSpill_spill reading keep spills alloc r@(VirtualRegWithFormat vr vrF flip delListFromUFM (fmap virtualRegWithFormat_reg keep) $ filterUFM (inRegOrBoth . locWithFormat_loc) $ assig - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- candidates lists the vregs in a register, except those + -- in keep, in the order of their uniques, and that order + -- picks the vreg evicted below: of those whose register + -- is of the class needed (compat), the first in both a + -- register and a slot, else the first in a register only + -- (Note [Unique Determinism and code generation]) let candidates = nonDetUFMToList candidates' -- the vregs we could kick out that are already in a slot ===================================== compiler/GHC/CmmToAsm/Reg/Linear/AArch64.hs ===================================== @@ -72,7 +72,8 @@ allocateReg (RealRegSingle r) (FreeRegs g f) | r > 31 = panic $ "Linear.AArch64.allocReg: double allocation of float reg v" ++ show (r - 32) ++ "; " ++ showBits f | otherwise = pprPanic "Linear.AArch64.allocReg" $ text ("double allocation of gp reg x" ++ show r ++ "; " ++ showBits g) --- we start from 28 downwards... the logic is similar to the ppc logic. +-- getFreeRegs starts from x18 downwards (x19 to x28 hold STG's registers, +-- below) and from v31 downwards... the logic is similar to the ppc logic. -- 31 is Stack Pointer -- 30 is Link Register -- 29 is Stack Frame (by convention) ===================================== compiler/GHC/CmmToAsm/Reg/Linear/Base.hs ===================================== @@ -153,7 +153,7 @@ regsOfLoc (InBoth r _) = [r] regsOfLoc (InMem _) = [] -- | Reasons why instructions might be inserted by the spiller. --- Used when generating stats for -ddrop-asm-stats. +-- Used when generating stats for -ddump-asm-stats. -- data SpillReason -- | vreg was spilled to a slot so we could use its @@ -208,7 +208,7 @@ data RA_State freeRegs -- | unique supply for generating names for join point fixup blocks. , ra_us :: DUniqSupply - -- | Record why things were spilled, for -ddrop-asm-stats. + -- | Record why things were spilled, for -ddump-asm-stats. -- Just keep a list here instead of a map of regs -> reasons. -- We don't want to slow down the allocator if we're not going to emit the stats. , ra_spills :: [SpillReason] ===================================== compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs ===================================== @@ -23,11 +23,13 @@ import GHC.Platform -- Here's an inefficient 'executable specification' of the FreeRegs data type: -- -- type FreeRegs = [RegNo] --- noFreeRegs = 0 +-- noFreeRegs = [] -- releaseReg n f = if n `elem` f then f else (n : f) -- initFreeRegs = allocatableRegs --- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f +-- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) (inOrder f) -- allocateReg f r = filter (/= r) f +-- +-- where inOrder sorts the registers into the instance's own fixed order. import qualified GHC.CmmToAsm.Reg.Linear.PPC as PPC import qualified GHC.CmmToAsm.Reg.Linear.X86 as X86 ===================================== compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs ===================================== @@ -97,9 +97,9 @@ joinToTargets' block_live new_blocks block_id instr (dest:dests) -- and free up those registers which are now free. let to_free = [ r | (reg, Loc loc _locFmt) <- nonDetUFMToList assig - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- The registers are released into a bitmap of + -- free registers, so the order does not matter + -- (Note [Unique Determinism and code generation]) , not (elemUniqSet_Directly reg $ getRegs live_set) , r <- regsOfLoc loc ] @@ -159,9 +159,9 @@ joinToTargets_again | equalIgnoringFormats (nonDetUFMToList dest_assig) (nonDetUFMToList src_assig) - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- Both lists are in the order of the uniques, so + -- the comparison does not depend on that order + -- (Note [Unique Determinism and code generation]) = joinToTargets' block_live new_blocks block_id instr dests -- assignments don't match, need fixup code @@ -237,17 +237,15 @@ joinToTargets_again -- | Construct a graph of register\/spill movements. -- --- Cyclic components seem to occur only very rarely. --- -- We cut some corners by not handling memory-to-memory moves. -- This shouldn't happen because every temporary gets its own stack slot. -- makeRegMovementGraph :: RegMap Loc -> RegMap Loc -> [Node Loc Unique] makeRegMovementGraph adjusted_assig dest_assig = [ node | (vreg, src) <- nonDetUFMToList adjusted_assig - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- The list's order, by unique, decides the order of the + -- fixup moves and which move of a cycle goes through the + -- stack (Note [Unique Determinism and code generation]) -- source reg might not be needed at the dest: , Just loc <- [lookupUFM_Directly dest_assig vreg] , node <- expandNode vreg src loc ] @@ -323,8 +321,10 @@ handleComponent delta _ (AcyclicSCC (DigraphNode vreg src dsts)) -- (vreg1, InReg r1, [InReg r2]) -- (vreg2, InReg r2, [InReg r1]) -- --- To avoid needing temp register, we just spill all the source regs, then --- reaload them into their destination regs. +-- To avoid needing a temp register, we spill the first move's source +-- reg into its vreg's slot, do the other moves (handling any cycle left +-- among them the same way), and reload the slot into the first move's +-- destination reg last. -- -- Note that we can not have cycles that involve memory locations as -- sources as single destination because memory locations (stack slots) ===================================== compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs ===================================== @@ -7,8 +7,9 @@ -- The StackMap stack map keeps track of virtual register - stack slot -- associations and of which stack slots are still free. Once it has been --- associated, a stack slot is never "freed" or removed from the StackMap again, --- it remains associated until we are done with the current CmmProc. +-- associated, a stack slot is never "freed": no other virtual register +-- gets it before we are done with the current CmmProc, even after its +-- register has outgrown it and moved to new slots. -- module GHC.CmmToAsm.Reg.Linear.StackMap ( StackSlot, ===================================== compiler/GHC/CmmToAsm/Reg/Liveness.hs ===================================== @@ -522,9 +522,9 @@ slurpReloadCoalesce live = listToUFM_Directly $ [ (k, r1) | (k, r1) <- nonDetUFMToList map1 - -- This is non-deterministic but we do not - -- currently support deterministic code-generation. - -- See Note [Unique Determinism and code generation] + -- Each entry is kept or dropped on its own and the list + -- becomes a map again, so its order does not matter + -- (Note [Unique Determinism and code generation]) , case lookupUFM_Directly map2 k of Nothing -> False Just r2 -> r1 == r2 ] ===================================== compiler/GHC/CmmToAsm/Reg/Target.hs ===================================== @@ -1,7 +1,5 @@ -- | Hard wired things related to registers. --- This is module is preventing the native code generator being able to --- emit code for non-host architectures. -- -- TODO: Do a better job of the overloading, and eliminate this module. -- We'd probably do better with a Register type class, and hook this to ===================================== compiler/GHC/CmmToAsm/X86/CodeGen.hs ===================================== @@ -344,8 +344,11 @@ stmtToInstrs bid stmt = do CmmBranch id -> return $ genBranch id - --We try to arrange blocks such that the likely branch is the fallthrough - --in GHC.Cmm.ContFlowOpt. So we can assume the condition is likely false here. + -- The condition may be likely true here: GHC.Cmm.ContFlowOpt inverts a + -- condition whose true target has one predecessor if the condition is + -- likely true, but also, whatever its likelihood, if the false target + -- has more than one predecessor (Note [Invert Cmm conditionals]). + -- genCondBranch does not read the likelihood. CmmCondBranch arg true false _ -> genCondBranch bid true false arg CmmSwitch arg ids -> genSwitch arg ids bid CmmCall { cml_target = arg ===================================== compiler/GHC/CmmToAsm/X86/Instr.hs ===================================== @@ -448,8 +448,12 @@ regUsageOfInstr platform instr , OpReg {} <- src , OpReg {} <- dst -> readOp dst_fmt src <.> modifyOp dst_fmt dst - -- other MOV instructions zero any remaining upper part of the destination - -- (largely to avoid partial register stalls) + -- The usage of the other MOV instructions has a register destination + -- written, not read. Some of them zero any remaining upper part of the + -- destination (largely to avoid partial register stalls), 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 (movss, movsd) + -- and an 8-bit or 16-bit MOV into a general register. | otherwise -> readOp dst_fmt src <.> writeOp dst_fmt dst MOVD fmt1 fmt2 src dst -> ===================================== compiler/GHC/CmmToAsm/X86/Ppr.hs ===================================== @@ -105,8 +105,8 @@ pprNatCmmDecl config proc@(CmmProc top_info entry_lbl _ (ListGraph blocks)) = -- info table and not the entry code! , pprProcAlignment config - -- Special label when ncgExposeInternalSymbols is enabled. See Note - -- [Internal proc labels] in GHC.Cmm.Label + -- Special label when ncgExposeInternalSymbols is enabled. See + -- Note [Internal proc labels] in GHC.Cmm.CLabel , pprExposedInternalProcLabel config entry_lbl -- Subsections-via-symbols label. See Note [Subsections Via Symbols] ===================================== compiler/GHC/CmmToAsm/X86/Regs.hs ===================================== @@ -225,10 +225,10 @@ allMachRegNos platform = intregnos (platformWordSize platform) ++ floatregnos pl -- | Take the class of a register. {-# INLINE classOfRealReg #-} classOfRealReg :: Platform -> RealReg -> RegClass --- On x86, we might want to have an 8-bit RegClass, which would --- contain just regs 1-4 (the others don't have 8-bit versions). +-- On i386, we might want to have an 8-bit RegClass, which would +-- contain just regs 0-3 (the others don't have 8-bit versions). -- However, we can get away without this at the moment because the --- only allocatable integer regs are also 8-bit compatible (1, 3, 4). +-- only allocatable integer regs are also 8-bit compatible (0, 2, 3). classOfRealReg platform reg = case reg of RealRegSingle i ===================================== compiler/GHC/Platform/Reg.hs ===================================== @@ -72,8 +72,8 @@ data VirtualReg -- We can't derive Ord, because Unique doesn't have an Ord instance. -- Note nonDetCmpUnique in the implementation. See Note [No Ord for Unique]. --- This is non-deterministic but we do not currently support deterministic --- code-generation. See Note [Unique Determinism and code generation] +-- This compares uniques, so the order is deterministic only if the uniques are: +-- see Note [Unique Determinism and code generation]. instance Ord VirtualReg where compare vr1 vr2 = case compare (I# (dataToTag# vr1)) (I# (dataToTag# vr2)) of ===================================== compiler/GHC/Platform/Reg/Class.hs ===================================== @@ -30,7 +30,9 @@ instance Outputable RegClass where data RegArch -- | Floating-point and vector registers are unified (e.g. X86, AArch64). = Unified - -- | Floating-point and vector registers are separate (e.g. RISC-V). + -- | Floating-point and vector registers are separate. No architecture uses + -- this yet: registerArch gives RISC-V NoVectors, as its vector registers are + -- not supported. | Separate -- | No vector registers. | NoVectors ===================================== compiler/GHC/StgToCmm/Monad.hs ===================================== @@ -835,10 +835,14 @@ mkCmmIfThenElse' e tbranch fbranch likely = do let (test, then_, else_, likely') = case likely of Just False | Just e' <- maybeInvertCmmExpr e - -- currently NCG doesn't know about likely - -- annotations. We manually switch then and - -- else branch so the likely false branch - -- becomes a fallthrough. + -- The NCG uses likely annotations on x86-64, where getCfg in + -- GHC.CmmToAsm.CFG weights the CFG's edges by them for the block layout + -- and the order of some conditional branches' jumps, and on PowerPC, + -- which prints them as hints on its branches. Where maybeInvertCmmExpr + -- can invert it, a test annotated likely false becomes a likely-true + -- test of the inverse, with the branches swapped. GHC.Cmm.ContFlowOpt + -- swaps them back where the true target, after shortcutting, has one + -- predecessor (Note [Invert Cmm conditionals]). -> (e', fbranch, tbranch, Just True) _ -> (e, tbranch, fbranch, likely) ===================================== docs/users_guide/using-optimisation.rst ===================================== @@ -250,8 +250,7 @@ as such you shouldn't need to set any of them explicitly. A flag :default: off but enabled by :ghc-flag:`-O`. Enables the sinking pass in the code generator. - This optimisation attempts to find identical Cmm blocks and - eliminate the duplicates attempts to move variable bindings closer + This optimisation attempts to move variable bindings closer to their usage sites. It also inlines simple expressions like literals or registers. @@ -263,10 +262,15 @@ as such you shouldn't need to set any of them explicitly. A flag :default: off but enabled by :ghc-flag:`-O`. - This enables static control flow prediction on the final Cmm - code. If enabled GHC will apply certain heuristics to identify - loops and hot code paths. This information is then used by the - register allocation and code layout passes. + This enables static control flow prediction in the native code generator + for x86-64. If enabled GHC will apply certain heuristics to identify loops + and hot code paths, and use this information to lay out the code and to + order the jumps of some conditional branches. On x86-64 the graph colouring + allocators (:ghc-flag:`-fregs-graph`, :ghc-flag:`-fregs-iterative`) weight + the register uses and definitions they count by the same heuristics whatever + this flag says, unless :ghc-flag:`-finfo-table-map` is on, but they choose + what to spill by live range length alone, so this flag does not change their + allocation. It has no effect when :ghc-flag:`-finfo-table-map` is on. .. ghc-flag:: -fcmm-control-flow :shortdesc: Enable control flow optimisation in the Cmm backend. Implied by :ghc-flag:`-O`. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/5b2bbcc8fbf6da4903b9209e3c11eb8f... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/5b2bbcc8fbf6da4903b9209e3c11eb8f... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Mikolaj Konarski (@Mikolaj)