ccgcalls.nim 29 KB

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