ccgstmts.nim 55 KB

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