ccgstmts.nim 59 KB

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