liftdestructors.nim 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements lifting for type-bound operations
  10. ## (``=sink``, ``=``, ``=destroy``, ``=deepCopy``).
  11. # Todo:
  12. # - use openArray instead of array to avoid over-specializations
  13. import modulegraphs, lineinfos, idents, ast, renderer, semdata,
  14. sighashes, lowerings, options, types, msgs, magicsys, tables
  15. from trees import isCaseObj
  16. type
  17. TLiftCtx = object
  18. g: ModuleGraph
  19. info: TLineInfo # for construction
  20. kind: TTypeAttachedOp
  21. fn: PSym
  22. asgnForType: PType
  23. recurse: bool
  24. filterDiscriminator: PSym # we generating destructor for case branch
  25. addMemReset: bool # add wasMoved() call after destructor call
  26. c: PContext # c can be nil, then we are called from lambdalifting!
  27. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode)
  28. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  29. info: TLineInfo): PSym
  30. proc createTypeBoundOps*(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo)
  31. proc at(a, i: PNode, elemType: PType): PNode =
  32. result = newNodeI(nkBracketExpr, a.info, 2)
  33. result[0] = a
  34. result[1] = i
  35. result.typ = elemType
  36. proc fillBodyTup(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  37. for i in 0..<t.len:
  38. let lit = lowerings.newIntLit(c.g, x.info, i)
  39. let b = if c.kind == attachedTrace: y else: y.at(lit, t[i])
  40. fillBody(c, t[i], body, x.at(lit, t[i]), b)
  41. proc dotField(x: PNode, f: PSym): PNode =
  42. result = newNodeI(nkDotExpr, x.info, 2)
  43. if x.typ.skipTypes(abstractInst).kind == tyVar:
  44. result[0] = x.newDeref
  45. else:
  46. result[0] = x
  47. result[1] = newSymNode(f, x.info)
  48. result.typ = f.typ
  49. proc newAsgnStmt(le, ri: PNode): PNode =
  50. result = newNodeI(nkAsgn, le.info, 2)
  51. result[0] = le
  52. result[1] = ri
  53. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  54. if c.kind in {attachedAsgn, attachedDeepCopy, attachedSink}:
  55. body.add newAsgnStmt(x, y)
  56. proc genAddr(g: ModuleGraph; x: PNode): PNode =
  57. if x.kind == nkHiddenDeref:
  58. checkSonsLen(x, 1, g.config)
  59. result = x[0]
  60. else:
  61. result = newNodeIT(nkHiddenAddr, x.info, makeVarType(x.typ.owner, x.typ))
  62. result.add x
  63. proc genBuiltin(g: ModuleGraph; magic: TMagic; name: string; i: PNode): PNode =
  64. result = newNodeI(nkCall, i.info)
  65. result.add createMagic(g, name, magic).newSymNode
  66. result.add i
  67. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  68. result = newNodeI(nkWhileStmt, c.info, 2)
  69. let cmp = genBuiltin(c.g, mLtI, "<", i)
  70. cmp.add genLen(c.g, dest)
  71. cmp.typ = getSysType(c.g, c.info, tyBool)
  72. result[0] = cmp
  73. result[1] = newNodeI(nkStmtList, c.info)
  74. proc genIf(c: var TLiftCtx; cond, action: PNode): PNode =
  75. result = newTree(nkIfStmt, newTree(nkElifBranch, cond, action))
  76. proc genContainerOf(c: TLiftCtx; objType: PType, field, x: PSym): PNode =
  77. # generate: cast[ptr ObjType](cast[int](addr(x)) - offsetOf(objType.field))
  78. let intType = getSysType(c.g, unknownLineInfo, tyInt)
  79. let addrOf = newNodeIT(nkAddr, c.info, makePtrType(x.owner, x.typ))
  80. addrOf.add newDeref(newSymNode(x))
  81. let castExpr1 = newNodeIT(nkCast, c.info, intType)
  82. castExpr1.add newNodeIT(nkType, c.info, intType)
  83. castExpr1.add addrOf
  84. let dotExpr = newNodeIT(nkDotExpr, c.info, x.typ)
  85. dotExpr.add newNodeIT(nkType, c.info, objType)
  86. dotExpr.add newSymNode(field)
  87. let offsetOf = genBuiltin(c.g, mOffsetOf, "offsetof", dotExpr)
  88. offsetOf.typ = intType
  89. let minusExpr = genBuiltin(c.g, mSubI, "-", castExpr1)
  90. minusExpr.typ = intType
  91. minusExpr.add offsetOf
  92. let objPtr = makePtrType(objType.owner, objType)
  93. result = newNodeIT(nkCast, c.info, objPtr)
  94. result.add newNodeIT(nkType, c.info, objPtr)
  95. result.add minusExpr
  96. proc destructorCall(c: TLiftCtx; op: PSym; x: PNode): PNode =
  97. var destroy = newNodeIT(nkCall, x.info, op.typ[0])
  98. destroy.add(newSymNode(op))
  99. destroy.add genAddr(c.g, x)
  100. if c.addMemReset:
  101. result = newTree(nkStmtList, destroy, genBuiltin(c.g, mWasMoved, "wasMoved", x))
  102. else:
  103. result = destroy
  104. proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool) =
  105. case n.kind
  106. of nkSym:
  107. if c.filterDiscriminator != nil: return
  108. let f = n.sym
  109. let b = if c.kind == attachedTrace: y else: y.dotField(f)
  110. if (sfCursor in f.flags and f.typ.skipTypes(abstractInst).kind in {tyRef, tyProc} and
  111. c.g.config.selectedGC in {gcArc, gcOrc, gcHooks}) or
  112. enforceDefaultOp:
  113. defaultOp(c, f.typ, body, x.dotField(f), b)
  114. else:
  115. fillBody(c, f.typ, body, x.dotField(f), b)
  116. of nkNilLit: discard
  117. of nkRecCase:
  118. let oldfilterDiscriminator = c.filterDiscriminator
  119. if c.filterDiscriminator == n[0].sym:
  120. c.filterDiscriminator = nil # we have found the case part, proceed as normal
  121. # XXX This is only correct for 'attachedSink'!
  122. var localEnforceDefaultOp = enforceDefaultOp
  123. if c.kind == attachedSink:
  124. # the value needs to be destroyed before we assign the selector
  125. # or the value is lost
  126. let prevKind = c.kind
  127. c.kind = attachedDestructor
  128. fillBodyObj(c, n, body, x, y, enforceDefaultOp = false)
  129. c.kind = prevKind
  130. localEnforceDefaultOp = true
  131. # copy the selector:
  132. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  133. # we need to generate a case statement:
  134. var caseStmt = newNodeI(nkCaseStmt, c.info)
  135. # XXX generate 'if' that checks same branches
  136. # generate selector:
  137. var access = dotField(x, n[0].sym)
  138. caseStmt.add(access)
  139. var emptyBranches = 0
  140. # copy the branches over, but replace the fields with the for loop body:
  141. for i in 1..<n.len:
  142. var branch = copyTree(n[i])
  143. branch[^1] = newNodeI(nkStmtList, c.info)
  144. fillBodyObj(c, n[i].lastSon, branch[^1], x, y,
  145. enforceDefaultOp = localEnforceDefaultOp)
  146. if branch[^1].len == 0: inc emptyBranches
  147. caseStmt.add(branch)
  148. if emptyBranches != n.len-1:
  149. body.add(caseStmt)
  150. c.filterDiscriminator = oldfilterDiscriminator
  151. of nkRecList:
  152. for t in items(n): fillBodyObj(c, t, body, x, y, enforceDefaultOp)
  153. else:
  154. illFormedAstLocal(n, c.g.config)
  155. proc fillBodyObjTImpl(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  156. if t.len > 0 and t[0] != nil:
  157. fillBody(c, skipTypes(t[0], abstractPtrs), body, x, y)
  158. fillBodyObj(c, t.n, body, x, y, enforceDefaultOp = false)
  159. proc fillBodyObjT(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  160. var hasCase = isCaseObj(t.n)
  161. var obj = t
  162. while obj.len > 0 and obj[0] != nil:
  163. obj = skipTypes(obj[0], abstractPtrs)
  164. hasCase = hasCase or isCaseObj(obj.n)
  165. if hasCase and c.kind in {attachedAsgn, attachedDeepCopy}:
  166. # assignment for case objects is complex, we do:
  167. # =destroy(dest)
  168. # wasMoved(dest)
  169. # for every field:
  170. # `=` dest.field, src.field
  171. # ^ this is what we used to do, but for 'result = result.sons[0]' it
  172. # destroys 'result' too early.
  173. # So this is what we really need to do:
  174. # let blob {.cursor.} = dest # remembers the old dest.kind
  175. # wasMoved(dest)
  176. # dest.kind = src.kind
  177. # for every field (dependent on dest.kind):
  178. # `=` dest.field, src.field
  179. # =destroy(blob)
  180. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.fn, c.info)
  181. temp.typ = x.typ
  182. incl(temp.flags, sfFromGeneric)
  183. var v = newNodeI(nkVarSection, c.info)
  184. let blob = newSymNode(temp)
  185. v.addVar(blob, x)
  186. body.add v
  187. #body.add newAsgnStmt(blob, x)
  188. var wasMovedCall = newNodeI(nkCall, c.info)
  189. wasMovedCall.add(newSymNode(createMagic(c.g, "wasMoved", mWasMoved)))
  190. wasMovedCall.add x # mWasMoved does not take the address
  191. body.add wasMovedCall
  192. fillBodyObjTImpl(c, t, body, x, y)
  193. when false:
  194. # does not work yet due to phase-ordering problems:
  195. assert t.destructor != nil
  196. body.add destructorCall(c.g, t.destructor, blob)
  197. let prevKind = c.kind
  198. c.kind = attachedDestructor
  199. fillBodyObjTImpl(c, t, body, blob, y)
  200. c.kind = prevKind
  201. else:
  202. fillBodyObjTImpl(c, t, body, x, y)
  203. proc newHookCall(g: ModuleGraph; op: PSym; x, y: PNode): PNode =
  204. #if sfError in op.flags:
  205. # localError(c.config, x.info, "usage of '$1' is a user-defined error" % op.name.s)
  206. result = newNodeI(nkCall, x.info)
  207. result.add newSymNode(op)
  208. if op.typ.sons[1].kind == tyVar:
  209. result.add genAddr(g, x)
  210. else:
  211. result.add x
  212. if y != nil:
  213. result.add y
  214. proc newOpCall(op: PSym; x: PNode): PNode =
  215. result = newNodeIT(nkCall, x.info, op.typ[0])
  216. result.add(newSymNode(op))
  217. result.add x
  218. proc newDeepCopyCall(op: PSym; x, y: PNode): PNode =
  219. result = newAsgnStmt(x, newOpCall(op, y))
  220. proc useNoGc(c: TLiftCtx; t: PType): bool {.inline.} =
  221. result = optSeqDestructors in c.g.config.globalOptions and
  222. ({tfHasGCedMem, tfHasOwned} * t.flags != {} or t.isGCedMem)
  223. proc requiresDestructor(c: TLiftCtx; t: PType): bool {.inline.} =
  224. result = optSeqDestructors in c.g.config.globalOptions and
  225. containsGarbageCollectedRef(t)
  226. proc instantiateGeneric(c: var TLiftCtx; op: PSym; t, typeInst: PType): PSym =
  227. if c.c != nil and typeInst != nil:
  228. result = c.c.instTypeBoundOp(c.c, op, typeInst, c.info, attachedAsgn, 1)
  229. else:
  230. localError(c.g.config, c.info,
  231. "cannot generate destructor for generic type: " & typeToString(t))
  232. result = nil
  233. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  234. field: var PSym): bool =
  235. if optSeqDestructors in c.g.config.globalOptions:
  236. let op = field
  237. if field != nil and sfOverriden in field.flags:
  238. if sfError in op.flags:
  239. incl c.fn.flags, sfError
  240. #else:
  241. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  242. onUse(c.info, op)
  243. body.add newHookCall(c.g, op, x, y)
  244. result = true
  245. elif tfHasAsgn in t.flags:
  246. var op: PSym
  247. if sameType(t, c.asgnForType):
  248. # generate recursive call:
  249. if c.recurse:
  250. op = c.fn
  251. else:
  252. c.recurse = true
  253. return false
  254. else:
  255. op = field
  256. if op == nil:
  257. op = produceSym(c.g, c.c, t, c.kind, c.info)
  258. if sfError in op.flags:
  259. incl c.fn.flags, sfError
  260. #else:
  261. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  262. onUse(c.info, op)
  263. # We also now do generic instantiations in the destructor lifting pass:
  264. if op.ast[genericParamsPos].kind != nkEmpty:
  265. op = instantiateGeneric(c, op, t, t.typeInst)
  266. field = op
  267. #echo "trying to use ", op.ast
  268. #echo "for ", op.name.s, " "
  269. #debug(t)
  270. #return false
  271. assert op.ast[genericParamsPos].kind == nkEmpty
  272. body.add newHookCall(c.g, op, x, y)
  273. result = true
  274. proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) =
  275. let t = orig.skipTypes(abstractInst)
  276. var op = t.destructor
  277. if op != nil and sfOverriden in op.flags:
  278. if op.ast[genericParamsPos].kind != nkEmpty:
  279. # patch generic destructor:
  280. op = instantiateGeneric(c, op, t, t.typeInst)
  281. t.attachedOps[attachedDestructor] = op
  282. if op == nil and (useNoGc(c, t) or requiresDestructor(c, t)):
  283. op = produceSym(c.g, c.c, t, attachedDestructor, c.info)
  284. doAssert op != nil
  285. doAssert op == t.destructor
  286. if op != nil:
  287. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  288. onUse(c.info, op)
  289. body.add destructorCall(c, op, x)
  290. elif useNoGc(c, t):
  291. internalError(c.g.config, c.info,
  292. "type-bound operator could not be resolved")
  293. proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  294. case c.kind
  295. of attachedDestructor:
  296. var op = t.destructor
  297. if op != nil and sfOverriden in op.flags:
  298. if op.ast[genericParamsPos].kind != nkEmpty:
  299. # patch generic destructor:
  300. op = instantiateGeneric(c, op, t, t.typeInst)
  301. t.attachedOps[attachedDestructor] = op
  302. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  303. onUse(c.info, op)
  304. body.add destructorCall(c, op, x)
  305. result = true
  306. #result = addDestructorCall(c, t, body, x)
  307. of attachedAsgn, attachedSink, attachedTrace:
  308. result = considerAsgnOrSink(c, t, body, x, y, t.attachedOps[c.kind])
  309. of attachedDispose:
  310. result = considerAsgnOrSink(c, t, body, x, nil, t.attachedOps[c.kind])
  311. of attachedDeepCopy:
  312. let op = t.attachedOps[attachedDeepCopy]
  313. if op != nil:
  314. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  315. onUse(c.info, op)
  316. body.add newDeepCopyCall(op, x, y)
  317. result = true
  318. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  319. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.fn, c.info)
  320. temp.typ = getSysType(c.g, body.info, tyInt)
  321. incl(temp.flags, sfFromGeneric)
  322. var v = newNodeI(nkVarSection, c.info)
  323. result = newSymNode(temp)
  324. v.addVar(result, lowerings.newIntLit(c.g, body.info, first))
  325. body.add v
  326. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  327. let incCall = genBuiltin(c.g, mInc, "inc", i)
  328. incCall.add lowerings.newIntLit(c.g, c.info, 1)
  329. body.add incCall
  330. proc newSeqCall(g: ModuleGraph; x, y: PNode): PNode =
  331. # don't call genAddr(c, x) here:
  332. result = genBuiltin(g, mNewSeq, "newSeq", x)
  333. let lenCall = genBuiltin(g, mLengthSeq, "len", y)
  334. lenCall.typ = getSysType(g, x.info, tyInt)
  335. result.add lenCall
  336. proc setLenStrCall(g: ModuleGraph; x, y: PNode): PNode =
  337. let lenCall = genBuiltin(g, mLengthStr, "len", y)
  338. lenCall.typ = getSysType(g, x.info, tyInt)
  339. result = genBuiltin(g, mSetLengthStr, "setLen", x) # genAddr(g, x))
  340. result.add lenCall
  341. proc setLenSeqCall(c: var TLiftCtx; t: PType; x, y: PNode): PNode =
  342. let lenCall = genBuiltin(c.g, mLengthSeq, "len", y)
  343. lenCall.typ = getSysType(c.g, x.info, tyInt)
  344. var op = getSysMagic(c.g, x.info, "setLen", mSetLengthSeq)
  345. op = instantiateGeneric(c, op, t, t)
  346. result = newTree(nkCall, newSymNode(op, x.info), x, lenCall)
  347. proc forallElements(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  348. let i = declareCounter(c, body, toInt64(firstOrd(c.g.config, t)))
  349. let whileLoop = genWhileLoop(c, i, x)
  350. let elemType = t.lastSon
  351. let b = if c.kind == attachedTrace: y else: y.at(i, elemType)
  352. fillBody(c, elemType, whileLoop[1], x.at(i, elemType), b)
  353. addIncStmt(c, whileLoop[1], i)
  354. body.add whileLoop
  355. proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  356. case c.kind
  357. of attachedAsgn, attachedDeepCopy:
  358. # we generate:
  359. # setLen(dest, y.len)
  360. # var i = 0
  361. # while i < y.len: dest[i] = y[i]; inc(i)
  362. # This is usually more efficient than a destroy/create pair.
  363. body.add setLenSeqCall(c, t, x, y)
  364. forallElements(c, t, body, x, y)
  365. of attachedSink:
  366. let moveCall = genBuiltin(c.g, mMove, "move", x)
  367. moveCall.add y
  368. doAssert t.destructor != nil
  369. moveCall.add destructorCall(c, t.destructor, x)
  370. body.add moveCall
  371. of attachedDestructor:
  372. # destroy all elements:
  373. forallElements(c, t, body, x, y)
  374. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  375. of attachedTrace:
  376. # follow all elements:
  377. forallElements(c, t, body, x, y)
  378. of attachedDispose:
  379. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  380. proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  381. createTypeBoundOps(c.g, c.c, t, body.info)
  382. # recursions are tricky, so we might need to forward the generated
  383. # operation here:
  384. var t = t
  385. if t.assignment == nil or t.destructor == nil:
  386. let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
  387. let canon = c.g.canonTypes.getOrDefault(h)
  388. if canon != nil: t = canon
  389. case c.kind
  390. of attachedAsgn, attachedDeepCopy:
  391. doAssert t.assignment != nil
  392. body.add newHookCall(c.g, t.assignment, x, y)
  393. of attachedSink:
  394. # we always inline the move for better performance:
  395. let moveCall = genBuiltin(c.g, mMove, "move", x)
  396. moveCall.add y
  397. doAssert t.destructor != nil
  398. moveCall.add destructorCall(c, t.destructor, x)
  399. body.add moveCall
  400. # alternatively we could do this:
  401. when false:
  402. doAssert t.asink != nil
  403. body.add newHookCall(c.g, t.asink, x, y)
  404. of attachedDestructor:
  405. doAssert t.destructor != nil
  406. body.add destructorCall(c, t.destructor, x)
  407. of attachedTrace:
  408. body.add newHookCall(c.g, t.attachedOps[c.kind], x, y)
  409. of attachedDispose:
  410. body.add newHookCall(c.g, t.attachedOps[c.kind], x, nil)
  411. proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  412. case c.kind
  413. of attachedAsgn, attachedDeepCopy:
  414. body.add callCodegenProc(c.g, "nimAsgnStrV2", c.info, genAddr(c.g, x), y)
  415. of attachedSink:
  416. let moveCall = genBuiltin(c.g, mMove, "move", x)
  417. moveCall.add y
  418. doAssert t.destructor != nil
  419. moveCall.add destructorCall(c, t.destructor, x)
  420. body.add moveCall
  421. of attachedDestructor, attachedDispose:
  422. body.add genBuiltin(c.g, mDestroy, "destroy", x)
  423. of attachedTrace:
  424. discard "strings are atomic and have no inner elements that are to trace"
  425. proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  426. var actions = newNodeI(nkStmtList, c.info)
  427. let elemType = t.lastSon
  428. if isFinal(elemType):
  429. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  430. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x)
  431. else:
  432. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  433. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  434. let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(t)
  435. var cond: PNode
  436. if isCyclic:
  437. if isFinal(elemType):
  438. let typInfo = genBuiltin(c.g, mGetTypeInfo, "getTypeInfo", newNodeIT(nkType, x.info, elemType))
  439. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  440. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, x, typInfo)
  441. else:
  442. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, x)
  443. else:
  444. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  445. cond.typ = getSysType(c.g, x.info, tyBool)
  446. case c.kind
  447. of attachedSink:
  448. body.add genIf(c, cond, actions)
  449. body.add newAsgnStmt(x, y)
  450. of attachedAsgn:
  451. body.add genIf(c, y, callCodegenProc(c.g,
  452. if isCyclic: "nimIncRefCyclic" else: "nimIncRef", c.info, y))
  453. body.add genIf(c, cond, actions)
  454. body.add newAsgnStmt(x, y)
  455. of attachedDestructor:
  456. body.add genIf(c, cond, actions)
  457. body.add newAsgnStmt(x, newNodeIT(nkNilLit, body.info, t))
  458. of attachedDeepCopy: assert(false, "cannot happen")
  459. of attachedTrace:
  460. if isFinal(elemType):
  461. let typInfo = genBuiltin(c.g, mGetTypeInfo, "getTypeInfo", newNodeIT(nkType, x.info, elemType))
  462. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  463. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x), typInfo, y)
  464. else:
  465. # If the ref is polymorphic we have to account for this
  466. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x), y)
  467. of attachedDispose:
  468. # this is crucial! dispose is like =destroy but we don't follow refs
  469. # as that is dealt within the cycle collector.
  470. when false:
  471. let cond = copyTree(x)
  472. cond.typ = getSysType(c.g, x.info, tyBool)
  473. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x)
  474. body.add genIf(c, cond, actions)
  475. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  476. ## Closures are really like refs except they always use a virtual destructor
  477. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  478. let xenv = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  479. xenv.typ = getSysType(c.g, c.info, tyPointer)
  480. var actions = newNodeI(nkStmtList, c.info)
  481. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xenv)
  482. let decRefProc =
  483. if c.g.config.selectedGC == gcOrc: "nimDecRefIsLastCyclicDyn"
  484. else: "nimDecRefIsLast"
  485. let cond = callCodegenProc(c.g, decRefProc, c.info, xenv)
  486. cond.typ = getSysType(c.g, x.info, tyBool)
  487. case c.kind
  488. of attachedSink:
  489. body.add genIf(c, cond, actions)
  490. body.add newAsgnStmt(x, y)
  491. of attachedAsgn:
  492. let yenv = genBuiltin(c.g, mAccessEnv, "accessEnv", y)
  493. yenv.typ = getSysType(c.g, c.info, tyPointer)
  494. let incRefProc =
  495. if c.g.config.selectedGC == gcOrc: "nimIncRefCyclic"
  496. else: "nimIncRef"
  497. body.add genIf(c, yenv, callCodegenProc(c.g, incRefProc, c.info, yenv))
  498. body.add genIf(c, cond, actions)
  499. body.add newAsgnStmt(x, y)
  500. of attachedDestructor:
  501. body.add genIf(c, cond, actions)
  502. body.add newAsgnStmt(xenv, newNodeIT(nkNilLit, body.info, xenv.typ))
  503. of attachedDeepCopy: assert(false, "cannot happen")
  504. of attachedTrace:
  505. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv), y)
  506. of attachedDispose:
  507. # this is crucial! dispose is like =destroy but we don't follow refs
  508. # as that is dealt within the cycle collector.
  509. when false:
  510. let cond = copyTree(xenv)
  511. cond.typ = getSysType(c.g, xenv.info, tyBool)
  512. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, xenv)
  513. body.add genIf(c, cond, actions)
  514. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  515. case c.kind
  516. of attachedSink:
  517. # we 'nil' y out afterwards so we *need* to take over its reference
  518. # count value:
  519. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  520. body.add newAsgnStmt(x, y)
  521. of attachedAsgn:
  522. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  523. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  524. body.add newAsgnStmt(x, y)
  525. of attachedDestructor:
  526. # it's better to prepend the destruction of weak refs in order to
  527. # prevent wrong "dangling refs exist" problems:
  528. var actions = newNodeI(nkStmtList, c.info)
  529. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  530. actions.add newAsgnStmt(x, newNodeIT(nkNilLit, body.info, t))
  531. let des = genIf(c, x, actions)
  532. if body.len == 0:
  533. body.add des
  534. else:
  535. body.sons.insert(des, 0)
  536. of attachedDeepCopy: assert(false, "cannot happen")
  537. of attachedTrace, attachedDispose: discard
  538. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  539. var actions = newNodeI(nkStmtList, c.info)
  540. let elemType = t.lastSon
  541. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  542. #var disposeCall = genBuiltin(c.g, mDispose, "dispose", x)
  543. if isFinal(elemType):
  544. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  545. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x)
  546. else:
  547. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  548. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  549. case c.kind
  550. of attachedSink, attachedAsgn:
  551. body.add genIf(c, x, actions)
  552. body.add newAsgnStmt(x, y)
  553. of attachedDestructor:
  554. body.add genIf(c, x, actions)
  555. body.add newAsgnStmt(x, newNodeIT(nkNilLit, body.info, t))
  556. of attachedDeepCopy: assert(false, "cannot happen")
  557. of attachedTrace, attachedDispose: discard
  558. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  559. if c.kind == attachedDeepCopy:
  560. # a big problem is that we don't know the environment's type here, so we
  561. # have to go through some indirection; we delegate this to the codegen:
  562. let call = newNodeI(nkCall, c.info, 2)
  563. call.typ = t
  564. call[0] = newSymNode(createMagic(c.g, "deepCopy", mDeepCopy))
  565. call[1] = y
  566. body.add newAsgnStmt(x, call)
  567. elif (optOwnedRefs in c.g.config.globalOptions and
  568. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcOrc}:
  569. let xx = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  570. xx.typ = getSysType(c.g, c.info, tyPointer)
  571. case c.kind
  572. of attachedSink:
  573. # we 'nil' y out afterwards so we *need* to take over its reference
  574. # count value:
  575. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  576. body.add newAsgnStmt(x, y)
  577. of attachedAsgn:
  578. let yy = genBuiltin(c.g, mAccessEnv, "accessEnv", y)
  579. yy.typ = getSysType(c.g, c.info, tyPointer)
  580. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  581. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  582. body.add newAsgnStmt(x, y)
  583. of attachedDestructor:
  584. var actions = newNodeI(nkStmtList, c.info)
  585. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, xx)
  586. actions.add newAsgnStmt(xx, newNodeIT(nkNilLit, body.info, xx.typ))
  587. let des = genIf(c, xx, actions)
  588. if body.len == 0:
  589. body.add des
  590. else:
  591. body.sons.insert(des, 0)
  592. of attachedDeepCopy: assert(false, "cannot happen")
  593. of attachedTrace, attachedDispose: discard
  594. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  595. let xx = genBuiltin(c.g, mAccessEnv, "accessEnv", x)
  596. xx.typ = getSysType(c.g, c.info, tyPointer)
  597. var actions = newNodeI(nkStmtList, c.info)
  598. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  599. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  600. case c.kind
  601. of attachedSink, attachedAsgn:
  602. body.add genIf(c, xx, actions)
  603. body.add newAsgnStmt(x, y)
  604. of attachedDestructor:
  605. body.add genIf(c, xx, actions)
  606. body.add newAsgnStmt(xx, newNodeIT(nkNilLit, body.info, xx.typ))
  607. of attachedDeepCopy: assert(false, "cannot happen")
  608. of attachedTrace, attachedDispose: discard
  609. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  610. case t.kind
  611. of tyNone, tyEmpty, tyVoid: discard
  612. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCString,
  613. tyPtr, tyOpt, tyUncheckedArray, tyVar, tyLent:
  614. defaultOp(c, t, body, x, y)
  615. of tyRef:
  616. if c.g.config.selectedGC in {gcArc, gcOrc}:
  617. atomicRefOp(c, t, body, x, y)
  618. elif (optOwnedRefs in c.g.config.globalOptions and
  619. optRefCheck in c.g.config.options):
  620. weakrefOp(c, t, body, x, y)
  621. else:
  622. defaultOp(c, t, body, x, y)
  623. of tyProc:
  624. if t.callConv == ccClosure:
  625. if c.g.config.selectedGC in {gcArc, gcOrc}:
  626. atomicClosureOp(c, t, body, x, y)
  627. else:
  628. closureOp(c, t, body, x, y)
  629. else:
  630. defaultOp(c, t, body, x, y)
  631. of tyOwned:
  632. let base = t.skipTypes(abstractInstOwned)
  633. if optOwnedRefs in c.g.config.globalOptions:
  634. case base.kind
  635. of tyRef:
  636. ownedRefOp(c, base, body, x, y)
  637. return
  638. of tyProc:
  639. if base.callConv == ccClosure:
  640. ownedClosureOp(c, base, body, x, y)
  641. return
  642. else: discard
  643. defaultOp(c, base, body, x, y)
  644. of tyArray:
  645. if tfHasAsgn in t.flags or useNoGc(c, t):
  646. forallElements(c, t, body, x, y)
  647. else:
  648. defaultOp(c, t, body, x, y)
  649. of tySequence:
  650. if useNoGc(c, t):
  651. useSeqOrStrOp(c, t, body, x, y)
  652. elif optSeqDestructors in c.g.config.globalOptions:
  653. # note that tfHasAsgn is propagated so we need the check on
  654. # 'selectedGC' here to determine if we have the new runtime.
  655. discard considerUserDefinedOp(c, t, body, x, y)
  656. elif tfHasAsgn in t.flags:
  657. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  658. body.add newSeqCall(c.g, x, y)
  659. forallElements(c, t, body, x, y)
  660. else:
  661. defaultOp(c, t, body, x, y)
  662. of tyString:
  663. if useNoGc(c, t):
  664. useSeqOrStrOp(c, t, body, x, y)
  665. elif tfHasAsgn in t.flags:
  666. discard considerUserDefinedOp(c, t, body, x, y)
  667. else:
  668. defaultOp(c, t, body, x, y)
  669. of tyObject:
  670. if not considerUserDefinedOp(c, t, body, x, y):
  671. if c.kind in {attachedAsgn, attachedSink} and t.sym != nil and sfImportc in t.sym.flags:
  672. body.add newAsgnStmt(x, y)
  673. else:
  674. fillBodyObjT(c, t, body, x, y)
  675. of tyDistinct:
  676. if not considerUserDefinedOp(c, t, body, x, y):
  677. fillBody(c, t[0], body, x, y)
  678. of tyTuple:
  679. fillBodyTup(c, t, body, x, y)
  680. of tyVarargs, tyOpenArray:
  681. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  682. forallElements(c, t, body, x, y)
  683. else:
  684. discard "cannot copy openArray"
  685. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  686. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  687. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  688. tyTypeDesc, tyGenericInvocation, tyForward:
  689. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  690. discard
  691. of tyOrdinal, tyRange, tyInferred,
  692. tyGenericInst, tyStatic, tyAlias, tySink:
  693. fillBody(c, lastSon(t), body, x, y)
  694. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  695. kind: TTypeAttachedOp; info: TLineInfo): PSym =
  696. assert typ.kind == tyDistinct
  697. let baseType = typ[0]
  698. if baseType.attachedOps[kind] == nil:
  699. discard produceSym(g, c, baseType, kind, info)
  700. typ.attachedOps[kind] = baseType.attachedOps[kind]
  701. result = typ.attachedOps[kind]
  702. proc symPrototype(g: ModuleGraph; typ: PType; kind: TTypeAttachedOp;
  703. info: TLineInfo): PSym =
  704. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  705. result = newSym(skProc, procname, typ.owner, info)
  706. let dest = newSym(skParam, getIdent(g.cache, "dest"), result, info)
  707. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"), result, info)
  708. dest.typ = makeVarType(typ.owner, typ)
  709. if kind == attachedTrace:
  710. src.typ = getSysType(g, info, tyPointer)
  711. else:
  712. src.typ = typ
  713. result.typ = newProcType(info, typ.owner)
  714. result.typ.addParam dest
  715. if kind notin {attachedDestructor, attachedDispose}:
  716. result.typ.addParam src
  717. var n = newNodeI(nkProcDef, info, bodyPos+1)
  718. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  719. n[namePos] = newSymNode(result)
  720. n[paramsPos] = result.typ.n
  721. n[bodyPos] = newNodeI(nkStmtList, info)
  722. result.ast = n
  723. incl result.flags, sfFromGeneric
  724. incl result.flags, sfGeneratedOp
  725. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  726. info: TLineInfo): PSym =
  727. if typ.kind == tyDistinct:
  728. return produceSymDistinctType(g, c, typ, kind, info)
  729. result = symPrototype(g, typ, kind, info)
  730. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType:typ)
  731. a.fn = result
  732. let dest = result.typ.n[1].sym
  733. let d = newDeref(newSymNode(dest))
  734. let src = if kind in {attachedDestructor, attachedDispose}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  735. else: newSymNode(result.typ.n[2].sym)
  736. # register this operation already:
  737. typ.attachedOps[kind] = result
  738. if kind == attachedSink and typ.attachedOps[attachedDestructor] != nil and
  739. sfOverriden in typ.attachedOps[attachedDestructor].flags:
  740. ## compiler can use a combination of `=destroy` and memCopy for sink op
  741. dest.flags.incl sfCursor
  742. result.ast[bodyPos].add newOpCall(typ.attachedOps[attachedDestructor], d[0])
  743. result.ast[bodyPos].add newAsgnStmt(d, src)
  744. else:
  745. var tk: TTypeKind
  746. if g.config.selectedGC in {gcArc, gcOrc, gcHooks}:
  747. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  748. else:
  749. tk = tyNone # no special casing for strings and seqs
  750. case tk
  751. of tySequence:
  752. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  753. of tyString:
  754. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  755. else:
  756. fillBody(a, typ, result.ast[bodyPos], d, src)
  757. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym, info: TLineInfo): PSym =
  758. assert(typ.kind == tyObject)
  759. result = symPrototype(g, field.typ, attachedDestructor, info)
  760. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ)
  761. a.fn = result
  762. a.asgnForType = typ
  763. a.filterDiscriminator = field
  764. a.addMemReset = true
  765. let discrimantDest = result.typ.n[1].sym
  766. let dst = newSym(skVar, getIdent(g.cache, "dest"), result, info)
  767. dst.typ = makePtrType(typ.owner, typ)
  768. let dstSym = newSymNode(dst)
  769. let d = newDeref(dstSym)
  770. let v = newNodeI(nkVarSection, info)
  771. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  772. result.ast[bodyPos].add v
  773. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  774. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  775. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  776. discard "now a nop"
  777. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo) =
  778. if n.kind in nkCallKinds:
  779. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  780. let t = n[1].typ.skipTypes(abstractVar)
  781. if t.destructor == nil:
  782. discard produceSym(g, c, t, attachedDestructor, info)
  783. if t.destructor != nil:
  784. if t.destructor.ast[genericParamsPos].kind != nkEmpty:
  785. internalError(g.config, info, "resolved destructor is generic")
  786. if t.destructor.magic == mDestroy:
  787. internalError(g.config, info, "patching mDestroy with mDestroy?")
  788. n[0] = newSymNode(t.destructor)
  789. for x in n: patchBody(g, c, x, info)
  790. template inst(field, t) =
  791. if field.ast != nil and field.ast[genericParamsPos].kind != nkEmpty:
  792. if t.typeInst != nil:
  793. var a: TLiftCtx
  794. a.info = info
  795. a.g = g
  796. a.kind = k
  797. a.c = c
  798. field = instantiateGeneric(a, field, t, t.typeInst)
  799. if field.ast != nil:
  800. patchBody(g, c, field.ast, info)
  801. else:
  802. localError(g.config, info, "unresolved generic parameter")
  803. proc isTrival(s: PSym): bool {.inline.} =
  804. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  805. proc isEmptyContainer(g: ModuleGraph, t: PType): bool =
  806. (t.kind == tyArray and lengthOrd(g.config, t[0]) == 0) or
  807. (t.kind == tySequence and t[0].kind == tyError)
  808. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo) =
  809. ## In the semantic pass this is called in strategic places
  810. ## to ensure we lift assignment, destructors and moves properly.
  811. ## The later 'injectdestructors' pass depends on it.
  812. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  813. incl orig.flags, tfCheckedForDestructor
  814. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  815. if isEmptyContainer(skipped): return
  816. let h = sighashes.hashType(skipped, {CoType, CoConsiderOwned, CoDistinct})
  817. var canon = g.canonTypes.getOrDefault(h)
  818. if canon == nil:
  819. g.canonTypes[h] = skipped
  820. canon = skipped
  821. # multiple cases are to distinguish here:
  822. # 1. we don't know yet if 'typ' has a nontrival destructor.
  823. # 2. we have a nop destructor. --> mDestroy
  824. # 3. we have a lifted destructor.
  825. # 4. We have a custom destructor.
  826. # 5. We have a (custom) generic destructor.
  827. # we do not generate '=trace' nor '=dispose' procs if we
  828. # have the cycle detection disabled, saves code size.
  829. let lastAttached = if g.config.selectedGC == gcOrc: attachedDispose
  830. else: attachedSink
  831. # we generate the destructor first so that other operators can depend on it:
  832. for k in attachedDestructor..lastAttached:
  833. if canon.attachedOps[k] == nil:
  834. discard produceSym(g, c, canon, k, info)
  835. else:
  836. inst(canon.attachedOps[k], canon)
  837. if canon != orig:
  838. orig.attachedOps[k] = canon.attachedOps[k]
  839. if not isTrival(orig.destructor):
  840. #or not isTrival(orig.assignment) or
  841. # not isTrival(orig.sink):
  842. orig.flags.incl tfHasAsgn