From 7734e9656fd681fa978b3803a7ec86e4314d0f3b Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 20 Nov 2026 20:52:34 +0100 Subject: [PATCH 1/3] IC: compilerprocs, type infos and consts are no liveness roots The merge stage's liveness walk only sees cnif-marked names, so every definition whose uses it could not see had to be a root: * compilerprocs (named at sem time, so unmarked) and `extern:` procs: their names are now marked like any other routine's. A `cgsym` whose caller writes the name verbatim records an invisible use (`cuse`) of the proc being generated, or a module root at the top level: the same demand-driven rule as whole-program codegen. * V1/V2 type infos and consts were `'d'` data roots, and V1 init procs ran from every DatInit. They are `'u'` units now with marked uses; a V1 init is called from a same-named DatInit unit, so it runs exactly when its type info is live. Discriminant checks and deepCopy get explicit edges to the V1 info whose init fills what they read. Release build of the compiler: IC minus classic goes from +616 KB to +416 KB (.text +417 KB -> +268 KB, .bss +53 KB -> +1.6 KB). A hello world: 116 KB -> 57 KB text (classic: 53 KB). cnif format 7 -> 8. `-d:icWhyLive` + `IC_WHY_LIVE=name,...` prints why the merge keeps a name. Co-Authored-By: Claude Opus 5.5 --- compiler/ccgexprs.nim | 13 ++-- compiler/ccgstmts.nim | 5 +- compiler/ccgtypes.nim | 107 +++++++++++++++++++++++------ compiler/cgen.nim | 31 ++++++++- compiler/cgendata.nim | 9 +++ compiler/cnif.nim | 98 ++++++++++++++++++++++++-- tests/ic/mdcelive.nim | 40 +++++++++++ tests/ic/tdcelive.nim | 25 +++++++ tests/ic/tdceliverefc.nim | 28 ++++++++ tests/ic/tdceliverefc_temp.nim.cfg | 2 + 10 files changed, 323 insertions(+), 35 deletions(-) create mode 100644 tests/ic/mdcelive.nim create mode 100644 tests/ic/tdcelive.nim create mode 100644 tests/ic/tdceliverefc.nim create mode 100644 tests/ic/tdceliverefc_temp.nim.cfg diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 3ce87a3341fba..1237ba38510f9 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -3594,9 +3594,10 @@ proc genConstHeader(m, q: BModule; p: BProc, sym: PSym) = getModuleDllPath(q, sym), '"' & sym.loc.snippet & '"') else: + # unmarked: a name at the artifact's top level would be a liveness root var headerDecl = newBuilder("") headerDecl.addDeclWithVisibility(Extern): - headerDecl.addVar(kind = Local, name = sym.loc.snippet, + headerDecl.addVar(kind = Local, name = stripCnifMarks(sym.loc.snippet), typ = constType(getTypeDesc(m, sym.loc.t, dkVar))) m.s[cfsData].add(extract(headerDecl)) if sfExportc in sym.flags and p.module.g.generatedHeader != nil: @@ -3614,14 +3615,16 @@ proc genConstDefinition(q: BModule; p: BProc; sym: PSym) = # Each `cg` process that demands this const emits its definition # (emit-everywhere). Always declare it first (the data analogue of a proc # prototype) so a TU whose copy the merge stage drops still has a valid - # declaration; wrap the definition as a droppable `'d'` unit the merge - # stage assigns to a single owner. + # declaration; wrap the definition as a droppable `'u'` unit the merge + # stage assigns to a single owner. It is no root (its uses are marked) + # unless C code may name it. let cname = stripCnifMarks(actualConstName) var decl = newBuilder("") decl.addDeclWithVisibility(Extern): - decl.addVar(kind = Local, name = actualConstName, typ = td) + decl.addVar(kind = Local, name = cname, typ = td) q.s[cfsData].add(extract(decl)) - q.s[cfsData].add(cnifDefDirective(cname, "d", icNifName(q, sym))) + q.s[cfsData].add(cnifDefDirective(cname, + if sfExportc in sym.flags: "d" else: "u", icNifName(q, sym))) q.s[cfsData].add(extract(data)) q.s[cfsData].add(cnifEndDefs()) q.icDataDefs.add (cname, icNifName(q, sym)) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index 1580855a83d57..af85685867753 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -1897,7 +1897,10 @@ proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType, field: PSym) = var t = skipTypes(objtype, abstractVar) assert t.kind == tyObject - discard genTypeInfoV1(p.module, t, a.lode.info) + let ti = genTypeInfoV1(p.module, t, a.lode.info) + if p.config.cmd == cmdNifC: + # the discriminator table below is filled by the type info's init + p.s(cpsStmts).add(cnifUsesOf(ti)) if not containsOrIncl(p.module.declaredThings, field.id): p.module.s[cfsVars].addDeclWithVisibility(Extern): discriminatorTableDecl(p.module, t, field, p.module.s[cfsVars]) diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index f1f497307df6b..f8a9ea7c9a754 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -144,6 +144,17 @@ proc fillBackendName(m: BModule; s: PSym) = s.locImpl.snippet = markCName(result) else: s.locImpl.snippet = result + elif m.config.cmd == cmdNifC and not m.hcrOn and s.kind in routineKinds and + sfImportc notin s.flags and + (sfExportc notin s.flags or sfCompilerProc in s.flags) and + not hasCnifMarks(s.loc.snippet) and + allCharsInSet(s.loc.snippet, IdentChars): + # A C name from an `extern:` pragma (most of the stdlib's `rtl` procs) or + # of a compilerproc is set at sem time. Mark it too: otherwise the merge + # stage's liveness walk cannot see its uses and has to keep every such + # proc, used or not. + backendEnsureMutable s + s.locImpl.snippet = markCName(s.loc.snippet) proc fillParamName(m: BModule; s: PSym) = if s.loc.snippet == "": @@ -1464,12 +1475,13 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType; # `cg` process emits this type info's tentative definition. Declare it # `extern` first (the data analogue of a proc prototype) so a TU whose copy # the merge stage drops still has a valid declaration; wrap the definition - # as a droppable `'d'` unit the merge stage assigns to a single owner so + # as a droppable `'u'` unit the merge stage assigns to a single owner so # exactly one external-linkage tentative definition survives (preserving - # the RTTI pointer identity refc relies on). + # the RTTI pointer identity refc relies on). Unlike `'d'` it is no root: + # its uses are marked (`rttiRef`), so it lives only if something does. m.s[cfsStrData].addDeclWithVisibility(Extern): m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimType") - m.s[cfsStrData].add(cnifDefDirective(name, "d", icNifName(m, origType))) + m.s[cfsStrData].add(cnifDefDirective(name, "u", icNifName(m, origType))) m.s[cfsStrData].addDeclWithVisibility(Private): m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimType") m.s[cfsStrData].add(cnifEndDefs()) @@ -1766,6 +1778,15 @@ proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) = m.s[cfsTypeInit3].addFieldAssignmentWithValue(result, "deepcopy"): m.s[cfsTypeInit3].add(cCast(pt, s.loc.snippet)) +proc rttiRef(m: BModule; name: Snippet): Snippet = + ## A reference to the type info `name`. In the per-module backend it is + ## cnif-marked: the type info is a DCE'd unit, live only when used. + if m.config.cmd == cmdNifC and not m.hcrOn and name.startsWith("NTI") and + allCharsInSet(name, IdentChars): + markCName(name) + else: + name + proc declareNimType(m: BModule; name: string; str: Rope, module: int) = let nr = rope(name) if m.hcrOn: @@ -1779,13 +1800,11 @@ proc declareNimType(m: BModule; name: string; str: Rope, module: int) = m.s[cfsTypeInit1].addArgument(hcrGlobal): m.s[cfsTypeInit1].add("\"" & str & "\"") else: - # cnif-mark the name: this extern declaration is the reference the - # def-retention check consults when the defining TU regenerates and - # the typeinfo cannot be re-demanded (type vanished) — the referencing - # TU must lose its reuse then instead of producing a link error - let declName = if m.config.cmd == cmdNifC: markCName(str) else: str + # NOT cnif-marked: a name at the artifact's top level is a liveness root. + # The uses are marked instead (`rttiRef`), which also makes them the + # references the def-retention check consults. m.s[cfsStrData].addDeclWithVisibility(Extern): - m.s[cfsStrData].addVar(kind = Local, name = declName, typ = nr) + m.s[cfsStrData].addVar(kind = Local, name = str, typ = nr) proc genTypeInfo2Name(m: BModule; t: PType): Rope = var it = t @@ -2047,7 +2066,12 @@ proc genTypeInfoV2OldImpl(m: BModule; t, origType: PType, tiName: Rope; info: TL m.s[cfsTypeInit3].add extract(typeEntry) if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions: - discard genTypeInfoV1(m, t, info) + let v1 = genTypeInfoV1(m, t, info) + if m.config.cmd == cmdNifC and not m.hcrOn: + # see `genTypeInfoV2Impl` + m.s[cfsVars].add(cnifDefDirective(tiName, "d", "")) + m.s[cfsVars].add(cnifUsesOf(v1)) + m.s[cfsVars].add(cnifEndDefs()) proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) = cgsym(m, "TNimTypeV2") @@ -2121,14 +2145,22 @@ proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineIn typeEntry.addField(typeInit, name = "flags"): typeEntry.addIntValue(flags) if m.config.cmd == cmdNifC: - m.s[cfsVars].add(cnifDefDirective(name, "d", icNifName(m, origType))) + # 'u', not 'd': no root, its uses are marked (`rttiRef`) and it keeps the + # hooks it points to alive only while it is live itself + m.s[cfsVars].add(cnifDefDirective(name, "u", icNifName(m, origType))) m.s[cfsVars].add extract(typeEntry) m.s[cfsVars].add(cnifEndDefs()) else: m.s[cfsVars].add extract(typeEntry) if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions: - discard genTypeInfoV1(m, t, info) + let v1 = genTypeInfoV1(m, t, info) + if m.config.cmd == cmdNifC: + # deepCopy reaches the V1 info through this one's `typeInfoV1` field, + # which the V1 info's init sets: depend on it + m.s[cfsVars].add(cnifDefDirective(name, "u", "")) + m.s[cfsVars].add(cnifUsesOf(v1)) + m.s[cfsVars].add(cnifEndDefs()) proc myModuleOpenForCodegen(m: BModule; idx: FileIndex): bool {.inline.} = if moduleOpenForCodegen(m.g.graph, idx): @@ -2145,7 +2177,7 @@ proc genTypeInfoV2(m: BModule; t: PType; info: TLineInfo): Rope = if m.hcrOn: wrapPar(x) else: - cAddr(x) + cAddr(rttiRef(m, x)) let sig = hashType(origType, m.config) result = m.typeInfoMarkerV2.getOrDefault(sig) @@ -2229,6 +2261,7 @@ type markers: Builder typeNodes: int typeNodesName: Rope + procUses: seq[string] # the enclosing definition's `icProcUses` proc beginRttiInit(m: BModule; scope: var RttiInitScope) = ## The per-module backend emits V1 type info everywhere it is demanded, and @@ -2247,6 +2280,12 @@ proc beginRttiInit(m: BModule; scope: var RttiInitScope) = scope.typeNodesName = m.typeNodesName m.typeNodes = 0 m.typeNodesName = getTempName(m) + inc m.rttiInitDepth + scope.procUses = move m.icProcUses + inc m.icProcDepth + +proc emitRttiInit(m: BModule; name: Rope; markers: Snippet; body: var Builder; + uses: seq[string]) proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) = ## Wraps the init code gathered since `beginRttiInit` into `_init`, @@ -2265,8 +2304,16 @@ proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) = swap(m.s[s], scope.sections[s]) m.typeNodes = scope.typeNodes m.typeNodesName = scope.typeNodesName - if body.buf.len == 0: return - + dec m.rttiInitDepth + let uses = move m.icProcUses + m.icProcUses = move scope.procUses + dec m.icProcDepth + if body.buf.len > 0: emitRttiInit(m, name, markers, body, uses) + if m.rttiInitDepth == 0 and m.rttiInitCalls.buf.len > 0: + m.s[cfsTypeInit3].add(extract(m.rttiInitCalls)) + +proc emitRttiInit(m: BModule; name: Rope; markers: Snippet; body: var Builder; + uses: seq[string]) = let initName = name & "_init" var header = newBuilder("") header.addDeclWithVisibility(Private): @@ -2274,10 +2321,14 @@ proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) = let proto = extract(header) m.s[cfsProcHeaders].add(proto) m.s[cfsProcHeaders].finishProcHeaderAsProto() - # 'd': a liveness root kept by its owner only; 'u': a unique proc body, so a - # split module may move it into any of its C files. The prototype comes - # first so the unit starts like a proc, and the markers precede their use. - m.s[cfsProcs].add(cnifDefDirective(initName, "ud", "")) + # 'u': a unique proc body, so a split module may move it into any of its C + # files. It is no root: it lives while its type info does (see the call + # below). The prototype comes first so the unit starts like a proc, and the + # markers precede their use. The invisible use keeps the type info alive + # with the init that writes it. + m.s[cfsProcs].add(cnifDefDirective(initName, "u", "")) + m.s[cfsProcs].add(cnifUse(name)) + for u in uses: m.s[cfsProcs].add(cnifUse(u)) m.s[cfsProcs].add(proto) m.s[cfsProcs].finishProcHeaderAsProto() m.s[cfsProcs].add(markers) @@ -2290,7 +2341,21 @@ proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) = m.s[cfsProcs].addAssignment("nimRttiDone", NimTrue) m.s[cfsProcs].add(extract(body)) m.s[cfsProcs].add(cnifEndDefs()) - m.s[cfsTypeInit3].addCallStmt(initName) + if m.rttiInitDepth > 0: + # built for an enclosing type info: its init runs this one first + m.s[cfsTypeInit3].addCallStmt(markCName(initName)) + # The DatInit call belongs to the type info: a unit of the same name, so the + # init runs if and only if the type info is live (and only in its owner; + # every DatInit runs before any module's init code). A nested type info gets + # its own call too, as it can outlive the enclosing one. + var call = newBuilder("") + call.add(cnifDefDirective(name, "u", "")) + call.addCallStmt(markCName(initName)) + call.add(cnifEndDefs()) + if m.rttiInitDepth > 0: + m.rttiInitCalls.add(extract(call)) + else: + m.s[cfsTypeInit3].add(extract(call)) proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope = let origType = t @@ -2300,7 +2365,7 @@ proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope = if m.hcrOn: wrapPar(x) else: - cAddr(x) + cAddr(rttiRef(m, x)) let sig = hashType(origType, m.config) result = m.typeInfoMarker.getOrDefault(sig) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index db98a39100100..b24e3bd3ce02f 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -1529,6 +1529,15 @@ proc cgsym(m: BModule, name: string) = let sym = magicsys.getCompilerProc(m.g.graph, name) if sym != nil: cgsymImpl m, sym + if m.config.cmd == cmdNifC and sym.kind in routineKinds: + # The caller writes `name` into the C text itself, unmarked: the merge + # stage cannot see that use, so it is recorded explicitly. Uses + # through `cgsymValue` (and `#name` in `ropecg`) carry the marked name. + # Inside a proc (or RTTI init) it is an invisible use of that definition. + let r = stripCnifMarks(sym.loc.snippet) + if m.icProcDepth > 0: + if r notin m.icProcUses: m.icProcUses.add r + elif r notin m.icCgsymRoots: m.icCgsymRoots.add r else: rawMessage(m.config, errGenerated, "system module needs: " & name) @@ -1824,7 +1833,7 @@ proc resultDestructorCpp(p: BProc; prc: PSym; res: PSym; procBody: PNode): PNode arg = newTreeIT(nkHiddenAddr, res.info, makePtrType(res.typ, p.module.idgen), arg) result = newTreeI(nkCall, res.info, newSymNode(op), arg) -proc genProcLvl3*(m: BModule, prc: PSym) = +proc genProcLvl3Impl(m: BModule, prc: PSym) = if m.config.cmd == cmdNifC: fillBackendName(m, prc) if (prc.disamb and (InstanceDisambBit or HookDisambBit)) != 0'i32 and @@ -2056,7 +2065,12 @@ proc genProcLvl3*(m: BModule, prc: PSym) = # cfsProcs emitters (NimMain block, trav markers, ...) never end up # inside a definition's span. var defFlags = "" - if sfExportc in prc.flags or sfConstructor in prc.flags: defFlags.add 'x' + # A compilerproc is `exportc` only to fix its C name: like in whole-program + # codegen it is generated when used, so it is no root (unless exported + # from a library). + if (sfExportc in prc.flags and sfCompilerProc notin prc.flags) or + sfConstructor in prc.flags or lfExportLib in prc.loc.flags: + defFlags.add 'x' if sfCompilerProc in prc.flags: defFlags.add 'c' if prc.kind == skMethod or sfDispatcher in prc.flags: defFlags.add 'm' if (prc.typ == nil or prc.typ.callConv != ccInline) and @@ -2085,6 +2099,7 @@ proc genProcLvl3*(m: BModule, prc: PSym) = if sfCppMember * prc.flags != {}: icNifName(m, prc) else: stripCnifMarks(prc.loc.snippet) m.s[cfsProcs].add(cnifDefDirective(defName, defFlags, icNifName(m, prc))) + for u in m.icProcUses: m.s[cfsProcs].add(cnifUse(u)) let pushed = icTargetPush(m, prc) m.s[cfsProcs].add(extract(generatedProc)) if pushed: icTargetPop(m) @@ -2103,6 +2118,17 @@ proc genProcLvl3*(m: BModule, prc: PSym) = '"' & prc.loc.snippet & '"', cCast(CPointer, prc.loc.snippet & "_actual")) +proc genProcLvl3*(m: BModule, prc: PSym) = + if m.config.cmd == cmdNifC: + # collect the compilerprocs `cgsym` demands by name for this proc's text + var saved = move m.icProcUses + inc m.icProcDepth + genProcLvl3Impl(m, prc) + dec m.icProcDepth + swap m.icProcUses, saved + else: + genProcLvl3Impl(m, prc) + proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} = result = (sfCompileToCpp in m.module.flags and sfCompileToCpp notin sym.getModule().flags and @@ -3115,6 +3141,7 @@ proc genModule(m: BModule, cfile: Cfile): Rope = # close the definitions section: the init procs that follow belong to # the artifact's top level (always-run code, hence liveness roots) res.add(cnifEndDefs()) + for r in m.icCgsymRoots: res.add(cnifUse(r)) if m.s[cfsInitProc].buf.len > 0: moduleIsEmpty = false diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim index 4a2b80fc744b4..6f693ef97b2b2 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -220,6 +220,15 @@ type # recorded in the cnif artifact so a later run # can reuse the TU and re-demand definitions # that cached TUs still reference + icCgsymRoots*: seq[string] # per-module backend: the routines `cgsym` + # demanded by NAME. Their C text names them + # verbatim, out of reach of the cnif marks, so + # they become liveness roots of the module. + icProcUses*: seq[string] # the same for the proc being generated: + # invisible uses of its definition + icProcDepth*: int # nesting of procs (and RTTI inits) being built + rttiInitDepth*: int # nesting of V1 RTTI init procs being built + rttiInitCalls*: Builder # their DatInit calls, flushed by the outermost hasTopLevelEmit*: bool # a top-level `{.emit.}` wrote user C text into # a file section: `emit` must not split the # module, its text may define anything diff --git a/compiler/cnif.nim b/compiler/cnif.nim index 4b09830ed7719..f571d0ef2e518 100644 --- a/compiler/cnif.nim +++ b/compiler/cnif.nim @@ -39,6 +39,9 @@ ## \4 \31 P \5 start of the procs section: what ## precedes it declares, what follows ## defines (see `renderCPartsFromArtifact`) +## \6 name \3 an invisible use of `name`: a liveness +## edge without C text, for references the +## C text makes by a name it cannot mark import std / [tables, sets, os, assertions, syncio, algorithm, hashes, strutils] import "../dist/nimony/src/lib" / [nifbuilder, nifcoreparse, stringviews] @@ -50,13 +53,33 @@ const CnifDefStart* = '\4' CnifDefSep* = '\31' # same separator char as cgen's postprocess directives CnifDefEnd* = '\5' + CnifUseStart* = '\6' + +proc cnifUse*(name: string): string {.inline.} = + ## An invisible use of `name`: inside a definition it is a liveness edge, + ## at the top level a root. It renders to no C text at all. + CnifUseStart & name & CnifSymEnd + +proc cnifUsesOf*(s: string): string = + ## The marked names of the C snippet `s` as invisible uses: what makes a + ## definition depend on code that it does not contain itself. + result = "" + var i = 0 + while i < s.len: + if s[i] == CnifSymStart: + let e = s.find(CnifSymEnd, i+1) + if e < 0: break + result.add cnifUse(s.substr(i+1, e-1)) + i = e + 1 + else: + inc i proc markCName*(name: string): string {.inline.} = CnifSymStart & name & CnifSymEnd proc hasCnifMarks*(s: string): bool = for c in s: - if c in {CnifSymStart, CnifSymEnd, CnifDefStart}: return true + if c in {CnifSymStart, CnifSymEnd, CnifDefStart, CnifUseStart}: return true false proc stripCnifMarks*(s: string): string = @@ -72,12 +95,15 @@ proc stripCnifMarks*(s: string): string = of CnifDefStart: while i < s.len and s[i] != CnifDefEnd: inc i inc i # skip CnifDefEnd + of CnifUseStart: + while i < s.len and s[i] != CnifSymEnd: inc i + inc i # skip CnifSymEnd else: result.add s[i] inc i const - CnifVersion* = "7" + CnifVersion* = "8" ## Artifact format version, stored in the meta head. Artifacts written ## by an older compiler lack the NIF names and the cref group the ## def-retention check needs (v2), the cdeps group the fine-grained @@ -85,7 +111,9 @@ const ## RTTI references the typeinfo flavor of the def-retention check ## needs (v4), or the global-destructor name the main module's `cg` ## calls at teardown (v5), or deferred dynlib loader indices (v6), or the - ## `(cprocs)` section marker that splitting a big module needs (v7); + ## `(cprocs)` section marker that splitting a big module needs (v7), or + ## the `(cuse)` invisible uses and the compilerprocs that are no longer + ## roots by themselves (v8); ## `readCnifHeads` reports them as invalid so ## their TUs simply regenerate once. @@ -140,6 +168,14 @@ proc writeCnifArtifact*(code: string; outfile: string; inc i inc i uses.incl name + of CnifUseStart: + inc i + var name = "" + while i < code.len and code[i] != CnifSymEnd: + name.add code[i] + inc i + inc i + uses.incl name of CnifDefStart: inc i var payload = "" @@ -199,6 +235,16 @@ proc writeCnifArtifact*(code: string; outfile: string; inc i inc i # skip CnifSymEnd b.addSymbol name, "" + of CnifUseStart: + flushRaw() + inc i + var name = "" + while i < code.len and code[i] != CnifSymEnd: + name.add code[i] + inc i + inc i # skip CnifSymEnd + b.withTree "cuse": + b.addSymbol name, "" of CnifDefStart: flushRaw() inc i @@ -249,6 +295,9 @@ proc renderMarkedC*(code: string; live: HashSet[string]; dropped: var int): stri case code[i] of CnifSymStart, CnifSymEnd: inc i + of CnifUseStart: + while i < code.len and code[i] != CnifSymEnd: inc i + inc i # skip CnifSymEnd of CnifDefStart: var payload = "" inc i @@ -442,6 +491,7 @@ proc computeLiveFromCArtifacts*(files: openArray[string]): CnifLiveness = let crefTag = tags.registerTag("cref") let cdepsTag = tags.registerTag("cdeps") let metaTag = tags.registerTag("meta") + let cuseTag = tags.registerTag("cuse") var uses = initTable[string, HashSet[string]]() var roots = initHashSet[string]() var defs = initHashSet[string]() @@ -482,8 +532,10 @@ proc computeLiveFromCArtifacts*(files: openArray[string]): CnifLiveness = flagsSeen = true for ch in name: # 'd' marks a data definition (const/RTTI): never DCE'd, so it - # is a root whose body keeps its referenced procs live - if ch in {'x', 'c', 'm', 'd'}: + # is a root whose body keeps its referenced procs live. A + # compilerproc ('c') is not a root: it is live when used, + # like in whole-program codegen + if ch in {'x', 'm', 'd'}: roots.incl owner break else: @@ -492,6 +544,14 @@ proc computeLiveFromCArtifacts*(files: openArray[string]): CnifLiveness = of DotToken: flagsSeen = true # empty flags field inc c + of TagLit: + if c.cursorTagId == cuseTag: + c.loopInto: + if c.kind in {Symbol, Ident}: + uses.mgetOrPut(owner, initHashSet[string]()).incl symOrIdentName(c) + inc c + else: + skip c else: skip c else: @@ -557,6 +617,7 @@ proc computeMergeDecision*(files: openArray[string]): MergeDecision = let crefTag = tags.registerTag("cref") let cdepsTag = tags.registerTag("cdeps") let metaTag = tags.registerTag("meta") + let cuseTag = tags.registerTag("cuse") var uses = initTable[string, HashSet[string]]() var roots = initHashSet[string]() var defs = initHashSet[string]() @@ -596,7 +657,8 @@ proc computeMergeDecision*(files: openArray[string]): MergeDecision = if not flagsSeen: flagsSeen = true for ch in name: - if ch in {'x', 'c', 'm'}: roots.incl ownerName + # a compilerproc ('c') is no root: live when used + if ch in {'x', 'm'}: roots.incl ownerName # 'u' = unique proc (DCE'd), 'd' = data (never DCE'd, hence a # root); both need a single owner across the emit-everywhere # processes @@ -610,6 +672,15 @@ proc computeMergeDecision*(files: openArray[string]): MergeDecision = of DotToken: flagsSeen = true # empty flags field inc c + of TagLit: + if c.cursorTagId == cuseTag: + # invisible uses (`cnifUse`): edges without C text + c.loopInto: + if c.kind in {Symbol, Ident}: + uses.mgetOrPut(ownerName, initHashSet[string]()).incl symOrIdentName(c) + inc c + else: + skip c else: skip c if needsOwner and ownerName.len > 0: @@ -629,13 +700,26 @@ proc computeMergeDecision*(files: openArray[string]): MergeDecision = endRead(c) var work = newSeqOfCap[string](roots.len) for r in roots: work.add r + when defined(icWhyLive): + var parent = initTable[string, string]() while work.len > 0: let s = work.pop() if not result.live.containsOrIncl(s): if uses.hasKey(s): for dep in uses[s]: if dep notin result.live: + when defined(icWhyLive): + if dep notin parent: parent[dep] = s work.add dep + when defined(icWhyLive): + for q in getEnv("IC_WHY_LIVE").split(','): + var x = q + var chain = x + while parent.hasKey(x): + x = parent[x] + chain.add " <- " & x + if x in roots: chain.add " [root]" + stderr.writeLine "[whylive] ", chain result.defs = defs.len for d in defs: if d in result.live: inc result.liveDefs @@ -834,6 +918,8 @@ proc readCPieces(artifact: string; d: MergeDecision; ownerId: string; if not p.keep: inc dropped state = 3 inc c + elif c.kind == TagLit: # `(cuse)`: no C text + skip c else: # body tokens if p.keep: if c.kind == StrLit: p.text.add strVal(c) diff --git a/tests/ic/mdcelive.nim b/tests/ic/mdcelive.nim new file mode 100644 index 0000000000000..37aa103120677 --- /dev/null +++ b/tests/ic/mdcelive.nim @@ -0,0 +1,40 @@ +# helper of tdcelive/tdceliverefc: only some of these are used + +type + Kind* = enum kInt, kBig, kStr, kNode + Node* = ref object of RootObj + case kind*: Kind + of kInt, kBig: i*: int + of kStr: s*: string + of kNode: kids*: seq[Node] + Leaf* = ref object of Node + tag*: string + +proc toStr*(n: Node): string = + case n.kind + of kInt: $n.i + of kBig: "big " & $n.i + of kStr: n.s + of kNode: + var r = "(" + for k in n.kids: r.add toStr(k) & " " + r & ")" + +proc makeBig*(n: Node) = + # a discriminant assignment: checked against the RTTI's discriminator table + # (which the type info's init fills); stays in the branch, so it is allowed + n.kind = kBig + +proc tryMakeStr*(n: Node): string = + # leaves the branch: only a filled discriminator table can tell + try: + n.kind = kStr + result = "not caught" + except FieldDefect: + result = "caught" + +proc deadSwitch*(n: Node) = + # never called: neither it nor what only it needs may survive + n.kind = kInt + +proc deadFloat*(x: float): string = "dead:" & $x diff --git a/tests/ic/tdcelive.nim b/tests/ic/tdcelive.nim new file mode 100644 index 0000000000000..9a5e0851c1de1 --- /dev/null +++ b/tests/ic/tdcelive.nim @@ -0,0 +1,25 @@ +discard """ + output: '''(1 abc (2 ) ) +big 5 caught +true false +leaf 7''' +""" + +# The per-module backend's merge stage keeps a definition only if something +# live uses it: compilerprocs, type infos (and their init procs) and consts are +# no liveness roots of their own. Every reference that the C text makes by an +# unmarked name must therefore show up as an explicit use, or the merge drops +# what the program still needs: the discriminator table filled by the type +# info's init, nested type infos, compilerprocs that codegen names directly. + +import mdcelive + +var tree = Node(kind: kNode, kids: @[Node(kind: kInt, i: 1), + Node(kind: kStr, s: "abc"), Node(kind: kNode, kids: @[Node(kind: kInt, i: 2)])]) +echo toStr(tree) +var n = Node(kind: kInt, i: 5) +makeBig(n) +echo toStr(n), " ", tryMakeStr(n) +let l: Node = Leaf(kind: kInt, i: 7, tag: "leaf") +echo l of Leaf, " ", tree of Leaf +echo Leaf(l).tag, " ", toStr(l) diff --git a/tests/ic/tdceliverefc.nim b/tests/ic/tdceliverefc.nim new file mode 100644 index 0000000000000..a26044e413aa3 --- /dev/null +++ b/tests/ic/tdceliverefc.nim @@ -0,0 +1,28 @@ +discard """ + output: '''(1 abc ) +big 5 caught +true false +leaf 7 +(1 abc ) 1''' +""" + +# `tdcelive` under refc (see `tdceliverefc_temp.nim.cfg`): there the V1 type +# infos are what the GC and `deepCopy` read, and their init procs must run +# whenever a type info is live. + +import mdcelive + +var tree = Node(kind: kNode, kids: @[Node(kind: kInt, i: 1), + Node(kind: kStr, s: "abc")]) +echo toStr(tree) +var n = Node(kind: kInt, i: 5) +makeBig(n) +echo toStr(n), " ", tryMakeStr(n) +let l: Node = Leaf(kind: kInt, i: 7, tag: "leaf") +echo l of Leaf, " ", tree of Leaf +echo Leaf(l).tag, " ", toStr(l) +var copy: Node +deepCopy(copy, tree) +tree.kids.setLen 1 +GC_fullCollect() +echo toStr(copy), " ", tree.kids.len diff --git a/tests/ic/tdceliverefc_temp.nim.cfg b/tests/ic/tdceliverefc_temp.nim.cfg new file mode 100644 index 0000000000000..a6f488ef01e49 --- /dev/null +++ b/tests/ic/tdceliverefc_temp.nim.cfg @@ -0,0 +1,2 @@ +--mm:refc +--deepcopy:on From a2309b76daa2bbb2d887d46c76fcb7a21a8e414a Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 5 Dec 2026 10:34:59 +0100 Subject: [PATCH 2/3] IC+HCR: consts, V2 type infos and V1 init calls stay liveness roots Under --hotCodeReloading these are reached through hcrGetGlobal by string name or registered from the module init under a `_const` name, so no marked use refers to them: as 'u' units the merge dropped them (undefined `*_const` at link/dlopen; refc crashed in newSeq because the V1 init calls, wrapped in a unit named after a type info that is no cnif unit under HCR, never ran). Fixes tests/dll/nimhcr_ic.nim. Co-Authored-By: Claude Opus 5.5 --- compiler/ccgexprs.nim | 5 +++-- compiler/ccgtypes.nim | 14 +++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 0b58b299c35a6..04e9f013dfd2d 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -3629,14 +3629,15 @@ proc genConstDefinition(q: BModule; p: BProc; sym: PSym) = # prototype) so a TU whose copy the merge stage drops still has a valid # declaration; wrap the definition as a droppable `'u'` unit the merge # stage assigns to a single owner. It is no root (its uses are marked) - # unless C code may name it. + # unless C code may name it, or HCR registers it from the module's init + # under its `_const` name, which no marked use refers to. let cname = stripCnifMarks(actualConstName) var decl = newBuilder("") decl.addDeclWithVisibility(Extern): decl.addVar(kind = Local, name = cname, typ = td) q.s[cfsData].add(extract(decl)) q.s[cfsData].add(cnifDefDirective(cname, - if sfExportc in sym.flags: "d" else: "u", icNifName(q, sym))) + if sfExportc in sym.flags or q.hcrOn: "d" else: "u", icNifName(q, sym))) q.s[cfsData].add(extract(data)) q.s[cfsData].add(cnifEndDefs()) q.icDataDefs.add (cname, icNifName(q, sym)) diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index d58c6a0187976..e77fa15d96ddb 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -2146,8 +2146,10 @@ proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineIn typeEntry.addIntValue(flags) if m.config.cmd == cmdNifC: # 'u', not 'd': no root, its uses are marked (`rttiRef`) and it keeps the - # hooks it points to alive only while it is live itself - m.s[cfsVars].add(cnifDefDirective(name, "u", icNifName(m, origType))) + # hooks it points to alive only while it is live itself. Under HCR its + # uses look it up by its string name (`hcrGetGlobal`): a root. + m.s[cfsVars].add(cnifDefDirective(name, if m.hcrOn: "d" else: "u", + icNifName(m, origType))) m.s[cfsVars].add extract(typeEntry) m.s[cfsVars].add(cnifEndDefs()) else: @@ -2158,7 +2160,7 @@ proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineIn if m.config.cmd == cmdNifC: # deepCopy reaches the V1 info through this one's `typeInfoV1` field, # which the V1 info's init sets: depend on it - m.s[cfsVars].add(cnifDefDirective(name, "u", "")) + m.s[cfsVars].add(cnifDefDirective(name, if m.hcrOn: "d" else: "u", "")) m.s[cfsVars].add(cnifUsesOf(v1)) m.s[cfsVars].add(cnifEndDefs()) @@ -2351,10 +2353,12 @@ proc emitRttiInit(m: BModule; name: Rope; markers: Snippet; body: var Builder; # init runs if and only if the type info is live (and only in its owner; # every DatInit runs before any module's init code). A nested type info gets # its own call too, as it can outlive the enclosing one. + # Under HCR the type info is no cnif unit (`declareTypeInfoForHcr`) and so + # never live: the call stays at the top level, a liveness root. var call = newBuilder("") - call.add(cnifDefDirective(name, "u", "")) + if not m.hcrOn: call.add(cnifDefDirective(name, "u", "")) call.addCallStmt(markCName(initName)) - call.add(cnifEndDefs()) + if not m.hcrOn: call.add(cnifEndDefs()) if m.rttiInitDepth > 0: m.rttiInitCalls.add(extract(call)) else: From f65a842aa22975fdbbbc9bb469e1690192fb3959 Mon Sep 17 00:00:00 2001 From: Araq Date: Sat, 5 Dec 2026 16:14:53 +0100 Subject: [PATCH 3/3] IC: drop dead identifier guards on cnif marking; inline cnifUse in cnifUsesOf The allCharsInSet(.., IdentChars) checks in fillBackendName and rttiRef never fail (probed with a nim ic build of the compiler, tests/cpp member /constructor tests and tests/ic); rttiRef's callers only pass NTI names. Co-Authored-By: Claude Opus 5.5 --- compiler/ccgtypes.nim | 6 ++---- compiler/cnif.nim | 4 +++- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index e77fa15d96ddb..63a5ff9cbf82d 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -147,8 +147,7 @@ proc fillBackendName(m: BModule; s: PSym) = elif m.config.cmd == cmdNifC and not m.hcrOn and s.kind in routineKinds and sfImportc notin s.flags and (sfExportc notin s.flags or sfCompilerProc in s.flags) and - not hasCnifMarks(s.loc.snippet) and - allCharsInSet(s.loc.snippet, IdentChars): + not hasCnifMarks(s.loc.snippet): # A C name from an `extern:` pragma (most of the stdlib's `rtl` procs) or # of a compilerproc is set at sem time. Mark it too: otherwise the merge # stage's liveness walk cannot see its uses and has to keep every such @@ -1781,8 +1780,7 @@ proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) = proc rttiRef(m: BModule; name: Snippet): Snippet = ## A reference to the type info `name`. In the per-module backend it is ## cnif-marked: the type info is a DCE'd unit, live only when used. - if m.config.cmd == cmdNifC and not m.hcrOn and name.startsWith("NTI") and - allCharsInSet(name, IdentChars): + if m.config.cmd == cmdNifC and not m.hcrOn: markCName(name) else: name diff --git a/compiler/cnif.nim b/compiler/cnif.nim index 2c46fb9c83707..1dbfd39db598f 100644 --- a/compiler/cnif.nim +++ b/compiler/cnif.nim @@ -69,7 +69,9 @@ proc cnifUsesOf*(s: string): string = if s[i] == CnifSymStart: let e = s.find(CnifSymEnd, i+1) if e < 0: break - result.add cnifUse(s.substr(i+1, e-1)) + # `cnifUse` inlined: no temporary for the name + result.add CnifUseStart + for j in i+1..e: result.add s[j] # the name and its CnifSymEnd i = e + 1 else: inc i