ccgcalls.nim 29 KB

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