lowerings.nim 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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 common simple lowerings.
  10. const
  11. genPrefix* = ":tmp" # prefix for generated names
  12. import ast, astalgo, types, idents, magicsys, msgs, options, modulegraphs,
  13. lineinfos
  14. from trees import getMagic
  15. proc newDeref*(n: PNode): PNode {.inline.} =
  16. result = newNodeIT(nkHiddenDeref, n.info, n.typ.sons[0])
  17. addSon(result, n)
  18. proc newTupleAccess*(g: ModuleGraph; tup: PNode, i: int): PNode =
  19. result = newNodeIT(nkBracketExpr, tup.info, tup.typ.skipTypes(
  20. abstractInst).sons[i])
  21. addSon(result, copyTree(tup))
  22. var lit = newNodeIT(nkIntLit, tup.info, getSysType(g, tup.info, tyInt))
  23. lit.intVal = i
  24. addSon(result, lit)
  25. proc addVar*(father, v: PNode) =
  26. var vpart = newNodeI(nkIdentDefs, v.info, 3)
  27. vpart.sons[0] = v
  28. vpart.sons[1] = newNodeI(nkEmpty, v.info)
  29. vpart.sons[2] = vpart[1]
  30. addSon(father, vpart)
  31. proc newAsgnStmt(le, ri: PNode): PNode =
  32. result = newNodeI(nkAsgn, le.info, 2)
  33. result.sons[0] = le
  34. result.sons[1] = ri
  35. proc newFastAsgnStmt(le, ri: PNode): PNode =
  36. result = newNodeI(nkFastAsgn, le.info, 2)
  37. result.sons[0] = le
  38. result.sons[1] = ri
  39. proc lowerTupleUnpacking*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
  40. assert n.kind == nkVarTuple
  41. let value = n.lastSon
  42. result = newNodeI(nkStmtList, n.info)
  43. var temp = newSym(skTemp, getIdent(g.cache, genPrefix), owner, value.info, g.config.options)
  44. temp.typ = skipTypes(value.typ, abstractInst)
  45. incl(temp.flags, sfFromGeneric)
  46. var v = newNodeI(nkVarSection, value.info)
  47. let tempAsNode = newSymNode(temp)
  48. v.addVar(tempAsNode)
  49. result.add(v)
  50. result.add newAsgnStmt(tempAsNode, value)
  51. for i in 0 .. n.len-3:
  52. if n.sons[i].kind == nkSym: v.addVar(n.sons[i])
  53. result.add newAsgnStmt(n.sons[i], newTupleAccess(g, tempAsNode, i))
  54. proc newTupleAccessRaw*(tup: PNode, i: int): PNode =
  55. result = newNodeI(nkBracketExpr, tup.info)
  56. addSon(result, copyTree(tup))
  57. var lit = newNodeI(nkIntLit, tup.info)
  58. lit.intVal = i
  59. addSon(result, lit)
  60. proc newTryFinally*(body, final: PNode): PNode =
  61. result = newTree(nkTryStmt, body, newTree(nkFinally, final))
  62. proc lowerTupleUnpackingForAsgn*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
  63. let value = n.lastSon
  64. result = newNodeI(nkStmtList, n.info)
  65. var temp = newSym(skLet, getIdent(g.cache, "_"), owner, value.info, owner.options)
  66. var v = newNodeI(nkLetSection, value.info)
  67. let tempAsNode = newSymNode(temp) #newIdentNode(getIdent(genPrefix & $temp.id), value.info)
  68. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  69. vpart.sons[0] = tempAsNode
  70. vpart.sons[1] = newNodeI(nkEmpty, value.info)
  71. vpart.sons[2] = value
  72. addSon(v, vpart)
  73. result.add(v)
  74. let lhs = n.sons[0]
  75. for i in 0 .. lhs.len-1:
  76. result.add newAsgnStmt(lhs.sons[i], newTupleAccessRaw(tempAsNode, i))
  77. proc lowerSwap*(g: ModuleGraph; n: PNode; owner: PSym): PNode =
  78. result = newNodeI(nkStmtList, n.info)
  79. # note: cannot use 'skTemp' here cause we really need the copy for the VM :-(
  80. var temp = newSym(skVar, getIdent(g.cache, genPrefix), owner, n.info, owner.options)
  81. temp.typ = n.sons[1].typ
  82. incl(temp.flags, sfFromGeneric)
  83. var v = newNodeI(nkVarSection, n.info)
  84. let tempAsNode = newSymNode(temp)
  85. var vpart = newNodeI(nkIdentDefs, v.info, 3)
  86. vpart.sons[0] = tempAsNode
  87. vpart.sons[1] = newNodeI(nkEmpty, v.info)
  88. vpart.sons[2] = n[1]
  89. addSon(v, vpart)
  90. result.add(v)
  91. result.add newFastAsgnStmt(n[1], n[2])
  92. result.add newFastAsgnStmt(n[2], tempAsNode)
  93. proc createObj*(g: ModuleGraph; owner: PSym, info: TLineInfo; final=true): PType =
  94. result = newType(tyObject, owner)
  95. if final:
  96. rawAddSon(result, nil)
  97. incl result.flags, tfFinal
  98. else:
  99. rawAddSon(result, getCompilerProc(g, "RootObj").typ)
  100. result.n = newNodeI(nkRecList, info)
  101. let s = newSym(skType, getIdent(g.cache, "Env_" & toFilename(g.config, info)),
  102. owner, info, owner.options)
  103. incl s.flags, sfAnon
  104. s.typ = result
  105. result.sym = s
  106. proc rawAddField*(obj: PType; field: PSym) =
  107. assert field.kind == skField
  108. field.position = sonsLen(obj.n)
  109. addSon(obj.n, newSymNode(field))
  110. proc rawIndirectAccess*(a: PNode; field: PSym; info: TLineInfo): PNode =
  111. # returns a[].field as a node
  112. assert field.kind == skField
  113. var deref = newNodeI(nkHiddenDeref, info)
  114. deref.typ = a.typ.skipTypes(abstractInst).sons[0]
  115. addSon(deref, a)
  116. result = newNodeI(nkDotExpr, info)
  117. addSon(result, deref)
  118. addSon(result, newSymNode(field))
  119. result.typ = field.typ
  120. proc rawDirectAccess*(obj, field: PSym): PNode =
  121. # returns a.field as a node
  122. assert field.kind == skField
  123. result = newNodeI(nkDotExpr, field.info)
  124. addSon(result, newSymNode obj)
  125. addSon(result, newSymNode field)
  126. result.typ = field.typ
  127. proc lookupInRecord(n: PNode, id: int): PSym =
  128. result = nil
  129. case n.kind
  130. of nkRecList:
  131. for i in countup(0, sonsLen(n) - 1):
  132. result = lookupInRecord(n.sons[i], id)
  133. if result != nil: return
  134. of nkRecCase:
  135. if n.sons[0].kind != nkSym: return
  136. result = lookupInRecord(n.sons[0], id)
  137. if result != nil: return
  138. for i in countup(1, sonsLen(n) - 1):
  139. case n.sons[i].kind
  140. of nkOfBranch, nkElse:
  141. result = lookupInRecord(lastSon(n.sons[i]), id)
  142. if result != nil: return
  143. else: discard
  144. of nkSym:
  145. if n.sym.id == -abs(id): result = n.sym
  146. else: discard
  147. proc addField*(obj: PType; s: PSym; cache: IdentCache) =
  148. # because of 'gensym' support, we have to mangle the name with its ID.
  149. # This is hacky but the clean solution is much more complex than it looks.
  150. var field = newSym(skField, getIdent(cache, s.name.s & $obj.n.len), s.owner, s.info,
  151. s.options)
  152. field.id = -s.id
  153. let t = skipIntLit(s.typ)
  154. field.typ = t
  155. assert t.kind != tyStmt
  156. field.position = sonsLen(obj.n)
  157. addSon(obj.n, newSymNode(field))
  158. proc addUniqueField*(obj: PType; s: PSym; cache: IdentCache): PSym {.discardable.} =
  159. result = lookupInRecord(obj.n, s.id)
  160. if result == nil:
  161. var field = newSym(skField, getIdent(cache, s.name.s & $obj.n.len), s.owner, s.info,
  162. s.options)
  163. field.id = -s.id
  164. let t = skipIntLit(s.typ)
  165. field.typ = t
  166. assert t.kind != tyStmt
  167. field.position = sonsLen(obj.n)
  168. addSon(obj.n, newSymNode(field))
  169. result = field
  170. proc newDotExpr(obj, b: PSym): PNode =
  171. result = newNodeI(nkDotExpr, obj.info)
  172. let field = lookupInRecord(obj.typ.n, b.id)
  173. assert field != nil, b.name.s
  174. addSon(result, newSymNode(obj))
  175. addSon(result, newSymNode(field))
  176. result.typ = field.typ
  177. proc indirectAccess*(a: PNode, b: int, info: TLineInfo): PNode =
  178. # returns a[].b as a node
  179. var deref = newNodeI(nkHiddenDeref, info)
  180. deref.typ = a.typ.skipTypes(abstractInst).sons[0]
  181. var t = deref.typ.skipTypes(abstractInst)
  182. var field: PSym
  183. while true:
  184. assert t.kind == tyObject
  185. field = lookupInRecord(t.n, b)
  186. if field != nil: break
  187. t = t.sons[0]
  188. if t == nil: break
  189. t = t.skipTypes(skipPtrs)
  190. #if field == nil:
  191. # echo "FIELD ", b
  192. # debug deref.typ
  193. assert field != nil
  194. addSon(deref, a)
  195. result = newNodeI(nkDotExpr, info)
  196. addSon(result, deref)
  197. addSon(result, newSymNode(field))
  198. result.typ = field.typ
  199. proc indirectAccess(a: PNode, b: string, info: TLineInfo; cache: IdentCache): PNode =
  200. # returns a[].b as a node
  201. var deref = newNodeI(nkHiddenDeref, info)
  202. deref.typ = a.typ.skipTypes(abstractInst).sons[0]
  203. var t = deref.typ.skipTypes(abstractInst)
  204. var field: PSym
  205. let bb = getIdent(cache, b)
  206. while true:
  207. assert t.kind == tyObject
  208. field = getSymFromList(t.n, bb)
  209. if field != nil: break
  210. t = t.sons[0]
  211. if t == nil: break
  212. t = t.skipTypes(skipPtrs)
  213. #if field == nil:
  214. # echo "FIELD ", b
  215. # debug deref.typ
  216. assert field != nil
  217. addSon(deref, a)
  218. result = newNodeI(nkDotExpr, info)
  219. addSon(result, deref)
  220. addSon(result, newSymNode(field))
  221. result.typ = field.typ
  222. proc getFieldFromObj*(t: PType; v: PSym): PSym =
  223. assert v.kind != skField
  224. var t = t
  225. while true:
  226. assert t.kind == tyObject
  227. result = lookupInRecord(t.n, v.id)
  228. if result != nil: break
  229. t = t.sons[0]
  230. if t == nil: break
  231. t = t.skipTypes(skipPtrs)
  232. proc indirectAccess*(a: PNode, b: PSym, info: TLineInfo): PNode =
  233. # returns a[].b as a node
  234. result = indirectAccess(a, b.id, info)
  235. proc indirectAccess*(a, b: PSym, info: TLineInfo): PNode =
  236. result = indirectAccess(newSymNode(a), b, info)
  237. proc genAddrOf*(n: PNode): PNode =
  238. result = newNodeI(nkAddr, n.info, 1)
  239. result.sons[0] = n
  240. result.typ = newType(tyPtr, n.typ.owner)
  241. result.typ.rawAddSon(n.typ)
  242. proc genDeref*(n: PNode): PNode =
  243. result = newNodeIT(nkHiddenDeref, n.info,
  244. n.typ.skipTypes(abstractInst).sons[0])
  245. result.add n
  246. proc callCodegenProc*(g: ModuleGraph; name: string;
  247. info: TLineInfo = unknownLineInfo();
  248. arg1, arg2, arg3, optionalArgs: PNode = nil): PNode =
  249. result = newNodeI(nkCall, info)
  250. let sym = magicsys.getCompilerProc(g, name)
  251. if sym == nil:
  252. localError(g.config, info, "system module needs: " & name)
  253. else:
  254. result.add newSymNode(sym)
  255. if arg1 != nil: result.add arg1
  256. if arg2 != nil: result.add arg2
  257. if arg3 != nil: result.add arg3
  258. if optionalArgs != nil:
  259. for i in 1..optionalArgs.len-3:
  260. result.add optionalArgs[i]
  261. result.typ = sym.typ.sons[0]
  262. proc callProc(a: PNode): PNode =
  263. result = newNodeI(nkCall, a.info)
  264. result.add a
  265. result.typ = a.typ.sons[0]
  266. # we have 4 cases to consider:
  267. # - a void proc --> nothing to do
  268. # - a proc returning GC'ed memory --> requires a flowVar
  269. # - a proc returning non GC'ed memory --> pass as hidden 'var' parameter
  270. # - not in a parallel environment --> requires a flowVar for memory safety
  271. type
  272. TSpawnResult* = enum
  273. srVoid, srFlowVar, srByVar
  274. TFlowVarKind = enum
  275. fvInvalid # invalid type T for 'FlowVar[T]'
  276. fvGC # FlowVar of a GC'ed type
  277. fvBlob # FlowVar of a blob type
  278. proc spawnResult*(t: PType; inParallel: bool): TSpawnResult =
  279. if t.isEmptyType: srVoid
  280. elif inParallel and not containsGarbageCollectedRef(t): srByVar
  281. else: srFlowVar
  282. proc flowVarKind(t: PType): TFlowVarKind =
  283. if t.skipTypes(abstractInst).kind in {tyRef, tyString, tySequence}: fvGC
  284. elif containsGarbageCollectedRef(t): fvInvalid
  285. else: fvBlob
  286. proc typeNeedsNoDeepCopy(t: PType): bool =
  287. var t = t.skipTypes(abstractInst)
  288. # for the tconvexhull example (and others) we're a bit lax here and pretend
  289. # seqs and strings are *by value* only and 'shallow' doesn't exist!
  290. if t.kind == tyString: return true
  291. # note that seq[T] is fine, but 'var seq[T]' is not, so we need to skip 'var'
  292. # for the stricter check and likewise we can skip 'seq' for a less
  293. # strict check:
  294. if t.kind in {tyVar, tyLent, tySequence}: t = t.lastSon
  295. result = not containsGarbageCollectedRef(t)
  296. proc hoistExpr*(varSection, expr: PNode, name: PIdent, owner: PSym): PSym =
  297. result = newSym(skLet, name, owner, varSection.info, owner.options)
  298. result.flags.incl sfHoisted
  299. result.typ = expr.typ
  300. var varDef = newNodeI(nkIdentDefs, varSection.info, 3)
  301. varDef.sons[0] = newSymNode(result)
  302. varDef.sons[1] = newNodeI(nkEmpty, varSection.info)
  303. varDef.sons[2] = expr
  304. varSection.add varDef
  305. proc addLocalVar(g: ModuleGraph; varSection, varInit: PNode; owner: PSym; typ: PType;
  306. v: PNode; useShallowCopy=false): PSym =
  307. result = newSym(skTemp, getIdent(g.cache, genPrefix), owner, varSection.info,
  308. owner.options)
  309. result.typ = typ
  310. incl(result.flags, sfFromGeneric)
  311. var vpart = newNodeI(nkIdentDefs, varSection.info, 3)
  312. vpart.sons[0] = newSymNode(result)
  313. vpart.sons[1] = newNodeI(nkEmpty, varSection.info)
  314. vpart.sons[2] = if varInit.isNil: v else: vpart[1]
  315. varSection.add vpart
  316. if varInit != nil:
  317. if useShallowCopy and typeNeedsNoDeepCopy(typ):
  318. varInit.add newFastAsgnStmt(newSymNode(result), v)
  319. else:
  320. let deepCopyCall = newNodeI(nkCall, varInit.info, 3)
  321. deepCopyCall.sons[0] = newSymNode(getSysMagic(g, varSection.info, "deepCopy", mDeepCopy))
  322. deepCopyCall.sons[1] = newSymNode(result)
  323. deepCopyCall.sons[2] = v
  324. varInit.add deepCopyCall
  325. discard """
  326. We generate roughly this:
  327. proc f_wrapper(thread, args) =
  328. barrierEnter(args.barrier) # for parallel statement
  329. var a = args.a # thread transfer; deepCopy or shallowCopy or no copy
  330. # depending on whether we're in a 'parallel' statement
  331. var b = args.b
  332. var fv = args.fv
  333. fv.owner = thread # optional
  334. nimArgsPassingDone() # signal parent that the work is done
  335. #
  336. args.fv.blob = f(a, b, ...)
  337. nimFlowVarSignal(args.fv)
  338. # - or -
  339. f(a, b, ...)
  340. barrierLeave(args.barrier) # for parallel statement
  341. stmtList:
  342. var scratchObj
  343. scratchObj.a = a
  344. scratchObj.b = b
  345. nimSpawn(f_wrapper, addr scratchObj)
  346. scratchObj.fv # optional
  347. """
  348. proc createWrapperProc(g: ModuleGraph; f: PNode; threadParam, argsParam: PSym;
  349. varSection, varInit, call, barrier, fv: PNode;
  350. spawnKind: TSpawnResult): PSym =
  351. var body = newNodeI(nkStmtList, f.info)
  352. body.flags.incl nfTransf # do not transform further
  353. var threadLocalBarrier: PSym
  354. if barrier != nil:
  355. var varSection2 = newNodeI(nkVarSection, barrier.info)
  356. threadLocalBarrier = addLocalVar(g, varSection2, nil, argsParam.owner,
  357. barrier.typ, barrier)
  358. body.add varSection2
  359. body.add callCodegenProc(g, "barrierEnter", threadLocalBarrier.info,
  360. threadLocalBarrier.newSymNode)
  361. var threadLocalProm: PSym
  362. if spawnKind == srByVar:
  363. threadLocalProm = addLocalVar(g, varSection, nil, argsParam.owner, fv.typ, fv)
  364. elif fv != nil:
  365. internalAssert g.config, fv.typ.kind == tyGenericInst
  366. threadLocalProm = addLocalVar(g, varSection, nil, argsParam.owner, fv.typ, fv)
  367. body.add varSection
  368. body.add varInit
  369. if fv != nil and spawnKind != srByVar:
  370. # generate:
  371. # fv.owner = threadParam
  372. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  373. "owner", fv.info, g.cache), threadParam.newSymNode)
  374. body.add callCodegenProc(g, "nimArgsPassingDone", threadParam.info,
  375. threadParam.newSymNode)
  376. if spawnKind == srByVar:
  377. body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
  378. elif fv != nil:
  379. let fk = fv.typ.sons[1].flowVarKind
  380. if fk == fvInvalid:
  381. localError(g.config, f.info, "cannot create a flowVar of type: " &
  382. typeToString(fv.typ.sons[1]))
  383. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  384. if fk == fvGC: "data" else: "blob", fv.info, g.cache), call)
  385. if fk == fvGC:
  386. let incRefCall = newNodeI(nkCall, fv.info, 2)
  387. incRefCall.sons[0] = newSymNode(getSysMagic(g, fv.info, "GCref", mGCref))
  388. incRefCall.sons[1] = indirectAccess(threadLocalProm.newSymNode,
  389. "data", fv.info, g.cache)
  390. body.add incRefCall
  391. if barrier == nil:
  392. # by now 'fv' is shared and thus might have beeen overwritten! we need
  393. # to use the thread-local view instead:
  394. body.add callCodegenProc(g, "nimFlowVarSignal", threadLocalProm.info,
  395. threadLocalProm.newSymNode)
  396. else:
  397. body.add call
  398. if barrier != nil:
  399. body.add callCodegenProc(g, "barrierLeave", threadLocalBarrier.info,
  400. threadLocalBarrier.newSymNode)
  401. var params = newNodeI(nkFormalParams, f.info)
  402. params.add newNodeI(nkEmpty, f.info)
  403. params.add threadParam.newSymNode
  404. params.add argsParam.newSymNode
  405. var t = newType(tyProc, threadParam.owner)
  406. t.rawAddSon nil
  407. t.rawAddSon threadParam.typ
  408. t.rawAddSon argsParam.typ
  409. t.n = newNodeI(nkFormalParams, f.info)
  410. t.n.add newNodeI(nkEffectList, f.info)
  411. t.n.add threadParam.newSymNode
  412. t.n.add argsParam.newSymNode
  413. let name = (if f.kind == nkSym: f.sym.name.s else: genPrefix) & "Wrapper"
  414. result = newSym(skProc, getIdent(g.cache, name), argsParam.owner, f.info,
  415. argsParam.options)
  416. let emptyNode = newNodeI(nkEmpty, f.info)
  417. result.ast = newProcNode(nkProcDef, f.info, body = body,
  418. params = params, name = newSymNode(result), pattern = emptyNode,
  419. genericParams = emptyNode, pragmas = emptyNode,
  420. exceptions = emptyNode)
  421. result.typ = t
  422. proc createCastExpr(argsParam: PSym; objType: PType): PNode =
  423. result = newNodeI(nkCast, argsParam.info)
  424. result.add newNodeI(nkEmpty, argsParam.info)
  425. result.add newSymNode(argsParam)
  426. result.typ = newType(tyPtr, objType.owner)
  427. result.typ.rawAddSon(objType)
  428. proc setupArgsForConcurrency(g: ModuleGraph; n: PNode; objType: PType; scratchObj: PSym,
  429. castExpr, call,
  430. varSection, varInit, result: PNode) =
  431. let formals = n[0].typ.n
  432. let tmpName = getIdent(g.cache, genPrefix)
  433. for i in 1 ..< n.len:
  434. # we pick n's type here, which hopefully is 'tyArray' and not
  435. # 'tyOpenArray':
  436. var argType = n[i].typ.skipTypes(abstractInst)
  437. if i < formals.len and formals[i].typ.kind in {tyVar, tyLent}:
  438. localError(g.config, n[i].info, "'spawn'ed function cannot have a 'var' parameter")
  439. #elif containsTyRef(argType):
  440. # localError(n[i].info, "'spawn'ed function cannot refer to 'ref'/closure")
  441. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  442. var field = newSym(skField, fieldname, objType.owner, n.info, g.config.options)
  443. field.typ = argType
  444. objType.addField(field, g.cache)
  445. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[i])
  446. let temp = addLocalVar(g, varSection, varInit, objType.owner, argType,
  447. indirectAccess(castExpr, field, n.info))
  448. call.add(newSymNode(temp))
  449. proc getRoot*(n: PNode): PSym =
  450. ## ``getRoot`` takes a *path* ``n``. A path is an lvalue expression
  451. ## like ``obj.x[i].y``. The *root* of a path is the symbol that can be
  452. ## determined as the owner; ``obj`` in the example.
  453. case n.kind
  454. of nkSym:
  455. if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar}:
  456. result = n.sym
  457. of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr,
  458. nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr:
  459. result = getRoot(n.sons[0])
  460. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  461. result = getRoot(n.sons[1])
  462. of nkCallKinds:
  463. if getMagic(n) == mSlice: result = getRoot(n.sons[1])
  464. else: discard
  465. proc newIntLit*(g: ModuleGraph; info: TLineInfo; value: BiggestInt): PNode =
  466. result = nkIntLit.newIntNode(value)
  467. result.typ = getSysType(g, info, tyInt)
  468. proc genHigh*(g: ModuleGraph; n: PNode): PNode =
  469. if skipTypes(n.typ, abstractVar).kind == tyArray:
  470. result = newIntLit(g, n.info, lastOrd(g.config, skipTypes(n.typ, abstractVar)))
  471. else:
  472. result = newNodeI(nkCall, n.info, 2)
  473. result.typ = getSysType(g, n.info, tyInt)
  474. result.sons[0] = newSymNode(getSysMagic(g, n.info, "high", mHigh))
  475. result.sons[1] = n
  476. proc setupArgsForParallelism(g: ModuleGraph; n: PNode; objType: PType; scratchObj: PSym;
  477. castExpr, call,
  478. varSection, varInit, result: PNode) =
  479. let formals = n[0].typ.n
  480. let tmpName = getIdent(g.cache, genPrefix)
  481. # we need to copy the foreign scratch object fields into local variables
  482. # for correctness: These are called 'threadLocal' here.
  483. for i in 1 ..< n.len:
  484. let n = n[i]
  485. let argType = skipTypes(if i < formals.len: formals[i].typ else: n.typ,
  486. abstractInst)
  487. #if containsTyRef(argType):
  488. # localError(n.info, "'spawn'ed function cannot refer to 'ref'/closure")
  489. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  490. var field = newSym(skField, fieldname, objType.owner, n.info, g.config.options)
  491. if argType.kind in {tyVarargs, tyOpenArray}:
  492. # important special case: we always create a zero-copy slice:
  493. let slice = newNodeI(nkCall, n.info, 4)
  494. slice.typ = n.typ
  495. slice.sons[0] = newSymNode(createMagic(g, "slice", mSlice))
  496. slice.sons[0].typ = getSysType(g, n.info, tyInt) # fake type
  497. var fieldB = newSym(skField, tmpName, objType.owner, n.info, g.config.options)
  498. fieldB.typ = getSysType(g, n.info, tyInt)
  499. objType.addField(fieldB, g.cache)
  500. if getMagic(n) == mSlice:
  501. let a = genAddrOf(n[1])
  502. field.typ = a.typ
  503. objType.addField(field, g.cache)
  504. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  505. var fieldA = newSym(skField, tmpName, objType.owner, n.info, g.config.options)
  506. fieldA.typ = getSysType(g, n.info, tyInt)
  507. objType.addField(fieldA, g.cache)
  508. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldA), n[2])
  509. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), n[3])
  510. let threadLocal = addLocalVar(g, varSection,nil, objType.owner, fieldA.typ,
  511. indirectAccess(castExpr, fieldA, n.info),
  512. useShallowCopy=true)
  513. slice.sons[2] = threadLocal.newSymNode
  514. else:
  515. let a = genAddrOf(n)
  516. field.typ = a.typ
  517. objType.addField(field, g.cache)
  518. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  519. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), genHigh(g, n))
  520. slice.sons[2] = newIntLit(g, n.info, 0)
  521. # the array itself does not need to go through a thread local variable:
  522. slice.sons[1] = genDeref(indirectAccess(castExpr, field, n.info))
  523. let threadLocal = addLocalVar(g, varSection,nil, objType.owner, fieldB.typ,
  524. indirectAccess(castExpr, fieldB, n.info),
  525. useShallowCopy=true)
  526. slice.sons[3] = threadLocal.newSymNode
  527. call.add slice
  528. elif (let size = computeSize(g.config, argType); size < 0 or size > 16) and
  529. n.getRoot != nil:
  530. # it is more efficient to pass a pointer instead:
  531. let a = genAddrOf(n)
  532. field.typ = a.typ
  533. objType.addField(field, g.cache)
  534. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  535. let threadLocal = addLocalVar(g, varSection,nil, objType.owner, field.typ,
  536. indirectAccess(castExpr, field, n.info),
  537. useShallowCopy=true)
  538. call.add(genDeref(threadLocal.newSymNode))
  539. else:
  540. # boring case
  541. field.typ = argType
  542. objType.addField(field, g.cache)
  543. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n)
  544. let threadLocal = addLocalVar(g, varSection, varInit,
  545. objType.owner, field.typ,
  546. indirectAccess(castExpr, field, n.info),
  547. useShallowCopy=true)
  548. call.add(threadLocal.newSymNode)
  549. proc wrapProcForSpawn*(g: ModuleGraph; owner: PSym; spawnExpr: PNode; retType: PType;
  550. barrier, dest: PNode = nil): PNode =
  551. # if 'barrier' != nil, then it is in a 'parallel' section and we
  552. # generate quite different code
  553. let n = spawnExpr[^2]
  554. let spawnKind = spawnResult(retType, barrier!=nil)
  555. case spawnKind
  556. of srVoid:
  557. internalAssert g.config, dest == nil
  558. result = newNodeI(nkStmtList, n.info)
  559. of srFlowVar:
  560. internalAssert g.config, dest == nil
  561. result = newNodeIT(nkStmtListExpr, n.info, retType)
  562. of srByVar:
  563. if dest == nil: localError(g.config, n.info, "'spawn' must not be discarded")
  564. result = newNodeI(nkStmtList, n.info)
  565. if n.kind notin nkCallKinds:
  566. localError(g.config, n.info, "'spawn' takes a call expression")
  567. return
  568. if optThreadAnalysis in g.config.globalOptions:
  569. if {tfThread, tfNoSideEffect} * n[0].typ.flags == {}:
  570. localError(g.config, n.info, "'spawn' takes a GC safe call expression")
  571. var
  572. threadParam = newSym(skParam, getIdent(g.cache, "thread"), owner, n.info, g.config.options)
  573. argsParam = newSym(skParam, getIdent(g.cache, "args"), owner, n.info, g.config.options)
  574. block:
  575. let ptrType = getSysType(g, n.info, tyPointer)
  576. threadParam.typ = ptrType
  577. argsParam.typ = ptrType
  578. argsParam.position = 1
  579. var objType = createObj(g, owner, n.info)
  580. incl(objType.flags, tfFinal)
  581. let castExpr = createCastExpr(argsParam, objType)
  582. var scratchObj = newSym(skVar, getIdent(g.cache, "scratch"), owner, n.info, g.config.options)
  583. block:
  584. scratchObj.typ = objType
  585. incl(scratchObj.flags, sfFromGeneric)
  586. var varSectionB = newNodeI(nkVarSection, n.info)
  587. varSectionB.addVar(scratchObj.newSymNode)
  588. result.add varSectionB
  589. var call = newNodeIT(nkCall, n.info, n.typ)
  590. var fn = n.sons[0]
  591. # templates and macros are in fact valid here due to the nature of
  592. # the transformation:
  593. if fn.kind == nkClosure:
  594. localError(g.config, n.info, "closure in spawn environment is not allowed")
  595. if not (fn.kind == nkSym and fn.sym.kind in {skProc, skTemplate, skMacro,
  596. skFunc, skMethod, skConverter}):
  597. # for indirect calls we pass the function pointer in the scratchObj
  598. var argType = n[0].typ.skipTypes(abstractInst)
  599. var field = newSym(skField, getIdent(g.cache, "fn"), owner, n.info, g.config.options)
  600. field.typ = argType
  601. objType.addField(field, g.cache)
  602. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[0])
  603. fn = indirectAccess(castExpr, field, n.info)
  604. elif fn.kind == nkSym and fn.sym.kind == skIterator:
  605. localError(g.config, n.info, "iterator in spawn environment is not allowed")
  606. elif fn.typ.callConv == ccClosure:
  607. localError(g.config, n.info, "closure in spawn environment is not allowed")
  608. call.add(fn)
  609. var varSection = newNodeI(nkVarSection, n.info)
  610. var varInit = newNodeI(nkStmtList, n.info)
  611. if barrier.isNil:
  612. setupArgsForConcurrency(g, n, objType, scratchObj, castExpr, call,
  613. varSection, varInit, result)
  614. else:
  615. setupArgsForParallelism(g, n, objType, scratchObj, castExpr, call,
  616. varSection, varInit, result)
  617. var barrierAsExpr: PNode = nil
  618. if barrier != nil:
  619. let typ = newType(tyPtr, owner)
  620. typ.rawAddSon(magicsys.getCompilerProc(g, "Barrier").typ)
  621. var field = newSym(skField, getIdent(g.cache, "barrier"), owner, n.info, g.config.options)
  622. field.typ = typ
  623. objType.addField(field, g.cache)
  624. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), barrier)
  625. barrierAsExpr = indirectAccess(castExpr, field, n.info)
  626. var fvField, fvAsExpr: PNode = nil
  627. if spawnKind == srFlowVar:
  628. var field = newSym(skField, getIdent(g.cache, "fv"), owner, n.info, g.config.options)
  629. field.typ = retType
  630. objType.addField(field, g.cache)
  631. fvField = newDotExpr(scratchObj, field)
  632. fvAsExpr = indirectAccess(castExpr, field, n.info)
  633. # create flowVar:
  634. result.add newFastAsgnStmt(fvField, callProc(spawnExpr[^1]))
  635. if barrier == nil:
  636. result.add callCodegenProc(g, "nimFlowVarCreateSemaphore", fvField.info,
  637. fvField)
  638. elif spawnKind == srByVar:
  639. var field = newSym(skField, getIdent(g.cache, "fv"), owner, n.info, g.config.options)
  640. field.typ = newType(tyPtr, objType.owner)
  641. field.typ.rawAddSon(retType)
  642. objType.addField(field, g.cache)
  643. fvAsExpr = indirectAccess(castExpr, field, n.info)
  644. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), genAddrOf(dest))
  645. let wrapper = createWrapperProc(g, fn, threadParam, argsParam,
  646. varSection, varInit, call,
  647. barrierAsExpr, fvAsExpr, spawnKind)
  648. result.add callCodegenProc(g, "nimSpawn" & $spawnExpr.len, wrapper.info,
  649. wrapper.newSymNode, genAddrOf(scratchObj.newSymNode), nil, spawnExpr)
  650. if spawnKind == srFlowVar: result.add fvField