injectdestructors.nim 44 KB

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