diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 8e67f72cd13da..04e9f013dfd2d 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -3606,9 +3606,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: @@ -3626,14 +3627,17 @@ 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, 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 = 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 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/ccgstmts.nim b/compiler/ccgstmts.nim index 9fcfa0864a0e7..777dba27fe18c 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -1903,7 +1903,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 caa68940a7a3b..63a5ff9cbf82d 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -144,6 +144,16 @@ 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): + # 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 +1474,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 +1777,14 @@ 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: + markCName(name) + else: + name + proc declareNimType(m: BModule; name: string; str: Rope, module: int) = let nr = rope(name) if m.hcrOn: @@ -1779,13 +1798,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 +2064,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 +2143,24 @@ 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. 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: 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, if m.hcrOn: "d" else: "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) @@ -2232,6 +2264,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 @@ -2250,6 +2283,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`, @@ -2268,8 +2307,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): @@ -2277,10 +2324,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) @@ -2293,7 +2344,23 @@ 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. + # 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("") + if not m.hcrOn: call.add(cnifDefDirective(name, "u", "")) + call.addCallStmt(markCName(initName)) + if not m.hcrOn: 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 @@ -2303,7 +2370,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 b690d9fd93de5..b25833df32635 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -1531,6 +1531,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) @@ -1826,7 +1835,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 @@ -2058,7 +2067,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 @@ -2087,6 +2101,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) @@ -2105,6 +2120,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 @@ -3120,6 +3146,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 4f9b1d9073f73..4ef90bcb81792 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -222,6 +222,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 fffe807966f82..1dbfd39db598f 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,35 @@ 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 + # `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 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 +97,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 +113,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 +170,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 +237,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 +297,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 +493,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 +534,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 +546,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 +619,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 +659,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 +674,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 +702,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 @@ -844,6 +930,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