ccgstmts.nim 61 KB

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