ccgstmts.nim 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  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 registerGcRoot(p: BProc, v: PSym) =
  16. if p.config.selectedGC in {gcMarkAndSweep, gcDestructors, gcV2, gcRefc} and
  17. containsGarbageCollectedRef(v.loc.t):
  18. # we register a specialized marked proc here; this has the advantage
  19. # that it works out of the box for thread local storage then :-)
  20. let prc = genTraverseProcForGlobal(p.module, v, v.info)
  21. if sfThread in v.flags:
  22. appcg(p.module, p.module.initProc.procSec(cpsInit),
  23. "#nimRegisterThreadLocalMarker($1);$n", [prc])
  24. else:
  25. appcg(p.module, p.module.initProc.procSec(cpsInit),
  26. "#nimRegisterGlobalMarker($1);$n", [prc])
  27. proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} =
  28. if n.kind == nkEmpty: return false
  29. if isInvalidReturnType(conf, n.typ):
  30. # var v = f()
  31. # is transformed into: var v; f(addr v)
  32. # where 'f' **does not** initialize the result!
  33. return false
  34. result = true
  35. proc inExceptBlockLen(p: BProc): int =
  36. for x in p.nestedTryStmts:
  37. if x.inExcept: result.inc
  38. proc genVarTuple(p: BProc, n: PNode) =
  39. var tup, field: TLoc
  40. if n.kind != nkVarTuple: internalError(p.config, n.info, "genVarTuple")
  41. var L = sonsLen(n)
  42. # if we have a something that's been captured, use the lowering instead:
  43. for i in countup(0, L-3):
  44. if n[i].kind != nkSym:
  45. genStmts(p, lowerTupleUnpacking(p.module.g.graph, n, p.prc))
  46. return
  47. genLineDir(p, n)
  48. initLocExpr(p, n.sons[L-1], tup)
  49. var t = tup.t.skipTypes(abstractInst)
  50. for i in countup(0, L-3):
  51. let vn = n.sons[i]
  52. let v = vn.sym
  53. if sfCompileTime in v.flags: continue
  54. if sfGlobal in v.flags:
  55. assignGlobalVar(p, vn)
  56. genObjectInit(p, cpsInit, v.typ, v.loc, true)
  57. registerGcRoot(p, v)
  58. else:
  59. assignLocalVar(p, vn)
  60. initLocalVar(p, v, immediateAsgn=isAssignedImmediately(p.config, n[L-1]))
  61. initLoc(field, locExpr, vn, tup.storage)
  62. if t.kind == tyTuple:
  63. field.r = "$1.Field$2" % [rdLoc(tup), rope(i)]
  64. else:
  65. if t.n.sons[i].kind != nkSym: internalError(p.config, n.info, "genVarTuple")
  66. field.r = "$1.$2" % [rdLoc(tup), mangleRecFieldName(p.module, t.n.sons[i].sym)]
  67. putLocIntoDest(p, v.loc, field)
  68. proc genDeref(p: BProc, e: PNode, d: var TLoc; enforceDeref=false)
  69. proc loadInto(p: BProc, le, ri: PNode, a: var TLoc) {.inline.} =
  70. if ri.kind in nkCallKinds and (ri.sons[0].kind != nkSym or
  71. ri.sons[0].sym.magic == mNone):
  72. genAsgnCall(p, le, ri, a)
  73. elif ri.kind in {nkDerefExpr, nkHiddenDeref}:
  74. # this is a hacky way to fix #1181 (tmissingderef)::
  75. #
  76. # var arr1 = cast[ptr array[4, int8]](addr foo)[]
  77. #
  78. # However, fixing this properly really requires modelling 'array' as
  79. # a 'struct' in C to preserve dereferencing semantics completely. Not
  80. # worth the effort until version 1.0 is out.
  81. genDeref(p, ri, a, enforceDeref=true)
  82. else:
  83. expr(p, ri, a)
  84. proc startBlock(p: BProc, start: FormatStr = "{$n",
  85. args: varargs[Rope]): int {.discardable.} =
  86. lineCg(p, cpsStmts, start, args)
  87. inc(p.labels)
  88. result = len(p.blocks)
  89. setLen(p.blocks, result + 1)
  90. p.blocks[result].id = p.labels
  91. p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16
  92. p.blocks[result].nestedExceptStmts = p.inExceptBlockLen.int16
  93. proc assignLabel(b: var TBlock): Rope {.inline.} =
  94. b.label = "LA" & b.id.rope
  95. result = b.label
  96. proc blockBody(b: var TBlock): Rope =
  97. result = b.sections[cpsLocals]
  98. if b.frameLen > 0:
  99. result.addf("FR_.len+=$1;$n", [b.frameLen.rope])
  100. result.add(b.sections[cpsInit])
  101. result.add(b.sections[cpsStmts])
  102. proc endBlock(p: BProc, blockEnd: Rope) =
  103. let topBlock = p.blocks.len-1
  104. # the block is merged into the parent block
  105. add(p.blocks[topBlock-1].sections[cpsStmts], p.blocks[topBlock].blockBody)
  106. setLen(p.blocks, topBlock)
  107. # this is done after the block is popped so $n is
  108. # properly indented when pretty printing is enabled
  109. line(p, cpsStmts, blockEnd)
  110. proc endBlock(p: BProc) =
  111. let topBlock = p.blocks.len - 1
  112. var blockEnd = if p.blocks[topBlock].label != nil:
  113. ropecg(p.module, "} $1: ;$n", p.blocks[topBlock].label)
  114. else:
  115. ~"}$n"
  116. let frameLen = p.blocks[topBlock].frameLen
  117. if frameLen > 0:
  118. blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope])
  119. endBlock(p, blockEnd)
  120. proc genSimpleBlock(p: BProc, stmts: PNode) {.inline.} =
  121. startBlock(p)
  122. genStmts(p, stmts)
  123. endBlock(p)
  124. proc exprBlock(p: BProc, n: PNode, d: var TLoc) =
  125. startBlock(p)
  126. expr(p, n, d)
  127. endBlock(p)
  128. template preserveBreakIdx(body: untyped): untyped =
  129. var oldBreakIdx = p.breakIdx
  130. body
  131. p.breakIdx = oldBreakIdx
  132. proc genState(p: BProc, n: PNode) =
  133. internalAssert p.config, n.len == 1
  134. let n0 = n[0]
  135. if n0.kind == nkIntLit:
  136. let idx = n.sons[0].intVal
  137. linefmt(p, cpsStmts, "STATE$1: ;$n", idx.rope)
  138. elif n0.kind == nkStrLit:
  139. linefmt(p, cpsStmts, "$1: ;$n", n0.strVal.rope)
  140. proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int) =
  141. # Called by return and break stmts.
  142. # Deals with issues faced when jumping out of try/except/finally stmts,
  143. var stack = newSeq[tuple[n: PNode, inExcept: bool]](0)
  144. for i in countup(1, howManyTrys):
  145. let tryStmt = p.nestedTryStmts.pop
  146. if not p.module.compileToCpp or optNoCppExceptions in p.config.globalOptions:
  147. # Pop safe points generated by try
  148. if not tryStmt.inExcept:
  149. linefmt(p, cpsStmts, "#popSafePoint();$n")
  150. # Pop this try-stmt of the list of nested trys
  151. # so we don't infinite recurse on it in the next step.
  152. stack.add(tryStmt)
  153. # Find finally-stmt for this try-stmt
  154. # and generate a copy of its sons
  155. var finallyStmt = lastSon(tryStmt.n)
  156. if finallyStmt.kind == nkFinally:
  157. genStmts(p, finallyStmt.sons[0])
  158. # push old elements again:
  159. for i in countdown(howManyTrys-1, 0):
  160. p.nestedTryStmts.add(stack[i])
  161. if not p.module.compileToCpp or optNoCppExceptions in p.config.globalOptions:
  162. # Pop exceptions that was handled by the
  163. # except-blocks we are in
  164. for i in countdown(howManyExcepts-1, 0):
  165. linefmt(p, cpsStmts, "#popCurrentException();$n")
  166. proc genGotoState(p: BProc, n: PNode) =
  167. # we resist the temptation to translate it into duff's device as it later
  168. # will be translated into computed gotos anyway for GCC at least:
  169. # switch (x.state) {
  170. # case 0: goto STATE0;
  171. # ...
  172. var a: TLoc
  173. initLocExpr(p, n.sons[0], a)
  174. lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)])
  175. p.beforeRetNeeded = true
  176. lineF(p, cpsStmts, "case -1:$n", [])
  177. blockLeaveActions(p,
  178. howManyTrys = p.nestedTryStmts.len,
  179. howManyExcepts = p.inExceptBlockLen)
  180. lineF(p, cpsStmts, " goto BeforeRet_;$n", [])
  181. var statesCounter = lastOrd(p.config, n.sons[0].typ)
  182. if n.len >= 2 and n[1].kind == nkIntLit:
  183. statesCounter = n[1].intVal
  184. let prefix = if n.len == 3 and n[2].kind == nkStrLit: n[2].strVal.rope
  185. else: rope"STATE"
  186. for i in 0i64 .. statesCounter:
  187. lineF(p, cpsStmts, "case $2: goto $1$2;$n", [prefix, rope(i)])
  188. lineF(p, cpsStmts, "}$n", [])
  189. proc genBreakState(p: BProc, n: PNode, d: var TLoc) =
  190. var a: TLoc
  191. initLoc(d, locExpr, n, OnUnknown)
  192. if n.sons[0].kind == nkClosure:
  193. initLocExpr(p, n.sons[0].sons[1], a)
  194. d.r = "(((NI*) $1)[1] < 0)" % [rdLoc(a)]
  195. else:
  196. initLocExpr(p, n.sons[0], a)
  197. # the environment is guaranteed to contain the 'state' field at offset 1:
  198. d.r = "((((NI*) $1.ClE_0)[1]) < 0)" % [rdLoc(a)]
  199. proc genGotoVar(p: BProc; value: PNode) =
  200. if value.kind notin {nkCharLit..nkUInt64Lit}:
  201. localError(p.config, value.info, "'goto' target must be a literal value")
  202. else:
  203. lineF(p, cpsStmts, "goto NIMSTATE_$#;$n", [value.intVal.rope])
  204. proc genSingleVar(p: BProc, a: PNode) =
  205. let vn = a.sons[0]
  206. let v = vn.sym
  207. if sfCompileTime in v.flags: return
  208. if sfGoto in v.flags:
  209. # translate 'var state {.goto.} = X' into 'goto LX':
  210. genGotoVar(p, a.sons[2])
  211. return
  212. var targetProc = p
  213. if sfGlobal in v.flags:
  214. if v.flags * {sfImportc, sfExportc} == {sfImportc} and
  215. a.sons[2].kind == nkEmpty and
  216. v.loc.flags * {lfHeader, lfNoDecl} != {}:
  217. return
  218. if sfPure in v.flags:
  219. # v.owner.kind != skModule:
  220. targetProc = p.module.preInitProc
  221. assignGlobalVar(targetProc, vn)
  222. # XXX: be careful here.
  223. # Global variables should not be zeromem-ed within loops
  224. # (see bug #20).
  225. # That's why we are doing the construction inside the preInitProc.
  226. # genObjectInit relies on the C runtime's guarantees that
  227. # global variables will be initialized to zero.
  228. var loc = v.loc
  229. # When the native TLS is unavailable, a global thread-local variable needs
  230. # one more layer of indirection in order to access the TLS block.
  231. # Only do this for complex types that may need a call to `objectInit`
  232. if sfThread in v.flags and emulatedThreadVars(p.config) and
  233. isComplexValueType(v.typ):
  234. initLocExprSingleUse(p.module.preInitProc, vn, loc)
  235. genObjectInit(p.module.preInitProc, cpsInit, v.typ, loc, true)
  236. # Alternative construction using default constructor (which may zeromem):
  237. # if sfImportc notin v.flags: constructLoc(p.module.preInitProc, v.loc)
  238. if sfExportc in v.flags and p.module.g.generatedHeader != nil:
  239. genVarPrototype(p.module.g.generatedHeader, vn)
  240. registerGcRoot(p, v)
  241. else:
  242. let value = a.sons[2]
  243. let imm = isAssignedImmediately(p.config, value)
  244. if imm and p.module.compileToCpp and p.splitDecls == 0 and
  245. not containsHiddenPointer(v.typ):
  246. # C++ really doesn't like things like 'Foo f; f = x' as that invokes a
  247. # parameterless constructor followed by an assignment operator. So we
  248. # generate better code here: 'Foo f = x;'
  249. genLineDir(p, a)
  250. let decl = localVarDecl(p, vn)
  251. var tmp: TLoc
  252. if value.kind in nkCallKinds and value[0].kind == nkSym and
  253. sfConstructor in value[0].sym.flags:
  254. var params: Rope
  255. let typ = skipTypes(value.sons[0].typ, abstractInst)
  256. assert(typ.kind == tyProc)
  257. for i in 1..<value.len:
  258. if params != nil: params.add(~", ")
  259. assert(sonsLen(typ) == sonsLen(typ.n))
  260. add(params, genOtherArg(p, value, i, typ))
  261. if params == nil:
  262. lineF(p, cpsStmts, "$#;$n", [decl])
  263. else:
  264. lineF(p, cpsStmts, "$#($#);$n", [decl, params])
  265. else:
  266. initLocExprSingleUse(p, value, tmp)
  267. lineF(p, cpsStmts, "$# = $#;$n", [decl, tmp.rdLoc])
  268. return
  269. assignLocalVar(p, vn)
  270. initLocalVar(p, v, imm)
  271. if a.sons[2].kind != nkEmpty:
  272. genLineDir(targetProc, a)
  273. loadInto(targetProc, a.sons[0], a.sons[2], v.loc)
  274. proc genClosureVar(p: BProc, a: PNode) =
  275. var immediateAsgn = a.sons[2].kind != nkEmpty
  276. var v: TLoc
  277. initLocExpr(p, a.sons[0], v)
  278. genLineDir(p, a)
  279. if immediateAsgn:
  280. loadInto(p, a.sons[0], a.sons[2], v)
  281. else:
  282. constructLoc(p, v)
  283. proc genVarStmt(p: BProc, n: PNode) =
  284. for it in n.sons:
  285. if it.kind == nkCommentStmt: continue
  286. if it.kind == nkIdentDefs:
  287. # can be a lifted var nowadays ...
  288. if it.sons[0].kind == nkSym:
  289. genSingleVar(p, it)
  290. else:
  291. genClosureVar(p, it)
  292. else:
  293. genVarTuple(p, it)
  294. proc genIf(p: BProc, n: PNode, d: var TLoc) =
  295. #
  296. # { if (!expr1) goto L1;
  297. # thenPart }
  298. # goto LEnd
  299. # L1:
  300. # { if (!expr2) goto L2;
  301. # thenPart2 }
  302. # goto LEnd
  303. # L2:
  304. # { elsePart }
  305. # Lend:
  306. var
  307. a: TLoc
  308. lelse: TLabel
  309. if not isEmptyType(n.typ) and d.k == locNone:
  310. getTemp(p, n.typ, d)
  311. genLineDir(p, n)
  312. let lend = getLabel(p)
  313. for it in n.sons:
  314. # bug #4230: avoid false sharing between branches:
  315. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  316. if it.len == 2:
  317. startBlock(p)
  318. initLocExprSingleUse(p, it.sons[0], a)
  319. lelse = getLabel(p)
  320. inc(p.labels)
  321. lineF(p, cpsStmts, "if (!$1) goto $2;$n",
  322. [rdLoc(a), lelse])
  323. if p.module.compileToCpp:
  324. # avoid "jump to label crosses initialization" error:
  325. add(p.s(cpsStmts), "{")
  326. expr(p, it.sons[1], d)
  327. add(p.s(cpsStmts), "}")
  328. else:
  329. expr(p, it.sons[1], d)
  330. endBlock(p)
  331. if sonsLen(n) > 1:
  332. lineF(p, cpsStmts, "goto $1;$n", [lend])
  333. fixLabel(p, lelse)
  334. elif it.len == 1:
  335. startBlock(p)
  336. expr(p, it.sons[0], d)
  337. endBlock(p)
  338. else: internalError(p.config, n.info, "genIf()")
  339. if sonsLen(n) > 1: fixLabel(p, lend)
  340. proc genReturnStmt(p: BProc, t: PNode) =
  341. if nfPreventCg in t.flags: return
  342. p.beforeRetNeeded = true
  343. genLineDir(p, t)
  344. if (t.sons[0].kind != nkEmpty): genStmts(p, t.sons[0])
  345. blockLeaveActions(p,
  346. howManyTrys = p.nestedTryStmts.len,
  347. howManyExcepts = p.inExceptBlockLen)
  348. if (p.finallySafePoints.len > 0):
  349. # If we're in a finally block, and we came here by exception
  350. # consume it before we return.
  351. var safePoint = p.finallySafePoints[p.finallySafePoints.len-1]
  352. linefmt(p, cpsStmts, "if ($1.status != 0) #popCurrentException();$n", safePoint)
  353. lineF(p, cpsStmts, "goto BeforeRet_;$n", [])
  354. proc genGotoForCase(p: BProc; caseStmt: PNode) =
  355. for i in 1 ..< caseStmt.len:
  356. startBlock(p)
  357. let it = caseStmt.sons[i]
  358. for j in 0 .. it.len-2:
  359. if it.sons[j].kind == nkRange:
  360. localError(p.config, it.info, "range notation not available for computed goto")
  361. return
  362. let val = getOrdValue(it.sons[j])
  363. lineF(p, cpsStmts, "NIMSTATE_$#:$n", [val.rope])
  364. genStmts(p, it.lastSon)
  365. endBlock(p)
  366. iterator fieldValuePairs(n: PNode): tuple[memberSym, valueSym: PNode] =
  367. assert(n.kind in {nkLetSection, nkVarSection})
  368. for identDefs in n:
  369. if identDefs.kind == nkIdentDefs:
  370. let valueSym = identDefs[^1]
  371. for i in 0 ..< identDefs.len-2:
  372. let memberSym = identDefs[i]
  373. yield((memberSym: memberSym, valueSym: valueSym))
  374. proc genComputedGoto(p: BProc; n: PNode) =
  375. # first pass: Generate array of computed labels:
  376. var casePos = -1
  377. var arraySize: int
  378. for i in 0 ..< n.len:
  379. let it = n.sons[i]
  380. if it.kind == nkCaseStmt:
  381. if lastSon(it).kind != nkOfBranch:
  382. localError(p.config, it.info,
  383. "case statement must be exhaustive for computed goto"); return
  384. casePos = i
  385. if enumHasHoles(it.sons[0].typ):
  386. localError(p.config, it.info,
  387. "case statement cannot work on enums with holes for computed goto"); return
  388. let aSize = lengthOrd(p.config, it.sons[0].typ)
  389. if aSize > 10_000:
  390. localError(p.config, it.info,
  391. "case statement has too many cases for computed goto"); return
  392. arraySize = aSize.int
  393. if firstOrd(p.config, it.sons[0].typ) != 0:
  394. localError(p.config, it.info,
  395. "case statement has to start at 0 for computed goto"); return
  396. if casePos < 0:
  397. localError(p.config, n.info, "no case statement found for computed goto"); return
  398. var id = p.labels+1
  399. inc p.labels, arraySize+1
  400. let tmp = "TMP$1_" % [id.rope]
  401. var gotoArray = "static void* $#[$#] = {" % [tmp, arraySize.rope]
  402. for i in 1..arraySize-1:
  403. gotoArray.addf("&&TMP$#_, ", [rope(id+i)])
  404. gotoArray.addf("&&TMP$#_};$n", [rope(id+arraySize)])
  405. line(p, cpsLocals, gotoArray)
  406. for j in 0 ..< casePos:
  407. genStmts(p, n.sons[j])
  408. let caseStmt = n.sons[casePos]
  409. var a: TLoc
  410. initLocExpr(p, caseStmt.sons[0], a)
  411. # first goto:
  412. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  413. for i in 1 ..< caseStmt.len:
  414. startBlock(p)
  415. let it = caseStmt.sons[i]
  416. for j in 0 .. it.len-2:
  417. if it.sons[j].kind == nkRange:
  418. localError(p.config, it.info, "range notation not available for computed goto")
  419. return
  420. let val = getOrdValue(it.sons[j])
  421. lineF(p, cpsStmts, "TMP$#_:$n", [intLiteral(val+id+1)])
  422. genStmts(p, it.lastSon)
  423. for j in casePos+1 ..< n.sons.len:
  424. genStmts(p, n.sons[j])
  425. for j in 0 ..< casePos:
  426. # prevent new local declarations
  427. # compile declarations as assignments
  428. let it = n.sons[j]
  429. if it.kind in {nkLetSection, nkVarSection}:
  430. let asgn = copyNode(it)
  431. asgn.kind = nkAsgn
  432. asgn.sons.setLen 2
  433. for sym, value in it.fieldValuePairs:
  434. if value.kind != nkEmpty:
  435. asgn.sons[0] = sym
  436. asgn.sons[1] = value
  437. genStmts(p, asgn)
  438. else:
  439. genStmts(p, it)
  440. var a: TLoc
  441. initLocExpr(p, caseStmt.sons[0], a)
  442. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  443. endBlock(p)
  444. for j in casePos+1 ..< n.sons.len:
  445. genStmts(p, n.sons[j])
  446. proc genWhileStmt(p: BProc, t: PNode) =
  447. # we don't generate labels here as for example GCC would produce
  448. # significantly worse code
  449. var
  450. a: TLoc
  451. assert(sonsLen(t) == 2)
  452. inc(p.withinLoop)
  453. genLineDir(p, t)
  454. preserveBreakIdx:
  455. var loopBody = t.sons[1]
  456. if loopBody.stmtsContainPragma(wComputedGoto) and
  457. hasComputedGoto in CC[p.config.cCompiler].props:
  458. # for closure support weird loop bodies are generated:
  459. if loopBody.len == 2 and loopBody.sons[0].kind == nkEmpty:
  460. loopBody = loopBody.sons[1]
  461. genComputedGoto(p, loopBody)
  462. else:
  463. p.breakIdx = startBlock(p, "while (1) {$n")
  464. p.blocks[p.breakIdx].isLoop = true
  465. initLocExpr(p, t.sons[0], a)
  466. if (t.sons[0].kind != nkIntLit) or (t.sons[0].intVal == 0):
  467. let label = assignLabel(p.blocks[p.breakIdx])
  468. lineF(p, cpsStmts, "if (!$1) goto $2;$n", [rdLoc(a), label])
  469. genStmts(p, loopBody)
  470. if optProfiler in p.options:
  471. # invoke at loop body exit:
  472. linefmt(p, cpsStmts, "#nimProfile();$n")
  473. endBlock(p)
  474. dec(p.withinLoop)
  475. proc genBlock(p: BProc, n: PNode, d: var TLoc) =
  476. # bug #4505: allocate the temp in the outer scope
  477. # so that it can escape the generated {}:
  478. if not isEmptyType(n.typ) and d.k == locNone:
  479. getTemp(p, n.typ, d)
  480. preserveBreakIdx:
  481. p.breakIdx = startBlock(p)
  482. if n.sons[0].kind != nkEmpty:
  483. # named block?
  484. assert(n.sons[0].kind == nkSym)
  485. var sym = n.sons[0].sym
  486. sym.loc.k = locOther
  487. sym.position = p.breakIdx+1
  488. expr(p, n.sons[1], d)
  489. endBlock(p)
  490. proc genParForStmt(p: BProc, t: PNode) =
  491. assert(sonsLen(t) == 3)
  492. inc(p.withinLoop)
  493. genLineDir(p, t)
  494. preserveBreakIdx:
  495. let forLoopVar = t.sons[0].sym
  496. var rangeA, rangeB: TLoc
  497. assignLocalVar(p, t.sons[0])
  498. #initLoc(forLoopVar.loc, locLocalVar, forLoopVar.typ, onStack)
  499. #discard mangleName(forLoopVar)
  500. let call = t.sons[1]
  501. initLocExpr(p, call.sons[1], rangeA)
  502. initLocExpr(p, call.sons[2], rangeB)
  503. # $n at the beginning because of #9710
  504. lineF(p, cpsStmts, "$n#pragma omp $4$n" &
  505. "for ($1 = $2; $1 <= $3; ++$1)",
  506. [forLoopVar.loc.rdLoc,
  507. rangeA.rdLoc, rangeB.rdLoc,
  508. call.sons[3].getStr.rope])
  509. p.breakIdx = startBlock(p)
  510. p.blocks[p.breakIdx].isLoop = true
  511. genStmts(p, t.sons[2])
  512. endBlock(p)
  513. dec(p.withinLoop)
  514. proc genBreakStmt(p: BProc, t: PNode) =
  515. var idx = p.breakIdx
  516. if t.sons[0].kind != nkEmpty:
  517. # named break?
  518. assert(t.sons[0].kind == nkSym)
  519. var sym = t.sons[0].sym
  520. doAssert(sym.loc.k == locOther)
  521. idx = sym.position-1
  522. else:
  523. # an unnamed 'break' can only break a loop after 'transf' pass:
  524. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  525. if idx < 0 or not p.blocks[idx].isLoop:
  526. internalError(p.config, t.info, "no loop to break")
  527. let label = assignLabel(p.blocks[idx])
  528. blockLeaveActions(p,
  529. p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts,
  530. p.inExceptBlockLen - p.blocks[idx].nestedExceptStmts)
  531. genLineDir(p, t)
  532. lineF(p, cpsStmts, "goto $1;$n", [label])
  533. proc genRaiseStmt(p: BProc, t: PNode) =
  534. if p.module.compileToCpp:
  535. discard cgsym(p.module, "popCurrentExceptionEx")
  536. if p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
  537. # if the current try stmt have a finally block,
  538. # we must execute it before reraising
  539. var finallyBlock = p.nestedTryStmts[^1].n[^1]
  540. if finallyBlock.kind == nkFinally:
  541. genSimpleBlock(p, finallyBlock[0])
  542. if t[0].kind != nkEmpty:
  543. var a: TLoc
  544. initLocExprSingleUse(p, t[0], a)
  545. var e = rdLoc(a)
  546. var typ = skipTypes(t[0].typ, abstractPtrs)
  547. genLineDir(p, t)
  548. if isImportedException(typ, p.config):
  549. lineF(p, cpsStmts, "throw $1;$n", [e])
  550. else:
  551. lineCg(p, cpsStmts, "#raiseExceptionEx((#Exception*)$1, $2, $3, $4, $5);$n",
  552. [e, makeCString(typ.sym.name.s),
  553. makeCString(if p.prc != nil: p.prc.name.s else: p.module.module.name.s),
  554. makeCString(toFileName(p.config, t.info)), rope(toLinenumber(t.info))])
  555. else:
  556. genLineDir(p, t)
  557. # reraise the last exception:
  558. if p.module.compileToCpp and optNoCppExceptions notin p.config.globalOptions:
  559. line(p, cpsStmts, ~"throw;$n")
  560. else:
  561. linefmt(p, cpsStmts, "#reraiseException();$n")
  562. proc genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
  563. rangeFormat, eqFormat: FormatStr, labl: TLabel) =
  564. var
  565. x, y: TLoc
  566. var length = sonsLen(b)
  567. for i in countup(0, length - 2):
  568. if b.sons[i].kind == nkRange:
  569. initLocExpr(p, b.sons[i].sons[0], x)
  570. initLocExpr(p, b.sons[i].sons[1], y)
  571. lineCg(p, cpsStmts, rangeFormat,
  572. [rdCharLoc(e), rdCharLoc(x), rdCharLoc(y), labl])
  573. else:
  574. initLocExpr(p, b.sons[i], x)
  575. lineCg(p, cpsStmts, eqFormat, [rdCharLoc(e), rdCharLoc(x), labl])
  576. proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
  577. labId, until: int): TLabel =
  578. var lend = getLabel(p)
  579. for i in 1..until:
  580. # bug #4230: avoid false sharing between branches:
  581. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  582. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(labId + i)])
  583. if t.sons[i].kind == nkOfBranch:
  584. var length = sonsLen(t.sons[i])
  585. exprBlock(p, t.sons[i].sons[length - 1], d)
  586. lineF(p, cpsStmts, "goto $1;$n", [lend])
  587. else:
  588. exprBlock(p, t.sons[i].sons[0], d)
  589. result = lend
  590. proc genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
  591. rangeFormat, eqFormat: FormatStr,
  592. until: int, a: TLoc): TLabel =
  593. # generate a C-if statement for a Nim case statement
  594. var labId = p.labels
  595. for i in 1..until:
  596. inc(p.labels)
  597. if t.sons[i].kind == nkOfBranch: # else statement
  598. genCaseGenericBranch(p, t.sons[i], a, rangeFormat, eqFormat,
  599. "LA" & rope(p.labels) & "_")
  600. else:
  601. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  602. if until < t.len-1:
  603. inc(p.labels)
  604. var gotoTarget = p.labels
  605. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(gotoTarget)])
  606. result = genCaseSecondPass(p, t, d, labId, until)
  607. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(gotoTarget)])
  608. else:
  609. result = genCaseSecondPass(p, t, d, labId, until)
  610. proc genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
  611. rangeFormat, eqFormat: FormatStr) =
  612. var a: TLoc
  613. initLocExpr(p, t.sons[0], a)
  614. var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, sonsLen(t)-1, a)
  615. fixLabel(p, lend)
  616. proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
  617. branches: var openArray[Rope]) =
  618. var x: TLoc
  619. var length = sonsLen(b)
  620. for i in countup(0, length - 2):
  621. assert(b.sons[i].kind != nkRange)
  622. initLocExpr(p, b.sons[i], x)
  623. assert(b.sons[i].kind in {nkStrLit..nkTripleStrLit})
  624. var j = int(hashString(p.config, b.sons[i].strVal) and high(branches))
  625. appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
  626. [rdLoc(e), rdLoc(x), labl])
  627. proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
  628. # count how many constant strings there are in the case:
  629. var strings = 0
  630. for i in countup(1, sonsLen(t) - 1):
  631. if t.sons[i].kind == nkOfBranch: inc(strings, sonsLen(t.sons[i]) - 1)
  632. if strings > stringCaseThreshold:
  633. var bitMask = math.nextPowerOfTwo(strings) - 1
  634. var branches: seq[Rope]
  635. newSeq(branches, bitMask + 1)
  636. var a: TLoc
  637. initLocExpr(p, t.sons[0], a) # fist pass: gnerate ifs+goto:
  638. var labId = p.labels
  639. for i in countup(1, sonsLen(t) - 1):
  640. inc(p.labels)
  641. if t.sons[i].kind == nkOfBranch:
  642. genCaseStringBranch(p, t.sons[i], a, "LA" & rope(p.labels) & "_",
  643. branches)
  644. else:
  645. # else statement: nothing to do yet
  646. # but we reserved a label, which we use later
  647. discard
  648. linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
  649. rdLoc(a), rope(bitMask))
  650. for j in countup(0, high(branches)):
  651. if branches[j] != nil:
  652. lineF(p, cpsStmts, "case $1: $n$2break;$n",
  653. [intLiteral(j), branches[j]])
  654. lineF(p, cpsStmts, "}$n", []) # else statement:
  655. if t.sons[sonsLen(t)-1].kind != nkOfBranch:
  656. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  657. # third pass: generate statements
  658. var lend = genCaseSecondPass(p, t, d, labId, sonsLen(t)-1)
  659. fixLabel(p, lend)
  660. else:
  661. genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
  662. proc branchHasTooBigRange(b: PNode): bool =
  663. for i in countup(0, sonsLen(b)-2):
  664. # last son is block
  665. if (b.sons[i].kind == nkRange) and
  666. b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit:
  667. return true
  668. proc ifSwitchSplitPoint(p: BProc, n: PNode): int =
  669. for i in 1..n.len-1:
  670. var branch = n[i]
  671. var stmtBlock = lastSon(branch)
  672. if stmtBlock.stmtsContainPragma(wLinearScanEnd):
  673. result = i
  674. elif hasSwitchRange notin CC[p.config.cCompiler].props:
  675. if branch.kind == nkOfBranch and branchHasTooBigRange(branch):
  676. result = i
  677. proc genCaseRange(p: BProc, branch: PNode) =
  678. var length = branch.len
  679. for j in 0 .. length-2:
  680. if branch[j].kind == nkRange:
  681. if hasSwitchRange in CC[p.config.cCompiler].props:
  682. lineF(p, cpsStmts, "case $1 ... $2:$n", [
  683. genLiteral(p, branch[j][0]),
  684. genLiteral(p, branch[j][1])])
  685. else:
  686. var v = copyNode(branch[j][0])
  687. while v.intVal <= branch[j][1].intVal:
  688. lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, v)])
  689. inc(v.intVal)
  690. else:
  691. lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, branch[j])])
  692. proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
  693. # analyse 'case' statement:
  694. var splitPoint = ifSwitchSplitPoint(p, n)
  695. # generate if part (might be empty):
  696. var a: TLoc
  697. initLocExpr(p, n.sons[0], a)
  698. var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
  699. rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  700. eqFormat = "if ($1 == $2) goto $3;$n",
  701. splitPoint, a) else: nil
  702. # generate switch part (might be empty):
  703. if splitPoint+1 < n.len:
  704. lineF(p, cpsStmts, "switch ($1) {$n", [rdCharLoc(a)])
  705. var hasDefault = false
  706. for i in splitPoint+1 ..< n.len:
  707. # bug #4230: avoid false sharing between branches:
  708. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  709. var branch = n[i]
  710. if branch.kind == nkOfBranch:
  711. genCaseRange(p, branch)
  712. else:
  713. # else part of case statement:
  714. lineF(p, cpsStmts, "default:$n", [])
  715. hasDefault = true
  716. exprBlock(p, branch.lastSon, d)
  717. lineF(p, cpsStmts, "break;$n", [])
  718. if (hasAssume in CC[p.config.cCompiler].props) and not hasDefault:
  719. lineF(p, cpsStmts, "default: __assume(0);$n", [])
  720. lineF(p, cpsStmts, "}$n", [])
  721. if lend != nil: fixLabel(p, lend)
  722. proc genCase(p: BProc, t: PNode, d: var TLoc) =
  723. genLineDir(p, t)
  724. if not isEmptyType(t.typ) and d.k == locNone:
  725. getTemp(p, t.typ, d)
  726. case skipTypes(t.sons[0].typ, abstractVarRange).kind
  727. of tyString:
  728. genStringCase(p, t, d)
  729. of tyFloat..tyFloat128:
  730. genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  731. "if ($1 == $2) goto $3;$n")
  732. else:
  733. if t.sons[0].kind == nkSym and sfGoto in t.sons[0].sym.flags:
  734. genGotoForCase(p, t)
  735. else:
  736. genOrdinalCase(p, t, d)
  737. proc genRestoreFrameAfterException(p: BProc) =
  738. if optStackTrace in p.module.config.options:
  739. if not p.hasCurFramePointer:
  740. p.hasCurFramePointer = true
  741. p.procSec(cpsLocals).add(ropecg(p.module, "\tTFrame* _nimCurFrame;$n", []))
  742. p.procSec(cpsInit).add(ropecg(p.module, "\t_nimCurFrame = #getFrame();$n", []))
  743. linefmt(p, cpsStmts, "#setFrame(_nimCurFrame);$n")
  744. proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
  745. # code to generate:
  746. #
  747. # try
  748. # {
  749. # myDiv(4, 9);
  750. # } catch (NimExceptionType1&) {
  751. # body
  752. # } catch (NimExceptionType2&) {
  753. # finallyPart()
  754. # raise;
  755. # }
  756. # catch(...) {
  757. # general_handler_body
  758. # }
  759. # finallyPart();
  760. template genExceptBranchBody(body: PNode) {.dirty.} =
  761. genRestoreFrameAfterException(p)
  762. expr(p, body, d)
  763. if not isEmptyType(t.typ) and d.k == locNone:
  764. getTemp(p, t.typ, d)
  765. genLineDir(p, t)
  766. discard cgsym(p.module, "popCurrentExceptionEx")
  767. add(p.nestedTryStmts, (t, false))
  768. startBlock(p, "try {$n")
  769. expr(p, t[0], d)
  770. endBlock(p)
  771. var catchAllPresent = false
  772. p.nestedTryStmts[^1].inExcept = true
  773. for i in 1..<t.len:
  774. if t[i].kind != nkExceptBranch: break
  775. # bug #4230: avoid false sharing between branches:
  776. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  777. if t[i].len == 1:
  778. # general except section:
  779. catchAllPresent = true
  780. startBlock(p, "catch (...) {$n")
  781. genExceptBranchBody(t[i][0])
  782. endBlock(p)
  783. else:
  784. for j in 0..t[i].len-2:
  785. if t[i][j].isInfixAs():
  786. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  787. fillLoc(exvar.sym.loc, locTemp, exvar, mangleLocalName(p, exvar.sym), OnUnknown)
  788. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
  789. else:
  790. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  791. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  792. endBlock(p)
  793. discard pop(p.nestedTryStmts)
  794. if t[^1].kind == nkFinally:
  795. # c++ does not have finally, therefore code needs to be generated twice
  796. if not catchAllPresent:
  797. # finally requires catch all presence
  798. startBlock(p, "catch (...) {$n")
  799. genStmts(p, t[^1][0])
  800. line(p, cpsStmts, ~"throw;$n")
  801. endBlock(p)
  802. genSimpleBlock(p, t[^1][0])
  803. proc genTry(p: BProc, t: PNode, d: var TLoc) =
  804. # code to generate:
  805. #
  806. # XXX: There should be a standard dispatch algorithm
  807. # that's used both here and with multi-methods
  808. #
  809. # TSafePoint sp;
  810. # pushSafePoint(&sp);
  811. # sp.status = setjmp(sp.context);
  812. # if (sp.status == 0) {
  813. # myDiv(4, 9);
  814. # popSafePoint();
  815. # } else {
  816. # popSafePoint();
  817. # /* except DivisionByZero: */
  818. # if (sp.status == DivisionByZero) {
  819. # printf('Division by Zero\n');
  820. # clearException();
  821. # } else {
  822. # clearException();
  823. # }
  824. # }
  825. # {
  826. # /* finally: */
  827. # printf('fin!\n');
  828. # }
  829. # if (exception not cleared)
  830. # propagateCurrentException();
  831. #
  832. if not isEmptyType(t.typ) and d.k == locNone:
  833. getTemp(p, t.typ, d)
  834. p.module.includeHeader("<setjmp.h>")
  835. genLineDir(p, t)
  836. var safePoint = getTempName(p.module)
  837. discard cgsym(p.module, "Exception")
  838. linefmt(p, cpsLocals, "#TSafePoint $1;$n", safePoint)
  839. linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", safePoint)
  840. if isDefined(p.config, "nimStdSetjmp"):
  841. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", safePoint)
  842. elif isDefined(p.config, "nimSigSetjmp"):
  843. linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", safePoint)
  844. elif isDefined(p.config, "nimRawSetjmp"):
  845. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", safePoint)
  846. else:
  847. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", safePoint)
  848. startBlock(p, "if ($1.status == 0) {$n", [safePoint])
  849. var length = sonsLen(t)
  850. add(p.nestedTryStmts, (t, false))
  851. expr(p, t.sons[0], d)
  852. linefmt(p, cpsStmts, "#popSafePoint();$n")
  853. endBlock(p)
  854. startBlock(p, "else {$n")
  855. linefmt(p, cpsStmts, "#popSafePoint();$n")
  856. genRestoreFrameAfterException(p)
  857. p.nestedTryStmts[^1].inExcept = true
  858. var i = 1
  859. while (i < length) and (t.sons[i].kind == nkExceptBranch):
  860. # bug #4230: avoid false sharing between branches:
  861. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  862. var blen = sonsLen(t.sons[i])
  863. if blen == 1:
  864. # general except section:
  865. if i > 1: lineF(p, cpsStmts, "else", [])
  866. startBlock(p)
  867. linefmt(p, cpsStmts, "$1.status = 0;$n", safePoint)
  868. expr(p, t.sons[i].sons[0], d)
  869. linefmt(p, cpsStmts, "#popCurrentException();$n")
  870. endBlock(p)
  871. else:
  872. var orExpr: Rope = nil
  873. for j in countup(0, blen - 2):
  874. assert(t.sons[i].sons[j].kind == nkType)
  875. if orExpr != nil: add(orExpr, "||")
  876. let isObjFormat = if not p.module.compileToCpp:
  877. "#isObj(#getCurrentException()->Sup.m_type, $1)"
  878. else: "#isObj(#getCurrentException()->m_type, $1)"
  879. appcg(p.module, orExpr, isObjFormat,
  880. [genTypeInfo(p.module, t[i][j].typ, t[i][j].info)])
  881. if i > 1: line(p, cpsStmts, "else ")
  882. startBlock(p, "if ($1) {$n", [orExpr])
  883. linefmt(p, cpsStmts, "$1.status = 0;$n", safePoint)
  884. expr(p, t.sons[i].sons[blen-1], d)
  885. linefmt(p, cpsStmts, "#popCurrentException();$n")
  886. endBlock(p)
  887. inc(i)
  888. discard pop(p.nestedTryStmts)
  889. endBlock(p) # end of else block
  890. if i < length and t.sons[i].kind == nkFinally:
  891. p.finallySafePoints.add(safePoint)
  892. genSimpleBlock(p, t.sons[i].sons[0])
  893. discard pop(p.finallySafePoints)
  894. linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", safePoint)
  895. proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): Rope =
  896. var res = ""
  897. for it in t.sons:
  898. case it.kind
  899. of nkStrLit..nkTripleStrLit:
  900. res.add(it.strVal)
  901. of nkSym:
  902. var sym = it.sym
  903. if sym.kind in {skProc, skFunc, skIterator, skMethod}:
  904. var a: TLoc
  905. initLocExpr(p, it, a)
  906. res.add($rdLoc(a))
  907. elif sym.kind == skType:
  908. res.add($getTypeDesc(p.module, sym.typ))
  909. else:
  910. discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
  911. var r = sym.loc.r
  912. if r == nil:
  913. # if no name has already been given,
  914. # it doesn't matter much:
  915. r = mangleName(p.module, sym)
  916. sym.loc.r = r # but be consequent!
  917. res.add($r)
  918. of nkTypeOfExpr:
  919. res.add($getTypeDesc(p.module, it.typ))
  920. else:
  921. discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs))
  922. var a: TLoc
  923. initLocExpr(p, it, a)
  924. res.add($a.rdLoc)
  925. if isAsmStmt and hasGnuAsm in CC[p.config.cCompiler].props:
  926. for x in splitLines(res):
  927. var j = 0
  928. while j < x.len and x[j] in {' ', '\t'}: inc(j)
  929. if j < x.len:
  930. if x[j] in {'"', ':'}:
  931. # don't modify the line if already in quotes or
  932. # some clobber register list:
  933. add(result, x); add(result, "\L")
  934. else:
  935. # ignore empty lines
  936. add(result, "\"")
  937. add(result, x)
  938. add(result, "\\n\"\n")
  939. else:
  940. res.add("\L")
  941. result = res.rope
  942. proc genAsmStmt(p: BProc, t: PNode) =
  943. assert(t.kind == nkAsmStmt)
  944. genLineDir(p, t)
  945. var s = genAsmOrEmitStmt(p, t, isAsmStmt=true)
  946. # see bug #2362, "top level asm statements" seem to be a mis-feature
  947. # but even if we don't do this, the example in #2362 cannot possibly
  948. # work:
  949. if p.prc == nil:
  950. # top level asm statement?
  951. addf(p.module.s[cfsProcHeaders], CC[p.config.cCompiler].asmStmtFrmt, [s])
  952. else:
  953. lineF(p, cpsStmts, CC[p.config.cCompiler].asmStmtFrmt, [s])
  954. proc determineSection(n: PNode): TCFileSection =
  955. result = cfsProcHeaders
  956. if n.len >= 1 and n.sons[0].kind in {nkStrLit..nkTripleStrLit}:
  957. let sec = n.sons[0].strVal
  958. if sec.startsWith("/*TYPESECTION*/"): result = cfsTypes
  959. elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
  960. elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
  961. proc genEmit(p: BProc, t: PNode) =
  962. var s = genAsmOrEmitStmt(p, t.sons[1])
  963. if p.prc == nil:
  964. # top level emit pragma?
  965. let section = determineSection(t[1])
  966. genCLineDir(p.module.s[section], t.info, p.config)
  967. add(p.module.s[section], s)
  968. else:
  969. genLineDir(p, t)
  970. line(p, cpsStmts, s)
  971. proc genBreakPoint(p: BProc, t: PNode) =
  972. var name: string
  973. if optEndb in p.options:
  974. if t.kind == nkExprColonExpr:
  975. assert(t.sons[1].kind in {nkStrLit..nkTripleStrLit})
  976. name = normalize(t.sons[1].strVal)
  977. else:
  978. inc(p.module.g.breakPointId)
  979. name = "bp" & $p.module.g.breakPointId
  980. genLineDir(p, t) # BUGFIX
  981. appcg(p.module, p.module.g.breakpoints,
  982. "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", [
  983. rope(toLinenumber(t.info)), makeCString(toFilename(p.config, t.info)),
  984. makeCString(name)])
  985. proc genWatchpoint(p: BProc, n: PNode) =
  986. if optEndb notin p.options: return
  987. var a: TLoc
  988. initLocExpr(p, n.sons[1], a)
  989. let typ = skipTypes(n.sons[1].typ, abstractVarRange)
  990. lineCg(p, cpsStmts, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n",
  991. [addrLoc(p.config, a), makeCString(renderTree(n.sons[1])),
  992. genTypeInfo(p.module, typ, n.info)])
  993. proc genPragma(p: BProc, n: PNode) =
  994. for it in n.sons:
  995. case whichPragma(it)
  996. of wEmit: genEmit(p, it)
  997. of wBreakpoint: genBreakPoint(p, it)
  998. of wWatchPoint: genWatchpoint(p, it)
  999. of wInjectStmt:
  1000. var p = newProc(nil, p.module)
  1001. p.options = p.options - {optLineTrace, optStackTrace}
  1002. genStmts(p, it.sons[1])
  1003. p.module.injectStmt = p.s(cpsStmts)
  1004. else: discard
  1005. proc fieldDiscriminantCheckNeeded(p: BProc, asgn: PNode): bool =
  1006. if optFieldCheck in p.options:
  1007. var le = asgn.sons[0]
  1008. if le.kind == nkCheckedFieldExpr:
  1009. var field = le.sons[0].sons[1].sym
  1010. result = sfDiscriminant in field.flags
  1011. elif le.kind == nkDotExpr:
  1012. var field = le.sons[1].sym
  1013. result = sfDiscriminant in field.flags
  1014. proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
  1015. field: PSym) =
  1016. var t = skipTypes(objtype, abstractVar)
  1017. assert t.kind == tyObject
  1018. discard genTypeInfo(p.module, t, a.lode.info)
  1019. var L = lengthOrd(p.config, field.typ)
  1020. if not containsOrIncl(p.module.declaredThings, field.id):
  1021. appcg(p.module, cfsVars, "extern $1",
  1022. discriminatorTableDecl(p.module, t, field))
  1023. lineCg(p, cpsStmts,
  1024. "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
  1025. [rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
  1026. intLiteral(L+1)])
  1027. proc asgnFieldDiscriminant(p: BProc, e: PNode) =
  1028. var a, tmp: TLoc
  1029. var dotExpr = e.sons[0]
  1030. if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr.sons[0]
  1031. initLocExpr(p, e.sons[0], a)
  1032. getTemp(p, a.t, tmp)
  1033. expr(p, e.sons[1], tmp)
  1034. genDiscriminantCheck(p, a, tmp, dotExpr.sons[0].typ, dotExpr.sons[1].sym)
  1035. genAssignment(p, a, tmp, {})
  1036. proc patchAsgnStmtListExpr(father, orig, n: PNode) =
  1037. case n.kind
  1038. of nkDerefExpr, nkHiddenDeref:
  1039. let asgn = copyNode(orig)
  1040. asgn.add orig[0]
  1041. asgn.add n
  1042. father.add asgn
  1043. of nkStmtList, nkStmtListExpr:
  1044. for x in n:
  1045. patchAsgnStmtListExpr(father, orig, x)
  1046. else:
  1047. father.add n
  1048. proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
  1049. if e.sons[0].kind == nkSym and sfGoto in e.sons[0].sym.flags:
  1050. genLineDir(p, e)
  1051. genGotoVar(p, e.sons[1])
  1052. elif not fieldDiscriminantCheckNeeded(p, e):
  1053. # this fixes bug #6422 but we really need to change the representation of
  1054. # arrays in the backend...
  1055. let le = e[0]
  1056. let ri = e[1]
  1057. var needsRepair = false
  1058. var it = ri
  1059. while it.kind in {nkStmtList, nkStmtListExpr}:
  1060. it = it.lastSon
  1061. needsRepair = true
  1062. if it.kind in {nkDerefExpr, nkHiddenDeref} and needsRepair:
  1063. var patchedTree = newNodeI(nkStmtList, e.info)
  1064. patchAsgnStmtListExpr(patchedTree, e, ri)
  1065. genStmts(p, patchedTree)
  1066. return
  1067. var a: TLoc
  1068. discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs))
  1069. if le.kind in {nkDerefExpr, nkHiddenDeref}:
  1070. genDeref(p, le, a, enforceDeref=true)
  1071. else:
  1072. initLocExpr(p, le, a)
  1073. if fastAsgn: incl(a.flags, lfNoDeepCopy)
  1074. assert(a.t != nil)
  1075. genLineDir(p, ri)
  1076. loadInto(p, e.sons[0], ri, a)
  1077. else:
  1078. genLineDir(p, e)
  1079. asgnFieldDiscriminant(p, e)
  1080. proc genStmts(p: BProc, t: PNode) =
  1081. var a: TLoc
  1082. let isPush = hintExtendedContext in p.config.notes
  1083. if isPush: pushInfoContext(p.config, t.info)
  1084. expr(p, t, a)
  1085. if isPush: popInfoContext(p.config)
  1086. internalAssert p.config, a.k in {locNone, locTemp, locLocalVar, locExpr}