ccgcalls.nim 28 KB

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