destroyer.nim 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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. ## Rules for destructor injections:
  13. ##
  14. ## foo(bar(X(), Y()))
  15. ## X and Y get destroyed after bar completes:
  16. ##
  17. ## foo( (tmpX = X(); tmpY = Y(); tmpBar = bar(tmpX, tmpY);
  18. ## destroy(tmpX); destroy(tmpY);
  19. ## tmpBar))
  20. ## destroy(tmpBar)
  21. ##
  22. ## var x = f()
  23. ## body
  24. ##
  25. ## is the same as:
  26. ##
  27. ## var x;
  28. ## try:
  29. ## move(x, f())
  30. ## finally:
  31. ## destroy(x)
  32. ##
  33. ## But this really just an optimization that tries to avoid to
  34. ## introduce too many temporaries, the 'destroy' is caused by
  35. ## the 'f()' call. No! That is not true for 'result = f()'!
  36. ##
  37. ## x = y where y is read only once
  38. ## is the same as: move(x, y)
  39. ##
  40. ## Actually the more general rule is: The *last* read of ``y``
  41. ## can become a move if ``y`` is the result of a construction.
  42. ##
  43. ## We also need to keep in mind here that the number of reads is
  44. ## control flow dependent:
  45. ## let x = foo()
  46. ## while true:
  47. ## y = x # only one read, but the 2nd iteration will fail!
  48. ## This also affects recursions! Only usages that do not cross
  49. ## a loop boundary (scope) and are not used in function calls
  50. ## are safe.
  51. ##
  52. ##
  53. ## x = f() is the same as: move(x, f())
  54. ##
  55. ## x = y
  56. ## is the same as: copy(x, y)
  57. ##
  58. ## Reassignment works under this scheme:
  59. ## var x = f()
  60. ## x = y
  61. ##
  62. ## is the same as:
  63. ##
  64. ## var x;
  65. ## try:
  66. ## move(x, f())
  67. ## copy(x, y)
  68. ## finally:
  69. ## destroy(x)
  70. ##
  71. ## result = f() must not destroy 'result'!
  72. ##
  73. ## The produced temporaries clutter up the code and might lead to
  74. ## inefficiencies. A better strategy is to collect all the temporaries
  75. ## in a single object that we put into a single try-finally that
  76. ## surrounds the proc body. This means the code stays quite efficient
  77. ## when compiled to C. In fact, we do the same for variables, so
  78. ## destructors are called when the proc returns, not at scope exit!
  79. ## This makes certains idioms easier to support. (Taking the slice
  80. ## of a temporary object.)
  81. ##
  82. ## foo(bar(X(), Y()))
  83. ## X and Y get destroyed after bar completes:
  84. ##
  85. ## var tmp: object
  86. ## foo( (move tmp.x, X(); move tmp.y, Y(); tmp.bar = bar(tmpX, tmpY);
  87. ## tmp.bar))
  88. ## destroy(tmp.bar)
  89. ## destroy(tmp.x); destroy(tmp.y)
  90. ##
  91. ##[
  92. From https://github.com/nim-lang/Nim/wiki/Destructors
  93. Rule Pattern Transformed into
  94. ---- ------- ----------------
  95. 1.1 var x: T; stmts var x: T; try stmts
  96. finally: `=destroy`(x)
  97. 1.2 var x: sink T; stmts var x: sink T; stmts; ensureEmpty(x)
  98. 2 x = f() `=sink`(x, f())
  99. 3 x = lastReadOf z `=sink`(x, z); wasMoved(z)
  100. 4.1 y = sinkParam `=sink`(y, sinkParam)
  101. 4.2 x = y `=`(x, y) # a copy
  102. 5.1 f_sink(g()) f_sink(g())
  103. 5.2 f_sink(y) f_sink(copy y); # copy unless we can see it's the last read
  104. 5.3 f_sink(move y) f_sink(y); wasMoved(y) # explicit moves empties 'y'
  105. 5.4 f_noSink(g()) var tmp = bitwiseCopy(g()); f(tmp); `=destroy`(tmp)
  106. Remarks: Rule 1.2 is not yet implemented because ``sink`` is currently
  107. not allowed as a local variable.
  108. ``move`` builtin needs to be implemented.
  109. ]##
  110. import
  111. intsets, ast, astalgo, msgs, renderer, magicsys, types, idents, trees,
  112. strutils, options, dfa, lowerings, tables, modulegraphs, msgs,
  113. lineinfos, parampatterns
  114. const
  115. InterestingSyms = {skVar, skResult, skLet}
  116. type
  117. Con = object
  118. owner: PSym
  119. g: ControlFlowGraph
  120. jumpTargets: IntSet
  121. destroys, topLevelVars: PNode
  122. graph: ModuleGraph
  123. emptyNode: PNode
  124. otherRead: PNode
  125. proc isLastRead(s: PSym; c: var Con; pc, comesFrom: int): int =
  126. var pc = pc
  127. while pc < c.g.len:
  128. case c.g[pc].kind
  129. of def:
  130. if c.g[pc].sym == s:
  131. # the path lead to a redefinition of 's' --> abandon it.
  132. return high(int)
  133. inc pc
  134. of use:
  135. if c.g[pc].sym == s:
  136. c.otherRead = c.g[pc].n
  137. return -1
  138. inc pc
  139. of goto:
  140. pc = pc + c.g[pc].dest
  141. of fork:
  142. # every branch must lead to the last read of the location:
  143. var variantA = isLastRead(s, c, pc+1, pc)
  144. if variantA < 0: return -1
  145. let variantB = isLastRead(s, c, pc + c.g[pc].dest, pc)
  146. if variantB < 0: return -1
  147. elif variantA == high(int):
  148. variantA = variantB
  149. pc = variantA
  150. of InstrKind.join:
  151. let dest = pc + c.g[pc].dest
  152. if dest == comesFrom: return pc + 1
  153. inc pc
  154. return pc
  155. proc isLastRead(n: PNode; c: var Con): bool =
  156. # first we need to search for the instruction that belongs to 'n':
  157. doAssert n.kind == nkSym
  158. c.otherRead = nil
  159. var instr = -1
  160. for i in 0..<c.g.len:
  161. if c.g[i].n == n:
  162. if instr < 0:
  163. instr = i
  164. break
  165. if instr < 0: return false
  166. # we go through all paths beginning from 'instr+1' and need to
  167. # ensure that we don't find another 'use X' instruction.
  168. if instr+1 >= c.g.len: return true
  169. when true:
  170. result = isLastRead(n.sym, c, instr+1, -1) >= 0
  171. else:
  172. let s = n.sym
  173. var pcs: seq[int] = @[instr+1]
  174. var takenGotos: IntSet
  175. var takenForks = initIntSet()
  176. while pcs.len > 0:
  177. var pc = pcs.pop
  178. takenGotos = initIntSet()
  179. while pc < c.g.len:
  180. case c.g[pc].kind
  181. of def:
  182. if c.g[pc].sym == s:
  183. # the path lead to a redefinition of 's' --> abandon it.
  184. break
  185. inc pc
  186. of use:
  187. if c.g[pc].sym == s:
  188. c.otherRead = c.g[pc].n
  189. return false
  190. inc pc
  191. of goto:
  192. # we must leave endless loops eventually:
  193. if not takenGotos.containsOrIncl(pc):
  194. pc = pc + c.g[pc].dest
  195. else:
  196. inc pc
  197. of fork:
  198. # we follow the next instruction but push the dest onto our "work" stack:
  199. if not takenForks.containsOrIncl(pc):
  200. pcs.add pc + c.g[pc].dest
  201. inc pc
  202. of InstrKind.join:
  203. inc pc
  204. #echo c.graph.config $ n.info, " last read here!"
  205. return true
  206. template interestingSym(s: PSym): bool =
  207. s.owner == c.owner and s.kind in InterestingSyms and hasDestructor(s.typ)
  208. template isUnpackedTuple(s: PSym): bool =
  209. ## we move out all elements of unpacked tuples,
  210. ## hence unpacked tuples themselves don't need to be destroyed
  211. s.kind == skTemp and s.typ.kind == tyTuple
  212. proc patchHead(n: PNode) =
  213. if n.kind in nkCallKinds and n[0].kind == nkSym and n.len > 1:
  214. let s = n[0].sym
  215. if s.name.s[0] == '=' and s.name.s in ["=sink", "=", "=destroy"]:
  216. if sfFromGeneric in s.flags:
  217. excl(s.flags, sfFromGeneric)
  218. patchHead(s.getBody)
  219. let t = n[1].typ.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink, tyInferred})
  220. template patch(op, field) =
  221. if s.name.s == op and field != nil and field != s:
  222. n.sons[0].sym = field
  223. patch "=sink", t.sink
  224. patch "=", t.assignment
  225. patch "=destroy", t.destructor
  226. for x in n:
  227. patchHead(x)
  228. proc patchHead(s: PSym) =
  229. if sfFromGeneric in s.flags:
  230. # do not patch the builtin type bound operators for seqs:
  231. let dest = s.typ.sons[1].skipTypes(abstractVar)
  232. if dest.kind != tySequence:
  233. patchHead(s.ast[bodyPos])
  234. proc checkForErrorPragma(c: Con; t: PType; ri: PNode; opname: string) =
  235. var m = "'" & opname & "' is not available for type <" & typeToString(t) & ">"
  236. if opname == "=" and ri != nil:
  237. m.add "; requires a copy because it's not the last read of '"
  238. m.add renderTree(ri)
  239. m.add '\''
  240. if c.otherRead != nil:
  241. m.add "; another read is done here: "
  242. m.add c.graph.config $ c.otherRead.info
  243. localError(c.graph.config, ri.info, errGenerated, m)
  244. proc makePtrType(c: Con, baseType: PType): PType =
  245. result = newType(tyPtr, c.owner)
  246. addSonSkipIntLit(result, baseType)
  247. template genOp(opr, opname, ri) =
  248. let op = opr
  249. if op == nil:
  250. globalError(c.graph.config, dest.info, "internal error: '" & opname &
  251. "' operator not found for type " & typeToString(t))
  252. elif op.ast[genericParamsPos].kind != nkEmpty:
  253. globalError(c.graph.config, dest.info, "internal error: '" & opname &
  254. "' operator is generic")
  255. patchHead op
  256. if sfError in op.flags: checkForErrorPragma(c, t, ri, opname)
  257. let addrExp = newNodeIT(nkHiddenAddr, dest.info, makePtrType(c, dest.typ))
  258. addrExp.add(dest)
  259. result = newTree(nkCall, newSymNode(op), addrExp)
  260. proc genSink(c: Con; t: PType; dest, ri: PNode): PNode =
  261. when false:
  262. if t.kind != tyString:
  263. echo "this one ", c.graph.config$dest.info, " for ", typeToString(t, preferDesc)
  264. debug t.sink.typ.sons[2]
  265. echo t.sink.id, " owner ", t.id
  266. quit 1
  267. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  268. genOp(if t.sink != nil: t.sink else: t.assignment, "=sink", ri)
  269. proc genCopy(c: Con; t: PType; dest, ri: PNode): PNode =
  270. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  271. genOp(t.assignment, "=", ri)
  272. proc genDestroy(c: Con; t: PType; dest: PNode): PNode =
  273. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  274. genOp(t.destructor, "=destroy", nil)
  275. proc addTopVar(c: var Con; v: PNode) =
  276. c.topLevelVars.add newTree(nkIdentDefs, v, c.emptyNode, c.emptyNode)
  277. proc getTemp(c: var Con; typ: PType; info: TLineInfo): PNode =
  278. let sym = newSym(skTemp, getIdent(c.graph.cache, ":tmpD"), c.owner, info)
  279. sym.typ = typ
  280. result = newSymNode(sym)
  281. c.addTopVar(result)
  282. proc p(n: PNode; c: var Con): PNode
  283. template recurse(n, dest) =
  284. for i in 0..<n.len:
  285. dest.add p(n[i], c)
  286. proc isSinkParam(s: PSym): bool {.inline.} =
  287. result = s.kind == skParam and s.typ.kind == tySink
  288. proc genMagicCall(n: PNode; c: var Con; magicname: string; m: TMagic): PNode =
  289. result = newNodeI(nkCall, n.info)
  290. result.add(newSymNode(createMagic(c.graph, magicname, m)))
  291. result.add n
  292. proc genWasMoved(n: PNode; c: var Con): PNode =
  293. # The mWasMoved builtin does not take the address.
  294. result = genMagicCall(n, c, "wasMoved", mWasMoved)
  295. proc destructiveMoveVar(n: PNode; c: var Con): PNode =
  296. # generate: (let tmp = v; reset(v); tmp)
  297. # XXX: Strictly speaking we can only move if there is a ``=sink`` defined
  298. # or if no ``=sink`` is defined and also no assignment.
  299. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  300. var temp = newSym(skLet, getIdent(c.graph.cache, "blitTmp"), c.owner, n.info)
  301. temp.typ = n.typ
  302. var v = newNodeI(nkLetSection, n.info)
  303. let tempAsNode = newSymNode(temp)
  304. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  305. vpart.sons[0] = tempAsNode
  306. vpart.sons[1] = c.emptyNode
  307. vpart.sons[2] = n
  308. add(v, vpart)
  309. result.add v
  310. result.add genWasMoved(n, c)
  311. result.add tempAsNode
  312. proc sinkParamIsLastReadCheck(c: var Con, s: PNode) =
  313. assert s.kind == nkSym and s.sym.kind == skParam
  314. if not isLastRead(s, c):
  315. localError(c.graph.config, c.otherRead.info, "sink parameter `" & $s.sym.name.s &
  316. "` is already consumed at " & toFileLineCol(c. graph.config, s.info))
  317. proc passCopyToSink(n: PNode; c: var Con): PNode =
  318. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  319. let tmp = getTemp(c, n.typ, n.info)
  320. if hasDestructor(n.typ):
  321. var m = genCopy(c, n.typ, tmp, n)
  322. m.add p(n, c)
  323. result.add m
  324. if isLValue(n):
  325. message(c.graph.config, n.info, hintPerformance,
  326. ("passing '$1' to a sink parameter introduces an implicit copy; " &
  327. "use 'move($1)' to prevent it") % $n)
  328. else:
  329. result.add newTree(nkAsgn, tmp, p(n, c))
  330. result.add tmp
  331. proc pArg(arg: PNode; c: var Con; isSink: bool): PNode =
  332. template pArgIfTyped(arg_part: PNode): PNode =
  333. # typ is nil if we are in if/case expr branch with noreturn
  334. if arg_part.typ == nil: p(arg_part, c)
  335. else: pArg(arg_part, c, isSink)
  336. if isSink:
  337. if arg.kind in nkCallKinds:
  338. # recurse but skip the call expression in order to prevent
  339. # destructor injections: Rule 5.1 is different from rule 5.4!
  340. result = copyNode(arg)
  341. let parameters = arg[0].typ
  342. let L = if parameters != nil: parameters.len else: 0
  343. result.add arg[0]
  344. for i in 1..<arg.len:
  345. result.add pArg(arg[i], c, i < L and parameters[i].kind == tySink)
  346. elif arg.kind in {nkBracket, nkObjConstr, nkTupleConstr, nkBracket, nkCharLit..nkFloat128Lit}:
  347. discard "object construction to sink parameter: nothing to do"
  348. result = arg
  349. elif arg.kind == nkSym and isSinkParam(arg.sym):
  350. # Sinked params can be consumed only once. We need to reset the memory
  351. # to disable the destructor which we have not elided
  352. sinkParamIsLastReadCheck(c, arg)
  353. result = destructiveMoveVar(arg, c)
  354. elif arg.kind == nkSym and arg.sym.kind in InterestingSyms and isLastRead(arg, c):
  355. # it is the last read, can be sinked. We need to reset the memory
  356. # to disable the destructor which we have not elided
  357. result = destructiveMoveVar(arg, c)
  358. elif arg.kind in {nkBlockExpr, nkBlockStmt}:
  359. result = copyNode(arg)
  360. result.add arg[0]
  361. result.add pArg(arg[1], c, isSink)
  362. elif arg.kind == nkStmtListExpr:
  363. result = copyNode(arg)
  364. for i in 0..arg.len-2:
  365. result.add p(arg[i], c)
  366. result.add pArg(arg[^1], c, isSink)
  367. elif arg.kind in {nkIfExpr, nkIfStmt}:
  368. result = copyNode(arg)
  369. for i in 0..<arg.len:
  370. var branch = copyNode(arg[i])
  371. if arg[i].kind in {nkElifBranch, nkElifExpr}:
  372. branch.add p(arg[i][0], c)
  373. branch.add pArgIfTyped(arg[i][1])
  374. else:
  375. branch.add pArgIfTyped(arg[i][0])
  376. result.add branch
  377. elif arg.kind == nkCaseStmt:
  378. result = copyNode(arg)
  379. result.add p(arg[0], c)
  380. for i in 1..<arg.len:
  381. var branch: PNode
  382. if arg[i].kind == nkOfbranch:
  383. branch = arg[i] # of branch conditions are constants
  384. branch[^1] = pArgIfTyped(arg[i][^1])
  385. elif arg[i].kind in {nkElifBranch, nkElifExpr}:
  386. branch = copyNode(arg[i])
  387. branch.add p(arg[i][0], c)
  388. branch.add pArgIfTyped(arg[i][1])
  389. else:
  390. branch = copyNode(arg[i])
  391. branch.add pArgIfTyped(arg[i][0])
  392. result.add branch
  393. else:
  394. # an object that is not temporary but passed to a 'sink' parameter
  395. # results in a copy.
  396. result = passCopyToSink(arg, c)
  397. else:
  398. result = p(arg, c)
  399. proc moveOrCopy(dest, ri: PNode; c: var Con): PNode =
  400. template moveOrCopyIfTyped(ri_part: PNode): PNode =
  401. # typ is nil if we are in if/case expr branch with noreturn
  402. if ri_part.typ == nil: p(ri_part, c)
  403. else: moveOrCopy(dest, ri_part, c)
  404. case ri.kind
  405. of nkCallKinds:
  406. result = genSink(c, dest.typ, dest, ri)
  407. # watch out and no not transform 'ri' twice if it's a call:
  408. let ri2 = copyNode(ri)
  409. let parameters = ri[0].typ
  410. let L = if parameters != nil: parameters.len else: 0
  411. ri2.add ri[0]
  412. for i in 1..<ri.len:
  413. ri2.add pArg(ri[i], c, i < L and parameters[i].kind == tySink)
  414. #recurse(ri, ri2)
  415. result.add ri2
  416. of nkBracketExpr:
  417. if ri[0].kind == nkSym and isUnpackedTuple(ri[0].sym):
  418. # unpacking of tuple: move out the elements
  419. result = genSink(c, dest.typ, dest, ri)
  420. else:
  421. result = genCopy(c, dest.typ, dest, ri)
  422. result.add p(ri, c)
  423. of nkStmtListExpr:
  424. result = newNodeI(nkStmtList, ri.info)
  425. for i in 0..ri.len-2:
  426. result.add p(ri[i], c)
  427. result.add moveOrCopy(dest, ri[^1], c)
  428. of nkBlockExpr, nkBlockStmt:
  429. result = newNodeI(nkBlockStmt, ri.info)
  430. result.add ri[0] # add label
  431. result.add moveOrCopy(dest, ri[1], c)
  432. of nkIfExpr, nkIfStmt:
  433. result = newNodeI(nkIfStmt, ri.info)
  434. for i in 0..<ri.len:
  435. var branch = copyNode(ri[i])
  436. if ri[i].kind in {nkElifBranch, nkElifExpr}:
  437. branch.add p(ri[i][0], c)
  438. branch.add moveOrCopyIfTyped(ri[i][1])
  439. else:
  440. branch.add moveOrCopyIfTyped(ri[i][0])
  441. result.add branch
  442. of nkCaseStmt:
  443. result = newNodeI(nkCaseStmt, ri.info)
  444. result.add p(ri[0], c)
  445. for i in 1..<ri.len:
  446. var branch: PNode
  447. if ri[i].kind == nkOfbranch:
  448. branch = ri[i] # of branch conditions are constants
  449. branch[^1] = moveOrCopyIfTyped(ri[i][^1])
  450. elif ri[i].kind in {nkElifBranch, nkElifExpr}:
  451. branch = copyNode(ri[i])
  452. branch.add p(ri[i][0], c)
  453. branch.add moveOrCopyIfTyped(ri[i][1])
  454. else:
  455. branch = copyNode(ri[i])
  456. branch.add moveOrCopyIfTyped(ri[i][0])
  457. result.add branch
  458. of nkBracket:
  459. # array constructor
  460. result = genSink(c, dest.typ, dest, ri)
  461. let ri2 = copyTree(ri)
  462. for i in 0..<ri.len:
  463. # everything that is passed to an array constructor is consumed,
  464. # so these all act like 'sink' parameters:
  465. ri2[i] = pArg(ri[i], c, isSink = true)
  466. result.add ri2
  467. of nkObjConstr:
  468. result = genSink(c, dest.typ, dest, ri)
  469. let ri2 = copyTree(ri)
  470. for i in 1..<ri.len:
  471. # everything that is passed to an object constructor is consumed,
  472. # so these all act like 'sink' parameters:
  473. ri2[i].sons[1] = pArg(ri[i][1], c, isSink = true)
  474. result.add ri2
  475. of nkTupleConstr:
  476. result = genSink(c, dest.typ, dest, ri)
  477. let ri2 = copyTree(ri)
  478. for i in 0..<ri.len:
  479. # everything that is passed to an tuple constructor is consumed,
  480. # so these all act like 'sink' parameters:
  481. if ri[i].kind == nkExprColonExpr:
  482. ri2[i].sons[1] = pArg(ri[i][1], c, isSink = true)
  483. else:
  484. ri2[i] = pArg(ri[i], c, isSink = true)
  485. result.add ri2
  486. of nkSym:
  487. if isSinkParam(ri.sym):
  488. # Rule 3: `=sink`(x, z); wasMoved(z)
  489. sinkParamIsLastReadCheck(c, ri)
  490. var snk = genSink(c, dest.typ, dest, ri)
  491. snk.add ri
  492. result = newTree(nkStmtList, snk, genMagicCall(ri, c, "wasMoved", mWasMoved))
  493. elif ri.sym.kind != skParam and isLastRead(ri, c):
  494. # Rule 3: `=sink`(x, z); wasMoved(z)
  495. var snk = genSink(c, dest.typ, dest, ri)
  496. snk.add ri
  497. result = newTree(nkStmtList, snk, genMagicCall(ri, c, "wasMoved", mWasMoved))
  498. else:
  499. result = genCopy(c, dest.typ, dest, ri)
  500. result.add p(ri, c)
  501. else:
  502. result = genCopy(c, dest.typ, dest, ri)
  503. result.add p(ri, c)
  504. proc p(n: PNode; c: var Con): PNode =
  505. case n.kind
  506. of nkVarSection, nkLetSection:
  507. discard "transform; var x = y to var x; x op y where op is a move or copy"
  508. result = newNodeI(nkStmtList, n.info)
  509. for i in 0..<n.len:
  510. let it = n[i]
  511. let L = it.len-1
  512. let ri = it[L]
  513. if it.kind == nkVarTuple and hasDestructor(ri.typ):
  514. let x = lowerTupleUnpacking(c.graph, it, c.owner)
  515. result.add p(x, c)
  516. elif it.kind == nkIdentDefs and hasDestructor(it[0].typ):
  517. for j in 0..L-2:
  518. let v = it[j]
  519. doAssert v.kind == nkSym
  520. # move the variable declaration to the top of the frame:
  521. c.addTopVar v
  522. # make sure it's destroyed at the end of the proc:
  523. if not isUnpackedTuple(it[0].sym):
  524. c.destroys.add genDestroy(c, v.typ, v)
  525. if ri.kind != nkEmpty:
  526. let r = moveOrCopy(v, ri, c)
  527. result.add r
  528. else:
  529. # keep it, but transform 'ri':
  530. var varSection = copyNode(n)
  531. var itCopy = copyNode(it)
  532. for j in 0..L-1:
  533. itCopy.add it[j]
  534. itCopy.add p(ri, c)
  535. varSection.add itCopy
  536. result.add varSection
  537. of nkCallKinds:
  538. let parameters = n[0].typ
  539. let L = if parameters != nil: parameters.len else: 0
  540. for i in 1 ..< n.len:
  541. n.sons[i] = pArg(n[i], c, i < L and parameters[i].kind == tySink)
  542. if n.typ != nil and hasDestructor(n.typ):
  543. discard "produce temp creation"
  544. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  545. let tmp = getTemp(c, n.typ, n.info)
  546. var sinkExpr = genSink(c, n.typ, tmp, n)
  547. sinkExpr.add n
  548. result.add sinkExpr
  549. result.add tmp
  550. c.destroys.add genDestroy(c, n.typ, tmp)
  551. else:
  552. result = n
  553. of nkAsgn, nkFastAsgn:
  554. if hasDestructor(n[0].typ):
  555. result = moveOrCopy(n[0], n[1], c)
  556. else:
  557. result = copyNode(n)
  558. recurse(n, result)
  559. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
  560. nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef,
  561. nkCommentStmt:
  562. result = n
  563. of nkDiscardStmt:
  564. result = n
  565. if n[0].typ != nil and hasDestructor(n[0].typ):
  566. result = genDestroy(c, n[0].typ, n[0])
  567. of nkCast, nkHiddenStdConv, nkHiddenSubConv, nkConv:
  568. result = copyNode(n)
  569. # Destination type
  570. result.add n[0]
  571. # Analyse the inner expression
  572. result.add p(n[1], c)
  573. else:
  574. result = copyNode(n)
  575. recurse(n, result)
  576. proc injectDestructorCalls*(g: ModuleGraph; owner: PSym; n: PNode): PNode =
  577. when false: # defined(nimDebugDestroys):
  578. echo "injecting into ", n
  579. var c: Con
  580. c.owner = owner
  581. c.destroys = newNodeI(nkStmtList, n.info)
  582. c.topLevelVars = newNodeI(nkVarSection, n.info)
  583. c.graph = g
  584. c.emptyNode = newNodeI(nkEmpty, n.info)
  585. let cfg = constructCfg(owner, n)
  586. shallowCopy(c.g, cfg)
  587. c.jumpTargets = initIntSet()
  588. for i in 0..<c.g.len:
  589. if c.g[i].kind in {goto, fork}:
  590. c.jumpTargets.incl(i+c.g[i].dest)
  591. #if owner.name.s == "test0p1":
  592. # echoCfg(c.g)
  593. if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:
  594. let params = owner.typ.n
  595. for i in 1 ..< params.len:
  596. let param = params[i].sym
  597. if param.typ.kind == tySink and hasDestructor(param.typ.sons[0]):
  598. c.destroys.add genDestroy(c, param.typ.skipTypes({tyGenericInst, tyAlias, tySink}), params[i])
  599. let body = p(n, c)
  600. result = newNodeI(nkStmtList, n.info)
  601. if c.topLevelVars.len > 0:
  602. result.add c.topLevelVars
  603. if c.destroys.len > 0:
  604. result.add newTryFinally(body, c.destroys)
  605. else:
  606. result.add body
  607. when defined(nimDebugDestroys):
  608. if true:
  609. echo "------------------------------------"
  610. echo owner.name.s, " transformed to: "
  611. echo result