injectdestructors.nim 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281
  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; isFromSink: bool) =
  277. if c.graph.config.selectedGC == gcOrc:
  278. let t = dest.typ.skipTypes(tyUserTypeClasses + {tyGenericInst, tyAlias, tySink, tyDistinct})
  279. if cyclicType(c.graph, t):
  280. result.add boolLit(c.graph, result.info, isFromSink or isCriticalLink(dest))
  281. proc genMarkCyclic(c: var Con; result, dest: PNode) =
  282. if c.graph.config.selectedGC == gcOrc:
  283. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  284. if cyclicType(c.graph, t):
  285. if t.kind == tyRef:
  286. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, dest)
  287. else:
  288. let xenv = genBuiltin(c.graph, c.idgen, mAccessEnv, "accessEnv", dest)
  289. xenv.typ = getSysType(c.graph, dest.info, tyPointer)
  290. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, xenv)
  291. proc genCopyNoCheck(c: var Con; dest, ri: PNode; a: TTypeAttachedOp): PNode =
  292. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  293. result = c.genOp(t, a, dest, ri)
  294. assert ri.typ != nil
  295. proc genCopy(c: var Con; dest, ri: PNode; flags: set[MoveOrCopyFlag]): PNode =
  296. if c.inEnsureMove > 0:
  297. localError(c.graph.config, ri.info, errFailedMove, "cannot move '" & $ri &
  298. "', which introduces an implicit copy")
  299. let t = dest.typ
  300. if tfHasOwned in t.flags and ri.kind != nkNilLit:
  301. # try to improve the error message here:
  302. if IsExplicitSink in flags:
  303. c.checkForErrorPragma(t, ri, "=sink")
  304. else:
  305. c.checkForErrorPragma(t, ri, "=copy")
  306. let a = if IsExplicitSink in flags: attachedSink else: attachedAsgn
  307. result = c.genCopyNoCheck(dest, ri, a)
  308. assert ri.typ != nil
  309. proc genDiscriminantAsgn(c: var Con; s: var Scope; n: PNode): PNode =
  310. # discriminator is ordinal value that doesn't need sink destroy
  311. # but fields within active case branch might need destruction
  312. # tmp to support self assignments
  313. let tmp = c.getTemp(s, n[1].typ, n.info)
  314. result = newTree(nkStmtList)
  315. result.add newTree(nkFastAsgn, tmp, p(n[1], c, s, consumed))
  316. result.add p(n[0], c, s, normal)
  317. let le = p(n[0], c, s, normal)
  318. let leDotExpr = if le.kind == nkCheckedFieldExpr: le[0] else: le
  319. let objType = leDotExpr[0].typ
  320. if hasDestructor(c, objType):
  321. if getAttachedOp(c.graph, objType, attachedDestructor) != nil and
  322. sfOverridden in getAttachedOp(c.graph, objType, attachedDestructor).flags:
  323. localError(c.graph.config, n.info, errGenerated, """Assignment to discriminant for objects with user defined destructor is not supported, object must have default destructor.
  324. It is best to factor out piece of object that needs custom destructor into separate object or not use discriminator assignment""")
  325. result.add newTree(nkFastAsgn, le, tmp)
  326. return
  327. # generate: if le != tmp: `=destroy`(le)
  328. if c.inUncheckedAssignSection != 0:
  329. let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info, c.idgen)
  330. let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  331. cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
  332. cond.add le
  333. cond.add tmp
  334. let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  335. notExpr.add newSymNode(createMagic(c.graph, c.idgen, "not", mNot))
  336. notExpr.add cond
  337. result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, c.genOp(branchDestructor, le)))
  338. result.add newTree(nkFastAsgn, le, tmp)
  339. proc genWasMoved(c: var Con, n: PNode): PNode =
  340. let typ = n.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  341. let op = getAttachedOp(c.graph, n.typ, attachedWasMoved)
  342. if op != nil:
  343. if sfError in op.flags:
  344. c.checkForErrorPragma(n.typ, n, "=wasMoved")
  345. result = genOp(c, op, n)
  346. else:
  347. result = newNodeI(nkCall, n.info)
  348. result.add(newSymNode(createMagic(c.graph, c.idgen, "`=wasMoved`", mWasMoved)))
  349. result.add copyTree(n) #mWasMoved does not take the address
  350. #if n.kind != nkSym:
  351. # message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
  352. proc genDefaultCall(t: PType; c: Con; info: TLineInfo): PNode =
  353. result = newNodeI(nkCall, info)
  354. result.add(newSymNode(createMagic(c.graph, c.idgen, "default", mDefault)))
  355. result.typ = t
  356. proc destructiveMoveVar(n: PNode; c: var Con; s: var Scope): PNode =
  357. # generate: (let tmp = v; reset(v); tmp)
  358. if (not hasDestructor(c, n.typ)) and c.inEnsureMove == 0:
  359. assert n.kind != nkSym or not hasDestructor(c, n.sym.typ) or
  360. (n.typ.kind == tyPtr and n.sym.typ.kind == tyRef)
  361. # bug #23505; transformed by `transf`: addr (deref ref) -> ptr
  362. # we know it's really a pointer; so here we assign it directly
  363. result = copyTree(n)
  364. else:
  365. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  366. var temp = newSym(skLet, getIdent(c.graph.cache, "blitTmp"), c.idgen, c.owner, n.info)
  367. temp.typ = n.typ
  368. var v = newNodeI(nkLetSection, n.info)
  369. let tempAsNode = newSymNode(temp)
  370. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  371. vpart[0] = tempAsNode
  372. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  373. vpart[2] = n
  374. v.add(vpart)
  375. result.add v
  376. let nn = skipConv(n)
  377. if hasDestructor(c, n.typ):
  378. c.genMarkCyclic(result, nn)
  379. let wasMovedCall = c.genWasMoved(nn)
  380. result.add wasMovedCall
  381. result.add tempAsNode
  382. proc isCapturedVar(n: PNode): bool =
  383. let root = getRoot(n)
  384. if root != nil: result = root.name.s[0] == ':'
  385. else: result = false
  386. proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode =
  387. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  388. let nTyp = n.typ.skipTypes(tyUserTypeClasses)
  389. let tmp = c.getTemp(s, nTyp, n.info)
  390. if hasDestructor(c, nTyp):
  391. let typ = nTyp.skipTypes({tyGenericInst, tyAlias, tySink})
  392. let op = getAttachedOp(c.graph, typ, attachedDup)
  393. if op != nil and tfHasOwned notin typ.flags:
  394. if sfError in op.flags:
  395. c.checkForErrorPragma(nTyp, n, "=dup")
  396. else:
  397. let copyOp = getAttachedOp(c.graph, typ, attachedAsgn)
  398. if copyOp != nil and sfError in copyOp.flags and
  399. sfOverridden notin op.flags:
  400. c.checkForErrorPragma(nTyp, n, "=dup", inferredFromCopy = true)
  401. let src = p(n, c, s, normal)
  402. var newCall = newTreeIT(nkCall, src.info, src.typ,
  403. newSymNode(op),
  404. src)
  405. c.finishCopy(newCall, n, isFromSink = true)
  406. result.add newTreeI(nkFastAsgn,
  407. src.info, tmp,
  408. newCall
  409. )
  410. else:
  411. result.add c.genWasMoved(tmp)
  412. var m = c.genCopy(tmp, n, {})
  413. m.add p(n, c, s, normal)
  414. c.finishCopy(m, n, isFromSink = true)
  415. result.add m
  416. if isLValue(n) and not isCapturedVar(n) and nTyp.skipTypes(abstractInst).kind != tyRef and c.inSpawn == 0:
  417. message(c.graph.config, n.info, hintPerformance,
  418. ("passing '$1' to a sink parameter introduces an implicit copy; " &
  419. "if possible, rearrange your program's control flow to prevent it") % $n)
  420. if c.inEnsureMove > 0:
  421. localError(c.graph.config, n.info, errFailedMove,
  422. ("cannot move '$1', passing '$1' to a sink parameter introduces an implicit copy") % $n)
  423. else:
  424. if c.graph.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  425. assert(not containsManagedMemory(nTyp))
  426. if nTyp.skipTypes(abstractInst).kind in {tyOpenArray, tyVarargs}:
  427. localError(c.graph.config, n.info, "cannot create an implicit openArray copy to be passed to a sink parameter")
  428. result.add newTree(nkAsgn, tmp, p(n, c, s, normal))
  429. # Since we know somebody will take over the produced copy, there is
  430. # no need to destroy it.
  431. result.add tmp
  432. proc isDangerousSeq(t: PType): bool {.inline.} =
  433. let t = t.skipTypes(abstractInst)
  434. result = t.kind == tySequence and tfHasOwned notin t.elementType.flags
  435. proc containsConstSeq(n: PNode): bool =
  436. if n.kind == nkBracket and n.len > 0 and n.typ != nil and isDangerousSeq(n.typ):
  437. return true
  438. result = false
  439. case n.kind
  440. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv:
  441. result = containsConstSeq(n[1])
  442. of nkObjConstr, nkClosure:
  443. for i in 1..<n.len:
  444. if containsConstSeq(n[i]): return true
  445. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  446. for son in n:
  447. if containsConstSeq(son): return true
  448. else: discard
  449. proc ensureDestruction(arg, orig: PNode; c: var Con; s: var Scope): PNode =
  450. # it can happen that we need to destroy expression contructors
  451. # like [], (), closures explicitly in order to not leak them.
  452. if arg.typ != nil and hasDestructor(c, arg.typ):
  453. # produce temp creation for (fn, env). But we need to move 'env'?
  454. # This was already done in the sink parameter handling logic.
  455. result = newNodeIT(nkStmtListExpr, arg.info, arg.typ)
  456. let tmp = c.getTemp(s, arg.typ, arg.info)
  457. result.add c.genSink(s, tmp, arg, {IsDecl})
  458. result.add tmp
  459. s.final.add c.genDestroy(tmp)
  460. else:
  461. result = arg
  462. proc cycleCheck(n: PNode; c: var Con) =
  463. if c.graph.config.selectedGC notin {gcArc, gcAtomicArc}: return
  464. var value = n[1]
  465. if value.kind == nkClosure:
  466. value = value[1]
  467. if value.kind == nkNilLit: return
  468. let destTyp = n[0].typ.skipTypes(abstractInst)
  469. if destTyp.kind != tyRef and not (destTyp.kind == tyProc and destTyp.callConv == ccClosure):
  470. return
  471. var x = n[0]
  472. var field: PNode = nil
  473. while true:
  474. if x.kind == nkDotExpr:
  475. field = x[1]
  476. if field.kind == nkSym and sfCursor in field.sym.flags: return
  477. x = x[0]
  478. elif x.kind in {nkBracketExpr, nkCheckedFieldExpr, nkDerefExpr, nkHiddenDeref}:
  479. x = x[0]
  480. else:
  481. break
  482. if exprStructuralEquivalent(x, value, strictSymEquality = true):
  483. let msg =
  484. if field != nil:
  485. "'$#' creates an uncollectable ref cycle; annotate '$#' with .cursor" % [$n, $field]
  486. else:
  487. "'$#' creates an uncollectable ref cycle" % [$n]
  488. message(c.graph.config, n.info, warnCycleCreated, msg)
  489. break
  490. proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; res: PNode) =
  491. # move the variable declaration to the top of the frame:
  492. s.vars.add v.sym
  493. if isUnpackedTuple(v):
  494. if c.inLoop > 0:
  495. # unpacked tuple needs reset at every loop iteration
  496. res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info))
  497. elif sfThread notin v.sym.flags and sfCursor notin v.sym.flags:
  498. # do not destroy thread vars for now at all for consistency.
  499. if {sfGlobal, sfPure} <= v.sym.flags or sfGlobal in v.sym.flags and s.parent == nil:
  500. c.graph.globalDestructors.add c.genDestroy(v)
  501. else:
  502. s.final.add c.genDestroy(v)
  503. proc processScope(c: var Con; s: var Scope; ret: PNode): PNode =
  504. result = newNodeI(nkStmtList, ret.info)
  505. if s.vars.len > 0:
  506. let varSection = newNodeI(nkVarSection, ret.info)
  507. for tmp in s.vars:
  508. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  509. newNodeI(nkEmpty, ret.info))
  510. result.add varSection
  511. if s.wasMoved.len > 0 or s.final.len > 0:
  512. let finSection = newNodeI(nkStmtList, ret.info)
  513. for m in s.wasMoved: finSection.add m
  514. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  515. if s.needsTry:
  516. result.add newTryFinally(ret, finSection)
  517. else:
  518. result.add ret
  519. result.add finSection
  520. else:
  521. result.add ret
  522. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  523. template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped, tmpFlags: TSymFlags): PNode =
  524. assert not ret.typ.isEmptyType
  525. var result = newNodeIT(nkStmtListExpr, ret.info, ret.typ)
  526. # There is a possibility to do this check: s.wasMoved.len > 0 or s.final.len > 0
  527. # later and use it to eliminate the temporary when theres no need for it, but its
  528. # tricky because you would have to intercept moveOrCopy at a certain point
  529. let tmp = c.getTemp(s.parent[], ret.typ, ret.info)
  530. tmp.sym.flags = tmpFlags
  531. let cpy = if hasDestructor(c, ret.typ) and
  532. ret.typ.kind notin {tyOpenArray, tyVarargs}:
  533. # bug #23247 we don't own the data, so it's harmful to destroy it
  534. s.parent[].final.add c.genDestroy(tmp)
  535. moveOrCopy(tmp, ret, c, s, {IsDecl})
  536. else:
  537. newTree(nkFastAsgn, tmp, p(ret, c, s, normal))
  538. if s.vars.len > 0:
  539. let varSection = newNodeI(nkVarSection, ret.info)
  540. for tmp in s.vars:
  541. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  542. newNodeI(nkEmpty, ret.info))
  543. result.add varSection
  544. let finSection = newNodeI(nkStmtList, ret.info)
  545. for m in s.wasMoved: finSection.add m
  546. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  547. if s.needsTry:
  548. result.add newTryFinally(newTree(nkStmtListExpr, cpy, processCall(tmp, s.parent[])), finSection)
  549. else:
  550. result.add cpy
  551. result.add finSection
  552. result.add processCall(tmp, s.parent[])
  553. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  554. result
  555. template handleNestedTempl(n, processCall: untyped, willProduceStmt = false,
  556. tmpFlags = {sfSingleUsedTemp}) =
  557. template maybeVoid(child, s): untyped =
  558. if isEmptyType(child.typ): p(child, c, s, normal)
  559. else: processCall(child, s)
  560. case n.kind
  561. of nkStmtList, nkStmtListExpr:
  562. # a statement list does not open a new scope
  563. if n.len == 0: return n
  564. result = copyNode(n)
  565. for i in 0..<n.len-1:
  566. result.add p(n[i], c, s, normal)
  567. result.add maybeVoid(n[^1], s)
  568. of nkCaseStmt:
  569. result = copyNode(n)
  570. result.add p(n[0], c, s, normal)
  571. for i in 1..<n.len:
  572. let it = n[i]
  573. assert it.kind in {nkOfBranch, nkElse}
  574. var branch = shallowCopy(it)
  575. for j in 0 ..< it.len-1:
  576. branch[j] = copyTree(it[j])
  577. var ofScope = nestedScope(s, it.lastSon)
  578. branch[^1] = if n.typ.isEmptyType or it[^1].typ.isEmptyType or willProduceStmt:
  579. processScope(c, ofScope, maybeVoid(it[^1], ofScope))
  580. else:
  581. processScopeExpr(c, ofScope, it[^1], processCall, tmpFlags)
  582. result.add branch
  583. of nkWhileStmt:
  584. inc c.inLoop
  585. inc c.inLoopCond
  586. result = copyNode(n)
  587. result.add p(n[0], c, s, normal)
  588. dec c.inLoopCond
  589. var bodyScope = nestedScope(s, n[1])
  590. let bodyResult = p(n[1], c, bodyScope, normal)
  591. result.add processScope(c, bodyScope, bodyResult)
  592. dec c.inLoop
  593. of nkParForStmt:
  594. inc c.inLoop
  595. result = shallowCopy(n)
  596. let last = n.len-1
  597. for i in 0..<last-1:
  598. result[i] = n[i]
  599. result[last-1] = p(n[last-1], c, s, normal)
  600. var bodyScope = nestedScope(s, n[1])
  601. let bodyResult = p(n[last], c, bodyScope, normal)
  602. result[last] = processScope(c, bodyScope, bodyResult)
  603. dec c.inLoop
  604. of nkBlockStmt, nkBlockExpr:
  605. result = copyNode(n)
  606. result.add n[0]
  607. var bodyScope = nestedScope(s, n[1])
  608. result.add if n[1].typ.isEmptyType or willProduceStmt:
  609. processScope(c, bodyScope, processCall(n[1], bodyScope))
  610. else:
  611. processScopeExpr(c, bodyScope, n[1], processCall, tmpFlags)
  612. of nkIfStmt, nkIfExpr:
  613. result = copyNode(n)
  614. for i in 0..<n.len:
  615. let it = n[i]
  616. var branch = shallowCopy(it)
  617. var branchScope = nestedScope(s, it.lastSon)
  618. if it.kind in {nkElifBranch, nkElifExpr}:
  619. #Condition needs to be destroyed outside of the condition/branch scope
  620. branch[0] = p(it[0], c, s, normal)
  621. branch[^1] = if n.typ.isEmptyType or it[^1].typ.isEmptyType or willProduceStmt:
  622. processScope(c, branchScope, maybeVoid(it[^1], branchScope))
  623. else:
  624. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  625. result.add branch
  626. of nkTryStmt:
  627. result = copyNode(n)
  628. var tryScope = nestedScope(s, n[0])
  629. result.add if n[0].typ.isEmptyType or willProduceStmt:
  630. processScope(c, tryScope, maybeVoid(n[0], tryScope))
  631. else:
  632. processScopeExpr(c, tryScope, n[0], maybeVoid, tmpFlags)
  633. for i in 1..<n.len:
  634. let it = n[i]
  635. var branch = copyTree(it)
  636. var branchScope = nestedScope(s, it[^1])
  637. branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt or it.kind == nkFinally:
  638. processScope(c, branchScope, if it.kind == nkFinally: p(it[^1], c, branchScope, normal)
  639. else: maybeVoid(it[^1], branchScope))
  640. else:
  641. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  642. result.add branch
  643. of nkWhen: # This should be a "when nimvm" node.
  644. result = copyTree(n)
  645. result[1][0] = processCall(n[1][0], s)
  646. of nkPragmaBlock:
  647. var inUncheckedAssignSection = 0
  648. let pragmaList = n[0]
  649. for pi in pragmaList:
  650. if whichPragma(pi) == wCast:
  651. case whichPragma(pi[1])
  652. of wUncheckedAssign:
  653. inUncheckedAssignSection = 1
  654. else:
  655. discard
  656. result = shallowCopy(n)
  657. inc c.inUncheckedAssignSection, inUncheckedAssignSection
  658. for i in 0 ..< n.len-1:
  659. result[i] = p(n[i], c, s, normal)
  660. result[^1] = maybeVoid(n[^1], s)
  661. dec c.inUncheckedAssignSection, inUncheckedAssignSection
  662. else:
  663. result = nil
  664. assert(false)
  665. proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
  666. if optOwnedRefs in c.graph.config.globalOptions and n[0].kind != nkEmpty:
  667. if n[0].kind in nkCallKinds:
  668. let call = p(n[0], c, s, normal)
  669. result = copyNode(n)
  670. result.add call
  671. else:
  672. let tmp = c.getTemp(s, n[0].typ, n.info)
  673. var m = c.genCopyNoCheck(tmp, n[0], attachedAsgn)
  674. m.add p(n[0], c, s, normal)
  675. c.finishCopy(m, n[0], isFromSink = false)
  676. result = newTree(nkStmtList, c.genWasMoved(tmp), m)
  677. var toDisarm = n[0]
  678. if toDisarm.kind == nkStmtListExpr: toDisarm = toDisarm.lastSon
  679. if toDisarm.kind == nkSym and toDisarm.sym.owner == c.owner:
  680. result.add c.genWasMoved(toDisarm)
  681. result.add newTree(nkRaiseStmt, tmp)
  682. else:
  683. result = copyNode(n)
  684. if n[0].kind != nkEmpty:
  685. result.add p(n[0], c, s, sinkArg)
  686. else:
  687. result.add copyNode(n[0])
  688. s.needsTry = true
  689. template isCustomDestructor(c: Con, t: PType): bool =
  690. hasDestructor(c, t) and
  691. getAttachedOp(c.graph, t, attachedDestructor) != nil and
  692. sfOverridden in getAttachedOp(c.graph, t, attachedDestructor).flags
  693. proc hasCustomDestructor(c: Con, t: PType): bool =
  694. result = isCustomDestructor(c, t)
  695. var obj = t
  696. while obj.baseClass != nil:
  697. obj = skipTypes(obj.baseClass, abstractPtrs)
  698. result = result or isCustomDestructor(c, obj)
  699. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}; inReturn = false): PNode =
  700. if n.kind in {nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkIfStmt,
  701. nkIfExpr, nkCaseStmt, nkWhen, nkWhileStmt, nkParForStmt, nkTryStmt, nkPragmaBlock}:
  702. template process(child, s): untyped = p(child, c, s, mode)
  703. handleNestedTempl(n, process, tmpFlags = tmpFlags)
  704. elif mode == sinkArg:
  705. if n.containsConstSeq:
  706. # const sequences are not mutable and so we need to pass a copy to the
  707. # sink parameter (bug #11524). Note that the string implementation is
  708. # different and can deal with 'const string sunk into var'.
  709. result = passCopyToSink(n, c, s)
  710. elif n.kind in {nkBracket, nkObjConstr, nkTupleConstr, nkClosure, nkNilLit} +
  711. nkCallKinds + nkLiterals:
  712. if n.kind in nkCallKinds and n[0].kind == nkSym:
  713. if n[0].sym.magic == mEnsureMove:
  714. inc c.inEnsureMove
  715. result = p(n[1], c, s, sinkArg)
  716. dec c.inEnsureMove
  717. else:
  718. result = p(n, c, s, consumed)
  719. else:
  720. result = p(n, c, s, consumed)
  721. elif ((n.kind == nkSym and isSinkParam(n.sym)) or isAnalysableFieldAccess(n, c.owner)) and
  722. isLastRead(n, c, s) and not (n.kind == nkSym and isCursor(n)):
  723. # Sinked params can be consumed only once. We need to reset the memory
  724. # to disable the destructor which we have not elided
  725. result = destructiveMoveVar(n, c, s)
  726. elif n.kind in {nkHiddenSubConv, nkHiddenStdConv, nkConv}:
  727. result = copyTree(n)
  728. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  729. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  730. # allow conversions from owned to unowned via this little hack:
  731. let nTyp = n[1].typ
  732. n[1].typ = n.typ
  733. result[1] = p(n[1], c, s, sinkArg)
  734. result[1].typ = nTyp
  735. else:
  736. result[1] = p(n[1], c, s, sinkArg)
  737. elif n.kind in {nkObjDownConv, nkObjUpConv}:
  738. result = copyTree(n)
  739. result[0] = p(n[0], c, s, sinkArg)
  740. elif n.typ == nil:
  741. # 'raise X' can be part of a 'case' expression. Deal with it here:
  742. result = p(n, c, s, normal)
  743. else:
  744. # copy objects that are not temporary but passed to a 'sink' parameter
  745. result = passCopyToSink(n, c, s)
  746. else:
  747. case n.kind
  748. of nkBracket, nkTupleConstr, nkClosure, nkCurly:
  749. # Let C(x) be the construction, 'x' the vector of arguments.
  750. # C(x) either owns 'x' or it doesn't.
  751. # If C(x) owns its data, we must consume C(x).
  752. # If it doesn't own the data, it's harmful to destroy it (double frees etc).
  753. # We have the freedom to choose whether it owns it or not so we are smart about it
  754. # and we say, "if passed to a sink we demand C(x) to own its data"
  755. # otherwise we say "C(x) is just some temporary storage, it doesn't own anything,
  756. # don't destroy it"
  757. # but if C(x) is a ref it MUST own its data since we must destroy it
  758. # so then we have no choice but to use 'sinkArg'.
  759. let m = if mode == normal: normal
  760. else: sinkArg
  761. result = copyTree(n)
  762. for i in ord(n.kind == nkClosure)..<n.len:
  763. if n[i].kind == nkExprColonExpr:
  764. result[i][1] = p(n[i][1], c, s, m)
  765. elif n[i].kind == nkRange:
  766. result[i][0] = p(n[i][0], c, s, m)
  767. result[i][1] = p(n[i][1], c, s, m)
  768. else:
  769. result[i] = p(n[i], c, s, m)
  770. of nkObjConstr:
  771. # see also the remark about `nkTupleConstr`.
  772. let t = n.typ.skipTypes(abstractInst)
  773. let isRefConstr = t.kind == tyRef
  774. let m = if isRefConstr: sinkArg
  775. elif mode == normal: normal
  776. else: sinkArg
  777. result = copyTree(n)
  778. for i in 1..<n.len:
  779. if n[i].kind == nkExprColonExpr:
  780. let field = lookupFieldAgain(t, n[i][0].sym)
  781. if field != nil and (sfCursor in field.flags or field.typ.kind in {tyOpenArray, tyVarargs}):
  782. # don't sink fields with openarray types
  783. result[i][1] = p(n[i][1], c, s, normal)
  784. else:
  785. result[i][1] = p(n[i][1], c, s, m)
  786. else:
  787. result[i] = p(n[i], c, s, m)
  788. if mode == normal and (isRefConstr or hasCustomDestructor(c, t)):
  789. result = ensureDestruction(result, n, c, s)
  790. of nkCallKinds:
  791. if n[0].kind == nkSym and n[0].sym.magic == mEnsureMove:
  792. inc c.inEnsureMove
  793. result = p(n[1], c, s, sinkArg)
  794. dec c.inEnsureMove
  795. return
  796. let inSpawn = c.inSpawn
  797. if n[0].kind == nkSym and n[0].sym.magic == mSpawn:
  798. c.inSpawn.inc
  799. elif c.inSpawn > 0:
  800. c.inSpawn.dec
  801. # bug #23907; skips tyGenericInst for generic callbacks
  802. let parameters = if n[0].typ != nil: n[0].typ.skipTypes(abstractInst) else: n[0].typ
  803. let L = if parameters != nil: parameters.signatureLen else: 0
  804. when false:
  805. var isDangerous = false
  806. if n[0].kind == nkSym and n[0].sym.magic in {mOr, mAnd}:
  807. inc c.inDangerousBranch
  808. isDangerous = true
  809. result = shallowCopy(n)
  810. for i in 1..<n.len:
  811. if i < L and isCompileTimeOnly(parameters[i]):
  812. result[i] = n[i]
  813. elif i < L and (isSinkTypeForParam(parameters[i]) or inSpawn > 0):
  814. result[i] = p(n[i], c, s, sinkArg)
  815. else:
  816. result[i] = p(n[i], c, s, normal)
  817. when false:
  818. if isDangerous:
  819. dec c.inDangerousBranch
  820. if n[0].kind == nkSym and n[0].sym.magic in {mNew, mNewFinalize}:
  821. result[0] = copyTree(n[0])
  822. if c.graph.config.selectedGC in {gcHooks, gcArc, gcAtomicArc, gcOrc}:
  823. let destroyOld = c.genDestroy(result[1])
  824. result = newTree(nkStmtList, destroyOld, result)
  825. else:
  826. result[0] = p(n[0], c, s, normal)
  827. if canRaise(n[0]): s.needsTry = true
  828. if mode == normal:
  829. if result.typ != nil and result.typ.kind notin {tyOpenArray, tyVarargs}:
  830. # Returns of openarray types shouldn't be destroyed
  831. # bug #19435; # bug #23247
  832. result = ensureDestruction(result, n, c, s)
  833. of nkDiscardStmt: # Small optimization
  834. result = shallowCopy(n)
  835. if n[0].kind != nkEmpty:
  836. result[0] = p(n[0], c, s, normal)
  837. else:
  838. result[0] = copyNode(n[0])
  839. of nkVarSection, nkLetSection:
  840. # transform; var x = y to var x; x op y where op is a move or copy
  841. result = newNodeI(nkStmtList, n.info)
  842. for it in n:
  843. var ri = it[^1]
  844. if it.kind == nkVarTuple and hasDestructor(c, ri.typ):
  845. for i in 0..<it.len-2:
  846. if it[i].kind == nkSym: s.locals.add it[i].sym
  847. let x = lowerTupleUnpacking(c.graph, it, c.idgen, c.owner)
  848. result.add p(x, c, s, consumed)
  849. elif it.kind == nkIdentDefs and hasDestructor(c, skipPragmaExpr(it[0]).typ):
  850. for j in 0..<it.len-2:
  851. let v = skipPragmaExpr(it[j])
  852. if v.kind == nkSym:
  853. if sfCompileTime in v.sym.flags: continue
  854. s.locals.add v.sym
  855. pVarTopLevel(v, c, s, result)
  856. if ri.kind != nkEmpty:
  857. result.add moveOrCopy(v, ri, c, s, if v.kind == nkSym: {IsDecl} else: {})
  858. elif ri.kind == nkEmpty and c.inLoop > 0:
  859. let skipInit = v.kind == nkDotExpr and # Closure var
  860. sfNoInit in v[1].sym.flags
  861. if not skipInit:
  862. result.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, if v.kind == nkSym: {IsDecl} else: {})
  863. else: # keep the var but transform 'ri':
  864. var v = copyNode(n)
  865. var itCopy = copyNode(it)
  866. for j in 0..<it.len-1:
  867. itCopy.add it[j]
  868. var flags = {sfSingleUsedTemp}
  869. if it.kind == nkIdentDefs and it.len == 3 and it[0].kind == nkSym and
  870. sfGlobal in it[0].sym.flags:
  871. flags.incl sfGlobal
  872. itCopy.add p(it[^1], c, s, normal, tmpFlags = flags)
  873. v.add itCopy
  874. result.add v
  875. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  876. if hasDestructor(c, n[0].typ) and n[1].kind notin {nkProcDef, nkDo, nkLambda}:
  877. if n[0].kind in {nkDotExpr, nkCheckedFieldExpr}:
  878. cycleCheck(n, c)
  879. assert n[1].kind notin {nkAsgn, nkFastAsgn, nkSinkAsgn}
  880. var flags = if n.kind == nkSinkAsgn: {IsExplicitSink} else: {}
  881. if inReturn:
  882. flags.incl(IsReturn)
  883. result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s, flags)
  884. elif isDiscriminantField(n[0]):
  885. result = c.genDiscriminantAsgn(s, n)
  886. else:
  887. result = copyNode(n)
  888. result.add p(n[0], c, s, mode)
  889. result.add p(n[1], c, s, consumed)
  890. of nkRaiseStmt:
  891. result = pRaiseStmt(n, c, s)
  892. of nkWhileStmt:
  893. internalError(c.graph.config, n.info, "nkWhileStmt should have been handled earlier")
  894. result = n
  895. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  896. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  897. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  898. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  899. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  900. result = n
  901. of nkStringToCString, nkCStringToString, nkChckRangeF, nkChckRange64, nkChckRange:
  902. result = shallowCopy(n)
  903. for i in 0 ..< n.len:
  904. result[i] = p(n[i], c, s, normal)
  905. if n.typ != nil and hasDestructor(c, n.typ):
  906. if mode == normal:
  907. result = ensureDestruction(result, n, c, s)
  908. of nkHiddenSubConv, nkHiddenStdConv, nkConv:
  909. # we have an "ownership invariance" for all constructors C(x).
  910. # See the comment for nkBracket construction. If the caller wants
  911. # to own 'C(x)', it really wants to own 'x' too. If it doesn't,
  912. # we need to destroy 'x' but the function call handling ensures that
  913. # already.
  914. result = copyTree(n)
  915. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  916. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  917. # allow conversions from owned to unowned via this little hack:
  918. let nTyp = n[1].typ
  919. n[1].typ = n.typ
  920. result[1] = p(n[1], c, s, mode)
  921. result[1].typ = nTyp
  922. else:
  923. result[1] = p(n[1], c, s, mode)
  924. of nkObjDownConv, nkObjUpConv:
  925. result = copyTree(n)
  926. result[0] = p(n[0], c, s, mode)
  927. of nkDotExpr:
  928. result = shallowCopy(n)
  929. result[0] = p(n[0], c, s, normal)
  930. for i in 1 ..< n.len:
  931. result[i] = n[i]
  932. if mode == sinkArg and hasDestructor(c, n.typ):
  933. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  934. s.wasMoved.add c.genWasMoved(n)
  935. else:
  936. result = passCopyToSink(result, c, s)
  937. of nkBracketExpr, nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  938. result = shallowCopy(n)
  939. for i in 0 ..< n.len:
  940. result[i] = p(n[i], c, s, normal)
  941. if mode == sinkArg and hasDestructor(c, n.typ):
  942. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  943. # consider 'a[(g; destroy(g); 3)]', we want to say 'wasMoved(a[3])'
  944. # without the junk, hence 'c.genWasMoved(n)'
  945. # and not 'c.genWasMoved(result)':
  946. s.wasMoved.add c.genWasMoved(n)
  947. else:
  948. result = passCopyToSink(result, c, s)
  949. of nkDefer, nkRange:
  950. result = shallowCopy(n)
  951. for i in 0 ..< n.len:
  952. result[i] = p(n[i], c, s, normal)
  953. of nkBreakStmt:
  954. s.needsTry = true
  955. result = n
  956. of nkReturnStmt:
  957. result = shallowCopy(n)
  958. for i in 0..<n.len:
  959. result[i] = p(n[i], c, s, mode, inReturn=true)
  960. s.needsTry = true
  961. of nkCast:
  962. result = shallowCopy(n)
  963. result[0] = n[0]
  964. result[1] = p(n[1], c, s, mode)
  965. of nkCheckedFieldExpr:
  966. result = shallowCopy(n)
  967. result[0] = p(n[0], c, s, mode)
  968. for i in 1..<n.len:
  969. result[i] = n[i]
  970. of nkGotoState, nkState, nkAsmStmt:
  971. result = n
  972. else:
  973. result = nil
  974. internalError(c.graph.config, n.info, "cannot inject destructors to node kind: " & $n.kind)
  975. proc sameLocation*(a, b: PNode): bool =
  976. proc sameConstant(a, b: PNode): bool =
  977. a.kind in nkLiterals and b.kind in nkLiterals and a.intVal == b.intVal
  978. const nkEndPoint = {nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}
  979. if a.kind in nkEndPoint and b.kind in nkEndPoint:
  980. if a.kind == b.kind:
  981. case a.kind
  982. of nkSym: a.sym == b.sym
  983. of nkDotExpr, nkCheckedFieldExpr: sameLocation(a[0], b[0]) and sameLocation(a[1], b[1])
  984. of nkBracketExpr: sameLocation(a[0], b[0]) and sameConstant(a[1], b[1])
  985. else: false
  986. else: false
  987. else:
  988. case a.kind
  989. of nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr:
  990. # Reached an endpoint, flip to recurse the other side.
  991. sameLocation(b, a)
  992. of nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  993. # We don't need to check addr/deref levels or differentiate between the two,
  994. # since pointers don't have hooks :) (e.g: var p: ptr pointer; p[] = addr p)
  995. sameLocation(a[0], b)
  996. of nkObjDownConv, nkObjUpConv: sameLocation(a[0], b)
  997. of nkHiddenStdConv, nkHiddenSubConv: sameLocation(a[1], b)
  998. else: false
  999. proc genFieldAccessSideEffects(c: var Con; s: var Scope; dest, ri: PNode; flags: set[MoveOrCopyFlag] = {}): PNode =
  1000. # with side effects
  1001. var temp = newSym(skLet, getIdent(c.graph.cache, "bracketTmp"), c.idgen, c.owner, ri[1].info)
  1002. temp.typ = ri[1].typ
  1003. var v = newNodeI(nkLetSection, ri[1].info)
  1004. let tempAsNode = newSymNode(temp)
  1005. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  1006. vpart[0] = tempAsNode
  1007. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  1008. vpart[2] = ri[1]
  1009. v.add(vpart)
  1010. var newAccess = copyNode(ri)
  1011. newAccess.add ri[0]
  1012. newAccess.add tempAsNode
  1013. var snk = c.genSink(s, dest, newAccess, flags)
  1014. result = newTree(nkStmtList, v, snk, c.genWasMoved(newAccess))
  1015. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, flags: set[MoveOrCopyFlag] = {}): PNode =
  1016. var ri = ri
  1017. var isEnsureMove = 0
  1018. if ri.kind in nkCallKinds and ri[0].kind == nkSym and ri[0].sym.magic == mEnsureMove:
  1019. ri = ri[1]
  1020. isEnsureMove = 1
  1021. if sameLocation(dest, ri):
  1022. # rule (self-assignment-removal):
  1023. result = newNodeI(nkEmpty, dest.info)
  1024. elif isCursor(dest) or dest.typ.kind in {tyOpenArray, tyVarargs}:
  1025. # hoisted openArray parameters might end up here
  1026. # openArray types don't have a lifted assignment operation (it's empty)
  1027. # bug #22132
  1028. case ri.kind:
  1029. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  1030. template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
  1031. # We know the result will be a stmt so we use that fact to optimize
  1032. handleNestedTempl(ri, process, willProduceStmt = true)
  1033. else:
  1034. result = newTree(nkFastAsgn, dest, p(ri, c, s, normal))
  1035. else:
  1036. let ri2 = if ri.kind == nkWhen: ri[1][0] else: ri
  1037. case ri2.kind
  1038. of nkCallKinds:
  1039. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1040. of nkBracketExpr:
  1041. if isUnpackedTuple(ri[0]):
  1042. # unpacking of tuple: take over the elements
  1043. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1044. elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s):
  1045. if aliases(dest, ri) == no:
  1046. # Rule 3: `=sink`(x, z); wasMoved(z)
  1047. if isAtom(ri[1]):
  1048. var snk = c.genSink(s, dest, ri, flags)
  1049. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1050. else:
  1051. result = genFieldAccessSideEffects(c, s, dest, ri, flags)
  1052. else:
  1053. result = c.genSink(s, dest, destructiveMoveVar(ri, c, s), flags)
  1054. else:
  1055. inc c.inEnsureMove, isEnsureMove
  1056. result = c.genCopy(dest, ri, flags)
  1057. dec c.inEnsureMove, isEnsureMove
  1058. result.add p(ri, c, s, consumed)
  1059. c.finishCopy(result, dest, isFromSink = false)
  1060. of nkBracket:
  1061. # array constructor
  1062. if ri.len > 0 and isDangerousSeq(ri.typ):
  1063. inc c.inEnsureMove, isEnsureMove
  1064. result = c.genCopy(dest, ri, flags)
  1065. dec c.inEnsureMove, isEnsureMove
  1066. result.add p(ri, c, s, consumed)
  1067. c.finishCopy(result, dest, isFromSink = false)
  1068. else:
  1069. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1070. of nkObjConstr, nkTupleConstr, nkClosure, nkCharLit..nkNilLit:
  1071. result = c.genSink(s, dest, p(ri, c, s, consumed), flags)
  1072. of nkSym:
  1073. if isSinkParam(ri.sym) and isLastRead(ri, c, s):
  1074. # Rule 3: `=sink`(x, z); wasMoved(z)
  1075. let snk = c.genSink(s, dest, ri, flags)
  1076. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1077. elif ri.sym.kind != skParam and
  1078. isAnalysableFieldAccess(ri, c.owner) and
  1079. isLastRead(ri, c, s) and canBeMoved(c, dest.typ):
  1080. # Rule 3: `=sink`(x, z); wasMoved(z)
  1081. let snk = c.genSink(s, dest, ri, flags)
  1082. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1083. else:
  1084. inc c.inEnsureMove, isEnsureMove
  1085. result = c.genCopy(dest, ri, flags)
  1086. dec c.inEnsureMove, isEnsureMove
  1087. result.add p(ri, c, s, consumed)
  1088. c.finishCopy(result, dest, isFromSink = false)
  1089. of nkHiddenSubConv, nkHiddenStdConv, nkConv, nkObjDownConv, nkObjUpConv, nkCast:
  1090. result = c.genSink(s, dest, p(ri, c, s, sinkArg), flags)
  1091. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  1092. template process(child, s): untyped = moveOrCopy(dest, child, c, s, flags)
  1093. # We know the result will be a stmt so we use that fact to optimize
  1094. handleNestedTempl(ri, process, willProduceStmt = true)
  1095. of nkRaiseStmt:
  1096. result = pRaiseStmt(ri, c, s)
  1097. else:
  1098. if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s) and
  1099. canBeMoved(c, dest.typ):
  1100. # Rule 3: `=sink`(x, z); wasMoved(z)
  1101. let snk = c.genSink(s, dest, ri, flags)
  1102. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  1103. else:
  1104. inc c.inEnsureMove, isEnsureMove
  1105. result = c.genCopy(dest, ri, flags)
  1106. dec c.inEnsureMove, isEnsureMove
  1107. result.add p(ri, c, s, consumed)
  1108. c.finishCopy(result, dest, isFromSink = false)
  1109. when false:
  1110. proc computeUninit(c: var Con) =
  1111. if not c.uninitComputed:
  1112. c.uninitComputed = true
  1113. c.uninit = initIntSet()
  1114. var init = initIntSet()
  1115. discard initialized(c.g, pc = 0, init, c.uninit, int.high)
  1116. proc injectDefaultCalls(n: PNode, c: var Con) =
  1117. case n.kind
  1118. of nkVarSection, nkLetSection:
  1119. for it in n:
  1120. if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
  1121. computeUninit(c)
  1122. for j in 0..<it.len-2:
  1123. let v = skipPragmaExpr(it[j])
  1124. doAssert v.kind == nkSym
  1125. if c.uninit.contains(v.sym.id):
  1126. it[^1] = genDefaultCall(v.sym.typ, c, v.info)
  1127. break
  1128. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
  1129. nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  1130. discard
  1131. else:
  1132. for i in 0..<n.safeLen:
  1133. injectDefaultCalls(n[i], c)
  1134. proc injectDestructorCalls*(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode =
  1135. when toDebug.len > 0:
  1136. shouldDebug = toDebug == owner.name.s or toDebug == "always"
  1137. if sfGeneratedOp in owner.flags or (owner.kind == skIterator and isInlineIterator(owner.typ)):
  1138. return n
  1139. var c = Con(owner: owner, graph: g, idgen: idgen, body: n, otherUsage: unknownLineInfo)
  1140. if optCursorInference in g.config.options:
  1141. computeCursors(owner, n, g)
  1142. var scope = Scope(body: n)
  1143. let body = p(n, c, scope, normal)
  1144. if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:
  1145. let params = owner.typ.n
  1146. for i in 1..<params.len:
  1147. let t = params[i].sym.typ
  1148. if isSinkTypeForParam(t) and hasDestructor(c, t.skipTypes({tySink})):
  1149. scope.final.add c.genDestroy(params[i])
  1150. #if optNimV2 in c.graph.config.globalOptions:
  1151. # injectDefaultCalls(n, c)
  1152. result = optimize processScope(c, scope, body)
  1153. dbg:
  1154. echo ">---------transformed-to--------->"
  1155. echo renderTree(result, {renderIds})
  1156. if g.config.arcToExpand.hasKey(owner.name.s):
  1157. echo "--expandArc: ", owner.name.s
  1158. echo renderTree(result, {renderIr, renderNoComments})
  1159. echo "-- end of expandArc ------------------------"