ccgstmts.nim 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. # included from cgen.nim
  10. const
  11. RangeExpandLimit = 256 # do not generate ranges
  12. # over 'RangeExpandLimit' elements
  13. stringCaseThreshold = 8
  14. # above X strings a hash-switch for strings is generated
  15. proc registerTraverseProc(p: BProc, v: PSym) =
  16. var traverseProc = ""
  17. if p.config.selectedGC in {gcMarkAndSweep, gcHooks, gcRefc} and
  18. optOwnedRefs notin p.config.globalOptions and
  19. containsGarbageCollectedRef(v.loc.t):
  20. # we register a specialized marked proc here; this has the advantage
  21. # that it works out of the box for thread local storage then :-)
  22. traverseProc = genTraverseProcForGlobal(p.module, v, v.info)
  23. if traverseProc.len != 0 and not p.hcrOn:
  24. if sfThread in v.flags:
  25. appcg(p.module, p.module.preInitProc.procSec(cpsInit),
  26. "$n\t#nimRegisterThreadLocalMarker($1);$n$n", [traverseProc])
  27. else:
  28. appcg(p.module, p.module.preInitProc.procSec(cpsInit),
  29. "$n\t#nimRegisterGlobalMarker($1);$n$n", [traverseProc])
  30. proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} =
  31. if n.kind == nkEmpty:
  32. result = false
  33. elif n.kind in nkCallKinds and n[0] != nil and n[0].typ != nil and n[0].typ.skipTypes(abstractInst).kind == tyProc:
  34. if n[0].kind == nkSym and sfConstructor in n[0].sym.flags:
  35. result = true
  36. elif isInvalidReturnType(conf, n[0].typ, true):
  37. # var v = f()
  38. # is transformed into: var v; f(addr v)
  39. # where 'f' **does not** initialize the result!
  40. result = false
  41. else:
  42. result = true
  43. elif isInvalidReturnType(conf, n.typ, false):
  44. result = false
  45. else:
  46. result = true
  47. proc inExceptBlockLen(p: BProc): int =
  48. for x in p.nestedTryStmts:
  49. if x.inExcept: result.inc
  50. proc startBlockInternal(p: BProc): int {.discardable.} =
  51. inc(p.labels)
  52. result = p.blocks.len
  53. p.blocks.add initBlock()
  54. p.blocks[result].id = p.labels
  55. p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16
  56. p.blocks[result].nestedExceptStmts = p.inExceptBlockLen.int16
  57. template startBlock(p: BProc, start: FormatStr = "{$n",
  58. args: varargs[Rope]): int =
  59. lineCg(p, cpsStmts, start, args)
  60. startBlockInternal(p)
  61. proc endBlock(p: BProc)
  62. proc genVarTuple(p: BProc, n: PNode) =
  63. var tup, field: TLoc
  64. if n.kind != nkVarTuple: internalError(p.config, n.info, "genVarTuple")
  65. # if we have a something that's been captured, use the lowering instead:
  66. for i in 0..<n.len-2:
  67. if n[i].kind != nkSym:
  68. genStmts(p, lowerTupleUnpacking(p.module.g.graph, n, p.module.idgen, p.prc))
  69. return
  70. # check only the first son
  71. var forHcr = treatGlobalDifferentlyForHCR(p.module, n[0].sym)
  72. let hcrCond = if forHcr: getTempName(p.module) else: ""
  73. var hcrGlobals: seq[tuple[loc: TLoc, tp: Rope]]
  74. # determine if the tuple is constructed at top-level scope or inside of a block (if/while/block)
  75. let isGlobalInBlock = forHcr and p.blocks.len > 2
  76. # do not close and reopen blocks if this is a 'global' but inside of a block (if/while/block)
  77. forHcr = forHcr and not isGlobalInBlock
  78. if forHcr:
  79. # check with the boolean if the initializing code for the tuple should be ran
  80. lineCg(p, cpsStmts, "if ($1)$n", [hcrCond])
  81. startBlock(p)
  82. genLineDir(p, n)
  83. initLocExpr(p, n[^1], tup)
  84. var t = tup.t.skipTypes(abstractInst)
  85. for i in 0..<n.len-2:
  86. let vn = n[i]
  87. let v = vn.sym
  88. if sfCompileTime in v.flags: continue
  89. if sfGlobal in v.flags:
  90. assignGlobalVar(p, vn, "")
  91. genObjectInit(p, cpsInit, v.typ, v.loc, constructObj)
  92. registerTraverseProc(p, v)
  93. else:
  94. assignLocalVar(p, vn)
  95. initLocalVar(p, v, immediateAsgn=isAssignedImmediately(p.config, n[^1]))
  96. initLoc(field, locExpr, vn, tup.storage)
  97. if t.kind == tyTuple:
  98. field.r = "$1.Field$2" % [rdLoc(tup), rope(i)]
  99. else:
  100. if t.n[i].kind != nkSym: internalError(p.config, n.info, "genVarTuple")
  101. field.r = "$1.$2" % [rdLoc(tup), mangleRecFieldName(p.module, t.n[i].sym)]
  102. putLocIntoDest(p, v.loc, field)
  103. if forHcr or isGlobalInBlock:
  104. hcrGlobals.add((loc: v.loc, tp: "NULL"))
  105. if forHcr:
  106. # end the block where the tuple gets initialized
  107. endBlock(p)
  108. if forHcr or isGlobalInBlock:
  109. # insert the registration of the globals for the different parts of the tuple at the
  110. # start of the current scope (after they have been iterated) and init a boolean to
  111. # check if any of them is newly introduced and the initializing code has to be ran
  112. lineCg(p, cpsLocals, "NIM_BOOL $1 = NIM_FALSE;$n", [hcrCond])
  113. for curr in hcrGlobals:
  114. lineCg(p, cpsLocals, "$1 |= hcrRegisterGlobal($4, \"$2\", sizeof($3), $5, (void**)&$2);$N",
  115. [hcrCond, curr.loc.r, rdLoc(curr.loc), getModuleDllPath(p.module, n[0].sym), curr.tp])
  116. proc loadInto(p: BProc, le, ri: PNode, a: var TLoc) {.inline.} =
  117. if ri.kind in nkCallKinds and (ri[0].kind != nkSym or
  118. ri[0].sym.magic == mNone):
  119. genAsgnCall(p, le, ri, a)
  120. else:
  121. # this is a hacky way to fix #1181 (tmissingderef)::
  122. #
  123. # var arr1 = cast[ptr array[4, int8]](addr foo)[]
  124. #
  125. # However, fixing this properly really requires modelling 'array' as
  126. # a 'struct' in C to preserve dereferencing semantics completely. Not
  127. # worth the effort until version 1.0 is out.
  128. a.flags.incl(lfEnforceDeref)
  129. expr(p, ri, a)
  130. proc assignLabel(b: var TBlock; result: var Rope) {.inline.} =
  131. b.label = "LA" & b.id.rope
  132. result.add b.label
  133. proc blockBody(b: var TBlock; result: var Rope) =
  134. result.add b.sections[cpsLocals]
  135. if b.frameLen > 0:
  136. result.addf("FR_.len+=$1;$n", [b.frameLen.rope])
  137. result.add(b.sections[cpsInit])
  138. result.add(b.sections[cpsStmts])
  139. proc endBlock(p: BProc, blockEnd: Rope) =
  140. let topBlock = p.blocks.len-1
  141. # the block is merged into the parent block
  142. p.blocks[topBlock].blockBody(p.blocks[topBlock-1].sections[cpsStmts])
  143. setLen(p.blocks, topBlock)
  144. # this is done after the block is popped so $n is
  145. # properly indented when pretty printing is enabled
  146. line(p, cpsStmts, blockEnd)
  147. proc endBlock(p: BProc) =
  148. let topBlock = p.blocks.len - 1
  149. let frameLen = p.blocks[topBlock].frameLen
  150. var blockEnd: Rope
  151. if frameLen > 0:
  152. blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope])
  153. if p.blocks[topBlock].label.len != 0:
  154. blockEnd.addf("} $1: ;$n", [p.blocks[topBlock].label])
  155. else:
  156. blockEnd.addf("}$n", [])
  157. endBlock(p, blockEnd)
  158. proc genSimpleBlock(p: BProc, stmts: PNode) {.inline.} =
  159. startBlock(p)
  160. genStmts(p, stmts)
  161. endBlock(p)
  162. proc exprBlock(p: BProc, n: PNode, d: var TLoc) =
  163. startBlock(p)
  164. expr(p, n, d)
  165. endBlock(p)
  166. template preserveBreakIdx(body: untyped): untyped =
  167. var oldBreakIdx = p.breakIdx
  168. body
  169. p.breakIdx = oldBreakIdx
  170. proc genState(p: BProc, n: PNode) =
  171. internalAssert p.config, n.len == 1
  172. let n0 = n[0]
  173. if n0.kind == nkIntLit:
  174. let idx = n[0].intVal
  175. linefmt(p, cpsStmts, "STATE$1: ;$n", [idx])
  176. elif n0.kind == nkStrLit:
  177. linefmt(p, cpsStmts, "$1: ;$n", [n0.strVal])
  178. proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int) =
  179. # Called by return and break stmts.
  180. # Deals with issues faced when jumping out of try/except/finally stmts.
  181. var stack = newSeq[tuple[fin: PNode, inExcept: bool, label: Natural]](0)
  182. inc p.withinBlockLeaveActions
  183. for i in 1..howManyTrys:
  184. let tryStmt = p.nestedTryStmts.pop
  185. if p.config.exc == excSetjmp:
  186. # Pop safe points generated by try
  187. if not tryStmt.inExcept:
  188. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  189. # Pop this try-stmt of the list of nested trys
  190. # so we don't infinite recurse on it in the next step.
  191. stack.add(tryStmt)
  192. # Find finally-stmt for this try-stmt
  193. # and generate a copy of its sons
  194. var finallyStmt = tryStmt.fin
  195. if finallyStmt != nil:
  196. genStmts(p, finallyStmt[0])
  197. dec p.withinBlockLeaveActions
  198. # push old elements again:
  199. for i in countdown(howManyTrys-1, 0):
  200. p.nestedTryStmts.add(stack[i])
  201. # Pop exceptions that was handled by the
  202. # except-blocks we are in
  203. if noSafePoints notin p.flags:
  204. for i in countdown(howManyExcepts-1, 0):
  205. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  206. proc genGotoState(p: BProc, n: PNode) =
  207. # we resist the temptation to translate it into duff's device as it later
  208. # will be translated into computed gotos anyway for GCC at least:
  209. # switch (x.state) {
  210. # case 0: goto STATE0;
  211. # ...
  212. var a: TLoc
  213. initLocExpr(p, n[0], a)
  214. lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)])
  215. p.flags.incl beforeRetNeeded
  216. lineF(p, cpsStmts, "case -1:$n", [])
  217. blockLeaveActions(p,
  218. howManyTrys = p.nestedTryStmts.len,
  219. howManyExcepts = p.inExceptBlockLen)
  220. lineF(p, cpsStmts, " goto BeforeRet_;$n", [])
  221. var statesCounter = lastOrd(p.config, n[0].typ)
  222. if n.len >= 2 and n[1].kind == nkIntLit:
  223. statesCounter = getInt(n[1])
  224. let prefix = if n.len == 3 and n[2].kind == nkStrLit: n[2].strVal.rope
  225. else: rope"STATE"
  226. for i in 0i64..toInt64(statesCounter):
  227. lineF(p, cpsStmts, "case $2: goto $1$2;$n", [prefix, rope(i)])
  228. lineF(p, cpsStmts, "}$n", [])
  229. proc genBreakState(p: BProc, n: PNode, d: var TLoc) =
  230. var a: TLoc
  231. initLoc(d, locExpr, n, OnUnknown)
  232. if n[0].kind == nkClosure:
  233. initLocExpr(p, n[0][1], a)
  234. d.r = "(((NI*) $1)[1] < 0)" % [rdLoc(a)]
  235. else:
  236. initLocExpr(p, n[0], a)
  237. # the environment is guaranteed to contain the 'state' field at offset 1:
  238. d.r = "((((NI*) $1.ClE_0)[1]) < 0)" % [rdLoc(a)]
  239. proc genGotoVar(p: BProc; value: PNode) =
  240. if value.kind notin {nkCharLit..nkUInt64Lit}:
  241. localError(p.config, value.info, "'goto' target must be a literal value")
  242. else:
  243. lineF(p, cpsStmts, "goto NIMSTATE_$#;$n", [value.intVal.rope])
  244. proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; result: var Rope)
  245. proc potentialValueInit(p: BProc; v: PSym; value: PNode; result: var Rope) =
  246. if lfDynamicLib in v.loc.flags or sfThread in v.flags or p.hcrOn:
  247. discard "nothing to do"
  248. elif sfGlobal in v.flags and value != nil and isDeepConstExpr(value, p.module.compileToCpp) and
  249. p.withinLoop == 0 and not containsGarbageCollectedRef(v.typ):
  250. #echo "New code produced for ", v.name.s, " ", p.config $ value.info
  251. genBracedInit(p, value, isConst = false, v.typ, result)
  252. proc genCppVarForCtor(p: BProc, v: PSym; vn, value: PNode; decl: var Rope) =
  253. var params = newRopeAppender()
  254. var argsCounter = 0
  255. let typ = skipTypes(value[0].typ, abstractInst)
  256. assert(typ.kind == tyProc)
  257. for i in 1..<value.len:
  258. assert(typ.len == typ.n.len)
  259. genOtherArg(p, value, i, typ, params, argsCounter)
  260. if params.len == 0:
  261. decl = runtimeFormat("$#;\n", [decl])
  262. else:
  263. decl = runtimeFormat("$#($#);\n", [decl, params])
  264. proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
  265. if sfGoto in v.flags:
  266. # translate 'var state {.goto.} = X' into 'goto LX':
  267. genGotoVar(p, value)
  268. return
  269. let imm = isAssignedImmediately(p.config, value)
  270. let isCppCtorCall = p.module.compileToCpp and imm and
  271. value.kind in nkCallKinds and value[0].kind == nkSym and
  272. v.typ.kind != tyPtr and sfConstructor in value[0].sym.flags
  273. var targetProc = p
  274. var valueAsRope = ""
  275. potentialValueInit(p, v, value, valueAsRope)
  276. if sfGlobal in v.flags:
  277. if v.flags * {sfImportc, sfExportc} == {sfImportc} and
  278. value.kind == nkEmpty and
  279. v.loc.flags * {lfHeader, lfNoDecl} != {}:
  280. return
  281. if sfPure in v.flags:
  282. # v.owner.kind != skModule:
  283. targetProc = p.module.preInitProc
  284. if isCppCtorCall and not containsHiddenPointer(v.typ):
  285. callGlobalVarCppCtor(targetProc, v, vn, value)
  286. else:
  287. assignGlobalVar(targetProc, vn, valueAsRope)
  288. # XXX: be careful here.
  289. # Global variables should not be zeromem-ed within loops
  290. # (see bug #20).
  291. # That's why we are doing the construction inside the preInitProc.
  292. # genObjectInit relies on the C runtime's guarantees that
  293. # global variables will be initialized to zero.
  294. if valueAsRope.len == 0:
  295. var loc = v.loc
  296. # When the native TLS is unavailable, a global thread-local variable needs
  297. # one more layer of indirection in order to access the TLS block.
  298. # Only do this for complex types that may need a call to `objectInit`
  299. if sfThread in v.flags and emulatedThreadVars(p.config) and
  300. isComplexValueType(v.typ):
  301. initLocExprSingleUse(p.module.preInitProc, vn, loc)
  302. genObjectInit(p.module.preInitProc, cpsInit, v.typ, loc, constructObj)
  303. # Alternative construction using default constructor (which may zeromem):
  304. # if sfImportc notin v.flags: constructLoc(p.module.preInitProc, v.loc)
  305. if sfExportc in v.flags and p.module.g.generatedHeader != nil:
  306. genVarPrototype(p.module.g.generatedHeader, vn)
  307. registerTraverseProc(p, v)
  308. else:
  309. if imm and p.module.compileToCpp and p.splitDecls == 0 and
  310. not containsHiddenPointer(v.typ) and
  311. nimErrorFlagAccessed notin p.flags:
  312. # C++ really doesn't like things like 'Foo f; f = x' as that invokes a
  313. # parameterless constructor followed by an assignment operator. So we
  314. # generate better code here: 'Foo f = x;'
  315. genLineDir(p, vn)
  316. var decl = localVarDecl(p, vn)
  317. var tmp: TLoc
  318. if isCppCtorCall:
  319. genCppVarForCtor(p, v, vn, value, decl)
  320. line(p, cpsStmts, decl)
  321. else:
  322. initLocExprSingleUse(p, value, tmp)
  323. lineF(p, cpsStmts, "$# = $#;\n", [decl, tmp.rdLoc])
  324. return
  325. assignLocalVar(p, vn)
  326. initLocalVar(p, v, imm)
  327. let traverseProc = "NULL"
  328. # If the var is in a block (control flow like if/while or a block) in global scope just
  329. # register the so called "global" so it can be used later on. There is no need to close
  330. # and reopen of if (nim_hcr_do_init_) blocks because we are in one already anyway.
  331. var forHcr = treatGlobalDifferentlyForHCR(p.module, v)
  332. if forHcr and targetProc.blocks.len > 3 and v.owner.kind == skModule:
  333. # put it in the locals section - mainly because of loops which
  334. # use the var in a call to resetLoc() in the statements section
  335. lineCg(targetProc, cpsLocals, "hcrRegisterGlobal($3, \"$1\", sizeof($2), $4, (void**)&$1);$n",
  336. [v.loc.r, rdLoc(v.loc), getModuleDllPath(p.module, v), traverseProc])
  337. # nothing special left to do later on - let's avoid closing and reopening blocks
  338. forHcr = false
  339. # we close and reopen the global if (nim_hcr_do_init_) blocks in the main Init function
  340. # for the module so we can have globals and top-level code be interleaved and still
  341. # be able to re-run it but without the top level code - just the init of globals
  342. if forHcr:
  343. lineCg(targetProc, cpsStmts, "if (hcrRegisterGlobal($3, \"$1\", sizeof($2), $4, (void**)&$1))$N",
  344. [v.loc.r, rdLoc(v.loc), getModuleDllPath(p.module, v), traverseProc])
  345. startBlock(targetProc)
  346. if value.kind != nkEmpty and valueAsRope.len == 0:
  347. genLineDir(targetProc, vn)
  348. if not isCppCtorCall:
  349. loadInto(targetProc, vn, value, v.loc)
  350. if forHcr:
  351. endBlock(targetProc)
  352. proc genSingleVar(p: BProc, a: PNode) =
  353. let v = a[0].sym
  354. if sfCompileTime in v.flags:
  355. # fix issue #12640
  356. # {.global, compileTime.} pragma in proc
  357. if sfGlobal in v.flags and p.prc != nil and p.prc.kind == skProc:
  358. discard
  359. else:
  360. return
  361. genSingleVar(p, v, a[0], a[2])
  362. proc genClosureVar(p: BProc, a: PNode) =
  363. var immediateAsgn = a[2].kind != nkEmpty
  364. var v: TLoc
  365. initLocExpr(p, a[0], v)
  366. genLineDir(p, a)
  367. if immediateAsgn:
  368. loadInto(p, a[0], a[2], v)
  369. elif sfNoInit notin a[0][1].sym.flags:
  370. constructLoc(p, v)
  371. proc genVarStmt(p: BProc, n: PNode) =
  372. for it in n.sons:
  373. if it.kind == nkCommentStmt: continue
  374. if it.kind == nkIdentDefs:
  375. # can be a lifted var nowadays ...
  376. if it[0].kind == nkSym:
  377. genSingleVar(p, it)
  378. else:
  379. genClosureVar(p, it)
  380. else:
  381. genVarTuple(p, it)
  382. proc genIf(p: BProc, n: PNode, d: var TLoc) =
  383. #
  384. # { if (!expr1) goto L1;
  385. # thenPart }
  386. # goto LEnd
  387. # L1:
  388. # { if (!expr2) goto L2;
  389. # thenPart2 }
  390. # goto LEnd
  391. # L2:
  392. # { elsePart }
  393. # Lend:
  394. var
  395. a: TLoc
  396. lelse: TLabel
  397. if not isEmptyType(n.typ) and d.k == locNone:
  398. getTemp(p, n.typ, d)
  399. genLineDir(p, n)
  400. let lend = getLabel(p)
  401. for it in n.sons:
  402. # bug #4230: avoid false sharing between branches:
  403. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  404. if it.len == 2:
  405. startBlock(p)
  406. initLocExprSingleUse(p, it[0], a)
  407. lelse = getLabel(p)
  408. inc(p.labels)
  409. lineF(p, cpsStmts, "if (!$1) goto $2;$n",
  410. [rdLoc(a), lelse])
  411. if p.module.compileToCpp:
  412. # avoid "jump to label crosses initialization" error:
  413. p.s(cpsStmts).add "{"
  414. expr(p, it[1], d)
  415. p.s(cpsStmts).add "}"
  416. else:
  417. expr(p, it[1], d)
  418. endBlock(p)
  419. if n.len > 1:
  420. lineF(p, cpsStmts, "goto $1;$n", [lend])
  421. fixLabel(p, lelse)
  422. elif it.len == 1:
  423. startBlock(p)
  424. expr(p, it[0], d)
  425. endBlock(p)
  426. else: internalError(p.config, n.info, "genIf()")
  427. if n.len > 1: fixLabel(p, lend)
  428. proc genReturnStmt(p: BProc, t: PNode) =
  429. if nfPreventCg in t.flags: return
  430. p.flags.incl beforeRetNeeded
  431. genLineDir(p, t)
  432. if (t[0].kind != nkEmpty): genStmts(p, t[0])
  433. blockLeaveActions(p,
  434. howManyTrys = p.nestedTryStmts.len,
  435. howManyExcepts = p.inExceptBlockLen)
  436. if (p.finallySafePoints.len > 0) and noSafePoints notin p.flags:
  437. # If we're in a finally block, and we came here by exception
  438. # consume it before we return.
  439. var safePoint = p.finallySafePoints[^1]
  440. linefmt(p, cpsStmts, "if ($1.status != 0) #popCurrentException();$n", [safePoint])
  441. lineF(p, cpsStmts, "goto BeforeRet_;$n", [])
  442. proc genGotoForCase(p: BProc; caseStmt: PNode) =
  443. for i in 1..<caseStmt.len:
  444. startBlock(p)
  445. let it = caseStmt[i]
  446. for j in 0..<it.len-1:
  447. if it[j].kind == nkRange:
  448. localError(p.config, it.info, "range notation not available for computed goto")
  449. return
  450. let val = getOrdValue(it[j])
  451. lineF(p, cpsStmts, "NIMSTATE_$#:$n", [val.rope])
  452. genStmts(p, it.lastSon)
  453. endBlock(p)
  454. iterator fieldValuePairs(n: PNode): tuple[memberSym, valueSym: PNode] =
  455. assert(n.kind in {nkLetSection, nkVarSection})
  456. for identDefs in n:
  457. if identDefs.kind == nkIdentDefs:
  458. let valueSym = identDefs[^1]
  459. for i in 0..<identDefs.len-2:
  460. let memberSym = identDefs[i]
  461. yield((memberSym: memberSym, valueSym: valueSym))
  462. proc genComputedGoto(p: BProc; n: PNode) =
  463. # first pass: Generate array of computed labels:
  464. # flatten the loop body because otherwise let and var sections
  465. # wrapped inside stmt lists by inject destructors won't be recognised
  466. let n = n.flattenStmts()
  467. var casePos = -1
  468. var arraySize: int
  469. for i in 0..<n.len:
  470. let it = n[i]
  471. if it.kind == nkCaseStmt:
  472. if lastSon(it).kind != nkOfBranch:
  473. localError(p.config, it.info,
  474. "case statement must be exhaustive for computed goto"); return
  475. casePos = i
  476. if enumHasHoles(it[0].typ):
  477. localError(p.config, it.info,
  478. "case statement cannot work on enums with holes for computed goto"); return
  479. let aSize = lengthOrd(p.config, it[0].typ)
  480. if aSize > 10_000:
  481. localError(p.config, it.info,
  482. "case statement has too many cases for computed goto"); return
  483. arraySize = toInt(aSize)
  484. if firstOrd(p.config, it[0].typ) != 0:
  485. localError(p.config, it.info,
  486. "case statement has to start at 0 for computed goto"); return
  487. if casePos < 0:
  488. localError(p.config, n.info, "no case statement found for computed goto"); return
  489. var id = p.labels+1
  490. inc p.labels, arraySize+1
  491. let tmp = "TMP$1_" % [id.rope]
  492. var gotoArray = "static void* $#[$#] = {" % [tmp, arraySize.rope]
  493. for i in 1..arraySize-1:
  494. gotoArray.addf("&&TMP$#_, ", [rope(id+i)])
  495. gotoArray.addf("&&TMP$#_};$n", [rope(id+arraySize)])
  496. line(p, cpsLocals, gotoArray)
  497. for j in 0..<casePos:
  498. genStmts(p, n[j])
  499. let caseStmt = n[casePos]
  500. var a: TLoc
  501. initLocExpr(p, caseStmt[0], a)
  502. # first goto:
  503. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  504. for i in 1..<caseStmt.len:
  505. startBlock(p)
  506. let it = caseStmt[i]
  507. for j in 0..<it.len-1:
  508. if it[j].kind == nkRange:
  509. localError(p.config, it.info, "range notation not available for computed goto")
  510. return
  511. let val = getOrdValue(it[j])
  512. var lit = newRopeAppender()
  513. intLiteral(toInt64(val)+id+1, lit)
  514. lineF(p, cpsStmts, "TMP$#_:$n", [lit])
  515. genStmts(p, it.lastSon)
  516. for j in casePos+1..<n.len:
  517. genStmts(p, n[j])
  518. for j in 0..<casePos:
  519. # prevent new local declarations
  520. # compile declarations as assignments
  521. let it = n[j]
  522. if it.kind in {nkLetSection, nkVarSection}:
  523. let asgn = copyNode(it)
  524. asgn.transitionSonsKind(nkAsgn)
  525. asgn.sons.setLen 2
  526. for sym, value in it.fieldValuePairs:
  527. if value.kind != nkEmpty:
  528. asgn[0] = sym
  529. asgn[1] = value
  530. genStmts(p, asgn)
  531. else:
  532. genStmts(p, it)
  533. var a: TLoc
  534. initLocExpr(p, caseStmt[0], a)
  535. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  536. endBlock(p)
  537. for j in casePos+1..<n.len:
  538. genStmts(p, n[j])
  539. proc genWhileStmt(p: BProc, t: PNode) =
  540. # we don't generate labels here as for example GCC would produce
  541. # significantly worse code
  542. var
  543. a: TLoc
  544. assert(t.len == 2)
  545. inc(p.withinLoop)
  546. genLineDir(p, t)
  547. preserveBreakIdx:
  548. var loopBody = t[1]
  549. if loopBody.stmtsContainPragma(wComputedGoto) and
  550. hasComputedGoto in CC[p.config.cCompiler].props:
  551. # for closure support weird loop bodies are generated:
  552. if loopBody.len == 2 and loopBody[0].kind == nkEmpty:
  553. loopBody = loopBody[1]
  554. genComputedGoto(p, loopBody)
  555. else:
  556. p.breakIdx = startBlock(p, "while (1) {$n")
  557. p.blocks[p.breakIdx].isLoop = true
  558. initLocExpr(p, t[0], a)
  559. if (t[0].kind != nkIntLit) or (t[0].intVal == 0):
  560. lineF(p, cpsStmts, "if (!$1) goto ", [rdLoc(a)])
  561. assignLabel(p.blocks[p.breakIdx], p.s(cpsStmts))
  562. appcg(p, cpsStmts, ";$n", [])
  563. genStmts(p, loopBody)
  564. if optProfiler in p.options:
  565. # invoke at loop body exit:
  566. linefmt(p, cpsStmts, "#nimProfile();$n", [])
  567. endBlock(p)
  568. dec(p.withinLoop)
  569. proc genBlock(p: BProc, n: PNode, d: var TLoc) =
  570. if not isEmptyType(n.typ):
  571. # bug #4505: allocate the temp in the outer scope
  572. # so that it can escape the generated {}:
  573. if d.k == locNone:
  574. getTemp(p, n.typ, d)
  575. d.flags.incl(lfEnforceDeref)
  576. preserveBreakIdx:
  577. p.breakIdx = startBlock(p)
  578. if n[0].kind != nkEmpty:
  579. # named block?
  580. assert(n[0].kind == nkSym)
  581. var sym = n[0].sym
  582. sym.loc.k = locOther
  583. sym.position = p.breakIdx+1
  584. expr(p, n[1], d)
  585. endBlock(p)
  586. proc genParForStmt(p: BProc, t: PNode) =
  587. assert(t.len == 3)
  588. inc(p.withinLoop)
  589. genLineDir(p, t)
  590. preserveBreakIdx:
  591. let forLoopVar = t[0].sym
  592. var rangeA, rangeB: TLoc
  593. assignLocalVar(p, t[0])
  594. #initLoc(forLoopVar.loc, locLocalVar, forLoopVar.typ, onStack)
  595. #discard mangleName(forLoopVar)
  596. let call = t[1]
  597. assert(call.len == 4 or call.len == 5)
  598. initLocExpr(p, call[1], rangeA)
  599. initLocExpr(p, call[2], rangeB)
  600. # $n at the beginning because of #9710
  601. if call.len == 4: # procName(a, b, annotation)
  602. if call[0].sym.name.s == "||": # `||`(a, b, annotation)
  603. lineF(p, cpsStmts, "$n#pragma omp $4$n" &
  604. "for ($1 = $2; $1 <= $3; ++$1)",
  605. [forLoopVar.loc.rdLoc,
  606. rangeA.rdLoc, rangeB.rdLoc,
  607. call[3].getStr.rope])
  608. else:
  609. lineF(p, cpsStmts, "$n#pragma $4$n" &
  610. "for ($1 = $2; $1 <= $3; ++$1)",
  611. [forLoopVar.loc.rdLoc,
  612. rangeA.rdLoc, rangeB.rdLoc,
  613. call[3].getStr.rope])
  614. else: # `||`(a, b, step, annotation)
  615. var step: TLoc
  616. initLocExpr(p, call[3], step)
  617. lineF(p, cpsStmts, "$n#pragma omp $5$n" &
  618. "for ($1 = $2; $1 <= $3; $1 += $4)",
  619. [forLoopVar.loc.rdLoc,
  620. rangeA.rdLoc, rangeB.rdLoc, step.rdLoc,
  621. call[4].getStr.rope])
  622. p.breakIdx = startBlock(p)
  623. p.blocks[p.breakIdx].isLoop = true
  624. genStmts(p, t[2])
  625. endBlock(p)
  626. dec(p.withinLoop)
  627. proc genBreakStmt(p: BProc, t: PNode) =
  628. var idx = p.breakIdx
  629. if t[0].kind != nkEmpty:
  630. # named break?
  631. assert(t[0].kind == nkSym)
  632. var sym = t[0].sym
  633. doAssert(sym.loc.k == locOther)
  634. idx = sym.position-1
  635. else:
  636. # an unnamed 'break' can only break a loop after 'transf' pass:
  637. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  638. if idx < 0 or not p.blocks[idx].isLoop:
  639. internalError(p.config, t.info, "no loop to break")
  640. p.blocks[idx].label = "LA" & p.blocks[idx].id.rope
  641. blockLeaveActions(p,
  642. p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts,
  643. p.inExceptBlockLen - p.blocks[idx].nestedExceptStmts)
  644. genLineDir(p, t)
  645. lineF(p, cpsStmts, "goto $1;$n", [p.blocks[idx].label])
  646. proc raiseExit(p: BProc) =
  647. assert p.config.exc == excGoto
  648. if nimErrorFlagDisabled notin p.flags:
  649. p.flags.incl nimErrorFlagAccessed
  650. if p.nestedTryStmts.len == 0:
  651. p.flags.incl beforeRetNeeded
  652. # easy case, simply goto 'ret':
  653. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) goto BeforeRet_;$n", [])
  654. else:
  655. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) goto LA$1_;$n",
  656. [p.nestedTryStmts[^1].label])
  657. proc finallyActions(p: BProc) =
  658. if p.config.exc != excGoto and p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
  659. # if the current try stmt have a finally block,
  660. # we must execute it before reraising
  661. let finallyBlock = p.nestedTryStmts[^1].fin
  662. if finallyBlock != nil:
  663. genSimpleBlock(p, finallyBlock[0])
  664. proc raiseInstr(p: BProc; result: var Rope) =
  665. if p.config.exc == excGoto:
  666. let L = p.nestedTryStmts.len
  667. if L == 0:
  668. p.flags.incl beforeRetNeeded
  669. # easy case, simply goto 'ret':
  670. result.add ropecg(p.module, "goto BeforeRet_;$n", [])
  671. else:
  672. # raise inside an 'except' must go to the finally block,
  673. # raise outside an 'except' block must go to the 'except' list.
  674. result.add ropecg(p.module, "goto LA$1_;$n",
  675. [p.nestedTryStmts[L-1].label])
  676. # + ord(p.nestedTryStmts[L-1].inExcept)])
  677. proc genRaiseStmt(p: BProc, t: PNode) =
  678. if t[0].kind != nkEmpty:
  679. var a: TLoc
  680. initLocExprSingleUse(p, t[0], a)
  681. finallyActions(p)
  682. var e = rdLoc(a)
  683. discard getTypeDesc(p.module, t[0].typ)
  684. var typ = skipTypes(t[0].typ, abstractPtrs)
  685. # XXX For reasons that currently escape me, this is only required by the new
  686. # C++ based exception handling:
  687. if p.config.exc == excCpp:
  688. blockLeaveActions(p, howManyTrys = 0, howManyExcepts = p.inExceptBlockLen)
  689. genLineDir(p, t)
  690. if isImportedException(typ, p.config):
  691. lineF(p, cpsStmts, "throw $1;$n", [e])
  692. else:
  693. lineCg(p, cpsStmts, "#raiseExceptionEx((#Exception*)$1, $2, $3, $4, $5);$n",
  694. [e, makeCString(typ.sym.name.s),
  695. makeCString(if p.prc != nil: p.prc.name.s else: p.module.module.name.s),
  696. quotedFilename(p.config, t.info), toLinenumber(t.info)])
  697. if optOwnedRefs in p.config.globalOptions:
  698. lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [e])
  699. else:
  700. finallyActions(p)
  701. genLineDir(p, t)
  702. linefmt(p, cpsStmts, "#reraiseException();$n", [])
  703. raiseInstr(p, p.s(cpsStmts))
  704. template genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
  705. rangeFormat, eqFormat: FormatStr, labl: TLabel) =
  706. var x, y: TLoc
  707. for i in 0..<b.len - 1:
  708. if b[i].kind == nkRange:
  709. initLocExpr(p, b[i][0], x)
  710. initLocExpr(p, b[i][1], y)
  711. lineCg(p, cpsStmts, rangeFormat,
  712. [rdCharLoc(e), rdCharLoc(x), rdCharLoc(y), labl])
  713. else:
  714. initLocExpr(p, b[i], x)
  715. lineCg(p, cpsStmts, eqFormat, [rdCharLoc(e), rdCharLoc(x), labl])
  716. proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
  717. labId, until: int): TLabel =
  718. var lend = getLabel(p)
  719. for i in 1..until:
  720. # bug #4230: avoid false sharing between branches:
  721. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  722. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(labId + i)])
  723. if t[i].kind == nkOfBranch:
  724. exprBlock(p, t[i][^1], d)
  725. lineF(p, cpsStmts, "goto $1;$n", [lend])
  726. else:
  727. exprBlock(p, t[i][0], d)
  728. result = lend
  729. template genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
  730. rangeFormat, eqFormat: FormatStr,
  731. until: int, a: TLoc): TLabel =
  732. # generate a C-if statement for a Nim case statement
  733. var res: TLabel
  734. var labId = p.labels
  735. for i in 1..until:
  736. inc(p.labels)
  737. if t[i].kind == nkOfBranch: # else statement
  738. genCaseGenericBranch(p, t[i], a, rangeFormat, eqFormat,
  739. "LA" & rope(p.labels) & "_")
  740. else:
  741. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  742. if until < t.len-1:
  743. inc(p.labels)
  744. var gotoTarget = p.labels
  745. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(gotoTarget)])
  746. res = genCaseSecondPass(p, t, d, labId, until)
  747. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(gotoTarget)])
  748. else:
  749. res = genCaseSecondPass(p, t, d, labId, until)
  750. res
  751. template genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
  752. rangeFormat, eqFormat: FormatStr) =
  753. var a: TLoc
  754. initLocExpr(p, t[0], a)
  755. var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, t.len-1, a)
  756. fixLabel(p, lend)
  757. proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
  758. stringKind: TTypeKind,
  759. branches: var openArray[Rope]) =
  760. var x: TLoc
  761. for i in 0..<b.len - 1:
  762. assert(b[i].kind != nkRange)
  763. initLocExpr(p, b[i], x)
  764. var j: int
  765. case b[i].kind
  766. of nkStrLit..nkTripleStrLit:
  767. j = int(hashString(p.config, b[i].strVal) and high(branches))
  768. of nkNilLit: j = 0
  769. else:
  770. assert false, "invalid string case branch node kind"
  771. if stringKind == tyCstring:
  772. appcg(p.module, branches[j], "if (#eqCstrings($1, $2)) goto $3;$n",
  773. [rdLoc(e), rdLoc(x), labl])
  774. else:
  775. appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
  776. [rdLoc(e), rdLoc(x), labl])
  777. proc genStringCase(p: BProc, t: PNode, stringKind: TTypeKind, d: var TLoc) =
  778. # count how many constant strings there are in the case:
  779. var strings = 0
  780. for i in 1..<t.len:
  781. if t[i].kind == nkOfBranch: inc(strings, t[i].len - 1)
  782. if strings > stringCaseThreshold:
  783. var bitMask = math.nextPowerOfTwo(strings) - 1
  784. var branches: seq[Rope]
  785. newSeq(branches, bitMask + 1)
  786. var a: TLoc
  787. initLocExpr(p, t[0], a) # fist pass: generate ifs+goto:
  788. var labId = p.labels
  789. for i in 1..<t.len:
  790. inc(p.labels)
  791. if t[i].kind == nkOfBranch:
  792. genCaseStringBranch(p, t[i], a, "LA" & rope(p.labels) & "_",
  793. stringKind, branches)
  794. else:
  795. # else statement: nothing to do yet
  796. # but we reserved a label, which we use later
  797. discard
  798. if stringKind == tyCstring:
  799. linefmt(p, cpsStmts, "switch (#hashCstring($1) & $2) {$n",
  800. [rdLoc(a), bitMask])
  801. else:
  802. linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
  803. [rdLoc(a), bitMask])
  804. for j in 0..high(branches):
  805. if branches[j] != "":
  806. var lit = newRopeAppender()
  807. intLiteral(j, lit)
  808. lineF(p, cpsStmts, "case $1: $n$2break;$n",
  809. [lit, branches[j]])
  810. lineF(p, cpsStmts, "}$n", []) # else statement:
  811. if t[^1].kind != nkOfBranch:
  812. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  813. # third pass: generate statements
  814. var lend = genCaseSecondPass(p, t, d, labId, t.len-1)
  815. fixLabel(p, lend)
  816. else:
  817. if stringKind == tyCstring:
  818. genCaseGeneric(p, t, d, "", "if (#eqCstrings($1, $2)) goto $3;$n")
  819. else:
  820. genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
  821. proc branchHasTooBigRange(b: PNode): bool =
  822. for it in b:
  823. # last son is block
  824. if (it.kind == nkRange) and
  825. it[1].intVal - it[0].intVal > RangeExpandLimit:
  826. return true
  827. proc ifSwitchSplitPoint(p: BProc, n: PNode): int =
  828. for i in 1..<n.len:
  829. var branch = n[i]
  830. var stmtBlock = lastSon(branch)
  831. if stmtBlock.stmtsContainPragma(wLinearScanEnd):
  832. result = i
  833. elif hasSwitchRange notin CC[p.config.cCompiler].props:
  834. if branch.kind == nkOfBranch and branchHasTooBigRange(branch):
  835. result = i
  836. proc genCaseRange(p: BProc, branch: PNode) =
  837. for j in 0..<branch.len-1:
  838. if branch[j].kind == nkRange:
  839. if hasSwitchRange in CC[p.config.cCompiler].props:
  840. var litA = newRopeAppender()
  841. var litB = newRopeAppender()
  842. genLiteral(p, branch[j][0], litA)
  843. genLiteral(p, branch[j][1], litB)
  844. lineF(p, cpsStmts, "case $1 ... $2:$n", [litA, litB])
  845. else:
  846. var v = copyNode(branch[j][0])
  847. while v.intVal <= branch[j][1].intVal:
  848. var litA = newRopeAppender()
  849. genLiteral(p, v, litA)
  850. lineF(p, cpsStmts, "case $1:$n", [litA])
  851. inc(v.intVal)
  852. else:
  853. var litA = newRopeAppender()
  854. genLiteral(p, branch[j], litA)
  855. lineF(p, cpsStmts, "case $1:$n", [litA])
  856. proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
  857. # analyse 'case' statement:
  858. var splitPoint = ifSwitchSplitPoint(p, n)
  859. # generate if part (might be empty):
  860. var a: TLoc
  861. initLocExpr(p, n[0], a)
  862. var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
  863. rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  864. eqFormat = "if ($1 == $2) goto $3;$n",
  865. splitPoint, a) else: ""
  866. # generate switch part (might be empty):
  867. if splitPoint+1 < n.len:
  868. lineF(p, cpsStmts, "switch ($1) {$n", [rdCharLoc(a)])
  869. var hasDefault = false
  870. for i in splitPoint+1..<n.len:
  871. # bug #4230: avoid false sharing between branches:
  872. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  873. var branch = n[i]
  874. if branch.kind == nkOfBranch:
  875. genCaseRange(p, branch)
  876. else:
  877. # else part of case statement:
  878. lineF(p, cpsStmts, "default:$n", [])
  879. hasDefault = true
  880. exprBlock(p, branch.lastSon, d)
  881. lineF(p, cpsStmts, "break;$n", [])
  882. if not hasDefault:
  883. if hasBuiltinUnreachable in CC[p.config.cCompiler].props:
  884. lineF(p, cpsStmts, "default: __builtin_unreachable();$n", [])
  885. elif hasAssume in CC[p.config.cCompiler].props:
  886. lineF(p, cpsStmts, "default: __assume(0);$n", [])
  887. lineF(p, cpsStmts, "}$n", [])
  888. if lend != "": fixLabel(p, lend)
  889. proc genCase(p: BProc, t: PNode, d: var TLoc) =
  890. genLineDir(p, t)
  891. if not isEmptyType(t.typ) and d.k == locNone:
  892. getTemp(p, t.typ, d)
  893. case skipTypes(t[0].typ, abstractVarRange).kind
  894. of tyString:
  895. genStringCase(p, t, tyString, d)
  896. of tyCstring:
  897. genStringCase(p, t, tyCstring, d)
  898. of tyFloat..tyFloat128:
  899. genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  900. "if ($1 == $2) goto $3;$n")
  901. else:
  902. if t[0].kind == nkSym and sfGoto in t[0].sym.flags:
  903. genGotoForCase(p, t)
  904. else:
  905. genOrdinalCase(p, t, d)
  906. proc genRestoreFrameAfterException(p: BProc) =
  907. if optStackTrace in p.module.config.options:
  908. if hasCurFramePointer notin p.flags:
  909. p.flags.incl hasCurFramePointer
  910. p.procSec(cpsLocals).add(ropecg(p.module, "\tTFrame* _nimCurFrame;$n", []))
  911. p.procSec(cpsInit).add(ropecg(p.module, "\t_nimCurFrame = #getFrame();$n", []))
  912. linefmt(p, cpsStmts, "#setFrame(_nimCurFrame);$n", [])
  913. proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
  914. #[ code to generate:
  915. std::exception_ptr error;
  916. try {
  917. body;
  918. } catch (Exception e) {
  919. error = std::current_exception();
  920. if (ofExpr(e, TypeHere)) {
  921. error = nullptr; // handled
  922. } else if (...) {
  923. } else {
  924. throw;
  925. }
  926. } catch(...) {
  927. // C++ exception occured, not under Nim's control.
  928. }
  929. {
  930. /* finally: */
  931. printf('fin!\n');
  932. if (error) std::rethrow_exception(error); // re-raise the exception
  933. }
  934. ]#
  935. p.module.includeHeader("<exception>")
  936. if not isEmptyType(t.typ) and d.k == locNone:
  937. getTemp(p, t.typ, d)
  938. genLineDir(p, t)
  939. inc(p.labels, 2)
  940. let etmp = p.labels
  941. lineCg(p, cpsStmts, "std::exception_ptr T$1_;$n", [etmp])
  942. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  943. p.nestedTryStmts.add((fin, false, 0.Natural))
  944. if t.kind == nkHiddenTryStmt:
  945. lineCg(p, cpsStmts, "try {$n", [])
  946. expr(p, t[0], d)
  947. lineCg(p, cpsStmts, "}$n", [])
  948. else:
  949. startBlock(p, "try {$n")
  950. expr(p, t[0], d)
  951. endBlock(p)
  952. # First pass: handle Nim based exceptions:
  953. lineCg(p, cpsStmts, "catch (#Exception* T$1_) {$n", [etmp+1])
  954. genRestoreFrameAfterException(p)
  955. # an unhandled exception happened!
  956. lineCg(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  957. p.nestedTryStmts[^1].inExcept = true
  958. var hasImportedCppExceptions = false
  959. var i = 1
  960. var hasIf = false
  961. var hasElse = false
  962. while (i < t.len) and (t[i].kind == nkExceptBranch):
  963. # bug #4230: avoid false sharing between branches:
  964. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  965. if t[i].len == 1:
  966. hasImportedCppExceptions = true
  967. # general except section:
  968. hasElse = true
  969. if hasIf: lineF(p, cpsStmts, "else ", [])
  970. startBlock(p)
  971. # we handled the error:
  972. expr(p, t[i][0], d)
  973. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  974. endBlock(p)
  975. else:
  976. var orExpr = newRopeAppender()
  977. var exvar = PNode(nil)
  978. for j in 0..<t[i].len - 1:
  979. var typeNode = t[i][j]
  980. if t[i][j].isInfixAs():
  981. typeNode = t[i][j][1]
  982. exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  983. assert(typeNode.kind == nkType)
  984. if isImportedException(typeNode.typ, p.config):
  985. hasImportedCppExceptions = true
  986. else:
  987. if orExpr.len != 0: orExpr.add("||")
  988. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  989. if optTinyRtti in p.config.globalOptions:
  990. let checkFor = $getObjDepth(typeNode.typ)
  991. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(typeNode.typ, p.config)))])
  992. else:
  993. let checkFor = genTypeInfoV1(p.module, typeNode.typ, typeNode.info)
  994. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  995. if orExpr.len != 0:
  996. if hasIf:
  997. startBlock(p, "else if ($1) {$n", [orExpr])
  998. else:
  999. startBlock(p, "if ($1) {$n", [orExpr])
  1000. hasIf = true
  1001. if exvar != nil:
  1002. fillLocalName(p, exvar.sym)
  1003. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1004. linefmt(p, cpsStmts, "$1 $2 = T$3_;$n", [getTypeDesc(p.module, exvar.sym.typ),
  1005. rdLoc(exvar.sym.loc), rope(etmp+1)])
  1006. # we handled the error:
  1007. linefmt(p, cpsStmts, "T$1_ = nullptr;$n", [etmp])
  1008. expr(p, t[i][^1], d)
  1009. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1010. endBlock(p)
  1011. inc(i)
  1012. if hasIf and not hasElse:
  1013. linefmt(p, cpsStmts, "else throw;$n", [etmp])
  1014. linefmt(p, cpsStmts, "}$n", [])
  1015. # Second pass: handle C++ based exceptions:
  1016. template genExceptBranchBody(body: PNode) {.dirty.} =
  1017. genRestoreFrameAfterException(p)
  1018. #linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1019. expr(p, body, d)
  1020. var catchAllPresent = false
  1021. incl p.flags, noSafePoints # mark as not needing 'popCurrentException'
  1022. if hasImportedCppExceptions:
  1023. for i in 1..<t.len:
  1024. if t[i].kind != nkExceptBranch: break
  1025. # bug #4230: avoid false sharing between branches:
  1026. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1027. if t[i].len == 1:
  1028. # general except section:
  1029. startBlock(p, "catch (...) {$n", [])
  1030. genExceptBranchBody(t[i][0])
  1031. endBlock(p)
  1032. catchAllPresent = true
  1033. else:
  1034. for j in 0..<t[i].len-1:
  1035. var typeNode = t[i][j]
  1036. if t[i][j].isInfixAs():
  1037. typeNode = t[i][j][1]
  1038. if isImportedException(typeNode.typ, p.config):
  1039. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1040. fillLocalName(p, exvar.sym)
  1041. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1042. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, typeNode.typ), rdLoc(exvar.sym.loc))
  1043. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1044. endBlock(p)
  1045. elif isImportedException(typeNode.typ, p.config):
  1046. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1047. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1048. endBlock(p)
  1049. excl p.flags, noSafePoints
  1050. discard pop(p.nestedTryStmts)
  1051. # general finally block:
  1052. if t.len > 0 and t[^1].kind == nkFinally:
  1053. if not catchAllPresent:
  1054. startBlock(p, "catch (...) {$n", [])
  1055. genRestoreFrameAfterException(p)
  1056. linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1057. endBlock(p)
  1058. startBlock(p)
  1059. genStmts(p, t[^1][0])
  1060. linefmt(p, cpsStmts, "if (T$1_) std::rethrow_exception(T$1_);$n", [etmp])
  1061. endBlock(p)
  1062. proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
  1063. # There are two versions we generate, depending on whether we
  1064. # catch C++ exceptions, imported via .importcpp or not. The
  1065. # code can be easier if there are no imported C++ exceptions
  1066. # to deal with.
  1067. # code to generate:
  1068. #
  1069. # try
  1070. # {
  1071. # myDiv(4, 9);
  1072. # } catch (NimExceptionType1&) {
  1073. # body
  1074. # } catch (NimExceptionType2&) {
  1075. # finallyPart()
  1076. # raise;
  1077. # }
  1078. # catch(...) {
  1079. # general_handler_body
  1080. # }
  1081. # finallyPart();
  1082. template genExceptBranchBody(body: PNode) {.dirty.} =
  1083. genRestoreFrameAfterException(p)
  1084. expr(p, body, d)
  1085. if not isEmptyType(t.typ) and d.k == locNone:
  1086. getTemp(p, t.typ, d)
  1087. genLineDir(p, t)
  1088. cgsym(p.module, "popCurrentExceptionEx")
  1089. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1090. p.nestedTryStmts.add((fin, false, 0.Natural))
  1091. startBlock(p, "try {$n")
  1092. expr(p, t[0], d)
  1093. endBlock(p)
  1094. var catchAllPresent = false
  1095. p.nestedTryStmts[^1].inExcept = true
  1096. for i in 1..<t.len:
  1097. if t[i].kind != nkExceptBranch: break
  1098. # bug #4230: avoid false sharing between branches:
  1099. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1100. if t[i].len == 1:
  1101. # general except section:
  1102. catchAllPresent = true
  1103. startBlock(p, "catch (...) {$n")
  1104. genExceptBranchBody(t[i][0])
  1105. endBlock(p)
  1106. else:
  1107. for j in 0..<t[i].len-1:
  1108. if t[i][j].isInfixAs():
  1109. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1110. fillLocalName(p, exvar.sym)
  1111. fillLoc(exvar.sym.loc, locTemp, exvar, OnUnknown)
  1112. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
  1113. else:
  1114. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1115. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1116. endBlock(p)
  1117. discard pop(p.nestedTryStmts)
  1118. if t[^1].kind == nkFinally:
  1119. # c++ does not have finally, therefore code needs to be generated twice
  1120. if not catchAllPresent:
  1121. # finally requires catch all presence
  1122. startBlock(p, "catch (...) {$n")
  1123. genStmts(p, t[^1][0])
  1124. line(p, cpsStmts, "throw;\n")
  1125. endBlock(p)
  1126. genSimpleBlock(p, t[^1][0])
  1127. proc bodyCanRaise(p: BProc; n: PNode): bool =
  1128. case n.kind
  1129. of nkCallKinds:
  1130. result = canRaiseDisp(p, n[0])
  1131. if not result:
  1132. # also check the arguments:
  1133. for i in 1 ..< n.len:
  1134. if bodyCanRaise(p, n[i]): return true
  1135. of nkRaiseStmt:
  1136. result = true
  1137. of nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef,
  1138. nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  1139. result = false
  1140. else:
  1141. for i in 0 ..< safeLen(n):
  1142. if bodyCanRaise(p, n[i]): return true
  1143. result = false
  1144. proc genTryGoto(p: BProc; t: PNode; d: var TLoc) =
  1145. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1146. inc p.labels
  1147. let lab = p.labels
  1148. let hasExcept = t[1].kind == nkExceptBranch
  1149. if hasExcept: inc p.withinTryWithExcept
  1150. p.nestedTryStmts.add((fin, false, Natural lab))
  1151. p.flags.incl nimErrorFlagAccessed
  1152. if not isEmptyType(t.typ) and d.k == locNone:
  1153. getTemp(p, t.typ, d)
  1154. expr(p, t[0], d)
  1155. if 1 < t.len and t[1].kind == nkExceptBranch:
  1156. startBlock(p, "if (NIM_UNLIKELY(*nimErr_)) {$n")
  1157. else:
  1158. startBlock(p)
  1159. linefmt(p, cpsStmts, "LA$1_:;$n", [lab])
  1160. p.nestedTryStmts[^1].inExcept = true
  1161. var i = 1
  1162. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1163. inc p.labels
  1164. let nextExcept = p.labels
  1165. p.nestedTryStmts[^1].label = nextExcept
  1166. # bug #4230: avoid false sharing between branches:
  1167. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1168. if t[i].len == 1:
  1169. # general except section:
  1170. if i > 1: lineF(p, cpsStmts, "else", [])
  1171. startBlock(p)
  1172. # we handled the exception, remember this:
  1173. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1174. expr(p, t[i][0], d)
  1175. else:
  1176. var orExpr = newRopeAppender()
  1177. for j in 0..<t[i].len - 1:
  1178. assert(t[i][j].kind == nkType)
  1179. if orExpr.len != 0: orExpr.add("||")
  1180. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1181. if optTinyRtti in p.config.globalOptions:
  1182. let checkFor = $getObjDepth(t[i][j].typ)
  1183. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)",
  1184. [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1185. else:
  1186. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1187. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1188. if i > 1: line(p, cpsStmts, "else ")
  1189. startBlock(p, "if ($1) {$n", [orExpr])
  1190. # we handled the exception, remember this:
  1191. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1192. expr(p, t[i][^1], d)
  1193. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1194. linefmt(p, cpsStmts, "LA$1_:;$n", [nextExcept])
  1195. endBlock(p)
  1196. inc(i)
  1197. discard pop(p.nestedTryStmts)
  1198. endBlock(p)
  1199. if i < t.len and t[i].kind == nkFinally:
  1200. startBlock(p)
  1201. if not bodyCanRaise(p, t[i][0]):
  1202. # this is an important optimization; most destroy blocks are detected not to raise an
  1203. # exception and so we help the C optimizer by not mutating nimErr_ pointlessly:
  1204. genStmts(p, t[i][0])
  1205. else:
  1206. # pretend we did handle the error for the safe execution of the 'finally' section:
  1207. p.procSec(cpsLocals).add(ropecg(p.module, "NIM_BOOL oldNimErrFin$1_;$n", [lab]))
  1208. linefmt(p, cpsStmts, "oldNimErrFin$1_ = *nimErr_; *nimErr_ = NIM_FALSE;$n", [lab])
  1209. genStmts(p, t[i][0])
  1210. # this is correct for all these cases:
  1211. # 1. finally is run during ordinary control flow
  1212. # 2. finally is run after 'except' block handling: these however set the
  1213. # error back to nil.
  1214. # 3. finally is run for exception handling code without any 'except'
  1215. # handler present or only handlers that did not match.
  1216. linefmt(p, cpsStmts, "*nimErr_ = oldNimErrFin$1_;$n", [lab])
  1217. endBlock(p)
  1218. raiseExit(p)
  1219. if hasExcept: inc p.withinTryWithExcept
  1220. proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
  1221. # code to generate:
  1222. #
  1223. # XXX: There should be a standard dispatch algorithm
  1224. # that's used both here and with multi-methods
  1225. #
  1226. # TSafePoint sp;
  1227. # pushSafePoint(&sp);
  1228. # sp.status = setjmp(sp.context);
  1229. # if (sp.status == 0) {
  1230. # myDiv(4, 9);
  1231. # popSafePoint();
  1232. # } else {
  1233. # popSafePoint();
  1234. # /* except DivisionByZero: */
  1235. # if (sp.status == DivisionByZero) {
  1236. # printf('Division by Zero\n');
  1237. # clearException();
  1238. # } else {
  1239. # clearException();
  1240. # }
  1241. # }
  1242. # {
  1243. # /* finally: */
  1244. # printf('fin!\n');
  1245. # }
  1246. # if (exception not cleared)
  1247. # propagateCurrentException();
  1248. #
  1249. if not isEmptyType(t.typ) and d.k == locNone:
  1250. getTemp(p, t.typ, d)
  1251. let quirkyExceptions = p.config.exc == excQuirky or
  1252. (t.kind == nkHiddenTryStmt and sfSystemModule in p.module.module.flags)
  1253. if not quirkyExceptions:
  1254. p.module.includeHeader("<setjmp.h>")
  1255. else:
  1256. p.flags.incl noSafePoints
  1257. genLineDir(p, t)
  1258. cgsym(p.module, "Exception")
  1259. var safePoint: Rope
  1260. if not quirkyExceptions:
  1261. safePoint = getTempName(p.module)
  1262. linefmt(p, cpsLocals, "#TSafePoint $1;$n", [safePoint])
  1263. linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", [safePoint])
  1264. if isDefined(p.config, "nimStdSetjmp"):
  1265. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1266. elif isDefined(p.config, "nimSigSetjmp"):
  1267. linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", [safePoint])
  1268. elif isDefined(p.config, "nimBuiltinSetjmp"):
  1269. linefmt(p, cpsStmts, "$1.status = __builtin_setjmp($1.context);$n", [safePoint])
  1270. elif isDefined(p.config, "nimRawSetjmp"):
  1271. if isDefined(p.config, "mswindows"):
  1272. if isDefined(p.config, "vcc") or isDefined(p.config, "clangcl"):
  1273. # For the vcc compiler, use `setjmp()` with one argument.
  1274. # See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setjmp?view=msvc-170
  1275. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1276. else:
  1277. # The Windows `_setjmp()` takes two arguments, with the second being an
  1278. # undocumented buffer used by the SEH mechanism for stack unwinding.
  1279. # Mingw-w64 has been trying to get it right for years, but it's still
  1280. # prone to stack corruption during unwinding, so we disable that by setting
  1281. # it to NULL.
  1282. # More details: https://github.com/status-im/nimbus-eth2/issues/3121
  1283. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context, 0);$n", [safePoint])
  1284. else:
  1285. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", [safePoint])
  1286. else:
  1287. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1288. lineCg(p, cpsStmts, "if ($1.status == 0) {$n", [safePoint])
  1289. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1290. p.nestedTryStmts.add((fin, quirkyExceptions, 0.Natural))
  1291. expr(p, t[0], d)
  1292. if not quirkyExceptions:
  1293. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1294. lineCg(p, cpsStmts, "}$n", [])
  1295. startBlock(p, "else {$n")
  1296. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1297. genRestoreFrameAfterException(p)
  1298. elif 1 < t.len and t[1].kind == nkExceptBranch:
  1299. startBlock(p, "if (#nimBorrowCurrentException()) {$n")
  1300. else:
  1301. startBlock(p)
  1302. p.nestedTryStmts[^1].inExcept = true
  1303. var i = 1
  1304. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1305. # bug #4230: avoid false sharing between branches:
  1306. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1307. if t[i].len == 1:
  1308. # general except section:
  1309. if i > 1: lineF(p, cpsStmts, "else", [])
  1310. startBlock(p)
  1311. if not quirkyExceptions:
  1312. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1313. expr(p, t[i][0], d)
  1314. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1315. endBlock(p)
  1316. else:
  1317. var orExpr = newRopeAppender()
  1318. for j in 0..<t[i].len - 1:
  1319. assert(t[i][j].kind == nkType)
  1320. if orExpr.len != 0: orExpr.add("||")
  1321. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1322. if optTinyRtti in p.config.globalOptions:
  1323. let checkFor = $getObjDepth(t[i][j].typ)
  1324. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1325. else:
  1326. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1327. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1328. if i > 1: line(p, cpsStmts, "else ")
  1329. startBlock(p, "if ($1) {$n", [orExpr])
  1330. if not quirkyExceptions:
  1331. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1332. expr(p, t[i][^1], d)
  1333. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1334. endBlock(p)
  1335. inc(i)
  1336. discard pop(p.nestedTryStmts)
  1337. endBlock(p) # end of else block
  1338. if i < t.len and t[i].kind == nkFinally:
  1339. p.finallySafePoints.add(safePoint)
  1340. startBlock(p)
  1341. genStmts(p, t[i][0])
  1342. # pretend we handled the exception in a 'finally' so that we don't
  1343. # re-raise the unhandled one but instead keep the old one (it was
  1344. # not popped either):
  1345. if not quirkyExceptions and getCompilerProc(p.module.g.graph, "nimLeaveFinally") != nil:
  1346. linefmt(p, cpsStmts, "if ($1.status != 0) #nimLeaveFinally();$n", [safePoint])
  1347. endBlock(p)
  1348. discard pop(p.finallySafePoints)
  1349. if not quirkyExceptions:
  1350. linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", [safePoint])
  1351. proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) =
  1352. var res = ""
  1353. for it in t.sons:
  1354. case it.kind
  1355. of nkStrLit..nkTripleStrLit:
  1356. res.add(it.strVal)
  1357. of nkSym:
  1358. var sym = it.sym
  1359. if sym.kind in {skProc, skFunc, skIterator, skMethod}:
  1360. var a: TLoc
  1361. initLocExpr(p, it, a)
  1362. res.add($rdLoc(a))
  1363. elif sym.kind == skType:
  1364. res.add($getTypeDesc(p.module, sym.typ))
  1365. else:
  1366. discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
  1367. fillBackendName(p.module, sym)
  1368. res.add($sym.loc.r)
  1369. of nkTypeOfExpr:
  1370. res.add($getTypeDesc(p.module, it.typ))
  1371. else:
  1372. discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs))
  1373. var a: TLoc
  1374. initLocExpr(p, it, a)
  1375. res.add($a.rdLoc)
  1376. if isAsmStmt and hasGnuAsm in CC[p.config.cCompiler].props:
  1377. for x in splitLines(res):
  1378. var j = 0
  1379. while j < x.len and x[j] in {' ', '\t'}: inc(j)
  1380. if j < x.len:
  1381. if x[j] in {'"', ':'}:
  1382. # don't modify the line if already in quotes or
  1383. # some clobber register list:
  1384. result.add(x); result.add("\L")
  1385. else:
  1386. # ignore empty lines
  1387. result.add("\"")
  1388. result.add(x.replace("\"", "\\\""))
  1389. result.add("\\n\"\n")
  1390. else:
  1391. res.add("\L")
  1392. result.add res.rope
  1393. proc genAsmStmt(p: BProc, t: PNode) =
  1394. assert(t.kind == nkAsmStmt)
  1395. genLineDir(p, t)
  1396. var s = newRopeAppender()
  1397. genAsmOrEmitStmt(p, t, isAsmStmt=true, s)
  1398. # see bug #2362, "top level asm statements" seem to be a mis-feature
  1399. # but even if we don't do this, the example in #2362 cannot possibly
  1400. # work:
  1401. if p.prc == nil:
  1402. # top level asm statement?
  1403. p.module.s[cfsProcHeaders].add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1404. else:
  1405. addIndent p, p.s(cpsStmts)
  1406. p.s(cpsStmts).add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1407. proc determineSection(n: PNode): TCFileSection =
  1408. result = cfsProcHeaders
  1409. if n.len >= 1 and n[0].kind in {nkStrLit..nkTripleStrLit}:
  1410. let sec = n[0].strVal
  1411. if sec.startsWith("/*TYPESECTION*/"): result = cfsForwardTypes # TODO WORKAROUND
  1412. elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
  1413. elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
  1414. proc genEmit(p: BProc, t: PNode) =
  1415. var s = newRopeAppender()
  1416. genAsmOrEmitStmt(p, t[1], false, s)
  1417. if p.prc == nil:
  1418. # top level emit pragma?
  1419. let section = determineSection(t[1])
  1420. genCLineDir(p.module.s[section], t.info, p.config)
  1421. p.module.s[section].add(s)
  1422. else:
  1423. genLineDir(p, t)
  1424. line(p, cpsStmts, s)
  1425. proc genPragma(p: BProc, n: PNode) =
  1426. for i in 0..<n.len:
  1427. let it = n[i]
  1428. case whichPragma(it)
  1429. of wEmit: genEmit(p, it)
  1430. of wPush:
  1431. processPushBackendOption(p.optionsStack, p.options, n, i+1)
  1432. of wPop:
  1433. processPopBackendOption(p.optionsStack, p.options)
  1434. else: discard
  1435. proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
  1436. field: PSym) =
  1437. var t = skipTypes(objtype, abstractVar)
  1438. assert t.kind == tyObject
  1439. discard genTypeInfoV1(p.module, t, a.lode.info)
  1440. if not containsOrIncl(p.module.declaredThings, field.id):
  1441. appcg(p.module, cfsVars, "extern $1",
  1442. [discriminatorTableDecl(p.module, t, field)])
  1443. var lit = newRopeAppender()
  1444. intLiteral(toInt64(lengthOrd(p.config, field.typ))+1, lit)
  1445. lineCg(p, cpsStmts,
  1446. "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
  1447. [rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
  1448. lit])
  1449. if p.config.exc == excGoto:
  1450. raiseExit(p)
  1451. when false:
  1452. proc genCaseObjDiscMapping(p: BProc, e: PNode, t: PType, field: PSym; d: var TLoc) =
  1453. const ObjDiscMappingProcSlot = -5
  1454. var theProc: PSym = nil
  1455. for idx, p in items(t.methods):
  1456. if idx == ObjDiscMappingProcSlot:
  1457. theProc = p
  1458. break
  1459. if theProc == nil:
  1460. theProc = genCaseObjDiscMapping(t, field, e.info, p.module.g.graph, p.module.idgen)
  1461. t.methods.add((ObjDiscMappingProcSlot, theProc))
  1462. var call = newNodeIT(nkCall, e.info, getSysType(p.module.g.graph, e.info, tyUInt8))
  1463. call.add newSymNode(theProc)
  1464. call.add e
  1465. expr(p, call, d)
  1466. proc asgnFieldDiscriminant(p: BProc, e: PNode) =
  1467. var a, tmp: TLoc
  1468. var dotExpr = e[0]
  1469. if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr[0]
  1470. initLocExpr(p, e[0], a)
  1471. getTemp(p, a.t, tmp)
  1472. expr(p, e[1], tmp)
  1473. if p.inUncheckedAssignSection == 0:
  1474. let field = dotExpr[1].sym
  1475. genDiscriminantCheck(p, a, tmp, dotExpr[0].typ, field)
  1476. message(p.config, e.info, warnCaseTransition)
  1477. genAssignment(p, a, tmp, {})
  1478. proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
  1479. if e[0].kind == nkSym and sfGoto in e[0].sym.flags:
  1480. genLineDir(p, e)
  1481. genGotoVar(p, e[1])
  1482. elif optFieldCheck in p.options and isDiscriminantField(e[0]):
  1483. genLineDir(p, e)
  1484. asgnFieldDiscriminant(p, e)
  1485. else:
  1486. let le = e[0]
  1487. let ri = e[1]
  1488. var a: TLoc
  1489. discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs), dkVar)
  1490. initLoc(a, locNone, le, OnUnknown)
  1491. a.flags.incl(lfEnforceDeref)
  1492. a.flags.incl(lfPrepareForMutation)
  1493. genLineDir(p, le) # it can be a nkBracketExpr, which may raise
  1494. expr(p, le, a)
  1495. a.flags.excl(lfPrepareForMutation)
  1496. if fastAsgn: incl(a.flags, lfNoDeepCopy)
  1497. assert(a.t != nil)
  1498. genLineDir(p, ri)
  1499. loadInto(p, le, ri, a)
  1500. proc genStmts(p: BProc, t: PNode) =
  1501. var a: TLoc
  1502. let isPush = p.config.hasHint(hintExtendedContext)
  1503. if isPush: pushInfoContext(p.config, t.info)
  1504. expr(p, t, a)
  1505. if isPush: popInfoContext(p.config)
  1506. internalAssert p.config, a.k in {locNone, locTemp, locLocalVar, locExpr}