ccgcalls.nim 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. #
  10. # included from cgen.nim
  11. proc canRaiseDisp(p: BProc; n: PNode): bool =
  12. # we assume things like sysFatal cannot raise themselves
  13. if n.kind == nkSym and {sfNeverRaises, sfImportc, sfCompilerProc} * n.sym.flags != {}:
  14. result = false
  15. elif optPanics in p.config.globalOptions or
  16. (n.kind == nkSym and sfSystemModule in getModule(n.sym).flags):
  17. # we know we can be strict:
  18. result = canRaise(n)
  19. else:
  20. # we have to be *very* conservative:
  21. result = canRaiseConservative(n)
  22. proc preventNrvo(p: BProc; dest, le, ri: PNode): bool =
  23. proc locationEscapes(p: BProc; le: PNode; inTryStmt: bool): bool =
  24. var n = le
  25. while true:
  26. # do NOT follow nkHiddenDeref here!
  27. case n.kind
  28. of nkSym:
  29. # we don't own the location so it escapes:
  30. if n.sym.owner != p.prc:
  31. return true
  32. elif inTryStmt and sfUsedInFinallyOrExcept in n.sym.flags:
  33. # it is also an observable store if the location is used
  34. # in 'except' or 'finally'
  35. return true
  36. return false
  37. of nkDotExpr, nkBracketExpr, nkObjUpConv, nkObjDownConv,
  38. nkCheckedFieldExpr:
  39. n = n[0]
  40. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  41. n = n[1]
  42. else:
  43. # cannot analyse the location; assume the worst
  44. return true
  45. if le != nil:
  46. for i in 1..<ri.len:
  47. let r = ri[i]
  48. if isPartOf(le, r) != arNo: return true
  49. # we use the weaker 'canRaise' here in order to prevent too many
  50. # annoying warnings, see #14514
  51. if canRaise(ri[0]) and
  52. locationEscapes(p, le, p.nestedTryStmts.len > 0):
  53. message(p.config, le.info, warnObservableStores, $le)
  54. # bug #19613 prevent dangerous aliasing too:
  55. if dest != nil and dest != le:
  56. for i in 1..<ri.len:
  57. let r = ri[i]
  58. if isPartOf(dest, r) != arNo: return true
  59. proc hasNoInit(call: PNode): bool {.inline.} =
  60. result = call[0].kind == nkSym and sfNoInit in call[0].sym.flags
  61. proc isHarmlessStore(p: BProc; canRaise: bool; d: TLoc): bool =
  62. if d.k in {locTemp, locNone} or not canRaise:
  63. result = true
  64. elif d.k == locLocalVar and p.withinTryWithExcept == 0:
  65. # we cannot observe a store to a local variable if the current proc
  66. # has no error handler:
  67. result = true
  68. else:
  69. result = false
  70. proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
  71. callee, params: Rope) =
  72. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  73. genLineDir(p, ri)
  74. var pl = callee & ~"(" & params
  75. # getUniqueType() is too expensive here:
  76. var typ = skipTypes(ri[0].typ, abstractInst)
  77. if typ[0] != nil:
  78. if isInvalidReturnType(p.config, typ):
  79. if params != nil: pl.add(~", ")
  80. # beware of 'result = p(result)'. We may need to allocate a temporary:
  81. if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
  82. # Great, we can use 'd':
  83. if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
  84. elif d.k notin {locTemp} and not hasNoInit(ri):
  85. # reset before pass as 'result' var:
  86. discard "resetLoc(p, d)"
  87. pl.add(addrLoc(p.config, d))
  88. pl.add(~");$n")
  89. line(p, cpsStmts, pl)
  90. else:
  91. var tmp: TLoc
  92. getTemp(p, typ[0], tmp, needsInit=true)
  93. pl.add(addrLoc(p.config, tmp))
  94. pl.add(~");$n")
  95. line(p, cpsStmts, pl)
  96. genAssignment(p, d, tmp, {}) # no need for deep copying
  97. if canRaise: raiseExit(p)
  98. else:
  99. pl.add(~")")
  100. if p.module.compileToCpp:
  101. if lfSingleUse in d.flags:
  102. # do not generate spurious temporaries for C++! For C we're better off
  103. # with them to prevent undefined behaviour and because the codegen
  104. # is free to emit expressions multiple times!
  105. d.k = locCall
  106. d.r = pl
  107. excl d.flags, lfSingleUse
  108. else:
  109. if d.k == locNone and p.splitDecls == 0:
  110. getTempCpp(p, typ[0], d, pl)
  111. else:
  112. if d.k == locNone: getTemp(p, typ[0], d)
  113. var list: TLoc
  114. initLoc(list, locCall, d.lode, OnUnknown)
  115. list.r = pl
  116. genAssignment(p, d, list, {}) # no need for deep copying
  117. if canRaise: raiseExit(p)
  118. elif isHarmlessStore(p, canRaise, d):
  119. if d.k == locNone: getTemp(p, typ[0], d)
  120. assert(d.t != nil) # generate an assignment to d:
  121. var list: TLoc
  122. initLoc(list, locCall, d.lode, OnUnknown)
  123. list.r = pl
  124. genAssignment(p, d, list, {}) # no need for deep copying
  125. if canRaise: raiseExit(p)
  126. else:
  127. var tmp: TLoc
  128. getTemp(p, typ[0], tmp, needsInit=true)
  129. var list: TLoc
  130. initLoc(list, locCall, d.lode, OnUnknown)
  131. list.r = pl
  132. genAssignment(p, tmp, list, {}) # no need for deep copying
  133. if canRaise: raiseExit(p)
  134. genAssignment(p, d, tmp, {})
  135. else:
  136. pl.add(~");$n")
  137. line(p, cpsStmts, pl)
  138. if canRaise: raiseExit(p)
  139. proc genBoundsCheck(p: BProc; arr, a, b: TLoc)
  140. proc reifiedOpenArray(n: PNode): bool {.inline.} =
  141. var x = n
  142. while x.kind in {nkAddr, nkHiddenAddr, nkHiddenStdConv, nkHiddenDeref}:
  143. x = x[0]
  144. if x.kind == nkSym and x.sym.kind == skParam:
  145. result = false
  146. else:
  147. result = true
  148. proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType; prepareForMutation = false): (Rope, Rope) =
  149. var a, b, c: TLoc
  150. initLocExpr(p, q[1], a)
  151. initLocExpr(p, q[2], b)
  152. initLocExpr(p, q[3], c)
  153. # but first produce the required index checks:
  154. if optBoundsCheck in p.options:
  155. genBoundsCheck(p, a, b, c)
  156. if prepareForMutation:
  157. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  158. let ty = skipTypes(a.t, abstractVar+{tyPtr})
  159. let dest = getTypeDesc(p.module, destType)
  160. let lengthExpr = "($1)-($2)+1" % [rdLoc(c), rdLoc(b)]
  161. case ty.kind
  162. of tyArray:
  163. let first = toInt64(firstOrd(p.config, ty))
  164. if first == 0:
  165. result = ("($3*)(($1)+($2))" % [rdLoc(a), rdLoc(b), dest],
  166. lengthExpr)
  167. else:
  168. result = ("($4*)($1)+(($2)-($3))" %
  169. [rdLoc(a), rdLoc(b), intLiteral(first), dest],
  170. lengthExpr)
  171. of tyOpenArray, tyVarargs:
  172. if reifiedOpenArray(q[1]):
  173. result = ("($3*)($1.Field0)+($2)" % [rdLoc(a), rdLoc(b), dest],
  174. lengthExpr)
  175. else:
  176. result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
  177. lengthExpr)
  178. of tyUncheckedArray, tyCstring:
  179. result = ("($3*)($1)+($2)" % [rdLoc(a), rdLoc(b), dest],
  180. lengthExpr)
  181. of tyString, tySequence:
  182. let atyp = skipTypes(a.t, abstractInst)
  183. if formalType.skipTypes(abstractInst).kind in {tyVar} and atyp.kind == tyString and
  184. optSeqDestructors in p.config.globalOptions:
  185. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  186. if atyp.kind in {tyVar} and not compileToCpp(p.module):
  187. result = ("(($5) ? (($4*)(*$1)$3+($2)) : NIM_NIL)" %
  188. [rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, "*" & rdLoc(a))],
  189. lengthExpr)
  190. else:
  191. result = ("(($5) ? (($4*)$1$3+($2)) : NIM_NIL)" %
  192. [rdLoc(a), rdLoc(b), dataField(p), dest, dataFieldAccessor(p, rdLoc(a))],
  193. lengthExpr)
  194. else:
  195. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  196. proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
  197. var q = skipConv(n)
  198. var skipped = false
  199. while q.kind == nkStmtListExpr and q.len > 0:
  200. skipped = true
  201. q = q.lastSon
  202. if getMagic(q) == mSlice:
  203. # magic: pass slice to openArray:
  204. if skipped:
  205. q = skipConv(n)
  206. while q.kind == nkStmtListExpr and q.len > 0:
  207. for i in 0..<q.len-1:
  208. genStmts(p, q[i])
  209. q = q.lastSon
  210. let (x, y) = genOpenArraySlice(p, q, formalType, n.typ[0])
  211. result = x & ", " & y
  212. else:
  213. var a: TLoc
  214. initLocExpr(p, if n.kind == nkHiddenStdConv: n[1] else: n, a)
  215. case skipTypes(a.t, abstractVar+{tyStatic}).kind
  216. of tyOpenArray, tyVarargs:
  217. if reifiedOpenArray(n):
  218. if a.t.kind in {tyVar, tyLent}:
  219. result = "$1->Field0, $1->Field1" % [rdLoc(a)]
  220. else:
  221. result = "$1.Field0, $1.Field1" % [rdLoc(a)]
  222. else:
  223. result = "$1, $1Len_0" % [rdLoc(a)]
  224. of tyString, tySequence:
  225. let ntyp = skipTypes(n.typ, abstractInst)
  226. if formalType.skipTypes(abstractInst).kind in {tyVar} and ntyp.kind == tyString and
  227. optSeqDestructors in p.config.globalOptions:
  228. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  229. if ntyp.kind in {tyVar} and not compileToCpp(p.module):
  230. var t: TLoc
  231. t.r = "(*$1)" % [a.rdLoc]
  232. result = "($4) ? ((*$1)$3) : NIM_NIL, $2" %
  233. [a.rdLoc, lenExpr(p, t), dataField(p),
  234. dataFieldAccessor(p, "*" & a.rdLoc)]
  235. else:
  236. result = "($4) ? ($1$3) : NIM_NIL, $2" %
  237. [a.rdLoc, lenExpr(p, a), dataField(p), dataFieldAccessor(p, a.rdLoc)]
  238. of tyArray:
  239. result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))]
  240. of tyPtr, tyRef:
  241. case lastSon(a.t).kind
  242. of tyString, tySequence:
  243. var t: TLoc
  244. t.r = "(*$1)" % [a.rdLoc]
  245. result = "($4) ? ((*$1)$3) : NIM_NIL, $2" %
  246. [a.rdLoc, lenExpr(p, t), dataField(p),
  247. dataFieldAccessor(p, "*" & a.rdLoc)]
  248. of tyArray:
  249. result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, lastSon(a.t)))]
  250. else:
  251. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  252. else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  253. proc withTmpIfNeeded(p: BProc, a: TLoc, needsTmp: bool): TLoc =
  254. # Bug https://github.com/status-im/nimbus-eth2/issues/1549
  255. # Aliasing is preferred over stack overflows.
  256. # Also don't regress for non ARC-builds, too risky.
  257. if needsTmp and a.lode.typ != nil and p.config.selectedGC in {gcArc, gcOrc} and
  258. getSize(p.config, a.lode.typ) < 1024:
  259. getTemp(p, a.lode.typ, result, needsInit=false)
  260. genAssignment(p, result, a, {})
  261. else:
  262. result = a
  263. proc literalsNeedsTmp(p: BProc, a: TLoc): TLoc =
  264. getTemp(p, a.lode.typ, result, needsInit=false)
  265. genAssignment(p, result, a, {})
  266. proc genArgStringToCString(p: BProc, n: PNode, needsTmp: bool): Rope {.inline.} =
  267. var a: TLoc
  268. initLocExpr(p, n[0], a)
  269. ropecg(p.module, "#nimToCStringConv($1)", [withTmpIfNeeded(p, a, needsTmp).rdLoc])
  270. proc genArg(p: BProc, n: PNode, param: PSym; call: PNode, needsTmp = false): Rope =
  271. var a: TLoc
  272. if n.kind == nkStringToCString:
  273. result = genArgStringToCString(p, n, needsTmp)
  274. elif skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs}:
  275. var n = if n.kind != nkHiddenAddr: n else: n[0]
  276. result = openArrayLoc(p, param.typ, n)
  277. elif ccgIntroducedPtr(p.config, param, call[0].typ[0]):
  278. initLocExpr(p, n, a)
  279. if n.kind in {nkCharLit..nkNilLit}:
  280. result = addrLoc(p.config, literalsNeedsTmp(p, a))
  281. else:
  282. result = addrLoc(p.config, withTmpIfNeeded(p, a, needsTmp))
  283. elif p.module.compileToCpp and param.typ.kind in {tyVar} and
  284. n.kind == nkHiddenAddr:
  285. initLocExprSingleUse(p, n[0], a)
  286. # if the proc is 'importc'ed but not 'importcpp'ed then 'var T' still
  287. # means '*T'. See posix.nim for lots of examples that do that in the wild.
  288. let callee = call[0]
  289. if callee.kind == nkSym and
  290. {sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
  291. {lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
  292. result = addrLoc(p.config, a)
  293. else:
  294. result = rdLoc(a)
  295. else:
  296. initLocExprSingleUse(p, n, a)
  297. result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
  298. #assert result != nil
  299. proc genArgNoParam(p: BProc, n: PNode, needsTmp = false): Rope =
  300. var a: TLoc
  301. if n.kind == nkStringToCString:
  302. result = genArgStringToCString(p, n, needsTmp)
  303. else:
  304. initLocExprSingleUse(p, n, a)
  305. result = rdLoc(withTmpIfNeeded(p, a, needsTmp))
  306. from dfa import aliases, AliasKind
  307. proc potentialAlias(n: PNode, potentialWrites: seq[PNode]): bool =
  308. for p in potentialWrites:
  309. if p.aliases(n) != no or n.aliases(p) != no:
  310. return true
  311. proc skipTrivialIndirections(n: PNode): PNode =
  312. result = n
  313. while true:
  314. case result.kind
  315. of nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv:
  316. result = result[0]
  317. of nkHiddenStdConv, nkHiddenSubConv:
  318. result = result[1]
  319. else: break
  320. proc getPotentialWrites(n: PNode; mutate: bool; result: var seq[PNode]) =
  321. case n.kind:
  322. of nkLiterals, nkIdent, nkFormalParams: discard
  323. of nkSym:
  324. if mutate: result.add n
  325. of nkAsgn, nkFastAsgn:
  326. getPotentialWrites(n[0], true, result)
  327. getPotentialWrites(n[1], mutate, result)
  328. of nkAddr, nkHiddenAddr:
  329. getPotentialWrites(n[0], true, result)
  330. of nkBracketExpr, nkDotExpr, nkCheckedFieldExpr:
  331. getPotentialWrites(n[0], mutate, result)
  332. of nkCallKinds:
  333. case n.getMagic:
  334. of mIncl, mExcl, mInc, mDec, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  335. mAddr, mNew, mNewFinalize, mWasMoved, mDestroy, mReset:
  336. getPotentialWrites(n[1], true, result)
  337. for i in 2..<n.len:
  338. getPotentialWrites(n[i], mutate, result)
  339. of mSwap:
  340. for i in 1..<n.len:
  341. getPotentialWrites(n[i], true, result)
  342. else:
  343. for i in 1..<n.len:
  344. getPotentialWrites(n[i], mutate, result)
  345. else:
  346. for s in n:
  347. getPotentialWrites(s, mutate, result)
  348. proc getPotentialReads(n: PNode; result: var seq[PNode]) =
  349. case n.kind:
  350. of nkLiterals, nkIdent, nkFormalParams: discard
  351. of nkSym: result.add n
  352. else:
  353. for s in n:
  354. getPotentialReads(s, result)
  355. proc genParams(p: BProc, ri: PNode, typ: PType): Rope =
  356. # We must generate temporaries in cases like #14396
  357. # to keep the strict Left-To-Right evaluation
  358. var needTmp = newSeq[bool](ri.len - 1)
  359. var potentialWrites: seq[PNode]
  360. for i in countdown(ri.len - 1, 1):
  361. if ri[i].skipTrivialIndirections.kind == nkSym:
  362. needTmp[i - 1] = potentialAlias(ri[i], potentialWrites)
  363. else:
  364. #if not ri[i].typ.isCompileTimeOnly:
  365. var potentialReads: seq[PNode]
  366. getPotentialReads(ri[i], potentialReads)
  367. for n in potentialReads:
  368. if not needTmp[i - 1]:
  369. needTmp[i - 1] = potentialAlias(n, potentialWrites)
  370. getPotentialWrites(ri[i], false, potentialWrites)
  371. if ri[i].kind in {nkHiddenAddr, nkAddr}:
  372. # Optimization: don't use a temp, if we would only take the address anyway
  373. needTmp[i - 1] = false
  374. for i in 1..<ri.len:
  375. if i < typ.len:
  376. assert(typ.n[i].kind == nkSym)
  377. let paramType = typ.n[i]
  378. if not paramType.typ.isCompileTimeOnly:
  379. if result != nil: result.add(~", ")
  380. result.add(genArg(p, ri[i], paramType.sym, ri, needTmp[i-1]))
  381. else:
  382. if result != nil: result.add(~", ")
  383. result.add(genArgNoParam(p, ri[i], needTmp[i-1]))
  384. proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
  385. if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
  386. (sym.typ.callConv == ccInline or sym.owner.id == module.id):
  387. res = res & "_actual".rope
  388. proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  389. var op: TLoc
  390. # this is a hotspot in the compiler
  391. initLocExpr(p, ri[0], op)
  392. # getUniqueType() is too expensive here:
  393. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  394. assert(typ.kind == tyProc)
  395. assert(typ.len == typ.n.len)
  396. var params = genParams(p, ri, typ)
  397. var callee = rdLoc(op)
  398. if p.hcrOn and ri[0].kind == nkSym:
  399. callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
  400. fixupCall(p, le, ri, d, callee, params)
  401. proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
  402. proc addComma(r: Rope): Rope =
  403. if r == nil: r else: r & ~", "
  404. const PatProc = "$1.ClE_0? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)"
  405. const PatIter = "$1.ClP_0($3$1.ClE_0)" # we know the env exists
  406. var op: TLoc
  407. initLocExpr(p, ri[0], op)
  408. # getUniqueType() is too expensive here:
  409. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  410. assert(typ.kind == tyProc)
  411. assert(typ.len == typ.n.len)
  412. var pl = genParams(p, ri, typ)
  413. template genCallPattern {.dirty.} =
  414. if tfIterator in typ.flags:
  415. lineF(p, cpsStmts, PatIter & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  416. else:
  417. lineF(p, cpsStmts, PatProc & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  418. let rawProc = getClosureType(p.module, typ, clHalf)
  419. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  420. if typ[0] != nil:
  421. if isInvalidReturnType(p.config, typ):
  422. if ri.len > 1: pl.add(~", ")
  423. # beware of 'result = p(result)'. We may need to allocate a temporary:
  424. if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
  425. # Great, we can use 'd':
  426. if d.k == locNone:
  427. getTemp(p, typ[0], d, needsInit=true)
  428. elif d.k notin {locTemp} and not hasNoInit(ri):
  429. # reset before pass as 'result' var:
  430. discard "resetLoc(p, d)"
  431. pl.add(addrLoc(p.config, d))
  432. genCallPattern()
  433. else:
  434. var tmp: TLoc
  435. getTemp(p, typ[0], tmp, needsInit=true)
  436. pl.add(addrLoc(p.config, tmp))
  437. genCallPattern()
  438. if canRaise: raiseExit(p)
  439. genAssignment(p, d, tmp, {}) # no need for deep copying
  440. elif isHarmlessStore(p, canRaise, d):
  441. if d.k == locNone: getTemp(p, typ[0], d)
  442. assert(d.t != nil) # generate an assignment to d:
  443. var list: TLoc
  444. initLoc(list, locCall, d.lode, OnUnknown)
  445. if tfIterator in typ.flags:
  446. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  447. else:
  448. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  449. genAssignment(p, d, list, {}) # no need for deep copying
  450. if canRaise: raiseExit(p)
  451. else:
  452. var tmp: TLoc
  453. getTemp(p, typ[0], tmp)
  454. assert(d.t != nil) # generate an assignment to d:
  455. var list: TLoc
  456. initLoc(list, locCall, d.lode, OnUnknown)
  457. if tfIterator in typ.flags:
  458. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  459. else:
  460. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  461. genAssignment(p, tmp, list, {})
  462. if canRaise: raiseExit(p)
  463. genAssignment(p, d, tmp, {})
  464. else:
  465. genCallPattern()
  466. if canRaise: raiseExit(p)
  467. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
  468. if i < typ.len:
  469. # 'var T' is 'T&' in C++. This means we ignore the request of
  470. # any nkHiddenAddr when it's a 'var T'.
  471. let paramType = typ.n[i]
  472. assert(paramType.kind == nkSym)
  473. if paramType.typ.isCompileTimeOnly:
  474. result = nil
  475. elif typ[i].kind in {tyVar} and ri[i].kind == nkHiddenAddr:
  476. result = genArgNoParam(p, ri[i][0])
  477. else:
  478. result = genArgNoParam(p, ri[i]) #, typ.n[i].sym)
  479. else:
  480. if tfVarargs notin typ.flags:
  481. localError(p.config, ri.info, "wrong argument count")
  482. result = nil
  483. else:
  484. result = genArgNoParam(p, ri[i])
  485. discard """
  486. Dot call syntax in C++
  487. ======================
  488. so c2nim translates 'this' sometimes to 'T' and sometimes to 'var T'
  489. both of which are wrong, but often more convenient to use.
  490. For manual wrappers it can also be 'ptr T'
  491. Fortunately we know which parameter is the 'this' parameter and so can fix this
  492. mess in the codegen.
  493. now ... if the *argument* is a 'ptr' the codegen shall emit -> and otherwise .
  494. but this only depends on the argument and not on how the 'this' was declared
  495. however how the 'this' was declared affects whether we end up with
  496. wrong 'addr' and '[]' ops...
  497. Since I'm tired I'll enumerate all the cases here:
  498. var
  499. x: ptr T
  500. y: T
  501. proc t(x: T)
  502. x[].t() --> (*x).t() is correct.
  503. y.t() --> y.t() is correct
  504. proc u(x: ptr T)
  505. x.u() --> needs to become x->u()
  506. (addr y).u() --> needs to become y.u()
  507. proc v(x: var T)
  508. --> first skip the implicit 'nkAddr' node
  509. x[].v() --> (*x).v() is correct, but might have been eliminated due
  510. to the nkAddr node! So for this case we need to generate '->'
  511. y.v() --> y.v() is correct
  512. """
  513. proc skipAddrDeref(node: PNode): PNode =
  514. var n = node
  515. var isAddr = false
  516. case n.kind
  517. of nkAddr, nkHiddenAddr:
  518. n = n[0]
  519. isAddr = true
  520. of nkDerefExpr, nkHiddenDeref:
  521. n = n[0]
  522. else: return n
  523. if n.kind == nkObjDownConv: n = n[0]
  524. if isAddr and n.kind in {nkDerefExpr, nkHiddenDeref}:
  525. result = n[0]
  526. elif n.kind in {nkAddr, nkHiddenAddr}:
  527. result = n[0]
  528. else:
  529. result = node
  530. proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
  531. # for better or worse c2nim translates the 'this' argument to a 'var T'.
  532. # However manual wrappers may also use 'ptr T'. In any case we support both
  533. # for convenience.
  534. internalAssert p.config, i < typ.len
  535. assert(typ.n[i].kind == nkSym)
  536. # if the parameter is lying (tyVar) and thus we required an additional deref,
  537. # skip the deref:
  538. var ri = ri[i]
  539. while ri.kind == nkObjDownConv: ri = ri[0]
  540. let t = typ[i].skipTypes({tyGenericInst, tyAlias, tySink})
  541. if t.kind in {tyVar}:
  542. let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
  543. if x.typ.kind == tyPtr:
  544. result = genArgNoParam(p, x)
  545. result.add("->")
  546. elif x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].typ.kind == tyPtr:
  547. result = genArgNoParam(p, x[0])
  548. result.add("->")
  549. else:
  550. result = genArgNoParam(p, x)
  551. result.add(".")
  552. elif t.kind == tyPtr:
  553. if ri.kind in {nkAddr, nkHiddenAddr}:
  554. result = genArgNoParam(p, ri[0])
  555. result.add(".")
  556. else:
  557. result = genArgNoParam(p, ri)
  558. result.add("->")
  559. else:
  560. ri = skipAddrDeref(ri)
  561. if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
  562. result = genArgNoParam(p, ri) #, typ.n[i].sym)
  563. result.add(".")
  564. proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
  565. var i = 0
  566. var j = 1
  567. while i < pat.len:
  568. case pat[i]
  569. of '@':
  570. var first = true
  571. for k in j..<ri.len:
  572. let arg = genOtherArg(p, ri, k, typ)
  573. if arg.len > 0:
  574. if not first:
  575. result.add(~", ")
  576. first = false
  577. result.add arg
  578. inc i
  579. of '#':
  580. if i+1 < pat.len and pat[i+1] in {'+', '@'}:
  581. let ri = ri[j]
  582. if ri.kind in nkCallKinds:
  583. let typ = skipTypes(ri[0].typ, abstractInst)
  584. if pat[i+1] == '+': result.add genArgNoParam(p, ri[0])
  585. result.add(~"(")
  586. if 1 < ri.len:
  587. result.add genOtherArg(p, ri, 1, typ)
  588. for k in j+1..<ri.len:
  589. result.add(~", ")
  590. result.add genOtherArg(p, ri, k, typ)
  591. result.add(~")")
  592. else:
  593. localError(p.config, ri.info, "call expression expected for C++ pattern")
  594. inc i
  595. elif i+1 < pat.len and pat[i+1] == '.':
  596. result.add genThisArg(p, ri, j, typ)
  597. inc i
  598. elif i+1 < pat.len and pat[i+1] == '[':
  599. var arg = ri[j].skipAddrDeref
  600. while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
  601. result.add genArgNoParam(p, arg)
  602. #result.add debugTree(arg, 0, 10)
  603. else:
  604. result.add genOtherArg(p, ri, j, typ)
  605. inc j
  606. inc i
  607. of '\'':
  608. var idx, stars: int
  609. if scanCppGenericSlot(pat, i, idx, stars):
  610. var t = resolveStarsInCppType(typ, idx, stars)
  611. if t == nil: result.add(~"void")
  612. else: result.add(getTypeDesc(p.module, t))
  613. else:
  614. let start = i
  615. while i < pat.len:
  616. if pat[i] notin {'@', '#', '\''}: inc(i)
  617. else: break
  618. if i - 1 >= start:
  619. result.add(substr(pat, start, i - 1))
  620. proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  621. var op: TLoc
  622. initLocExpr(p, ri[0], op)
  623. # getUniqueType() is too expensive here:
  624. var typ = skipTypes(ri[0].typ, abstractInst)
  625. assert(typ.kind == tyProc)
  626. assert(typ.len == typ.n.len)
  627. # don't call '$' here for efficiency:
  628. let pat = ri[0].sym.loc.r.data
  629. internalAssert p.config, pat.len > 0
  630. if pat.contains({'#', '(', '@', '\''}):
  631. var pl = genPatternCall(p, ri, pat, typ)
  632. # simpler version of 'fixupCall' that works with the pl+params combination:
  633. var typ = skipTypes(ri[0].typ, abstractInst)
  634. if typ[0] != nil:
  635. if p.module.compileToCpp and lfSingleUse in d.flags:
  636. # do not generate spurious temporaries for C++! For C we're better off
  637. # with them to prevent undefined behaviour and because the codegen
  638. # is free to emit expressions multiple times!
  639. d.k = locCall
  640. d.r = pl
  641. excl d.flags, lfSingleUse
  642. else:
  643. if d.k == locNone: getTemp(p, typ[0], d)
  644. assert(d.t != nil) # generate an assignment to d:
  645. var list: TLoc
  646. initLoc(list, locCall, d.lode, OnUnknown)
  647. list.r = pl
  648. genAssignment(p, d, list, {}) # no need for deep copying
  649. else:
  650. pl.add(~";$n")
  651. line(p, cpsStmts, pl)
  652. else:
  653. var pl: Rope = nil
  654. #var param = typ.n[1].sym
  655. if 1 < ri.len:
  656. pl.add(genThisArg(p, ri, 1, typ))
  657. pl.add(op.r)
  658. var params: Rope
  659. for i in 2..<ri.len:
  660. if params != nil: params.add(~", ")
  661. assert(typ.len == typ.n.len)
  662. params.add(genOtherArg(p, ri, i, typ))
  663. fixupCall(p, le, ri, d, pl, params)
  664. proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
  665. # generates a crappy ObjC call
  666. var op: TLoc
  667. initLocExpr(p, ri[0], op)
  668. var pl = ~"["
  669. # getUniqueType() is too expensive here:
  670. var typ = skipTypes(ri[0].typ, abstractInst)
  671. assert(typ.kind == tyProc)
  672. assert(typ.len == typ.n.len)
  673. # don't call '$' here for efficiency:
  674. let pat = ri[0].sym.loc.r.data
  675. internalAssert p.config, pat.len > 0
  676. var start = 3
  677. if ' ' in pat:
  678. start = 1
  679. pl.add(op.r)
  680. if ri.len > 1:
  681. pl.add(~": ")
  682. pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
  683. start = 2
  684. else:
  685. if ri.len > 1:
  686. pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
  687. pl.add(~" ")
  688. pl.add(op.r)
  689. if ri.len > 2:
  690. pl.add(~": ")
  691. pl.add(genArg(p, ri[2], typ.n[2].sym, ri))
  692. for i in start..<ri.len:
  693. assert(typ.len == typ.n.len)
  694. if i >= typ.len:
  695. internalError(p.config, ri.info, "varargs for objective C method?")
  696. assert(typ.n[i].kind == nkSym)
  697. var param = typ.n[i].sym
  698. pl.add(~" ")
  699. pl.add(param.name.s)
  700. pl.add(~": ")
  701. pl.add(genArg(p, ri[i], param, ri))
  702. if typ[0] != nil:
  703. if isInvalidReturnType(p.config, typ):
  704. if ri.len > 1: pl.add(~" ")
  705. # beware of 'result = p(result)'. We always allocate a temporary:
  706. if d.k in {locTemp, locNone}:
  707. # We already got a temp. Great, special case it:
  708. if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
  709. pl.add(~"Result: ")
  710. pl.add(addrLoc(p.config, d))
  711. pl.add(~"];$n")
  712. line(p, cpsStmts, pl)
  713. else:
  714. var tmp: TLoc
  715. getTemp(p, typ[0], tmp, needsInit=true)
  716. pl.add(addrLoc(p.config, tmp))
  717. pl.add(~"];$n")
  718. line(p, cpsStmts, pl)
  719. genAssignment(p, d, tmp, {}) # no need for deep copying
  720. else:
  721. pl.add(~"]")
  722. if d.k == locNone: getTemp(p, typ[0], d)
  723. assert(d.t != nil) # generate an assignment to d:
  724. var list: TLoc
  725. initLoc(list, locCall, ri, OnUnknown)
  726. list.r = pl
  727. genAssignment(p, d, list, {}) # no need for deep copying
  728. else:
  729. pl.add(~"];$n")
  730. line(p, cpsStmts, pl)
  731. proc notYetAlive(n: PNode): bool {.inline.} =
  732. let r = getRoot(n)
  733. result = r != nil and r.loc.lode == nil
  734. proc isInactiveDestructorCall(p: BProc, e: PNode): bool =
  735. #[ Consider this example.
  736. var :tmpD_3281815
  737. try:
  738. if true:
  739. return
  740. let args_3280013 =
  741. wasMoved_3281816(:tmpD_3281815)
  742. `=_3280036`(:tmpD_3281815, [1])
  743. :tmpD_3281815
  744. finally:
  745. `=destroy_3280027`(args_3280013)
  746. We want to return early but the 'finally' section is traversed before
  747. the 'let args = ...' statement. We exploit this to generate better
  748. code for 'return'. ]#
  749. result = e.len == 2 and e[0].kind == nkSym and
  750. e[0].sym.name.s == "=destroy" and notYetAlive(e[1].skipAddr)
  751. proc genAsgnCall(p: BProc, le, ri: PNode, d: var TLoc) =
  752. if p.withinBlockLeaveActions > 0 and isInactiveDestructorCall(p, ri):
  753. return
  754. if ri[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
  755. genClosureCall(p, le, ri, d)
  756. elif ri[0].kind == nkSym and sfInfixCall in ri[0].sym.flags:
  757. genInfixCall(p, le, ri, d)
  758. elif ri[0].kind == nkSym and sfNamedParamCall in ri[0].sym.flags:
  759. genNamedParamCall(p, ri, d)
  760. else:
  761. genPrefixCall(p, le, ri, d)
  762. proc genCall(p: BProc, e: PNode, d: var TLoc) = genAsgnCall(p, nil, e, d)