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