[Git][ghc/ghc][wip/ncg-notes] 10 commits: Fix stale and false comments in the NCG
Mikolaj Konarski pushed to branch wip/ncg-notes at Glasgow Haskell Compiler / GHC Commits: 78010b54 by Mikolaj Konarski at 2026-11-29T13:06:55+01:00 Fix stale and false comments in the NCG Of what anyone working with the NCG needs, this commit serves "Comments and Notes that are true of the code they describe." Comments and documentation only: the generated code is the same. Each item names a comment, says what it said, and says what holds instead. - The comment above genMachCode in GHC.CmmToAsm named stix code and the UniqSM monad. The code is Cmm, and genMachCode switches from the UniqDSM monad to NatM. - The comment on NcgImpl's extractUnwindPoints, in GHC.CmmToAsm.Monad, placed Note [Unwinding information in the NCG] in that module. The Note is in GHC.CmmToAsm. - The header of GHC.CmmToAsm.PIC named the modules CLabel, Cmm, AsmCodeGen and MachCodeGen. It now names the modules and functions that do what it lists, and which labels each converts. Two comments further down named MachCodeGen. One named it as calling cmmMakeDynamicReference for static data, which the instruction selectors do for some labels, such as those of floating point literals on i386 and PowerPC. The other named it as calling the initialization of the PIC base register for every procedure that accessed it, which cmmTopCodeGen does on i386 and on 32-bit PowerPC but not AIX. They now say so. The first also said that cmmToCmm calls cmmMakeDynamicReference for every CmmLabel in the Cmm code, where it does so only in procedures' code, and the second that the initialization adds its instructions to the top of the procedure, where on ELF it also adds them to the top of each block with an info table. They now say that too. The header also said that for Win32 only SRTs might contain addresses of __imp_ symbol pointers, with a TODO that this might be bitrotted. Only cmmMakeDynamicReference makes such a pointer's label, so none is in data, and an SRT holds its closures' own labels, also under -fexternal-dynamic-refs for closures in other packages. The sentence and its TODO are deleted. - The header of GHC.CmmToAsm.Reg.Target said that the module keeps the NCG from emitting code for an architecture other than the host's. Each of its functions dispatches on the target platform's architecture, and the sentence is deleted. Its TODO, to make arch specific versions of RegAlloc.Graph.TrivColorable, named a module now called GHC.CmmToAsm.Reg.Graph.TrivColorable, and dates from 2009, when that module chose its counts of registers by the host's architecture. trivColorable now takes the target platform, by which it chooses each architecture's count, and the squeeze functions of the target's Regs module, which this module's targetVirtualRegSqueeze and targetRealRegSqueeze choose. The TODO is deleted. - Note [CFG based code layout] in GHC.CmmToAsm.BlockLayout placed optimizeCFG right after instruction selection. cmmNativeGen runs it, where it keeps the CFG (x86 and x86-64, not under -finfo-table-map), after register allocation and shortcutting. The Note presented the next two steps, loopInfo's loop analysis and mkGlobalWeights' refinement of the edge weights, as unconditional. optimizeCFG takes them only under -fcmm-static-pred, which -O implies, and the Note now says so. The Note said that the refined weights are normalized relative to the most often visited node. They are relative to the entry node, to which calcFreqs gives frequency 1. The Note also said that sequenceChain and addPreentryBlock recognise call edges by their CmmCall source. addPreentryBlock, through isCallEdge, also takes a CmmForeignCall source, and the Note now says so. - The haddock of the Ord instance of CfgEdge, in GHC.CmmToAsm.CFG, said that edges are sorted ascending pointwise by weight, source and destination. The instance orders them lexicographically, and "pointwise" is deleted. - Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG said that its author knew of a jump target that is an immediate value only without tables next to code. With tables next to code a tail call's jump to a label has one, which x86's canShortcut accepts, and the sentence is deleted. - Note [CFG Edge Weights] in GHC.CmmToAsm.CFG gave the default weight as 20k; defaultWeights has 1000. It said that likely branches are taken more than 80% of the time and unlikely ones less than 20%; the default weights give 75% and 25%. It said that the false side of a regular branch is preferred; getCfg gives both sides the same weight. On x86 and x86-64 the x86 instruction selector adds 3 to the false side of a floating-point comparison, and, where the weights stay equal, as they do not after that 3, optHsPatterns' favourFewerPreds may weight one side above the other by their predecessors. It said that calls are ignored completely; the layout leaves a call's edge out while it builds chains and while it combines neighbouring chains, and divides its weight by 64 when it merges the chains. - Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout said that edges constituted by a call are ignored. The layout ignores them while it builds the chains and while it combines neighbouring chains, and counts a 64th of their weight when it merges the chains. - Note [Static Branch Prediction] in GHC.CmmToAsm.CFG named two heuristics. staticBranchPrediction applies three, ohPredicts being the third. - In staticBranchPrediction, in GHC.CmmToAsm.CFG, a comment said that s1 is the branch in the true case; s1 is the successor with the smaller label. The guard commented "Only backedges" is also reached by a back edge beside a heap or stack check's edge, and its comment now says so. - The comment above findBackEdges, in GHC.CmmToAsm.CFG, said that back edges are found by BFS. findBackEdges finds them by a depth-first search (classifyEdges in GHC.Data.Graph.Directed). - A comment in the Instruction class said that regUsageOfInstr is to state precisely the registers an instruction reads and writes. x86's regUsageOfInstr returns them as the register allocators are to use them. The comment now says so, with examples of where that departs from what the hardware does. - The comment at the last arm of regUsageOfInstr's MOV case, in GHC.CmmToAsm.X86.Instr, said that the MOV instructions reaching it zero any remaining upper part of the destination. Some do, such as a 32-bit MOV into a general register and, up to bit 127, a load at FF32 or FF64. Others keep it, such as a MOV between registers at FF32 or FF64, printed movss or movsd, and an 8-bit or 16-bit MOV into a general register. The comment now also says that the usage of the other MOV instructions has a register destination written, not read. The comment at the MOVD arm said that MOVD and MOVQ always zero any remaining upper part of the destination. The legacy forms GHC prints zero it only up to bit 127, keeping bits 128 and above of a ymm register, and the comment now says up to bit 127. - Comments in GHC.CmmToAsm.Reg.Liveness, in both register allocators and at the Ord instances of CmmTickScope, LocalReg and VirtualReg said that deterministic code generation is not supported, which -fobject-determinism provides for a Haskell module compiled without -fcmm-thread-sanitizer, in its object's code, data and relocations; under -g, with other values of -dinitial-unique and -dunique-increment, the object's DWARF lexical blocks come in another order, and under -fllvm the object's FILE symbol names a temporary .ll file whose name depends, among other things, on what else the build compiles. In GHC.CmmToAsm.Reg.Liveness and the allocators, each now says whether the order at hand matters and, where it does, what it decides. At the Ord instances, each now says that the order compares uniques and so is deterministic if the uniques are. - In GHC.CmmToAsm.Reg.Graph.SpillCost, a comment said that there are no loops in the code, so that the block frequencies can be 1. Given a CFG, slurpSpillCostInfo scales the uses and definitions it counts by the CFG's block frequencies. The sentence is deleted. - linearRegAlloc's haddock and the comment over process said that a block of an SCC is allocated before a jump into it only if it is the first block (the haddock) or the procedure's entry block (the comment). Any of the procedure's entry blocks is. The comment over process also said that process loops where a block's assignment never gets set. process stops after a round that allocates no block, and so drops such a block. - findPrefRealReg's comment said that the preferred register is the first one the variable was assigned to. It is the variable's register in the first entry assignment, in allocation order, that maps it to a register. A block's entry assignment is recorded at the first jump into it. - Two comments in GHC.CmmToAsm.Reg.Graph named the flag -fasm-lint, which is -dasm-lint. The one in a round that spills also said that the graph is then validated, which it is not: nothing evaluates the validated graph that round stores, and that comment is deleted. - Two comments in GHC.CmmToAsm.Reg.Linear.Base named the stats flag -ddrop-asm-stats, which is -ddump-asm-stats. - The executable specification of FreeRegs, in GHC.CmmToAsm.Reg.Linear.FreeRegs, handed out the most recently released registers first. It now gives noFreeRegs as [] and has getFreeRegs hand out the registers in each instance's fixed order. Its allocateReg took the set first and its getFreeRegs classed registers by regClass, which GHC does not have; both now follow the instances (the register first, targetClassOfRealReg). It made releasing a free register and allocating an allocated one no-ops and now says that the AArch64, RISC-V and LoongArch instances panic there. - The header of GHC.CmmToAsm.Reg.Linear.StackMap said that a slot stays associated with its register to the end of the procedure. A register that outgrows its slot moves to new ones. What holds is that no other register gets the old slot. - The comment at handleComponent's case for a cycle of moves, in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that all the cycle's source registers are spilled. handleComponent spills one. - makeRegMovementGraph's comment said that cyclic components seem to occur only very rarely. They are frequent in some code: in the benchmark of an unreleased version of orthotope, a Haskell array library, the fixup code breaks register cycles through a stack slot in $w$s$wequalT1 and in $w$s$w$ccompare1. The sentence is deleted. - A comment at expandNode's case for a move from InBoth to InMem, in GHC.CmmToAsm.Reg.Linear.JoinToTargets, said that the source's slot is guaranteed to be the destination's. They can differ where the virtual register has more than one slot, and the value is then stored from its register. The comment now says that the guard fails only there. - A comment in GHC.CmmToAsm.X86.Ppr's pprNatCmmDecl cited Note [Internal proc labels] in GHC.Cmm.Label, across two lines. The Note is in GHC.Cmm.CLabel, and the citation is now on one line. - A comment in GHC.CmmToAsm.Reg.Linear.AArch64 said that getFreeRegs scans the integer registers from 28 down. getFreeRegs starts from x18, and the comment now also says that it starts from v31 among the v registers. - The comment at classOfRealReg in GHC.CmmToAsm.X86.Regs said "On x86" of what holds on i386 alone. It numbered the registers with 8-bit versions 1-4, and the allocatable ones among them 1, 3 and 4. It now says "On i386", and they are 0-3, and 0, 2 and 3. - The haddock of RegArch's Separate, in GHC.Platform.Reg.Class, gave RISC-V as an example. registerArch gives RISC-V NoVectors and no architecture Separate. - A comment in the stmtToInstrs of each of X86, AArch64, LA64 and RV64 said that the condition of a conditional branch can be assumed likely false, because GHC.Cmm.ContFlowOpt arranges for the likely side to fall through. ContFlowOpt also inverts a condition whatever its likelihood where the condition can be inverted, the true target has one predecessor and the false target more than one, so the condition may be likely true. None of the four genCondBranch functions uses the likelihood. - A comment in mkCmmIfThenElse', in GHC.StgToCmm.Monad, said that the NCG does not know about likely annotations. The PowerPC code generator has printed them as branch hints since 2017. Since 2018 getCfg has weighted the CFG's edges by them, and on x86 and x86-64 without -finfo-table-map the block layout (not under -fblock-layout-weightless without -fblock-layout-cfg) and the order of some conditional branches' jumps (invertCondBranches) follow these weights. The comment's clause on a fallthrough is replaced by what the swap does: where the test can be inverted it becomes a likely-true test of the inverse, and GHC.Cmm.ContFlowOpt swaps the branches back where the true target, after shortcutting, has one predecessor. - Note [Updating the CFG during CodeGen], in GHC.CmmToAsm.Monad, said that cmmNativeGen removes the unreachable blocks before it builds the CFG and generates code. cmmNativeGen removes none there. The CFG lacks them, instruction selection still covers them, and no pass drops them before it. So the combinators that split a block panic in getSuccessorEdges when called in an unreachable block (ISSUE 28088). The Note now says so. - Note [Updating the CFG during CodeGen] also said that a store emits the code of its address before the code of its value and takes the address from getNonClobberedAmode. The assignMem_* functions of GHC.CmmToAsm.X86.CodeGen generate and emit the code of the value first and take the address from getAmode. getNonClobberedAmode is for code that must come between an amode and its use. The Note now says so. - Note [Updating the CFG during CodeGen] also said that sanityCheckCfg checks the CFG against the final instruction stream when -dasm-lint is on. sanityCheckCfg checks it against the code before block layout, also in a DEBUG compiler, and in either case only where ncgEnableDeadCodeElimination holds: on x86 and x86-64, without -finfo-table-map. The Note now says so. ISSUE 28179 reports three sentences of the Note: the one on sanityCheckCfg and those that said that cmmNativeGen removes the unreachable blocks before it builds the CFG and that a store emits the code of its address before that of its value. - A comment at makeImportsDoc, in GHC.CmmToAsm, put a hack for .subsections_via_symbols in PprMach.pprNatCmmDecl. A comment above initializePicBase_x86, in GHC.CmmToAsm.PIC, cited PprMach.hs for how FETCHGOT is printed. A comment above pprWordArray, in GHC.CmmToC, cited codeGen/ClosureInfo and nativeGen/PprMach for info tables as arrays of words. No module PprMach or ClosureInfo is left. The first comment now cites the printers' pprNatCmmDecl and Note [Subsections Via Symbols] in GHC.CmmToAsm.X86.Ppr, the second cites GHC.CmmToAsm.X86.Ppr, and the third cites mkInfoTable in GHC.Cmm.Info, which lays the info tables out, and pprNatCmmDecl in each GHC.CmmToAsm.*.Ppr, which prints them. - A comment in raInsn, in GHC.CmmToAsm.Reg.Linear, said that a real source register must be allocatable, since it would otherwise not be in r_dying, a name raInsn does not have. The guard looks the register up in liveDieRead, which the comment now names. - A comment in genRaInsn, in GHC.CmmToAsm.Reg.Linear, said that using nub on the registers read is no problem. The code uses nubOrdOn, and the clause is deleted. - The comment at initBlock's case for a block without an entry assignment, in GHC.CmmToAsm.Reg.Linear, took the block to be part of a loop that the allocator iterates over again. No block is allocated twice. The case is reached by an entry block, or by a block that no allocated jump reaches. The comment now says so, and what the case does. - The haddock of lookupFirstUsed, in GHC.CmmToAsm.Reg.Linear.Base, said that it gives the register a virtual register was first assigned to. lookupFirstUsed gives the variable's register in the first entry assignment, in allocation order, that maps it to a register, as findPrefRealReg's comment now says. The haddock now says so too. - The haddock of minusCoveredRegs, in GHC.CmmToAsm.Reg.Regs, said that it removes a register only where its format in the second argument is at least as large as in the first. minusCoveredRegs removes a register at a scalar format in the first whatever its format in the second, and compares a vector format by Format's derived Ord; the haddock now says so. - The haddock of shrinkingRegs, in GHC.CmmToAsm.Reg.Regs, said that it computes the registers in both arguments whose size is smaller in the second. shrinkingRegs also keeps every register of the first argument that is not in the second, and compares the formats by Format's derived Ord; the haddock now says so. - The comment "A Rule of the Game (tm) for Amodes" and the haddock of getNonClobberedAmode, in GHC.CmmToAsm.X86.CodeGen, said that getNonClobberedAmode's amode stays valid across other code. getNonClobberedAmode computes the address into a new temporary only where getAmode's amode names a real register that freeReg hands out; otherwise code that writes a virtual register the amode names breaks it. Both now except such code. - A comment in getAmode, in GHC.CmmToAsm.X86.CodeGen, said that a clause turns lit1 << n + lit2 into lit2 + lit1 << n for the next clause. The shifted operand is any expression. The clause is reached only for a literal that the clause for x + lit does not take. The swapped sum goes to the clause for x + (y << shift) or to the one for x + y. The comment now says so. - Note [Sinking and inlining] and the comment at shouldDiscard, in GHC.Cmm.Sink, compared sinking's deletion of dead assignments with removeDeadAssignments, which no longer exists. They now say only that sinking does not delete every dead assignment, without master's reason, that it would need multiple passes: no number of passes deletes a local that only its own assignment in a loop reads, or a dead store to a global register. - The haddock of FrontierMap, in GHC.CmmToAsm.BlockLayout, said that it maps the blocks near the end of a chain, and gave the front blocks [A,B] of [A,B,C,D,E] as the end region. combineNeighbourhood keeps one such map for the ends of the chains and one for their fronts. The haddock now says so, with an entry of each. - Note [When does an assignment conflict?], in GHC.Cmm.Sink, swapped 'A' and 'N' in its conditions (C1) and (C2). Its own (C1a) and (C1b), and the labels in conflicts, have (C1) where N assigns to a register A mentions, and (C2) where N reads the register A assigns. The conditions now say so. - The users' guide's entry of -fcmm-static-pred said that the prediction is made on the final Cmm code and used by the register allocation and code layout passes. The prediction is made only in the NCG for x86 and x86-64, on the NCG's CFG after register allocation and shortcutting. It is used, without -finfo-table-map, for the layout (not under -fblock-layout-weightless without -fblock-layout-cfg) and for the order of some conditional branches' jumps (invertCondBranches). The entry now also says that the graph colouring allocators (-fregs-graph, -fregs-iterative) choose what to spill by live range length alone (chooseSpill, spillCost_length), so that the flag does not change their allocation. Its short description, "Enable static control flow prediction.", named neither limit; it now names the native code generator for x86 and x86-64 and excludes -finfo-table-map. - The users' guide's entry of -fcmm-sink said that the sinking pass attempts to find identical Cmm blocks and eliminate the duplicates. Those are words of the -fcmm-elim-common-blocks entry, run into this entry's sentence since the two entries were written. The sentence now says only that the pass attempts to move variable bindings closer to their usage sites. - The users' guide's entries of -fblock-layout-cfg and -fblock-layout-weightless did not say that the flags act only where the CFG is kept. sequenceTop uses the chain algorithm, and the old algorithm uses the edge weights, only on x86 and x86-64 and without -finfo-table-map. Both entries now say so, and so does the short description of -fblock-layout-cfg, "Use the new cfg based block layout algorithm.", which named neither limit. The short description of -fblock-layout-weights said that the flag sets edge weights used by the new code layout algorithm; the old algorithm uses them too, without -fblock-layout-weightless, and invertCondBranches orders the jumps of some conditional branches by them. It now names both uses and the limits. The -fblock-layout-cfg entry also said that the flag builds a control flow graph, which cmmNativeGen builds whatever the flag says, and set the chain algorithm against the last jump of each block, which the old algorithm follows there only under -fblock-layout-weightless; it now sets it against at most one edge per block. The -fblock-layout-weightless entry said that without the flag the old algorithm also uses the heaviest outgoing edge; it uses that edge instead of the last jump, or none where that edge's weight is not positive or the block has more than two successors. The entry of -fasm-shortcutting and its short description, "Enable shortcutting on assembly.", did not say that the flag acts only on x86 and x86-64: the canShortcut of PowerPC, AArch64, RISC-V and LoongArch returns Nothing for every instruction, so that shortcutBranches removes no block there. Both now say so. - A comment above initializePicBase_x86, in GHC.CmmToAsm.PIC, and the one on FETCHGOT, in GHC.CmmToAsm.X86.Instr, said that FETCHGOT prints its last line as addl __GLOBAL_OFFSET_TABLE__+.-1b and the register. GHC.CmmToAsm.X86.Ppr prints addl $_GLOBAL_OFFSET_TABLE_+(.-1b), with one underscore at each end of the symbol, and the comments now show that line. - The short description of -fblock-layout-weightless in the users' guide said that the flag ignores the CFG's weights for code layout. The flag acts only on the old layout algorithm, as the entry's own text says, and at -O it changes nothing: on x86 and x86-64 without -finfo-table-map, -fblock-layout-cfg replaces that algorithm, and elsewhere that algorithm is given no CFG. The short description now names the old algorithm. - Note [When does an assignment conflict?], in GHC.Cmm.Sink, said that (C1) includes two situations, and lists three, (C1a) to (C1c). It now says three. - Note [Internal proc labels], in GHC.Cmm.CLabel, named the flag -fexpose-all-symbols and said that it is enabled by default, and the haddock of ppInternalProcLabel named Opt_ExposeAllSymbols. The flag is -fexpose-internal-symbols, whose GeneralFlag is Opt_ExposeInternalSymbols, and it is off by default. Both now say so. - The haddock of FrontierMap, in GHC.CmmToAsm.BlockLayout, said "cheaper then" where it means "cheaper than", which it now says. - Note [Sinking and inlining], in GHC.Cmm.Sink, said that an assignment is cheap where its right-hand side is a local register, the comment above isTrivial counted registers, both local and global, as trivial, and Note [Inline GlobalRegs?] said that GlobalRegs are treated as trivial and inlined everywhere. isTrivial, which decides it, accepts a local register, a literal, and a global register only where it is held in a machine register or, on ARM, any global register. The three now say so. Sinking does not inline such a register everywhere: an unsafe foreign call that returns defines the global registers held in machine registers that callerSaves names, okToInline returns False for an expression reading one and the call, and conflicts returns True for an assignment from one and the call, so the assignment is neither inlined into the call nor carried past it. On x86-64 Linux, where R3 is held in rsi, an assignment of R3 to a local register stays before an unsafe foreign call that takes the local, which on AArch64, where R3 is held in x24, takes R3 itself. The Note no longer says everywhere. The comment above okToInline said that nothing referring to global registers is inlined into an unsafe foreign call, where R1 is inlined into one on x86-64 Linux; it now names the global registers the call defines. - The users' guide's entries of -g and -fexpose-internal-symbols said that -g2 implies -fexpose-internal-symbols. setDebugLevel, in GHC.Driver.Session, sets the flag only above level 2, so -g3 implies it, and -g, which is level 2, does not. Both entries now say level 3. - A comment at CmmUnsafeForeignCall, in GHC.Cmm.Node, named GHC.Platform.callerSaves, which GHC.Platform does not export. The function is GHC.Platform.Regs.callerSaves, which the comment now names. - Note [Internal proc labels], in GHC.Cmm.CLabel, and the users' guide's entry of -fexpose-internal-symbols said that the flag makes GHC produce symbols for procedures internal to a module, and the haddock of ppInternalProcLabel made the function's label conditional on the flag. Only the code generator for x86 and x86-64 tests the flag, in pprExposedInternalProcLabel, before it calls ppInternalProcLabel, which tests none. The three now say so. The entry's short description, "Produce symbols for all functions, including internal functions.", named no target; it now names the native code generator for x86 and x86-64. The entry also said that -fno-expose-internal-symbols suppresses all non-global symbol table entries; it suppresses only the labels that the flag adds, and the sentence is deleted. - Note [Chain based CFG serialization], in GHC.CmmToAsm.BlockLayout, said that the chains are built ignoring calls and edges into a block prefixed by an info table, and its example of a block that ends up in a chain of its own was reached by such a jump. sequenceChain ignores only call edges there and keeps an edge into an info table's block at an eighth of its weight. The Note now names only calls, and its example reaches the block by a call. Its step 2 said that an edge (A -> B) fuses two chains where A ends one and B starts the other, and that the edge is skipped where no such chains are found. mergeChains fuses the chains holding A and B, that of A first, wherever A and B are in them, and skips the edge only where A and B are in one chain. Step 2 also said that it combines the chains resulting from the step above it, and came before step 3, which places neighbouring chains next to each other. sequenceChain runs combineNeighbourhood, step 3, before mergeChains, step 2, which takes its result. The Note now says so, and places and numbers the neighbour step before the fusing step. - The comment on cmmMakeDynamicReference above ReferenceKind, in GHC.CmmToAsm.PIC, said that a function for recording an imported symbol must be passed in, addImportCmmOpt or addImportNat. cmmMakeDynamicReference takes no such argument: it runs in an instance of CmmMakeDynamicReferenceM, whose addImport is addImportCmmOpt for CmmOptM and addImportNat for NatM. The comment now says so. - The users' guide's chapter on debugging compiled programs gave -g's levels as 0, 1 or 2 in the flag's short description, and its walkthrough said that there are three levels, -g2 emitting everything GHC knows, and that the GHC-specific annotations are emitted with -g2. The entry's list of levels said that -g2 adds unwinding records for inner blocks, allowing more precise backtraces than -g1, and that -g3 produces GHC-specific DWARF information, its section on GHC's DIEs gave the tag of DW_TAG_ghc_src_note as 0x5b01, and its implementor's notes said that under -g the DIEs in .debug_info can identify all relevant source locations. The entry's levels are 0 to 3, and it said that those are accepted, where -g9 and -g-1 compile too: GHC tests debugLevel only by > 0, < 2 and > 2, so a higher level acts as 3 and a negative one as 0, as the entry now says. Below level 2, dwarfGen, in GHC.CmmToAsm.Dwarf, strips the blocks (ncgDwarfStripBlockInfo, in GHC.Driver.Config.CmmToAsm) only from the DIEs and gives debugFrame the unstripped procedures, so -g1, -g2 and -g3 emit the same unwinding records, as objdump --dwarf=frames of objects compiled at the three levels shows, and -g2 adds DW_TAG_lexical_block DIEs. -g2 also emits GHC's own attribute DW_AT_ghc_tick_parent; what needs -g3 is the source-note DIEs: ncgDwarfSourceNotes holds only above level 2. GHC.CmmToAsm.Dwarf.Constants gives dW_TAG_ghc_src_note as 0x5b00. Below level 3 no DIE carries a source location: the subprogram and block abbreviations in GHC.CmmToAsm.Dwarf.Types hold none, and the spans are attributes of the source-note DIEs. The short description, the walkthrough and the annotations' sentence now name level 3, the walkthrough and the list give -g2 the block DIEs and -g3 the source notes, the section gives 0x5b00, and the notes give the source locations to the source-note DIEs that -g3 adds. The notes said that GHC produces DWARF v4, where GHC emits version 3 headers in .debug_info (compileUnitHeader, in GHC.CmmToAsm.Dwarf) and in .debug_frame (its CIE, in pprDwarfFrame in GHC.CmmToAsm.Dwarf.Types), and they now say v3. They said that the DIEs in .debug_info describe all of the basic blocks in the compiled program, where below level 2 they describe no block inside a procedure, and at no level a procedure that cmmDebugLink drops (the next item); they now say that its DIEs describe the functions and, from -g2, the blocks inside them. They named the sections .debug_frames and .debug_arange, which GHC.CmmToAsm.Dwarf.Constants names .debug_frame and .debug_aranges, as the notes now do. Note [Info Offset], in GHC.CmmToAsm.Dwarf.Types, named the frame section .debug_frames too, and now names it .debug_frame. - The users' guide's entry of -g said that only DWARF debug information is supported on x86-64 and i386, its short description said that the flag produces DWARF debug information in compiled object files, and a tip of its chapter on debugging compiled programs said how to extract the debug information on Mac OS X with dsymutil. Only the native code generator emits DWARF, and ncgDwarfEnabled, in GHC.Driver.Config.CmmToAsm, holds only for ELF targets other than AArch64: Mac OS X gets none, and x86, x86-64, 64-bit PowerPC with the ELFv2 ABI, RISC-V and LoongArch can get it, with unwinding records that follow the Haskell stack pointer only on x86 and x86-64, where extractUnwindPoints returns unwinding points, and there at most through a procedure's first block: the frame description entry ends at the end label that X86's pprBasicBlock prints after the procedure's entry block (procToFrame in GHC.CmmToAsm.Dwarf, pprFrameProc in GHC.CmmToAsm.Dwarf.Types), and the row added around a C call, naming the C stack pointer alone, gets from addDefaultUnwindings in GHC.CmmToAsm.Dwarf the CIE's initial rule for the Haskell stack pointer, Sp+0, which differs from the procedure's own rule at its entry where an argument is on the stack. objdump --dwarf=frames shows both for an object compiled at -O1 -g1 by a compiler of master's code, on x86-64 from Haskell, where a procedure of 0x92 bytes by nm -S gets a frame description entry of 10 bytes and a row setting the frame address's offset to 0 at a C call made where Sp is 8 bytes below its value at entry, and given an i386 target description through -B, from Cmm. The entry now says so, its short description names the native code generator and some ELF targets, and the tip is deleted. A comment in cmmDebugLabels, in GHC.Cmm.DebugBlock, said that declaring a block that holds only meta instructions missing skips debug data generation without messing up the block hierarchy. cmmDebugLink drops a missing block's DebugBlock with every block and procedure nested under it, so where a procedure's entry block holds only meta instructions, as at -O0 -g on x86-64 for an entry block that only moves the arguments and jumps to the heap check, that procedure and those nested under it get no DIEs from GHC and no unwinding records. The comment now says that cmmDebugLink skips the nested blocks and procedures too. - The haddock of mkGlobalWeights, Note [Static Branch Prediction] and the comment above calcFreqs, in GHC.CmmToAsm.CFG, gave the title of Wu and Larus's paper as "Static Branch Prediction and Program Profile Analysis". The paper, at MICRO-27 in 1994, is "Static Branch Frequency and Program Profile Analysis", which the three now give. - The users' guide's chapter on debugging compiled programs said that the debugging information does not affect the optimizations GHC performs. Under -g the native code generator can keep a block that holds only a jump, which -fasm-shortcutting removes without -g, as in the testsuite's T5149_cmm.cmm at -O2 on x86-64: compiled by a compiler of master's code, it jumps to g5149 directly without -g and through a kept block with it. The sentence is deleted. - The users' guide's entry of -fproc-alignment said that the flag aligns functions to multiples of the given value and that only powers of two are valid values. Only the native code generator's printers for x86, x86-64, RISC-V and LoongArch use the value, by pprProcAlignment, through mkAlignment in GHC.Types.Basic, which panics on a value that is not a power of two or is over 512, and the flag's parser checks no value; the native code generator for AArch64, PowerPC and wasm32, the LLVM backend and the C backend ignore it. On RISC-V and LoongArch the printers put the alignment before the procedure's section directive, so that for a value over 8 the flag does not align a procedure that data precedes, nor any under -fsplit-sections. The entry now says so. Given -fproc-alignment=64, a compiler of master's code gave the assembly it gave without the flag under -fllvm on x86-64 and given AArch64, 64-bit PowerPC and wasm32 target descriptions, and given 3 it panicked on x86-64 and compiled under -fllvm and for wasm32; given RISC-V and LoongArch ones, it put the info table of a procedure after an SRT in .data off 64 in the linked output. - The users' guide's entry of -mla664 said that GHC does not use LA664 specific instructions, so that the flag has no effect with the native code generator or the LLVM backend. With the flag, LoongArch's native code generator emits amcas_db for MO_Cmpxchg (genCmpxchg) and amswap_db for MO_Xchg (genXchg), which the compare-and-swap primops on byte arrays and addresses, the atomic exchange primops, Cmm's %cmpxchg and %xchg and the registration of -ticky's counters give, where without it it calls hs_cmpxchg8 to hs_cmpxchg64 and hs_xchg8 to hs_xchg64. The flag changes nothing else the code generators emit, and no code of the LLVM backend tests it. The entry now says so, naming the primops, and so does its short description, "Used for new instructions for la664 uarch", which named neither instruction. Given a LoongArch target description, a compiler of master's code emitted amcas_db and amswap_db under the flag and calls of hs_cmpxchg64 and hs_xchg64 without it. - Comments named modules and files by names that no longer exist, or never did. The header of GHC.Platform.Reg named NCGMonad, now GHC.CmmToAsm.Monad, which it now names. The header of GHC.CmmToAsm.Format had a TODO, from 2009, saying that the module is shared by all architectures because NCGMonad needs it to make a virtual register, and that architecture specific formats would be better, as SPARC does not use FF80. The SPARC code generator and FF80 have since been removed, and since 2024 the register allocators use Format too, for RegWithFormat; the TODO is deleted. Note [GHC's data format representations], in the same module, named Format.Format, now GHC.CmmToAsm.Format.Format. The header of GHC.CmmToAsm.Reg.Graph.Base placed the hand written versions of its functions in MachRegs*.hs, and the comment on its RegClass placed the allocatable register classes in MachRegs.hs; the header of GHC.CmmToAsm.Reg.Graph.X86 placed the reference in RegArchBase.hs and trivColorable in MachRegs.hs, and the haddock of that module's worst named RegColorBase; and the commented-out specification in GHC.CmmToAsm.Reg.Graph.TrivColorable compared its worst with RegArchX86 and said that the trivColorable function of each architecture should implement it, where one trivColorable takes each architecture's squeeze functions. The comments now name the squeeze functions of each architecture's Regs module, which trivColorable takes, GHC.Platform.Reg.Class, GHC.CmmToAsm.Reg.Graph.Base, GHC.CmmToAsm.Reg.Graph.TrivColorable and GHC.CmmToAsm.Reg.Graph.X86. The specification calls regClass and applies Reg's constructor RealReg, both removed in 2009, and its header now says that it is a sketch. The header of GHC.CmmToAsm.Reg.Graph.TrivColorable said that there is an allocatableRegsInClass :: RegClass -> Int, but that the unboxing is too slow there, with a TODO asking whether that is still true and whether allocatableRegsInClass could be used. allocatableRegsInClass is defined only in that specification, since 2009, and trivColorable uses the counts that allocatableRegs :: Arch -> RegClass -> Int hard-codes. The sentence and its TODO are deleted. The comment on the PowerPC calling conventions in GHC.CmmToAsm.PPC.CodeGen pointed to MachRegs.hs for the argument and nonvolatile registers, and now points to GHC.CmmToAsm.PPC.Regs. The haddock of PicBaseReg, in GHC.Cmm.Reg, named the module PositionIndependentCode, and comments in the AArch64, RISC-V and LoongArch instruction selectors named Cmm.CmmToAsm.PIC; both now name GHC.CmmToAsm.PIC. The same comments placed cmmExprNative, the second of the two callsites they gave cmmMakeDynamicReference, in GHC.CmmToAsm; it is in GHC.Cmm.GenericOpt, and each selector calls cmmMakeDynamicReference in genSwitch too, LoongArch's in genPrimCCall and genLibCCall rather than in genCCall, as the comments now say. A comment in GHC.CmmToAsm.Reg.Liveness named Digraph, now GHC.Data.Graph.Directed. Comments in GHC.Cmm.CLabel and GHC.Cmm.Sink named PprC, now GHC.CmmToC, and comments in GHC.Cmm.DebugBlock and GHC.Cmm.Utils named CmmSink, and one in compiler/CodeGen.Platform.h CmmSink.hs, now GHC.Cmm.Sink. A comment in GHC.CmmToC named nativeGen/AsmCodeGen as reordering blocks, which GHC.CmmToAsm.BlockLayout does and the comment now names. The comment on isTrivial's case for ARM, in GHC.Cmm.Sink, said that CodeGen.Platform.ARM does not have globalRegMaybe. When the case was added, in 2014, globalRegMaybe panicked on ARM; GHC.Platform.ARM's globalRegMaybe does not, and the comment now says so. A comment in GHC.Cmm.Parser said that OldCmm does not support a first class else statement. OldCmm was removed in 2012, and the comment is deleted. GHC.Cmm.Info named rts/include/rts/storage/InfoTable.h, and Note [No static object resurrection], in GHC.Cmm.Info.Build, named smStorage.h; the files are rts/include/rts/storage/InfoTables.h and rts/sm/Storage.h. Assisted-by: Claude Opus 5.5 - - - - - a4d7e4bc by Mikolaj Konarski at 2026-11-29T13:06:55+01:00 Define the labels of the NCG's comments Of what anyone working with the NCG needs, this commit serves "The kind of each statement in the NCG's comments, shown at the statement: a bug, half-done work, a likely change or code meant to stay.", "What a comment that does not show the kind of its statements does and does not claim.", "How the statements on bugs, half-done work and likely changes are kept true as the code changes." and "Each known bug's tracker issue, named at the code it concerns." Comments only; the generated code is the same. Note [Labels in NCG comments], added to GHC.CmmToAsm, defines the labels that comments added to the native code generator since then put at the head of a statement. The commits that follow label each statement they add, and are read under this Note: BUG wrong behaviour, a missing check or misleading code; the statement says in short what it leads to and, where the code shows it, where it is reached WIP half-done work TODO what is likely to change, correct or buggy; a bug marked TODO alone is accepted for now and worked around BUG TODO both, where both are to be stressed no label what is meant to stay, but a statement citing a labelled one is of its kind; a kept trade-off says why A BUG statement names its consequence: wrong code, wrong debugging information, a panic or another failed compilation, assembly the assembler rejects, only slower or larger code, only a warning from the assembler, only more C stack space, or only a misled reader. The Note does not reach back to older comments: their TODO, ToDo, FIXME and XXX predate its meanings, and an older comment's lack of a label makes no claim that the code is meant to stay. The Note also says how the labels are kept true. A change to what a labelled statement describes removes or rewrites the statement, and each statement that cites it, in the same change; BUG, TODO and BUG TODO gain the issue's number when the issue is filed, and the section's number after it where the issue collects several bugs in numbered sections; and a git grep given in the Note lists the labelled lines. Assisted-by: Claude Opus 5.5 - - - - - 19c2abd1 by Mikolaj Konarski at 2026-11-29T17:57:57+01:00 Document bugs and TODOs in the NCG's CFG and block layout Of what anyone working with the NCG needs, this commit serves "Where the code does something other than what reading it suggests.", "Where the code is known to behave wrongly or is half done.", "What each known bug leads to, such as wrong code, a compiler panic or only slower code, and under which flags and on which targets it is reached.", "Each known bug's tracker issue, named at the code it concerns." and "Where the code is likely to change, and how." Comments only; the generated code is the same. The statements carry the labels of Note [Labels in NCG comments]: BUG for wrong behaviour, BUG TODO for a bug that is also likely to change, TODO for what is likely to change, none for what is meant to stay. What each BUG leads to, where it is reached and what that rests on: - build_mapping in shortcutBranches, GHC.CmmToAsm (BUG, ISSUE 28222 section 2.2: under -g a block that holds only its jump can also hold the location and unwinding information that -g adds, and is then kept where without -g it is shorted). The code under -g jumps through the kept block, and on x86 and 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, ISSUE 28222 section 2.3: with tables next to code, 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 and x86-64, the targets with a CFG after register allocation, under -fasm-shortcutting, not on Darwin, not under -finfo-table-map, not for a jump through a symbol pointer, and under -g only for a jump-only block to which -g adds nothing. This rests on master's code read: the removed block ends in a tail call and has no edges out in the CFG; it leaves the code and the CFG together, and no block becomes unreachable; and the readers of the CFG after shortcutWeightMap do not panic on a missing edge: optimizeCFG's lookups take their blocks and edges from the CFG itself; sanityCheckCfg compares the jumps to blocks with the edges, and the jump that loses its edge, now to a label, is not among those jumps; 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. - Note [Updating the CFG during shortcutting] in GHC.CmmToAsm.CFG, its BUG TODO, ISSUE 28222 section 2.4 (where a redirected edge A -> C coincides with an edge A -> C already there, or with another redirected edge, only one EdgeInfo is kept, chosen by the order of the fold over A's targets in update_from_edge). The weights are not summed. This costs only speed, on x86 and x86-64 under -fasm-shortcutting, not on Darwin, not under -finfo-table-map, and under -g only for a jump-only block to which -g adds nothing. This rests on master's code read and on a run of master's compiler at -O0 -fasm-shortcutting, where in the Cmm procedure f (W_ x, W_ y, W_ z) { W_ t; if (x > y) (likely: True) { goto b; } else { goto c; } b: t = y; goto c; c: R1 = z + 1; jump g [R1]; } the two edges into c become one with the weight of one of them. - getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28088: the CFG gets only the blocks reachable from the entry, while instruction selection still covers the blocks that cmmToCmm makes unreachable when, after the Cmm pipeline has removed the unreachable blocks, it turns a branch on a constant into a jump). Where the selector splits such a block in the CFG (addImmediateSuccessor), as X86's cmpxchg loop for an atomic and, or, xor or nand does, the compiler panics with "getSuccessorEdges: Block does not exist". This is reached on x86 and x86-64, at any optimisation level: cmmToCmm turns a branch on a literal into a jump under every flag, and the literal comes at -O0 from cmmToCmm's own constant folding and at -O from sinking's. For x86-64 this rests on master's code read and on runs of master's compiler under -dcmm-lint. A procedure whose if (1 != 0) leaves a block with a fetch-and-and unreachable panics with that message at -O0 and at -O, and also at both with -finfo-table-map added, under which no CFG is kept after instruction selection. Where the branch tests a local set to 1 instead, the procedure panics at -O and compiles at -O0. For i386 it rests on runs of a compiler of master's code given an i386 target description through -B, with -dcmm-lint, where f (bits32 p) { bits32 r; if (1 != 0) { return (1); } (r) = prim %fetch_and32(p, 18::bits32); return (r); } panics with that message at -O0 and at -O, with -finfo-table-map too, and compiles where it tests p != 0 instead, and on master's code read: getCfgProc builds the CFG for every target the NCG compiles but wasm32; i386 runs the same selector (ncgX86 = ncgX86_64), and updateCfgNat forces each update, so addImmediateSuccessor's call of getSuccessorEdges panics during instruction selection whether or not a CFG is kept after it. It rests also on ISSUE 28088's record. - parseWeights in GHC.CmmToAsm.CFG.Weight (BUG, ISSUE 28222 section 1.2: a setting without "=" or of an unknown name panics, and a value is read lazily). -fblock-layout-weights=1 then makes the compiler panic, "Invalid CFG weight parameters." followed by the example parameters, and foo=1 "foo is not a CFG weight parameter.", each with the request for a bug report, where the flag's HasArg in GHC.Driver.Session could report a usage error; a non-numeric value, uncondWeight=x, is accepted where the compilation uses no weight it sets and otherwise makes the compiler panic later, "Prelude.read: no parse". This is a failed compilation reported as a panic, from the command line or an OPTIONS_GHC pragma, on any module, at -O0 and -O, under the native code generator; under -fllvm the value is not used. This rests on master's code read (parseWeights and its local assignment and update; the flag's entry in GHC.Driver.Session) and on a compiler of master's code on x86-64 and given an AArch64 target description through -B: on a module whose one function is f x = x + 1, -fblock-layout-weights=1 panicked so at -O0 on x86-64, and at -O0 and -O for AArch64, and foo=1 at -O0 on x86-64; uncondWeight=x compiled it at -O0 and -O, and uncondWeight=x,condBranchWeight=y panicked with no parse at -O0 and -O on a function with a conditional; with -fllvm, -fblock-layout-weights=1 compiled it; and in an OPTIONS_GHC pragma, the command line naming no such flag, -fblock-layout-weights=1 panicked so at -O0 and -O on x86-64. - Note [Layout relevant edge weights] in GHC.CmmToAsm.BlockLayout (BUG TODO, ISSUE 27799: where buildChains skips one edge of a conditional branch because it would close a cycle, as it can skip a loop latch's back edge, not fusing the branch's other edge leaves an unconditional jump as well, and the modifier on the edges of a conditional branch then under-prices that other edge). An unconditional edge of nearly equal weight from another predecessor can be fused with the target first. Where the latch's CmmCondBranch has the exit as its true target, the loop then ends in a conditional jump to the exit and an unconditional one back, one jump more on every iteration, as in the issue's program; where it has the body, the loop ends in a conditional jump back and an unconditional one to the exit, which runs once, as the loop exits. This costs only speed, on x86 and x86-64 under -fblock-layout-cfg, not under -finfo-table-map. This rests on master's code read (directEdges' relevantWeight in sequenceChain), on ISSUE 27799's record and on a run of master's compiler at -O2 on the issue's program: under -fobject-determinism its latch ends in jge and jmp, and without it in jl alone; and on runs of master's compiler at -O1 on a Cmm loop of each form, whose latch ends in jae to the exit and jmp, or in jb to the body and jmp. Two TODOs for ISSUE 28170, at livenessCfg in cmmNativeGen and at ncgEnableDeadCodeElimination in initNCGConfig, say that since 55a6377a5d, a workaround for ISSUE 20428, -finfo-table-map turns dead code elimination off, and with it, from the liveness pass on, every use of the CFG that can change the code. No CFG is then kept after register allocation, so the layout has neither static prediction nor the chains of -fblock-layout-cfg, and lays the blocks out without weights. Note [CFG Edge Weights] now says what -fcmm-static-pred changes: that under it, where the CFG is kept (x86 and x86-64, not under -finfo-table-map), the weights become estimated frequencies before the layout uses them. At getCfg's case for a switch, master's comment says that the weight -1 given to every target of a switch with more than ten entries (its case values and its default), a compiler performance hack, keeps the layout from considering them. A TODO there now says that, where the CFG is kept, the layout considers them nonetheless under -fblock-layout-cfg, and under -fcmm-static-pred where they go to at most two blocks, both flags on at -O1 and -O2, and that what the hack saves has not been measured. Other TODOs say: - at the Ord instance of CfgEdge, that edges of equal weight are ordered by their labels, which carry no meaning for the layout; - at allEdges' relevantWeight in sequenceChain, that it differs from directEdges'; - at dropJumps, that a block that only jumps to the next one is left as an empty label and a jump over it is kept. In X86's genCondBranch', a comment says that the 3 added to the weight of a floating-point comparison's false edge breaks layout ties toward the false target. Assisted-by: Claude Opus 5.5 - - - - - 48101c27 by Mikolaj Konarski at 2026-11-29T17:57:57+01:00 Document bugs and TODOs in static branch prediction and loop analysis Of what anyone working with the NCG needs, this commit serves "The paper or earlier design each part of the NCG is based on, where there is one, and which code is no longer used and since which change.", "Which designs were tried and given up, and the measurement or the bug that decided each.", "Where the code does something other than what reading it suggests.", "Where the code is known to behave wrongly or is half done.", "What each known bug leads to, such as wrong code, a compiler panic or only slower code, and under which flags and on which targets it is reached.", "Each known bug's tracker issue, named at the code it concerns." and "Where the code is likely to change, and how." Comments only; the generated code is the same. The statements carry the labels of Note [Labels in NCG comments]: BUG for wrong behaviour, BUG TODO for a bug that is also likely to change, WIP for half-done work, TODO for what is likely to change, none for what is meant to stay. What each BUG leads to, where it is reached and what that rests on: - getCfg in GHC.CmmToAsm.CFG (BUG, ISSUE 28222 section 2.5: after fixStgRegisters, a test of any global register with no machine register on the target, CurrentTSO or CurrentNursery among them, reads BaseReg and is tagged HeapStackCheck, as is any test that reads BaseReg itself). 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 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. This rests on master's code read. The tag decides the code only through isHeapOrStackCheck, all of whose callers are in staticBranchPrediction, which runs inside mkGlobalWeights. mkGlobalWeights reaches the code through staticPredCfg, only under -fcmm-static-pred, and otherwise only through the graph allocator's spill costs, on whose frequencies no spill choice depends. optimizeCFG, which calls staticPredCfg, runs only where the CFG is kept, and so not under -finfo-table-map. - Note [Back edges in loopInfo], added to GHC.CmmToAsm.CFG, its BUG citing ISSUE 28083 (an edge into the entry block is never a back edge, as mkDomMap leaves the root out of every dominator set). A loop whose head is the entry block is not found. This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. This rests on master's code read and ISSUE 28083's record. loopInfo's result reaches the code only through static prediction and block layout: of its two callers, loopLevels is never called, and mkGlobalWeights serves staticPredCfg, under -fcmm-static-pred, and otherwise only the graph allocator's spill costs, on whose frequencies no spill choice depends. - Note [Back edges in loopInfo] in GHC.CmmToAsm.CFG, its BUG citing ISSUE 28093 (a self loop is a back edge only where its block dominates no other block). A block that jumps to itself and to an exit it dominates, as cmpxchg_code's retry loop in GHC.CmmToAsm.X86.CodeGen does where the linear allocator puts no fixup block on its retry edge, is not a loop. calcFreqs then counts the block as irreducible and, unless the block heads a loop that loopInfo finds, gives it frequency 0, and so 0 to the edges out of it. This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map, by the same path as the BUG of ISSUE 28083. For static prediction, loopInfo runs on the CFG after register allocation, so a fixup block that the linear allocator puts on the retry edge makes the retry loop a cycle of two blocks, which loopInfo finds. This rests on master's code read, on the record of ISSUE 28093, and on -ddump-cfg-weights by the compiler of master 37ad471050: of MR 16269's test T28093.cmm, a self loop whose block dominates the exit, which weighs the self edge and the exit edge 0, and of a loop calling fetchOrIntArray#, which weighs the retry block's edges and the loop's back edge 0; and on -ddump-cfg-weights at -O by a compiler of master's code, of .cmm procedures: for x86-64, of one applying %fetch_or64, whose retry block keeps its self loop, both of its edges weighing 0, and of the same with fourteen locals live across the operation, whose retry edge gets a fixup block, the exit edge weighing 1; given an i386 target description through -B, of one applying %fetch_or32, whose retry edge gets a fixup block, the exit edge weighing 1, and which under -fregs-graph keeps its self loop, both of its edges weighing 0; and, for i386, of a hand-written self loop whose block dominates the exit, both of whose edges weigh 0, and 799 and 801 under -fno-cmm-static-pred. - Note [Static Branch Prediction] in GHC.CmmToAsm.CFG (BUG, ISSUE 28222 section 2.6: the back edge rule supersedes a likely annotation in the Cmm as well). A branch with both a back edge and another edge is predicted to take the back edge, whatever its annotation says, unless an edge of it is tagged HeapStackCheck (a heap or stack check). This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. This rests on master's code read: staticBranchPrediction's case for a mix of back edges and other edges tests no annotation. - ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG (BUG TODO, ISSUE 28222 section 2.7: a constructor-tag test is predicted like any other comparison). The prediction is wrong for the trees of Data.Map and Data.Set, which declare Bin first, where the test is left spelt as an equality, as in a client's copy of Data.Map's lookup specialised at Int keys: the side that stays in the loop is predicted unlikely. This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. It is accepted until the knowledge of the likely side reaches the CFG, hence TODO as well. This rests on master's code read and on a compiler of master's code at -O1 and -O2, which left an equality in a client's copy of lookup specialised at Int keys, and inverted the test in that client's copies of Data.Map's and Data.Set's member and in Data.Map.Internal's own lookup and member. - ohPredicts in staticBranchPrediction, GHC.CmmToAsm.CFG, its BUG, ISSUE 28222 section 2.8 (ohPredicts treats s1 as the true side only where it is ltrue, the label the branch was made with, which an edge no longer ends at once the linear allocator's fixup block, by addNodesBetween, the block that allocMoreStack moves the entry block's code to, by addPreentryBlock, or shortcutting, by shortcutWeightMap, has redirected it). Where the redirected true edge's new target has the smaller label of the two, each side gets the other's prediction. This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. This rests on master's code read, and on a compiler of master 37ad471050's code with a counter added, which found over nofib's modules 7 of the 4874 unannotated equality tests with a literal predicted inverted at -O2 and none of the 4401 at -O1. - calcFreqs in GHC.CmmToAsm.CFG (BUG, ISSUE 28222 section 2.9: mkGlobalWeights passes the loops in the order of loopInfo's back edges, descending by label, and not by nesting). An enclosing loop's pass can come before an inner loop's and use the branch probability of an inner back edge where its cycle probability belongs, which gives nested loops wrong cycle probabilities. This costs only speed, on x86 and x86-64 under -fcmm-static-pred, not under -finfo-table-map. This rests on master's code read and on -ddump-cfg-weights by a compiler of master's code at -O1 and -O2: of a .cmm procedure of a loop counting down to 0 nested in another, each loop testing its counter at its head and the outer one jumping out where an equality test of its counter with 0 holds, the outer loop's latch having the larger label, which weighs the outer back edge 448, and of the same nest with the inner loop's test inverted, giving the inner latch the larger label, which weighs the outer back edge 7. A WIP in Note [Static Branch Prediction] says that the paper's other heuristics are stubs. calcFreqs' comment on an irreducible block, "Rare we don't care", now says what frequency such a block keeps and, as a TODO, where such blocks arise and how few procedures of a sample hold one, that the layout then ranks edges by frequencies that do not add up, with a loop calling fetchOrIntArray#, compiled for x86-64 by the compiler of master 37ad471050, for a case, and that summing their inflow was tried on a development branch and kept there. In the CFGs that -ddump-cfg-weights gives as final, from a compiler of master's code, of containers at -O1 and of 49 nofib programs at -O2, 4 procedures of 11410 hold a block that at least 0.01 enters and nothing leaves, and a replication of calcFreqs' test takes those 4 blocks as irreducible and no other, none of them on a self loop: in compress2 and in scs, each on a cycle that is entered at two of its blocks and runs through a call's continuation. Of two Cmm procedures compiled by that compiler at -O1, one gives 0 to a block whose only loop is on itself, though 0.5 enters it, and the other gives 1 to the head of a loop that also loops on itself, though 0.00098 enters the loop, which 0.088 then leaves. Other TODOs say: - in Note [Back edges in loopInfo], that findBackEdges, which optHsPatterns uses for the back edge bonus, and loopInfo differ on edges into the entry block, on back edges of irreducible cycles and on a self loop only where its block dominates no other block; - at ohPredicts, that it matches only MO_Eq, so the spelling GHC.Cmm.ContFlowOpt leaves decides whether a test is predicted, and that predicting a pointer-tag test spelt with MO_Ne as its MO_Eq spelling is predicted was tried on a development branch and cost nofib 0.36% more instructions at -O2; - at lehPredicts, that where a heap or stack check's call to the garbage collector returns into the procedure, loopInfo counts the cycle through that call as a loop: lehPredicts then returns Nothing for a branch into the checking block where that block is the loop's head, and counts a branch towards a case alternative without such a check as a loop exit where the head is the block choosing the alternative; - at calcFreqs, that nothing checks its result, and that a check could compare each block's frequency with the sum of the frequencies on its in-edges, which the propagation departs from at some blocks, among them an irreducible block, a loop head whose cycle probability is capped, and the entry block; - at loopMembers, that neither it nor loopLevels has a caller in GHC: loopMembers since the graph allocator's spill costs, for which it was added early in 2019, began that year to weight by block frequencies instead, and loopLevels since it came with the loop analysis that year. A comment at optimizeCFG says that static prediction starts from the weights optHsPatterns leaves, so that their adjustments carry into the predicted probabilities, except where the back edge rule replaces them. Assisted-by: Claude Opus 5.5 - - - - - 71cadc0e by Mikolaj Konarski at 2026-11-29T17:57:57+01:00 Document bugs and TODOs in liveness and the register allocators Of what anyone working with the NCG needs, this commit serves "Which designs were tried and given up, and the measurement or the bug that decided each.", "The invariants the code depends on.", "Where the code does something other than what reading it suggests.", "Where the code is known to behave wrongly or is half done.", "What each known bug leads to, such as wrong code, a compiler panic or only slower code, and under which flags and on which targets it is reached.", "Each known bug's tracker issue, named at the code it concerns." and "Where the code is likely to change, and how." Comments only; the generated code is the same. The statements carry the labels of Note [Labels in NCG comments]. What each BUG leads to, where it is reached and what that rests on: - regAlloc in GHC.CmmToAsm.Reg.Graph (BUG, ISSUE 28214: once regSpill has grown the pool of slots, it returns slotsCount', the pool's highest slot number, which counts the preallocated slots and every slot of the pool, used or not, as the stack needed, and the driver passes it to ncgAllocMoreStack, where the linear allocator's regAlloc returns only the slots from maxSpillSlots on): the preallocated slots are reserved a second time, and with them the slots that no spill uses, as the pool starts with maxSpillSlots+1 slots and regSpill in GHC.CmmToAsm.Reg.Graph.Spill grows it 512 slots at a time when a round of spilling needs more than are free. This costs C stack space, under -fregs-graph or -fregs-iterative, on every target the NCG compiles but wasm32, and where a target's mkStackAllocInstr returns more instructions for a larger amount, code at entry and exit: on AArch64 one instruction more for each 4095 bytes, on RISC-V, LoongArch and PowerPC more past the range of an immediate, and on Windows x86-64 a call of ___chkstk_ms past 4 KB. This rests on master's code read and on a compile by a compiler of master's code, at -O0 on x86-64, of a procedure whose live locals took 2042 spill slots: under -fregs-graph its code reserved 2551 slots (subq $20416,%rsp), and under the linear allocator 32 bytes. The graph allocator can be chosen for any target the NCG compiles but wasm32, and trivColorable covers x86, x86-64, PowerPC, AArch64, RISC-V and LoongArch. - regAlloc_spin in GHC.CmmToAsm.Reg.Graph, its branch for a round that spills (BUG, ISSUE 28222 section 5.2: nothing evaluates the graph it validates under -dasm-lint, which goes only into the lazy raGraph field of a RegAllocStatsSpill, while only a RegAllocStatsStart's raGraph is ever accessed). So -dasm-lint validates no graph of a round that spills, only that of the round that colours every node, and checks less than it appears to. The code is the same: this only misleads a reader, under -fregs-graph or -fregs-iterative, on every target the NCG compiles but wasm32. This rests on master's code read (the accesses to raGraph in GHC.CmmToAsm.Reg.Graph.Stats and GHC.CmmToAsm, all of a RegAllocStatsStart, raGraph being a lazy field) and on a program built against the ghc package of a compiler of master's code, which passed a RegAllocStatsSpill whose raGraph is an error through the printing of -ddump-asm-regalloc-stages and -ddump-asm-stats without forcing it. The stages dump's printing of that graph, which forced the check, was commented out and then deleted in e174477111 (2010). - buildGraph in GHC.CmmToAsm.Reg.Graph (BUG, ISSUE 28222 section 2.11: slurpConflicts returns the set of registers live after each instruction, and graphAddConflictSet adds each set whole). addConflicts in GHC.Data.Graph.Ops unions the whole set into the conflict set of each member, so for N values live together over some N instructions building the graph makes on the order of N^3 set insertions, for a graph of N^2/2 edges; regAlloc_spin builds the graph afresh in each round, under -fregs-iterative as under -fregs-graph. This costs compile time and memory, up to a compilation that runs out of memory, under -fregs-graph and -fregs-iterative, from Haskell at -O1 and from Cmm at -O0, on every target the graph allocators serve; at -O1 Cmm sinking moves a load to its single use, which keeps such values from being live together. This rests on master's code read (slurpConflicts, buildGraph, graphAddConflictSet, addConflicts, regAlloc_spin) and on a compiler of master's code on x86-64. A Haskell function that reads 1000 Ints from a MutableByteArray# and returns the sum of their squares, each value used twice so that sinking leaves it in place, took at -O1 -c 70 s and 2.0 GB under -fregs-graph and under -fregs-iterative alike, and 1.5 s and 170 MB under the linear allocator; with 2100 Ints it ran out of memory under -fregs-graph within an 8 GB address-space limit. A .cmm procedure that loads 2100 words into locals and then sums them took at -O0 -S 8 minutes and 5.3 GB under -fregs-graph, against 0.14 s and 105 MB under the linear allocator. - pprSpillCostRecord in GHC.CmmToAsm.Reg.Graph.SpillCost (BUG, ISSUE 28222 section 5.3: it binds a SpillCostRecord as (reg, uses, defs, life), where the type's comments give its fields as the writes, the reads and the lifetime). Only the names are wrong: it prints the two counts in the record's order, under no names, and their sum divided by the register's node degree, and nothing in GHC calls it. This rests on master's code read: slurpSpillCostInfo's incDefs fills the second field and incUses the third. - regAlloc in GHC.CmmToAsm.Reg.Linear, at extra_stack (BUG, ISSUE 28222 section 1.6: stack_use counts the slots used, while the C stack area that the RTS reserves holds slots 0 to maxSpillSlots): at maxSpillSlots+1 slots regAlloc returns 1 as the extra stack needed, where none is, and beyond that one slot more than is needed. This costs C stack space, 16 bytes at most, as each target's allocMoreStack rounds the amount up to a multiple of 16 bytes, and at maxSpillSlots+1 slots the blocks and stack adjustments that ncgAllocMoreStack adds at entry and exit, under the linear allocator, on every target the NCG compiles but wasm32. On i386 and x86-64 under -falignment-sanitisation those adjustments make the compiler panic, "insert_dealloc: cannot handle JXX_GBL", a failed compilation, where the procedure holds the conditional jump to the bad-alignment label that addAlignmentCheck in GHC.CmmToAsm.X86.CodeGen adds, a JXX_GBL, of which insert_dealloc in X86's allocMoreStack has no case. This rests on master's code read: getStackUse returns the stack map's next free slot, counted from 0 (emptyStackMap); each target's maxSpillSlots is the number of slots the area holds less 1, and its spillSlotToOffset puts slot maxSpillSlots inside the area; and cmmNativeGen gives the graph allocator the free slots 0 to maxSpillSlots; and on a compiler of master's code on x86-64, which at -O0 under -falignment-sanitisation panicked so on a Haskell function of 2040 spill slots, maxSpillSlots+1 there, and compiled one of 2039, and without the flag gave the first two subq $16,%rsp and the second none. - saveClobberedTemps in GHC.CmmToAsm.Reg.Linear (BUG TODO, ISSUE 26631: my_reg is the first free register of the class that the instruction does not clobber, chosen without regard to what the instructions before the value's next read do to it). Where they write it too, as the moves of a C call's arguments into their registers do, the value is moved from register to register, and where the call clobbers every register of the value's class, as on x86-64 a C call clobbers every floating-point register except on Windows, the call then spills it all the same. This costs only speed, under the linear allocator, on every target the NCG compiles but wasm32. This rests on master's code read, on ISSUE 26631's record and on a run of master's compiler at -O on x86-64 of f x y z = c_hypot z x + y * z on Doubles, f marked NOINLINE and c_hypot an unsafe foreign import of hypot, which moved z from xmm3 to xmm0 to xmm4 and then spilled it before the call of hypot. - joinToTargets in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG, ISSUE 28222 section 2.12: on x86 and x86-64 a floating-point == or /= test's block ends in three jumps, two of which name one target, genCondBranch's parity jump and a conditional or unconditional one, and each is joined on its own). Where that target needs a fixup block, each of the two jumps gets one, with the same moves, and both are reachable, while only one can fall into the target. This costs only speed and code size, on x86 and x86-64 under the linear allocator: where one of the two falls into the target, the path through the other ends in a jump to it. Under -fblock-layout-cfg, on by default at -O and -O2, the edges into the two weigh the same, and sequenceChain in GHC.CmmToAsm.BlockLayout hands buildChains edges of one weight in the descending order of CfgEdge's Ord, by label; in the runs below, this lets the twin of the second of the two jumps fall into the target, so that a /= test whose true target needs the blocks ends in a jump to the target on the path taken when the operands are ordered and differ, and an == test whose false target needs them on the path taken when an operand is NaN. Without -fblock-layout-cfg, at -O0 or under -fno-block-layout-cfg, the block has three successors, and mkNode in GHC.CmmToAsm.BlockLayout gives no preferred successor to a block with more than two successors in the CFG, so the block's false target can be placed away from it and reached by a jump. This rests on master's code read and on constructed Cmm compiled by a compiler of master's code for x86-64 and, given an i386 target description through -B, for i386: at -O and at -O2, a /= test whose true target needs the blocks ends in jne and jp, the jne's twin ending in a jump to the target, where a > test's one fixup block falls into it, and an == test whose false target needs them falls through its unconditional jump's twin into the target, its parity jump's twin ending in a jump to it; under -fno-block-layout-cfg, at -O, the /= test also ends in a jump to its false target, which the > test falls into. No module of the compile benchmarks, compiled by master's compiler, was found to show it. A fix that shares the block where the two jumps' stack deltas agree, the target's vregs have the same locations at both and no value moves between two slots was written on a development branch and is left out. - Note [The first jump into a block fixes its entry assignment], added to GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG TODO, ISSUE 27800: a return continuation is an entry block, and the allocator, going in SCC order, processes one that jumps into a loop from outside it before that loop). Where the procedure's entry and such a continuation enter one loop at two different blocks, the two can record incompatible assignments, and the loop's own edges then get fixup code that runs on every iteration. This costs only speed, under the linear allocator, on every target the NCG compiles but wasm32. MR 16673 proposes a fix. This rests on master's code read and on ISSUE 27800's record, whose Cmm procedure gets two fixup blocks inside its loop on x86-64. - joinToTargets_first in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG TODO, ISSUE 27981: to_free holds only registers that hold virtual registers, so a real register still allocated at the jump, such as R1 on x86-64 where it is read after a conditional branch, stays allocated in the free registers recorded for the block, even when it is not live into it). The block's code then cannot use that register, and a jump from it into a block whose entry assignment holds a value there gets fixup moves, which on a loop's back edge run on every iteration. This costs only speed, under the linear allocator, where an STG register's machine register is handed out between its uses: x86-64, PowerPC and, for XMM1 to XMM4, i386. This rests on master's code read, on ISSUE 27981's record and on a run of master's compiler at -O on the issue's program on x86-64, in which a loop's return continuation falls into a fixup block of two moves before the loop head on every iteration. - 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, ISSUE 28215, a statement of its own, ISSUE 27638 reporting only the panic), the destination's slot is written only if it is the slot spillR picks; otherwise it can keep a stale value, which is wrong code where the slot is reloaded. Both can be reached only under the linear allocator, where a virtual register's format grows past 8 bytes, which only a vector format does, and so only on i386, x86-64 and AArch64, the targets whose regUsageOfInstr can give a register a vector format: those of PowerPC, RV64 and LA64 give every register the format of its class, of 8 bytes at most (regFormat in their Instr modules), and RV64's and LA64's stop with sorry on a vector register. The first is reached on x86-64 at -O0, -O1 and -O2: master's compiler panics so at all three on a function in which a Double# is passed to an unsafe foreign call of type Double# -> Double#, then broadcast to a DoubleX2# whose lane goes to a second such call in one arm of a case whose other arm returns the first call's result, and used again after the case, whose result a strict let binds. The second is reached on x86-64 at -O1 and -O2: a compiler of master's code gave wrong code at both for a function that binds x to the product of two Double# arguments and, in one arm of a case, passes a lane of x broadcast to a DoubleX2#, and in the other a sine, to a join point that adds x to the sine of its argument; its program printed sin 30 + 0 where sin 30 + 30 was due, and sin 30 + 30 at -O0. 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, a run of master's compiler and a compiler of master's code given 64-bit PowerPC ELFv2 and ELFv1, RISC-V and LoongArch target descriptions through -B: at -O a function adding two DoubleX2# arguments went through PowerPC's register allocator, as -ddump-asm-regalloc shows, to a panic in pprInstr on a VecFormat load, and stopped on a W128 load in RV64's and LA64's getRegister, and a broadcast or a pack gave the sorry of checkVecCompatibility. 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. - handleComponent and makeMove in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG, ISSUE 28222 sections 5.4 and 5.5: handleComponent's cyclic case spills the first move's source at the source's format and reloads it at the destination's, and makeMove loads from a slot at the destination's format too). Where the destination's format is a vector one and the slot was written at a narrower one, the load reads past what was written, into the bytes after the slot, which can be another virtual register's slot, against Note [Use spilled format when reloading] in GHC.CmmToAsm.Reg.Linear, which says that a register is reloaded at the format it was spilled at. That is wrong code where a value is computed from a lane so loaded; no program is known to compute one. The formats differ so where X86's broadcast of a Double# or a Float# writes the scalar's own register at the vector's format on the path of the first jump into a block, which fixes the block's entry assignment (Note [The first jump into a block fixes its entry assignment]), and another jump into the block holds the scalar at its own format, in a register in a cycle of moves or in its slot. That is reached on x86-64 and i386 at -O0, -O1 and -O2. This rests on master's code read (spillR, whose slot getStackSlotFor sizes by the format given, and loadR; expandNode and makeRegMovementGraph, which keep each end's format; makeMove's case for a move from a slot to a register; vector_float_broadcast_sse and vector_float_broadcast_avx in GHC.CmmToAsm.X86.CodeGen, which take their operand's register from getSomeReg and write it) and on a compiler of master's code. On x86-64, for a function in which a Double# x, passed to a C call, is broadcast to a DoubleX2# in one arm of a case and read as a Double# by a join point both arms jump to, the cyclic case's fixup block spilled x with movsd and reloaded it with movupd at -O1 under -msse4.2 and with no -m flag and at -O2 -msse4.2, and with vmovupd at -O1 -mavx, the upper lane coming from the next slot, which the same block had just written with another variable's value; with a Float# broadcast to a FloatX4# it reloaded with movups, and with a DoubleX4# under -mavx2 with vmovupd into a ymm register. In a variant whose other arm does not read x, which then stays in its slot at that arm's jump, makeMove's load of x was movupd too, at -O0, -O1 and -O2, on x86-64 and on i386. Both programs gave at -O1 the results they gave at -O0. In variants in which a DoubleX2#, FloatX4# or Int64X2# variable or a broadcast scalar enters such a join point, at -O0 and -O1 under -msse4.2 and at -O2 -mavx2, no block both spilled a slot and reloaded it wider. Given an AArch64 target description through -B, at -O1, the first function's broadcast wrote a register of its own, and its cyclic fixup spilled and reloaded at 8 bytes. - expandNode in GHC.CmmToAsm.Reg.Linear.JoinToTargets (BUG TODO, ISSUE 28222 section 2.13: where the destination is InBoth with the source's slot, as when a virtual register is InBoth at both ends of the jump, it stores the value into a slot that already holds it). This costs only speed and code size, under the linear allocator, on every target the NCG compiles but wasm32. This rests on master's code read: the case of an InBoth source drops the source's slot and expands the node as from an InReg source, whose cases for an InBoth destination keep the store to its slot. - livenessSCCs in GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 27619: Regs' Eq compares the registers and not their formats, so the fixpoint can stop before the formats recorded for a cycle's blocks converge): a vector register can be recorded live at a format narrower than the value it holds, and a write at that format then kills it in minusCoveredRegs, which is wrong code where a later instruction reads a part of the register that the write leaves alone. On x86 such a write is one that regUsageOfInstr declares written, not modified, and that keeps the rest of the register, as a MOV between registers at FF32 or FF64 (movss, movsd) does. No program is known to give a wrong result: the insert of a Double# into lane 0 of a DoubleX2#, a MOV between registers at the vector's format, is declared read and modified, and so leaves the register live. ISSUE 27619's record gives the consequence as spills and reloads narrower than the value; the formats so recorded set no spill or reload width. The linear allocator spills and reloads at the format of a variable's Loc, which comes from an instruction's operand: a write's, for a reload the spill's, or, for a move from a real register that raInsn eliminates, the move's read in liveDieRead, which at an instruction that is not a branch holds the instruction's own reads; the graph allocator spills and reloads at the formats regUsageOfInstr gives the instruction's operands. This rests on master's code read, on ISSUE 27619's record, whose program shows a register recorded so, and on a compiler of master's code: a variant of that program with an unsafe C call in its loop, whose counter rises so that it ends, compiled at -O -fno-cse, records the DoubleX2# at FF64 on entry to the loop's head, and it is spilled and reloaded at 16 bytes, by movupd or, under -mavx, vmovupd, under both allocators, the graph allocator also reloading 8 bytes for the instructions that read lane 0 alone; the program gives the result it gives at -O0. - getSlotMap in slurpReloadCoalesce, GHC.CmmToAsm.Reg.Liveness (BUG, ISSUE 28222 section 5.6: 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 the NCG compiles but wasm32. This rests on master's code read; buildGraph in GHC.CmmToAsm.Reg.Graph is the only caller of slurpReloadCoalesce. - maxRegWithFormat in GHC.CmmToAsm.Reg.Regs (BUG, ISSUE 27619: Format's derived Ord compares a VecFormat's number of elements before their format, ranking VecFormat 16 FmtInt8, 128 bits, above VecFormat 4 FmtDouble, 256 bits): it can keep the narrower of two formats. Were one register read at both, a write at the narrower would kill it in minusCoveredRegs, which is wrong code where a later instruction reads a part of the register that the write leaves alone; whether any register is read so is not known. This rests on master's code read and ISSUE 27619's record. The haddocks of minusCoveredRegs and shrinkingRegs, which compare formats by the same Ord, point to it. The other statements, by part. The linear allocator: - Note [The first jump into a block fixes its entry assignment], in GHC.CmmToAsm.Reg.Linear.JoinToTargets, says that the first jump into a block that the allocator processes records the block's entry assignment, spilled values included, and that every later jump conforms to it by fixup code. Its two TODOs, and its BUG TODO for ISSUE 27800 above, are what follows from that: a loop head recorded from a preheader that spilled a loop-carried value has the value reloaded on every iteration, and stored again by every back edge once the body has written it; and the block that a failed heap or stack check returns to from the garbage collector can be allocated before the hot path's jump into the checking block and record that block's entry assignment, as the order of allocation depends on no frequency. process' comment cites the Note. - Note [Unique order in the linear allocator], added to GHC.CmmToAsm.Reg.Linear, first lists the tags that the vregs' uniques carry, in their order, and says which of them -fobject-determinism renames. It then says, as a TODO, which decisions take the order of the vregs' uniques as a ranking: the spill victim, and the order in which saveClobberedTemps moves values out of clobbered registers. It also says that the order decides, of joinToTargets' fixup moves, the order of those that their dependencies leave free and which move of a cycle goes through the stack. The comments at those three folds cite it. - Issues get labels where the code behaves as they report: BUG TODO for ISSUE 26631, ISSUE 27800 and ISSUE 27981 above, and BUG for ISSUE 27638 at handleComponent, makeMove, makeRegMovementGraph and StackMap's header, whose comments ruled out a move between two stack slots, which ISSUE 26668 made possible. - TODOs without an issue: raInsn's elimination of a move gives the destination the source's register, whatever register an entry assignment recorded for a block it is live into; and findPrefRealReg's preference is keyed by virtual register, while a Cmm local is one virtual register over all its live ranges. - The header of GHC.CmmToAsm.Reg.Linear.StackMap says that a stack slot belongs to one virtual register for the whole procedure, as getStackSlotFor takes new slots only at the next free one, which only grows, and a register that outgrows its slot gets another, keeping the first; that the fixups at a jump rely on this; and that it costs stack, the slots of a procedure adding up over every register spilled in it. - Step (j) of the outline at the top of GHC.CmmToAsm.Reg.Linear, re-adding a dead spilled register's stack slot to the free list, is marked WIP: it is not done, as a StackMap never frees a slot. - A comment at clobberRegs' filter says that on AArch64, RISC-V and LoongArch frAllocateReg panics on a register that is not free. - Three designs tried on a development branch are recorded, with what each trial measured, beside the code they would change: handing out the floating-point registers in descending order (at the BUG TODO for ISSUE 26631 in saveClobberedTemps), taking the entry block first and then, after each SCC, an SCC holding a block whose entry assignment is recorded, a cyclic one first (at the BUG TODO for ISSUE 27800), and putting fixup moves before an unconditional jump rather than in a block of their own (in joinToTargets_again). Liveness, in GHC.CmmToAsm.Reg.Liveness and GHC.CmmToAsm.Reg.Regs: - The comment at the fixpoint of livenessSCCs says that its test compares the whole map, where only the SCC's blocks can change (TODO, ISSUE 27437), and that its steps are monotone, so that a test comparing the formats too would reach a result independent of the order in which the blocks are walked. The comment at Regs' Eq says that Eq ignores formats and that ISSUE 27619 proposes one that compares them (TODO, ISSUE 27619), and points to the BUG at livenessSCCs for what ignoring them leads to. - The comment on the SCCs' order says that no block may fall through, and liveDieRead's haddock that at a branch it also holds the registers live into its targets only. - A comment at computeLiveness' panic on SCCs out of reverse dependent order says that, where sccBlocks has a CFG, a jump to a block missing from the CFG reaches it too. The graph allocator: in GHC.CmmToAsm.Reg.Graph.SpillCost, a WIP comment says that the block frequencies scale only the counts of uses and definitions, on which no spill choice depends, as spillCost_chaitin, which would use them, is commented out. Both allocators: a TODO at patchRegsOfInstr says that, as it maps a register to a register, both allocators reload a spilled value into a register for an instruction that reads it, even at its last read, where an x86 instruction could read the stack slot. Assisted-by: Claude Opus 5.5 - - - - - 888cde02 by Mikolaj Konarski at 2026-11-29T17:57:57+01:00 Document bugs and TODOs in code generators, DWARF and an unused module Of what anyone working with the NCG needs, this commit serves "The paper or earlier design each part of the NCG is based on, where there is one, and which code is no longer used and since which change.", "Where the code is known to behave wrongly or is half done.", "What each known bug leads to, such as wrong code, a compiler panic or only slower code, and under which flags and on which targets it is reached.", "Each known bug's tracker issue, named at the code it concerns.", "Where the code is likely to change, and how." and "What the NCG leaves to the assembler and the linker: which operand ranges a code generator checks and which only the assembler rejects, which branches the NCG lengthens, and which assemblers its output is written for." Comments only; the generated code is the same. The statements carry the labels of Note [Labels in NCG comments]. What each BUG leads to, where it is reached and what that rests on: - getRegister' in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28126: isNbitEncodeable 12 admits label offsets from -2048 to 2047, while check_off in GHC.CmmToAsm.AArch64.Ppr accepts only 0 to 4095): on AArch64, compiling a label at an offset from -2048 to -1 stops with check_off's error, a pgmError, "GHC.CmmToAsm.AArch64.Ppr.check_off : -8 is out of 12 bit" for an offset of -8. Below -2048 the guard fails, and the next clause adds the offset through a register. This rests on master's code read (litToImm', ImmIndex, check_off), ISSUE 28126's record and a run of master's x86-64 compiler given an AArch64 target description, in which a Cmm load from a label less 8, at -O0 and at -O, and plusAddr# of a string literal and -1#, at -O, stop with check_off's error; nothing was run on AArch64. - genCondJump in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28222 section 2.19: no case there tests its operands' type, and Cmm lint checks a MachOp's operands by width alone). A hand-written Cmm integer comparison of two float64 or float32 values, as %lt(x, y) rather than %flt, then reaches the integer cases, wrong code or a failed compilation on AArch64 at -O0 and -O. In icond a CMP of two floating-point registers prints as fcmp and is read by the integer condition, so, as read from the instructions, %lt(x, y), %le(x, y), x >= y and x > y, branching on lt, le, hs and hi, are true for an unordered pair, where MO_F_Lt and its siblings test OLT, OLE, OGE and OGT; the value form, through the comparison cases of getRegister', is the same. Against 0 the CBZ and CBNZ cases emit cbz or cbnz on the floating-point register, and for MO_Eq, MO_Ne and MO_S_* signExtendRegister gives a literal an integer register, so that x != 1.0 emits an fmov of 1.0 into an x register, each of which GNU as rejects; it gives a load one too, so that float64[p] != float64[q] compares the loaded bits by cmp. No Haskell program reaches it, StgToCmm emitting MO_F_Eq and its siblings for floating-point operands. This rests on master's code read (genCondJump, icond, signExtendRegister, lintCmmExpr and machOpArgReps in GHC.Cmm.Lint) and on a compiler of master's code given an AArch64 target description through -B, nothing run on AArch64: under -dcmm-lint at -O, the -O0 output differing by copies alone, it printed fcmp d12, d13 and b.lt for if (%lt(x, y)) on float64 arguments, b.le, b.hs and b.hi for %le, >= and >, and fcmp s8, s9 and b.lt on float32 ones; cbnz d12 for x != 0 and cbz d12 for x == 0; fmov x18, #1.0 and cmp d12, x18 for x != 1.0, which GNU as 2.42 rejected, as it did the cbz and cbnz; and cmp x18, x17 for float64[p] != float64[q]. - 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 (ISSUE 28222 sections 3.4 and 3.1 for wasm32 and LA64, ISSUE 28133 for RV64: the sum is not truncated to a sub-word register's width, as each target's general lowering of a sub-word MO_Add truncates its result, and cmmMachOpFoldM in GHC.Cmm.Opt folds a sub-word register plus or minus a literal into a CmmRegOff at any width validOffsetRep allows). Where an operation reads the bits above the width, this is wrong code: on wasm32 a widening MO_UU_Conv of a sub-word value masks nothing, and on RV64 Note [Signed arithmetic on RISCV64] keeps a sub-word value zero-extended between operations. On LA64 the first case breaks the same invariant, stated under "Signed arithmetic on LoongArch64", harmlessly, each reader of a sub-word register there that the printer accepts extending or masking it first, or reading its low bits alone; but MO_Add's case for a literal of 12 bits, at 8 and 16 bits, sign-extends its operand in the operand's own register, and where that operand is also the first operand of an unsigned comparison in genCondJump, whose ubcond zero-extends that register ahead of the second operand's code, the extension undoes the zero extension and the branch compares the sign-extended value. This is wrong code on LoongArch, from Haskell at -O and -O2, where sinking puts the sum into the comparison: the code for x < x + 5 on a Word8 gives False for x from 128 to 250, and on a Word16 for x from 32768 to 65530. At -O -fno-cmm-sink the comparison goes through getRegister''s case for MO_U_Lt, which extends after both operands' code, and at -O0 through Word8's Ord and Num methods, and both are right. Most other cases of an operation of 8 or 16 bits extend or mask its operand in place too, among them those of the shifts, of MO_And, MO_Or and MO_Xor and of MO_Mul, MO_S_Quot, MO_S_Rem, MO_U_Quot and MO_U_Rem, all but the shifts' at 32 bits too: a zero extension there undoes the sign extension that genCondJump's sbcond makes for a signed comparison, and a sign extension the zero extension of ubcond. Haskell reaches each of those named at -O and -O2, where sinking puts the operation into the comparison and its operand is the comparison's first operand: the code for x < x * 3 gives False on a Word8 for x from 129 to 170, on a Word16 from 32769 to 43690 and on a Word32 from 2147483649 to 2863311530; and the primops on sub-word values reach the shifts and the logical operations, as in ltInt8# of x and of x masked with 127 by andWord8#, whose code gives False for x from -128 to -1. The methods of Bits tried on Word8 and Int8 shift or mask a conversion of the operand into a register of its own, and their code is right. LA64's second case is, for a register of 8 or 16 bits, a compiler panic, "LA64.ppr: ADD error": its ADD of two registers at the register's width is one that GHC.CmmToAsm.LA64.Ppr prints at 32 and 64 bits alone. An 8-bit register reaches it where the folds add literals one at a time to a CmmRegOff, summing the offsets unnarrowed. This rests on master's code read, ISSUE 28133's record and runs of a compiler of master's code given RISC-V and LoongArch target descriptions through -B, on Cmm with -dcmm-lint: a bits8 local plus 1, compared with 0 at -O -fno-cmm-sink, under which the NCG folds nothing into a CmmRegOff, became on RV64 an add with no truncation before the comparison; a bits16 local plus 5000, and a bits8 local plus 100 added 21 times in one expression, each local also stored, at -O0 and at -O, were returned through %zx64 with no truncation on RV64 and made the compiler panic so on LA64; and on LA64 a bits8 local plus 1 was extended or masked wherever it was shifted, multiplied, negated, divided, compared, switched on, converted or passed to a C call. On LA64, for a Haskell function f x = if x < x + 5 then 1 else 0 on Word8, at -O and -O2, it printed bstrpick.d $a0,$a0,7,0, ext.w.b $a0,$a0, addi.d $a1,$a0,5, bstrpick.d $a1,$a1,7,0 and bgeu $a0,$a1, the branch taken to return 0, and likewise ext.w.h and bstrpick.d to 15 bits on Word16 and addi.d $a1,$a0,-5 for x - 5; for x < x * 3 on Word8, at -O and -O2, it printed bstrpick.d $a0,$a0,7,0 and ext.w.b $a0,$a0 before mul.d $a1,$a0,$a1 and bgeu $a0,$a1, and the instructions from each such function's entry to its branch, run in a simulator over every 8- and 16-bit input and over a sample of 32-bit ones, were wrong at those inputs alone, and at -O -fno-cmm-sink, on Word8 and Int8, at none; on Cmm with -dcmm-lint, at -O0 and -O, x < x + 5::bits8 on a bits8 x gave the same sequence before a bltu, and %lt(x, x >> 1), %lt(x, x & 0x7f::bits8) and %ltu(x, x << 1) gave an extension of x in place between the comparison's own extension of x and the branch, as did %lt(x, x & 0x7f::bits32) on a bits32 x, at -O. Nothing was run on these targets, and nothing was compiled for wasm32. On RV64 and LA64 an offset that fits in 12 bits goes to the case of MO_Add for such a literal, or on RV64 for an offset from -2047 to -1 to that of MO_Sub, which does not truncate either; on RV64 an offset of -2048 goes to MO_Sub's general case, which truncates. RV64's BUG cites ISSUE 28133, which reports the cases of MO_Add, MO_Sub and MO_Or for a register and a 12-bit literal, the first two of which RV64's first case reaches; its other case has no issue. - makeFarBranches in GHC.CmmToAsm.AArch64.CodeGen (BUG, ISSUE 28213: instr_pos counts an LDR of a label as one instruction, where it prints as two, or three with an offset, and the meta instructions DELTA, PUSH_STACK_FRAME, POP_STACK_FRAME and, in a DEBUG compiler, MULTILINE_COMMENT as one each, where replace_jump counts them as none). The estimate of a branch's distance can fall short, that of a backward branch by at least one for each of these meta instructions before its target, and a conditional branch beyond its reach is then left as it is, on AArch64. LLVM's assembler (clang 18) and GNU as 2.42 reject such a module. This rests on master's code read (instr_pos, replace_jump, isMetaInstr, and the printing of LDR in GHC.CmmToAsm.AArch64.Ppr) and on a compiler of master's code given an AArch64 target description through -B: of a Cmm procedure that branches over 42000 stores of a label plus an offset to addresses 8 bytes apart, it printed at -O0 a cbz whose target lay past its reach of 1 MiB, which LLVM's assembler rejected ("fixup value out of range"), as GNU as did ("conditional branch out of range"); with 70000 stores the estimate passed the threshold and the branch was rewritten. Of a procedure f (W_ x, W_ p) of 2000 C calls, each with a PUSH_STACK_FRAME, printed as two instructions, a POP_STACK_FRAME and two DELTA, then a loop of 263000 stores W_[p] = x, printed as one str each, that tests x != 0 and leaves x unchanged, it printed at -O0 a cbnz whose target lay 263002 instructions back, past its reach, which both assemblers rejected likewise; without the calls the branch was rewritten, and where the loop also decremented x the cbnz went instead to a fixup block within its reach, which the linear allocator put on the loop's back edge. - makeFarBranches in GHC.CmmToAsm.RV64.CodeGen (BUG, ISSUE 28222 section 5.1: max_jump_dist is 2^11-1 instructions, where a BCOND, printed as a B-type branch, reaches 4 KiB each way, 1024 instructions back and 1023 forward where none is compressed; and instr_size counts a MOV that prints as li as two instructions, where the assembler expands li of a 64-bit constant to up to eight). A conditional branch whose target lies more than 4 KiB away, but fewer than 2^11-1 instructions by the estimate, is left beyond its reach, on RISC-V, and only an assembler that lengthens such a branch assembles the module as meant: LLVM's (clang 18) and GNU as 2.42 lengthen such a beq, with and without -mno-relax. This rests on master's code read and on a compiler of master's code given a RISC-V target description through -B, which printed such a beq past its reach, not rewritten, that both assemblers turned into a bne over a j. The second cause leaves a branch that a corrected max_jump_dist would also leave: at -O, for a .cmm procedure whose branch skips 300 stores of distinct 64-bit constants, it printed a beq over 300 li and 300 sd, counted near 900 instructions, under 1023, which GNU as 2.42 placed 11 KiB, 0x2c28 bytes, before its target, each li expanded to eight instructions, and lengthened to a bne over a j without a message, as clang 18 did. Haskell reaches it too: at -O0 and -O, for a function whose case alternative writes one 64-bit literal by writeIntOffAddr# 114 times, it printed a bne over 114 li and 114 sd, which GNU as 2.42 with -mno-relax placed 4120 bytes before its target and lengthened to a beq over a j. - makeFarBranches in GHC.CmmToAsm.LA64.CodeGen (BUG, ISSUE 28222 section 3.2: replace_jump rewrites BCOND1 alone, never BEQZ or BNEZ, which genCondJump also emits and which reach 4 MiB each way; instr_size counts a MOV that prints as li.d as one instruction, where the assembler expands li.d to up to four; and replace_jump advances its position by two for each BCOND1 it rewrites, where instr_size counted one). The estimate of a forward branch's distance falls short by one for each BCOND1 rewritten before its target, through the advance where the BCOND1 comes before the branch and through instr_size's count where it comes between the two. A conditional branch beyond its reach can be left as it is, on LoongArch, and LLVM's assembler (clang 18) then rejects the module, where GNU as 2.42 lengthens the branch. This rests on master's code read and on a compiler of master's code given a LoongArch target description through -B, which left as they were a beqz past its reach; in a procedure of 9000 li.d and 9000 stores that the estimate put below its threshold, a bltu past BCOND1's 128 KiB; at -O0, after 40 BCOND1 that it rewrote, a bltu with 32780 instructions between it and its target, which it rewrote without the 40; and, at -O0 too, a bltu with 40 BCOND1 that it rewrote and 32700 stores between it and its target: LLVM's assembler rejected all four ("fixup value out of range"), and expanded two of the second procedure's li.d, assembled alone, to three and four instructions; GNU as 2.42 assembled each of the four as the inverted branch over a b. - getRegister''s case for MO_XX_Conv in GHC.CmmToAsm.LA64.CodeGen (BUG, ISSUE 28222 section 4.7: for a global register under the MO_XX_Conv, the register returned is the global's own, a Fixed one, which getSomeReg returns as the operand's register). Each operation that extends a sub-word operand in its own register then writes the global, wrong code on LoongArch at -O: genCondJump's ubcond zero-extends both operands of if (a < b) on bits16 arguments in R1 and R2, so a procedure returning R2 after it returns R2's low 16 bits alone, 0 for R2 65536, which it returns at -O0; sbcond, the == 0 and /= 0 cases of genCondJump and the 8- and 16-bit arithmetic, bitwise, shift and comparison cases of getRegister' write R2 likewise. The case for MO_UU_Conv writes a fresh dst, as RISC-V's narrowing MO_XX_Conv does. A global reaches an MO_XX_Conv only through copyIn in GHC.Cmm.Graph, as a sub-word argument or result whose upper bits the calling convention ignores (Note [Width of parameters]), so only hand-written Cmm that uses the global after it is affected. This rests on master's code read (the case, getRegister''s case for a global register, getSomeReg, copyIn, ubcond, sbcond) and on a compiler of master's code given a LoongArch target description through -B, nothing run on LoongArch: at -O it printed bstrpick.d $s4, $s4, 15, 0 on R2's register before the bltu of if (a < b) and the move $s3, $s4 that returns R2, ext.w.h $s4, $s4 for if (b == 0::bits16), and bstrpick.d $s4, $s4, 15, 0 for if (a + b == 7::bits16), where at -O0 each extension went to a copy. - do_mul_may_oflo in GHC.CmmToAsm.LA64.CodeGen, local to getRegister', its case for W32 (BUG, ISSUE 28222 section 4.1: MULW is given operands of 64 bits, which GHC.CmmToAsm.LA64.Ppr prints at 32 bits alone). MO_S_MulMayOflo at 32 bits is then a compiler panic, "LA64.ppr: MULW error", on LoongArch, at -O0 and -O, from hand-written Cmm alone: StgToCmm emits MO_S_MulMayOflo for IntMulMayOfloOp at the word's width, and the cases for 8, 16 and 64 bits compile. The testsuite's MulMayOflo_full.cmm panics so, and its all.T marks it expect_broken(23742) on every architecture but AArch64, x86-64, i386 and RISC-V; ISSUE 23742 reports that the other backends compute the MachOp wrongly for sub-word inputs and names no panic. This rests on master's code read (do_mul_may_oflo's cases, and MULW's printing) and on a compiler of master's code given a LoongArch target description through -B, which panicked so at -O0 and -O on r = %mulmayoflo(a, b) of a procedure's two bits32 arguments, which -dcmm-lint passes, and at -O on MulMayOflo_full.cmm; at bits8, bits16 and bits64 it compiled. - do_mul_may_oflo in GHC.CmmToAsm.LA64.CodeGen, local to getRegister', its general case (BUG, ISSUE 28222 section 4.6: at 8 and 16 bits it sign-extends the operands into the registers getSomeReg returns for them, which for a CmmReg, or an MO_XX_Conv of one, is that register itself). genCondJump's ubcond zero-extends its first operand's register before the second operand's code runs, so where the second operand holds an 8- or 16-bit MO_S_MulMayOflo of the first, the unsigned branch compares a sign-extended value, wrong code on LoongArch at -O0 and -O: if (a < %mulmayoflo(a, b) + 40000::bits16) on bits16 arguments returns 0 for a from 32768 to 39999 with b 0, where 1 is right, and with bits8 arguments and 200::bits8 for a from 128 to 199; at -O, where b is an MO_XX_Conv of R2, whose own register the BUG at MO_XX_Conv in getRegister' returns, the sign extension also replaces R2's upper bits. Only hand-written Cmm reaches it, IntMulMayOfloOp in GHC.StgToCmm.Prim emitting MO_S_MulMayOflo at the word's width alone; ISSUE 28131 reports the same bug in RISC-V's do_mul_may_oflo. This rests on master's code read (do_mul_may_oflo, getSomeReg, ubcond, the comment "Signed arithmetic on LoongArch64") and on a compiler of master's code given a LoongArch target description through -B, the values read from the instructions, nothing run on LoongArch: for that procedure at -O0 and -O it printed a bstrpick.d of a's register and then an ext.w.h and an slli.w of the same register before the bltu that compares it, and ext.w.b at 8 bits likewise; for one that returns R2 after %mulmayoflo(a, b) != 0::bits16, at -O, ext.w.h $s4, $s4 and slli.w $s4, $s4, 0 on R2's register before move $s3, $s4, where at -O0 the extensions went to copies. - sbcond in GHC.CmmToAsm.LA64.CodeGen, local to genCondJump (BUG, ISSUE 28222 section 3.8: at 8, 16 and 32 bits it sign-extends the first operand into the register getSomeReg returns for it, which for a CmmReg, or an MO_XX_Conv of one, is that register itself, before the second operand's code runs). Where that code zero-extends the same register in place, as the case of getRegister' for MO_U_Quot at 8 and 16 bits and the unsigned case of intOp, which serves MO_Add, MO_Sub and MO_U_Rem, do, the branch compares a zero-extended first operand with a sign-extended second one, wrong code on LoongArch, from Haskell at -O and from Cmm at -O0 and -O: read from the instructions, x < x + y on Int16 is False for a negative x and a positive y, and if (a == %divu(a, b)) on bits16 returns 0 for a 32768 and b 1, where 1 is right. At -O the two sign extensions also write R2 where an operand is an MO_XX_Conv of it, whose own register the BUG at MO_XX_Conv in getRegister' returns, as if (a == b) on bits16 arguments does. No Cmm file under rts/ reaches it as read in the code, its sub-word comparisons being with a literal; ISSUE 28050 reports the same in-place sign extension in RISC-V's sbcond. This rests on master's code read (sbcond, getSomeReg, the case for MO_U_Quot, intOp) and on a compiler of master's code given a LoongArch target description through -B, nothing run on LoongArch: for x < x + y it printed at -O, on Int16, an ext.w.h and then a bstrpick.d of x's register before the bge, and on Int32 an slli.w and a bstrpick.d; for if (a == %divu(a, b)), at -O0 and -O, an ext.w.h and then a bstrpick.d of a's register before the beq; and for a procedure returning R2 after if (a == b), at -O, ext.w.h $s4, $s4 before move $s3, $s4. - genCmpxchg in GHC.CmmToAsm.LA64.CodeGen, its path under -mla664 (BUG, ISSUE 28222 section 3.9: amcas writes the memory's old value into its first register, which is the register getSomeReg returns for the expected value, for a CmmReg that register itself). Each use of the expected value after the AMCASDB then uses the value found, wrong code on LoongArch under -mla664 at -O0 and -O, from Haskell and from the RTS's Cmm: read from the instructions, r ==# old after casIntArray# is 1 whatever the memory held, and so at 8, 16 and 32 bits and after atomicCasAddrAddr# and atomicCasWordAddr#; an atomic increment that retries while r /=# old never retries, losing its increment where another thread has changed the memory; and in rts/PrimOps.cmm built with the flag, whose tests h != old and h != x after %cmpxchgW are never true, stg_casMutVarzh, stg_casArrayzh and stg_casSmallArrayzh report success for a failed swap and stg_atomicModifyMutVar2zh and stg_atomicModifyMutVarzuzh lose an update. No file of the build system builds the RTS with -mla664. For a literal 0 expected value getSomeReg returns the zero register, so the result, moved from it, is 0 whatever the memory held. Where the expected value is the same variable as the new value or the address, the AMCASDB's first register is also its second or its third, which GNU as rejects, a failed compilation. This rests on master's code read (genCmpxchg, whose MOV takes the AMCASDB's first register as the old value; getSomeReg; getRegister''s cases for a CmmReg and for a literal 0; the uses of MO_Cmpxchg in GHC.StgToCmm.Prim) and on a compiler of master's code given a LoongArch target description through -B, nothing run on LoongArch: for casIntArray# followed by r ==# old it printed amcas_db.d $s5, $s6, $a0, move $a0, $s5 and sub.d $s3, $a0, $s5 at -O, $s5 being R3, which holds old, the same on a copy of R3 at -O0, and amcas_db.b, .h and .w at the other widths; for the atomic increment at -O, amcas_db.d $a1, $a3, $a2, move $a2, $a1 and bne $a2, $a1; for master's rts/PrimOps.cmm under THREADED_RTS, at -O0 and -O, in each of the five procedures a bne between the amcas_db.d's first register and its copy; for casIntArray# arr 0# 0# new, amcas_db.d $zero and move $a0, $zero at -O0 and -O; and for casIntArray# arr 0# x x and atomicCasAddrAddr# p p new, amcas_db.d $s5, $s5, $a0 and amcas_db.d $s4, $s5, $s4 at -O and amcas_db.d $a0, $a0, $a1 and amcas_db.d $a1, $a0, $a1 at -O0, which GNU as 2.42 rejected ("AMO insns require rd != base && rd != rt when rd isn't $r0"). - regUsageOfInstr's case for AMSWAPDB in GHC.CmmToAsm.LA64.Instr (BUG, ISSUE 28222 section 3.10: dst is written only, so the linear allocator may give it the register of src1 or src2 where that operand is a temporary dying at the instruction). Under -mla664 genXchg in GHC.CmmToAsm.LA64.CodeGen gives its fresh tmp as dst, and genRaInsn in GHC.CmmToAsm.Reg.Linear releases the registers of the read temporaries that die at an instruction before it allocates those the instruction writes, so the amswap_db's first register can also be its second or its third, which GNU as rejects, a failed compilation on LoongArch under -mla664, from Haskell: at -O0 where an argument's copy dies at the exchange, at -O where the address is computed in the function, as that of a MutVar#'s field is, and under -ticky in a counter's registration at -O0 and -O. The comment above the case says that rd and rj should not be one register. AMADDDB, AMANDDB, AMORDB and AMXORDB share the usage, and no code emits them; AMCASDB's dst, being modified, is live into the instruction. This rests on master's code read (the usage, genXchg, genRaInsn's steps (e) and (g)) and on a compiler of master's code given a LoongArch target description through -B, nothing run on LoongArch: amswap_db.d $a0, $a0, $a1 at -O0 for atomicExchangeWordAddr#, where -O gave amswap_db.d $a0, $s5, $s4 on R3 and R2, which assembled; amswap_db.d $a0, $a0, $a2 at -O0 and amswap_db.d $a0, $s5, $a0 at -O for atomicSwapMutVar#; amswap_db.d $a1, $a2, $a1 at -O for a copy of atomicSwapIORef; and amswap_db.d $a1, $a2, $a1 at -O0 and -O for a module of k x = x + 1 under -ticky, each rejected by GNU as 2.42 ("AMO insns require rd != base && rd != rt when rd isn't $r0"). - makeFarBranches in GHC.CmmToAsm.PPC.Instr (BUG, ISSUE 28222 section 3.3: blockLen counts each instruction as one, where MFOV, LDFAR, STFAR and FETCHPC print as two, as does a BCC that makeFar turns into a BCCFAR). The estimate of a branch's distance can fall short by more than the margin that nearLimit, 7000 instructions less maxRetInfoTableSizeW for each info table, keeps below bc's reach of 8192 instructions back and 8191 forward, and a conditional branch beyond its reach is then left as it is, on PowerPC. LLVM's assembler (clang 18) encodes such a branch without a message, with a wrapped displacement, which is wrong code, and GNU as 2.42 rejects the module. This rests on master's code read (blockLen, nearLimit, makeFar, and the printing of these instructions in GHC.CmmToAsm.PPC.Ppr) and on a compiler of master's code given a 64-bit PowerPC target description with the ELFv2 ABI through -B: of a Cmm procedure that branches over 2300 stores of %mulmayoflo, it printed at -O0 a beq with 9205 instructions between it and its target, past its reach of 32 KiB, which LLVM's assembler encoded as a branch backwards and GNU as 2.42 rejected ("operand out of range"). - iselExpr64 in GHC.CmmToAsm.PPC.CodeGen (BUG, ISSUE 28222 section 4.2: it has no case for a conversion to 64 bits from fewer than 32, or for a 64-bit multiply, shift or logical operation). Each such expression panics ("iselExpr64(powerpc)"), a failed compilation, on 32-bit PowerPC, at -O0 as at -O1. On this target StgToCmm emits the Int64# and Word64# primops for these operations as callish MachOps, such as MO_x64_Mul, which genCCall compiles to a call of hs_mul64, as stgToCmmAllowArith64 in GHC.Driver.Config.StgToCmm is off for the NCG of a 32-bit target other than i386 and wasm32, and an Int8# reaches 64 bits through the word; so only hand-written Cmm is known to reach these cases, though ISSUE 26828, closed, showed GHC's own source reaching iselExpr64 with a 64-bit subtraction of a literal, which has a case on master. This rests on master's code read (iselExpr64's cases; stgToCmmAllowArith64, and opTranslate64 in GHC.StgToCmm.Prim) and on a compiler of master's code given a 32-bit PowerPC target description through -B. At -O0 and -O1 it panicked so on bits64[p] = %zx64(x) for a bits8 or a bits16 x, on %sx64 of a bits8 and on the product of two bits64 loads, and at -O1 on %sx64 of a bits16, a 64-bit shift and a 64-bit and; it compiled %zx64 of a bits32 and the sum of two bits64 loads at -O0 and -O1, and %sx64 of a bits32 at -O1. Haskell was not compiled for this target, and nothing was assembled. - getRegister''s case for CmmRegOff in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28222 section 2.14: neither mangleIndexTree nor add_int narrows the offset to the register's width, and cmmMachOpFoldM's folds of literals into a CmmRegOff sum them unnarrowed). For a 16-bit register whose offset lies outside 16 bits, add_int's LEA, printed as an ADD of an immediate where the result takes the operand's register, makes the assembler shorten the immediate, with a warning where its magnitude reaches 2^16 (addw $90000,%ax for a 16-bit register plus three times 30000); the shortened immediate gives the value meant, so this costs at most the warning, on x86 and x86-64. An 8-bit register's sum takes an ADD whose immediate litToImm narrows, an LEA printed as an LEA takes the offset as a 32-bit displacement without a warning, and a wider register holds any offset add_int is given. This rests on master's code read (mangleIndexTree, add_code, add_int and the printing of an LEA as an ADD in GHC.CmmToAsm.X86.Ppr), on master's compiler, whose assembly for such a sum in Cmm made the assembler warn so, and on GNU as given addw and leaw with such an immediate and displacement, with and without --32: it warned of the addw alone and assembled both. - getRegister''s case for MO_VS_Abs in GHC.CmmToAsm.X86.CodeGen, with MO_VF_Sqrt's below it (BUG, ISSUE 28222 section 1.11: the guards test the extensions and the lane width, not the vector's length). At 256 and 512 bits vector_int_abs_ssse3 and vector_int_abs_sse2, at 64-bit lanes without AVX-512VL, which the 512-bit VPABSQ does not need, vector_int64_abs_sse42 and vector_int64_abs_sse2, and without AVX vector_float_sqrt then emit SSE instructions, which have no 256-bit or 512-bit form, and the assembler rejects the module, a failed compilation, from Haskell on x86 and x86-64: at -O for the 256-bit and 512-bit vector integer absolute values at lanes of 8 to 32 bits and, without -mavx512vl, at 64-bit lanes, and for the square roots without -mavx; at -O0 only under -mavx2 or -mavx512f, without which movInstr's sorry stops a 256-bit or 512-bit vector first, so that there vector_int_abs_ssse3 and vector_int64_abs_sse42 alone are reached. This rests on master's code read (the guards; the four SSE functions and vector_float_sqrt, each forming its instructions' format from the vector's length; movInstr's sorry) and on a compiler of master's code on x86-64 and, given an i386 target description through -B, for i386. On x86-64, absInt64X4# under -mavx2 gave pcmpgtq %ymm1,%xmm0, pxor %ymm0,%ymm1 and psubq %ymm0,%xmm1 at -O, and at -O0 movdqu %ymm1,%ymm2, pcmpgtq %ymm1,%xmm0, pxor %ymm0,%ymm2 and psubq %ymm0,%xmm2, absInt8X32# under -mavx2 pabsb %ymm1,%xmm1 at -O, absInt64X8# under -mavx512f pcmpgtq %zmm1,%xmm0 at -O0 and -O, and without a flag, at -O, absInt32X8# pcmpgtd %ymm1,%xmm0 and sqrtDoubleX4# sqrtpd %ymm1,%xmm1, where at -O0 both stopped with the sorry; GNU as 2.42 rejected each of these lines, the pxor and the movdqu, whose operands are both at 256 bits, included. For i386, absInt32X8# under -mavx2 gave pabsd %ymm0,%xmm0 at -O0 and -O1, which i686-linux-gnu-as --32 rejected. - getRegister''s case for MO_V_Broadcast in GHC.CmmToAsm.X86.CodeGen, above its first alternative, with a pointer at its case for MO_V_Insert 2 W64 (BUG, ISSUE 28222 section 3.5: on i386, vector_int64x2_broadcast and vector_int_broadcast_avx2 for 64-bit lanes, and vector_int64x2_insert_sse2 and vector_int_insert_pinsr for MO_V_Insert 2 W64, compile the 64-bit integer by getNonClobberedReg, into one 32-bit register, and move it by MOVD or PINSR at II64). On i386 a 64-bit integer takes two registers, which iselExpr64 gives; getRegister' instead panics on a 64-bit load ("getRegister(x86) CmmLoad"), gives for a 64-bit Cmm local the virtual register of its low half, VirtualRegI of its unique, and compiles a 64-bit literal to a MOV at II64, printed movq. MOVD and PINSR at II64 are printed movq and pinsrq of that 32-bit register, neither of which exists in 32-bit mode. So, from Haskell, each broadcastInt64X2# and broadcastWord64X2#, under -mavx2 each broadcastInt64X4# and broadcastWord64X4#, and each insertInt64X2#, insertWord64X2#, packInt64X2# and packWord64X2# that reaches the code generator fails to compile, under -msse4.2, -mavx2 or neither: at -O0, where the operand is a Cmm local or a literal, the assembler rejects the module (GNU as: "operand type mismatch for `movq'", and for an insert under SSE4.1 "`pinsrq' is only supported in 64-bit mode"); at -O1 and -O2 the compiler panics where the operand is a load, as a function's argument is, and at -O1 the assembler rejects the module where the operand is a literal or an unsafe foreign call's result, and an operand computed by intToInt64# stops the compiler with a sorry error ("Invalid conversion operation from W32 to W64"). A lane unpacked from an Int64X2# or a Word64X2# stops the compiler first at -O0, by the BUG at iselExpr64's last clause, and at -O1 and -O2, where Cmm sinking puts the lane's extraction into the operand, the extraction is printed movq or pextrq of a 32-bit register too. getRegister''s case for CmmLit compiles a vector literal whose lanes are equal and not zero by MO_V_Broadcast of a lane, so an Int64X2# or Word64X2# constant of equal lanes that getRegister' compiles fails too, as a pack of two equal literals does at -O1, where one of zero lanes or of unequal lanes compiles. A comment on ISSUE 25498, an issue on SIMD tests that fail on i386 under the LLVM backend, says that packInt64X2# and unpackInt64X2# are not implemented in the i386 NCG, explaining why the test T25030, which the Makefile compiles without -fllvm, fails there; that issue reports the test's failure in the LLVM ways, which the comment proposes to fix by passing -fllvm, and no issue reports the NCG's failure, so the statement cites none. This rests on master's code read (getRegister''s cases for MO_V_Broadcast and MO_V_Insert and its cases for CmmLoad, CmmReg and CmmLit, getLocalRegReg, mkVirtualReg in GHC.CmmToAsm.X86.RegInfo, localReg64 in GHC.CmmToAsm.Monad, the four functions, and pprMovdOpOp and pprPinsr in GHC.CmmToAsm.X86.Ppr) and on a compiler of master's code given an i386 target description through -B, at -S, its assembly given to GNU as 2.42 with --32: for f a = broadcastInt64X2# a the assembler rejected movq %eax,%xmm0 at -O0, and the compiler panicked at -O1 and -O2, under -msse4.2, -mavx2 or neither; so did broadcastWord64X2#, packInt64X2#, packWord64X2#, insertInt64X2#, insertWord64X2#, plusInt64X2# of two broadcasts and timesWord64X2# of a broadcast and an argument, the assembler rejecting the pinsrq of the packs and the inserts under -msse4.2 and -mavx2; broadcastInt64X4# and broadcastWord64X4# did so under -mavx2, and stopped otherwise with "256-bit wide integer SIMD vector instructions require at least -mavx2"; at -O1 the broadcast of a literal and of an unsafe foreign call's result, the insert of a literal and the pack of two equal literals compiled to assembly the assembler rejected, and the packs of two unequal literals and of two zeros compiled to assembly it accepted; clang 18, given -target i386-linux-gnu, rejected the assembly of broadcastInt64X2# at -O0, of broadcastInt64X4# at -O0 under -mavx2, of insertInt64X2# at -O0 under -msse4.2 and of the two broadcasts at -O1; plusInt64X2# of two arguments, broadcastInt32X4#, broadcastInt8X16# and broadcastDoubleX2# compiled and assembled at -O0 and -O1. Nothing was linked or run. - iselExpr64 in GHC.CmmToAsm.X86.CodeGen, above its last clause, with a pointer at getRegister''s case for MO_V_Extract 2 W64 (BUG, ISSUE 28222 section 3.6: it has no case for MO_V_Extract). On i386 a 64-bit integer takes two registers, which iselExpr64 gives: stmtToInstrs passes each assignment of a 64-bit value to a local or to memory to assignReg_I64Code or assignMem_I64Code, which compile the value by iselExpr64, as condIntCode' does a 64-bit comparison's operands, genCCall32 a foreign call's 64-bit arguments and getRegister' the operand of its narrowings from 64 bits. StgToCmm emits MO_V_Extract for the unpack primops alone (doVecUnpackOp), as one assignment of each lane to a local, so each extraction of a 64-bit lane that reaches iselExpr64 panics in its last clause ("iselExpr64(i386)"), a failed compilation, on i386, from Haskell, under -msse4.2, -mavx2 or neither: at -O0, where an unpack any of whose lanes is used extracts every lane, that of each such unpackInt64X2# and unpackWord64X2#, under -mavx2 of each such unpackInt64X4# and unpackWord64X4#, and under -mavx512f of each such unpackInt64X8# and unpackWord64X8#, the 256-bit and 512-bit ones stopping instead on x86-64 with the sorry error asking for -fllvm that getRegister''s case for MO_V_Extract gives for them; at -O1 and -O2, that of each such unpack whose lane is returned, stored, compared, narrowed, added or passed to an unsafe foreign call. At -O1 and -O2 cmmMachOpFoldM folds an extraction to the lane's value where the Cmm gives it, as for an unpack of a pack or of an insert at that lane, leaving none to compile, and the extraction of a 128-bit vector's lane that Cmm sinking puts into the operand of a broadcast or an insert, packs included, reaches getRegister''s case for MO_V_Extract 2 W64 instead, through the BUG at its case for MO_V_Broadcast: there vector_int64x2_extract_sse2, or under SSE4.1 vector_int_extract_pextr, moves the lane by MOVD or PEXTR at II64 into one 32-bit register, printed movq or pextrq, and the assembler rejects the module; for a 256-bit vector's lane under -mavx2, getRegister''s case for MO_V_Extract stops with the sorry error instead. A comment on ISSUE 25498, an issue on SIMD tests that fail on i386 under the LLVM backend, says that packInt64X2# and unpackInt64X2# are not implemented in the i386 NCG, to explain a test's failure in the LLVM ways, which that issue reports, and ISSUE 23537, open, reports iselExpr64's panic on i386 for a 64-bit subtraction of a literal and a 64-bit shift, for which iselExpr64 has cases on master; no issue reports the panic on an extraction, so the statement cites none. This rests on master's code read (iselExpr64's cases, stmtToInstrs, assignReg_I64Code, assignMem_I64Code, condIntCode', genCCall32's push_arg, getRegister''s cases for narrowings from 64 bits and for MO_V_Extract, vector_int64x2_extract_sse2, vector_int_extract_pextr, doVecUnpackOp in GHC.StgToCmm.Prim and cmmMachOpFoldM's case for MO_V_Extract in GHC.Cmm.Opt) and on a compiler of master's code given an i386 target description through -B, at -S, its assembly given to GNU as 2.42 with --32: for f v = unpackInt64X2# v it panicked so at -O0, -O1 and -O2, under -msse4.2, -mavx2 or neither, and so did unpackWord64X2#, an unpack whose lane 0 or lane 1 alone is returned, and one whose lane is narrowed by int64ToInt#, added, compared, written to a byte array or passed to an unsafe foreign call; unpackInt64X4# and unpackWord64X4# did so at -O0, -O1 and -O2 under -mavx2 and stopped otherwise with "256-bit wide integer SIMD vector instructions require at least -mavx2", and unpackInt64X8# and unpackWord64X8# did so at -O0, -O1 and -O2 under -mavx512f, while a compiler of master's code on x86-64 stopped with "Please use -fllvm" for unpackInt64X4# under -mavx2 and unpackInt64X8# under -mavx512f and compiled unpackInt64X2#; at -O1 and -O2 a broadcast, an insert and a pack of unpacked lanes compiled to a movq from an xmm register to a 32-bit one, or with -msse4.2 or -mavx2 to a pextrq, which the assembler rejected, as clang 18, given -target i386-linux-gnu, did for the broadcast's and the pack's at -O1; a broadcast of lane 0 of an unpackInt64X4# under -mavx2 stopped with that sorry error at -O1 and -O2, and an unpack of a pack of two arguments and one of an insert at the lane used compiled at -O1 and -O2 to assembly the assembler accepted, their -O1 Cmm holding no extraction; unpackDoubleX2# and unpackInt32X4# compiled and assembled at -O0, -O1 and -O2, and so did, at -O0 and -O1, a .cmm procedure computing a 64-bit shift and a 64-bit subtraction of a literal. Nothing was linked or run. - getRegister''s case for MO_V_Broadcast in GHC.CmmToAsm.X86.CodeGen, its last alternative (BUG, ISSUE 28212: every 512-bit integer broadcast reaches its panic, the alternative for vector_int_broadcast_avx2 taking 128 and 256 bits alone). Under -mavx512f each 512-bit integer broadcast panics ("Unsupported integer vector broadcast operation"), a failed compilation, on x86-64, from Haskell, where under -mavx2 the compiler rejects 512-bit integer vectors as an unimplemented feature that requires -mavx512f. This rests on master's code read and on a compiler of master's code on x86-64: for a function returning broadcastInt8X64#, broadcastInt16X32#, broadcastInt32X16#, broadcastInt64X8#, broadcastWord8X64#, broadcastWord16X32#, broadcastWord32X16# or broadcastWord64X8# of its argument, at -O0 and -O1, it panicked so under -mavx512f and stopped with "512-bit wide integer SIMD vector instructions require at least -mavx512f" under -mavx2; broadcastInt64X4#, broadcastWord32X8# and broadcastInt32X4# compiled under both. - vector_float_broadcast_avx in GHC.CmmToAsm.X86.CodeGen, local to getRegister' (BUG, ISSUE 27767: VSHUF with immediate 0, printed vshufpd or vshufps, copies within each 128 bits of the register the first element of those 128 bits). For a 256-bit or 512-bit vector only the low 128 bits then hold the scalar, and each higher 128 bits hold copies of their own first element, whatever the register held there. This is wrong code, under -mavx2 for broadcastDoubleX4# and broadcastFloatX8#, and under -mavx512f for the 512-bit broadcasts; a 128-bit broadcast is right, and under -mavx alone a 256-bit vector is rejected. ISSUE 27767's program, an fmaddDoubleX4# of a broadcastDoubleX4#, is wrong in its two high lanes by this alone. This rests on master's code read (getRegister''s case for MO_VF_Broadcast, which takes vector_float_broadcast_avx under -mavx, and VSHUF's printing as vshufpd and vshufps), ISSUE 27767's record and a compiler of master's code on x86-64 under -mavx2. At -O0 and -O1, broadcastDoubleX4# of a Double# computed by scalar code gave (2.5, 2.5, 0.0, 0.0) and broadcastFloatX8# 2.5 in the four low lanes and 0.0 in the four high ones; at -O1, broadcastDoubleX4# of lane 0 of a DoubleX4# loaded as (1.0, 2.0, 3.0, 4.0) gave (1.0, 1.0, 3.0, 3.0), and broadcastFloatX8# of lane 0 of 1.0 to 8.0 gave 1.0 in the four low lanes and 5.0 in the four high ones; broadcastDoubleX2# and broadcastFloatX4# gave the scalar in every lane. ISSUE 27767's program gave (12.0,24.0,30.0,40.0) at -O0 and -O1, and (12.0,24.0,36.0,48.0) with the broadcast replaced by four stores and a 256-bit load, as under -fllvm. Under -mavx512f the 512-bit broadcasts compiled to vshufpd and vshufps on zmm registers, which were not run. Nothing was run on i386. - vector_int_broadcast_avx2 in GHC.CmmToAsm.X86.CodeGen, local to getRegister' (BUG, ISSUE 28211: for a 256-bit vector, MOVD's destination and VPBROADCAST's source take the vector's format, so both are printed as a ymm register). On x86-64, and on i386 for lanes of 8 to 32 bits, the assembler rejects the module for every 256-bit integer broadcast under -mavx2, which -mavx512f implies, and a 128-bit broadcast takes xmm registers and assembles; on i386 a broadcast of 64-bit lanes of either width fails by the BUG at getRegister''s case for MO_V_Broadcast above its first alternative, and one of 256 bits by this BUG too: at -O0 the assembler rejects its vpbroadcastq of a ymm register as well as its movq of a 32-bit register into one, and at -O the compiler panics first where the operand is a load; a 512-bit broadcast does not reach this function. This rests on master's code read (getRegister''s cases for MO_V_Broadcast, and pprMovdOpOp and pprBroadcast in GHC.CmmToAsm.X86.Ppr, which print each operand at the format given) and on a compiler of master's code on x86-64: for a module defining f (I32# a) = (# broadcastInt32X8# a #), it printed movd %eax,%ymm1 and vpbroadcastd %ymm1,%ymm1 at -O1 -mavx2, which GNU as 2.42 ("operand type mismatch for `movd'") and clang 18 rejected; ghc -c failed so for each 256-bit Int and Word broadcast at -O0 and -O1, under -mavx2 and under -mavx512f, and compiled the 128-bit ones tried; for i386, given its target description through -B, GNU as 2.42 with --32 rejected so the assembly of broadcastInt32X8#, broadcastInt16X16# and broadcastWord8X32# at -O0 and -O1 under -mavx2, and assembled that of broadcastInt32X4# and broadcastInt8X16#, and rejected that of broadcastInt64X4# and broadcastWord64X4# at -O0 under -mavx2 at movq %eax,%ymm0 and at vpbroadcastq %ymm0,%ymm0. Nothing was run on i386. - vector_op_sse_reg in GHC.CmmToAsm.X86.CodeGen and the second PALIGNR fallback of vector_shuffle_int128_common there, taken by the 128-bit integer shuffles without SSSE3, both local to getRegister', one at each (BUG, ISSUE 28179: the first operand's code is generated before the second's but emitted after it). On i386, where both operands' code splits a block, as the code of a 64-bit shift does (iselExpr64's shifts end the block and call addCondBlock), the CFG has the splits the other way round. Where the CFG is kept, the compiler then panics in addNodesBetween ("Can't find weight for edge that should have one") if the linear allocator puts a fixup block on an edge the CFG lacks, and otherwise in sanityCheckCfg ("Block list and cfg nodes don't match") under -dasm-lint or in a DEBUG compiler. On x86-64 no expression's code splits a block, so the reversal is harmless there. This rests on master's code read (vector_op_sse_reg's two cases, iselExpr64's shifts, addCondBlock, and cmmNativeGen, where sanityCheckCfg forces the CFG that addNodesBetween returns), ISSUE 28179's record and runs of an x86-64 stage-1 compiler built from this branch, whose code is master's, given an i386 target description through -B. At -S -O -dasm-lint, sanityCheckCfg panicked on plusInt32X4# of two broadcasts of 64-bit shift results and, without -mssse3, on shuffleInt32X4# of two such broadcasts with indices (# 6#, 7#, 0#, 1# #), whose assembly without -dasm-lint has psrldq, pslldq and por and no palignr; addNodesBetween panicked on a loop of such additions at -O, with -dasm-lint or without, and sanityCheckCfg did instead under -fregs-graph -dasm-lint. These compiled: the addition with one operand shifted, at -O0, without -dasm-lint and for x86-64; the shuffle with indices (# 2#, 3#, 4#, 5# #); the shuffle and the loop under -finfo-table-map -dasm-lint; and the loop under -fregs-graph without -dasm-lint. Nothing was assembled, linked or run, and nothing was run on i386. - vector_float_extract in GHC.CmmToAsm.X86.CodeGen, local to getRegister', its case for 32-bit lanes under AVX (BUG, ISSUE 27422: VPSHUFD with the lane as its immediate selects, by the immediate's two low bits, a lane of the vector's low 128 bits). Lane k of a FloatX8# or a FloatX16# then gives lane k mod 4, which is wrong code for lanes 4 to 7 of a FloatX8# under -mavx2 and for lanes 4 to 15 of a FloatX16# under -mavx512f, on x86-64, from Haskell; a FloatX4# is right. ISSUE 27422's program, an unpackFloatX8# of a sum, is wrong by this alone. This rests on master's code read (getRegister''s case for MO_VF_Extract, and VPSHUFD's printing as vpshufd), ISSUE 27422's record and a compiler of master's code on x86-64 under -mavx2. A program unpacking a FloatX8# loaded from (1.0, ..., 8.0) printed [1.0,2.0,3.0,4.0,1.0,2.0,3.0,4.0] at -O0, -O1 and -O2, its assembly vpshufd $1 to vpshufd $7 on ymm registers, and one unpacking a FloatX4# so printed [1.0,2.0,3.0,4.0]. ISSUE 27422's program printed 11.0, 22.0, 33.0 and 44.0 twice at -O1 and -O2, as the issue reports, and was refused at -O0 ("FloatX8# insert operations require -fllvm"); with its sum stored to memory and read back lane by lane in place of the unpack, it printed 11.0 to 88.0. Under -mavx512f, lane 9 of a FloatX16# compiled to vpshufd $9 on zmm registers, which was not run. Nothing was run on i386. - vector_float_extract in GHC.CmmToAsm.X86.CodeGen, local to getRegister', its case for 64-bit lanes (BUG, ISSUE 28216: it takes the offsets 0 and 1 alone). Extracting lane 2 or above of a DoubleX4# or a DoubleX8# panics ("Unsupported AVX floating-point vector extract offset"), a failed compilation, on x86-64 under -mavx2 and -mavx512f, and at -O1 and -O2 under -mavx, from Haskell; at -O0, where an unpack extracts every lane, so does every unpackDoubleX4# and unpackDoubleX8# any of whose lanes the program uses. This rests on master's code read (getRegister''s case for MO_VF_Extract, which takes this case for 64-bit lanes at every length and under every SIMD flag) and on a compiler of master's code on x86-64. For functions returning one lane of an unpackDoubleX4# of their argument, at -O1 and -O2 under -mavx, -mavx2 and -mavx512f, it compiled lanes 0 and 1 and panicked so on lanes 2 and 3, and at -O0 under -mavx2 and -mavx512f it panicked so on each lane; for an unpackDoubleX8# under -mavx512f, it compiled lane 1 and panicked on lanes 2 and 7 at -O1, and panicked on lane 1 at -O0. - getHiVirtualRegFromLo in GHC.Platform.Reg, pointed to from localReg64 and getNewReg64 in GHC.CmmToAsm.Monad and from genByteSwap in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28125: the high half keeps the number of the low half's unique): a 64-bit Cmm local and a 64-bit NCG temporary with the same number share their high half, and where both are live, writing one overwrites the other's high 32 bits. This is wrong code on i386 and 32-bit PowerPC. Equal numbers occur, as the NCG's uniques count from 0 in each Haskell module (initDUniqSupply in GHC.Driver.Main.Compile) and, in a .cmm file, continue the supply its Cmm pipeline used: in a .cmm file that a ghc process compiles first, whose parser numbers its locals from 1 on; in a Haskell module under -fobject-determinism, which renumbers its Cmm locals from 54 on (emptyDetUFM in GHC.Cmm.UniqueRenamer); and in any other Haskell module or .cmm file once the NCG's count reaches the numbers that the global unique counter gave its Cmm locals. In genByteSwap, equal high halves with different low halves can arise so, and the branch for that case swaps correctly. This rests on master's code read, ISSUE 28125's record, whose runs show all three, and runs of a compiler of master's code given i386 and 32-bit PowerPC target descriptions through -B, with -dcmm-lint, at -O, each of the procedures f and g below compiled by a ghc process of its own. For i386 the .cmm procedure f (bits64 x, bits64 y, gcptr p) { bits64[p] = (x * y) + x; return (); } gave its 64-bit local x, numbered 1, and the NCG temporary that loads its second argument, y, one high half, and the final assembly loaded y's high half (movl 12(%ebp),%ecx) into the register holding x's (movl 4(%ebp),%ecx) before reading it as x's; for 32-bit PowerPC, iselExpr64, which has no case for a 64-bit shift or multiply, panicked on that procedure's x * y. For both, the procedure g (gcptr p, gcptr q) { bits64 x; x = bits64[p]; bits64[q] = bits64[q + 8]; bits64[q + 16] = bits64[q + 24]; bits64[q + 32] = bits64[q + 40]; bits64[q + 48] = x; return (); }, whose 64-bit local x, numbered 3, is live across three later 64-bit loads, gave x and the NCG temporary that loads the third of them one high half, and the final assembly stored that value's high word as x's. For i386, a procedure like g whose x is live across eight later 64-bit loads, in a .cmm file that a ghc process compiled after f's file, numbered x 7 and gave it and the NCG temporary that loads the seventh of them one high half, and the final assembly stored that value's high word as x's. Nothing was assembled, linked or run, and nothing was run on either target. - callerSaves in compiler/CodeGen.Platform.h (BUG, ISSUE 28221: no clause names XmmReg, YmmReg or ZmmReg, though rts/include/stg/MachRegs/x86.h defines CALLER_SAVES_XMM1 and up for x86-64, and arm64.h CALLER_SAVES_XMM1 and XMM2; for i386, x86.h puts XMM1 to XMM4 in xmm0 to xmm3 and defines none for them). The Cmm passes treat a vector STG register as surviving an unsafe foreign call, which clobbers its machine register, and Cmm lint accepts one among such a call's arguments. Where Cmm copies a vector STG register to a local before such a call, or a callish MachOp compiled to one such as MO_F64_Sin, and uses the local after it, as StgToCmm does with a function's vector argument, sinking, on at -O1 and -O2, can move the copy past the call; and under -fcmm-thread-sanitizer, at any -O level, around each call that GHC.Cmm.ThreadSanitizer inserts, saveRestoreCallerRegs saves only the STG registers that callerSaves names. Either is wrong code on AArch64 and i386, each reached on both from Haskell that uses vector primops. On x86-64, each of XMM1 to XMM6 that x86.h makes caller-saves, XMM6 not on Windows, shares its machine register with an F and a D register that callerSaves names, so sinking keeps the copy before the call, but saveRestoreCallerRegs saves and restores only the low 64 bits of that machine register. This rests on master's code read (activeCallerSavesRegs in GHC.Cmm.Node, from which sinking takes a call's clobbers, mayNotMentionCallerSavedRegs in GHC.Cmm.Lint, and saveRestoreCallerRegs) and on a compiler of master's code given AArch64 and i386 target descriptions through -B, which at -O -dcmm-lint moved v = XMM1 past foreign "C" foo(x) in a procedure that then sets XMM2 = v; given the AArch64 one, at -O and -O2, it compiled Haskell functions that add a DoubleX2# argument to itself after an unsafe foreign call, or after sinDouble#, to a bl foo or bl sin followed by an fadd of v4, XMM1's machine register, which the call clobbers, where at -O0, for x86-64 at -O, and for the sinDouble# one at -O with -fno-cmm-sink, the vector was kept on the stack across the call. Given the i386 one, at -O1 and -O2, it compiled the same functions to a call followed by an addpd of xmm0, XMM1's machine register, which the call clobbers, where at -O0, and at -O1 with -fno-cmm-sink, the vector was kept on the stack across the call. Under -fcmm-thread-sanitizer, at -O0, -O1 and -O2, it compiled the function with the unsafe foreign call, for AArch64 and i386, to code that keeps the sum in v4 or xmm0 across the call to __tsan_read8 or __tsan_read4 that the pass inserts for the load of the return address, and for x86-64 to code that saves xmm1 around that call by movsd alone. Nothing compiled under -fcmm-thread-sanitizer was run. - callClobberedRegs in GHC.CmmToAsm.X86.Regs, its case for x86-64 Windows (BUG, ISSUE 28219: a callee saves only the low 128 bits of xmm6 to xmm15, and the case names those registers at no width). The register allocators can then keep a 256-bit or 512-bit value in ymm6 to ymm15 or zmm6 to zmm15 across a C call, of an unsafe foreign call or of a callish MachOp such as MO_F64_Sin, and the callee can destroy the value's bits above 127. This is wrong code on x86-64 Windows, under -mavx2 for 256-bit values and under -mavx512f for 512-bit ones, from Haskell and from hand-written Cmm; a value of 128 bits or fewer survives the call. This rests on master's code read (callClobberedRegs; clobbered in GHC.CmmToAsm.X86.Instr, which writes the registers it names; padStackArgs in GHC.CmmToAsm.X86.CodeGen, which rejects only 256-bit and 512-bit arguments of a Windows C call), on the x64 ABI document that the case's comment cites, whose table makes the upper half of ymm6 to ymm15 volatile, and on a compiler of master's code given an x86-64 Windows target description through -B. For a Haskell function adding a DoubleX4# argument to itself after an unsafe foreign call, at -O0, -O1 and -O2 under -mavx2 and at -O1 under -fregs-graph, it printed vmovupd %ymm1,%ymm6 before the call and vaddpd %ymm6,%ymm6 after it, where for x86-64 Linux the vector was spilled across the call; it did likewise for sinDouble# in place of the foreign call, for a DoubleX8# under -mavx512f at -O0 and -O1 with zmm6, and for a .cmm procedure keeping two vec256 locals across foreign "C" foo(), at -O0 and -O1, with ymm6 and ymm7. clang 18, for x86_64-w64-windows-gnu, compiled a function clobbering ymm6 to a save and restore of xmm6 alone, and that code, run on x86-64 Linux after the compiler's sequence for a DoubleX4# of (1, 2, 3, 4), left (1, 2, 0, 0). Nothing was run on Windows, and nothing compiled under -mavx512f was run. - verifyBasicBlock in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28222 section 5.7: a block of native code whose last jump is missing is caught only where that jump alone would cover one of the block's edges in the CFG: sanityCheckCfg, where the CFG is kept and under -dasm-lint or in a DEBUG compiler, checks that the block's jumps and its edges, a call's aside, agree, so a block with no such edge, as one meant to end in a tail call or a return, goes unchecked; this checks, in a DEBUG compiler, only that nothing but jumps follows a jump). A block that did not end in one would run on into whichever block the layout puts after it, which is wrong code; no instruction selector is known to make such a block. This rests on master's code read. - getAmode in GHC.CmmToAsm.X86.CodeGen, three clauses (BUG, ISSUE 28105: each can emit a displacement outside the signed 32-bit range: -i where i = -2^31; an offset left unchecked; and an offset checked only at shift 3, as && binds tighter than ||): where the displacement does not fit, the x86-64 assembler rejects the module. This rests on master's code read, ISSUE 28105's record and a compiler of master's code on x86-64, which printed, for hand-written Cmm at -O0 and -O, movq 2147483648(%rax) for bits64[bits64[p] - (-2147483648)], and movq 4294967296(%rbx,%r14,4) for bits64[(p + 4294967296) + (i << 2)] and for bits64[p + ((i << 2) + 4294967296)], and at -O movb 4294967296(%r14,%rsi,4) for indexWord8OffAddr# (plusAddr# a 4294967296#) (i *# 4#) and for indexWord8OffAddr# a (i *# 4# +# 4294967296#), each of which GNU as 2.42 and clang 18 rejected. - getAmode in GHC.CmmToAsm.X86.CodeGen, its clause for a register offset plus a shift and, at shift 0 to 2, its clause for x + ((y << shift) + offset), one at each (BUG, ISSUE 28222 sections 4.3 and 4.4: nor is the offset narrowed to the register's width). On i386 an offset outside 32 bits reaches the assembler, which shortens it modulo 2^32, to the address meant, warning only where its magnitude reaches 2^32, so this costs at most the warning; on x86-64 such an offset is the BUG of ISSUE 28105 at each clause. It is reached at both clauses, from Haskell at -O1 and -O2 and from hand-written Cmm at -O0 and -O: cmmMachOpFoldM in GHC.Cmm.Opt narrows each literal it folds into a CmmRegOff to its width, but not their sum. This rests on master's code read, on GNU as given such displacements with --32, which it shortened, warning from a magnitude of 2^32 on, and assembled, and on a compiler of master's code given an i386 target description through -B. For bits32[p + ((i << 2) + 4294967296)] on bits32 p and i, in a .cmm procedure that -dcmm-lint passes, it printed movl 4294967296(%ecx,%eax,4),%eax at -O0 and its like on %esi at -O, which i686-linux-gnu-as --32 assembled with the warning "0x100000000 shortened to 0x0"; for bits32[(p + 4294967296) + (i << 2)] it printed movl (%esi,%eax,4), the offset folded to 0, and at shift 3, whose guard refuses the offset, the clause for x + y took it, and the offset was added by addl $0. For bits32[(((p + 2147483647) + 2147483647) + 2) + (i << 2)], whose literals cmmMachOpFoldM summed into a CmmRegOff of 4294967296, it printed movl 4294967296(%ecx,%eax,4),%eax at -O0 and its like on %esi at -O, by the first clause. Given Haskell, it printed movl -4294967296(%eax,%eax,4) at -O1 and -O2 for indexIntOffAddr# (plusAddr# (plusAddr# p -2147483648#) -2147483648#) (addr2Int# p), by the first clause, and movl -4294967296(%eax,%ecx,4) for the same sum on an address loaded from p, indexed by an argument, by the second, and the assembler warned "0xffffffff00000000 shortened to 0x0" at each; at -O0 neither had an offset outside 32 bits. - addAlignmentCheck in GHC.CmmToAsm.X86.CodeGen (BUG, ISSUE 28222 section 3.7: the check's conditional jump names mkBadAlignmentLabel bare, where under -dynamic an ordinary jump to the RTS goes through the GOT). On i386 under -dynamic, which implies -fPIC, with -falignment-sanitisation, the assembler relocates the jump as R_386_PC32 against stg_badAlignment_entry, a symbol of the RTS's shared object, so a shared object linked from the code carries a text relocation: GNU ld warns that it creates DT_TEXTREL, and fails under -z text. Hand-written Cmm reaches it, and so does Haskell, as StgToCmm emits the same check (wordAligned in GHC.Cmm.Info). On x86-64 the assembler relocates the same jump as R_X86_64_PLT32, and the object links. This rests on master's code read (addAlignmentCheck's JXX_GBL; wordAligned) and on a compiler of master's code given an i386 target description through -B, with GNU as and ld 2.42. For a .cmm procedure loading the info pointer of a gcptr, at -O0 -fPIC -dynamic -falignment-sanitisation, it printed jne stg_badAlignment_entry, which as --32 relocated as R_386_PC32, while an ordinary jump to stg_gc_noregs became jmp *stg_gc_noregs@got(%eax); ld -m elf_i386 -shared, given a stub shared object defining the symbol, warned "relocation against `stg_badAlignment_entry' in read-only section `.text'" and "creating DT_TEXTREL in a shared object", and with -z text failed with "read-only segment has dynamic relocations". On x86-64 a Haskell module under -fPIC -falignment-sanitisation held the same jne at -O0 and -O1. Haskell was not compiled for i386, and nothing was run. - getCondCode in GHC.CmmToAsm.X86.CodeGen, its last case (BUG, ISSUE 28222 section 2.18: any comparison but the floating-point ones comes there, whatever its operands' type, and Cmm lint checks a MachOp's operands by width alone). A hand-written Cmm integer comparison of two floating-point values, as x != y on two float64 values (MO_Ne W64) rather than %fne, then reaches condIntCode, whose CMP at the operands' format prints as ucomisd or ucomiss and whose CondCode is not marked floating-point, so genCondBranch' emits the condition's one jump and no parity test: wrong code on i386 and x86-64 at -O0 and -O, a NaN against 1.0 taking the branch for equal. The value form, through condIntReg from getRegister''s case for MO_Ne, is the same. Against 0 condIntCode' emits a TEST at an integer format on the floating-point register, and for a load against a literal a CMP with the literal as an immediate, which GNU as rejects, a failed compilation. No Haskell program reaches it, StgToCmm emitting MO_F_Eq and its siblings for floating-point operands, and no Cmm file of master's rts/ or libraries/ compares floating-point values. This rests on master's code read (getCondCode, condIntCode', genCondBranch', lintCmmExpr and machOpArgReps in GHC.Cmm.Lint, the Cmm parser's != as MO_Ne) and on a compiler of master's code on x86-64 and, given an i386 target description through -B, for i386. On x86-64, for if (x != y) on float64 arguments under -dcmm-lint, it printed ucomisd %xmm2,%xmm1 and jne at -O and ucomisd and je at -O0, and a program calling the procedure took the branch for equal for a NaN against 1.0, where %fne took the one for unequal, at -O0 and -O; return (x != y) gave ucomisd and setne alone; x != 0 gave testq %xmm1,%xmm1 and float64[p] != 1.0 ucomisd $1.0,(%r14), at -O0 and -O, which GNU as 2.42 rejected. For i386, if (x != y) gave ucomisd and jne alone at -O and je at -O0, and the two literal forms were rejected by i686-linux-gnu-as --32. - genXchg and the cmpxchg_code of genAtomicRMW in GHC.CmmToAsm.X86.CodeGen, one at each (BUG, ISSUE 28222 sections 2.16 and 2.15: where dst_r is a register that the amode names, as in (x) = prim %xchg64(x, y) or (x) = prim %fetch_and64(x, y) in a loop of hand-written Cmm where x is the address after Cmm sinking (-fcmm-sink, on at -O1 and -O2), a MOV into dst_r from another register overwrites the address before the XCHG, or the loop's CMPXCHG, uses it). On x86-64, where getSimpleAmode is getNonClobberedAmode, which returns an amode of virtual registers as it is, this is wrong code: at every width for And, Nand, Or and Xor among the atomic operations, as Add and Sub write dst_r after their XADD, and at 64 bits for the exchange, whose XCHG the assembler rejects at 8, 16 and 32 bits whatever its operands (the BUG at pprInstr's case for XCHG in GHC.CmmToAsm.X86.Ppr); on i386 getSimpleAmode computes the address into a fresh register. StgToCmm's result local is never the address's, and the RTS's Cmm has no such line, so only other hand-written Cmm reaches it. This rests on master's code read and on a compiler of master's code at -O: in a loop, (x) = prim %fetch_and64(x, y) assembled to a lock cmpxchgq through the overwritten register, and a program calling (x) = prim %xchg64(x, y) in a loop, whose code holds xchgq (%rbx),%rbx, crashed with a segmentation fault, where with a fresh result local it printed the old and new values. In the loop, (x) = prim %fetch_and8(x, y) assembled to movb %al,%bl before lock cmpxchgb %dl,(%rbx), and its 16-bit and 32-bit forms likewise, while (x) = prim %xchg8(x, y) printed xchgb (%rax),%rax, which the assembler rejected. At -O0 the line's arguments are copied to fresh locals first, and the code is right. Cmm sinking replaces x's copy by x, or by the right-hand side of x's one assignment where it moves that assignment into the line: with one assignment from a load followed by a store, the code held xchgq (%rsi),%rsi; with one from a load and a test of x before the line, it was wrong also at -O0 -fcmm-sink and right at -O -fno-cmm-sink; and two assignments that -O merges into one gave right code. - pprInstr's case for XCHG in GHC.CmmToAsm.X86.Ppr (BUG, ISSUE 28222 section 2.17: pprFormatOpReg prints the register operand at the word's format, not at the exchange's). At 8 and 16 bits, and on x86-64 at 32, the register's name then does not match the instruction's suffix, and the assembler rejects the module whatever the operands, at -O0 as at -O1. StgToCmm emits MO_Xchg at the word's width alone, and no Cmm in the tree calls a narrower %xchg, so only other hand-written Cmm reaches it. This rests on master's code read (pprFormatOpReg, which prints its register at archWordFormat; genXchg, which gives XCHG the exchange's format; StgToCmm's MO_Xchg) and on a compiler of master's code on x86-64 and, given an i386 target description through -B, for i386. For (r) = prim %xchg8(p, y) and its wider forms in hand-written Cmm, at -O0 and -O1 on x86-64, it printed xchgb (%rax),%r14, xchgw (%rax),%r14 and xchgl (%rax),%r14, which GNU as 2.42 and llvm-mc 18 rejected, and xchgq (%rax),%r14, which they assembled; at -O1 for i386, xchgb (%eax),%ecx and xchgw (%eax),%ecx, rejected, and xchgl (%eax),%ecx, assembled. - pprInstr's cases for VPABS and VSQRT in GHC.CmmToAsm.X86.Ppr, with PABS beside them (BUG, ISSUE 28222 section 1.10: pprFormatOpReg prints the destination at the word's format, not at the vector's). At 256 and 512 bits the source is then printed as a ymm or zmm register and the destination as an xmm one, and the assembler rejects the module, a failed compilation, from Haskell at -O0 and -O on x86 and x86-64, for the 256-bit and 512-bit vector square roots and integer absolute values: VSQRT's under AVX and VPABS's under AVX-512VL, and PABS's, SQRT's, PSUB's and PCMPGT's where the BUG at getRegister''s case for MO_VS_Abs in GHC.CmmToAsm.X86.CodeGen gives them such a format. At a scalar or 128-bit format the destination is an xmm register anyway. This rests on master's code read (pprFormatOpReg, which prints its register at archWordFormat; ppr_reg_float, which prints a vector register as a ymm or zmm one at a format of 256 or 512 bits alone) and on a compiler of master's code on x86-64 and, given an i386 target description through -B, for i386. On x86-64 it printed vsqrtpd %ymm1,%xmm1 at -O and vsqrtpd %ymm1,%xmm0 at -O0 for sqrtDoubleX4# under -mavx2, and vpabsq %ymm1,%xmm1 at -O and vpabsq %ymm1,%xmm0 at -O0 for absInt64X4# under -mavx512f -mavx512vl, which GNU as 2.42 rejected, and vsqrtpd %xmm1,%xmm1 for sqrtDoubleX2#, which it assembled; for i386, vsqrtpd %ymm0,%xmm0 for sqrtDoubleX4# under -mavx2 at -O0 and -O1, which i686-linux-gnu-as --32 rejected. - takeRegRegMoveInstr in GHC.CmmToAsm.X86.Instr, its case for MOV (BUG, ISSUE 28217: the guard tests the move's format alone, so a MOV of a scalar format from a vector register, which vector_float_extract emits to extract lane 0, is returned as a register-to-register move). In buildGraph in GHC.CmmToAsm.Reg.Graph, slurpConflicts adds a coalescing edge for every such move, usable where the vector dies, and slurpReloadCoalesce one between each reload of a spill slot and the register last spilled to it, so a vector's virtual registers before and after its spills join one class with the scalar's; the graph allocators' coalescing renames the class to the scalar's register, and the vector's reloads then load 8 bytes, by movsd, which zeroes the upper lane that a later movhlps reads. This is wrong code on x86-64 under -fregs-graph and -fregs-iterative, at -O1 and -O2, from Haskell that extracts lane 0 of a vector that is spilled and reads its other lane later. The linear allocator is spared: raInsn in GHC.CmmToAsm.Reg.Linear gives the move's destination the source's location only where the source dies, and renames no reload of the vector. This is not GHC #27993, 16-byte spills into 8-byte slots, and GHC #27619, on formats in the liveness fixpoint, is another mechanism. This rests on master's code read (takeRegRegMoveInstr; vector_float_extract's MOV FF32 and MOV FF64 for lane 0; buildGraph, slurpConflicts and slurpReloadCoalesce; raInsn) and on a compiler of master's code on x86-64. A program whose function unpacks the sum of a DoubleX2# of (a, b) and a broadcast of a, calls ldexp through an unsafe foreign call and then uses both lanes printed (8.0,-6.0,0.0) at -O1 and -O2 under -fregs-graph and -fregs-iterative, where it printed (8.0,-6.0,26.0) at -O2 under the linear allocator and at -O0 under both graph allocators. Its -fregs-graph assembly at -O2 spilled the sum by movupd and reloaded it by movsd before movhlps, and -ddump-asm-regalloc-stages listed as coalesced into the Double's virtual register the sum's registers before and after its spills, the one moved by movsd and the one read by movhlps among them. - shortcutJump's case for JMP_TBL in GHC.CmmToAsm.X86.Instr (BUG, ISSUE 28218: updateBlock applies the mapping once, where the case for JXX follows the chain of shortcuts, as shortBlockId does for the table's entries and shortcutWeightMap in GHC.CmmToAsm.CFG does for the CFG's edges). Where a block that a jump table targets is shortcut to a block that is shortcut in turn, the JMP_TBL's block list keeps a removed block while the CFG has the edge to the chain's end, and sanityCheckCfg panics ("Block list and cfg nodes don't match"), a failed compilation, under -dasm-lint or in a DEBUG compiler, on x86 and x86-64 under -fasm-shortcutting, not on Darwin; the emitted table follows the whole chain, so the code is right. Haskell reaches it too. The comment at apply_mapping in GHC.CmmToAsm, "shortcutJump should apply the mapping repeatedly", does not hold of a table's block list. This rests on master's code read (shortcutJump, shortcutStatic and shortBlockId, shortcutWeightMap, and the case for JMP_TBL of jumpDestsOfInstr, whose result sanityCheckCfg compares with the CFG) and on a compiler of master's code on x86-64: a .cmm procedure of eight switch cases, some of which reach their target through two blocks that end up a single jump each, panicked so ("missing edges") at -O2 -dasm-lint, at -O0 and -O1 with -fasm-shortcutting -dasm-lint and at -O2 -fregs-graph -dasm-lint, and compiled at -O2, at -O2 -fno-asm-shortcutting -dasm-lint and at -O0 -dasm-lint; at -O2 the table's entries went to the chains' ends. A Haskell function whose case on an Int# has seven alternatives, two of which call a local function that only calls a second one, which the third calls, panicked so at -O2 -dasm-lint and at -O0 and -O1 with -fasm-shortcutting -dasm-lint, and compiled at -O0 and -O1 with -dasm-lint alone and at -O2 -fno-asm-shortcutting -dasm-lint. - shortcutStatic in GHC.CmmToAsm.X86.Instr (BUG, ISSUE 28138: it retargets the first label of a CmmLabelDiffOff and keeps the second, which its comment says works for jump tables; since 84a087d5d5 (ISSUE 24016) a position-independent table's entries are relative to the label of the block that jumps through the table, in the procedure's section, and no longer to the table's label). An entry retargeted to a label in another section, an imported procedure's or, under -fsplit-sections, another procedure's, is a difference the assembler cannot resolve, and it rejects the module. This is reached under -fasm-shortcutting with -fPIC or -fPIE, on x86 and x86-64, not on Darwin, where shortcutting is off, and under -g only for a jump-only block to which -g adds nothing. Under -dynamic, which implies -fPIC and -fexternal-dynamic-refs, a jump to an imported procedure or to a procedure of a .cmm file goes through the GOT outside Windows, and canShortcut skips such a jump, so there it is reached only by a jump to another procedure of the same Haskell module under -fsplit-sections. The statement stands at shortcutStatic rather than at build_mapping in GHC.CmmToAsm, which maps a block to its jump's target in any section, as a jump may go to any label. This rests on master's code read (genSwitch, generateJumpTableForInstr, shortcutStatic, canShortcut, labelDynamic in GHC.Cmm.CLabel and wayGeneralFlags in GHC.Platform.Ways, and cmmNativeGen, which runs generateJumpTables before shortcutBranches), ISSUE 28138's record and a compiler of master's code: on x86-64, ISSUE 28138's T.hs, whose case tail-calls three procedures of another module, made GNU as 2.42 reject the module ("can't resolve U_a4_info - .Ln1") at -O2 -fPIC, -O2 -fPIE and -O1 -fPIC -fasm-shortcutting, and assembled at -O2, -O1 -fPIC, -O2 -fPIC -fno-asm-shortcutting and -O2 -fPIC -g; a .cmm procedure whose switch jumps to three procedures of its own file made the assembler reject it so ("can't resolve a1 - .Lc7") at -O2 -fPIC -fsplit-sections, for x86-64 and, given an i386 target description through -B and assembled with --32, for i386, and assembled without -fsplit-sections or with -fno-asm-shortcutting. -dynamic itself was tried on .cmm files alone, a Haskell module failing to compile under it, the compiler having no dynamic libraries; with the two flags it implies, at -O2 -fPIC -fexternal-dynamic-refs on x86-64, ISSUE 28138's T.hs assembled, with and without -fsplit-sections, its jumps to the other module's procedures going through the GOT; a module whose case tail-calls three procedures of its own made the assembler reject it ("can't resolve .text..LrGK_info - .Ln4") under -fsplit-sections, and assembled without it or with -fno-asm-shortcutting; and the .cmm procedure assembled under -fsplit-sections, for x86-64 and for i386, its jumps going through the GOT, as it did at -O2 -dynamic, with and without -fsplit-sections. Windows was not tried. - procToDwarf in GHC.CmmToAsm.Dwarf, its fallback for dwName (BUG, ISSUE 28222 section 2.10: show of a Label gives its unique as a number, where ppr gave the block's name). Under -g, the DIE of a procedure with no source note is then named by a number, such as L7133701809754871424, that no label of the assembly carries, where its DW_AT_low_pc names the block's label, such as .Lc1uU, and its linkage name is _blk_c1uU. This is only a misled reader of the debugging information, at -O0 and -O, from Haskell, on every target that emits DWARF; no effect on gdb was shown. 05550a5abc ("Avoid roundtrip through SDoc", 2020) put show where ppr of the label had given the c1uU form. This rests on master's code read (procToDwarf) and on a compiler of master's code on x86-64: for a module of three functions, a main and their local procedures, at -g -O, 9 of the 16 subprogram DIEs that readelf printed were named so, and at -g -O0, 3 of 19. - procToFrame in GHC.CmmToAsm.Dwarf (BUG, ISSUE 28222 section 1.3: dwFdeProc is the label of the procedure's entry block, and pprFrameProc in GHC.CmmToAsm.Dwarf.Types ends the frame description entry at that label's procedure end label, which X86's, PowerPC's, RV64's and LA64's pprBasicBlock print after the block itself, as for a block that may end up a procedure of its own). Under -g the entry then ends after the procedure's first block and leaves out the code and the rows of the procedure's other blocks, so that a debugger finds no frame description entry for a pc in them; a procedure of one block is spared. procToDwarf's subprogram DIE takes the same end, and so does mkDwarfARange's address range, which -fsplit-sections emits for each procedure; the compile unit's DW_AT_high_pc and, without -fsplit-sections, its one address range end after its last procedure's first block. This is wrong debugging information, reached under -g, -g1 included, at -O0 and -O1 alike, on the targets for which the compiler emits DWARF: x86, x86-64, 64-bit PowerPC with the ELFv2 ABI, RISC-V and LoongArch. This rests on master's code read (cmmDebugGen in GHC.Cmm.DebugBlock, which sets each DebugBlock's dblCLabel to its block's label; procToFrame, procToDwarf, mkDwarfARange and dwarfGen; pprFrameProc and pprDwarfInfoOpen; the four pprBasicBlock) and on a compiler of master's code on x86-64 and given 64-bit PowerPC ELFv2, RISC-V, LoongArch and i386 target descriptions through -B, with GNU as and readelf 2.42. On a Haskell module whose functions call C functions, for all but i386, and on a .cmm file of a procedure of four blocks and one of one block, for all five, at -O0 and -O1 under -g1 and -g, every frame description entry of a procedure of more than one block ended at the end of the procedure's first block, and every other one covered its procedure. On x86-64 at -O1 -g, readelf gave the entry of the module's first procedure the range 0x17 to 0x21, where the procedure's code runs from 0x18 to 0x7f, and its rows set_loc 0x30, 0x58, 0x66 and 0x71; it gave the procedure's DIE the same range and, under -fsplit-sections, its address range a length of 9 bytes; at -O0 -g, the compile unit's DW_AT_high_pc was 0x849, inside the last procedure, which runs from 0x840 to 0x88f. Linked and run under gdb, a trap in a C function called from a later block of a procedure gave a backtrace whose frame for that procedure lies at a pc no frame description entry covers, followed by a frame at pc 0; assembled from the same assembly with each entry's length rewritten to end at its procedure's end label, the backtrace ended at the procedure's frame. - pprFrameBlock in GHC.CmmToAsm.Dwarf.Types (BUG, ISSUE 28222 section 1.5: a point whose table differs from the one before gets a DW_CFA_set_loc even where it is the procedure's first). The state starts from the CIE's table, initUw in pprFrameProc, and the first point's set_loc names its label, minus 1 for a block with an info table, which is the frame description entry's own initial location; where the first point's table differs from the CIE's, as for a procedure entered with its arguments on the stack, whose Sp offset on entry is not 0, the entry opens with a set_loc to its own start. The DWARF standard says of DW_CFA_set_loc that the new location is always greater than the current one. This is wrong debugging information under -g, on x86-64 and i386, at -O0 and -O, from Haskell and Cmm: llvm-dwarfdump 18 refuses to decode such an entry into rows, where GNU readelf 2.42 prints its opcodes without a message; gdb was not tried. The BUG at procToFrame, on the entries' ranges, is another fault of the same entries. This rests on master's code read (pprFrameBlock and pprFrameProc) and on a compiler of master's code on x86-64 and given an i386 target description through -B. For a Haskell function of ten Int# arguments, at -g -O0 and -g -O, the function's entry, pc 0 to 0x1a, opened with DW_CFA_set_loc 0 and DW_CFA_def_cfa_offset 80, and llvm-dwarfdump --debug-frame stopped on it: "DW_CFA_set_loc with adrress 0x0 which must be greater than the current row address 0x0"; a module of functions entered with no arguments on the stack decoded without error. For a .cmm procedure of eight bits64 arguments, two of them on the stack, on x86-64, and one of two word arguments, both on the stack, for i386, assembled by i686-linux-gnu-as --32, at -g -O0 and -g -O, llvm-dwarfdump stopped the same way. - pprDwarfInfoOpen in GHC.CmmToAsm.Dwarf.Types, its case for DwarfSubprogram (BUG, ISSUE 28222 section 1.9: the DIE's DW_AT_low_pc is the procedure's entry minus 1, inside its info table). The offset, that of Note [Info Offset], lets gdb's lookup of a return address minus 1 find the function, and it is applied to every subprogram DIE. gdb sets a breakpoint on a function by its DIE, by break with the DIE's linkage name or by rbreak FILE:., at that low_pc, so its int3 overwrites the info table's last byte, which the garbage collector and a case on a constructor's tag read: under -g the program then crashes once a major collection reaches the function's closure, or takes the wrong branch on a tag. This is wrong debugging information, its effect under gdb a crash or a wrong result, at -O0 and -O1, from Haskell, shown on x86-64; break FILE:LINE sets the breakpoint at the entry. a4a6dc2a90 (2020, first released in 9.2.1) applied the offset to the subprogram DIE. Note [Info Offset], which says that the instruction pointer is expected never to end up inside the info table, now points here. With the BUG at mkBlock in GHC.Cmm.DebugBlock no DIE names the info label, so a breakpoint set by that symbol lies at the entry. This rests on master's code read (pprDwarfInfoOpen and Note [Info Offset]) and on a compiler of master's code on x86-64, with gdb, and given RISC-V, LoongArch and 64-bit PowerPC ELFv2 target descriptions through -B. For a module of f True = (), NOINLINE, and main = performMajorGC >> print (f True), built by ghc -g, the program printed (); under gdb, with break *0x4087af, f's DIE's low_pc and Main_f_info less 1, with break _blk_cFY, the DIE's linkage name, or with rbreak M.hs:., it received SIGSEGV in evacuate, while break *0x4087b0 stopped at the entry, after which the program printed (), and break M.hs:2 put the breakpoint at 0x4087b0; built at -O1 -g, a breakpoint at the low_pc of f's DIE gave the same SIGSEGV and one at the next address a normal exit. For a module of a data type of eight constructors, isH H = True, isH _ = False, NOINLINE, and main = print (isH H), the program printed True, and False under rbreak M.hs:. and under break *0x408a37, Main_H_con_info less 1, while break Main_H_con_info put the breakpoint at the symbol and the program printed True. Given the three descriptions, the low_pc of the DIE of a function f was its entry block's label minus 1 in the assembly, as on x86-64. - addDefaultUnwindings in GHC.CmmToAsm.Dwarf (BUG, ISSUE 28222 section 1.4: it gives every unwinding table that does not name Sp the CIE's initial rule for Sp, Sp+0, 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+0: rbp+0 on x86-64, where the table before it can give another offset, such as rbp+16 at the entry of a procedure two of whose arguments are on the stack. A debugger unwinding from there finds the wrong frame. Where such a row lies past a procedure's first block, the procedure's frame description entry leaves it out (the BUG at procToFrame), and no debugger consults it. 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: for a function of seven Int arguments calling labs, compiled at -O -g on x86-64, the worker's frame description entry gave rbp+16 at its entry and rbp+0 from the C call on. - dwarfReturnRegNo in GHC.CmmToAsm.Dwarf.Constants (BUG, ISSUE 11261: no case for 32-bit PowerPC or for 64-bit PowerPC with the ELFv1 ABI; dwarfRegNo has none for 32-bit PowerPC either). ncgDwarfEnabled holds under -g on ELF targets other than AArch64, so on these two the compiler can panic under -g on a module with code, with "dwarfReturnRegNo: Unsupported platform!", as ISSUE 11261 reports for 64-bit PowerPC. This rests on master's code read (initNCGConfig's ncgDwarfEnabled, and pprDwarfFrame, which prints the return register's number before any other register's) and on a compiler of master's code given a 64-bit PowerPC ELFv1 target description through -B, which panicked so on a Haskell module and on a .cmm file at -O -g, and on the module at -O0 -g, -O -g1 and -O0 -g1, and compiled the module at -O and, at -O -g, a module whose one binding is x = 5 :: Int, which has no code; given an ELFv2 one, it emitted .debug_info at -O -g, and given a 32-bit PowerPC one, it panicked so on a .cmm file at -O -g. - cmmDebugGen in GHC.Cmm.DebugBlock (BUG, ISSUE 28222 section 2.1: blockCtxs and scopeMap are maps keyed by CmmTickScope, whose Ord compares the scopes' uniques, and detRenameCmmTick in GHC.Cmm.UniqueRenamer leaves those uniques as they are under -fobject-determinism). The order of the top scopes and of each scope's nested scopes, and with it the order of the lexical-block DIEs that dwarfGen emits under -g, follows the unique supply, so under -g -fobject-determinism an object's .debug_info and its relocations differ between values of -dinitial-unique and -dunique-increment, against Note [Norms of the NCG] in GHC.CmmToAsm; the object's code, data and other sections, and the set of its DIEs' names, are the same. This is reached from Haskell at -O0, -O1 and -O2. This rests on master's code read (cmmDebugGen, blockContexts, the Ord instance of CmmTickScope in GHC.Cmm.Node, detRenameCmmTick, and procToDwarf and blockToDwarf in GHC.CmmToAsm.Dwarf, which keep the DebugBlocks' order) and on a compiler of master's code on x86-64 under -fobject-determinism, with -dinitial-unique=16777215 -dunique-increment=-1, as GHC's determinism test check-standalone.sh uses, against the default. For a module of a data type and a Data.Map fold, at -O0, -O1 and -O2 with -g, the objects differed in .debug_info and .rela.debug_info alone of ten sections compared; at -O1 readelf gave both the same DW_AT_name values in another order, each moved name a lexical block's; -ddump-debug showed the blocks in another order and nesting; and -ddump-cmm-raw showed the blocks under the same labels and their tick scopes under different uniques. Without -g the objects were identical. A --make build of seven modules at -O1 -g gave seven objects differing in .debug_info alone of six sections compared. Hand-written Cmm was not tried, and no target but x86-64. - mkBlock in GHC.Cmm.DebugBlock, local to cmmDebugGen (BUG, ISSUE 28222 section 1.8: dblCLabel is the entry block's local label, which procToDwarf in GHC.CmmToAsm.Dwarf makes the subprogram DIE's label). The case for DwarfSubprogram of pprDwarfInfoOpen in GHC.CmmToAsm.Dwarf.Types prints the label's C spelling, _blk_ and the unique, which no object defines, as the DIE's DW_AT_linkage_name, and externallyVisibleCLabel, False for a local block label, as its DW_AT_external. Under -g every subprogram DIE so carries a name that is no symbol and external 0, and gdb names and lists each Haskell function by that name: its bt gives the _blk_ name for a stop at a function's info label, info functions lists a static void function of the name, and info address of the info label says that the symbol is in a file compiled without debugging. This is wrong debugging information, at -O0 and -O1, from Haskell, on every target that emits DWARF. eebe1658cc (ISSUE 22792, first released in 9.12.1) replaced dblCLabel's info label by blockLbl label; the DIE's DW_AT_low_pc, that label minus 1, is the address the info label gave, the NCG defining the entry block's label right after the info label. This rests on master's code read (mkBlock, blockLbl in GHC.Cmm.BlockId, procToDwarf, pprDwarfInfoOpen, externallyVisibleCLabel and pprCLabelStyle in GHC.Cmm.CLabel) and on a compiler of master's code on x86-64 and given RISC-V, LoongArch and 64-bit PowerPC ELFv2 target descriptions through -B, with gdb. On x86-64, for main = pure () at -O0 -g, llvm-dwarfdump 18 gave main's DIE DW_AT_linkage_name ("_blk_cyK") and DW_AT_external (0x00), nm listed Main_main_info and no _blk_ symbol in the object or the program, and gdb, stopped by break Main_main_info, gave #0 _blk_cyK () in bt; for a module W of f True = () and a Main printing f True, at -O0 -g, gdb gave #0 _blk_cwA () in f, info functions _blk_ listed static void _blk_cwA(void);, and info address W_f_info said that W_f_info "is at 0x4088d8 in a file compiled without debugging"; at -O1 -g every subprogram DIE of the first module and of W had a _blk_ linkage name and external 0. Given the RISC-V description, W at -O0 -g, assembled by riscv64-linux-gnu-as, gave f's DIE the linkage name _blk_cwA and external 0, and given the LoongArch and ELFv2 ones the assembly did the same. - cmmDebugLink in GHC.Cmm.DebugBlock (BUG, ISSUE 28222 section 1.1: it drops a block missing from its labels with every block and procedure nested under it, and cmmDebugLabels declares missing a block that holds only meta instructions). Where such a block is a procedure's entry block, under -g dwarfGen emits no DIEs and no unwinding records for that procedure and those nested under it, and no section at all for a module whose procedures are all dropped so: the module's object then keeps only the debugging sections that the assembler makes from the .loc lines, and has no .debug_frame. Where such a block is the first of a tick scope inside a procedure, as for a local loop at -O0 on x86-64, dwarfGen emits none for the blocks of that scope. The first case is reached for an entry block that holds no more than moves of the arguments and a jump, which dropJumps in GHC.CmmToAsm.BlockLayout drops where block layout places the jump's target next. With -fcmm-control-flow off, the target can be the heap check: on x86-64 and 64-bit PowerPC at -O0, where the register allocator eliminates the moves, and on these and on i386, RISC-V and LoongArch at -O1 -fno-cmm-control-flow, where the Cmm sinking pass leaves the entry block only its jump. With the flag on or off, it can be the header of the procedure's loop, which has two predecessors, so that cmmCfgOpts does not merge it into the entry block: at -O1 and -O2 on 64-bit PowerPC, and on x86-64 under -fno-block-layout-cfg, where the register allocator eliminates the moves and sequenceBlocks places the header next. On x86-64 the default layout, sequenceChain, kept that jump in the runs below, and on i386, RISC-V and LoongArch such a procedure's entry block kept loads or copies of the arguments. Since eebe1658cc (ISSUE 22792) cmmDebugLink drops a missing block; before, it kept the block with no position. This rests on master's code read (cmmDebugLabels; cmmDebugLink's mapMaybe link; cmmDebugGen, which nests the other blocks of a tick scope and the blocks of its nested scopes, other procedures' among them, under the scope's first block; and dwarfGen, which emits nothing for no blocks) and on a compiler of master's code on x86-64 and given 64-bit PowerPC ELFv2 and ELFv1, i386, RISC-V and LoongArch target descriptions through -B. For a module whose one binding is mk n m = Just n, at -O0 -g it emitted no DWARF section for x86-64 and ELFv2, ghc -c leaving in the x86-64 object the .debug_info, .debug_line, .debug_aranges, .debug_abbrev and .debug_str of GNU as 2.42 and no .debug_frame, and five for RISC-V and LoongArch, where the entry block keeps two copies into temporaries; with -fcmm-control-flow it emitted five for x86-64 and ELFv2; and for x86-64 it emitted five at -O1 -g and none at -O1 -g -fno-cmm-control-flow. With two lambdas in mk, whose four procedures -ddump-debug at -O0 -g -fcmm-control-flow shows nested under mk's, it emitted none at -O0 -g for x86-64 and ELFv2, though each of the four keeps its stack check in its entry block; with a second binding whose entry block keeps its stack check, only that binding's DIEs and frame description entry, and for a binding whose local loop's first block holds only meta instructions, no DIE for the loop's blocks, for x86-64 at -O0 -g. For mk's module it emitted none at -O1 -g -fno-cmm-control-flow for ELFv2, ELFv1, RISC-V and LoongArch too, and none at -O0 -g for ELFv1; for i386, for a copy of the module that declares its own constructor, it emitted the DIE and frame description entry of one of its three procedures at -O1 -g -fno-cmm-control-flow and of all three at -O0 -g and at -O1 -g -fno-cmm-control-flow -fno-cmm-sink. For a module of three self-recursive Int loops, at -O1 -g it emitted them for its seven procedures for x86-64, RISC-V and LoongArch, and for four, the three workers' missing, for ELFv2, at -O2 -g and with -fno-cmm-control-flow too, and for x86-64 under -fno-block-layout-cfg; given the ELFv1 description it panicked in dwarfReturnRegNo (BUG #11261) on that module and emitted no DWARF section for a module of two Int# loops, at -O1 -g and -O2 -g; for i386 that module's two procedures kept theirs under -fno-block-layout-cfg too. - emitPrimOp in GHC.StgToCmm.Prim, its cases for the vector arithmetic, bitwise and FMA primops, VecAddOp to VecFNMSub (BUG, ISSUE 28220: they call no checkVecCompatibility, which the cases of VecBroadcastOp, VecPackOp, VecUnpackOp, VecInsertOp, the vector loads, stores and indexing primops and VecShuffleOp call). backendSimdValidity in GHC.Driver.Backend is IsValid for the native code generator on every target, so on a target whose code generator cannot compile a vector, VecAddOp, VecSubOp, VecMulOp, VecDivOp, VecQuotOp, VecRemOp, VecNegOp, VecAbsOp, VecSqrtOp, VecMinOp, VecMaxOp, VecAndOp, VecOrOp, VecXorOp, VecFMAdd, VecFMSub, VecFNMAdd and VecFNMSub reach it, and it panics where the check gives a sorry error, "SIMD vector instructions are not supported on this architecture" or, on AArch64, "256-bit wide SIMD vector instructions are not supported". This is a panic, a failed compilation, from Haskell, at -O0 and -O, on RISC-V ("Width too big! Cannot load: W128"), LoongArch ("Unknown width to load: W128"), PowerPC, 64-bit with the ELFv1 and ELFv2 ABIs and 32-bit ("PPC pprInstr: VecFormat"), and wasm32 ("someWasmTypeFromCmmType: unsupported CmmType Fx2V128" for a DoubleX2#) for any vector, and on AArch64 ("floatVecOp: invalid vector format", or "intVecOp: invalid vector format" for an integer vector) for a vector of 256 or 512 bits. Pointers at four of these panics, all but intVecOp's and someWasmTypeFromCmmType's, cite the BUG. This rests on master's code read (emitPrimOp's cases and checkVecCompatibility) and on a compiler of master's code given RISC-V, LoongArch, 64-bit PowerPC ELFv1 and ELFv2 and AArch64 target descriptions through -B: f a b = plusDoubleX2# a b panicked so at -O0 and -O on the first four, where f a = broadcastDoubleX2# a stopped with the sorry error; for AArch64, plusDoubleX4#, plusDoubleX8# and plusInt64X4# panicked so at -O0 and -O, where broadcastDoubleX4# stopped with the sorry error; given 32-bit PowerPC and wasm32 target descriptions over libraries of GHC.Prim alone, plusDoubleX2# panicked so at -O0 and -O. On x86-64 without -mavx, plusDoubleX4# stopped with a sorry error of GHC.CmmToAsm.X86.Instr's, "256-bit wide vectors require -mavx2". - initNCGConfig in GHC.Driver.Config.CmmToAsm, its field ncgProcAlignment, two statements (BUG, ISSUE 28222 section 1.7: the value of -fproc-alignment is not checked; BUG, ISSUE 23947: only X86's, RV64's and LA64's printers use it). A value that is not a power of 2 or is over 512 makes mkAlignment in GHC.Types.Basic, which their pprProcAlignment calls, panic ("mkAlignment: received either a non power of 2 argument or > 512"), a failed compilation, on x86, x86-64, RISC-V and LoongArch, from Haskell and Cmm, where the flag's parser could reject it; on AArch64, whose printer has its calls of pprProcAlignment commented out, on PowerPC, whose printer has none, and on wasm32, whose code generator does not read the field, the flag has no effect, which commit 1 adds to its entry in the users' guide and which ISSUE 23947, open, reports of the backends other than X86's. This rests on master's code read (the flag's intSuffix in GHC.Driver.Session, initNCGConfig, the three pprProcAlignment, AArch64's printer and PowerPC's, and the modules of GHC.CmmToAsm.Wasm, none of which names ncgProcAlignment), on ISSUE 23947's record and on a compiler of master's code on x86-64 and given i386, RISC-V, LoongArch, AArch64, 64-bit PowerPC ELFv1 and ELFv2 and 32-bit PowerPC target descriptions through -B. On x86-64, -fproc-alignment=0, 3, 1024 and -4 each made it panic so on a .cmm procedure and a Haskell module at -O1, and 3 on the module at -O0 and -O2 too, while 1, 16 and 512 compiled; for a .cmm procedure at -O1, 0 made it panic so for i386, RISC-V and LoongArch and compiled for AArch64 and the three PowerPC targets, whose assembly at 64 was that without the flag, where i386 added .align 64 and RISC-V and LoongArch .balign 64. - pprNatCmmDecl in GHC.CmmToAsm.RV64.Ppr and GHC.CmmToAsm.LA64.Ppr, one BUG at each (BUG, ISSUE 28222 section 4.5: pprProcAlignment is printed before the case on topInfoTable, each of whose alternatives starts with pprSectionAlign's section directive). The .balign of -fproc-alignment then applies to the section current where it is printed, the one the declaration before left current, such as the .data of a closure or an SRT, and the procedure's own section gets only its .balign 8, so for a value over 8 the flag does not align a procedure that data precedes, nor, each procedure being in a section of its own, any under -fsplit-sections. There is no incorrect result, crash, panic or assembler error: the flag fails to align, which defeats its use, stable code placement for measurements, on RISC-V and LoongArch, from Haskell, the printer being the same at every optimisation level. b56d737974 (ISSUE 20758, 2023-03-29, first released in 9.8.1) removed such a directive before the case from GHC.CmmToAsm.X86.Ppr, whose pprNatCmmDecl prints the alignment after pprSectionAlign; the RISC-V printer, from 1c479c01d9, and the LoongArch one, from 652cba7ee7, keep the old order. This rests on master's code read (the three pprNatCmmDecl) and on a compiler of master's code on x86-64 and given RISC-V and LoongArch target descriptions through -B, with GNU as and ld 2.42. Given the RISC-V description, for main = main at -fproc-alignment=64, the second .balign 64 came after the SRT's .section .data, and in the output of riscv64-linux-gnu-ld -shared ZCMain_main_info lay at 0x4c0, its info table of 16 bytes at 0x4b0, off 64, where the first procedure's table lay at 0x440; given the LoongArch description ZCMain_main_info lay at 0x548, its table at 0x538. For a module of f x = x and g x y = y, whose f has its closure in .data, g's info table lay at linked 0x370 for RISC-V and 0x368 for LoongArch, and on x86-64 ghc -c put both info tables on 64. Under -fsplit-sections objdump -h gave the module's .text.G_f_info and .text.G_g_info the alignment 2**3 for RISC-V and LoongArch and 2**6 on x86-64. The other statements: - The comment at mkRegRegMoveInstr, in GHC.CmmToAsm.X86.Instr, says that its move clears the upper part of the register. A TODO says that for a float or a double it is MOV FF64, printed movsd, which keeps the destination's upper half. - invertCondBranches inverts a jump only after an integer comparison. A TODO says that maybeInvertCond's complement on the flags is as sound after a floating-point one. - pprBasicBlock in GHC.CmmToAsm.X86.Ppr aligns, past a procedure's start, only a block with an info table (TODO, ISSUE 27668). - condIntCode' tests a value against zero even on a path where the instruction computing it has set ZF and SF from it, as on the back edge of a loop that counts down: it gets only the comparison, and another path into the test, such as the loop's entry, may set no flags. Only a condition that reads ZF and SF alone could use the flags of a dec, which writes OF and leaves CF where TEST clears both (TODO, ISSUE 27738). - The header of GHC.CmmToAsm.Reg.Graph.Coalesce says, as a TODO, that no module imports it, and that its pass, which ran before graph allocation (-fregs-graph), has had no caller since 2007, when it was taken out of the pipeline in favour of the coalescing that GHC.Data.Graph.Color.colorGraph does. - Note [Unsafe foreign calls clobber caller-save registers] in GHC.Cmm.Node points to the BUG at callerSaves. - Note [Updating the CFG during CodeGen] in GHC.CmmToAsm.Monad, on what a caller of getNonClobberedAmode must guard against, cites the BUGs at genXchg and at genAtomicRMW's cmpxchg_code. - The comment in cmmDebugLabels, in GHC.Cmm.DebugBlock, on the blocks it declares missing, points to the BUG at cmmDebugLink. - Note [Info Offset] in GHC.CmmToAsm.Dwarf.Types, on the offset of a subprogram DIE, points to the BUG at pprDwarfInfoOpen. - The panics on a vector's width or format in the CmmLoad cases of getRegister' in GHC.CmmToAsm.RV64.CodeGen and GHC.CmmToAsm.LA64.CodeGen, in pprInstr's case for LD in GHC.CmmToAsm.PPC.Ppr and in floatVecOp in GHC.CmmToAsm.AArch64.CodeGen point to the BUG at emitPrimOp's vector arithmetic primops. - The comment at getRegister''s case for MO_V_Insert 2 W64, in GHC.CmmToAsm.X86.CodeGen, points to the BUG at its case for MO_V_Broadcast. - The comment at getRegister''s case for MO_V_Extract 2 W64, in GHC.CmmToAsm.X86.CodeGen, points to the BUG at iselExpr64's last clause there. Assisted-by: Claude Opus 5.5 - - - - - f4c4e448 by Mikolaj Konarski at 2026-11-29T17:57:58+01:00 State the NCG's norms and where a branch's likely side is known Of what anyone working with the NCG needs, this commit serves "The norms and principles that apply to the NCG, whether each is agreed or only proposed, and which trade-offs are acceptable." and "How to write a test for a change to the NCG: where such tests live, what hand-written Cmm may contain, and how a test is confined to a target or a way or marked as a known failure." Comments only; the generated code is the same. Note [Norms of the NCG], in GHC.CmmToAsm, states two norms that GHC's own documents and testsuite hold the native code generator to, and what each means for a change. Under -fobject-determinism the output is to be bit-for-bit the same for the same inputs, so an order taken from uniques is a question for review. The testsuite passes -dcmm-lint by default, so a .cmm file that a test compiles with the ghc program must be one that Cmm lint accepts, unless the test turns the lints off. Note [Where a branch's likely side is known], in GHC.CmmToAsm.CFG, says where it is known which side of a conditional branch is likely: where the branch is made, as for heap and stack checks; upstream, and not carried down, for constructor-tag tests; and nowhere, for the rest, to which static prediction applies its heuristics on loop exits and equality tests where the branch is two-way and has no back edge, and its back edge rule where the branch has both a back edge and another edge. It also states the trade-offs kept with that knowledge, each with its reason: conditions inverted so that the true side falls through where it has one predecessor, even where the false side is likely if that side has more than one, 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 - - - - - ccd32ec2 by Mikolaj Konarski at 2026-11-29T17:57:58+01:00 Rewrite the NCG's overview Note Of what anyone working with the NCG needs, this commit serves "Comments and Notes that are true of the code they describe.", "Which targets go through the NCG, which of its parts each target uses, and what the NCG takes from the Cmm pipeline, StgToCmm and the RTS.", "The NCG's passes in the order they run, and what each requires of the one before.", "Which dump flag shows the output of which pass, and how to read each dump.", "The invariants the code depends on.", "What each MachOp and each Cmm construct means, precisely enough to write a code generator from: a shift by the width or more, the upper bits of a value narrower than its register, what a foreign call may clobber.", "What the NCG leaves to the assembler and the linker: which operand ranges a code generator checks and which only the assembler rejects, which branches the NCG lengthens, and which assemblers its output is written for.", "How to build and test a change to the NCG: which stage's compiler runs the changed code, which builds check the compiler's assertions, and which test directories and testsuite ways exercise the NCG.", "Which flags and build settings change what the NCG emits, such as `-g`, `-fPIC`, `-dynamic` and `-fproc-alignment`, and which of them the tests run with.", "What the tests cover and what they do not: which targets CI runs natively, which paths have few or no tests, and which performance test exercises which pass." and "How to measure a change to the NCG: which benchmarks exercise which parts of the NCG and which barely exercise it; which tools run them and compare two compilers' results, how to set them up and where to get them; how noisy each benchmark is; which counter to trust; and what besides the compiler moves a result, such as the host, the environment and how the baseline was built." Comments only; the generated code is the same. Note [Native code generator], the module header of GHC.CmmToAsm, named CmmStmts, cmmCodeGen, targetDoubleSize and smStablePtrTable, which nothing defines, and machine-independent optimisations "defined below", which are in GHC.Cmm.GenericOpt. This commit rewrites it. The Note now says: - which targets go through cmmNativeGen, that wasm32 has a generator of its own, and which back end the other targets get by default; - what the Cmm pipeline returns, and what the NCG takes from StgToCmm and the RTS; - the interfaces through which the machine-independent parts access a target, and what only some targets have; - the passes, in the order cmmNativeGen runs them, with the flags that turn them on and the dump flags that show their output, and, at step 4, what instruction selection must ensure; - where the NCG's uniques come from; - what the assembler and the linker do after it; - the flags, testsuite directories and benchmarks for working on the NCG. For detail it cites the Notes and labelled statements of the preceding commits. Assisted-by: Claude Opus 5.5 - - - - - deade80c by Mikolaj Konarski at 2026-11-30T01:40:54+01:00 Propose two principles for the NCG Of what anyone working with the NCG needs, this commit serves "The norms and principles that apply to the NCG, whether each is agreed or only proposed, and which trade-offs are acceptable." Comments only; the generated code is the same. Note [Proposed principles of the NCG], in GHC.CmmToAsm, puts two principles to GHC's developers, of which it says that the native code generator does not keep the second: - correctness first: semantic correctness is not traded for a measured gain that an incorrect form gives by accident, until a form with both has been looked for and the trade agreed in review; - one TODO set: a departure from correctness that is left in place is marked TODO, as a member of one set that is accepted for now and re-investigated together. No other commit cites the Note but the one adding the README, whose benchmarking section cites it in one sentence, so this commit can be dropped with that sentence. Assisted-by: Claude Opus 5.5 - - - - - d3305f87 by Mikolaj Konarski at 2026-12-01T00:20:13+01:00 Add a README to the NCG's directory Of what anyone working with the NCG needs, this commit serves "An order in which to read the NCG's Notes.", "One place where the terms the NCG's comments use are defined.", "One small function followed through the NCG's dumps, in the order of its passes.", "Which dump flag shows the output of which pass, and how to read each dump.", "Which parts of the NCG were examined for bugs, half-done work and likely changes, and which were not.", "What to ask of a merge request that changes the NCG, by the kind of change: which invariants it must keep, and which tests and measurements should come with it.", "The invariants the code depends on.", "How to find the pass at fault for a miscompilation or a compiler panic, and how to reduce the case to a Cmm test.", "What else must change when a MachOp, an instruction, a register or a relocation is added or changed.", "How to write a test for a change to the NCG: where such tests live, what hand-written Cmm may contain, and how a test is confined to a target or a way or marked as a known failure.", "How to measure a change to the NCG: which benchmarks exercise which parts of the NCG and which barely exercise it; which tools run them and compare two compilers' results, how to set them up and where to get them; how noisy each benchmark is; which counter to trust; and what besides the compiler moves a result, such as the host, the environment and how the baseline was built." and "The NCG's own compile-time cost: which passes are expected to be linear in the size of their input, and where they are not." Documentation only; the generated code is the same. compiler/GHC/CmmToAsm/README.md is a way in for anyone working with the native code generator, whether reading its output and dumps, tracking a fault to its pass, reviewing or making a change, or maintaining it. It says what to read and what to do. Its sections: - Where to start reading: three Notes of GHC.CmmToAsm, then Notes on the passes, each with its module, in the overview's order. - Vocabulary: the terms the NCG's comments use, each with where it is defined or used. - Finding the pass at fault: for a wrong result or a panic, the oracles to compare with, the flags that switch a pass off or swap it, the lints, and how to cut a case down to a Cmm test. - One function through the dumps: a small loop compiled at -O on x86-64, with an excerpt for each dump flag in the overview's list of passes but -ddump-asm-regalloc-stages and -ddump-asm-conflicts, which print nothing under the linear allocator. - Reviewing a change: questions to ask of a change by its kind, each citing the Note or comment it rests on. - Benchmarking a change, advice opening with its known limitations and the two compilers a build makes, in three parts: the generated code: what to count, which benchmark suites to use, tasty-papi serving the packages' benchmarks, which suites detect which kinds of change, why nofib gains less than the packages and is not to be relied on much, GHC's own tests as benchmarks, how the packages' benchmarks and nofib can count, the settings that move the counts, the RTS fix of ISSUE 28060 in MR 16891, which removes most of nofib's worst noise, how to tell a move from noise, what a -O0 figure measures, and losses and gains not to be taken at face value; compilation: what a build of the change measures for free, what to add for more and why GHC's tests rather than nofib's compiles, which instruments serve each kind of change, noise in practice, how to size an effect, and the figures' known limitations; and the asymptotics of compilation: unpublished scaling probes, programs generated at growing sizes, what they showed on the series, and that they show an effect's existence, not only its scale. - What the labelled statements cover: which parts of the NCG they were first written from, and which were left out. The excerpts are cut from the dumps of one compilation by a compiler built from master at 37ad471050: each of their lines but "..." is a line of a dump, in the dump's order, with tabs replaced by spaces. The benchmarking section's advice rests on figures measured on MR 16891's series, 62 commits, nearly all changing the NCG, each built and measured against its parent on one x86-64 Linux machine, and, for the noise, ten commits that change comments only and, for the generated code's, the 24 of the 62 whose messages state the same code. Every Note, function, module, flag and test the README names exists at this commit, and every path but those under _build, which exist only in a build tree. The overview, Note [Native code generator], now ends by pointing to the README. Assisted-by: Claude Opus 5.5 - - - - - 63 changed files: - compiler/CodeGen.Platform.h - compiler/GHC/Cmm/CLabel.hs - compiler/GHC/Cmm/DebugBlock.hs - compiler/GHC/Cmm/Info.hs - compiler/GHC/Cmm/Info/Build.hs - compiler/GHC/Cmm/Node.hs - compiler/GHC/Cmm/Parser.y - compiler/GHC/Cmm/Reg.hs - compiler/GHC/Cmm/Sink.hs - compiler/GHC/Cmm/Utils.hs - compiler/GHC/CmmToAsm.hs - compiler/GHC/CmmToAsm/AArch64/CodeGen.hs - compiler/GHC/CmmToAsm/BlockLayout.hs - compiler/GHC/CmmToAsm/CFG.hs - compiler/GHC/CmmToAsm/CFG/Weight.hs - compiler/GHC/CmmToAsm/Dwarf.hs - compiler/GHC/CmmToAsm/Dwarf/Constants.hs - compiler/GHC/CmmToAsm/Dwarf/Types.hs - compiler/GHC/CmmToAsm/Format.hs - compiler/GHC/CmmToAsm/Instr.hs - compiler/GHC/CmmToAsm/LA64/CodeGen.hs - compiler/GHC/CmmToAsm/LA64/Instr.hs - compiler/GHC/CmmToAsm/LA64/Ppr.hs - compiler/GHC/CmmToAsm/Monad.hs - compiler/GHC/CmmToAsm/PIC.hs - compiler/GHC/CmmToAsm/PPC/CodeGen.hs - compiler/GHC/CmmToAsm/PPC/Instr.hs - compiler/GHC/CmmToAsm/PPC/Ppr.hs - + compiler/GHC/CmmToAsm/README.md - compiler/GHC/CmmToAsm/RV64/CodeGen.hs - compiler/GHC/CmmToAsm/RV64/Ppr.hs - compiler/GHC/CmmToAsm/Reg/Graph.hs - compiler/GHC/CmmToAsm/Reg/Graph/Base.hs - compiler/GHC/CmmToAsm/Reg/Graph/Coalesce.hs - compiler/GHC/CmmToAsm/Reg/Graph/Spill.hs - compiler/GHC/CmmToAsm/Reg/Graph/SpillCost.hs - compiler/GHC/CmmToAsm/Reg/Graph/TrivColorable.hs - compiler/GHC/CmmToAsm/Reg/Graph/X86.hs - compiler/GHC/CmmToAsm/Reg/Linear.hs - compiler/GHC/CmmToAsm/Reg/Linear/AArch64.hs - compiler/GHC/CmmToAsm/Reg/Linear/Base.hs - compiler/GHC/CmmToAsm/Reg/Linear/FreeRegs.hs - compiler/GHC/CmmToAsm/Reg/Linear/JoinToTargets.hs - compiler/GHC/CmmToAsm/Reg/Linear/StackMap.hs - compiler/GHC/CmmToAsm/Reg/Liveness.hs - compiler/GHC/CmmToAsm/Reg/Regs.hs - compiler/GHC/CmmToAsm/Reg/Target.hs - compiler/GHC/CmmToAsm/Wasm/FromCmm.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/CmmToC.hs - compiler/GHC/Driver/Config/CmmToAsm.hs - compiler/GHC/Platform/Reg.hs - compiler/GHC/Platform/Reg/Class.hs - compiler/GHC/StgToCmm/Monad.hs - compiler/GHC/StgToCmm/Prim.hs - docs/users_guide/debug-info.rst - docs/users_guide/debugging.rst - docs/users_guide/phases.rst - docs/users_guide/using-optimisation.rst - docs/users_guide/using.rst The diff was not included because it is too large. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4d67151e8b0ab4ed2c01f258831951c... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/compare/4d67151e8b0ab4ed2c01f258831951c... 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)