injectdestructors.nim 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. ## XXX Optimization to implement: if a local variable is only assigned
  14. ## string literals as in ``let x = conf: "foo" else: "bar"`` do not
  15. ## produce a destructor call for ``x``. The address of ``x`` must also
  16. ## not have been taken. ``x = "abc"; x.add(...)``
  17. # Todo:
  18. # - eliminate 'wasMoved(x); destroy(x)' pairs as a post processing step.
  19. import
  20. intsets, ast, astalgo, msgs, renderer, magicsys, types, idents,
  21. strutils, options, dfa, lowerings, tables, modulegraphs, msgs,
  22. lineinfos, parampatterns, sighashes, liftdestructors
  23. from trees import exprStructuralEquivalent, getRoot
  24. type
  25. Scope = object # well we do scope-based memory management. \
  26. # a scope is comparable to an nkStmtListExpr like
  27. # (try: statements; dest = y(); finally: destructors(); dest)
  28. vars: seq[PSym]
  29. wasMoved: seq[PNode]
  30. final: seq[PNode] # finally section
  31. needsTry: bool
  32. parent: ptr Scope
  33. proc nestedScope(parent: var Scope): Scope =
  34. Scope(vars: @[], wasMoved: @[], final: @[], needsTry: false, parent: addr(parent))
  35. proc rememberParent(parent: var Scope; inner: Scope) {.inline.} =
  36. parent.needsTry = parent.needsTry or inner.needsTry
  37. proc optimize(s: var Scope) =
  38. # optimize away simple 'wasMoved(x); destroy(x)' pairs.
  39. #[ Unfortunately this optimization is only really safe when no exceptions
  40. are possible, see for example:
  41. proc main(inp: string; cond: bool) =
  42. if cond:
  43. try:
  44. var s = ["hi", inp & "more"]
  45. for i in 0..4:
  46. echo s
  47. consume(s)
  48. wasMoved(s)
  49. finally:
  50. destroy(x)
  51. Now assume 'echo' raises, then we shouldn't do the 'wasMoved(s)'
  52. ]#
  53. # XXX: Investigate how to really insert 'wasMoved()' calls!
  54. proc findCorrespondingDestroy(final: seq[PNode]; moved: PNode): int =
  55. # remember that it's destroy(addr(x))
  56. for i in 0 ..< final.len:
  57. if final[i] != nil and exprStructuralEquivalent(final[i][1].skipAddr, moved, strictSymEquality = true):
  58. return i
  59. return -1
  60. var removed = 0
  61. for i in 0 ..< s.wasMoved.len:
  62. let j = findCorrespondingDestroy(s.final, s.wasMoved[i][1])
  63. if j >= 0:
  64. s.wasMoved[i] = nil
  65. s.final[j] = nil
  66. inc removed
  67. if removed > 0:
  68. template filterNil(field) =
  69. var m = newSeq[PNode](s.field.len - removed)
  70. var mi = 0
  71. for i in 0 ..< s.field.len:
  72. if s.field[i] != nil:
  73. m[mi] = s.field[i]
  74. inc mi
  75. assert mi == m.len
  76. s.field = m
  77. filterNil(wasMoved)
  78. filterNil(final)
  79. proc toTree(s: var Scope; ret: PNode; onlyCareAboutVars = false): PNode =
  80. if not s.needsTry: optimize(s)
  81. assert ret != nil
  82. if s.vars.len == 0 and s.final.len == 0 and s.wasMoved.len == 0:
  83. # trivial, nothing was done:
  84. result = ret
  85. else:
  86. if isEmptyType(ret.typ):
  87. result = newNodeI(nkStmtList, ret.info)
  88. else:
  89. result = newNodeIT(nkStmtListExpr, ret.info, ret.typ)
  90. if s.vars.len > 0:
  91. let varSection = newNodeI(nkVarSection, ret.info)
  92. for tmp in s.vars:
  93. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  94. newNodeI(nkEmpty, ret.info))
  95. result.add varSection
  96. if onlyCareAboutVars:
  97. result.add ret
  98. s.vars.setLen 0
  99. elif s.needsTry:
  100. var finSection = newNodeI(nkStmtList, ret.info)
  101. for m in s.wasMoved: finSection.add m
  102. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  103. result.add newTryFinally(ret, finSection)
  104. else:
  105. #assert isEmptyType(ret.typ)
  106. result.add ret
  107. for m in s.wasMoved: result.add m
  108. for i in countdown(s.final.high, 0): result.add s.final[i]
  109. type
  110. Con = object
  111. owner: PSym
  112. g: ControlFlowGraph
  113. jumpTargets: IntSet
  114. destroys, topLevelVars: PNode
  115. graph: ModuleGraph
  116. emptyNode: PNode
  117. otherRead: PNode
  118. inLoop, inSpawn: int
  119. uninit: IntSet # set of uninit'ed vars
  120. uninitComputed: bool
  121. ProcessMode = enum
  122. normal
  123. consumed
  124. sinkArg
  125. const toDebug {.strdefine.} = ""
  126. template dbg(body) =
  127. when toDebug.len > 0:
  128. if c.owner.name.s == toDebug or toDebug == "always":
  129. body
  130. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode
  131. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; isDecl = false): PNode
  132. proc isLastRead(location: PNode; cfg: ControlFlowGraph; otherRead: var PNode; pc, until: int): int =
  133. var pc = pc
  134. while pc < cfg.len and pc < until:
  135. case cfg[pc].kind
  136. of def:
  137. if instrTargets(cfg[pc].n, location) == Full:
  138. # the path leads to a redefinition of 's' --> abandon it.
  139. return high(int)
  140. elif instrTargets(cfg[pc].n, location) == Partial:
  141. # only partially writes to 's' --> can't sink 's', so this def reads 's'
  142. otherRead = cfg[pc].n
  143. return -1
  144. inc pc
  145. of use:
  146. if instrTargets(cfg[pc].n, location) != None:
  147. otherRead = cfg[pc].n
  148. return -1
  149. inc pc
  150. of goto:
  151. pc = pc + cfg[pc].dest
  152. of fork:
  153. # every branch must lead to the last read of the location:
  154. var variantA = pc + 1
  155. var variantB = pc + cfg[pc].dest
  156. while variantA != variantB:
  157. if min(variantA, variantB) < 0: return -1
  158. if max(variantA, variantB) >= cfg.len or min(variantA, variantB) >= until:
  159. break
  160. if variantA < variantB:
  161. variantA = isLastRead(location, cfg, otherRead, variantA, min(variantB, until))
  162. else:
  163. variantB = isLastRead(location, cfg, otherRead, variantB, min(variantA, until))
  164. pc = min(variantA, variantB)
  165. return pc
  166. proc isLastRead(n: PNode; c: var Con): bool =
  167. # first we need to search for the instruction that belongs to 'n':
  168. var instr = -1
  169. let m = dfa.skipConvDfa(n)
  170. for i in 0..<c.g.len:
  171. # This comparison is correct and MUST not be ``instrTargets``:
  172. if c.g[i].kind == use and c.g[i].n == m:
  173. if instr < 0:
  174. instr = i
  175. break
  176. dbg: echo "starting point for ", n, " is ", instr, " ", n.kind
  177. if instr < 0: return false
  178. # we go through all paths beginning from 'instr+1' and need to
  179. # ensure that we don't find another 'use X' instruction.
  180. if instr+1 >= c.g.len: return true
  181. c.otherRead = nil
  182. result = isLastRead(n, c.g, c.otherRead, instr+1, int.high) >= 0
  183. dbg: echo "ugh ", c.otherRead.isNil, " ", result
  184. proc isFirstWrite(location: PNode; cfg: ControlFlowGraph; pc, until: int): int =
  185. var pc = pc
  186. while pc < until:
  187. case cfg[pc].kind
  188. of def:
  189. if instrTargets(cfg[pc].n, location) != None:
  190. # a definition of 's' before ours makes ours not the first write
  191. return -1
  192. inc pc
  193. of use:
  194. if instrTargets(cfg[pc].n, location) != None:
  195. return -1
  196. inc pc
  197. of goto:
  198. pc = pc + cfg[pc].dest
  199. of fork:
  200. # every branch must not contain a def/use of our location:
  201. var variantA = pc + 1
  202. var variantB = pc + cfg[pc].dest
  203. while variantA != variantB:
  204. if min(variantA, variantB) < 0: return -1
  205. if max(variantA, variantB) > until:
  206. break
  207. if variantA < variantB:
  208. variantA = isFirstWrite(location, cfg, variantA, min(variantB, until))
  209. else:
  210. variantB = isFirstWrite(location, cfg, variantB, min(variantA, until))
  211. pc = min(variantA, variantB)
  212. return pc
  213. proc isFirstWrite(n: PNode; c: var Con): bool =
  214. # first we need to search for the instruction that belongs to 'n':
  215. var instr = -1
  216. let m = dfa.skipConvDfa(n)
  217. for i in countdown(c.g.len-1, 0): # We search backwards here to treat loops correctly
  218. if c.g[i].kind == def and c.g[i].n == m:
  219. if instr < 0:
  220. instr = i
  221. break
  222. if instr < 0: return false
  223. # we go through all paths going to 'instr' and need to
  224. # ensure that we don't find another 'def/use X' instruction.
  225. if instr == 0: return true
  226. result = isFirstWrite(n, c.g, 0, instr) >= 0
  227. proc initialized(code: ControlFlowGraph; pc: int,
  228. init, uninit: var IntSet; until: int): int =
  229. ## Computes the set of definitely initialized variables across all code paths
  230. ## as an IntSet of IDs.
  231. var pc = pc
  232. while pc < code.len:
  233. case code[pc].kind
  234. of goto:
  235. pc = pc + code[pc].dest
  236. of fork:
  237. var initA = initIntSet()
  238. var initB = initIntSet()
  239. var variantA = pc + 1
  240. var variantB = pc + code[pc].dest
  241. while variantA != variantB:
  242. if max(variantA, variantB) > until:
  243. break
  244. if variantA < variantB:
  245. variantA = initialized(code, variantA, initA, uninit, min(variantB, until))
  246. else:
  247. variantB = initialized(code, variantB, initB, uninit, min(variantA, until))
  248. pc = min(variantA, variantB)
  249. # we add vars if they are in both branches:
  250. for v in initA:
  251. if v in initB:
  252. init.incl v
  253. of use:
  254. let v = code[pc].n.sym
  255. if v.kind != skParam and v.id notin init:
  256. # attempt to read an uninit'ed variable
  257. uninit.incl v.id
  258. inc pc
  259. of def:
  260. let v = code[pc].n.sym
  261. init.incl v.id
  262. inc pc
  263. return pc
  264. template isUnpackedTuple(n: PNode): bool =
  265. ## we move out all elements of unpacked tuples,
  266. ## hence unpacked tuples themselves don't need to be destroyed
  267. (n.kind == nkSym and n.sym.kind == skTemp and n.sym.typ.kind == tyTuple)
  268. proc checkForErrorPragma(c: Con; t: PType; ri: PNode; opname: string) =
  269. var m = "'" & opname & "' is not available for type <" & typeToString(t) & ">"
  270. if opname == "=" and ri != nil:
  271. m.add "; requires a copy because it's not the last read of '"
  272. m.add renderTree(ri)
  273. m.add '\''
  274. if c.otherRead != nil:
  275. m.add "; another read is done here: "
  276. m.add c.graph.config $ c.otherRead.info
  277. elif ri.kind == nkSym and ri.sym.kind == skParam and not isSinkType(ri.sym.typ):
  278. m.add "; try to make "
  279. m.add renderTree(ri)
  280. m.add " a 'sink' parameter"
  281. m.add "; routine: "
  282. m.add c.owner.name.s
  283. localError(c.graph.config, ri.info, errGenerated, m)
  284. proc makePtrType(c: Con, baseType: PType): PType =
  285. result = newType(tyPtr, c.owner)
  286. addSonSkipIntLit(result, baseType)
  287. proc genOp(c: Con; op: PSym; dest: PNode): PNode =
  288. let addrExp = newNodeIT(nkHiddenAddr, dest.info, makePtrType(c, dest.typ))
  289. addrExp.add(dest)
  290. result = newTree(nkCall, newSymNode(op), addrExp)
  291. proc genOp(c: Con; t: PType; kind: TTypeAttachedOp; dest, ri: PNode): PNode =
  292. var op = t.attachedOps[kind]
  293. if op == nil or op.ast[genericParamsPos].kind != nkEmpty:
  294. # give up and find the canonical type instead:
  295. let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
  296. let canon = c.graph.canonTypes.getOrDefault(h)
  297. if canon != nil:
  298. op = canon.attachedOps[kind]
  299. if op == nil:
  300. #echo dest.typ.id
  301. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  302. "' operator not found for type " & typeToString(t))
  303. elif op.ast[genericParamsPos].kind != nkEmpty:
  304. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  305. "' operator is generic")
  306. dbg:
  307. if kind == attachedDestructor:
  308. echo "destructor is ", op.id, " ", op.ast
  309. if sfError in op.flags: checkForErrorPragma(c, t, ri, AttachedOpToStr[kind])
  310. genOp(c, op, dest)
  311. proc genDestroy(c: Con; dest: PNode): PNode =
  312. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  313. result = genOp(c, t, attachedDestructor, dest, nil)
  314. proc canBeMoved(c: Con; t: PType): bool {.inline.} =
  315. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  316. if optOwnedRefs in c.graph.config.globalOptions:
  317. result = t.kind != tyRef and t.attachedOps[attachedSink] != nil
  318. else:
  319. result = t.attachedOps[attachedSink] != nil
  320. proc isNoInit(dest: PNode): bool {.inline.} =
  321. result = dest.kind == nkSym and sfNoInit in dest.sym.flags
  322. proc genSink(c: var Con; s: var Scope; dest, ri: PNode, isDecl = false): PNode =
  323. if isUnpackedTuple(dest) or (isDecl and c.inLoop <= 0) or
  324. (isAnalysableFieldAccess(dest, c.owner) and isFirstWrite(dest, c)) or
  325. isNoInit(dest):
  326. # optimize sink call into a bitwise memcopy
  327. result = newTree(nkFastAsgn, dest, ri)
  328. else:
  329. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  330. if t.attachedOps[attachedSink] != nil:
  331. result = genOp(c, t, attachedSink, dest, ri)
  332. result.add ri
  333. else:
  334. # the default is to use combination of `=destroy(dest)` and
  335. # and copyMem(dest, source). This is efficient.
  336. let snk = newTree(nkFastAsgn, dest, ri)
  337. result = newTree(nkStmtList, genDestroy(c, dest), snk)
  338. proc genCopyNoCheck(c: Con; dest, ri: PNode): PNode =
  339. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  340. result = genOp(c, t, attachedAsgn, dest, ri)
  341. proc genCopy(c: var Con; dest, ri: PNode): PNode =
  342. let t = dest.typ
  343. if tfHasOwned in t.flags and ri.kind != nkNilLit:
  344. # try to improve the error message here:
  345. if c.otherRead == nil: discard isLastRead(ri, c)
  346. checkForErrorPragma(c, t, ri, "=")
  347. result = genCopyNoCheck(c, dest, ri)
  348. proc addTopVar(c: var Con; s: var Scope; v: PNode) =
  349. s.vars.add v.sym
  350. proc getTemp(c: var Con; s: var Scope; typ: PType; info: TLineInfo): PNode =
  351. let sym = newSym(skTemp, getIdent(c.graph.cache, ":tmpD"), c.owner, info)
  352. sym.typ = typ
  353. s.vars.add(sym)
  354. result = newSymNode(sym)
  355. proc genDiscriminantAsgn(c: var Con; s: var Scope; n: PNode): PNode =
  356. # discriminator is ordinal value that doesn't need sink destroy
  357. # but fields within active case branch might need destruction
  358. # tmp to support self assignments
  359. let tmp = getTemp(c, s, n[1].typ, n.info)
  360. result = newTree(nkStmtList)
  361. result.add newTree(nkFastAsgn, tmp, p(n[1], c, s, consumed))
  362. result.add p(n[0], c, s, normal)
  363. let le = p(n[0], c, s, normal)
  364. let leDotExpr = if le.kind == nkCheckedFieldExpr: le[0] else: le
  365. let objType = leDotExpr[0].typ
  366. if hasDestructor(objType):
  367. if objType.attachedOps[attachedDestructor] != nil and
  368. sfOverriden in objType.attachedOps[attachedDestructor].flags:
  369. localError(c.graph.config, n.info, errGenerated, """Assignment to discriminant for objects with user defined destructor is not supported, object must have default destructor.
  370. It is best to factor out piece of object that needs custom destructor into separate object or not use discriminator assignment""")
  371. result.add newTree(nkFastAsgn, le, tmp)
  372. return
  373. # generate: if le != tmp: `=destroy`(le)
  374. let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info)
  375. let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  376. cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
  377. cond.add le
  378. cond.add tmp
  379. let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  380. notExpr.add newSymNode(createMagic(c.graph, "not", mNot))
  381. notExpr.add cond
  382. result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, genOp(c, branchDestructor, le)))
  383. result.add newTree(nkFastAsgn, le, tmp)
  384. proc genWasMoved(n: PNode; c: var Con): PNode =
  385. result = newNodeI(nkCall, n.info)
  386. result.add(newSymNode(createMagic(c.graph, "wasMoved", mWasMoved)))
  387. result.add copyTree(n) #mWasMoved does not take the address
  388. #if n.kind != nkSym:
  389. # message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
  390. proc genDefaultCall(t: PType; c: Con; info: TLineInfo): PNode =
  391. result = newNodeI(nkCall, info)
  392. result.add(newSymNode(createMagic(c.graph, "default", mDefault)))
  393. result.typ = t
  394. proc destructiveMoveVar(n: PNode; c: var Con; s: var Scope): PNode =
  395. # generate: (let tmp = v; reset(v); tmp)
  396. if not hasDestructor(n.typ):
  397. result = copyTree(n)
  398. else:
  399. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  400. var temp = newSym(skLet, getIdent(c.graph.cache, "blitTmp"), c.owner, n.info)
  401. temp.typ = n.typ
  402. var v = newNodeI(nkLetSection, n.info)
  403. let tempAsNode = newSymNode(temp)
  404. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  405. vpart[0] = tempAsNode
  406. vpart[1] = c.emptyNode
  407. vpart[2] = n
  408. v.add(vpart)
  409. result.add v
  410. let wasMovedCall = genWasMoved(skipConv(n), c)
  411. result.add wasMovedCall
  412. result.add tempAsNode
  413. proc isCapturedVar(n: PNode): bool =
  414. let root = getRoot(n)
  415. if root != nil: result = root.name.s[0] == ':'
  416. proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode =
  417. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  418. let tmp = getTemp(c, s, n.typ, n.info)
  419. if hasDestructor(n.typ):
  420. result.add genWasMoved(tmp, c)
  421. var m = genCopy(c, tmp, n)
  422. m.add p(n, c, s, normal)
  423. result.add m
  424. if isLValue(n) and not isCapturedVar(n) and n.typ.skipTypes(abstractInst).kind != tyRef and c.inSpawn == 0:
  425. message(c.graph.config, n.info, hintPerformance,
  426. ("passing '$1' to a sink parameter introduces an implicit copy; " &
  427. "if possible, rearrange your program's control flow to prevent it") % $n)
  428. else:
  429. if c.graph.config.selectedGC in {gcArc, gcOrc}:
  430. assert(not containsGarbageCollectedRef(n.typ))
  431. result.add newTree(nkAsgn, tmp, p(n, c, s, normal))
  432. # Since we know somebody will take over the produced copy, there is
  433. # no need to destroy it.
  434. result.add tmp
  435. proc isDangerousSeq(t: PType): bool {.inline.} =
  436. let t = t.skipTypes(abstractInst)
  437. result = t.kind == tySequence and tfHasOwned notin t[0].flags
  438. proc containsConstSeq(n: PNode): bool =
  439. if n.kind == nkBracket and n.len > 0 and n.typ != nil and isDangerousSeq(n.typ):
  440. return true
  441. result = false
  442. case n.kind
  443. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv:
  444. result = containsConstSeq(n[1])
  445. of nkObjConstr, nkClosure:
  446. for i in 1..<n.len:
  447. if containsConstSeq(n[i]): return true
  448. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  449. for son in n:
  450. if containsConstSeq(son): return true
  451. else: discard
  452. proc ensureDestruction(arg: PNode; c: var Con; s: var Scope): PNode =
  453. # it can happen that we need to destroy expression contructors
  454. # like [], (), closures explicitly in order to not leak them.
  455. if arg.typ != nil and hasDestructor(arg.typ):
  456. # produce temp creation for (fn, env). But we need to move 'env'?
  457. # This was already done in the sink parameter handling logic.
  458. result = newNodeIT(nkStmtListExpr, arg.info, arg.typ)
  459. if s.parent != nil:
  460. let tmp = getTemp(c, s.parent[], arg.typ, arg.info)
  461. result.add genSink(c, s, tmp, arg, isDecl = true)
  462. result.add tmp
  463. s.parent[].final.add genDestroy(c, tmp)
  464. else:
  465. let tmp = getTemp(c, s, arg.typ, arg.info)
  466. result.add genSink(c, s, tmp, arg, isDecl = true)
  467. result.add tmp
  468. s.final.add genDestroy(c, tmp)
  469. else:
  470. result = arg
  471. proc isCursor(n: PNode): bool =
  472. case n.kind
  473. of nkSym:
  474. result = sfCursor in n.sym.flags
  475. of nkDotExpr:
  476. result = sfCursor in n[1].sym.flags
  477. of nkCheckedFieldExpr:
  478. result = isCursor(n[0])
  479. else:
  480. result = false
  481. proc cycleCheck(n: PNode; c: var Con) =
  482. if c.graph.config.selectedGC != gcArc: return
  483. var value = n[1]
  484. if value.kind == nkClosure:
  485. value = value[1]
  486. if value.kind == nkNilLit: return
  487. let destTyp = n[0].typ.skipTypes(abstractInst)
  488. if destTyp.kind != tyRef and not (destTyp.kind == tyProc and destTyp.callConv == ccClosure):
  489. return
  490. var x = n[0]
  491. var field: PNode = nil
  492. while true:
  493. if x.kind == nkDotExpr:
  494. field = x[1]
  495. if field.kind == nkSym and sfCursor in field.sym.flags: return
  496. x = x[0]
  497. elif x.kind in {nkBracketExpr, nkCheckedFieldExpr, nkDerefExpr, nkHiddenDeref}:
  498. x = x[0]
  499. else:
  500. break
  501. if exprStructuralEquivalent(x, value, strictSymEquality = true):
  502. let msg =
  503. if field != nil:
  504. "'$#' creates an uncollectable ref cycle; annotate '$#' with .cursor" % [$n, $field]
  505. else:
  506. "'$#' creates an uncollectable ref cycle" % [$n]
  507. message(c.graph.config, n.info, warnCycleCreated, msg)
  508. break
  509. proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; ri, res: PNode) =
  510. # move the variable declaration to the top of the frame:
  511. c.addTopVar s, v
  512. if isUnpackedTuple(v):
  513. if c.inLoop > 0:
  514. # unpacked tuple needs reset at every loop iteration
  515. res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info))
  516. elif sfThread notin v.sym.flags:
  517. # do not destroy thread vars for now at all for consistency.
  518. if sfGlobal in v.sym.flags and s.parent == nil:
  519. c.graph.globalDestructors.add genDestroy(c, v)
  520. else:
  521. s.final.add genDestroy(c, v)
  522. if ri.kind == nkEmpty and c.inLoop > 0:
  523. res.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, isDecl = true)
  524. elif ri.kind != nkEmpty:
  525. res.add moveOrCopy(v, ri, c, s, isDecl = true)
  526. template handleNestedTempl(n: untyped, processCall: untyped) =
  527. template maybeVoid(child, s): untyped =
  528. if isEmptyType(child.typ): p(child, c, s, normal)
  529. else: processCall(child, s)
  530. case n.kind
  531. of nkStmtList, nkStmtListExpr:
  532. # a statement list does not open a new scope
  533. if n.len == 0: return n
  534. result = copyNode(n)
  535. for i in 0..<n.len-1:
  536. result.add p(n[i], c, s, normal)
  537. result.add maybeVoid(n[^1], s)
  538. of nkCaseStmt:
  539. result = copyNode(n)
  540. result.add p(n[0], c, s, normal)
  541. for i in 1..<n.len:
  542. let it = n[i]
  543. assert it.kind in {nkOfBranch, nkElse}
  544. var branch = shallowCopy(it)
  545. for j in 0 ..< it.len-1:
  546. branch[j] = copyTree(it[j])
  547. var ofScope = nestedScope(s)
  548. let ofResult = maybeVoid(it[^1], ofScope)
  549. branch[^1] = toTree(ofScope, ofResult)
  550. result.add branch
  551. rememberParent(s, ofScope)
  552. of nkWhileStmt:
  553. inc c.inLoop
  554. result = copyNode(n)
  555. result.add p(n[0], c, s, normal)
  556. var bodyScope = nestedScope(s)
  557. let bodyResult = p(n[1], c, bodyScope, normal)
  558. result.add toTree(bodyScope, bodyResult)
  559. rememberParent(s, bodyScope)
  560. dec c.inLoop
  561. of nkBlockStmt, nkBlockExpr:
  562. result = copyNode(n)
  563. result.add n[0]
  564. var bodyScope = nestedScope(s)
  565. let bodyResult = processCall(n[1], bodyScope)
  566. result.add toTree(bodyScope, bodyResult)
  567. rememberParent(s, bodyScope)
  568. of nkIfStmt, nkIfExpr:
  569. result = copyNode(n)
  570. for i in 0..<n.len:
  571. let it = n[i]
  572. var branch = shallowCopy(it)
  573. var branchScope = nestedScope(s)
  574. branchScope.parent = nil
  575. if it.kind in {nkElifBranch, nkElifExpr}:
  576. let cond = p(it[0], c, branchScope, normal)
  577. branch[0] = toTree(branchScope, cond, onlyCareAboutVars = true)
  578. branchScope.parent = addr(s)
  579. var branchResult = processCall(it[^1], branchScope)
  580. branch[^1] = toTree(branchScope, branchResult)
  581. result.add branch
  582. rememberParent(s, branchScope)
  583. of nkTryStmt:
  584. result = copyNode(n)
  585. var tryScope = nestedScope(s)
  586. var tryResult = maybeVoid(n[0], tryScope)
  587. result.add toTree(tryScope, tryResult)
  588. rememberParent(s, tryScope)
  589. for i in 1..<n.len:
  590. let it = n[i]
  591. var branch = copyTree(it)
  592. var branchScope = nestedScope(s)
  593. var branchResult = if it.kind == nkFinally: p(it[^1], c, branchScope, normal)
  594. else: processCall(it[^1], branchScope)
  595. branch[^1] = toTree(branchScope, branchResult)
  596. result.add branch
  597. rememberParent(s, branchScope)
  598. of nkWhen: # This should be a "when nimvm" node.
  599. result = copyTree(n)
  600. result[1][0] = processCall(n[1][0], s)
  601. else: assert(false)
  602. proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
  603. if optOwnedRefs in c.graph.config.globalOptions and n[0].kind != nkEmpty:
  604. if n[0].kind in nkCallKinds:
  605. let call = p(n[0], c, s, normal)
  606. result = copyNode(n)
  607. result.add call
  608. else:
  609. let tmp = getTemp(c, s, n[0].typ, n.info)
  610. var m = genCopyNoCheck(c, tmp, n[0])
  611. m.add p(n[0], c, s, normal)
  612. result = newTree(nkStmtList, genWasMoved(tmp, c), m)
  613. var toDisarm = n[0]
  614. if toDisarm.kind == nkStmtListExpr: toDisarm = toDisarm.lastSon
  615. if toDisarm.kind == nkSym and toDisarm.sym.owner == c.owner:
  616. result.add genWasMoved(toDisarm, c)
  617. result.add newTree(nkRaiseStmt, tmp)
  618. else:
  619. result = copyNode(n)
  620. if n[0].kind != nkEmpty:
  621. result.add p(n[0], c, s, sinkArg)
  622. else:
  623. result.add copyNode(n[0])
  624. s.needsTry = true
  625. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode): PNode =
  626. if n.kind in {nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkIfStmt,
  627. nkIfExpr, nkCaseStmt, nkWhen, nkWhileStmt}:
  628. template process(child, s): untyped = p(child, c, s, mode)
  629. handleNestedTempl(n, process)
  630. elif mode == sinkArg:
  631. if n.containsConstSeq:
  632. # const sequences are not mutable and so we need to pass a copy to the
  633. # sink parameter (bug #11524). Note that the string implementation is
  634. # different and can deal with 'const string sunk into var'.
  635. result = passCopyToSink(n, c, s)
  636. elif n.kind in {nkBracket, nkObjConstr, nkTupleConstr, nkClosure, nkNilLit} +
  637. nkCallKinds + nkLiterals:
  638. result = p(n, c, s, consumed)
  639. elif n.kind == nkSym and isSinkParam(n.sym) and isLastRead(n, c):
  640. # Sinked params can be consumed only once. We need to reset the memory
  641. # to disable the destructor which we have not elided
  642. result = destructiveMoveVar(n, c, s)
  643. elif isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c):
  644. # it is the last read, can be sinkArg. We need to reset the memory
  645. # to disable the destructor which we have not elided
  646. result = destructiveMoveVar(n, c, s)
  647. elif n.kind in {nkHiddenSubConv, nkHiddenStdConv, nkConv}:
  648. result = copyTree(n)
  649. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  650. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  651. # allow conversions from owned to unowned via this little hack:
  652. let nTyp = n[1].typ
  653. n[1].typ = n.typ
  654. result[1] = p(n[1], c, s, sinkArg)
  655. result[1].typ = nTyp
  656. else:
  657. result[1] = p(n[1], c, s, sinkArg)
  658. elif n.kind in {nkObjDownConv, nkObjUpConv}:
  659. result = copyTree(n)
  660. result[0] = p(n[0], c, s, sinkArg)
  661. elif n.typ == nil:
  662. # 'raise X' can be part of a 'case' expression. Deal with it here:
  663. result = p(n, c, s, normal)
  664. else:
  665. # copy objects that are not temporary but passed to a 'sink' parameter
  666. result = passCopyToSink(n, c, s)
  667. else:
  668. case n.kind
  669. of nkBracket, nkObjConstr, nkTupleConstr, nkClosure:
  670. # Let C(x) be the construction, 'x' the vector of arguments.
  671. # C(x) either owns 'x' or it doesn't.
  672. # If C(x) owns its data, we must consume C(x).
  673. # If it doesn't own the data, it's harmful to destroy it (double frees etc).
  674. # We have the freedom to choose whether it owns it or not so we are smart about it
  675. # and we say, "if passed to a sink we demand C(x) to own its data"
  676. # otherwise we say "C(x) is just some temporary storage, it doesn't own anything,
  677. # don't destroy it"
  678. # but if C(x) is a ref it MUST own its data since we must destroy it
  679. # so then we have no choice but to use 'sinkArg'.
  680. let isRefConstr = n.kind == nkObjConstr and n.typ.skipTypes(abstractInst).kind == tyRef
  681. let m = if isRefConstr: sinkArg
  682. elif mode == normal: normal
  683. else: sinkArg
  684. result = copyTree(n)
  685. for i in ord(n.kind in {nkObjConstr, nkClosure})..<n.len:
  686. if n[i].kind == nkExprColonExpr:
  687. result[i][1] = p(n[i][1], c, s, m)
  688. else:
  689. result[i] = p(n[i], c, s, m)
  690. if mode == normal and isRefConstr:
  691. result = ensureDestruction(result, c, s)
  692. of nkCallKinds:
  693. let inSpawn = c.inSpawn
  694. if n[0].kind == nkSym and n[0].sym.magic == mSpawn:
  695. c.inSpawn.inc
  696. elif c.inSpawn > 0:
  697. c.inSpawn.dec
  698. let parameters = n[0].typ
  699. let L = if parameters != nil: parameters.len else: 0
  700. when false:
  701. var isDangerous = false
  702. if n[0].kind == nkSym and n[0].sym.magic in {mOr, mAnd}:
  703. inc c.inDangerousBranch
  704. isDangerous = true
  705. result = shallowCopy(n)
  706. for i in 1..<n.len:
  707. if 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 = genDestroy(c, 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, 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(ri.typ):
  736. let x = lowerTupleUnpacking(c.graph, it, c.owner)
  737. result.add p(x, c, s, consumed)
  738. elif it.kind == nkIdentDefs and hasDestructor(it[0].typ) and not isCursor(it[0]):
  739. for j in 0..<it.len-2:
  740. let v = it[j]
  741. if v.kind == nkSym:
  742. if sfCompileTime in v.sym.flags: continue
  743. pVarTopLevel(v, c, s, ri, result)
  744. else:
  745. if ri.kind == nkEmpty and c.inLoop > 0:
  746. ri = genDefaultCall(v.typ, c, v.info)
  747. if ri.kind != nkEmpty:
  748. result.add moveOrCopy(v, ri, c, s, isDecl = true)
  749. else: # keep the var but transform 'ri':
  750. var v = copyNode(n)
  751. var itCopy = copyNode(it)
  752. for j in 0..<it.len-1:
  753. itCopy.add it[j]
  754. itCopy.add p(it[^1], c, s, normal)
  755. v.add itCopy
  756. result.add v
  757. of nkAsgn, nkFastAsgn:
  758. if hasDestructor(n[0].typ) and n[1].kind notin {nkProcDef, nkDo, nkLambda} and
  759. not isCursor(n[0]):
  760. # rule (self-assignment-removal):
  761. if n[1].kind == nkSym and n[0].kind == nkSym and n[0].sym == n[1].sym:
  762. result = newNodeI(nkEmpty, n.info)
  763. else:
  764. if n[0].kind in {nkDotExpr, nkCheckedFieldExpr}:
  765. cycleCheck(n, c)
  766. assert n[1].kind notin {nkAsgn, nkFastAsgn}
  767. result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s)
  768. elif isDiscriminantField(n[0]):
  769. result = genDiscriminantAsgn(c, s, n)
  770. else:
  771. result = copyNode(n)
  772. result.add p(n[0], c, s, mode)
  773. result.add p(n[1], c, s, consumed)
  774. of nkRaiseStmt:
  775. result = pRaiseStmt(n, c, s)
  776. of nkWhileStmt:
  777. internalError(c.graph.config, n.info, "nkWhileStmt should have been handled earlier")
  778. result = n
  779. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  780. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  781. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  782. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState:
  783. result = n
  784. of nkBreakStmt:
  785. s.needsTry = true
  786. result = n
  787. of nkReturnStmt:
  788. result = shallowCopy(n)
  789. for i in 0..<n.len:
  790. result[i] = p(n[i], c, s, mode)
  791. s.needsTry = true
  792. of nkCast:
  793. result = shallowCopy(n)
  794. result[0] = n[0]
  795. result[1] = p(n[1], c, s, mode)
  796. of nkCheckedFieldExpr:
  797. result = shallowCopy(n)
  798. result[0] = p(n[0], c, s, mode)
  799. for i in 1..<n.len:
  800. result[i] = n[i]
  801. else:
  802. result = shallowCopy(n)
  803. for i in 0..<n.len:
  804. result[i] = p(n[i], c, s, mode)
  805. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, isDecl = false): PNode =
  806. case ri.kind
  807. of nkCallKinds:
  808. result = genSink(c, s, dest, p(ri, c, s, consumed), isDecl)
  809. of nkBracketExpr:
  810. if isUnpackedTuple(ri[0]):
  811. # unpacking of tuple: take over the elements
  812. result = genSink(c, s, dest, p(ri, c, s, consumed), isDecl)
  813. elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c) and
  814. not aliases(dest, ri):
  815. # Rule 3: `=sink`(x, z); wasMoved(z)
  816. var snk = genSink(c, s, dest, ri, isDecl)
  817. result = newTree(nkStmtList, snk, genWasMoved(ri, c))
  818. else:
  819. result = genCopy(c, dest, ri)
  820. result.add p(ri, c, s, consumed)
  821. of nkBracket:
  822. # array constructor
  823. if ri.len > 0 and isDangerousSeq(ri.typ):
  824. result = genCopy(c, dest, ri)
  825. result.add p(ri, c, s, consumed)
  826. else:
  827. result = genSink(c, s, dest, p(ri, c, s, consumed), isDecl)
  828. of nkObjConstr, nkTupleConstr, nkClosure, nkCharLit..nkNilLit:
  829. result = genSink(c, s, dest, p(ri, c, s, consumed), isDecl)
  830. of nkSym:
  831. if isSinkParam(ri.sym) and isLastRead(ri, c):
  832. # Rule 3: `=sink`(x, z); wasMoved(z)
  833. let snk = genSink(c, s, dest, ri, isDecl)
  834. result = newTree(nkStmtList, snk, genWasMoved(ri, c))
  835. elif ri.sym.kind != skParam and ri.sym.owner == c.owner and
  836. isLastRead(ri, c) and canBeMoved(c, dest.typ):
  837. # Rule 3: `=sink`(x, z); wasMoved(z)
  838. let snk = genSink(c, s, dest, ri, isDecl)
  839. result = newTree(nkStmtList, snk, genWasMoved(ri, c))
  840. else:
  841. result = genCopy(c, dest, ri)
  842. result.add p(ri, c, s, consumed)
  843. of nkHiddenSubConv, nkHiddenStdConv, nkConv, nkObjDownConv, nkObjUpConv:
  844. result = genSink(c, s, dest, p(ri, c, s, sinkArg), isDecl)
  845. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt:
  846. template process(child, s): untyped = moveOrCopy(dest, child, c, s, isDecl)
  847. handleNestedTempl(ri, process)
  848. of nkRaiseStmt:
  849. result = pRaiseStmt(ri, c, s)
  850. else:
  851. if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c) and
  852. canBeMoved(c, dest.typ):
  853. # Rule 3: `=sink`(x, z); wasMoved(z)
  854. let snk = genSink(c, s, dest, ri, isDecl)
  855. result = newTree(nkStmtList, snk, genWasMoved(ri, c))
  856. else:
  857. result = genCopy(c, dest, ri)
  858. result.add p(ri, c, s, consumed)
  859. proc computeUninit(c: var Con) =
  860. if not c.uninitComputed:
  861. c.uninitComputed = true
  862. c.uninit = initIntSet()
  863. var init = initIntSet()
  864. discard initialized(c.g, pc = 0, init, c.uninit, int.high)
  865. proc injectDefaultCalls(n: PNode, c: var Con) =
  866. case n.kind
  867. of nkVarSection, nkLetSection:
  868. for it in n:
  869. if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
  870. computeUninit(c)
  871. for j in 0..<it.len-2:
  872. let v = it[j]
  873. doAssert v.kind == nkSym
  874. if c.uninit.contains(v.sym.id):
  875. it[^1] = genDefaultCall(v.sym.typ, c, v.info)
  876. break
  877. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
  878. nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  879. discard
  880. else:
  881. for i in 0..<n.safeLen:
  882. injectDefaultCalls(n[i], c)
  883. proc extractDestroysForTemporaries(c: Con, destroys: PNode): PNode =
  884. result = newNodeI(nkStmtList, destroys.info)
  885. for i in 0..<destroys.len:
  886. if destroys[i][1][0].sym.kind in {skTemp, skForVar}:
  887. result.add destroys[i]
  888. destroys[i] = c.emptyNode
  889. proc injectDestructorCalls*(g: ModuleGraph; owner: PSym; n: PNode): PNode =
  890. if sfGeneratedOp in owner.flags or (owner.kind == skIterator and isInlineIterator(owner.typ)):
  891. return n
  892. var c: Con
  893. c.owner = owner
  894. c.destroys = newNodeI(nkStmtList, n.info)
  895. c.topLevelVars = newNodeI(nkVarSection, n.info)
  896. c.graph = g
  897. c.emptyNode = newNodeI(nkEmpty, n.info)
  898. let cfg = constructCfg(owner, n)
  899. shallowCopy(c.g, cfg)
  900. c.jumpTargets = initIntSet()
  901. for i in 0..<c.g.len:
  902. if c.g[i].kind in {goto, fork}:
  903. c.jumpTargets.incl(i+c.g[i].dest)
  904. dbg:
  905. echo "\n### ", owner.name.s, ":\nCFG:"
  906. echoCfg(c.g)
  907. echo n
  908. var scope: Scope
  909. let body = p(n, c, scope, normal)
  910. if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:
  911. let params = owner.typ.n
  912. for i in 1..<params.len:
  913. let t = params[i].sym.typ
  914. if isSinkTypeForParam(t) and hasDestructor(t.skipTypes({tySink})):
  915. scope.final.add genDestroy(c, params[i])
  916. #if optNimV2 in c.graph.config.globalOptions:
  917. # injectDefaultCalls(n, c)
  918. result = toTree(scope, body)
  919. dbg:
  920. echo ">---------transformed-to--------->"
  921. echo renderTree(result, {renderIds})