ccgcalls.nim 30 KB

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