liftdestructors.nim 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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): 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 in 0..<t.len:
  49. let lit = lowerings.newIntLit(c.g, x.info, i)
  50. let b = if c.kind == attachedTrace: y else: y.at(lit, t[i])
  51. fillBody(c, t[i], body, x.at(lit, t[i]), 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[0])
  117. destroy.add(newSymNode(op))
  118. if op.typ[1].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[0])
  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.len > 0 and t[0] != nil:
  191. fillBody(c, skipTypes(t[0], 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.len > 0 and obj[0] != nil:
  197. obj = skipTypes(obj[0], 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 == 4:
  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[1].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.len == 4:
  271. assert y != nil
  272. if c.fn.typ.len == 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[0])
  279. result.add(newSymNode(op))
  280. result.add x
  281. if sfNeverRaises notin op.flags:
  282. c.canRaise = true
  283. proc newDeepCopyCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  284. result = newAsgnStmt(x, newOpCall(c, op, y))
  285. proc newDupCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  286. result = newAsgnStmt(x, newOpCall(c, op, y))
  287. proc usesBuiltinArc(t: PType): bool =
  288. proc wrap(t: PType): bool {.nimcall.} = ast.isGCedMem(t)
  289. result = types.searchTypeFor(t, wrap)
  290. proc useNoGc(c: TLiftCtx; t: PType): bool {.inline.} =
  291. result = optSeqDestructors in c.g.config.globalOptions and
  292. ({tfHasGCedMem, tfHasOwned} * t.flags != {} or usesBuiltinArc(t))
  293. proc requiresDestructor(c: TLiftCtx; t: PType): bool {.inline.} =
  294. result = optSeqDestructors in c.g.config.globalOptions and
  295. containsGarbageCollectedRef(t)
  296. proc instantiateGeneric(c: var TLiftCtx; op: PSym; t, typeInst: PType): PSym =
  297. if c.c != nil and typeInst != nil:
  298. result = c.c.instTypeBoundOp(c.c, op, typeInst, c.info, attachedAsgn, 1)
  299. else:
  300. localError(c.g.config, c.info,
  301. "cannot generate destructor for generic type: " & typeToString(t))
  302. result = nil
  303. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  304. field: var PSym): bool =
  305. if optSeqDestructors in c.g.config.globalOptions:
  306. var op = field
  307. let destructorOverridden = destructorOverridden(c.g, t)
  308. if op != nil and op != c.fn and
  309. (sfOverridden in op.flags or destructorOverridden):
  310. if sfError in op.flags:
  311. incl c.fn.flags, sfError
  312. #else:
  313. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  314. onUse(c.info, op)
  315. body.add newHookCall(c, op, x, y)
  316. result = true
  317. elif op == nil and destructorOverridden:
  318. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  319. body.add newHookCall(c, op, x, y)
  320. result = true
  321. else:
  322. result = false
  323. elif tfHasAsgn in t.flags:
  324. var op: PSym
  325. if sameType(t, c.asgnForType):
  326. # generate recursive call:
  327. if c.recurse:
  328. op = c.fn
  329. else:
  330. c.recurse = true
  331. return false
  332. else:
  333. op = field
  334. if op == nil:
  335. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  336. if sfError in op.flags:
  337. incl c.fn.flags, sfError
  338. #else:
  339. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  340. onUse(c.info, op)
  341. # We also now do generic instantiations in the destructor lifting pass:
  342. if op.ast.isGenericRoutine:
  343. op = instantiateGeneric(c, op, t, t.typeInst)
  344. field = op
  345. #echo "trying to use ", op.ast
  346. #echo "for ", op.name.s, " "
  347. #debug(t)
  348. #return false
  349. assert op.ast[genericParamsPos].kind == nkEmpty
  350. body.add newHookCall(c, op, x, y)
  351. result = true
  352. else:
  353. result = false
  354. proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) =
  355. let t = orig.skipTypes(abstractInst - {tyDistinct})
  356. var op = t.destructor
  357. if op != nil and sfOverridden in op.flags:
  358. if op.ast.isGenericRoutine:
  359. # patch generic destructor:
  360. op = instantiateGeneric(c, op, t, t.typeInst)
  361. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  362. if op == nil and (useNoGc(c, t) or requiresDestructor(c, t)):
  363. op = produceSym(c.g, c.c, t, attachedDestructor, c.info, c.idgen)
  364. doAssert op != nil
  365. doAssert op == t.destructor
  366. if op != nil:
  367. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  368. onUse(c.info, op)
  369. body.add destructorCall(c, op, x)
  370. elif useNoGc(c, t):
  371. internalError(c.g.config, c.info,
  372. "type-bound operator could not be resolved")
  373. proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  374. case c.kind
  375. of attachedDestructor:
  376. var op = t.destructor
  377. if op != nil and sfOverridden in op.flags:
  378. if op.ast.isGenericRoutine:
  379. # patch generic destructor:
  380. op = instantiateGeneric(c, op, t, t.typeInst)
  381. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  382. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  383. onUse(c.info, op)
  384. body.add destructorCall(c, op, x)
  385. result = true
  386. else:
  387. result = false
  388. #result = addDestructorCall(c, t, body, x)
  389. of attachedAsgn, attachedSink, attachedTrace:
  390. var op = getAttachedOp(c.g, t, c.kind)
  391. if op != nil and sfOverridden in op.flags:
  392. if op.ast.isGenericRoutine:
  393. # patch generic =trace:
  394. op = instantiateGeneric(c, op, t, t.typeInst)
  395. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  396. result = considerAsgnOrSink(c, t, body, x, y, op)
  397. if op != nil:
  398. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  399. of attachedDeepCopy:
  400. let op = getAttachedOp(c.g, t, attachedDeepCopy)
  401. if op != nil:
  402. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  403. onUse(c.info, op)
  404. body.add newDeepCopyCall(c, op, x, y)
  405. result = true
  406. else:
  407. result = false
  408. of attachedWasMoved:
  409. var op = getAttachedOp(c.g, t, attachedWasMoved)
  410. if op != nil and sfOverridden in op.flags:
  411. if op.ast.isGenericRoutine:
  412. # patch generic destructor:
  413. op = instantiateGeneric(c, op, t, t.typeInst)
  414. setAttachedOp(c.g, c.idgen.module, t, attachedWasMoved, op)
  415. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  416. onUse(c.info, op)
  417. body.add genWasMovedCall(c, op, x)
  418. result = true
  419. else:
  420. result = false
  421. of attachedDup:
  422. var op = getAttachedOp(c.g, t, attachedDup)
  423. if op != nil and sfOverridden in op.flags:
  424. if op.ast.isGenericRoutine:
  425. # patch generic destructor:
  426. op = instantiateGeneric(c, op, t, t.typeInst)
  427. setAttachedOp(c.g, c.idgen.module, t, attachedDup, op)
  428. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  429. onUse(c.info, op)
  430. body.add newDupCall(c, op, x, y)
  431. result = true
  432. else:
  433. result = false
  434. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  435. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  436. temp.typ = getSysType(c.g, body.info, tyInt)
  437. incl(temp.flags, sfFromGeneric)
  438. var v = newNodeI(nkVarSection, c.info)
  439. result = newSymNode(temp)
  440. v.addVar(result, lowerings.newIntLit(c.g, body.info, first))
  441. body.add v
  442. proc declareTempOf(c: var TLiftCtx; body: PNode; value: PNode): PNode =
  443. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  444. temp.typ = value.typ
  445. incl(temp.flags, sfFromGeneric)
  446. var v = newNodeI(nkVarSection, c.info)
  447. result = newSymNode(temp)
  448. v.addVar(result, value)
  449. body.add v
  450. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  451. let incCall = genBuiltin(c, mInc, "inc", i)
  452. incCall.add lowerings.newIntLit(c.g, c.info, 1)
  453. body.add incCall
  454. proc newSeqCall(c: var TLiftCtx; x, y: PNode): PNode =
  455. # don't call genAddr(c, x) here:
  456. result = genBuiltin(c, mNewSeq, "newSeq", x)
  457. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  458. lenCall.typ = getSysType(c.g, x.info, tyInt)
  459. result.add lenCall
  460. proc setLenStrCall(c: var TLiftCtx; x, y: PNode): PNode =
  461. let lenCall = genBuiltin(c, mLengthStr, "len", y)
  462. lenCall.typ = getSysType(c.g, x.info, tyInt)
  463. result = genBuiltin(c, mSetLengthStr, "setLen", x) # genAddr(g, x))
  464. result.add lenCall
  465. proc setLenSeqCall(c: var TLiftCtx; t: PType; x, y: PNode): PNode =
  466. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  467. lenCall.typ = getSysType(c.g, x.info, tyInt)
  468. var op = getSysMagic(c.g, x.info, "setLen", mSetLengthSeq)
  469. op = instantiateGeneric(c, op, t, t)
  470. result = newTree(nkCall, newSymNode(op, x.info), x, lenCall)
  471. proc forallElements(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  472. let counterIdx = body.len
  473. let i = declareCounter(c, body, toInt64(firstOrd(c.g.config, t)))
  474. let whileLoop = genWhileLoop(c, i, x)
  475. let elemType = t.lastSon
  476. let b = if c.kind == attachedTrace: y else: y.at(i, elemType)
  477. fillBody(c, elemType, whileLoop[1], x.at(i, elemType), b)
  478. if whileLoop[1].len > 0:
  479. addIncStmt(c, whileLoop[1], i)
  480. body.add whileLoop
  481. else:
  482. body.sons.setLen counterIdx
  483. proc checkSelfAssignment(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  484. var cond = callCodegenProc(c.g, "sameSeqPayload", c.info,
  485. newTreeIT(nkAddr, c.info, makePtrType(c.fn, x.typ, c.idgen), x),
  486. newTreeIT(nkAddr, c.info, makePtrType(c.fn, y.typ, c.idgen), y)
  487. )
  488. cond.typ = getSysType(c.g, c.info, tyBool)
  489. body.add genIf(c, cond, newTreeI(nkReturnStmt, c.info, newNodeI(nkEmpty, c.info)))
  490. proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  491. case c.kind
  492. of attachedDup:
  493. body.add setLenSeqCall(c, t, x, y)
  494. forallElements(c, t, body, x, y)
  495. of attachedAsgn, attachedDeepCopy:
  496. # we generate:
  497. # if x.p == y.p:
  498. # return
  499. # setLen(dest, y.len)
  500. # var i = 0
  501. # while i < y.len: dest[i] = y[i]; inc(i)
  502. # This is usually more efficient than a destroy/create pair.
  503. checkSelfAssignment(c, t, body, x, y)
  504. body.add setLenSeqCall(c, t, x, y)
  505. forallElements(c, t, body, x, y)
  506. of attachedSink:
  507. let moveCall = genBuiltin(c, mMove, "move", x)
  508. moveCall.add y
  509. doAssert t.destructor != nil
  510. moveCall.add destructorCall(c, t.destructor, x)
  511. body.add moveCall
  512. of attachedDestructor:
  513. # destroy all elements:
  514. forallElements(c, t, body, x, y)
  515. body.add genBuiltin(c, mDestroy, "destroy", x)
  516. of attachedTrace:
  517. if canFormAcycle(c.g, t.elemType):
  518. # follow all elements:
  519. forallElements(c, t, body, x, y)
  520. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  521. proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  522. createTypeBoundOps(c.g, c.c, t, body.info, c.idgen)
  523. # recursions are tricky, so we might need to forward the generated
  524. # operation here:
  525. var t = t
  526. if t.assignment == nil or t.destructor == nil or t.dup == nil:
  527. let h = sighashes.hashType(t,c.g.config, {CoType, CoConsiderOwned, CoDistinct})
  528. let canon = c.g.canonTypes.getOrDefault(h)
  529. if canon != nil: t = canon
  530. case c.kind
  531. of attachedAsgn, attachedDeepCopy:
  532. # XXX: replace these with assertions.
  533. if t.assignment == nil:
  534. return # protect from recursion
  535. body.add newHookCall(c, t.assignment, x, y)
  536. of attachedSink:
  537. # we always inline the move for better performance:
  538. let moveCall = genBuiltin(c, mMove, "move", x)
  539. moveCall.add y
  540. doAssert t.destructor != nil
  541. moveCall.add destructorCall(c, t.destructor, x)
  542. body.add moveCall
  543. # alternatively we could do this:
  544. when false:
  545. doAssert t.asink != nil
  546. body.add newHookCall(c, t.asink, x, y)
  547. of attachedDestructor:
  548. doAssert t.destructor != nil
  549. body.add destructorCall(c, t.destructor, x)
  550. of attachedTrace:
  551. if t.kind != tyString and canFormAcycle(c.g, t.elemType):
  552. let op = getAttachedOp(c.g, t, c.kind)
  553. if op == nil:
  554. return # protect from recursion
  555. body.add newHookCall(c, op, x, y)
  556. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  557. of attachedDup:
  558. # XXX: replace these with assertions.
  559. let op = getAttachedOp(c.g, t, c.kind)
  560. if op == nil:
  561. return # protect from recursion
  562. body.add newDupCall(c, op, x, y)
  563. proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  564. case c.kind
  565. of attachedAsgn, attachedDeepCopy, attachedDup:
  566. body.add callCodegenProc(c.g, "nimAsgnStrV2", c.info, genAddr(c, x), y)
  567. of attachedSink:
  568. let moveCall = genBuiltin(c, mMove, "move", x)
  569. moveCall.add y
  570. doAssert t.destructor != nil
  571. moveCall.add destructorCall(c, t.destructor, x)
  572. body.add moveCall
  573. of attachedDestructor:
  574. body.add genBuiltin(c, mDestroy, "destroy", x)
  575. of attachedTrace:
  576. discard "strings are atomic and have no inner elements that are to trace"
  577. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  578. proc cyclicType*(g: ModuleGraph, t: PType): bool =
  579. case t.kind
  580. of tyRef: result = types.canFormAcycle(g, t.lastSon)
  581. of tyProc: result = t.callConv == ccClosure
  582. else: result = false
  583. proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  584. #[ bug #15753 is really subtle. Usually the classical write barrier for reference
  585. counting looks like this::
  586. incRef source # increment first; this takes care of self-assignments1
  587. decRef dest
  588. dest[] = source
  589. However, 'decRef dest' might trigger a cycle collection and then the collector
  590. traverses the graph. It is crucial that when it follows the pointers the assignment
  591. 'dest[] = source' already happened so that we don't do trial deletion on a wrong
  592. graph -- this causes premature freeing of objects! The correct barrier looks like
  593. this::
  594. let tmp = dest
  595. incRef source
  596. dest[] = source
  597. decRef tmp
  598. ]#
  599. var actions = newNodeI(nkStmtList, c.info)
  600. let elemType = t.lastSon
  601. createTypeBoundOps(c.g, c.c, elemType, c.info, c.idgen)
  602. let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(c.g, elemType)
  603. let isInheritableAcyclicRef = c.g.config.selectedGC == gcOrc and
  604. (not isPureObject(elemType)) and
  605. tfAcyclic in skipTypes(elemType, abstractInst+{tyOwned}-{tyTypeDesc}).flags
  606. # dynamic Acyclic refs need to use dyn decRef
  607. let tmp =
  608. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  609. declareTempOf(c, body, x)
  610. else:
  611. x
  612. if isFinal(elemType):
  613. addDestructorCall(c, elemType, actions, genDeref(tmp, nkDerefExpr))
  614. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  615. alignOf.typ = getSysType(c.g, c.info, tyInt)
  616. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, tmp, alignOf)
  617. else:
  618. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(tmp, nkDerefExpr))
  619. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  620. var cond: PNode
  621. if isCyclic:
  622. if isFinal(elemType):
  623. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  624. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  625. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
  626. else:
  627. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
  628. elif isInheritableAcyclicRef:
  629. cond = callCodegenProc(c.g, "nimDecRefIsLastDyn", c.info, x)
  630. else:
  631. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  632. cond.typ = getSysType(c.g, x.info, tyBool)
  633. case c.kind
  634. of attachedSink:
  635. if isCyclic:
  636. body.add newAsgnStmt(x, y)
  637. body.add genIf(c, cond, actions)
  638. else:
  639. body.add genIf(c, cond, actions)
  640. body.add newAsgnStmt(x, y)
  641. of attachedAsgn:
  642. if isCyclic:
  643. body.add genIf(c, y, callCodegenProc(c.g,
  644. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  645. body.add newAsgnStmt(x, y)
  646. body.add genIf(c, cond, actions)
  647. else:
  648. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  649. body.add genIf(c, cond, actions)
  650. body.add newAsgnStmt(x, y)
  651. of attachedDestructor:
  652. body.add genIf(c, cond, actions)
  653. of attachedDeepCopy: assert(false, "cannot happen")
  654. of attachedTrace:
  655. if isCyclic:
  656. if isFinal(elemType):
  657. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  658. typInfo.typ = getSysType(c.g, c.info, tyPointer)
  659. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x, c.idgen), typInfo, y)
  660. else:
  661. # If the ref is polymorphic we have to account for this
  662. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
  663. #echo "can follow ", elemType, " static ", isFinal(elemType)
  664. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  665. of attachedDup:
  666. if isCyclic:
  667. body.add newAsgnStmt(x, y)
  668. body.add genIf(c, y, callCodegenProc(c.g,
  669. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  670. else:
  671. body.add newAsgnStmt(x, y)
  672. body.add genIf(c, y, callCodegenProc(c.g,
  673. "nimIncRef", c.info, y))
  674. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  675. ## Closures are really like refs except they always use a virtual destructor
  676. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  677. let xenv = genBuiltin(c, mAccessEnv, "accessEnv", x)
  678. xenv.typ = getSysType(c.g, c.info, tyPointer)
  679. let isCyclic = c.g.config.selectedGC == gcOrc
  680. let tmp =
  681. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  682. declareTempOf(c, body, xenv)
  683. else:
  684. xenv
  685. var actions = newNodeI(nkStmtList, c.info)
  686. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  687. let decRefProc =
  688. if isCyclic: "nimDecRefIsLastCyclicDyn"
  689. else: "nimDecRefIsLast"
  690. let cond = callCodegenProc(c.g, decRefProc, c.info, tmp)
  691. cond.typ = getSysType(c.g, x.info, tyBool)
  692. case c.kind
  693. of attachedSink:
  694. if isCyclic:
  695. body.add newAsgnStmt(x, y)
  696. body.add genIf(c, cond, actions)
  697. else:
  698. body.add genIf(c, cond, actions)
  699. body.add newAsgnStmt(x, y)
  700. of attachedAsgn:
  701. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  702. yenv.typ = getSysType(c.g, c.info, tyPointer)
  703. if isCyclic:
  704. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  705. body.add newAsgnStmt(x, y)
  706. body.add genIf(c, cond, actions)
  707. else:
  708. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  709. body.add genIf(c, cond, actions)
  710. body.add newAsgnStmt(x, y)
  711. of attachedDup:
  712. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  713. yenv.typ = getSysType(c.g, c.info, tyPointer)
  714. if isCyclic:
  715. body.add newAsgnStmt(x, y)
  716. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  717. else:
  718. body.add newAsgnStmt(x, y)
  719. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  720. of attachedDestructor:
  721. body.add genIf(c, cond, actions)
  722. of attachedDeepCopy: assert(false, "cannot happen")
  723. of attachedTrace:
  724. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
  725. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  726. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  727. case c.kind
  728. of attachedSink:
  729. # we 'nil' y out afterwards so we *need* to take over its reference
  730. # count value:
  731. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  732. body.add newAsgnStmt(x, y)
  733. of attachedAsgn:
  734. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  735. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  736. body.add newAsgnStmt(x, y)
  737. of attachedDup:
  738. body.add newAsgnStmt(x, y)
  739. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  740. of attachedDestructor:
  741. # it's better to prepend the destruction of weak refs in order to
  742. # prevent wrong "dangling refs exist" problems:
  743. var actions = newNodeI(nkStmtList, c.info)
  744. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  745. let des = genIf(c, x, actions)
  746. if body.len == 0:
  747. body.add des
  748. else:
  749. body.sons.insert(des, 0)
  750. of attachedDeepCopy: assert(false, "cannot happen")
  751. of attachedTrace: discard
  752. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  753. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  754. var actions = newNodeI(nkStmtList, c.info)
  755. let elemType = t.lastSon
  756. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  757. #var disposeCall = genBuiltin(c, mDispose, "dispose", x)
  758. if isFinal(elemType):
  759. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  760. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  761. alignOf.typ = getSysType(c.g, c.info, tyInt)
  762. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x, alignOf)
  763. else:
  764. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  765. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  766. case c.kind
  767. of attachedSink, attachedAsgn:
  768. body.add genIf(c, x, actions)
  769. body.add newAsgnStmt(x, y)
  770. of attachedDup:
  771. body.add newAsgnStmt(x, y)
  772. of attachedDestructor:
  773. body.add genIf(c, x, actions)
  774. of attachedDeepCopy: assert(false, "cannot happen")
  775. of attachedTrace: discard
  776. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  777. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  778. if c.kind == attachedDeepCopy:
  779. # a big problem is that we don't know the environment's type here, so we
  780. # have to go through some indirection; we delegate this to the codegen:
  781. let call = newNodeI(nkCall, c.info, 2)
  782. call.typ = t
  783. call[0] = newSymNode(createMagic(c.g, c.idgen, "deepCopy", mDeepCopy))
  784. call[1] = y
  785. body.add newAsgnStmt(x, call)
  786. elif (optOwnedRefs in c.g.config.globalOptions and
  787. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  788. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  789. xx.typ = getSysType(c.g, c.info, tyPointer)
  790. case c.kind
  791. of attachedSink:
  792. # we 'nil' y out afterwards so we *need* to take over its reference
  793. # count value:
  794. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  795. body.add newAsgnStmt(x, y)
  796. of attachedAsgn:
  797. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  798. yy.typ = getSysType(c.g, c.info, tyPointer)
  799. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  800. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  801. body.add newAsgnStmt(x, y)
  802. of attachedDup:
  803. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  804. yy.typ = getSysType(c.g, c.info, tyPointer)
  805. body.add newAsgnStmt(x, y)
  806. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  807. of attachedDestructor:
  808. let des = genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  809. if body.len == 0:
  810. body.add des
  811. else:
  812. body.sons.insert(des, 0)
  813. of attachedDeepCopy: assert(false, "cannot happen")
  814. of attachedTrace: discard
  815. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  816. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  817. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  818. xx.typ = getSysType(c.g, c.info, tyPointer)
  819. var actions = newNodeI(nkStmtList, c.info)
  820. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  821. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  822. case c.kind
  823. of attachedSink, attachedAsgn:
  824. body.add genIf(c, xx, actions)
  825. body.add newAsgnStmt(x, y)
  826. of attachedDup:
  827. body.add newAsgnStmt(x, y)
  828. of attachedDestructor:
  829. body.add genIf(c, xx, actions)
  830. of attachedDeepCopy: assert(false, "cannot happen")
  831. of attachedTrace: discard
  832. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  833. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  834. case t.kind
  835. of tyNone, tyEmpty, tyVoid: discard
  836. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCstring,
  837. tyPtr, tyUncheckedArray, tyVar, tyLent:
  838. defaultOp(c, t, body, x, y)
  839. of tyRef:
  840. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  841. atomicRefOp(c, t, body, x, y)
  842. elif (optOwnedRefs in c.g.config.globalOptions and
  843. optRefCheck in c.g.config.options):
  844. weakrefOp(c, t, body, x, y)
  845. else:
  846. defaultOp(c, t, body, x, y)
  847. of tyProc:
  848. if t.callConv == ccClosure:
  849. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  850. atomicClosureOp(c, t, body, x, y)
  851. else:
  852. closureOp(c, t, body, x, y)
  853. else:
  854. defaultOp(c, t, body, x, y)
  855. of tyOwned:
  856. let base = t.skipTypes(abstractInstOwned)
  857. if optOwnedRefs in c.g.config.globalOptions:
  858. case base.kind
  859. of tyRef:
  860. ownedRefOp(c, base, body, x, y)
  861. return
  862. of tyProc:
  863. if base.callConv == ccClosure:
  864. ownedClosureOp(c, base, body, x, y)
  865. return
  866. else: discard
  867. defaultOp(c, base, body, x, y)
  868. of tyArray:
  869. if tfHasAsgn in t.flags or useNoGc(c, t):
  870. forallElements(c, t, body, x, y)
  871. else:
  872. defaultOp(c, t, body, x, y)
  873. of tySequence:
  874. if useNoGc(c, t):
  875. useSeqOrStrOp(c, t, body, x, y)
  876. elif optSeqDestructors in c.g.config.globalOptions:
  877. # note that tfHasAsgn is propagated so we need the check on
  878. # 'selectedGC' here to determine if we have the new runtime.
  879. discard considerUserDefinedOp(c, t, body, x, y)
  880. elif tfHasAsgn in t.flags:
  881. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  882. body.add newSeqCall(c, x, y)
  883. forallElements(c, t, body, x, y)
  884. else:
  885. defaultOp(c, t, body, x, y)
  886. of tyString:
  887. if useNoGc(c, t):
  888. useSeqOrStrOp(c, t, body, x, y)
  889. elif tfHasAsgn in t.flags:
  890. discard considerUserDefinedOp(c, t, body, x, y)
  891. else:
  892. defaultOp(c, t, body, x, y)
  893. of tyObject:
  894. if not considerUserDefinedOp(c, t, body, x, y):
  895. if t.sym != nil and sfImportc in t.sym.flags:
  896. case c.kind
  897. of {attachedAsgn, attachedSink, attachedDup}:
  898. body.add newAsgnStmt(x, y)
  899. of attachedWasMoved:
  900. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  901. else:
  902. fillBodyObjT(c, t, body, x, y)
  903. else:
  904. if c.kind == attachedDup:
  905. var op2 = getAttachedOp(c.g, t, attachedAsgn)
  906. if op2 != nil and sfOverridden in op2.flags:
  907. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  908. onUse(c.info, op2)
  909. body.add newHookCall(c, t.assignment, x, y)
  910. else:
  911. fillBodyObjT(c, t, body, x, y)
  912. else:
  913. fillBodyObjT(c, t, body, x, y)
  914. of tyDistinct:
  915. if not considerUserDefinedOp(c, t, body, x, y):
  916. fillBody(c, t[0], body, x, y)
  917. of tyTuple:
  918. fillBodyTup(c, t, body, x, y)
  919. of tyVarargs, tyOpenArray:
  920. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  921. forallElements(c, t, body, x, y)
  922. else:
  923. discard "cannot copy openArray"
  924. of tyFromExpr, tyProxy, tyBuiltInTypeClass, tyUserTypeClass,
  925. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  926. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  927. tyTypeDesc, tyGenericInvocation, tyForward, tyStatic:
  928. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  929. discard
  930. of tyOrdinal, tyRange, tyInferred,
  931. tyGenericInst, tyAlias, tySink:
  932. fillBody(c, lastSon(t), body, x, y)
  933. of tyConcept, tyIterable: raiseAssert "unreachable"
  934. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  935. kind: TTypeAttachedOp; info: TLineInfo;
  936. idgen: IdGenerator): PSym =
  937. assert typ.kind == tyDistinct
  938. let baseType = typ[0]
  939. if getAttachedOp(g, baseType, kind) == nil:
  940. discard produceSym(g, c, baseType, kind, info, idgen)
  941. result = getAttachedOp(g, baseType, kind)
  942. setAttachedOp(g, idgen.module, typ, kind, result)
  943. proc symDupPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  944. info: TLineInfo; idgen: IdGenerator): PSym =
  945. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  946. result = newSym(skProc, procname, idgen, owner, info)
  947. let res = newSym(skResult, getIdent(g.cache, "result"), idgen, result, info)
  948. let src = newSym(skParam, getIdent(g.cache, "src"),
  949. idgen, result, info)
  950. res.typ = typ
  951. src.typ = typ
  952. result.typ = newType(tyProc, idgen, owner)
  953. result.typ.n = newNodeI(nkFormalParams, info)
  954. rawAddSon(result.typ, res.typ)
  955. result.typ.n.add newNodeI(nkEffectList, info)
  956. result.typ.addParam src
  957. if g.config.selectedGC == gcOrc and
  958. cyclicType(g, typ.skipTypes(abstractInst)):
  959. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  960. idgen, result, info)
  961. cycleParam.typ = getSysType(g, info, tyBool)
  962. result.typ.addParam cycleParam
  963. var n = newNodeI(nkProcDef, info, bodyPos+2)
  964. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  965. n[namePos] = newSymNode(result)
  966. n[paramsPos] = result.typ.n
  967. n[bodyPos] = newNodeI(nkStmtList, info)
  968. n[resultPos] = newSymNode(res)
  969. result.ast = n
  970. incl result.flags, sfFromGeneric
  971. incl result.flags, sfGeneratedOp
  972. proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  973. info: TLineInfo; idgen: IdGenerator): PSym =
  974. if kind == attachedDup:
  975. return symDupPrototype(g, typ, owner, kind, info, idgen)
  976. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  977. result = newSym(skProc, procname, idgen, owner, info)
  978. let dest = newSym(skParam, getIdent(g.cache, "dest"), idgen, result, info)
  979. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"),
  980. idgen, result, info)
  981. if kind == attachedDestructor and typ.kind in {tyRef, tyString, tySequence} and g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  982. dest.typ = typ
  983. else:
  984. dest.typ = makeVarType(typ.owner, typ, idgen)
  985. if kind == attachedTrace:
  986. src.typ = getSysType(g, info, tyPointer)
  987. else:
  988. src.typ = typ
  989. result.typ = newProcType(info, idgen, owner)
  990. result.typ.addParam dest
  991. if kind notin {attachedDestructor, attachedWasMoved}:
  992. result.typ.addParam src
  993. if kind == attachedAsgn and g.config.selectedGC == gcOrc and
  994. cyclicType(g, typ.skipTypes(abstractInst)):
  995. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  996. idgen, result, info)
  997. cycleParam.typ = getSysType(g, info, tyBool)
  998. result.typ.addParam cycleParam
  999. var n = newNodeI(nkProcDef, info, bodyPos+1)
  1000. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  1001. n[namePos] = newSymNode(result)
  1002. n[paramsPos] = result.typ.n
  1003. n[bodyPos] = newNodeI(nkStmtList, info)
  1004. result.ast = n
  1005. incl result.flags, sfFromGeneric
  1006. incl result.flags, sfGeneratedOp
  1007. if kind == attachedWasMoved:
  1008. incl result.flags, sfNoSideEffect
  1009. incl result.typ.flags, tfNoSideEffect
  1010. proc genTypeFieldCopy(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  1011. let xx = genBuiltin(c, mAccessTypeField, "accessTypeField", x)
  1012. let yy = genBuiltin(c, mAccessTypeField, "accessTypeField", y)
  1013. xx.typ = getSysType(c.g, c.info, tyPointer)
  1014. yy.typ = xx.typ
  1015. body.add newAsgnStmt(xx, yy)
  1016. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  1017. info: TLineInfo; idgen: IdGenerator): PSym =
  1018. if typ.kind == tyDistinct:
  1019. return produceSymDistinctType(g, c, typ, kind, info, idgen)
  1020. result = getAttachedOp(g, typ, kind)
  1021. if result == nil:
  1022. result = symPrototype(g, typ, typ.owner, kind, info, idgen)
  1023. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType: typ, idgen: idgen,
  1024. fn: result)
  1025. let dest = if kind == attachedDup: result.ast[resultPos].sym else: result.typ.n[1].sym
  1026. let d = if result.typ[1].kind == tyVar: newDeref(newSymNode(dest)) else: newSymNode(dest)
  1027. let src = case kind
  1028. of {attachedDestructor, attachedWasMoved}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1029. of attachedDup: newSymNode(result.typ.n[1].sym)
  1030. else: newSymNode(result.typ.n[2].sym)
  1031. # register this operation already:
  1032. setAttachedOpPartial(g, idgen.module, typ, kind, result)
  1033. if kind == attachedSink and destructorOverridden(g, typ):
  1034. ## compiler can use a combination of `=destroy` and memCopy for sink op
  1035. dest.flags.incl sfCursor
  1036. let op = getAttachedOp(g, typ, attachedDestructor)
  1037. result.ast[bodyPos].add newOpCall(a, op, if op.typ[1].kind == tyVar: d[0] else: d)
  1038. result.ast[bodyPos].add newAsgnStmt(d, src)
  1039. else:
  1040. var tk: TTypeKind
  1041. if g.config.selectedGC in {gcArc, gcOrc, gcHooks, gcAtomicArc}:
  1042. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  1043. else:
  1044. tk = tyNone # no special casing for strings and seqs
  1045. case tk
  1046. of tySequence:
  1047. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  1048. of tyString:
  1049. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  1050. else:
  1051. fillBody(a, typ, result.ast[bodyPos], d, src)
  1052. if tk == tyObject and a.kind in {attachedAsgn, attachedSink, attachedDeepCopy, attachedDup} and not lacksMTypeField(typ):
  1053. # bug #19205: Do not forget to also copy the hidden type field:
  1054. genTypeFieldCopy(a, typ, result.ast[bodyPos], d, src)
  1055. if not a.canRaise: incl result.flags, sfNeverRaises
  1056. completePartialOp(g, idgen.module, typ, kind, result)
  1057. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym,
  1058. info: TLineInfo; idgen: IdGenerator): PSym =
  1059. assert(typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject)
  1060. result = symPrototype(g, field.typ, typ.owner, attachedDestructor, info, idgen)
  1061. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ, idgen: idgen,
  1062. fn: result)
  1063. a.asgnForType = typ
  1064. a.filterDiscriminator = field
  1065. a.addMemReset = true
  1066. let discrimantDest = result.typ.n[1].sym
  1067. let dst = newSym(skVar, getIdent(g.cache, "dest"), idgen, result, info)
  1068. dst.typ = makePtrType(typ.owner, typ, idgen)
  1069. let dstSym = newSymNode(dst)
  1070. let d = newDeref(dstSym)
  1071. let v = newNodeI(nkVarSection, info)
  1072. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  1073. result.ast[bodyPos].add v
  1074. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1075. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  1076. if not a.canRaise: incl result.flags, sfNeverRaises
  1077. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  1078. discard "now a nop"
  1079. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo; idgen: IdGenerator) =
  1080. if n.kind in nkCallKinds:
  1081. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  1082. let t = n[1].typ.skipTypes(abstractVar)
  1083. if getAttachedOp(g, t, attachedDestructor) == nil:
  1084. discard produceSym(g, c, t, attachedDestructor, info, idgen)
  1085. let op = getAttachedOp(g, t, attachedDestructor)
  1086. if op != nil:
  1087. if op.ast.isGenericRoutine:
  1088. internalError(g.config, info, "resolved destructor is generic")
  1089. if op.magic == mDestroy and t.kind != tyString:
  1090. internalError(g.config, info, "patching mDestroy with mDestroy?")
  1091. n[0] = newSymNode(op)
  1092. for x in n: patchBody(g, c, x, info, idgen)
  1093. proc inst(g: ModuleGraph; c: PContext; t: PType; kind: TTypeAttachedOp; idgen: IdGenerator;
  1094. info: TLineInfo) =
  1095. let op = getAttachedOp(g, t, kind)
  1096. if op != nil and op.ast != nil and op.ast.isGenericRoutine:
  1097. if t.typeInst != nil:
  1098. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, idgen: idgen)
  1099. let opInst = instantiateGeneric(a, op, t, t.typeInst)
  1100. if opInst.ast != nil:
  1101. patchBody(g, c, opInst.ast, info, a.idgen)
  1102. setAttachedOp(g, idgen.module, t, kind, opInst)
  1103. else:
  1104. localError(g.config, info, "unresolved generic parameter")
  1105. proc isTrival(s: PSym): bool {.inline.} =
  1106. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  1107. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  1108. idgen: IdGenerator) =
  1109. ## In the semantic pass this is called in strategic places
  1110. ## to ensure we lift assignment, destructors and moves properly.
  1111. ## The later 'injectdestructors' pass depends on it.
  1112. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  1113. incl orig.flags, tfCheckedForDestructor
  1114. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  1115. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  1116. let h = sighashes.hashType(skipped, g.config, {CoType, CoConsiderOwned, CoDistinct})
  1117. var canon = g.canonTypes.getOrDefault(h)
  1118. if canon == nil:
  1119. g.canonTypes[h] = skipped
  1120. canon = skipped
  1121. # multiple cases are to distinguish here:
  1122. # 1. we don't know yet if 'typ' has a nontrival destructor.
  1123. # 2. we have a nop destructor. --> mDestroy
  1124. # 3. we have a lifted destructor.
  1125. # 4. We have a custom destructor.
  1126. # 5. We have a (custom) generic destructor.
  1127. # we do not generate '=trace' procs if we
  1128. # have the cycle detection disabled, saves code size.
  1129. let lastAttached = if g.config.selectedGC == gcOrc: attachedTrace
  1130. else: attachedSink
  1131. # bug #15122: We need to produce all prototypes before entering the
  1132. # mind boggling recursion. Hacks like these imply we should rewrite
  1133. # this module.
  1134. var generics: array[attachedWasMoved..attachedTrace, bool] = default(array[attachedWasMoved..attachedTrace, bool])
  1135. for k in attachedWasMoved..lastAttached:
  1136. generics[k] = getAttachedOp(g, canon, k) != nil
  1137. if not generics[k]:
  1138. setAttachedOp(g, idgen.module, canon, k,
  1139. symPrototype(g, canon, canon.owner, k, info, idgen))
  1140. # we generate the destructor first so that other operators can depend on it:
  1141. for k in attachedWasMoved..lastAttached:
  1142. if not generics[k]:
  1143. discard produceSym(g, c, canon, k, info, idgen)
  1144. else:
  1145. inst(g, c, canon, k, idgen, info)
  1146. if canon != orig:
  1147. setAttachedOp(g, idgen.module, orig, k, getAttachedOp(g, canon, k))
  1148. if not isTrival(getAttachedOp(g, orig, attachedDestructor)):
  1149. #or not isTrival(orig.assignment) or
  1150. # not isTrival(orig.sink):
  1151. orig.flags.incl tfHasAsgn
  1152. # ^ XXX Breaks IC!