liftdestructors.nim 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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`, `=copy`, `=destroy`, `=deepCopy`, `=wasMoved`, `=dup`).
  11. import modulegraphs, lineinfos, idents, ast, renderer, semdata,
  12. sighashes, lowerings, options, types, msgs, magicsys, ccgutils
  13. import std/tables
  14. from trees import isCaseObj
  15. when defined(nimPreviewSlimSystem):
  16. import std/assertions
  17. type
  18. TLiftCtx = object
  19. g: ModuleGraph
  20. info: TLineInfo # for construction
  21. kind: TTypeAttachedOp
  22. fn: PSym
  23. asgnForType: PType
  24. recurse: bool
  25. addMemReset: bool # add wasMoved() call after destructor call
  26. canRaise: bool
  27. filterDiscriminator: PSym # we generating destructor for case branch
  28. c: PContext # c can be nil, then we are called from lambdalifting!
  29. idgen: IdGenerator
  30. template destructor*(t: PType): PSym = getAttachedOp(c.g, t, attachedDestructor)
  31. template assignment*(t: PType): PSym = getAttachedOp(c.g, t, attachedAsgn)
  32. template dup*(t: PType): PSym = getAttachedOp(c.g, t, attachedDup)
  33. template asink*(t: PType): PSym = getAttachedOp(c.g, t, attachedSink)
  34. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode)
  35. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  36. info: TLineInfo; idgen: IdGenerator; isDistinct = false): PSym
  37. proc createTypeBoundOps*(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  38. idgen: IdGenerator)
  39. proc at(a, i: PNode, elemType: PType): PNode =
  40. result = newNodeI(nkBracketExpr, a.info, 2)
  41. result[0] = a
  42. result[1] = i
  43. result.typ = elemType
  44. proc destructorOverridden(g: ModuleGraph; t: PType): bool =
  45. let op = getAttachedOp(g, t, attachedDestructor)
  46. op != nil and sfOverridden in op.flags
  47. proc fillBodyTup(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  48. for i, a in t.ikids:
  49. let lit = lowerings.newIntLit(c.g, x.info, i)
  50. let b = if c.kind == attachedTrace: y else: y.at(lit, a)
  51. fillBody(c, a, body, x.at(lit, a), b)
  52. proc dotField(x: PNode, f: PSym): PNode =
  53. result = newNodeI(nkDotExpr, x.info, 2)
  54. if x.typ.skipTypes(abstractInst).kind == tyVar:
  55. result[0] = x.newDeref
  56. else:
  57. result[0] = x
  58. result[1] = newSymNode(f, x.info)
  59. result.typ = f.typ
  60. proc newAsgnStmt(le, ri: PNode): PNode =
  61. result = newNodeI(nkAsgn, le.info, 2)
  62. result[0] = le
  63. result[1] = ri
  64. proc genBuiltin*(g: ModuleGraph; idgen: IdGenerator; magic: TMagic; name: string; i: PNode): PNode =
  65. result = newNodeI(nkCall, i.info)
  66. result.add createMagic(g, idgen, name, magic).newSymNode
  67. result.add i
  68. proc genBuiltin(c: var TLiftCtx; magic: TMagic; name: string; i: PNode): PNode =
  69. result = genBuiltin(c.g, c.idgen, magic, name, i)
  70. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  71. if c.kind in {attachedAsgn, attachedDeepCopy, attachedSink, attachedDup}:
  72. body.add newAsgnStmt(x, y)
  73. elif c.kind == attachedDestructor and c.addMemReset:
  74. let call = genBuiltin(c, mDefault, "default", x)
  75. call.typ = t
  76. body.add newAsgnStmt(x, call)
  77. elif c.kind == attachedWasMoved:
  78. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  79. proc genAddr(c: var TLiftCtx; x: PNode): PNode =
  80. if x.kind == nkHiddenDeref:
  81. checkSonsLen(x, 1, c.g.config)
  82. result = x[0]
  83. else:
  84. result = newNodeIT(nkHiddenAddr, x.info, makeVarType(x.typ.owner, x.typ, c.idgen))
  85. result.add x
  86. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  87. result = newNodeI(nkWhileStmt, c.info, 2)
  88. let cmp = genBuiltin(c, mLtI, "<", i)
  89. cmp.add genLen(c.g, dest)
  90. cmp.typ = getSysType(c.g, c.info, tyBool)
  91. result[0] = cmp
  92. result[1] = newNodeI(nkStmtList, c.info)
  93. proc genIf(c: var TLiftCtx; cond, action: PNode): PNode =
  94. result = newTree(nkIfStmt, newTree(nkElifBranch, cond, action))
  95. proc genContainerOf(c: var TLiftCtx; objType: PType, field, x: PSym): PNode =
  96. # generate: cast[ptr ObjType](cast[int](addr(x)) - offsetOf(objType.field))
  97. let intType = getSysType(c.g, unknownLineInfo, tyInt)
  98. let addrOf = newNodeIT(nkAddr, c.info, makePtrType(x.owner, x.typ, c.idgen))
  99. addrOf.add newDeref(newSymNode(x))
  100. let castExpr1 = newNodeIT(nkCast, c.info, intType)
  101. castExpr1.add newNodeIT(nkType, c.info, intType)
  102. castExpr1.add addrOf
  103. let dotExpr = newNodeIT(nkDotExpr, c.info, x.typ)
  104. dotExpr.add newNodeIT(nkType, c.info, objType)
  105. dotExpr.add newSymNode(field)
  106. let offsetOf = genBuiltin(c, mOffsetOf, "offsetof", dotExpr)
  107. offsetOf.typ = intType
  108. let minusExpr = genBuiltin(c, mSubI, "-", castExpr1)
  109. minusExpr.typ = intType
  110. minusExpr.add offsetOf
  111. let objPtr = makePtrType(objType.owner, objType, c.idgen)
  112. result = newNodeIT(nkCast, c.info, objPtr)
  113. result.add newNodeIT(nkType, c.info, objPtr)
  114. result.add minusExpr
  115. proc destructorCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  116. var destroy = newNodeIT(nkCall, x.info, op.typ.returnType)
  117. destroy.add(newSymNode(op))
  118. if op.typ.firstParamType.kind != tyVar:
  119. destroy.add x
  120. else:
  121. destroy.add genAddr(c, x)
  122. if sfNeverRaises notin op.flags:
  123. c.canRaise = true
  124. if c.addMemReset:
  125. result = newTree(nkStmtList, destroy, genBuiltin(c, mWasMoved, "`=wasMoved`", x))
  126. else:
  127. result = destroy
  128. proc genWasMovedCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  129. result = newNodeIT(nkCall, x.info, op.typ.returnType)
  130. result.add(newSymNode(op))
  131. result.add genAddr(c, x)
  132. proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool) =
  133. case n.kind
  134. of nkSym:
  135. if c.filterDiscriminator != nil: return
  136. let f = n.sym
  137. let b = if c.kind == attachedTrace: y else: y.dotField(f)
  138. if (sfCursor in f.flags and c.g.config.selectedGC in {gcArc, gcAtomicArc, gcOrc, gcHooks}) or
  139. enforceDefaultOp:
  140. defaultOp(c, f.typ, body, x.dotField(f), b)
  141. else:
  142. fillBody(c, f.typ, body, x.dotField(f), b)
  143. of nkNilLit: discard
  144. of nkRecCase:
  145. # XXX This is only correct for 'attachedSink'!
  146. var localEnforceDefaultOp = enforceDefaultOp
  147. if c.kind == attachedSink:
  148. # the value needs to be destroyed before we assign the selector
  149. # or the value is lost
  150. let prevKind = c.kind
  151. let prevAddMemReset = c.addMemReset
  152. c.kind = attachedDestructor
  153. c.addMemReset = true
  154. fillBodyObj(c, n, body, x, y, enforceDefaultOp = false)
  155. c.kind = prevKind
  156. c.addMemReset = prevAddMemReset
  157. localEnforceDefaultOp = true
  158. if c.kind != attachedDestructor:
  159. # copy the selector before case stmt, but destroy after case stmt
  160. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  161. let oldfilterDiscriminator = c.filterDiscriminator
  162. if c.filterDiscriminator == n[0].sym:
  163. c.filterDiscriminator = nil # we have found the case part, proceed as normal
  164. # we need to generate a case statement:
  165. var caseStmt = newNodeI(nkCaseStmt, c.info)
  166. # XXX generate 'if' that checks same branches
  167. # generate selector:
  168. var access = dotField(x, n[0].sym)
  169. caseStmt.add(access)
  170. var emptyBranches = 0
  171. # copy the branches over, but replace the fields with the for loop body:
  172. for i in 1..<n.len:
  173. var branch = copyTree(n[i])
  174. branch[^1] = newNodeI(nkStmtList, c.info)
  175. fillBodyObj(c, n[i].lastSon, branch[^1], x, y,
  176. enforceDefaultOp = localEnforceDefaultOp)
  177. if branch[^1].len == 0: inc emptyBranches
  178. caseStmt.add(branch)
  179. if emptyBranches != n.len-1:
  180. body.add(caseStmt)
  181. if c.kind == attachedDestructor:
  182. # destructor for selector is done after case stmt
  183. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  184. c.filterDiscriminator = oldfilterDiscriminator
  185. of nkRecList:
  186. for t in items(n): fillBodyObj(c, t, body, x, y, enforceDefaultOp)
  187. else:
  188. illFormedAstLocal(n, c.g.config)
  189. proc fillBodyObjTImpl(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  190. if t.baseClass != nil:
  191. fillBody(c, skipTypes(t.baseClass, abstractPtrs), body, x, y)
  192. fillBodyObj(c, t.n, body, x, y, enforceDefaultOp = false)
  193. proc fillBodyObjT(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  194. var hasCase = isCaseObj(t.n)
  195. var obj = t
  196. while obj.baseClass != nil:
  197. obj = skipTypes(obj.baseClass, abstractPtrs)
  198. hasCase = hasCase or isCaseObj(obj.n)
  199. if hasCase and c.kind in {attachedAsgn, attachedDeepCopy}:
  200. # assignment for case objects is complex, we do:
  201. # =destroy(dest)
  202. # wasMoved(dest)
  203. # for every field:
  204. # `=` dest.field, src.field
  205. # ^ this is what we used to do, but for 'result = result.sons[0]' it
  206. # destroys 'result' too early.
  207. # So this is what we really need to do:
  208. # let blob {.cursor.} = dest # remembers the old dest.kind
  209. # wasMoved(dest)
  210. # dest.kind = src.kind
  211. # for every field (dependent on dest.kind):
  212. # `=` dest.field, src.field
  213. # =destroy(blob)
  214. var dummy = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  215. dummy.typ = y.typ
  216. if ccgIntroducedPtr(c.g.config, dummy, y.typ):
  217. # Because of potential aliasing when the src param is passed by ref, we need to check for equality here,
  218. # because the wasMoved(dest) call would zero out src, if dest aliases src.
  219. var cond = newTree(nkCall, newSymNode(c.g.getSysMagic(c.info, "==", mEqRef)),
  220. newTreeIT(nkAddr, c.info, makePtrType(c.fn, x.typ, c.idgen), x), newTreeIT(nkAddr, c.info, makePtrType(c.fn, y.typ, c.idgen), y))
  221. cond.typ = getSysType(c.g, x.info, tyBool)
  222. body.add genIf(c, cond, newTreeI(nkReturnStmt, c.info, newNodeI(nkEmpty, c.info)))
  223. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  224. temp.typ = x.typ
  225. incl(temp.flags, sfFromGeneric)
  226. var v = newNodeI(nkVarSection, c.info)
  227. let blob = newSymNode(temp)
  228. v.addVar(blob, x)
  229. body.add v
  230. #body.add newAsgnStmt(blob, x)
  231. var wasMovedCall = newNodeI(nkCall, c.info)
  232. wasMovedCall.add(newSymNode(createMagic(c.g, c.idgen, "`=wasMoved`", mWasMoved)))
  233. wasMovedCall.add x # mWasMoved does not take the address
  234. body.add wasMovedCall
  235. fillBodyObjTImpl(c, t, body, x, y)
  236. when false:
  237. # does not work yet due to phase-ordering problems:
  238. assert t.destructor != nil
  239. body.add destructorCall(c.g, t.destructor, blob)
  240. let prevKind = c.kind
  241. c.kind = attachedDestructor
  242. fillBodyObjTImpl(c, t, body, blob, y)
  243. c.kind = prevKind
  244. else:
  245. fillBodyObjTImpl(c, t, body, x, y)
  246. proc boolLit*(g: ModuleGraph; info: TLineInfo; value: bool): PNode =
  247. result = newIntLit(g, info, ord value)
  248. result.typ = getSysType(g, info, tyBool)
  249. proc getCycleParam(c: TLiftCtx): PNode =
  250. assert c.kind in {attachedAsgn, attachedDup}
  251. if c.fn.typ.len == 3 + ord(c.kind == attachedAsgn):
  252. result = c.fn.typ.n.lastSon
  253. assert result.kind == nkSym
  254. assert result.sym.name.s == "cyclic"
  255. else:
  256. result = boolLit(c.g, c.info, true)
  257. proc newHookCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  258. #if sfError in op.flags:
  259. # localError(c.config, x.info, "usage of '$1' is a user-defined error" % op.name.s)
  260. result = newNodeI(nkCall, x.info)
  261. result.add newSymNode(op)
  262. if sfNeverRaises notin op.flags:
  263. c.canRaise = true
  264. if op.typ.firstParamType.kind == tyVar:
  265. result.add genAddr(c, x)
  266. else:
  267. result.add x
  268. if y != nil:
  269. result.add y
  270. if op.typ.signatureLen == 4:
  271. assert y != nil
  272. if c.fn.typ.signatureLen == 4:
  273. result.add getCycleParam(c)
  274. else:
  275. # assume the worst: A cycle is created:
  276. result.add boolLit(c.g, y.info, true)
  277. proc newOpCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  278. result = newNodeIT(nkCall, x.info, op.typ.returnType)
  279. result.add(newSymNode(op))
  280. result.add x
  281. if sfNeverRaises notin op.flags:
  282. c.canRaise = true
  283. if c.kind == attachedDup and op.typ.len == 3:
  284. assert x != nil
  285. if c.fn.typ.len == 3:
  286. result.add getCycleParam(c)
  287. else:
  288. # assume the worst: A cycle is created:
  289. result.add boolLit(c.g, x.info, true)
  290. proc newDeepCopyCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  291. result = newAsgnStmt(x, newOpCall(c, op, y))
  292. proc newDupCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  293. result = newAsgnStmt(x, newOpCall(c, op, y))
  294. proc usesBuiltinArc(t: PType): bool =
  295. proc wrap(t: PType): bool {.nimcall.} = ast.isGCedMem(t)
  296. result = types.searchTypeFor(t, wrap)
  297. proc useNoGc(c: TLiftCtx; t: PType): bool {.inline.} =
  298. result = optSeqDestructors in c.g.config.globalOptions and
  299. ({tfHasGCedMem, tfHasOwned} * t.flags != {} or usesBuiltinArc(t))
  300. proc requiresDestructor(c: TLiftCtx; t: PType): bool {.inline.} =
  301. result = optSeqDestructors in c.g.config.globalOptions and
  302. containsGarbageCollectedRef(t)
  303. proc instantiateGeneric(c: var TLiftCtx; op: PSym; t, typeInst: PType): PSym =
  304. if c.c != nil and typeInst != nil:
  305. result = c.c.instTypeBoundOp(c.c, op, typeInst, c.info, attachedAsgn, 1)
  306. else:
  307. localError(c.g.config, c.info,
  308. "cannot generate destructor for generic type: " & typeToString(t))
  309. result = nil
  310. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  311. field: var PSym): bool =
  312. if optSeqDestructors in c.g.config.globalOptions:
  313. var op = field
  314. let destructorOverridden = destructorOverridden(c.g, t)
  315. if op != nil and op != c.fn and
  316. (sfOverridden in op.flags or destructorOverridden):
  317. if sfError in op.flags:
  318. incl c.fn.flags, sfError
  319. #else:
  320. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  321. onUse(c.info, op)
  322. body.add newHookCall(c, op, x, y)
  323. result = true
  324. elif op == nil and destructorOverridden:
  325. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  326. body.add newHookCall(c, op, x, y)
  327. result = true
  328. else:
  329. result = false
  330. elif tfHasAsgn in t.flags:
  331. var op: PSym
  332. if sameType(t, c.asgnForType):
  333. # generate recursive call:
  334. if c.recurse:
  335. op = c.fn
  336. else:
  337. c.recurse = true
  338. return false
  339. else:
  340. op = field
  341. if op == nil:
  342. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  343. if sfError in op.flags:
  344. incl c.fn.flags, sfError
  345. #else:
  346. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  347. onUse(c.info, op)
  348. # We also now do generic instantiations in the destructor lifting pass:
  349. if op.ast.isGenericRoutine:
  350. op = instantiateGeneric(c, op, t, t.typeInst)
  351. field = op
  352. #echo "trying to use ", op.ast
  353. #echo "for ", op.name.s, " "
  354. #debug(t)
  355. #return false
  356. assert op.ast[genericParamsPos].kind == nkEmpty
  357. body.add newHookCall(c, op, x, y)
  358. result = true
  359. else:
  360. result = false
  361. proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) =
  362. let t = orig.skipTypes(abstractInst - {tyDistinct})
  363. var op = t.destructor
  364. if op != nil and sfOverridden in op.flags:
  365. if op.ast.isGenericRoutine:
  366. # patch generic destructor:
  367. op = instantiateGeneric(c, op, t, t.typeInst)
  368. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  369. if op == nil and (useNoGc(c, t) or requiresDestructor(c, t)):
  370. op = produceSym(c.g, c.c, t, attachedDestructor, c.info, c.idgen)
  371. doAssert op != nil
  372. doAssert op == t.destructor
  373. if op != nil:
  374. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  375. onUse(c.info, op)
  376. body.add destructorCall(c, op, x)
  377. elif useNoGc(c, t):
  378. internalError(c.g.config, c.info,
  379. "type-bound operator could not be resolved")
  380. proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  381. case c.kind
  382. of attachedDestructor:
  383. var op = t.destructor
  384. if op != nil and sfOverridden in op.flags:
  385. if op.ast.isGenericRoutine:
  386. # patch generic destructor:
  387. op = instantiateGeneric(c, op, t, t.typeInst)
  388. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  389. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  390. onUse(c.info, op)
  391. body.add destructorCall(c, op, x)
  392. result = true
  393. else:
  394. result = false
  395. #result = addDestructorCall(c, t, body, x)
  396. of attachedAsgn, attachedSink, attachedTrace:
  397. var op = getAttachedOp(c.g, t, c.kind)
  398. if op != nil and sfOverridden in op.flags:
  399. if op.ast.isGenericRoutine:
  400. # patch generic =trace:
  401. op = instantiateGeneric(c, op, t, t.typeInst)
  402. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  403. result = considerAsgnOrSink(c, t, body, x, y, op)
  404. if op != nil:
  405. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  406. of attachedDeepCopy:
  407. let op = getAttachedOp(c.g, t, attachedDeepCopy)
  408. if op != nil:
  409. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  410. onUse(c.info, op)
  411. body.add newDeepCopyCall(c, op, x, y)
  412. result = true
  413. else:
  414. result = false
  415. of attachedWasMoved:
  416. var op = getAttachedOp(c.g, t, attachedWasMoved)
  417. if op != nil and sfOverridden in op.flags:
  418. if op.ast.isGenericRoutine:
  419. # patch generic destructor:
  420. op = instantiateGeneric(c, op, t, t.typeInst)
  421. setAttachedOp(c.g, c.idgen.module, t, attachedWasMoved, op)
  422. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  423. onUse(c.info, op)
  424. body.add genWasMovedCall(c, op, x)
  425. result = true
  426. else:
  427. result = false
  428. of attachedDup:
  429. var op = getAttachedOp(c.g, t, attachedDup)
  430. if op != nil and sfOverridden in op.flags:
  431. if op.ast.isGenericRoutine:
  432. # patch generic destructor:
  433. op = instantiateGeneric(c, op, t, t.typeInst)
  434. setAttachedOp(c.g, c.idgen.module, t, attachedDup, op)
  435. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  436. onUse(c.info, op)
  437. body.add newDupCall(c, op, x, y)
  438. result = true
  439. else:
  440. result = false
  441. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  442. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  443. temp.typ = getSysType(c.g, body.info, tyInt)
  444. incl(temp.flags, sfFromGeneric)
  445. var v = newNodeI(nkVarSection, c.info)
  446. result = newSymNode(temp)
  447. v.addVar(result, lowerings.newIntLit(c.g, body.info, first))
  448. body.add v
  449. proc declareTempOf(c: var TLiftCtx; body: PNode; value: PNode): PNode =
  450. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  451. temp.typ = value.typ
  452. incl(temp.flags, sfFromGeneric)
  453. var v = newNodeI(nkVarSection, c.info)
  454. result = newSymNode(temp)
  455. v.addVar(result, value)
  456. body.add v
  457. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  458. let incCall = genBuiltin(c, mInc, "inc", i)
  459. incCall.add lowerings.newIntLit(c.g, c.info, 1)
  460. body.add incCall
  461. proc newSeqCall(c: var TLiftCtx; x, y: PNode): PNode =
  462. # don't call genAddr(c, x) here:
  463. result = genBuiltin(c, mNewSeq, "newSeq", x)
  464. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  465. lenCall.typ = getSysType(c.g, x.info, tyInt)
  466. result.add lenCall
  467. proc setLenStrCall(c: var TLiftCtx; x, y: PNode): PNode =
  468. let lenCall = genBuiltin(c, mLengthStr, "len", y)
  469. lenCall.typ = getSysType(c.g, x.info, tyInt)
  470. result = genBuiltin(c, mSetLengthStr, "setLen", x) # genAddr(g, x))
  471. result.add lenCall
  472. proc setLenSeqCall(c: var TLiftCtx; t: PType; x, y: PNode): PNode =
  473. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  474. lenCall.typ = getSysType(c.g, x.info, tyInt)
  475. var op = getSysMagic(c.g, x.info, "setLen", mSetLengthSeq)
  476. op = instantiateGeneric(c, op, t, t)
  477. result = newTree(nkCall, newSymNode(op, x.info), x, lenCall)
  478. proc forallElements(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  479. let counterIdx = body.len
  480. let i = declareCounter(c, body, toInt64(firstOrd(c.g.config, t)))
  481. let whileLoop = genWhileLoop(c, i, x)
  482. let elemType = t.elementType
  483. let b = if c.kind == attachedTrace: y else: y.at(i, elemType)
  484. fillBody(c, elemType, whileLoop[1], x.at(i, elemType), b)
  485. if whileLoop[1].len > 0:
  486. addIncStmt(c, whileLoop[1], i)
  487. body.add whileLoop
  488. else:
  489. body.sons.setLen counterIdx
  490. proc checkSelfAssignment(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  491. var cond = callCodegenProc(c.g, "sameSeqPayload", c.info,
  492. newTreeIT(nkAddr, c.info, makePtrType(c.fn, x.typ, c.idgen), x),
  493. newTreeIT(nkAddr, c.info, makePtrType(c.fn, y.typ, c.idgen), y)
  494. )
  495. cond.typ = getSysType(c.g, c.info, tyBool)
  496. body.add genIf(c, cond, newTreeI(nkReturnStmt, c.info, newNodeI(nkEmpty, c.info)))
  497. proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  498. case c.kind
  499. of attachedDup:
  500. body.add setLenSeqCall(c, t, x, y)
  501. forallElements(c, t, body, x, y)
  502. of attachedAsgn, attachedDeepCopy:
  503. # we generate:
  504. # if x.p == y.p:
  505. # return
  506. # setLen(dest, y.len)
  507. # var i = 0
  508. # while i < y.len: dest[i] = y[i]; inc(i)
  509. # This is usually more efficient than a destroy/create pair.
  510. checkSelfAssignment(c, t, body, x, y)
  511. body.add setLenSeqCall(c, t, x, y)
  512. forallElements(c, t, body, x, y)
  513. of attachedSink:
  514. let moveCall = genBuiltin(c, mMove, "move", x)
  515. moveCall.add y
  516. doAssert t.destructor != nil
  517. moveCall.add destructorCall(c, t.destructor, x)
  518. body.add moveCall
  519. of attachedDestructor:
  520. # destroy all elements:
  521. forallElements(c, t, body, x, y)
  522. body.add genBuiltin(c, mDestroy, "destroy", x)
  523. of attachedTrace:
  524. if canFormAcycle(c.g, t.elemType):
  525. # follow all elements:
  526. forallElements(c, t, body, x, y)
  527. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  528. proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  529. createTypeBoundOps(c.g, c.c, t, body.info, c.idgen)
  530. # recursions are tricky, so we might need to forward the generated
  531. # operation here:
  532. var t = t
  533. if t.assignment == nil or t.destructor == nil or t.dup == nil:
  534. let h = sighashes.hashType(t,c.g.config, {CoType, CoConsiderOwned, CoDistinct})
  535. let canon = c.g.canonTypes.getOrDefault(h)
  536. if canon != nil: t = canon
  537. case c.kind
  538. of attachedAsgn, attachedDeepCopy:
  539. # XXX: replace these with assertions.
  540. if t.assignment == nil:
  541. return # protect from recursion
  542. body.add newHookCall(c, t.assignment, x, y)
  543. of attachedSink:
  544. # we always inline the move for better performance:
  545. let moveCall = genBuiltin(c, mMove, "move", x)
  546. moveCall.add y
  547. doAssert t.destructor != nil
  548. moveCall.add destructorCall(c, t.destructor, x)
  549. body.add moveCall
  550. # alternatively we could do this:
  551. when false:
  552. doAssert t.asink != nil
  553. body.add newHookCall(c, t.asink, x, y)
  554. of attachedDestructor:
  555. doAssert t.destructor != nil
  556. body.add destructorCall(c, t.destructor, x)
  557. of attachedTrace:
  558. if t.kind != tyString and canFormAcycle(c.g, t.elemType):
  559. let op = getAttachedOp(c.g, t, c.kind)
  560. if op == nil:
  561. return # protect from recursion
  562. body.add newHookCall(c, op, x, y)
  563. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  564. of attachedDup:
  565. # XXX: replace these with assertions.
  566. let op = getAttachedOp(c.g, t, c.kind)
  567. if op == nil:
  568. return # protect from recursion
  569. body.add newDupCall(c, op, x, y)
  570. proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  571. case c.kind
  572. of attachedAsgn, attachedDeepCopy, attachedDup:
  573. body.add callCodegenProc(c.g, "nimAsgnStrV2", c.info, genAddr(c, x), y)
  574. of attachedSink:
  575. let moveCall = genBuiltin(c, mMove, "move", x)
  576. moveCall.add y
  577. doAssert t.destructor != nil
  578. moveCall.add destructorCall(c, t.destructor, x)
  579. body.add moveCall
  580. of attachedDestructor:
  581. body.add genBuiltin(c, mDestroy, "destroy", x)
  582. of attachedTrace:
  583. discard "strings are atomic and have no inner elements that are to trace"
  584. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  585. proc cyclicType*(g: ModuleGraph, t: PType): bool =
  586. case t.kind
  587. of tyRef: result = types.canFormAcycle(g, t.elementType)
  588. of tyProc: result = t.callConv == ccClosure
  589. else: result = false
  590. proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  591. #[ bug #15753 is really subtle. Usually the classical write barrier for reference
  592. counting looks like this::
  593. incRef source # increment first; this takes care of self-assignments1
  594. decRef dest
  595. dest[] = source
  596. However, 'decRef dest' might trigger a cycle collection and then the collector
  597. traverses the graph. It is crucial that when it follows the pointers the assignment
  598. 'dest[] = source' already happened so that we don't do trial deletion on a wrong
  599. graph -- this causes premature freeing of objects! The correct barrier looks like
  600. this::
  601. let tmp = dest
  602. incRef source
  603. dest[] = source
  604. decRef tmp
  605. ]#
  606. var actions = newNodeI(nkStmtList, c.info)
  607. let elemType = t.elementType
  608. createTypeBoundOps(c.g, c.c, elemType, c.info, c.idgen)
  609. let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(c.g, elemType)
  610. let isInheritableAcyclicRef = c.g.config.selectedGC == gcOrc and
  611. (not isPureObject(elemType)) and
  612. tfAcyclic in skipTypes(elemType, abstractInst+{tyOwned}-{tyTypeDesc}).flags
  613. # dynamic Acyclic refs need to use dyn decRef
  614. let tmp =
  615. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  616. declareTempOf(c, body, x)
  617. else:
  618. x
  619. if isFinal(elemType):
  620. addDestructorCall(c, elemType, actions, genDeref(tmp, nkDerefExpr))
  621. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  622. alignOf.typ = getSysType(c.g, c.info, tyInt)
  623. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, tmp, alignOf)
  624. else:
  625. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(tmp, nkDerefExpr))
  626. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  627. var cond: PNode
  628. if isCyclic:
  629. if isFinal(elemType):
  630. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  631. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  632. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
  633. else:
  634. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
  635. elif isInheritableAcyclicRef:
  636. cond = callCodegenProc(c.g, "nimDecRefIsLastDyn", c.info, x)
  637. else:
  638. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  639. cond.typ = getSysType(c.g, x.info, tyBool)
  640. case c.kind
  641. of attachedSink:
  642. if isCyclic:
  643. body.add newAsgnStmt(x, y)
  644. body.add genIf(c, cond, actions)
  645. else:
  646. body.add genIf(c, cond, actions)
  647. body.add newAsgnStmt(x, y)
  648. of attachedAsgn:
  649. if isCyclic:
  650. body.add genIf(c, y, callCodegenProc(c.g,
  651. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  652. body.add newAsgnStmt(x, y)
  653. body.add genIf(c, cond, actions)
  654. else:
  655. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  656. body.add genIf(c, cond, actions)
  657. body.add newAsgnStmt(x, y)
  658. of attachedDestructor:
  659. body.add genIf(c, cond, actions)
  660. of attachedDeepCopy: assert(false, "cannot happen")
  661. of attachedTrace:
  662. if isCyclic:
  663. if isFinal(elemType):
  664. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  665. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  666. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x, c.idgen), typInfo, y)
  667. else:
  668. # If the ref is polymorphic we have to account for this
  669. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
  670. #echo "can follow ", elemType, " static ", isFinal(elemType)
  671. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  672. of attachedDup:
  673. if isCyclic:
  674. body.add newAsgnStmt(x, y)
  675. body.add genIf(c, y, callCodegenProc(c.g,
  676. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  677. else:
  678. body.add newAsgnStmt(x, y)
  679. body.add genIf(c, y, callCodegenProc(c.g,
  680. "nimIncRef", c.info, y))
  681. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  682. ## Closures are really like refs except they always use a virtual destructor
  683. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  684. let xenv = genBuiltin(c, mAccessEnv, "accessEnv", x)
  685. xenv.typ = getSysType(c.g, c.info, tyPointer)
  686. let isCyclic = c.g.config.selectedGC == gcOrc
  687. let tmp =
  688. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  689. declareTempOf(c, body, xenv)
  690. else:
  691. xenv
  692. var actions = newNodeI(nkStmtList, c.info)
  693. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  694. let decRefProc =
  695. if isCyclic: "nimDecRefIsLastCyclicDyn"
  696. else: "nimDecRefIsLast"
  697. let cond = callCodegenProc(c.g, decRefProc, c.info, tmp)
  698. cond.typ = getSysType(c.g, x.info, tyBool)
  699. case c.kind
  700. of attachedSink:
  701. if isCyclic:
  702. body.add newAsgnStmt(x, y)
  703. body.add genIf(c, cond, actions)
  704. else:
  705. body.add genIf(c, cond, actions)
  706. body.add newAsgnStmt(x, y)
  707. of attachedAsgn:
  708. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  709. yenv.typ = getSysType(c.g, c.info, tyPointer)
  710. if isCyclic:
  711. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  712. body.add newAsgnStmt(x, y)
  713. body.add genIf(c, cond, actions)
  714. else:
  715. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  716. body.add genIf(c, cond, actions)
  717. body.add newAsgnStmt(x, y)
  718. of attachedDup:
  719. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  720. yenv.typ = getSysType(c.g, c.info, tyPointer)
  721. if isCyclic:
  722. body.add newAsgnStmt(x, y)
  723. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  724. else:
  725. body.add newAsgnStmt(x, y)
  726. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  727. of attachedDestructor:
  728. body.add genIf(c, cond, actions)
  729. of attachedDeepCopy: assert(false, "cannot happen")
  730. of attachedTrace:
  731. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
  732. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  733. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  734. case c.kind
  735. of attachedSink:
  736. # we 'nil' y out afterwards so we *need* to take over its reference
  737. # count value:
  738. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  739. body.add newAsgnStmt(x, y)
  740. of attachedAsgn:
  741. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  742. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  743. body.add newAsgnStmt(x, y)
  744. of attachedDup:
  745. body.add newAsgnStmt(x, y)
  746. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  747. of attachedDestructor:
  748. # it's better to prepend the destruction of weak refs in order to
  749. # prevent wrong "dangling refs exist" problems:
  750. var actions = newNodeI(nkStmtList, c.info)
  751. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  752. let des = genIf(c, x, actions)
  753. if body.len == 0:
  754. body.add des
  755. else:
  756. body.sons.insert(des, 0)
  757. of attachedDeepCopy: assert(false, "cannot happen")
  758. of attachedTrace: discard
  759. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  760. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  761. var actions = newNodeI(nkStmtList, c.info)
  762. let elemType = t.skipModifier
  763. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  764. #var disposeCall = genBuiltin(c, mDispose, "dispose", x)
  765. if isFinal(elemType):
  766. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  767. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  768. alignOf.typ = getSysType(c.g, c.info, tyInt)
  769. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x, alignOf)
  770. else:
  771. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  772. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  773. case c.kind
  774. of attachedSink, attachedAsgn:
  775. body.add genIf(c, x, actions)
  776. body.add newAsgnStmt(x, y)
  777. of attachedDup:
  778. body.add newAsgnStmt(x, y)
  779. of attachedDestructor:
  780. body.add genIf(c, x, actions)
  781. of attachedDeepCopy: assert(false, "cannot happen")
  782. of attachedTrace: discard
  783. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  784. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  785. if c.kind == attachedDeepCopy:
  786. # a big problem is that we don't know the environment's type here, so we
  787. # have to go through some indirection; we delegate this to the codegen:
  788. let call = newNodeI(nkCall, c.info, 2)
  789. call.typ = t
  790. call[0] = newSymNode(createMagic(c.g, c.idgen, "deepCopy", mDeepCopy))
  791. call[1] = y
  792. body.add newAsgnStmt(x, call)
  793. elif (optOwnedRefs in c.g.config.globalOptions and
  794. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  795. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  796. xx.typ = getSysType(c.g, c.info, tyPointer)
  797. case c.kind
  798. of attachedSink:
  799. # we 'nil' y out afterwards so we *need* to take over its reference
  800. # count value:
  801. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  802. body.add newAsgnStmt(x, y)
  803. of attachedAsgn:
  804. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  805. yy.typ = getSysType(c.g, c.info, tyPointer)
  806. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  807. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  808. body.add newAsgnStmt(x, y)
  809. of attachedDup:
  810. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  811. yy.typ = getSysType(c.g, c.info, tyPointer)
  812. body.add newAsgnStmt(x, y)
  813. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  814. of attachedDestructor:
  815. let des = genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  816. if body.len == 0:
  817. body.add des
  818. else:
  819. body.sons.insert(des, 0)
  820. of attachedDeepCopy: assert(false, "cannot happen")
  821. of attachedTrace: discard
  822. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  823. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  824. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  825. xx.typ = getSysType(c.g, c.info, tyPointer)
  826. var actions = newNodeI(nkStmtList, c.info)
  827. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  828. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  829. case c.kind
  830. of attachedSink, attachedAsgn:
  831. body.add genIf(c, xx, actions)
  832. body.add newAsgnStmt(x, y)
  833. of attachedDup:
  834. body.add newAsgnStmt(x, y)
  835. of attachedDestructor:
  836. body.add genIf(c, xx, actions)
  837. of attachedDeepCopy: assert(false, "cannot happen")
  838. of attachedTrace: discard
  839. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  840. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  841. case t.kind
  842. of tyNone, tyEmpty, tyVoid: discard
  843. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCstring,
  844. tyPtr, tyUncheckedArray, tyVar, tyLent:
  845. defaultOp(c, t, body, x, y)
  846. of tyRef:
  847. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  848. atomicRefOp(c, t, body, x, y)
  849. elif (optOwnedRefs in c.g.config.globalOptions and
  850. optRefCheck in c.g.config.options):
  851. weakrefOp(c, t, body, x, y)
  852. else:
  853. defaultOp(c, t, body, x, y)
  854. of tyProc:
  855. if t.callConv == ccClosure:
  856. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  857. atomicClosureOp(c, t, body, x, y)
  858. else:
  859. closureOp(c, t, body, x, y)
  860. else:
  861. defaultOp(c, t, body, x, y)
  862. of tyOwned:
  863. let base = t.skipTypes(abstractInstOwned)
  864. if optOwnedRefs in c.g.config.globalOptions:
  865. case base.kind
  866. of tyRef:
  867. ownedRefOp(c, base, body, x, y)
  868. return
  869. of tyProc:
  870. if base.callConv == ccClosure:
  871. ownedClosureOp(c, base, body, x, y)
  872. return
  873. else: discard
  874. defaultOp(c, base, body, x, y)
  875. of tyArray:
  876. if tfHasAsgn in t.flags or useNoGc(c, t):
  877. forallElements(c, t, body, x, y)
  878. else:
  879. defaultOp(c, t, body, x, y)
  880. of tySequence:
  881. if useNoGc(c, t):
  882. useSeqOrStrOp(c, t, body, x, y)
  883. elif optSeqDestructors in c.g.config.globalOptions:
  884. # note that tfHasAsgn is propagated so we need the check on
  885. # 'selectedGC' here to determine if we have the new runtime.
  886. discard considerUserDefinedOp(c, t, body, x, y)
  887. elif tfHasAsgn in t.flags:
  888. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  889. body.add newSeqCall(c, x, y)
  890. forallElements(c, t, body, x, y)
  891. else:
  892. defaultOp(c, t, body, x, y)
  893. of tyString:
  894. if useNoGc(c, t):
  895. useSeqOrStrOp(c, t, body, x, y)
  896. elif tfHasAsgn in t.flags:
  897. discard considerUserDefinedOp(c, t, body, x, y)
  898. else:
  899. defaultOp(c, t, body, x, y)
  900. of tyObject:
  901. if not considerUserDefinedOp(c, t, body, x, y):
  902. if t.sym != nil and sfImportc in t.sym.flags:
  903. case c.kind
  904. of {attachedAsgn, attachedSink, attachedDup}:
  905. body.add newAsgnStmt(x, y)
  906. of attachedWasMoved:
  907. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  908. else:
  909. fillBodyObjT(c, t, body, x, y)
  910. else:
  911. if c.kind == attachedDup:
  912. var op2 = getAttachedOp(c.g, t, attachedAsgn)
  913. if op2 != nil and sfOverridden in op2.flags:
  914. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  915. onUse(c.info, op2)
  916. body.add newHookCall(c, t.assignment, x, y)
  917. else:
  918. fillBodyObjT(c, t, body, x, y)
  919. else:
  920. fillBodyObjT(c, t, body, x, y)
  921. of tyDistinct:
  922. if not considerUserDefinedOp(c, t, body, x, y):
  923. fillBody(c, t.elementType, body, x, y)
  924. of tyTuple:
  925. fillBodyTup(c, t, body, x, y)
  926. of tyVarargs, tyOpenArray:
  927. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  928. forallElements(c, t, body, x, y)
  929. else:
  930. discard "cannot copy openArray"
  931. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  932. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  933. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  934. tyTypeDesc, tyGenericInvocation, tyForward, tyStatic:
  935. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  936. discard
  937. of tyOrdinal, tyRange, tyInferred,
  938. tyGenericInst, tyAlias, tySink:
  939. fillBody(c, skipModifier(t), body, x, y)
  940. of tyConcept, tyIterable: raiseAssert "unreachable"
  941. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  942. kind: TTypeAttachedOp; info: TLineInfo;
  943. idgen: IdGenerator): PSym =
  944. assert typ.kind == tyDistinct
  945. let baseType = typ.elementType
  946. if getAttachedOp(g, baseType, kind) == nil:
  947. # TODO: fixme `isDistinct` is a fix for #23552; remove it after
  948. # `-d:nimPreviewNonVarDestructor` becomes the default
  949. discard produceSym(g, c, baseType, kind, info, idgen, isDistinct = true)
  950. result = getAttachedOp(g, baseType, kind)
  951. setAttachedOp(g, idgen.module, typ, kind, result)
  952. proc symDupPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  953. info: TLineInfo; idgen: IdGenerator): PSym =
  954. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  955. result = newSym(skProc, procname, idgen, owner, info)
  956. let res = newSym(skResult, getIdent(g.cache, "result"), idgen, result, info)
  957. let src = newSym(skParam, getIdent(g.cache, "src"),
  958. idgen, result, info)
  959. res.typ = typ
  960. src.typ = typ
  961. result.typ = newType(tyProc, idgen, owner)
  962. result.typ.n = newNodeI(nkFormalParams, info)
  963. rawAddSon(result.typ, res.typ)
  964. result.typ.n.add newNodeI(nkEffectList, info)
  965. result.typ.addParam src
  966. if g.config.selectedGC == gcOrc and
  967. cyclicType(g, typ.skipTypes(abstractInst)):
  968. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  969. idgen, result, info)
  970. cycleParam.typ = getSysType(g, info, tyBool)
  971. result.typ.addParam cycleParam
  972. var n = newNodeI(nkProcDef, info, bodyPos+2)
  973. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  974. n[namePos] = newSymNode(result)
  975. n[paramsPos] = result.typ.n
  976. n[bodyPos] = newNodeI(nkStmtList, info)
  977. n[resultPos] = newSymNode(res)
  978. result.ast = n
  979. incl result.flags, sfFromGeneric
  980. incl result.flags, sfGeneratedOp
  981. proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  982. info: TLineInfo; idgen: IdGenerator; isDiscriminant = false; isDistinct = false): PSym =
  983. if kind == attachedDup:
  984. return symDupPrototype(g, typ, owner, kind, info, idgen)
  985. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  986. result = newSym(skProc, procname, idgen, owner, info)
  987. let dest = newSym(skParam, getIdent(g.cache, "dest"), idgen, result, info)
  988. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"),
  989. idgen, result, info)
  990. if kind == attachedDestructor and g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc} and
  991. ((g.config.isDefined("nimPreviewNonVarDestructor") and not isDiscriminant) or (typ.kind in {tyRef, tyString, tySequence} and not isDistinct)):
  992. dest.typ = typ
  993. else:
  994. dest.typ = makeVarType(typ.owner, typ, idgen)
  995. if kind == attachedTrace:
  996. src.typ = getSysType(g, info, tyPointer)
  997. else:
  998. src.typ = typ
  999. result.typ = newProcType(info, idgen, owner)
  1000. result.typ.addParam dest
  1001. if kind notin {attachedDestructor, attachedWasMoved}:
  1002. result.typ.addParam src
  1003. if kind == attachedAsgn and g.config.selectedGC == gcOrc and
  1004. cyclicType(g, typ.skipTypes(abstractInst)):
  1005. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  1006. idgen, result, info)
  1007. cycleParam.typ = getSysType(g, info, tyBool)
  1008. result.typ.addParam cycleParam
  1009. var n = newNodeI(nkProcDef, info, bodyPos+1)
  1010. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  1011. n[namePos] = newSymNode(result)
  1012. n[paramsPos] = result.typ.n
  1013. n[bodyPos] = newNodeI(nkStmtList, info)
  1014. result.ast = n
  1015. incl result.flags, sfFromGeneric
  1016. incl result.flags, sfGeneratedOp
  1017. if kind == attachedWasMoved:
  1018. incl result.flags, sfNoSideEffect
  1019. incl result.typ.flags, tfNoSideEffect
  1020. proc genTypeFieldCopy(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  1021. let xx = genBuiltin(c, mAccessTypeField, "accessTypeField", x)
  1022. let yy = genBuiltin(c, mAccessTypeField, "accessTypeField", y)
  1023. xx.typ = getSysType(c.g, c.info, tyPointer)
  1024. yy.typ = xx.typ
  1025. body.add newAsgnStmt(xx, yy)
  1026. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  1027. info: TLineInfo; idgen: IdGenerator; isDistinct = false): PSym =
  1028. if typ.kind == tyDistinct:
  1029. return produceSymDistinctType(g, c, typ, kind, info, idgen)
  1030. result = getAttachedOp(g, typ, kind)
  1031. if result == nil:
  1032. result = symPrototype(g, typ, typ.owner, kind, info, idgen, isDistinct = isDistinct)
  1033. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType: typ, idgen: idgen,
  1034. fn: result)
  1035. let dest = if kind == attachedDup: result.ast[resultPos].sym else: result.typ.n[1].sym
  1036. let d = if result.typ.firstParamType.kind == tyVar: newDeref(newSymNode(dest)) else: newSymNode(dest)
  1037. let src = case kind
  1038. of {attachedDestructor, attachedWasMoved}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1039. of attachedDup: newSymNode(result.typ.n[1].sym)
  1040. else: newSymNode(result.typ.n[2].sym)
  1041. # register this operation already:
  1042. setAttachedOpPartial(g, idgen.module, typ, kind, result)
  1043. if kind == attachedSink and destructorOverridden(g, typ):
  1044. ## compiler can use a combination of `=destroy` and memCopy for sink op
  1045. dest.flags.incl sfCursor
  1046. let op = getAttachedOp(g, typ, attachedDestructor)
  1047. result.ast[bodyPos].add newOpCall(a, op, if op.typ.firstParamType.kind == tyVar: d[0] else: d)
  1048. result.ast[bodyPos].add newAsgnStmt(d, src)
  1049. else:
  1050. var tk: TTypeKind
  1051. if g.config.selectedGC in {gcArc, gcOrc, gcHooks, gcAtomicArc}:
  1052. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  1053. else:
  1054. tk = tyNone # no special casing for strings and seqs
  1055. case tk
  1056. of tySequence:
  1057. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  1058. of tyString:
  1059. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  1060. else:
  1061. fillBody(a, typ, result.ast[bodyPos], d, src)
  1062. if tk == tyObject and a.kind in {attachedAsgn, attachedSink, attachedDeepCopy, attachedDup} and not lacksMTypeField(typ):
  1063. # bug #19205: Do not forget to also copy the hidden type field:
  1064. genTypeFieldCopy(a, typ, result.ast[bodyPos], d, src)
  1065. if not a.canRaise:
  1066. incl result.flags, sfNeverRaises
  1067. result.ast[pragmasPos] = newNodeI(nkPragma, info)
  1068. result.ast[pragmasPos].add newTree(nkExprColonExpr,
  1069. newIdentNode(g.cache.getIdent("raises"), info), newNodeI(nkBracket, info))
  1070. completePartialOp(g, idgen.module, typ, kind, result)
  1071. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym,
  1072. info: TLineInfo; idgen: IdGenerator): PSym =
  1073. assert(typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject)
  1074. # discrimantor assignments needs pointers to destroy fields; alas, we cannot use non-var destructor here
  1075. result = symPrototype(g, field.typ, typ.owner, attachedDestructor, info, idgen, isDiscriminant = true)
  1076. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ, idgen: idgen,
  1077. fn: result)
  1078. a.asgnForType = typ
  1079. a.filterDiscriminator = field
  1080. a.addMemReset = true
  1081. let discrimantDest = result.typ.n[1].sym
  1082. let dst = newSym(skVar, getIdent(g.cache, "dest"), idgen, result, info)
  1083. dst.typ = makePtrType(typ.owner, typ, idgen)
  1084. let dstSym = newSymNode(dst)
  1085. let d = newDeref(dstSym)
  1086. let v = newNodeI(nkVarSection, info)
  1087. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  1088. result.ast[bodyPos].add v
  1089. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1090. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  1091. if not a.canRaise: incl result.flags, sfNeverRaises
  1092. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  1093. discard "now a nop"
  1094. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo; idgen: IdGenerator) =
  1095. if n.kind in nkCallKinds:
  1096. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  1097. let t = n[1].typ.skipTypes(abstractVar)
  1098. if getAttachedOp(g, t, attachedDestructor) == nil:
  1099. discard produceSym(g, c, t, attachedDestructor, info, idgen)
  1100. let op = getAttachedOp(g, t, attachedDestructor)
  1101. if op != nil:
  1102. if op.ast.isGenericRoutine:
  1103. internalError(g.config, info, "resolved destructor is generic")
  1104. if op.magic == mDestroy and t.kind != tyString:
  1105. internalError(g.config, info, "patching mDestroy with mDestroy?")
  1106. n[0] = newSymNode(op)
  1107. for x in n: patchBody(g, c, x, info, idgen)
  1108. proc inst(g: ModuleGraph; c: PContext; t: PType; kind: TTypeAttachedOp; idgen: IdGenerator;
  1109. info: TLineInfo) =
  1110. let op = getAttachedOp(g, t, kind)
  1111. if op != nil and op.ast != nil and op.ast.isGenericRoutine:
  1112. if t.typeInst != nil:
  1113. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, idgen: idgen)
  1114. let opInst = instantiateGeneric(a, op, t, t.typeInst)
  1115. if opInst.ast != nil:
  1116. patchBody(g, c, opInst.ast, info, a.idgen)
  1117. setAttachedOp(g, idgen.module, t, kind, opInst)
  1118. else:
  1119. localError(g.config, info, "unresolved generic parameter")
  1120. proc isTrival*(s: PSym): bool {.inline.} =
  1121. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  1122. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  1123. idgen: IdGenerator) =
  1124. ## In the semantic pass this is called in strategic places
  1125. ## to ensure we lift assignment, destructors and moves properly.
  1126. ## The later 'injectdestructors' pass depends on it.
  1127. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  1128. incl orig.flags, tfCheckedForDestructor
  1129. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  1130. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  1131. let h = sighashes.hashType(skipped, g.config, {CoType, CoConsiderOwned, CoDistinct})
  1132. var canon = g.canonTypes.getOrDefault(h)
  1133. if canon == nil:
  1134. g.canonTypes[h] = skipped
  1135. canon = skipped
  1136. # multiple cases are to distinguish here:
  1137. # 1. we don't know yet if 'typ' has a nontrival destructor.
  1138. # 2. we have a nop destructor. --> mDestroy
  1139. # 3. we have a lifted destructor.
  1140. # 4. We have a custom destructor.
  1141. # 5. We have a (custom) generic destructor.
  1142. # we do not generate '=trace' procs if we
  1143. # have the cycle detection disabled, saves code size.
  1144. let lastAttached = if g.config.selectedGC == gcOrc: attachedTrace
  1145. else: attachedSink
  1146. # bug #15122: We need to produce all prototypes before entering the
  1147. # mind boggling recursion. Hacks like these imply we should rewrite
  1148. # this module.
  1149. var generics: array[attachedWasMoved..attachedTrace, bool] = default(array[attachedWasMoved..attachedTrace, bool])
  1150. for k in attachedWasMoved..lastAttached:
  1151. generics[k] = getAttachedOp(g, canon, k) != nil
  1152. if not generics[k]:
  1153. setAttachedOp(g, idgen.module, canon, k,
  1154. symPrototype(g, canon, canon.owner, k, info, idgen))
  1155. # we generate the destructor first so that other operators can depend on it:
  1156. for k in attachedWasMoved..lastAttached:
  1157. if not generics[k]:
  1158. discard produceSym(g, c, canon, k, info, idgen)
  1159. else:
  1160. inst(g, c, canon, k, idgen, info)
  1161. if canon != orig:
  1162. setAttachedOp(g, idgen.module, orig, k, getAttachedOp(g, canon, k))
  1163. if not isTrival(getAttachedOp(g, orig, attachedDestructor)):
  1164. #or not isTrival(orig.assignment) or
  1165. # not isTrival(orig.sink):
  1166. orig.flags.incl tfHasAsgn
  1167. # ^ XXX Breaks IC!