injectdestructors.nim 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Injects destructor calls into Nim code as well as
  10. ## an optimizer that optimizes copies to moves. This is implemented as an
  11. ## AST to AST transformation so that every backend benefits from it.
  12. ## See doc/destructors.rst for a spec of the implemented rewrite rules
  13. import
  14. ast, astalgo, msgs, renderer, magicsys, types, idents,
  15. options, lowerings, modulegraphs,
  16. lineinfos, parampatterns, sighashes, liftdestructors, optimizer,
  17. varpartitions, aliasanalysis, dfa, wordrecg
  18. import std/[strtabs, tables, strutils, intsets]
  19. when defined(nimPreviewSlimSystem):
  20. import std/assertions
  21. from trees import exprStructuralEquivalent, getRoot, whichPragma
  22. type
  23. Con = object
  24. owner: PSym
  25. when true:
  26. g: ControlFlowGraph
  27. graph: ModuleGraph
  28. inLoop, inSpawn, inLoopCond: int
  29. uninit: IntSet # set of uninit'ed vars
  30. idgen: IdGenerator
  31. body: PNode
  32. otherUsage: TLineInfo
  33. inUncheckedAssignSection: int
  34. inEnsureMove: int
  35. Scope = object # we do scope-based memory management.
  36. # a scope is comparable to an nkStmtListExpr like
  37. # (try: statements; dest = y(); finally: destructors(); dest)
  38. vars: seq[PSym]
  39. wasMoved: seq[PNode]
  40. final: seq[PNode] # finally section
  41. locals: seq[PSym]
  42. body: PNode
  43. needsTry: bool
  44. parent: ptr Scope
  45. ProcessMode = enum
  46. normal
  47. consumed
  48. sinkArg
  49. const toDebug {.strdefine.} = ""
  50. when toDebug.len > 0:
  51. var shouldDebug = false
  52. template dbg(body) =
  53. when toDebug.len > 0:
  54. if shouldDebug:
  55. body
  56. proc hasDestructor(c: Con; t: PType): bool {.inline.} =
  57. result = ast.hasDestructor(t)
  58. when toDebug.len > 0:
  59. # for more effective debugging
  60. if not result and c.graph.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  61. assert(not containsGarbageCollectedRef(t))
  62. proc getTemp(c: var Con; s: var Scope; typ: PType; info: TLineInfo): PNode =
  63. let sym = newSym(skTemp, getIdent(c.graph.cache, ":tmpD"), c.idgen, c.owner, info)
  64. sym.typ = typ
  65. s.vars.add(sym)
  66. result = newSymNode(sym)
  67. proc nestedScope(parent: var Scope; body: PNode): Scope =
  68. Scope(vars: @[], locals: @[], wasMoved: @[], final: @[], body: body, needsTry: false, parent: addr(parent))
  69. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}; inReturn = false): PNode
  70. type
  71. MoveOrCopyFlag = enum
  72. IsDecl, IsExplicitSink, IsReturn
  73. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; flags: set[MoveOrCopyFlag] = {}): PNode
  74. when false:
  75. var
  76. perfCounters: array[InstrKind, int]
  77. proc showCounters*() =
  78. for i in low(InstrKind)..high(InstrKind):
  79. echo "INSTR ", i, " ", perfCounters[i]
  80. proc isLastReadImpl(n: PNode; c: var Con; scope: var Scope): bool =
  81. let root = parampatterns.exprRoot(n, allowCalls=false)
  82. if root == nil: return false
  83. var s = addr(scope)
  84. while s != nil:
  85. if s.locals.contains(root): break
  86. s = s.parent
  87. c.g = constructCfg(c.owner, if s != nil: s.body else: c.body, root)
  88. dbg:
  89. echo "\n### ", c.owner.name.s, ":\nCFG:"
  90. echoCfg(c.g)
  91. #echo c.body
  92. var j = 0
  93. while j < c.g.len:
  94. if c.g[j].kind == use and c.g[j].n == n: break
  95. inc j
  96. c.otherUsage = unknownLineInfo
  97. if j < c.g.len:
  98. var pcs = @[j+1]
  99. var marked = initIntSet()
  100. result = true
  101. while pcs.len > 0:
  102. var pc = pcs.pop()
  103. if not marked.contains(pc):
  104. let oldPc = pc
  105. while pc < c.g.len:
  106. dbg:
  107. echo "EXEC ", c.g[pc].kind, " ", pc, " ", n
  108. when false:
  109. inc perfCounters[c.g[pc].kind]
  110. case c.g[pc].kind
  111. of loop:
  112. let back = pc + c.g[pc].dest
  113. if not marked.containsOrIncl(back):
  114. pc = back
  115. else:
  116. break
  117. of goto:
  118. pc = pc + c.g[pc].dest
  119. of fork:
  120. if not marked.contains(pc+1):
  121. pcs.add pc + 1
  122. pc = pc + c.g[pc].dest
  123. of use:
  124. if c.g[pc].n.aliases(n) != no or n.aliases(c.g[pc].n) != no:
  125. c.otherUsage = c.g[pc].n.info
  126. return false
  127. inc pc
  128. of def:
  129. if c.g[pc].n.aliases(n) == yes:
  130. # the path leads to a redefinition of 's' --> sink 's'.
  131. break
  132. elif n.aliases(c.g[pc].n) != no:
  133. # only partially writes to 's' --> can't sink 's', so this def reads 's'
  134. # or maybe writes to 's' --> can't sink 's'
  135. c.otherUsage = c.g[pc].n.info
  136. return false
  137. inc pc
  138. marked.incl oldPc
  139. else:
  140. result = false
  141. proc isLastRead(n: PNode; c: var Con; s: var Scope): bool =
  142. # bug #23354; an object type could have a non-trival assignements when it is passed to a sink parameter
  143. if not hasDestructor(c, n.typ) and (n.typ.kind != tyObject or isTrival(getAttachedOp(c.graph, n.typ, attachedAsgn))): return true
  144. let m = skipConvDfa(n)
  145. result = (m.kind == nkSym and sfSingleUsedTemp in m.sym.flags) or
  146. isLastReadImpl(n, c, s)
  147. proc isFirstWrite(n: PNode; c: var Con): bool =
  148. let m = skipConvDfa(n)
  149. result = nfFirstWrite in m.flags
  150. proc isCursor(n: PNode): bool =
  151. case n.kind
  152. of nkSym:
  153. sfCursor in n.sym.flags
  154. of nkDotExpr:
  155. isCursor(n[1])
  156. of nkCheckedFieldExpr:
  157. isCursor(n[0])
  158. else:
  159. false
  160. template isUnpackedTuple(n: PNode): bool =
  161. ## we move out all elements of unpacked tuples,
  162. ## hence unpacked tuples themselves don't need to be destroyed
  163. ## except it's already a cursor
  164. (n.kind == nkSym and n.sym.kind == skTemp and
  165. n.sym.typ.kind == tyTuple and sfCursor notin n.sym.flags)
  166. proc checkForErrorPragma(c: Con; t: PType; ri: PNode; opname: string; inferredFromCopy = false) =
  167. var m = "'" & opname & "' is not available for type <" & typeToString(t) & ">"
  168. if inferredFromCopy:
  169. m.add ", which is inferred from unavailable '=copy'"
  170. if (opname == "=" or opname == "=copy" or opname == "=dup") and ri != nil:
  171. m.add "; requires a copy because it's not the last read of '"
  172. m.add renderTree(ri)
  173. m.add '\''
  174. if c.otherUsage != unknownLineInfo:
  175. # ri.comment.startsWith('\n'):
  176. m.add "; another read is done here: "
  177. m.add c.graph.config $ c.otherUsage
  178. #m.add c.graph.config $ c.g[parseInt(ri.comment[1..^1])].n.info
  179. elif ri.kind == nkSym and ri.sym.kind == skParam and not isSinkType(ri.sym.typ):
  180. m.add "; try to make "
  181. m.add renderTree(ri)
  182. m.add " a 'sink' parameter"
  183. m.add "; routine: "
  184. m.add c.owner.name.s
  185. #m.add "\n\n"
  186. #m.add renderTree(c.body, {renderIds})
  187. localError(c.graph.config, ri.info, errGenerated, m)
  188. proc makePtrType(c: var Con, baseType: PType): PType =
  189. result = newType(tyPtr, c.idgen, c.owner)
  190. addSonSkipIntLit(result, baseType, c.idgen)
  191. proc genOp(c: var Con; op: PSym; dest: PNode): PNode =
  192. var addrExp: PNode
  193. if op.typ != nil and op.typ.signatureLen > 1 and op.typ.firstParamType.kind != tyVar:
  194. addrExp = dest
  195. else:
  196. addrExp = newNodeIT(nkHiddenAddr, dest.info, makePtrType(c, dest.typ))
  197. addrExp.add(dest)
  198. result = newTree(nkCall, newSymNode(op), addrExp)
  199. proc genOp(c: var Con; t: PType; kind: TTypeAttachedOp; dest, ri: PNode): PNode =
  200. var op = getAttachedOp(c.graph, t, kind)
  201. if op == nil or op.ast.isGenericRoutine:
  202. # give up and find the canonical type instead:
  203. let h = sighashes.hashType(t, c.graph.config, {CoType, CoConsiderOwned, CoDistinct})
  204. let canon = c.graph.canonTypes.getOrDefault(h)
  205. if canon != nil:
  206. op = getAttachedOp(c.graph, canon, kind)
  207. if op == nil:
  208. #echo dest.typ.id
  209. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  210. "' operator not found for type " & typeToString(t))
  211. elif op.ast.isGenericRoutine:
  212. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  213. "' operator is generic")
  214. dbg:
  215. if kind == attachedDestructor:
  216. echo "destructor is ", op.id, " ", op.ast
  217. if sfError in op.flags: checkForErrorPragma(c, t, ri, AttachedOpToStr[kind])
  218. c.genOp(op, dest)
  219. proc genDestroy(c: var Con; dest: PNode): PNode =
  220. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  221. result = c.genOp(t, attachedDestructor, dest, nil)
  222. proc canBeMoved(c: Con; t: PType): bool {.inline.} =
  223. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  224. if optOwnedRefs in c.graph.config.globalOptions:
  225. result = t.kind != tyRef and getAttachedOp(c.graph, t, attachedSink) != nil
  226. else:
  227. result = getAttachedOp(c.graph, t, attachedSink) != nil
  228. proc isNoInit(dest: PNode): bool {.inline.} =
  229. result = dest.kind == nkSym and sfNoInit in dest.sym.flags
  230. proc deepAliases(dest, ri: PNode): bool =
  231. case ri.kind
  232. of nkCallKinds, nkStmtListExpr, nkBracket, nkTupleConstr, nkObjConstr,
  233. nkCast, nkConv, nkObjUpConv, nkObjDownConv:
  234. for r in ri:
  235. if deepAliases(dest, r): return true
  236. return false
  237. else:
  238. return aliases(dest, ri) != no
  239. proc genSink(c: var Con; s: var Scope; dest, ri: PNode; flags: set[MoveOrCopyFlag] = {}): PNode =
  240. if (c.inLoopCond == 0 and (isUnpackedTuple(dest) or IsDecl in flags or
  241. (isAnalysableFieldAccess(dest, c.owner) and isFirstWrite(dest, c)))) or
  242. isNoInit(dest) or IsReturn in flags:
  243. # optimize sink call into a bitwise memcopy
  244. result = newTree(nkFastAsgn, dest, ri)
  245. else:
  246. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  247. if getAttachedOp(c.graph, t, attachedSink) != nil:
  248. result = c.genOp(t, attachedSink, dest, ri)
  249. result.add ri
  250. else:
  251. # the default is to use combination of `=destroy(dest)` and
  252. # and copyMem(dest, source). This is efficient.
  253. if deepAliases(dest, ri):
  254. # consider: x = x + y, it is wrong to destroy the destination first!
  255. # tmp to support self assignments
  256. let tmp = c.getTemp(s, dest.typ, dest.info)
  257. result = newTree(nkStmtList, newTree(nkFastAsgn, tmp, dest), newTree(nkFastAsgn, dest, ri),
  258. c.genDestroy(tmp))
  259. else:
  260. result = newTree(nkStmtList, c.genDestroy(dest), newTree(nkFastAsgn, dest, ri))
  261. proc isCriticalLink(dest: PNode): bool {.inline.} =
  262. #[
  263. Lins's idea that only "critical" links can introduce a cycle. This is
  264. critical for the performance guarantees that we strive for: If you
  265. traverse a data structure, no tracing will be performed at all.
  266. ORC is about this promise: The GC only touches the memory that the
  267. mutator touches too.
  268. These constructs cannot possibly create cycles::
  269. local = ...
  270. new(x)
  271. dest = ObjectConstructor(field: noalias(dest))
  272. But since 'ObjectConstructor' is already moved into 'dest' all we really have
  273. to look for is assignments to local variables.
  274. ]#
  275. result = dest.kind != nkSym
  276. proc finishCopy(c: var Con; result, dest: PNode; flags: set[MoveOrCopyFlag]; isFromSink: bool) =
  277. if c.graph.config.selectedGC == gcOrc and IsExplicitSink notin flags:
  278. # add cyclic flag, but not to sink calls, which IsExplicitSink generates
  279. let t = dest.typ.skipTypes(tyUserTypeClasses + {tyGenericInst, tyAlias, tySink, tyDistinct})
  280. if cyclicType(c.graph, t):
  281. result.add boolLit(c.graph, result.info, isFromSink or isCriticalLink(dest))
  282. proc genMarkCyclic(c: var Con; result, dest: PNode) =
  283. if c.graph.config.selectedGC == gcOrc:
  284. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  285. if cyclicType(c.graph, t):
  286. if t.kind == tyRef:
  287. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, dest)
  288. else:
  289. let xenv = genBuiltin(c.graph, c.idgen, mAccessEnv, "accessEnv", dest)
  290. xenv.typ() = getSysType(c.graph, dest.info, tyPointer)
  291. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, xenv)
  292. proc genCopyNoCheck(c: var Con; dest, ri: PNode; a: TTypeAttachedOp): PNode =
  293. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  294. result = c.genOp(t, a, dest, ri)
  295. assert ri.typ != nil
  296. proc genCopy(c: var Con; dest, ri: PNode; flags: set[MoveOrCopyFlag]): PNode =
  297. if c.inEnsureMove > 0:
  298. localError(c.graph.config, ri.info, errFailedMove, "cannot move '" & $ri &
  299. "', which introduces an implicit copy")
  300. let t = dest.typ
  301. if tfHasOwned in t.flags and ri.kind != nkNilLit:
  302. # try to improve the error message here:
  303. if IsExplicitSink in flags:
  304. c.checkForErrorPragma(t, ri, "=sink")
  305. else:
  306. c.checkForErrorPragma(t, ri, "=copy")
  307. let a = if IsExplicitSink in flags: attachedSink else: attachedAsgn
  308. result = c.genCopyNoCheck(dest, ri, a)
  309. assert ri.typ != nil
  310. proc genDiscriminantAsgn(c: var Con; s: var Scope; n: PNode): PNode =
  311. # discriminator is ordinal value that doesn't need sink destroy
  312. # but fields within active case branch might need destruction
  313. # tmp to support self assignments
  314. let tmp = c.getTemp(s, n[1].typ, n.info)
  315. result = newTree(nkStmtList)
  316. result.add newTree(nkFastAsgn, tmp, p(n[1], c, s, consumed))
  317. result.add p(n[0], c, s, normal)
  318. let le = p(n[0], c, s, normal)
  319. let leDotExpr = if le.kind == nkCheckedFieldExpr: le[0] else: le
  320. let objType = leDotExpr[0].typ
  321. if hasDestructor(c, objType):
  322. if getAttachedOp(c.graph, objType, attachedDestructor) != nil and
  323. sfOverridden in getAttachedOp(c.graph, objType, attachedDestructor).flags:
  324. localError(c.graph.config, n.info, errGenerated, """Assignment to discriminant for objects with user defined destructor is not supported, object must have default destructor.
  325. It is best to factor out piece of object that needs custom destructor into separate object or not use discriminator assignment""")
  326. result.add newTree(nkFastAsgn, le, tmp)
  327. return
  328. # generate: if le != tmp: `=destroy`(le)
  329. if c.inUncheckedAssignSection != 0:
  330. let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info, c.idgen)
  331. let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  332. cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
  333. cond.add le
  334. cond.add tmp
  335. let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  336. notExpr.add newSymNode(createMagic(c.graph, c.idgen, "not", mNot))
  337. notExpr.add cond
  338. result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, c.genOp(branchDestructor, le)))
  339. result.add newTree(nkFastAsgn, le, tmp)
  340. proc genWasMoved(c: var Con, n: PNode): PNode =
  341. let typ = n.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  342. let op = getAttachedOp(c.graph, n.typ, attachedWasMoved)
  343. if op != nil:
  344. if sfError in op.flags:
  345. c.checkForErrorPragma(n.typ, n, "=wasMoved")
  346. result = genOp(c, op, n)
  347. else:
  348. result = newNodeI(nkCall, n.info)
  349. result.add(newSymNode(createMagic(c.graph, c.idgen, "`=wasMoved`", mWasMoved)))
  350. result.add copyTree(n) #mWasMoved does not take the address
  351. #if n.kind != nkSym:
  352. # message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
  353. proc genDefaultCall(t: PType; c: Con; info: TLineInfo): PNode =
  354. result = newNodeI(nkCall, info)
  355. result.add(newSymNode(createMagic(c.graph, c.idgen, "default", mDefault)))
  356. result.typ() = t
  357. proc destructiveMoveVar(n: PNode; c: var Con; s: var Scope): PNode =
  358. # generate: (let tmp = v; reset(v); tmp)
  359. if (not hasDestructor(c, n.typ)) and c.inEnsureMove == 0:
  360. assert n.kind != nkSym or not hasDestructor(c, n.sym.typ) or
  361. (n.typ.kind == tyPtr and n.sym.typ.kind == tyRef)
  362. # bug #23505; transformed by `transf`: addr (deref ref) -> ptr
  363. # we know it's really a pointer; so here we assign it directly
  364. result = copyTree(n)
  365. else:
  366. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  367. var temp = newSym(skLet, getIdent(c.graph.cache, "blitTmp"), c.idgen, c.owner, n.info)
  368. temp.typ = n.typ
  369. var v = newNodeI(nkLetSection, n.info)
  370. let tempAsNode = newSymNode(temp)
  371. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  372. vpart[0] = tempAsNode
  373. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  374. vpart[2] = n
  375. v.add(vpart)
  376. result.add v
  377. let nn = skipConv(n)
  378. if hasDestructor(c, n.typ):
  379. c.genMarkCyclic(result, nn)
  380. let wasMovedCall = c.genWasMoved(nn)
  381. result.add wasMovedCall
  382. result.add tempAsNode
  383. proc isCapturedVar(n: PNode): bool =
  384. let root = getRoot(n)
  385. if root != nil: result = root.name.s[0] == ':'
  386. else: result = false
  387. proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode =
  388. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  389. let nTyp = n.typ.skipTypes(tyUserTypeClasses)
  390. let tmp = c.getTemp(s, nTyp, n.info)
  391. if hasDestructor(c, nTyp):
  392. let typ = nTyp.skipTypes({tyGenericInst, tyAlias, tySink})
  393. let op = getAttachedOp(c.graph, typ, attachedDup)
  394. if op != nil and tfHasOwned notin typ.flags:
  395. if sfError in op.flags:
  396. c.checkForErrorPragma(nTyp, n, "=dup")
  397. else:
  398. let copyOp = getAttachedOp(c.graph, typ, attachedAsgn)
  399. if copyOp != nil and sfError in copyOp.flags and
  400. sfOverridden notin op.flags:
  401. c.checkForErrorPragma(nTyp, n, "=dup", inferredFromCopy = true)
  402. let src = p(n, c, s, normal)
  403. var newCall = newTreeIT(nkCall, src.info, src.typ,
  404. newSymNode(op),
  405. src)
  406. c.finishCopy(newCall, n, {}, isFromSink = true)
  407. result.add newTreeI(nkFastAsgn,
  408. src.info, tmp,
  409. newCall
  410. )
  411. else:
  412. result.add c.genWasMoved(tmp)
  413. var m = c.genCopy(tmp, n, {})
  414. m.add p(n, c, s, normal)
  415. c.finishCopy(m, n, {}, isFromSink = true)
  416. result.add m
  417. if isLValue(n) and not isCapturedVar(n) and nTyp.skipTypes(abstractInst).kind != tyRef and c.inSpawn == 0:
  418. message(c.graph.config, n.info, hintPerformance,
  419. ("passing '$1' to a sink parameter introduces an implicit copy; " &
  420. "if possible, rearrange your program's control flow to prevent it") % $n)
  421. if c.inEnsureMove > 0:
  422. localError(c.graph.config, n.info, errFailedMove,
  423. ("cannot move '$1', passing '$1' to a sink parameter introduces an implicit copy") % $n)
  424. else:
  425. if c.graph.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  426. assert(not containsManagedMemory(nTyp))
  427. if nTyp.skipTypes(abstractInst).kind in {tyOpenArray, tyVarargs}:
  428. localError(c.graph.config, n.info, "cannot create an implicit openArray copy to be passed to a sink parameter")
  429. result.add newTree(nkAsgn, tmp, p(n, c, s, normal))
  430. # Since we know somebody will take over the produced copy, there is
  431. # no need to destroy it.
  432. result.add tmp
  433. proc isDangerousSeq(t: PType): bool {.inline.} =
  434. let t = t.skipTypes(abstractInst)
  435. result = t.kind == tySequence and tfHasOwned notin t.elementType.flags
  436. proc containsConstSeq(n: PNode): bool =
  437. if n.kind == nkBracket and n.len > 0 and n.typ != nil and isDangerousSeq(n.typ):
  438. return true
  439. result = false
  440. case n.kind
  441. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv, nkCast:
  442. result = containsConstSeq(n[1])
  443. of nkObjConstr, nkClosure:
  444. for i in 1..<n.len:
  445. if containsConstSeq(n[i]): return true
  446. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  447. for son in n:
  448. if containsConstSeq(son): return true
  449. else: discard
  450. proc ensureDestruction(arg, orig: PNode; c: var Con; s: var Scope): PNode =
  451. # it can happen that we need to destroy expression contructors
  452. # like [], (), closures explicitly in order to not leak them.
  453. if arg.typ != nil and hasDestructor(c, arg.typ):
  454. # produce temp creation for (fn, env). But we need to move 'env'?
  455. # This was already done in the sink parameter handling logic.
  456. result = newNodeIT(nkStmtListExpr, arg.info, arg.typ)
  457. let tmp = c.getTemp(s, arg.typ, arg.info)
  458. result.add c.genSink(s, tmp, arg, {IsDecl})
  459. result.add tmp
  460. s.final.add c.genDestroy(tmp)
  461. else:
  462. result = arg
  463. proc cycleCheck(n: PNode; c: var Con) =
  464. if c.graph.config.selectedGC notin {gcArc, gcAtomicArc}: return
  465. var value = n[1]
  466. if value.kind == nkClosure:
  467. value = value[1]
  468. if value.kind == nkNilLit: return
  469. let destTyp = n[0].typ.skipTypes(abstractInst)
  470. if destTyp.kind != tyRef and not (destTyp.kind == tyProc and destTyp.callConv == ccClosure):
  471. return
  472. var x = n[0]
  473. var field: PNode = nil
  474. while true:
  475. if x.kind == nkDotExpr:
  476. field = x[1]
  477. if field.kind == nkSym and sfCursor in field.sym.flags: return
  478. x = x[0]
  479. elif x.kind in {nkBracketExpr, nkCheckedFieldExpr, nkDerefExpr, nkHiddenDeref}:
  480. x = x[0]
  481. else:
  482. break
  483. if exprStructuralEquivalent(x, value, strictSymEquality = true):
  484. let msg =
  485. if field != nil:
  486. "'$#' creates an uncollectable ref cycle; annotate '$#' with .cursor" % [$n, $field]
  487. else:
  488. "'$#' creates an uncollectable ref cycle" % [$n]
  489. message(c.graph.config, n.info, warnCycleCreated, msg)
  490. break
  491. proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; res: PNode) =
  492. # move the variable declaration to the top of the frame:
  493. s.vars.add v.sym
  494. if isUnpackedTuple(v):
  495. if c.inLoop > 0:
  496. # unpacked tuple needs reset at every loop iteration
  497. res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info))
  498. elif sfThread notin v.sym.flags and sfCursor notin v.sym.flags:
  499. # do not destroy thread vars for now at all for consistency.
  500. if {sfGlobal, sfPure} <= v.sym.flags or sfGlobal in v.sym.flags and s.parent == nil:
  501. c.graph.globalDestructors.add c.genDestroy(v)
  502. else:
  503. s.final.add c.genDestroy(v)
  504. proc processScope(c: var Con; s: var Scope; ret: PNode): PNode =
  505. result = newNodeI(nkStmtList, ret.info)
  506. if s.vars.len > 0:
  507. let varSection = newNodeI(nkVarSection, ret.info)
  508. for tmp in s.vars:
  509. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  510. newNodeI(nkEmpty, ret.info))
  511. result.add varSection
  512. if s.wasMoved.len > 0 or s.final.len > 0:
  513. let finSection = newNodeI(nkStmtList, ret.info)
  514. for m in s.wasMoved: finSection.add m
  515. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  516. if s.needsTry:
  517. result.add newTryFinally(ret, finSection)
  518. else:
  519. result.add ret
  520. result.add finSection
  521. else:
  522. result.add ret
  523. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  524. template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped, tmpFlags: TSymFlags): PNode =
  525. assert not ret.typ.isEmptyType
  526. var result = newNodeIT(nkStmtListExpr, ret.info, ret.typ)
  527. # There is a possibility to do this check: s.wasMoved.len > 0 or s.final.len > 0
  528. # later and use it to eliminate the temporary when theres no need for it, but its
  529. # tricky because you would have to intercept moveOrCopy at a certain point
  530. let tmp = c.getTemp(s.parent[], ret.typ, ret.info)
  531. tmp.sym.flags = tmpFlags
  532. let cpy = if hasDestructor(c, ret.typ) and
  533. ret.typ.kind notin {tyOpenArray, tyVarargs}:
  534. # bug #23247 we don't own the data, so it's harmful to destroy it
  535. s.parent[].final.add c.genDestroy(tmp)
  536. moveOrCopy(tmp, ret, c, s, {IsDecl})
  537. else:
  538. newTree(nkFastAsgn, tmp, p(ret, c, s, normal))
  539. if s.vars.len > 0:
  540. let varSection = newNodeI(nkVarSection, ret.info)
  541. for tmp in s.vars:
  542. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  543. newNodeI(nkEmpty, ret.info))
  544. result.add varSection
  545. let finSection = newNodeI(nkStmtList, ret.info)
  546. for m in s.wasMoved: finSection.add m
  547. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  548. if s.needsTry:
  549. result.add newTryFinally(newTree(nkStmtListExpr, cpy, processCall(tmp, s.parent[])), finSection)
  550. else:
  551. result.add cpy
  552. result.add finSection
  553. result.add processCall(tmp, s.parent[])
  554. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  555. result
  556. template handleNestedTempl(n, processCall: untyped, willProduceStmt = false,
  557. tmpFlags = {sfSingleUsedTemp}) =
  558. template maybeVoid(child, s): untyped =
  559. if isEmptyType(child.typ): p(child, c, s, normal)
  560. else: processCall(child, s)
  561. case n.kind
  562. of nkStmtList, nkStmtListExpr:
  563. # a statement list does not open a new scope
  564. if n.len == 0: return n
  565. result = copyNode(n)
  566. for i in 0..<n.len-1:
  567. result.add p(n[i], c, s, normal)
  568. result.add maybeVoid(n[^1], s)
  569. of nkCaseStmt:
  570. result = copyNode(n)
  571. result.add p(n[0], c, s, normal)
  572. for i in 1..<n.len:
  573. let it = n[i]
  574. assert it.kind in {nkOfBranch, nkElse}
  575. var branch = shallowCopy(it)
  576. for j in 0 ..< it.len-1:
  577. branch[j] = copyTree(it[j])
  578. var ofScope = nestedScope(s, it.lastSon)
  579. branch[^1] = if n.typ.isEmptyType or it[^1].typ.isEmptyType or willProduceStmt:
  580. processScope(c, ofScope, maybeVoid(it[^1], ofScope))
  581. else:
  582. processScopeExpr(c, ofScope, it[^1], processCall, tmpFlags)
  583. result.add branch
  584. of nkWhileStmt:
  585. inc c.inLoop
  586. inc c.inLoopCond
  587. result = copyNode(n)
  588. result.add p(n[0], c, s, normal)
  589. dec c.inLoopCond
  590. var bodyScope = nestedScope(s, n[1])
  591. let bodyResult = p(n[1], c, bodyScope, normal)
  592. result.add processScope(c, bodyScope, bodyResult)
  593. dec c.inLoop
  594. of nkParForStmt:
  595. inc c.inLoop
  596. result = shallowCopy(n)
  597. let last = n.len-1
  598. for i in 0..<last-1:
  599. result[i] = n[i]
  600. result[last-1] = p(n[last-1], c, s, normal)
  601. var bodyScope = nestedScope(s, n[1])
  602. let bodyResult = p(n[last], c, bodyScope, normal)
  603. result[last] = processScope(c, bodyScope, bodyResult)
  604. dec c.inLoop
  605. of nkBlockStmt, nkBlockExpr:
  606. result = copyNode(n)
  607. result.add n[0]
  608. var bodyScope = nestedScope(s, n[1])
  609. result.add if n[1].typ.isEmptyType or willProduceStmt:
  610. processScope(c, bodyScope, processCall(n[1], bodyScope))
  611. else:
  612. processScopeExpr(c, bodyScope, n[1], processCall, tmpFlags)
  613. of nkIfStmt, nkIfExpr:
  614. result = copyNode(n)
  615. for i in 0..<n.len:
  616. let it = n[i]
  617. var branch = shallowCopy(it)
  618. var branchScope = nestedScope(s, it.lastSon)
  619. if it.kind in {nkElifBranch, nkElifExpr}:
  620. #Condition needs to be destroyed outside of the condition/branch scope
  621. branch[0] = p(it[0], c, s, normal)
  622. branch[^1] = if n.typ.isEmptyType or it[^1].typ.isEmptyType or willProduceStmt:
  623. processScope(c, branchScope, maybeVoid(it[^1], branchScope))
  624. else:
  625. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  626. result.add branch
  627. of nkTryStmt:
  628. result = copyNode(n)
  629. var tryScope = nestedScope(s, n[0])
  630. result.add if n[0].typ.isEmptyType or willProduceStmt:
  631. processScope(c, tryScope, maybeVoid(n[0], tryScope))
  632. else:
  633. processScopeExpr(c, tryScope, n[0], maybeVoid, tmpFlags)
  634. for i in 1..<n.len:
  635. let it = n[i]
  636. var branch = copyTree(it)
  637. var branchScope = nestedScope(s, it[^1])
  638. branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt or it.kind == nkFinally:
  639. processScope(c, branchScope, if it.kind == nkFinally: p(it[^1], c, branchScope, normal)
  640. else: maybeVoid(it[^1], branchScope))
  641. else:
  642. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  643. result.add branch
  644. of nkWhen: # This should be a "when nimvm" node.
  645. result = copyTree(n)
  646. result[1][0] = processCall(n[1][0], s)
  647. of nkPragmaBlock:
  648. var inUncheckedAssignSection = 0
  649. let pragmaList = n[0]
  650. for pi in pragmaList:
  651. if whichPragma(pi) == wCast:
  652. case whichPragma(pi[1])
  653. of wUncheckedAssign:
  654. inUncheckedAssignSection = 1
  655. else:
  656. discard
  657. result = shallowCopy(n)
  658. inc c.inUncheckedAssignSection, inUncheckedAssignSection
  659. for i in 0 ..< n.len-1:
  660. result[i] = p(n[i], c, s, normal)
  661. result[^1] = maybeVoid(n[^1], s)
  662. dec c.inUncheckedAssignSection, inUncheckedAssignSection
  663. else:
  664. result = nil
  665. assert(false)
  666. proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
  667. if optOwnedRefs in c.graph.config.globalOptions and n[0].kind != nkEmpty:
  668. if n[0].kind in nkCallKinds:
  669. let call = p(n[0], c, s, normal)
  670. result = copyNode(n)
  671. result.add call
  672. else:
  673. let tmp = c.getTemp(s, n[0].typ, n.info)
  674. var m = c.genCopyNoCheck(tmp, n[0], attachedAsgn)
  675. m.add p(n[0], c, s, normal)
  676. c.finishCopy(m, n[0], {}, isFromSink = false)
  677. result = newTree(nkStmtList, c.genWasMoved(tmp), m)
  678. var toDisarm = n[0]
  679. if toDisarm.kind == nkStmtListExpr: toDisarm = toDisarm.lastSon
  680. if toDisarm.kind == nkSym and toDisarm.sym.owner == c.owner:
  681. result.add c.genWasMoved(toDisarm)
  682. result.add newTree(nkRaiseStmt, tmp)
  683. else:
  684. result = copyNode(n)
  685. if n[0].kind != nkEmpty:
  686. result.add p(n[0], c, s, sinkArg)
  687. else:
  688. result.add copyNode(n[0])
  689. s.needsTry = true
  690. template isCustomDestructor(c: Con, t: PType): bool =
  691. hasDestructor(c, t) and
  692. getAttachedOp(c.graph, t, attachedDestructor) != nil and
  693. sfOverridden in getAttachedOp(c.graph, t, attachedDestructor).flags
  694. proc hasCustomDestructor(c: Con, t: PType): bool =
  695. result = isCustomDestructor(c, t)
  696. var obj = t
  697. while obj.baseClass != nil:
  698. obj = skipTypes(obj.baseClass, abstractPtrs)
  699. result = result or isCustomDestructor(c, obj)
  700. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}; inReturn = false): PNode =
  701. if n.kind in {nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkIfStmt,
  702. nkIfExpr, nkCaseStmt, nkWhen, nkWhileStmt, nkParForStmt, nkTryStmt, nkPragmaBlock}:
  703. template process(child, s): untyped = p(child, c, s, mode)
  704. handleNestedTempl(n, process, tmpFlags = tmpFlags)
  705. elif mode == sinkArg:
  706. if n.containsConstSeq:
  707. # const sequences are not mutable and so we need to pass a copy to the
  708. # sink parameter (bug #11524). Note that the string implementation is
  709. # different and can deal with 'const string sunk into var'.
  710. result = passCopyToSink(n, c, s)
  711. elif n.kind in {nkBracket, nkObjConstr, nkTupleConstr, nkClosure, nkNilLit} +
  712. nkCallKinds + nkLiterals:
  713. if n.kind in nkCallKinds and n[0].kind == nkSym:
  714. if n[0].sym.magic == mEnsureMove:
  715. inc c.inEnsureMove
  716. result = p(n[1], c, s, sinkArg)
  717. dec c.inEnsureMove
  718. else:
  719. result = p(n, c, s, consumed)
  720. else:
  721. result = p(n, c, s, consumed)
  722. elif ((n.kind == nkSym and isSinkParam(n.sym)) or isAnalysableFieldAccess(n, c.owner)) and
  723. isLastRead(n, c, s) and not (n.kind == nkSym and isCursor(n)):
  724. # Sinked params can be consumed only once. We need to reset the memory
  725. # to disable the destructor which we have not elided
  726. result = destructiveMoveVar(n, c, s)
  727. elif n.kind in {nkHiddenSubConv, nkHiddenStdConv, nkConv}:
  728. result = copyTree(n)
  729. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  730. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  731. # allow conversions from owned to unowned via this little hack:
  732. let nTyp = n[1].typ
  733. n[1].typ() = n.typ
  734. result[1] = p(n[1], c, s, sinkArg)
  735. result[1].typ() = nTyp
  736. else:
  737. result[1] = p(n[1], c, s, sinkArg)
  738. elif n.kind in {nkObjDownConv, nkObjUpConv}:
  739. result = copyTree(n)
  740. result[0] = p(n[0], c, s, sinkArg)
  741. elif n.kind == nkCast and n.typ.skipTypes(abstractInst).kind in {tyString, tySequence}:
  742. result = copyTree(n)
  743. result[1] = p(n[1], c, s, sinkArg)
  744. elif n.typ == nil:
  745. # 'raise X' can be part of a 'case' expression. Deal with it here:
  746. result = p(n, c, s, normal)
  747. else:
  748. # copy objects that are not temporary but passed to a 'sink' parameter
  749. result = passCopyToSink(n, c, s)
  750. else:
  751. case n.kind
  752. of nkBracket, nkTupleConstr, nkClosure, nkCurly:
  753. # Let C(x) be the construction, 'x' the vector of arguments.
  754. # C(x) either owns 'x' or it doesn't.
  755. # If C(x) owns its data, we must consume C(x).
  756. # If it doesn't own the data, it's harmful to destroy it (double frees etc).
  757. # We have the freedom to choose whether it owns it or not so we are smart about it
  758. # and we say, "if passed to a sink we demand C(x) to own its data"
  759. # otherwise we say "C(x) is just some temporary storage, it doesn't own anything,
  760. # don't destroy it"
  761. # but if C(x) is a ref it MUST own its data since we must destroy it
  762. # so then we have no choice but to use 'sinkArg'.
  763. let m = if mode == normal: normal
  764. else: sinkArg
  765. result = copyTree(n)
  766. for i in ord(n.kind == nkClosure)..<n.len:
  767. if n[i].kind == nkExprColonExpr:
  768. result[i][1] = p(n[i][1], c, s, m)
  769. elif n[i].kind == nkRange:
  770. result[i][0] = p(n[i][0], c, s, m)
  771. result[i][1] = p(n[i][1], c, s, m)
  772. else:
  773. result[i] = p(n[i], c, s, m)
  774. of nkObjConstr:
  775. # see also the remark about `nkTupleConstr`.
  776. let t = n.typ.skipTypes(abstractInst)
  777. let isRefConstr = t.kind == tyRef
  778. let m = if isRefConstr: sinkArg
  779. elif mode == normal: normal
  780. else: sinkArg
  781. result = copyTree(n)
  782. for i in 1..<n.len:
  783. if n[i].kind == nkExprColonExpr:
  784. let field = lookupFieldAgain(t, n[i][0].sym)
  785. if field != nil and (sfCursor in field.flags or field.typ.kind in {tyOpenArray, tyVarargs}):
  786. # don't sink fields with openarray types
  787. result[i][1] = p(n[i][1], c, s, normal)
  788. else:
  789. result[i][1] = p(n[i][1], c, s, m)
  790. else:
  791. result[i] = p(n[i], c, s, m)
  792. if mode == normal and (isRefConstr or hasCustomDestructor(c, t)):
  793. result = ensureDestruction(result, n, c, s)
  794. of nkCallKinds:
  795. if n[0].kind == nkSym and n[0].sym.magic == mEnsureMove:
  796. inc c.inEnsureMove
  797. result = p(n[1], c, s, sinkArg)
  798. dec c.inEnsureMove
  799. return
  800. let inSpawn = c.inSpawn
  801. if n[0].kind == nkSym and n[0].sym.magic == mSpawn:
  802. c.inSpawn.inc
  803. elif c.inSpawn > 0:
  804. c.inSpawn.dec
  805. # bug #23907; skips tyGenericInst for generic callbacks
  806. let parameters = if n[0].typ != nil: n[0].typ.skipTypes(abstractInst) else: n[0].typ
  807. let L = if parameters != nil: parameters.signatureLen else: 0
  808. when false:
  809. var isDangerous = false
  810. if n[0].kind == nkSym and n[0].sym.magic in {mOr, mAnd}:
  811. inc c.inDangerousBranch
  812. isDangerous = true
  813. result = shallowCopy(n)
  814. for i in 1..<n.len:
  815. if i < L and isCompileTimeOnly(parameters[i]):
  816. result[i] = n[i]
  817. elif i < L and (isSinkTypeForParam(parameters[i]) or inSpawn > 0):
  818. result[i] = p(n[i], c, s, sinkArg)
  819. else:
  820. result[i] = p(n[i], c, s, normal)
  821. when false:
  822. if isDangerous:
  823. dec c.inDangerousBranch
  824. if n[0].kind == nkSym and n[0].sym.magic in {mNew, mNewFinalize}:
  825. result[0] = copyTree(n[0])
  826. if c.graph.config.selectedGC in {gcHooks, gcArc, gcAtomicArc, gcOrc}:
  827. let destroyOld = c.genDestroy(result[1])
  828. result = newTree(nkStmtList, destroyOld, result)
  829. else:
  830. result[0] = p(n[0], c, s, normal)
  831. if canRaise(n[0]): s.needsTry = true
  832. if mode == normal:
  833. if result.typ != nil and result.typ.kind notin {tyOpenArray, tyVarargs}:
  834. # Returns of openarray types shouldn't be destroyed
  835. # bug #19435; # bug #23247
  836. result = ensureDestruction(result, n, c, s)
  837. of nkDiscardStmt: # Small optimization
  838. result = shallowCopy(n)
  839. if n[0].kind != nkEmpty:
  840. result[0] = p(n[0], c, s, normal)
  841. else:
  842. result[0] = copyNode(n[0])
  843. of nkVarSection, nkLetSection:
  844. # transform; var x = y to var x; x op y where op is a move or copy
  845. result = newNodeI(nkStmtList, n.info)
  846. for it in n:
  847. var ri = it[^1]
  848. if it.kind == nkVarTuple and hasDestructor(c, ri.typ):
  849. for i in 0..<it.len-2:
  850. if it[i].kind == nkSym: s.locals.add it[i].sym
  851. let x = lowerTupleUnpacking(c.graph, it, c.idgen, c.owner)
  852. result.add p(x, c, s, consumed)
  853. elif it.kind == nkIdentDefs and hasDestructor(c, skipPragmaExpr(it[0]).typ):
  854. for j in 0..<it.len-2:
  855. let v = skipPragmaExpr(it[j])
  856. if v.kind == nkSym:
  857. if sfCompileTime in v.sym.flags: continue
  858. s.locals.add v.sym
  859. pVarTopLevel(v, c, s, result)
  860. if ri.kind != nkEmpty:
  861. result.add moveOrCopy(v, ri, c, s, if v.kind == nkSym: {IsDecl} else: {})
  862. elif ri.kind == nkEmpty and c.inLoop > 0:
  863. let skipInit = v.kind == nkDotExpr and # Closure var
  864. sfNoInit in v[1].sym.flags
  865. if not skipInit:
  866. result.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, if v.kind == nkSym: {IsDecl} else: {})
  867. else: # keep the var but transform 'ri':
  868. var v = copyNode(n)
  869. var itCopy = copyNode(it)
  870. for j in 0..<it.len-1:
  871. itCopy.add it[j]
  872. var flags = {sfSingleUsedTemp}
  873. if it.kind == nkIdentDefs and it.len == 3 and it[0].kind == nkSym and
  874. sfGlobal in it[0].sym.flags:
  875. flags.incl sfGlobal
  876. itCopy.add p(it[^1], c, s, normal, tmpFlags = flags)
  877. v.add itCopy
  878. result.add v
  879. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  880. if hasDestructor(c, n[0].typ) and n[1].kind notin {nkProcDef, nkDo, nkLambda}:
  881. if n[0].kind in {nkDotExpr, nkCheckedFieldExpr}:
  882. cycleCheck(n, c)
  883. assert n[1].kind notin {nkAsgn, nkFastAsgn, nkSinkAsgn}
  884. var flags = if n.kind == nkSinkAsgn: {IsExplicitSink} else: {}
  885. if inReturn:
  886. flags.incl(IsReturn)
  887. result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s, flags)
  888. elif isDiscriminantField(n[0]):
  889. result = c.genDiscriminantAsgn(s, n)
  890. else:
  891. result = copyNode(n)
  892. result.add p(n[0], c, s, mode)
  893. result.add p(n[1], c, s, consumed)
  894. of nkRaiseStmt:
  895. result = pRaiseStmt(n, c, s)
  896. of nkWhileStmt:
  897. internalError(c.graph.config, n.info, "nkWhileStmt should have been handled earlier")
  898. result = n
  899. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  900. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  901. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  902. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  903. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  904. result = n
  905. of nkStringToCString, nkCStringToString, nkChckRangeF, nkChckRange64, nkChckRange:
  906. result = shallowCopy(n)
  907. for i in 0 ..< n.len:
  908. result[i] = p(n[i], c, s, normal)
  909. if n.typ != nil and hasDestructor(c, n.typ):
  910. if mode == normal:
  911. result = ensureDestruction(result, n, c, s)
  912. of nkHiddenSubConv, nkHiddenStdConv, nkConv:
  913. # we have an "ownership invariance" for all constructors C(x).
  914. # See the comment for nkBracket construction. If the caller wants
  915. # to own 'C(x)', it really wants to own 'x' too. If it doesn't,
  916. # we need to destroy 'x' but the function call handling ensures that
  917. # already.
  918. result = copyTree(n)
  919. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  920. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  921. # allow conversions from owned to unowned via this little hack:
  922. let nTyp = n[1].typ
  923. n[1].typ() = n.typ
  924. result[1] = p(n[1], c, s, mode)
  925. result[1].typ() = nTyp
  926. else:
  927. result[1] = p(n[1], c, s, mode)
  928. of nkObjDownConv, nkObjUpConv:
  929. result = copyTree(n)
  930. result[0] = p(n[0], c, s, mode)
  931. of nkDotExpr:
  932. result = shallowCopy(n)
  933. result[0] = p(n[0], c, s, normal)
  934. for i in 1 ..< n.len:
  935. result[i] = n[i]
  936. if mode == sinkArg and hasDestructor(c, n.typ):
  937. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  938. s.wasMoved.add c.genWasMoved(n)
  939. else:
  940. result = passCopyToSink(result, c, s)
  941. of nkBracketExpr, nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  942. result = shallowCopy(n)
  943. for i in 0 ..< n.len:
  944. result[i] = p(n[i], c, s, normal)
  945. if mode == sinkArg and hasDestructor(c, n.typ):
  946. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  947. # consider 'a[(g; destroy(g); 3)]', we want to say 'wasMoved(a[3])'
  948. # without the junk, hence 'c.genWasMoved(n)'
  949. # and not 'c.genWasMoved(result)':
  950. s.wasMoved.add c.genWasMoved(n)
  951. else:
  952. result = passCopyToSink(result, c, s)
  953. of nkDefer, nkRange:
  954. result = shallowCopy(n)
  955. for i in 0 ..< n.len:
  956. result[i] = p(n[i], c, s, normal)
  957. of nkBreakStmt:
  958. s.needsTry = true
  959. result = n
  960. of nkReturnStmt:
  961. result = shallowCopy(n)
  962. for i in 0..<n.len:
  963. result[i] = p(n[i], c, s, mode, inReturn=true)
  964. s.needsTry = true
  965. of nkCast:
  966. result = shallowCopy(n)
  967. result[0] = n[0]
  968. result[1] = p(n[1], c, s, mode)
  969. of nkCheckedFieldExpr:
  970. result = shallowCopy(n)
  971. result[0] = p(n[0], c, s, mode)
  972. for i in 1..<n.len:
  973. result[i] = n[i]
  974. of nkGotoState, nkState, nkAsmStmt:
  975. result = n
  976. else:
  977. result = nil
  978. internalError(c.graph.config, n.info, "cannot inject destructors to node kind: " & $n.kind)
  979. proc sameLocation*(a, b: PNode): bool =
  980. proc sameConstant(a, b: PNode): bool =
  981. a.kind in nkLiterals and b.kind in nkLiterals and a.intVal == b.intVal
  982. const nkEndPoint = {nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}
  983. if a.kind in nkEndPoint and b.kind in nkEndPoint:
  984. if a.kind == b.kind:
  985. case a.kind
  986. of nkSym: a.sym == b.sym
  987. of nkDotExpr, nkCheckedFieldExpr: sameLocation(a[0], b[0]) and sameLocation(a[1], b[1])
  988. of nkBracketExpr: sameLocation(a[0], b[0]) and sameConstant(a[1], b[1])
  989. else: false
  990. else: false
  991. else:
  992. case a.kind
  993. of nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr:
  994. # Reached an endpoint, flip to recurse the other side.
  995. sameLocation(b, a)
  996. of nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  997. # We don't need to check addr/deref levels or differentiate between the two,
  998. # since pointers don't have hooks :) (e.g: var p: ptr pointer; p[] = addr p)
  999. sameLocation(a[0], b)
  1000. of nkObjDownConv, nkObjUpConv: sameLocation(a[0], b)
  1001. of nkHiddenStdConv, nkHiddenSubConv: sameLocation(a[1], b)
  1002. else: false
  1003. proc genFieldAccessSideEffects(c: var Con; s: var Scope; dest, ri: PNode; flags: set[MoveOrCopyFlag] = {}): PNode =
  1004. # with side effects
  1005. var temp = newSym(skLet, getIdent(c.graph.cache, "bracketTmp"), c.idgen, c.owner, ri[1].info)
  1006. temp.typ = ri[1].typ
  1007. var v = newNodeI(nkLetSection, ri[1].info)
  1008. let tempAsNode = newSymNode(temp)
  1009. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  1010. vpart[0] = tempAsNode
  1011. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  1012. vpart[2] = ri[1]
  1013. v.add(vpart)
  1014. var newAccess = copyNode(ri)
  1015. newAccess.add ri[0]
  1016. newAccess.add tempAsNode
  1017. var snk = c.genSink(s, dest, newAccess, flags)
  1018. result = newTree(nkStmtList, v, snk, c.genWasMoved(newAccess))
  1019. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, flags: set[MoveOrCopyFlag] = {}): PNode =
  1020. var ri = ri
  1021. var isEnsureMove = 0
  1022. if ri.kind in nkCallKinds and ri[0].kind == nkSym and ri[0].sym.magic == mEnsureMove:
  1023. ri = ri[1]
  1024. isEnsureMove = 1
  1025. if sameLocation(dest, ri):
  1026. # rule (self-assignment-removal):
  1027. result = newNodeI(nkEmpty, dest.info)
  1028. elif isCursor(dest) or dest.typ.kind in {tyOpenArray, tyVarargs}:
  1029. # hoisted openArray parameters might end up here
  1030. # openArray types don't have a lifted assignment operation (it's empty)
  1031. # bug #22132
  1032. case ri.kind:
  1033. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  1034. template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
  1035. # We know the result will be a stmt so we use that fact to optimize
  1036. handleNestedTempl(ri, process, willProduceStmt = true)
  1037. else:
  1038. result = newTree(nkFastAsgn, dest, p(ri, c, s, normal))
  1039. else:
  1040. let ri2 = if ri.kind == nkWhen: ri[1][0] else: ri
  1041. case ri2.kind
  1042. of nkCallKinds:
  1043. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1044. of nkBracketExpr:
  1045. if isUnpackedTuple(ri[0]):
  1046. # unpacking of tuple: take over the elements
  1047. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1048. elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s):
  1049. if aliases(dest, ri) == no:
  1050. # Rule 3: `=sink`(x, z); wasMoved(z)
  1051. if isAtom(ri[1]):
  1052. var snk = c.genSink(s, dest, ri, flags)
  1053. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1054. else:
  1055. result = genFieldAccessSideEffects(c, s, dest, ri, flags)
  1056. else:
  1057. result = c.genSink(s, dest, destructiveMoveVar(ri, c, s), flags)
  1058. else:
  1059. inc c.inEnsureMove, isEnsureMove
  1060. result = c.genCopy(dest, ri, flags)
  1061. dec c.inEnsureMove, isEnsureMove
  1062. result.add p(ri, c, s, consumed)
  1063. c.finishCopy(result, dest, flags, isFromSink = false)
  1064. of nkBracket:
  1065. # array constructor
  1066. if ri.len > 0 and isDangerousSeq(ri.typ):
  1067. inc c.inEnsureMove, isEnsureMove
  1068. result = c.genCopy(dest, ri, flags)
  1069. dec c.inEnsureMove, isEnsureMove
  1070. result.add p(ri, c, s, consumed)
  1071. c.finishCopy(result, dest, flags, isFromSink = false)
  1072. else:
  1073. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1074. of nkObjConstr, nkTupleConstr, nkClosure, nkCharLit..nkNilLit:
  1075. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1076. of nkSym:
  1077. if isSinkParam(ri.sym) and isLastRead(ri, c, s):
  1078. # Rule 3: `=sink`(x, z); wasMoved(z)
  1079. let snk = c.genSink(s, dest, ri, flags)
  1080. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1081. elif ri.sym.kind != skParam and
  1082. isAnalysableFieldAccess(ri, c.owner) and
  1083. isLastRead(ri, c, s) and canBeMoved(c, dest.typ):
  1084. # Rule 3: `=sink`(x, z); wasMoved(z)
  1085. let snk = c.genSink(s, dest, ri, flags)
  1086. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1087. else:
  1088. inc c.inEnsureMove, isEnsureMove
  1089. result = c.genCopy(dest, ri, flags)
  1090. dec c.inEnsureMove, isEnsureMove
  1091. result.add p(ri, c, s, consumed)
  1092. c.finishCopy(result, dest, flags, isFromSink = false)
  1093. of nkHiddenSubConv, nkHiddenStdConv, nkConv, nkObjDownConv, nkObjUpConv, nkCast:
  1094. result = c.genSink(s, dest, p(ri, c, s, sinkArg), flags)
  1095. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  1096. template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
  1097. # We know the result will be a stmt so we use that fact to optimize
  1098. handleNestedTempl(ri, process, willProduceStmt = true)
  1099. of nkRaiseStmt:
  1100. result = pRaiseStmt(ri, c, s)
  1101. else:
  1102. if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s) and
  1103. canBeMoved(c, dest.typ):
  1104. # Rule 3: `=sink`(x, z); wasMoved(z)
  1105. let snk = c.genSink(s, dest, ri, flags)
  1106. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1107. else:
  1108. inc c.inEnsureMove, isEnsureMove
  1109. result = c.genCopy(dest, ri, flags)
  1110. dec c.inEnsureMove, isEnsureMove
  1111. result.add p(ri, c, s, consumed)
  1112. c.finishCopy(result, dest, flags, isFromSink = false)
  1113. when false:
  1114. proc computeUninit(c: var Con) =
  1115. if not c.uninitComputed:
  1116. c.uninitComputed = true
  1117. c.uninit = initIntSet()
  1118. var init = initIntSet()
  1119. discard initialized(c.g, pc = 0, init, c.uninit, int.high)
  1120. proc injectDefaultCalls(n: PNode, c: var Con) =
  1121. case n.kind
  1122. of nkVarSection, nkLetSection:
  1123. for it in n:
  1124. if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
  1125. computeUninit(c)
  1126. for j in 0..<it.len-2:
  1127. let v = skipPragmaExpr(it[j])
  1128. doAssert v.kind == nkSym
  1129. if c.uninit.contains(v.sym.id):
  1130. it[^1] = genDefaultCall(v.sym.typ, c, v.info)
  1131. break
  1132. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
  1133. nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  1134. discard
  1135. else:
  1136. for i in 0..<n.safeLen:
  1137. injectDefaultCalls(n[i], c)
  1138. proc injectDestructorCalls*(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode =
  1139. when toDebug.len > 0:
  1140. shouldDebug = toDebug == owner.name.s or toDebug == "always"
  1141. if sfGeneratedOp in owner.flags or (owner.kind == skIterator and isInlineIterator(owner.typ)):
  1142. return n
  1143. var c = Con(owner: owner, graph: g, idgen: idgen, body: n, otherUsage: unknownLineInfo)
  1144. if optCursorInference in g.config.options:
  1145. computeCursors(owner, n, g)
  1146. var scope = Scope(body: n)
  1147. let body = p(n, c, scope, normal)
  1148. if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:
  1149. let params = owner.typ.n
  1150. for i in 1..<params.len:
  1151. let t = params[i].sym.typ
  1152. if isSinkTypeForParam(t) and hasDestructor(c, t.skipTypes({tySink})):
  1153. scope.final.add c.genDestroy(params[i])
  1154. #if optNimV2 in c.graph.config.globalOptions:
  1155. # injectDefaultCalls(n, c)
  1156. result = optimize processScope(c, scope, body)
  1157. dbg:
  1158. echo ">---------transformed-to--------->"
  1159. echo renderTree(result, {renderIds})
  1160. if g.config.arcToExpand.hasKey(owner.name.s):
  1161. echo "--expandArc: ", owner.name.s
  1162. echo renderTree(result, {renderIr, renderNoComments})
  1163. echo "-- end of expandArc ------------------------"