ccgstmts.nim 58 KB

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