vmgen.nim 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  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. ## This module implements the code generator for the VM.
  10. # Important things to remember:
  11. # - The VM does not distinguish between definitions ('var x = y') and
  12. # assignments ('x = y'). For simple data types that fit into a register
  13. # this doesn't matter. However it matters for strings and other complex
  14. # types that use the 'node' field; the reason is that slots are
  15. # re-used in a register based VM. Example:
  16. # ```nim
  17. # let s = a & b # no matter what, create fresh node
  18. # s = a & b # no matter what, keep the node
  19. # ```
  20. # Also *stores* into non-temporary memory need to perform deep copies:
  21. # a.b = x.y
  22. # We used to generate opcAsgn for the *load* of 'x.y' but this is clearly
  23. # wrong! We need to produce opcAsgn (the copy) for the *store*. This also
  24. # solves the opcLdConst vs opcAsgnConst issue. Of course whether we need
  25. # this copy depends on the involved types.
  26. import std/[tables, intsets, strutils]
  27. when defined(nimPreviewSlimSystem):
  28. import std/assertions
  29. import
  30. ast, types, msgs, renderer, vmdef, trees,
  31. magicsys, options, lowerings, lineinfos, transf, astmsgs
  32. from modulegraphs import getBody
  33. when defined(nimCompilerStacktraceHints):
  34. import std/stackframes
  35. const
  36. debugEchoCode* = defined(nimVMDebug)
  37. when debugEchoCode:
  38. import std/private/asciitables
  39. when hasFFI:
  40. import evalffi
  41. type
  42. TGenFlag = enum
  43. gfNode # Affects how variables are loaded - always loads as rkNode
  44. gfNodeAddr # Affects how variables are loaded - always loads as rkNodeAddr
  45. gfIsParam # do not deepcopy parameters, they are immutable
  46. TGenFlags = set[TGenFlag]
  47. proc debugInfo(c: PCtx; info: TLineInfo): string =
  48. result = toFileLineCol(c.config, info)
  49. proc codeListing(c: PCtx, result: var string, start=0; last = -1) =
  50. ## for debugging purposes
  51. # first iteration: compute all necessary labels:
  52. var jumpTargets = initIntSet()
  53. let last = if last < 0: c.code.len-1 else: min(last, c.code.len-1)
  54. for i in start..last:
  55. let x = c.code[i]
  56. if x.opcode in relativeJumps:
  57. jumpTargets.incl(i+x.regBx-wordExcess)
  58. template toStr(opc: TOpcode): string = ($opc).substr(3)
  59. result.add "code listing:\n"
  60. var i = start
  61. while i <= last:
  62. if i in jumpTargets: result.addf("L$1:\n", i)
  63. let x = c.code[i]
  64. result.add($i)
  65. let opc = opcode(x)
  66. if opc in {opcIndCall, opcIndCallAsgn}:
  67. result.addf("\t$#\tr$#, r$#, nargs:$#", opc.toStr, x.regA,
  68. x.regB, x.regC)
  69. elif opc in {opcConv, opcCast}:
  70. let y = c.code[i+1]
  71. let z = c.code[i+2]
  72. result.addf("\t$#\tr$#, r$#, $#, $#", opc.toStr, x.regA, x.regB,
  73. c.types[y.regBx-wordExcess].typeToString,
  74. c.types[z.regBx-wordExcess].typeToString)
  75. inc i, 2
  76. elif opc < firstABxInstr:
  77. result.addf("\t$#\tr$#, r$#, r$#", opc.toStr, x.regA,
  78. x.regB, x.regC)
  79. elif opc in relativeJumps + {opcTry}:
  80. result.addf("\t$#\tr$#, L$#", opc.toStr, x.regA,
  81. i+x.regBx-wordExcess)
  82. elif opc in {opcExcept}:
  83. let idx = x.regBx-wordExcess
  84. result.addf("\t$#\t$#, $#", opc.toStr, x.regA, $idx)
  85. elif opc in {opcLdConst, opcAsgnConst}:
  86. let idx = x.regBx-wordExcess
  87. result.addf("\t$#\tr$#, $# ($#)", opc.toStr, x.regA,
  88. c.constants[idx].renderTree, $idx)
  89. else:
  90. result.addf("\t$#\tr$#, $#", opc.toStr, x.regA, x.regBx-wordExcess)
  91. result.add("\t# ")
  92. result.add(debugInfo(c, c.debug[i]))
  93. result.add("\n")
  94. inc i
  95. when debugEchoCode:
  96. result = result.alignTable
  97. proc echoCode*(c: PCtx; start=0; last = -1) {.deprecated.} =
  98. var buf = ""
  99. codeListing(c, buf, start, last)
  100. echo buf
  101. proc gABC(ctx: PCtx; n: PNode; opc: TOpcode;
  102. a: TRegister = 0, b: TRegister = 0, c: TRegister = 0) =
  103. ## Takes the registers `b` and `c`, applies the operation `opc` to them, and
  104. ## stores the result into register `a`
  105. ## The node is needed for debug information
  106. assert opc.ord < 255
  107. let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
  108. (b.TInstrType shl regBShift) or
  109. (c.TInstrType shl regCShift)).TInstr
  110. when false:
  111. if ctx.code.len == 43:
  112. writeStackTrace()
  113. echo "generating ", opc
  114. ctx.code.add(ins)
  115. ctx.debug.add(n.info)
  116. proc gABI(c: PCtx; n: PNode; opc: TOpcode; a, b: TRegister; imm: BiggestInt) =
  117. # Takes the `b` register and the immediate `imm`, applies the operation `opc`,
  118. # and stores the output value into `a`.
  119. # `imm` is signed and must be within [-128, 127]
  120. if imm >= -128 and imm <= 127:
  121. let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
  122. (b.TInstrType shl regBShift) or
  123. (imm+byteExcess).TInstrType shl regCShift).TInstr
  124. c.code.add(ins)
  125. c.debug.add(n.info)
  126. else:
  127. localError(c.config, n.info,
  128. "VM: immediate value does not fit into an int8")
  129. proc gABx(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0; bx: int) =
  130. # Applies `opc` to `bx` and stores it into register `a`
  131. # `bx` must be signed and in the range [regBxMin, regBxMax]
  132. when false:
  133. if c.code.len == 43:
  134. writeStackTrace()
  135. echo "generating ", opc
  136. if bx >= regBxMin-1 and bx <= regBxMax:
  137. let ins = (opc.TInstrType or a.TInstrType shl regAShift or
  138. (bx+wordExcess).TInstrType shl regBxShift).TInstr
  139. c.code.add(ins)
  140. c.debug.add(n.info)
  141. else:
  142. localError(c.config, n.info,
  143. "VM: immediate value does not fit into regBx")
  144. proc xjmp(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0): TPosition =
  145. #assert opc in {opcJmp, opcFJmp, opcTJmp}
  146. result = TPosition(c.code.len)
  147. gABx(c, n, opc, a, 0)
  148. proc genLabel(c: PCtx): TPosition =
  149. result = TPosition(c.code.len)
  150. #c.jumpTargets.incl(c.code.len)
  151. proc jmpBack(c: PCtx, n: PNode, p = TPosition(0)) =
  152. let dist = p.int - c.code.len
  153. internalAssert(c.config, regBxMin < dist and dist < regBxMax)
  154. gABx(c, n, opcJmpBack, 0, dist)
  155. proc patch(c: PCtx, p: TPosition) =
  156. # patch with current index
  157. let p = p.int
  158. let diff = c.code.len - p
  159. #c.jumpTargets.incl(c.code.len)
  160. internalAssert(c.config, regBxMin < diff and diff < regBxMax)
  161. let oldInstr = c.code[p]
  162. # opcode and regA stay the same:
  163. c.code[p] = ((oldInstr.TInstrType and regBxMask).TInstrType or
  164. TInstrType(diff+wordExcess) shl regBxShift).TInstr
  165. proc getSlotKind(t: PType): TSlotKind =
  166. case t.skipTypes(abstractRange-{tyTypeDesc}).kind
  167. of tyBool, tyChar, tyEnum, tyOrdinal, tyInt..tyInt64, tyUInt..tyUInt64:
  168. slotTempInt
  169. of tyString, tyCstring:
  170. slotTempStr
  171. of tyFloat..tyFloat128:
  172. slotTempFloat
  173. else:
  174. slotTempComplex
  175. const
  176. HighRegisterPressure = 40
  177. proc bestEffort(c: PCtx): TLineInfo =
  178. if c.prc != nil and c.prc.sym != nil:
  179. c.prc.sym.info
  180. else:
  181. c.module.info
  182. proc getFreeRegister(cc: PCtx; k: TSlotKind; start: int): TRegister =
  183. let c = cc.prc
  184. # we prefer the same slot kind here for efficiency. Unfortunately for
  185. # discardable return types we may not know the desired type. This can happen
  186. # for e.g. mNAdd[Multiple]:
  187. for i in start..c.regInfo.len-1:
  188. if c.regInfo[i].kind == k and not c.regInfo[i].inUse:
  189. c.regInfo[i].inUse = true
  190. return TRegister(i)
  191. # if register pressure is high, we re-use more aggressively:
  192. if c.regInfo.len >= high(TRegister):
  193. for i in start..c.regInfo.len-1:
  194. if not c.regInfo[i].inUse:
  195. c.regInfo[i] = (inUse: true, kind: k)
  196. return TRegister(i)
  197. if c.regInfo.len >= high(TRegister):
  198. globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
  199. result = TRegister(max(c.regInfo.len, start))
  200. c.regInfo.setLen int(result)+1
  201. c.regInfo[result] = (inUse: true, kind: k)
  202. proc getTemp(cc: PCtx; tt: PType): TRegister =
  203. let typ = tt.skipTypesOrNil({tyStatic})
  204. # we prefer the same slot kind here for efficiency. Unfortunately for
  205. # discardable return types we may not know the desired type. This can happen
  206. # for e.g. mNAdd[Multiple]:
  207. let k = if typ.isNil: slotTempComplex else: typ.getSlotKind
  208. result = getFreeRegister(cc, k, start = 0)
  209. when false:
  210. # enable this to find "register" leaks:
  211. if result == 4:
  212. echo "begin ---------------"
  213. writeStackTrace()
  214. echo "end ----------------"
  215. proc freeTemp(c: PCtx; r: TRegister) =
  216. let c = c.prc
  217. if c.regInfo[r].kind in {slotSomeTemp..slotTempComplex}:
  218. # this seems to cause https://github.com/nim-lang/Nim/issues/10647
  219. c.regInfo[r].inUse = false
  220. proc getTempRange(cc: PCtx; n: int; kind: TSlotKind): TRegister =
  221. # if register pressure is high, we re-use more aggressively:
  222. let c = cc.prc
  223. # we could also customize via the following (with proper caching in ConfigRef):
  224. # let highRegisterPressure = cc.config.getConfigVar("vm.highRegisterPressure", "40").parseInt
  225. if c.regInfo.len >= HighRegisterPressure or c.regInfo.len+n >= high(TRegister):
  226. for i in 0..c.regInfo.len-n:
  227. if not c.regInfo[i].inUse:
  228. block search:
  229. for j in i+1..i+n-1:
  230. if c.regInfo[j].inUse: break search
  231. result = TRegister(i)
  232. for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
  233. return
  234. if c.regInfo.len+n >= high(TRegister):
  235. globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
  236. result = TRegister(c.regInfo.len)
  237. setLen c.regInfo, c.regInfo.len+n
  238. for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
  239. proc freeTempRange(c: PCtx; start: TRegister, n: int) =
  240. for i in start..start+n-1: c.freeTemp(TRegister(i))
  241. template withTemp(tmp, typ, body: untyped) {.dirty.} =
  242. var tmp = getTemp(c, typ)
  243. body
  244. c.freeTemp(tmp)
  245. proc popBlock(c: PCtx; oldLen: int) =
  246. for f in c.prc.blocks[oldLen].fixups:
  247. c.patch(f)
  248. c.prc.blocks.setLen(oldLen)
  249. template withBlock(labl: PSym; body: untyped) {.dirty.} =
  250. var oldLen {.gensym.} = c.prc.blocks.len
  251. c.prc.blocks.add TBlock(label: labl, fixups: @[])
  252. body
  253. popBlock(c, oldLen)
  254. proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {})
  255. proc gen(c: PCtx; n: PNode; dest: TRegister; flags: TGenFlags = {}) =
  256. var d: TDest = dest
  257. gen(c, n, d, flags)
  258. #internalAssert c.config, d == dest # issue #7407
  259. proc gen(c: PCtx; n: PNode; flags: TGenFlags = {}) =
  260. var tmp: TDest = -1
  261. gen(c, n, tmp, flags)
  262. if tmp >= 0:
  263. freeTemp(c, tmp)
  264. #if n.typ.isEmptyType: internalAssert tmp < 0
  265. proc genx(c: PCtx; n: PNode; flags: TGenFlags = {}): TRegister =
  266. var tmp: TDest = -1
  267. gen(c, n, tmp, flags)
  268. #internalAssert c.config, tmp >= 0 # 'nim check' does not like this internalAssert.
  269. if tmp >= 0:
  270. result = TRegister(tmp)
  271. else:
  272. result = 0
  273. proc clearDest(c: PCtx; n: PNode; dest: var TDest) {.inline.} =
  274. # stmt is different from 'void' in meta programming contexts.
  275. # So we only set dest to -1 if 'void':
  276. if dest >= 0 and (n.typ.isNil or n.typ.kind == tyVoid):
  277. c.freeTemp(dest)
  278. dest = -1
  279. proc isNotOpr(n: PNode): bool =
  280. n.kind in nkCallKinds and n[0].kind == nkSym and
  281. n[0].sym.magic == mNot
  282. proc genWhile(c: PCtx; n: PNode) =
  283. # lab1:
  284. # cond, tmp
  285. # fjmp tmp, lab2
  286. # body
  287. # jmp lab1
  288. # lab2:
  289. let lab1 = c.genLabel
  290. withBlock(nil):
  291. if isTrue(n[0]):
  292. c.gen(n[1])
  293. c.jmpBack(n, lab1)
  294. elif isNotOpr(n[0]):
  295. var tmp = c.genx(n[0][1])
  296. let lab2 = c.xjmp(n, opcTJmp, tmp)
  297. c.freeTemp(tmp)
  298. c.gen(n[1])
  299. c.jmpBack(n, lab1)
  300. c.patch(lab2)
  301. else:
  302. var tmp = c.genx(n[0])
  303. let lab2 = c.xjmp(n, opcFJmp, tmp)
  304. c.freeTemp(tmp)
  305. c.gen(n[1])
  306. c.jmpBack(n, lab1)
  307. c.patch(lab2)
  308. proc genBlock(c: PCtx; n: PNode; dest: var TDest) =
  309. let oldRegisterCount = c.prc.regInfo.len
  310. withBlock(n[0].sym):
  311. c.gen(n[1], dest)
  312. for i in oldRegisterCount..<c.prc.regInfo.len:
  313. #if c.prc.regInfo[i].kind in {slotFixedVar, slotFixedLet}:
  314. if i != dest:
  315. when not defined(release):
  316. if c.prc.regInfo[i].inUse and c.prc.regInfo[i].kind in {slotTempUnknown,
  317. slotTempInt,
  318. slotTempFloat,
  319. slotTempStr,
  320. slotTempComplex}:
  321. raiseAssert "leaking temporary " & $i & " " & $c.prc.regInfo[i].kind
  322. c.prc.regInfo[i] = (inUse: false, kind: slotEmpty)
  323. c.clearDest(n, dest)
  324. proc genBreak(c: PCtx; n: PNode) =
  325. let lab1 = c.xjmp(n, opcJmp)
  326. if n[0].kind == nkSym:
  327. #echo cast[int](n[0].sym)
  328. for i in countdown(c.prc.blocks.len-1, 0):
  329. if c.prc.blocks[i].label == n[0].sym:
  330. c.prc.blocks[i].fixups.add lab1
  331. return
  332. globalError(c.config, n.info, "VM problem: cannot find 'break' target")
  333. else:
  334. c.prc.blocks[c.prc.blocks.high].fixups.add lab1
  335. proc genIf(c: PCtx, n: PNode; dest: var TDest) =
  336. # if (!expr1) goto lab1;
  337. # thenPart
  338. # goto LEnd
  339. # lab1:
  340. # if (!expr2) goto lab2;
  341. # thenPart2
  342. # goto LEnd
  343. # lab2:
  344. # elsePart
  345. # Lend:
  346. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  347. var endings: seq[TPosition] = @[]
  348. for i in 0..<n.len:
  349. var it = n[i]
  350. if it.len == 2:
  351. withTemp(tmp, it[0].typ):
  352. var elsePos: TPosition
  353. if isNotOpr(it[0]):
  354. c.gen(it[0][1], tmp)
  355. elsePos = c.xjmp(it[0][1], opcTJmp, tmp) # if true
  356. else:
  357. c.gen(it[0], tmp)
  358. elsePos = c.xjmp(it[0], opcFJmp, tmp) # if false
  359. c.clearDest(n, dest)
  360. if isEmptyType(it[1].typ): # maybe noreturn call, don't touch `dest`
  361. c.gen(it[1])
  362. else:
  363. c.gen(it[1], dest) # then part
  364. if i < n.len-1:
  365. endings.add(c.xjmp(it[1], opcJmp, 0))
  366. c.patch(elsePos)
  367. else:
  368. c.clearDest(n, dest)
  369. if isEmptyType(it[0].typ): # maybe noreturn call, don't touch `dest`
  370. c.gen(it[0])
  371. else:
  372. c.gen(it[0], dest)
  373. for endPos in endings: c.patch(endPos)
  374. c.clearDest(n, dest)
  375. proc isTemp(c: PCtx; dest: TDest): bool =
  376. result = dest >= 0 and c.prc.regInfo[dest].kind >= slotTempUnknown
  377. proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) =
  378. # asgn dest, a
  379. # tjmp|fjmp lab1
  380. # asgn dest, b
  381. # lab1:
  382. let copyBack = dest < 0 or not isTemp(c, dest)
  383. let tmp = if copyBack:
  384. getTemp(c, n.typ)
  385. else:
  386. TRegister dest
  387. c.gen(n[1], tmp)
  388. let lab1 = c.xjmp(n, opc, tmp)
  389. c.gen(n[2], tmp)
  390. c.patch(lab1)
  391. if dest < 0:
  392. dest = tmp
  393. elif copyBack:
  394. c.gABC(n, opcAsgnInt, dest, tmp)
  395. freeTemp(c, tmp)
  396. proc rawGenLiteral(c: PCtx; n: PNode): int =
  397. result = c.constants.len
  398. #assert(n.kind != nkCall)
  399. n.flags.incl nfAllConst
  400. n.flags.excl nfIsRef
  401. c.constants.add n
  402. internalAssert c.config, result < regBxMax
  403. proc sameConstant*(a, b: PNode): bool =
  404. result = false
  405. if a == b:
  406. result = true
  407. elif a != nil and b != nil and a.kind == b.kind:
  408. case a.kind
  409. of nkSym: result = a.sym == b.sym
  410. of nkIdent: result = a.ident.id == b.ident.id
  411. of nkCharLit..nkUInt64Lit: result = a.intVal == b.intVal
  412. of nkFloatLit..nkFloat64Lit:
  413. result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
  414. # refs bug #16469
  415. # if we wanted to only distinguish 0.0 vs -0.0:
  416. # if a.floatVal == 0.0: result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
  417. # else: result = a.floatVal == b.floatVal
  418. of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal
  419. of nkType, nkNilLit: result = a.typ == b.typ
  420. of nkEmpty: result = true
  421. else:
  422. if a.len == b.len:
  423. for i in 0..<a.len:
  424. if not sameConstant(a[i], b[i]): return
  425. result = true
  426. proc genLiteral(c: PCtx; n: PNode): int =
  427. # types do not matter here:
  428. for i in 0..<c.constants.len:
  429. if sameConstant(c.constants[i], n): return i
  430. result = rawGenLiteral(c, n)
  431. proc unused(c: PCtx; n: PNode; x: TDest) {.inline.} =
  432. if x >= 0:
  433. #debug(n)
  434. globalError(c.config, n.info, "not unused")
  435. proc genCase(c: PCtx; n: PNode; dest: var TDest) =
  436. # if (!expr1) goto lab1;
  437. # thenPart
  438. # goto LEnd
  439. # lab1:
  440. # if (!expr2) goto lab2;
  441. # thenPart2
  442. # goto LEnd
  443. # lab2:
  444. # elsePart
  445. # Lend:
  446. if not isEmptyType(n.typ):
  447. if dest < 0: dest = getTemp(c, n.typ)
  448. else:
  449. unused(c, n, dest)
  450. var endings: seq[TPosition] = @[]
  451. withTemp(tmp, n[0].typ):
  452. c.gen(n[0], tmp)
  453. # branch tmp, codeIdx
  454. # fjmp elseLabel
  455. for i in 1..<n.len:
  456. let it = n[i]
  457. if it.len == 1:
  458. # else stmt:
  459. let body = it[0]
  460. if body.kind != nkNilLit or body.typ != nil:
  461. # an nkNilLit with nil for typ implies there is no else branch, this
  462. # avoids unused related errors as we've already consumed the dest
  463. if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
  464. c.gen(body)
  465. else:
  466. c.gen(body, dest)
  467. else:
  468. let b = rawGenLiteral(c, it)
  469. c.gABx(it, opcBranch, tmp, b)
  470. let body = it.lastSon
  471. let elsePos = c.xjmp(body, opcFJmp, tmp)
  472. if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
  473. c.gen(body)
  474. else:
  475. c.gen(body, dest)
  476. if i < n.len-1:
  477. endings.add(c.xjmp(body, opcJmp, 0))
  478. c.patch(elsePos)
  479. c.clearDest(n, dest)
  480. for endPos in endings: c.patch(endPos)
  481. proc genType(c: PCtx; typ: PType): int =
  482. for i, t in c.types:
  483. if sameType(t, typ): return i
  484. result = c.types.len
  485. c.types.add(typ)
  486. internalAssert(c.config, result <= regBxMax)
  487. proc genTry(c: PCtx; n: PNode; dest: var TDest) =
  488. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  489. var endings: seq[TPosition] = @[]
  490. let ehPos = c.xjmp(n, opcTry, 0)
  491. if isEmptyType(n[0].typ): # maybe noreturn call, don't touch `dest`
  492. c.gen(n[0])
  493. else:
  494. c.gen(n[0], dest)
  495. c.clearDest(n, dest)
  496. # Add a jump past the exception handling code
  497. let jumpToFinally = c.xjmp(n, opcJmp, 0)
  498. # This signals where the body ends and where the exception handling begins
  499. c.patch(ehPos)
  500. for i in 1..<n.len:
  501. let it = n[i]
  502. if it.kind != nkFinally:
  503. # first opcExcept contains the end label of the 'except' block:
  504. let endExcept = c.xjmp(it, opcExcept, 0)
  505. for j in 0..<it.len - 1:
  506. assert(it[j].kind == nkType)
  507. let typ = it[j].typ.skipTypes(abstractPtrs-{tyTypeDesc})
  508. c.gABx(it, opcExcept, 0, c.genType(typ))
  509. if it.len == 1:
  510. # general except section:
  511. c.gABx(it, opcExcept, 0, 0)
  512. let body = it.lastSon
  513. if isEmptyType(body.typ): # maybe noreturn call, don't touch `dest`
  514. c.gen(body)
  515. else:
  516. c.gen(body, dest)
  517. c.clearDest(n, dest)
  518. if i < n.len:
  519. endings.add(c.xjmp(it, opcJmp, 0))
  520. c.patch(endExcept)
  521. let fin = lastSon(n)
  522. # we always generate an 'opcFinally' as that pops the safepoint
  523. # from the stack if no exception is raised in the body.
  524. c.patch(jumpToFinally)
  525. c.gABx(fin, opcFinally, 0, 0)
  526. for endPos in endings: c.patch(endPos)
  527. if fin.kind == nkFinally:
  528. c.gen(fin[0])
  529. c.clearDest(n, dest)
  530. c.gABx(fin, opcFinallyEnd, 0, 0)
  531. proc genRaise(c: PCtx; n: PNode) =
  532. let dest = genx(c, n[0])
  533. c.gABC(n, opcRaise, dest)
  534. c.freeTemp(dest)
  535. proc genReturn(c: PCtx; n: PNode) =
  536. if n[0].kind != nkEmpty:
  537. gen(c, n[0])
  538. c.gABC(n, opcRet)
  539. proc genLit(c: PCtx; n: PNode; dest: var TDest) =
  540. # opcLdConst is now always valid. We produce the necessary copy in the
  541. # assignments now:
  542. #var opc = opcLdConst
  543. if dest < 0: dest = c.getTemp(n.typ)
  544. #elif c.prc.regInfo[dest].kind == slotFixedVar: opc = opcAsgnConst
  545. let lit = genLiteral(c, n)
  546. c.gABx(n, opcLdConst, dest, lit)
  547. proc genCall(c: PCtx; n: PNode; dest: var TDest) =
  548. # it can happen that due to inlining we have a 'n' that should be
  549. # treated as a constant (see issue #537).
  550. #if n.typ != nil and n.typ.sym != nil and n.typ.sym.magic == mPNimrodNode:
  551. # genLit(c, n, dest)
  552. # return
  553. # bug #10901: do not produce code for wrong call expressions:
  554. if n.len == 0 or n[0].typ.isNil: return
  555. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  556. let x = c.getTempRange(n.len, slotTempUnknown)
  557. # varargs need 'opcSetType' for the FFI support:
  558. let fntyp = skipTypes(n[0].typ, abstractInst)
  559. for i in 0..<n.len:
  560. var r: TRegister = x+i
  561. c.gen(n[i], r, {gfIsParam})
  562. if i >= fntyp.signatureLen:
  563. internalAssert c.config, tfVarargs in fntyp.flags
  564. c.gABx(n, opcSetType, r, c.genType(n[i].typ))
  565. if dest < 0:
  566. c.gABC(n, opcIndCall, 0, x, n.len)
  567. else:
  568. c.gABC(n, opcIndCallAsgn, dest, x, n.len)
  569. c.freeTempRange(x, n.len)
  570. template isGlobal(s: PSym): bool = sfGlobal in s.flags and s.kind != skForVar
  571. proc isGlobal(n: PNode): bool = n.kind == nkSym and isGlobal(n.sym)
  572. proc needsAsgnPatch(n: PNode): bool =
  573. n.kind in {nkBracketExpr, nkDotExpr, nkCheckedFieldExpr,
  574. nkDerefExpr, nkHiddenDeref} or (n.kind == nkSym and n.sym.isGlobal)
  575. proc genField(c: PCtx; n: PNode): TRegister =
  576. if n.kind != nkSym or n.sym.kind != skField:
  577. globalError(c.config, n.info, "no field symbol")
  578. let s = n.sym
  579. if s.position > high(typeof(result)):
  580. globalError(c.config, n.info,
  581. "too large offset! cannot generate code for: " & s.name.s)
  582. result = s.position
  583. proc genIndex(c: PCtx; n: PNode; arr: PType): TRegister =
  584. if arr.skipTypes(abstractInst).kind == tyArray and (let x = firstOrd(c.config, arr);
  585. x != Zero):
  586. let tmp = c.genx(n)
  587. # freeing the temporary here means we can produce: regA = regA - Imm
  588. c.freeTemp(tmp)
  589. result = c.getTemp(n.typ)
  590. c.gABI(n, opcSubImmInt, result, tmp, toInt(x))
  591. else:
  592. result = c.genx(n)
  593. proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags)
  594. proc genAsgnPatch(c: PCtx; le: PNode, value: TRegister) =
  595. case le.kind
  596. of nkBracketExpr:
  597. let
  598. dest = c.genx(le[0], {gfNode})
  599. idx = c.genIndex(le[1], le[0].typ)
  600. collTyp = le[0].typ.skipTypes(abstractVarRange-{tyTypeDesc})
  601. case collTyp.kind
  602. of tyString, tyCstring:
  603. c.gABC(le, opcWrStrIdx, dest, idx, value)
  604. of tyTuple:
  605. c.gABC(le, opcWrObj, dest, int le[1].intVal, value)
  606. else:
  607. c.gABC(le, opcWrArr, dest, idx, value)
  608. c.freeTemp(dest)
  609. c.freeTemp(idx)
  610. of nkCheckedFieldExpr:
  611. var objR: TDest = -1
  612. genCheckedObjAccessAux(c, le, objR, {gfNode})
  613. let idx = genField(c, le[0][1])
  614. c.gABC(le[0], opcWrObj, objR, idx, value)
  615. c.freeTemp(objR)
  616. of nkDotExpr:
  617. let dest = c.genx(le[0], {gfNode})
  618. let idx = genField(c, le[1])
  619. c.gABC(le, opcWrObj, dest, idx, value)
  620. c.freeTemp(dest)
  621. of nkDerefExpr, nkHiddenDeref:
  622. let dest = c.genx(le[0], {gfNode})
  623. c.gABC(le, opcWrDeref, dest, 0, value)
  624. c.freeTemp(dest)
  625. of nkSym:
  626. if le.sym.isGlobal:
  627. let dest = c.genx(le, {gfNodeAddr})
  628. c.gABC(le, opcWrDeref, dest, 0, value)
  629. c.freeTemp(dest)
  630. else:
  631. discard
  632. proc genNew(c: PCtx; n: PNode) =
  633. let dest = if needsAsgnPatch(n[1]): c.getTemp(n[1].typ)
  634. else: c.genx(n[1])
  635. # we use the ref's base type here as the VM conflates 'ref object'
  636. # and 'object' since internally we already have a pointer.
  637. c.gABx(n, opcNew, dest,
  638. c.genType(n[1].typ.skipTypes(abstractVar-{tyTypeDesc})[0]))
  639. c.genAsgnPatch(n[1], dest)
  640. c.freeTemp(dest)
  641. proc genNewSeq(c: PCtx; n: PNode) =
  642. let t = n[1].typ
  643. let dest = if needsAsgnPatch(n[1]): c.getTemp(t)
  644. else: c.genx(n[1])
  645. let tmp = c.genx(n[2])
  646. c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
  647. abstractVar-{tyTypeDesc})))
  648. c.gABx(n, opcNewSeq, tmp, 0)
  649. c.freeTemp(tmp)
  650. c.genAsgnPatch(n[1], dest)
  651. c.freeTemp(dest)
  652. proc genNewSeqOfCap(c: PCtx; n: PNode; dest: var TDest) =
  653. let t = n.typ
  654. if dest < 0:
  655. dest = c.getTemp(n.typ)
  656. let tmp = c.getTemp(n[1].typ)
  657. c.gABx(n, opcLdNull, dest, c.genType(t))
  658. c.gABx(n, opcLdImmInt, tmp, 0)
  659. c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
  660. abstractVar-{tyTypeDesc})))
  661. c.gABx(n, opcNewSeq, tmp, 0)
  662. c.freeTemp(tmp)
  663. proc genUnaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  664. let tmp = c.genx(n[1])
  665. if dest < 0: dest = c.getTemp(n.typ)
  666. c.gABC(n, opc, dest, tmp)
  667. c.freeTemp(tmp)
  668. proc genUnaryABI(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode; imm: BiggestInt=0) =
  669. let tmp = c.genx(n[1])
  670. if dest < 0: dest = c.getTemp(n.typ)
  671. c.gABI(n, opc, dest, tmp, imm)
  672. c.freeTemp(tmp)
  673. proc genBinaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  674. let
  675. tmp = c.genx(n[1])
  676. tmp2 = c.genx(n[2])
  677. if dest < 0: dest = c.getTemp(n.typ)
  678. c.gABC(n, opc, dest, tmp, tmp2)
  679. c.freeTemp(tmp)
  680. c.freeTemp(tmp2)
  681. proc genBinaryABCD(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  682. let
  683. tmp = c.genx(n[1])
  684. tmp2 = c.genx(n[2])
  685. tmp3 = c.genx(n[3])
  686. if dest < 0: dest = c.getTemp(n.typ)
  687. c.gABC(n, opc, dest, tmp, tmp2)
  688. c.gABC(n, opc, tmp3)
  689. c.freeTemp(tmp)
  690. c.freeTemp(tmp2)
  691. c.freeTemp(tmp3)
  692. template sizeOfLikeMsg(name): string =
  693. "'$1' requires '.importc' types to be '.completeStruct'" % [name]
  694. proc genNarrow(c: PCtx; n: PNode; dest: TDest) =
  695. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  696. # uint is uint64 in the VM, we we only need to mask the result for
  697. # other unsigned types:
  698. let size = getSize(c.config, t)
  699. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  700. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  701. elif t.kind in {tyInt8..tyInt32} or (t.kind == tyInt and size < 8):
  702. c.gABC(n, opcNarrowS, dest, TRegister(size*8))
  703. proc genNarrowU(c: PCtx; n: PNode; dest: TDest) =
  704. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  705. # uint is uint64 in the VM, we we only need to mask the result for
  706. # other unsigned types:
  707. let size = getSize(c.config, t)
  708. if t.kind in {tyUInt8..tyUInt32, tyInt8..tyInt32} or
  709. (t.kind in {tyUInt, tyInt} and size < 8):
  710. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  711. proc genBinaryABCnarrow(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  712. genBinaryABC(c, n, dest, opc)
  713. genNarrow(c, n, dest)
  714. proc genBinaryABCnarrowU(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  715. genBinaryABC(c, n, dest, opc)
  716. genNarrowU(c, n, dest)
  717. proc genSetType(c: PCtx; n: PNode; dest: TRegister) =
  718. let t = skipTypes(n.typ, abstractInst-{tyTypeDesc})
  719. if t.kind == tySet:
  720. c.gABx(n, opcSetType, dest, c.genType(t))
  721. proc genBinarySet(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  722. let
  723. tmp = c.genx(n[1])
  724. tmp2 = c.genx(n[2])
  725. if dest < 0: dest = c.getTemp(n.typ)
  726. c.genSetType(n[1], tmp)
  727. c.genSetType(n[2], tmp2)
  728. c.gABC(n, opc, dest, tmp, tmp2)
  729. c.freeTemp(tmp)
  730. c.freeTemp(tmp2)
  731. proc genBinaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
  732. let
  733. dest = c.genx(n[1])
  734. tmp = c.genx(n[2])
  735. c.gABC(n, opc, dest, tmp, 0)
  736. c.freeTemp(tmp)
  737. c.freeTemp(dest)
  738. proc genBinaryStmtVar(c: PCtx; n: PNode; opc: TOpcode) =
  739. var x = n[1]
  740. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  741. let
  742. dest = c.genx(x)
  743. tmp = c.genx(n[2])
  744. c.gABC(n, opc, dest, tmp, 0)
  745. #c.genAsgnPatch(n[1], dest)
  746. c.freeTemp(tmp)
  747. c.freeTemp(dest)
  748. proc genUnaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
  749. let tmp = c.genx(n[1])
  750. c.gABC(n, opc, tmp, 0, 0)
  751. c.freeTemp(tmp)
  752. proc genVarargsABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  753. if dest < 0: dest = getTemp(c, n.typ)
  754. var x = c.getTempRange(n.len-1, slotTempStr)
  755. for i in 1..<n.len:
  756. var r: TRegister = x+i-1
  757. c.gen(n[i], r)
  758. c.gABC(n, opc, dest, x, n.len-1)
  759. c.freeTempRange(x, n.len-1)
  760. proc isInt8Lit(n: PNode): bool =
  761. if n.kind in {nkCharLit..nkUInt64Lit}:
  762. result = n.intVal >= low(int8) and n.intVal <= high(int8)
  763. else:
  764. result = false
  765. proc isInt16Lit(n: PNode): bool =
  766. if n.kind in {nkCharLit..nkUInt64Lit}:
  767. result = n.intVal >= low(int16) and n.intVal <= high(int16)
  768. else:
  769. result = false
  770. proc genAddSubInt(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  771. if n[2].isInt8Lit:
  772. let tmp = c.genx(n[1])
  773. if dest < 0: dest = c.getTemp(n.typ)
  774. c.gABI(n, succ(opc), dest, tmp, n[2].intVal)
  775. c.freeTemp(tmp)
  776. else:
  777. genBinaryABC(c, n, dest, opc)
  778. c.genNarrow(n, dest)
  779. proc genConv(c: PCtx; n, arg: PNode; dest: var TDest; opc=opcConv) =
  780. let t2 = n.typ.skipTypes({tyDistinct})
  781. let targ2 = arg.typ.skipTypes({tyDistinct})
  782. proc implicitConv(): bool =
  783. if sameBackendType(t2, targ2): return true
  784. # xxx consider whether to use t2 and targ2 here
  785. if n.typ.kind == arg.typ.kind and arg.typ.kind == tyProc:
  786. # don't do anything for lambda lifting conversions:
  787. result = true
  788. else:
  789. result = false
  790. if implicitConv():
  791. gen(c, arg, dest)
  792. return
  793. let tmp = c.genx(arg)
  794. if dest < 0: dest = c.getTemp(n.typ)
  795. c.gABC(n, opc, dest, tmp)
  796. c.gABx(n, opc, 0, genType(c, n.typ.skipTypes({tyStatic})))
  797. c.gABx(n, opc, 0, genType(c, arg.typ.skipTypes({tyStatic})))
  798. c.freeTemp(tmp)
  799. proc genCard(c: PCtx; n: PNode; dest: var TDest) =
  800. let tmp = c.genx(n[1])
  801. if dest < 0: dest = c.getTemp(n.typ)
  802. c.genSetType(n[1], tmp)
  803. c.gABC(n, opcCard, dest, tmp)
  804. c.freeTemp(tmp)
  805. proc genCastIntFloat(c: PCtx; n: PNode; dest: var TDest) =
  806. const allowedIntegers = {tyInt..tyInt64, tyUInt..tyUInt64, tyChar, tyEnum, tyBool}
  807. var signedIntegers = {tyInt..tyInt64}
  808. var unsignedIntegers = {tyUInt..tyUInt64, tyChar, tyEnum, tyBool}
  809. let src = n[1].typ.skipTypes(abstractRange)#.kind
  810. let dst = n[0].typ.skipTypes(abstractRange)#.kind
  811. let srcSize = getSize(c.config, src)
  812. let dstSize = getSize(c.config, dst)
  813. const unsupportedCastDifferentSize =
  814. "VM does not support 'cast' from $1 with size $2 to $3 with size $4 due to different sizes"
  815. if src.kind in allowedIntegers and dst.kind in allowedIntegers:
  816. let tmp = c.genx(n[1])
  817. if dest < 0: dest = c.getTemp(n[0].typ)
  818. c.gABC(n, opcAsgnInt, dest, tmp)
  819. if dstSize != sizeof(BiggestInt): # don't do anything on biggest int types
  820. if dst.kind in signedIntegers: # we need to do sign extensions
  821. if dstSize <= srcSize:
  822. # Sign extension can be omitted when the size increases.
  823. c.gABC(n, opcSignExtend, dest, TRegister(dstSize*8))
  824. elif dst.kind in unsignedIntegers:
  825. if src.kind in signedIntegers or dstSize < srcSize:
  826. # Cast from signed to unsigned always needs narrowing. Cast
  827. # from unsigned to unsigned only needs narrowing when target
  828. # is smaller than source.
  829. c.gABC(n, opcNarrowU, dest, TRegister(dstSize*8))
  830. c.freeTemp(tmp)
  831. elif src.kind in allowedIntegers and
  832. dst.kind in {tyFloat, tyFloat32, tyFloat64}:
  833. if srcSize != dstSize:
  834. globalError(c.config, n.info, unsupportedCastDifferentSize %
  835. [$src.kind, $srcSize, $dst.kind, $dstSize])
  836. let tmp = c.genx(n[1])
  837. if dest < 0: dest = c.getTemp(n[0].typ)
  838. if dst.kind == tyFloat32:
  839. c.gABC(n, opcCastIntToFloat32, dest, tmp)
  840. else:
  841. c.gABC(n, opcCastIntToFloat64, dest, tmp)
  842. c.freeTemp(tmp)
  843. elif src.kind in {tyFloat, tyFloat32, tyFloat64} and
  844. dst.kind in allowedIntegers:
  845. if srcSize != dstSize:
  846. globalError(c.config, n.info, unsupportedCastDifferentSize %
  847. [$src.kind, $srcSize, $dst.kind, $dstSize])
  848. let tmp = c.genx(n[1])
  849. if dest < 0: dest = c.getTemp(n[0].typ)
  850. if src.kind == tyFloat32:
  851. c.gABC(n, opcCastFloatToInt32, dest, tmp)
  852. if dst.kind in unsignedIntegers:
  853. # integers are sign extended by default.
  854. # since there is no opcCastFloatToUInt32, narrowing should do the trick.
  855. c.gABC(n, opcNarrowU, dest, TRegister(32))
  856. else:
  857. c.gABC(n, opcCastFloatToInt64, dest, tmp)
  858. # narrowing for 64 bits not needed (no extended sign bits available).
  859. c.freeTemp(tmp)
  860. elif src.kind in PtrLikeKinds + {tyRef} and dst.kind == tyInt:
  861. let tmp = c.genx(n[1])
  862. if dest < 0: dest = c.getTemp(n[0].typ)
  863. var imm: BiggestInt = if src.kind in PtrLikeKinds: 1 else: 2
  864. c.gABI(n, opcCastPtrToInt, dest, tmp, imm)
  865. c.freeTemp(tmp)
  866. elif src.kind in PtrLikeKinds + {tyInt} and dst.kind in PtrLikeKinds:
  867. let tmp = c.genx(n[1])
  868. if dest < 0: dest = c.getTemp(n[0].typ)
  869. c.gABx(n, opcSetType, dest, c.genType(dst))
  870. c.gABC(n, opcCastIntToPtr, dest, tmp)
  871. c.freeTemp(tmp)
  872. elif src.kind == tyNil and dst.kind in NilableTypes:
  873. # supports casting nil literals to NilableTypes in VM
  874. # see #16024
  875. if dest < 0: dest = c.getTemp(n[0].typ)
  876. genLit(c, n[1], dest)
  877. else:
  878. # todo: support cast from tyInt to tyRef
  879. globalError(c.config, n.info, "VM does not support 'cast' from " & $src.kind & " to " & $dst.kind)
  880. proc genVoidABC(c: PCtx, n: PNode, dest: TDest, opcode: TOpcode) =
  881. unused(c, n, dest)
  882. var
  883. tmp1 = c.genx(n[1])
  884. tmp2 = c.genx(n[2])
  885. tmp3 = c.genx(n[3])
  886. c.gABC(n, opcode, tmp1, tmp2, tmp3)
  887. c.freeTemp(tmp1)
  888. c.freeTemp(tmp2)
  889. c.freeTemp(tmp3)
  890. proc genBindSym(c: PCtx; n: PNode; dest: var TDest) =
  891. # nah, cannot use c.config.features because sempass context
  892. # can have local experimental switch
  893. # if dynamicBindSym notin c.config.features:
  894. if n.len == 2: # hmm, reliable?
  895. # bindSym with static input
  896. if n[1].kind in {nkClosedSymChoice, nkOpenSymChoice, nkSym}:
  897. let idx = c.genLiteral(n[1])
  898. if dest < 0: dest = c.getTemp(n.typ)
  899. c.gABx(n, opcNBindSym, dest, idx)
  900. else:
  901. localError(c.config, n.info, "invalid bindSym usage")
  902. else:
  903. # experimental bindSym
  904. if dest < 0: dest = c.getTemp(n.typ)
  905. let x = c.getTempRange(n.len, slotTempUnknown)
  906. # callee symbol
  907. var tmp0 = TDest(x)
  908. c.genLit(n[0], tmp0)
  909. # original parameters
  910. for i in 1..<n.len-2:
  911. var r = TRegister(x+i)
  912. c.gen(n[i], r)
  913. # info node
  914. var tmp1 = TDest(x+n.len-2)
  915. c.genLit(n[^2], tmp1)
  916. # payload idx
  917. var tmp2 = TDest(x+n.len-1)
  918. c.genLit(n[^1], tmp2)
  919. c.gABC(n, opcNDynBindSym, dest, x, n.len)
  920. c.freeTempRange(x, n.len)
  921. proc fitsRegister*(t: PType): bool =
  922. assert t != nil
  923. t.skipTypes(abstractInst + {tyStatic} - {tyTypeDesc}).kind in {
  924. tyRange, tyEnum, tyBool, tyInt..tyUInt64, tyChar}
  925. proc ldNullOpcode(t: PType): TOpcode =
  926. assert t != nil
  927. if fitsRegister(t): opcLdNullReg else: opcLdNull
  928. proc whichAsgnOpc(n: PNode; requiresCopy = true): TOpcode =
  929. case n.typ.skipTypes(abstractRange+{tyOwned}-{tyTypeDesc}).kind
  930. of tyBool, tyChar, tyEnum, tyOrdinal, tyInt..tyInt64, tyUInt..tyUInt64:
  931. opcAsgnInt
  932. of tyFloat..tyFloat128:
  933. opcAsgnFloat
  934. of tyRef, tyNil, tyVar, tyLent, tyPtr:
  935. opcAsgnRef
  936. else:
  937. (if requiresCopy: opcAsgnComplex else: opcFastAsgnComplex)
  938. proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) =
  939. case m
  940. of mAnd: c.genAndOr(n, opcFJmp, dest)
  941. of mOr: c.genAndOr(n, opcTJmp, dest)
  942. of mPred, mSubI:
  943. c.genAddSubInt(n, dest, opcSubInt)
  944. of mSucc, mAddI:
  945. c.genAddSubInt(n, dest, opcAddInt)
  946. of mInc, mDec:
  947. unused(c, n, dest)
  948. let isUnsigned = n[1].typ.skipTypes(abstractVarRange).kind in {tyUInt..tyUInt64}
  949. let opc = if not isUnsigned:
  950. if m == mInc: opcAddInt else: opcSubInt
  951. else:
  952. if m == mInc: opcAddu else: opcSubu
  953. let d = c.genx(n[1])
  954. if n[2].isInt8Lit and not isUnsigned:
  955. c.gABI(n, succ(opc), d, d, n[2].intVal)
  956. else:
  957. let tmp = c.genx(n[2])
  958. c.gABC(n, opc, d, d, tmp)
  959. c.freeTemp(tmp)
  960. c.genNarrow(n[1], d)
  961. c.genAsgnPatch(n[1], d)
  962. c.freeTemp(d)
  963. of mOrd, mChr, mArrToSeq, mUnown: c.gen(n[1], dest)
  964. of generatedMagics:
  965. genCall(c, n, dest)
  966. of mNew, mNewFinalize:
  967. unused(c, n, dest)
  968. c.genNew(n)
  969. of mNewSeq:
  970. unused(c, n, dest)
  971. c.genNewSeq(n)
  972. of mNewSeqOfCap: c.genNewSeqOfCap(n, dest)
  973. of mNewString:
  974. genUnaryABC(c, n, dest, opcNewStr)
  975. # XXX buggy
  976. of mNewStringOfCap:
  977. # we ignore the 'cap' argument and translate it as 'newString(0)'.
  978. # eval n[1] for possible side effects:
  979. c.freeTemp(c.genx(n[1]))
  980. var tmp = c.getTemp(n[1].typ)
  981. c.gABx(n, opcLdImmInt, tmp, 0)
  982. if dest < 0: dest = c.getTemp(n.typ)
  983. c.gABC(n, opcNewStr, dest, tmp)
  984. c.freeTemp(tmp)
  985. # XXX buggy
  986. of mLengthOpenArray, mLengthArray, mLengthSeq:
  987. genUnaryABI(c, n, dest, opcLenSeq)
  988. of mLengthStr:
  989. case n[1].typ.skipTypes(abstractVarRange).kind
  990. of tyString: genUnaryABI(c, n, dest, opcLenStr)
  991. of tyCstring: genUnaryABI(c, n, dest, opcLenCstring)
  992. else: raiseAssert $n[1].typ.kind
  993. of mSlice:
  994. var
  995. d = c.genx(n[1])
  996. left = c.genIndex(n[2], n[1].typ)
  997. right = c.genIndex(n[3], n[1].typ)
  998. if dest < 0: dest = c.getTemp(n.typ)
  999. c.gABC(n, opcNodeToReg, dest, d)
  1000. c.gABC(n, opcSlice, dest, left, right)
  1001. c.freeTemp(left)
  1002. c.freeTemp(right)
  1003. c.freeTemp(d)
  1004. of mIncl, mExcl:
  1005. unused(c, n, dest)
  1006. var d = c.genx(n[1])
  1007. var tmp = c.genx(n[2])
  1008. c.genSetType(n[1], d)
  1009. c.gABC(n, if m == mIncl: opcIncl else: opcExcl, d, tmp)
  1010. c.freeTemp(d)
  1011. c.freeTemp(tmp)
  1012. of mCard: genCard(c, n, dest)
  1013. of mMulI: genBinaryABCnarrow(c, n, dest, opcMulInt)
  1014. of mDivI: genBinaryABCnarrow(c, n, dest, opcDivInt)
  1015. of mModI: genBinaryABCnarrow(c, n, dest, opcModInt)
  1016. of mAddF64: genBinaryABC(c, n, dest, opcAddFloat)
  1017. of mSubF64: genBinaryABC(c, n, dest, opcSubFloat)
  1018. of mMulF64: genBinaryABC(c, n, dest, opcMulFloat)
  1019. of mDivF64: genBinaryABC(c, n, dest, opcDivFloat)
  1020. of mShrI:
  1021. # modified: genBinaryABC(c, n, dest, opcShrInt)
  1022. # narrowU is applied to the left operandthe idea here is to narrow the left operand
  1023. let tmp = c.genx(n[1])
  1024. c.genNarrowU(n, tmp)
  1025. let tmp2 = c.genx(n[2])
  1026. if dest < 0: dest = c.getTemp(n.typ)
  1027. c.gABC(n, opcShrInt, dest, tmp, tmp2)
  1028. c.freeTemp(tmp)
  1029. c.freeTemp(tmp2)
  1030. of mShlI:
  1031. genBinaryABC(c, n, dest, opcShlInt)
  1032. # genNarrowU modified
  1033. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  1034. let size = getSize(c.config, t)
  1035. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  1036. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  1037. elif t.kind in {tyInt8..tyInt32} or (t.kind == tyInt and size < 8):
  1038. c.gABC(n, opcSignExtend, dest, TRegister(size*8))
  1039. of mAshrI: genBinaryABC(c, n, dest, opcAshrInt)
  1040. of mBitandI: genBinaryABC(c, n, dest, opcBitandInt)
  1041. of mBitorI: genBinaryABC(c, n, dest, opcBitorInt)
  1042. of mBitxorI: genBinaryABC(c, n, dest, opcBitxorInt)
  1043. of mAddU: genBinaryABCnarrowU(c, n, dest, opcAddu)
  1044. of mSubU: genBinaryABCnarrowU(c, n, dest, opcSubu)
  1045. of mMulU: genBinaryABCnarrowU(c, n, dest, opcMulu)
  1046. of mDivU: genBinaryABCnarrowU(c, n, dest, opcDivu)
  1047. of mModU: genBinaryABCnarrowU(c, n, dest, opcModu)
  1048. of mEqI, mEqB, mEqEnum, mEqCh:
  1049. genBinaryABC(c, n, dest, opcEqInt)
  1050. of mLeI, mLeEnum, mLeCh, mLeB:
  1051. genBinaryABC(c, n, dest, opcLeInt)
  1052. of mLtI, mLtEnum, mLtCh, mLtB:
  1053. genBinaryABC(c, n, dest, opcLtInt)
  1054. of mEqF64: genBinaryABC(c, n, dest, opcEqFloat)
  1055. of mLeF64: genBinaryABC(c, n, dest, opcLeFloat)
  1056. of mLtF64: genBinaryABC(c, n, dest, opcLtFloat)
  1057. of mLePtr, mLeU: genBinaryABC(c, n, dest, opcLeu)
  1058. of mLtPtr, mLtU: genBinaryABC(c, n, dest, opcLtu)
  1059. of mEqProc, mEqRef:
  1060. genBinaryABC(c, n, dest, opcEqRef)
  1061. of mXor: genBinaryABC(c, n, dest, opcXor)
  1062. of mNot: genUnaryABC(c, n, dest, opcNot)
  1063. of mUnaryMinusI, mUnaryMinusI64:
  1064. genUnaryABC(c, n, dest, opcUnaryMinusInt)
  1065. genNarrow(c, n, dest)
  1066. of mUnaryMinusF64: genUnaryABC(c, n, dest, opcUnaryMinusFloat)
  1067. of mUnaryPlusI, mUnaryPlusF64: gen(c, n[1], dest)
  1068. of mBitnotI:
  1069. genUnaryABC(c, n, dest, opcBitnotInt)
  1070. #genNarrowU modified, do not narrow signed types
  1071. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  1072. let size = getSize(c.config, t)
  1073. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  1074. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  1075. of mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr, mStrToStr, mEnumToStr:
  1076. genConv(c, n, n[1], dest)
  1077. of mEqStr: genBinaryABC(c, n, dest, opcEqStr)
  1078. of mEqCString: genBinaryABC(c, n, dest, opcEqCString)
  1079. of mLeStr: genBinaryABC(c, n, dest, opcLeStr)
  1080. of mLtStr: genBinaryABC(c, n, dest, opcLtStr)
  1081. of mEqSet: genBinarySet(c, n, dest, opcEqSet)
  1082. of mLeSet: genBinarySet(c, n, dest, opcLeSet)
  1083. of mLtSet: genBinarySet(c, n, dest, opcLtSet)
  1084. of mMulSet: genBinarySet(c, n, dest, opcMulSet)
  1085. of mPlusSet: genBinarySet(c, n, dest, opcPlusSet)
  1086. of mMinusSet: genBinarySet(c, n, dest, opcMinusSet)
  1087. of mConStrStr: genVarargsABC(c, n, dest, opcConcatStr)
  1088. of mInSet: genBinarySet(c, n, dest, opcContainsSet)
  1089. of mRepr: genUnaryABC(c, n, dest, opcRepr)
  1090. of mExit:
  1091. unused(c, n, dest)
  1092. var tmp = c.genx(n[1])
  1093. c.gABC(n, opcQuit, tmp)
  1094. c.freeTemp(tmp)
  1095. of mSetLengthStr, mSetLengthSeq:
  1096. unused(c, n, dest)
  1097. var d = c.genx(n[1])
  1098. var tmp = c.genx(n[2])
  1099. c.gABC(n, if m == mSetLengthStr: opcSetLenStr else: opcSetLenSeq, d, tmp)
  1100. c.genAsgnPatch(n[1], d)
  1101. c.freeTemp(tmp)
  1102. c.freeTemp(d)
  1103. of mSwap:
  1104. unused(c, n, dest)
  1105. c.gen(lowerSwap(c.graph, n, c.idgen, if c.prc == nil or c.prc.sym == nil: c.module else: c.prc.sym))
  1106. of mIsNil: genUnaryABC(c, n, dest, opcIsNil)
  1107. of mParseBiggestFloat:
  1108. if dest < 0: dest = c.getTemp(n.typ)
  1109. var d2: TRegister
  1110. # skip 'nkHiddenAddr':
  1111. let d2AsNode = n[2][0]
  1112. if needsAsgnPatch(d2AsNode):
  1113. d2 = c.getTemp(getSysType(c.graph, n.info, tyFloat))
  1114. else:
  1115. d2 = c.genx(d2AsNode)
  1116. var
  1117. tmp1 = c.genx(n[1])
  1118. c.gABC(n, opcParseFloat, dest, tmp1, d2)
  1119. c.freeTemp(tmp1)
  1120. c.genAsgnPatch(d2AsNode, d2)
  1121. c.freeTemp(d2)
  1122. of mReset:
  1123. unused(c, n, dest)
  1124. var d = c.genx(n[1])
  1125. # XXX use ldNullOpcode() here?
  1126. c.gABx(n, opcLdNull, d, c.genType(n[1].typ))
  1127. c.gABC(n, opcNodeToReg, d, d)
  1128. c.genAsgnPatch(n[1], d)
  1129. of mDefault, mZeroDefault:
  1130. if dest < 0: dest = c.getTemp(n.typ)
  1131. c.gABx(n, ldNullOpcode(n.typ), dest, c.genType(n.typ))
  1132. of mOf, mIs:
  1133. if dest < 0: dest = c.getTemp(n.typ)
  1134. var tmp = c.genx(n[1])
  1135. var idx = c.getTemp(getSysType(c.graph, n.info, tyInt))
  1136. var typ = n[2].typ
  1137. if m == mOf: typ = typ.skipTypes(abstractPtrs)
  1138. c.gABx(n, opcLdImmInt, idx, c.genType(typ))
  1139. c.gABC(n, if m == mOf: opcOf else: opcIs, dest, tmp, idx)
  1140. c.freeTemp(tmp)
  1141. c.freeTemp(idx)
  1142. of mHigh:
  1143. if dest < 0: dest = c.getTemp(n.typ)
  1144. let tmp = c.genx(n[1])
  1145. case n[1].typ.skipTypes(abstractVar-{tyTypeDesc}).kind:
  1146. of tyString: c.gABI(n, opcLenStr, dest, tmp, 1)
  1147. of tyCstring: c.gABI(n, opcLenCstring, dest, tmp, 1)
  1148. else: c.gABI(n, opcLenSeq, dest, tmp, 1)
  1149. c.freeTemp(tmp)
  1150. of mEcho:
  1151. unused(c, n, dest)
  1152. let n = n[1].skipConv
  1153. if n.kind == nkBracket:
  1154. # can happen for nim check, see bug #9609
  1155. let x = c.getTempRange(n.len, slotTempUnknown)
  1156. for i in 0..<n.len:
  1157. var r: TRegister = x+i
  1158. c.gen(n[i], r)
  1159. c.gABC(n, opcEcho, x, n.len)
  1160. c.freeTempRange(x, n.len)
  1161. of mAppendStrCh:
  1162. unused(c, n, dest)
  1163. genBinaryStmtVar(c, n, opcAddStrCh)
  1164. of mAppendStrStr:
  1165. unused(c, n, dest)
  1166. genBinaryStmtVar(c, n, opcAddStrStr)
  1167. of mAppendSeqElem:
  1168. unused(c, n, dest)
  1169. genBinaryStmtVar(c, n, opcAddSeqElem)
  1170. of mParseExprToAst:
  1171. genBinaryABC(c, n, dest, opcParseExprToAst)
  1172. of mParseStmtToAst:
  1173. genBinaryABC(c, n, dest, opcParseStmtToAst)
  1174. of mTypeTrait:
  1175. let tmp = c.genx(n[1])
  1176. if dest < 0: dest = c.getTemp(n.typ)
  1177. c.gABx(n, opcSetType, tmp, c.genType(n[1].typ))
  1178. c.gABC(n, opcTypeTrait, dest, tmp)
  1179. c.freeTemp(tmp)
  1180. of mSlurp: genUnaryABC(c, n, dest, opcSlurp)
  1181. of mStaticExec: genBinaryABCD(c, n, dest, opcGorge)
  1182. of mNLen: genUnaryABI(c, n, dest, opcLenSeq, nimNodeFlag)
  1183. of mGetImpl: genUnaryABC(c, n, dest, opcGetImpl)
  1184. of mGetImplTransf: genUnaryABC(c, n, dest, opcGetImplTransf)
  1185. of mSymOwner: genUnaryABC(c, n, dest, opcSymOwner)
  1186. of mSymIsInstantiationOf: genBinaryABC(c, n, dest, opcSymIsInstantiationOf)
  1187. of mNChild: genBinaryABC(c, n, dest, opcNChild)
  1188. of mNSetChild: genVoidABC(c, n, dest, opcNSetChild)
  1189. of mNDel: genVoidABC(c, n, dest, opcNDel)
  1190. of mNAdd: genBinaryABC(c, n, dest, opcNAdd)
  1191. of mNAddMultiple: genBinaryABC(c, n, dest, opcNAddMultiple)
  1192. of mNKind: genUnaryABC(c, n, dest, opcNKind)
  1193. of mNSymKind: genUnaryABC(c, n, dest, opcNSymKind)
  1194. of mNccValue: genUnaryABC(c, n, dest, opcNccValue)
  1195. of mNccInc: genBinaryABC(c, n, dest, opcNccInc)
  1196. of mNcsAdd: genBinaryABC(c, n, dest, opcNcsAdd)
  1197. of mNcsIncl: genBinaryABC(c, n, dest, opcNcsIncl)
  1198. of mNcsLen: genUnaryABC(c, n, dest, opcNcsLen)
  1199. of mNcsAt: genBinaryABC(c, n, dest, opcNcsAt)
  1200. of mNctPut: genVoidABC(c, n, dest, opcNctPut)
  1201. of mNctLen: genUnaryABC(c, n, dest, opcNctLen)
  1202. of mNctGet: genBinaryABC(c, n, dest, opcNctGet)
  1203. of mNctHasNext: genBinaryABC(c, n, dest, opcNctHasNext)
  1204. of mNctNext: genBinaryABC(c, n, dest, opcNctNext)
  1205. of mNIntVal: genUnaryABC(c, n, dest, opcNIntVal)
  1206. of mNFloatVal: genUnaryABC(c, n, dest, opcNFloatVal)
  1207. of mNSymbol: genUnaryABC(c, n, dest, opcNSymbol)
  1208. of mNIdent: genUnaryABC(c, n, dest, opcNIdent)
  1209. of mNGetType:
  1210. let tmp = c.genx(n[1])
  1211. if dest < 0: dest = c.getTemp(n.typ)
  1212. let rc = case n[0].sym.name.s:
  1213. of "getType": 0
  1214. of "typeKind": 1
  1215. of "getTypeInst": 2
  1216. else: 3 # "getTypeImpl"
  1217. c.gABC(n, opcNGetType, dest, tmp, rc)
  1218. c.freeTemp(tmp)
  1219. #genUnaryABC(c, n, dest, opcNGetType)
  1220. of mNSizeOf:
  1221. let imm = case n[0].sym.name.s:
  1222. of "getSize": 0
  1223. of "getAlign": 1
  1224. else: 2 # "getOffset"
  1225. c.genUnaryABI(n, dest, opcNGetSize, imm)
  1226. of mNStrVal: genUnaryABC(c, n, dest, opcNStrVal)
  1227. of mNSigHash: genUnaryABC(c, n , dest, opcNSigHash)
  1228. of mNSetIntVal:
  1229. unused(c, n, dest)
  1230. genBinaryStmt(c, n, opcNSetIntVal)
  1231. of mNSetFloatVal:
  1232. unused(c, n, dest)
  1233. genBinaryStmt(c, n, opcNSetFloatVal)
  1234. of mNSetSymbol:
  1235. unused(c, n, dest)
  1236. genBinaryStmt(c, n, opcNSetSymbol)
  1237. of mNSetIdent:
  1238. unused(c, n, dest)
  1239. genBinaryStmt(c, n, opcNSetIdent)
  1240. of mNSetStrVal:
  1241. unused(c, n, dest)
  1242. genBinaryStmt(c, n, opcNSetStrVal)
  1243. of mNNewNimNode: genBinaryABC(c, n, dest, opcNNewNimNode)
  1244. of mNCopyNimNode: genUnaryABC(c, n, dest, opcNCopyNimNode)
  1245. of mNCopyNimTree: genUnaryABC(c, n, dest, opcNCopyNimTree)
  1246. of mNBindSym: genBindSym(c, n, dest)
  1247. of mStrToIdent: genUnaryABC(c, n, dest, opcStrToIdent)
  1248. of mEqIdent: genBinaryABC(c, n, dest, opcEqIdent)
  1249. of mEqNimrodNode: genBinaryABC(c, n, dest, opcEqNimNode)
  1250. of mSameNodeType: genBinaryABC(c, n, dest, opcSameNodeType)
  1251. of mNLineInfo:
  1252. case n[0].sym.name.s
  1253. of "getFile": genUnaryABI(c, n, dest, opcNGetLineInfo, 0)
  1254. of "getLine": genUnaryABI(c, n, dest, opcNGetLineInfo, 1)
  1255. of "getColumn": genUnaryABI(c, n, dest, opcNGetLineInfo, 2)
  1256. of "copyLineInfo":
  1257. internalAssert c.config, n.len == 3
  1258. unused(c, n, dest)
  1259. genBinaryStmt(c, n, opcNCopyLineInfo)
  1260. of "setLine":
  1261. internalAssert c.config, n.len == 3
  1262. unused(c, n, dest)
  1263. genBinaryStmt(c, n, opcNSetLineInfoLine)
  1264. of "setColumn":
  1265. internalAssert c.config, n.len == 3
  1266. unused(c, n, dest)
  1267. genBinaryStmt(c, n, opcNSetLineInfoColumn)
  1268. of "setFile":
  1269. internalAssert c.config, n.len == 3
  1270. unused(c, n, dest)
  1271. genBinaryStmt(c, n, opcNSetLineInfoFile)
  1272. else: internalAssert c.config, false
  1273. of mNHint:
  1274. unused(c, n, dest)
  1275. genBinaryStmt(c, n, opcNHint)
  1276. of mNWarning:
  1277. unused(c, n, dest)
  1278. genBinaryStmt(c, n, opcNWarning)
  1279. of mNError:
  1280. if n.len <= 1:
  1281. # query error condition:
  1282. c.gABC(n, opcQueryErrorFlag, dest)
  1283. else:
  1284. # setter
  1285. unused(c, n, dest)
  1286. genBinaryStmt(c, n, opcNError)
  1287. of mNCallSite:
  1288. if dest < 0: dest = c.getTemp(n.typ)
  1289. c.gABC(n, opcCallSite, dest)
  1290. of mNGenSym: genBinaryABC(c, n, dest, opcGenSym)
  1291. of mMinI, mMaxI, mAbsI, mDotDot:
  1292. c.genCall(n, dest)
  1293. of mExpandToAst:
  1294. if n.len != 2:
  1295. globalError(c.config, n.info, "expandToAst requires 1 argument")
  1296. let arg = n[1]
  1297. if arg.kind in nkCallKinds:
  1298. #if arg[0].kind != nkSym or arg[0].sym.kind notin {skTemplate, skMacro}:
  1299. # "ExpandToAst: expanded symbol is no macro or template"
  1300. if dest < 0: dest = c.getTemp(n.typ)
  1301. c.genCall(arg, dest)
  1302. # do not call clearDest(n, dest) here as getAst has a meta-type as such
  1303. # produces a value
  1304. else:
  1305. globalError(c.config, n.info, "expandToAst requires a call expression")
  1306. of mSizeOf:
  1307. globalError(c.config, n.info, sizeOfLikeMsg("sizeof"))
  1308. of mAlignOf:
  1309. globalError(c.config, n.info, sizeOfLikeMsg("alignof"))
  1310. of mOffsetOf:
  1311. globalError(c.config, n.info, sizeOfLikeMsg("offsetof"))
  1312. of mRunnableExamples:
  1313. discard "just ignore any call to runnableExamples"
  1314. of mDestroy, mTrace: discard "ignore calls to the default destructor"
  1315. of mEnsureMove:
  1316. gen(c, n[1], dest)
  1317. of mMove:
  1318. let arg = n[1]
  1319. let a = c.genx(arg)
  1320. if dest < 0: dest = c.getTemp(arg.typ)
  1321. gABC(c, arg, whichAsgnOpc(arg, requiresCopy=false), dest, a)
  1322. # XXX use ldNullOpcode() here?
  1323. # Don't zero out the arg for now #17199
  1324. # c.gABx(n, opcLdNull, a, c.genType(arg.typ))
  1325. # c.gABx(n, opcNodeToReg, a, a)
  1326. # c.genAsgnPatch(arg, a)
  1327. c.freeTemp(a)
  1328. of mDup:
  1329. let arg = n[1]
  1330. let a = c.genx(arg)
  1331. if dest < 0: dest = c.getTemp(arg.typ)
  1332. gABC(c, arg, whichAsgnOpc(arg, requiresCopy=false), dest, a)
  1333. c.freeTemp(a)
  1334. of mNodeId:
  1335. c.genUnaryABC(n, dest, opcNodeId)
  1336. else:
  1337. # mGCref, mGCunref,
  1338. globalError(c.config, n.info, "cannot generate code for: " & $m)
  1339. proc unneededIndirection(n: PNode): bool =
  1340. n.typ.skipTypes(abstractInstOwned-{tyTypeDesc}).kind == tyRef
  1341. proc canElimAddr(n: PNode; idgen: IdGenerator): PNode =
  1342. result = nil
  1343. case n[0].kind
  1344. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  1345. var m = n[0][0]
  1346. if m.kind in {nkDerefExpr, nkHiddenDeref}:
  1347. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  1348. result = copyNode(n[0])
  1349. result.add m[0]
  1350. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  1351. result.typ = n.typ
  1352. elif n.typ.skipTypes(abstractInst).kind in {tyVar}:
  1353. result.typ = toVar(result.typ, n.typ.skipTypes(abstractInst).kind, idgen)
  1354. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1355. var m = n[0][1]
  1356. if m.kind in {nkDerefExpr, nkHiddenDeref}:
  1357. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  1358. result = copyNode(n[0])
  1359. result.add n[0][0]
  1360. result.add m[0]
  1361. if n.typ.skipTypes(abstractVar).kind != tyOpenArray:
  1362. result.typ = n.typ
  1363. elif n.typ.skipTypes(abstractInst).kind in {tyVar}:
  1364. result.typ = toVar(result.typ, n.typ.skipTypes(abstractInst).kind, idgen)
  1365. else:
  1366. if n[0].kind in {nkDerefExpr, nkHiddenDeref}:
  1367. # addr ( deref ( x )) --> x
  1368. result = n[0][0]
  1369. proc genAddr(c: PCtx, n: PNode, dest: var TDest, flags: TGenFlags) =
  1370. if (let m = canElimAddr(n, c.idgen); m != nil):
  1371. gen(c, m, dest, flags)
  1372. return
  1373. let newflags = flags-{gfNode}+{gfNodeAddr}
  1374. if isGlobal(n[0]) or n[0].kind in {nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}:
  1375. # checking for this pattern: addr(obj.field) / addr(array[i])
  1376. gen(c, n[0], dest, newflags)
  1377. else:
  1378. let tmp = c.genx(n[0], newflags)
  1379. if dest < 0: dest = c.getTemp(n.typ)
  1380. if c.prc.regInfo[tmp].kind >= slotTempUnknown:
  1381. gABC(c, n, opcAddrNode, dest, tmp)
  1382. # hack ahead; in order to fix bug #1781 we mark the temporary as
  1383. # permanent, so that it's not used for anything else:
  1384. c.prc.regInfo[tmp].kind = slotTempPerm
  1385. # XXX this is still a hack
  1386. #message(c.congig, n.info, warnUser, "suspicious opcode used")
  1387. else:
  1388. gABC(c, n, opcAddrReg, dest, tmp)
  1389. c.freeTemp(tmp)
  1390. proc genDeref(c: PCtx, n: PNode, dest: var TDest, flags: TGenFlags) =
  1391. if unneededIndirection(n[0]):
  1392. gen(c, n[0], dest, flags)
  1393. if {gfNodeAddr, gfNode} * flags == {} and fitsRegister(n.typ):
  1394. c.gABC(n, opcNodeToReg, dest, dest)
  1395. else:
  1396. let tmp = c.genx(n[0], flags)
  1397. if dest < 0: dest = c.getTemp(n.typ)
  1398. gABC(c, n, opcLdDeref, dest, tmp)
  1399. assert n.typ != nil
  1400. if {gfNodeAddr, gfNode} * flags == {} and fitsRegister(n.typ):
  1401. c.gABC(n, opcNodeToReg, dest, dest)
  1402. c.freeTemp(tmp)
  1403. proc genAsgn(c: PCtx; dest: TDest; ri: PNode; requiresCopy: bool) =
  1404. let tmp = c.genx(ri)
  1405. assert dest >= 0
  1406. gABC(c, ri, whichAsgnOpc(ri, requiresCopy), dest, tmp)
  1407. c.freeTemp(tmp)
  1408. proc setSlot(c: PCtx; v: PSym) =
  1409. # XXX generate type initialization here?
  1410. if v.position == 0:
  1411. v.position = getFreeRegister(c, if v.kind == skLet: slotFixedLet else: slotFixedVar, start = 1)
  1412. proc cannotEval(c: PCtx; n: PNode) {.noinline.} =
  1413. globalError(c.config, n.info, "cannot evaluate at compile time: " &
  1414. n.renderTree)
  1415. proc isOwnedBy(a, b: PSym): bool =
  1416. result = false
  1417. var a = a.owner
  1418. while a != nil and a.kind != skModule:
  1419. if a == b: return true
  1420. a = a.owner
  1421. proc getOwner(c: PCtx): PSym =
  1422. result = c.prc.sym
  1423. if result.isNil: result = c.module
  1424. proc importcCondVar*(s: PSym): bool {.inline.} =
  1425. # see also importcCond
  1426. if sfImportc in s.flags:
  1427. result = s.kind in {skVar, skLet, skConst}
  1428. else:
  1429. result = false
  1430. proc checkCanEval(c: PCtx; n: PNode) =
  1431. # we need to ensure that we don't evaluate 'x' here:
  1432. # proc foo() = var x ...
  1433. let s = n.sym
  1434. if {sfCompileTime, sfGlobal} <= s.flags: return
  1435. if compiletimeFFI in c.config.features and s.importcCondVar: return
  1436. if s.kind in {skVar, skTemp, skLet, skParam, skResult} and
  1437. not s.isOwnedBy(c.prc.sym) and s.owner != c.module and c.mode != emRepl:
  1438. # little hack ahead for bug #12612: assume gensym'ed variables
  1439. # are in the right scope:
  1440. if sfGenSym in s.flags and c.prc.sym == nil: discard
  1441. elif s.kind == skParam and s.typ.kind == tyTypeDesc: discard
  1442. else: cannotEval(c, n)
  1443. elif s.kind in {skProc, skFunc, skConverter, skMethod,
  1444. skIterator} and sfForward in s.flags:
  1445. cannotEval(c, n)
  1446. template needsAdditionalCopy(n): untyped =
  1447. not c.isTemp(dest) and not fitsRegister(n.typ)
  1448. proc genAdditionalCopy(c: PCtx; n: PNode; opc: TOpcode;
  1449. dest, idx, value: TRegister) =
  1450. var cc = c.getTemp(n.typ)
  1451. c.gABC(n, whichAsgnOpc(n), cc, value)
  1452. c.gABC(n, opc, dest, idx, cc)
  1453. c.freeTemp(cc)
  1454. proc preventFalseAlias(c: PCtx; n: PNode; opc: TOpcode;
  1455. dest, idx, value: TRegister) =
  1456. # opcLdObj et al really means "load address". We sometimes have to create a
  1457. # copy in order to not introduce false aliasing:
  1458. # mylocal = a.b # needs a copy of the data!
  1459. assert n.typ != nil
  1460. if needsAdditionalCopy(n):
  1461. genAdditionalCopy(c, n, opc, dest, idx, value)
  1462. else:
  1463. c.gABC(n, opc, dest, idx, value)
  1464. proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) =
  1465. case le.kind
  1466. of nkBracketExpr:
  1467. let
  1468. dest = c.genx(le[0], {gfNode})
  1469. idx = c.genIndex(le[1], le[0].typ)
  1470. tmp = c.genx(ri)
  1471. collTyp = le[0].typ.skipTypes(abstractVarRange-{tyTypeDesc})
  1472. case collTyp.kind
  1473. of tyString, tyCstring:
  1474. c.preventFalseAlias(le, opcWrStrIdx, dest, idx, tmp)
  1475. of tyTuple:
  1476. c.preventFalseAlias(le, opcWrObj, dest, int le[1].intVal, tmp)
  1477. else:
  1478. c.preventFalseAlias(le, opcWrArr, dest, idx, tmp)
  1479. c.freeTemp(tmp)
  1480. c.freeTemp(idx)
  1481. c.freeTemp(dest)
  1482. of nkCheckedFieldExpr:
  1483. var objR: TDest = -1
  1484. genCheckedObjAccessAux(c, le, objR, {gfNode})
  1485. let idx = genField(c, le[0][1])
  1486. let tmp = c.genx(ri)
  1487. c.preventFalseAlias(le[0], opcWrObj, objR, idx, tmp)
  1488. c.freeTemp(tmp)
  1489. # c.freeTemp(idx) # BUGFIX, see nkDotExpr
  1490. c.freeTemp(objR)
  1491. of nkDotExpr:
  1492. let dest = c.genx(le[0], {gfNode})
  1493. let idx = genField(c, le[1])
  1494. let tmp = c.genx(ri)
  1495. c.preventFalseAlias(le, opcWrObj, dest, idx, tmp)
  1496. # c.freeTemp(idx) # BUGFIX: idx is an immediate (field position), not a register
  1497. c.freeTemp(tmp)
  1498. c.freeTemp(dest)
  1499. of nkDerefExpr, nkHiddenDeref:
  1500. let dest = c.genx(le[0], {gfNode})
  1501. let tmp = c.genx(ri)
  1502. c.preventFalseAlias(le, opcWrDeref, dest, 0, tmp)
  1503. c.freeTemp(dest)
  1504. c.freeTemp(tmp)
  1505. of nkSym:
  1506. let s = le.sym
  1507. checkCanEval(c, le)
  1508. if s.isGlobal:
  1509. withTemp(tmp, le.typ):
  1510. c.gen(le, tmp, {gfNodeAddr})
  1511. let val = c.genx(ri)
  1512. c.preventFalseAlias(le, opcWrDeref, tmp, 0, val)
  1513. c.freeTemp(val)
  1514. else:
  1515. if s.kind == skForVar: c.setSlot s
  1516. internalAssert c.config, s.position > 0 or (s.position == 0 and
  1517. s.kind in {skParam, skResult})
  1518. var dest: TRegister = s.position + ord(s.kind == skParam)
  1519. assert le.typ != nil
  1520. if needsAdditionalCopy(le) and s.kind in {skResult, skVar, skParam}:
  1521. var cc = c.getTemp(le.typ)
  1522. gen(c, ri, cc)
  1523. c.gABC(le, whichAsgnOpc(le), dest, cc)
  1524. c.freeTemp(cc)
  1525. else:
  1526. gen(c, ri, dest)
  1527. else:
  1528. let dest = c.genx(le, {gfNodeAddr})
  1529. genAsgn(c, dest, ri, requiresCopy)
  1530. c.freeTemp(dest)
  1531. proc genTypeLit(c: PCtx; t: PType; dest: var TDest) =
  1532. var n = newNode(nkType)
  1533. n.typ = t
  1534. genLit(c, n, dest)
  1535. proc isEmptyBody(n: PNode): bool =
  1536. case n.kind
  1537. of nkStmtList:
  1538. for i in 0..<n.len:
  1539. if not isEmptyBody(n[i]): return false
  1540. result = true
  1541. else:
  1542. result = n.kind in {nkCommentStmt, nkEmpty}
  1543. proc importcCond*(c: PCtx; s: PSym): bool {.inline.} =
  1544. ## return true to importc `s`, false to execute its body instead (refs #8405)
  1545. result = false
  1546. if sfImportc in s.flags:
  1547. if s.kind in routineKinds:
  1548. return isEmptyBody(getBody(c.graph, s))
  1549. proc importcSym(c: PCtx; info: TLineInfo; s: PSym) =
  1550. when hasFFI:
  1551. if compiletimeFFI in c.config.features:
  1552. c.globals.add(importcSymbol(c.config, s))
  1553. s.position = c.globals.len
  1554. else:
  1555. localError(c.config, info,
  1556. "VM is not allowed to 'importc' without --experimental:compiletimeFFI")
  1557. else:
  1558. localError(c.config, info,
  1559. "cannot 'importc' variable at compile time; " & s.name.s)
  1560. proc getNullValue*(typ: PType, info: TLineInfo; conf: ConfigRef): PNode
  1561. proc genGlobalInit(c: PCtx; n: PNode; s: PSym) =
  1562. c.globals.add(getNullValue(s.typ, n.info, c.config))
  1563. s.position = c.globals.len
  1564. # This is rather hard to support, due to the laziness of the VM code
  1565. # generator. See tests/compile/tmacro2 for why this is necessary:
  1566. # var decls{.compileTime.}: seq[NimNode] = @[]
  1567. let dest = c.getTemp(s.typ)
  1568. c.gABx(n, opcLdGlobal, dest, s.position)
  1569. if s.astdef != nil:
  1570. let tmp = c.genx(s.astdef)
  1571. c.genAdditionalCopy(n, opcWrDeref, dest, 0, tmp)
  1572. c.freeTemp(dest)
  1573. c.freeTemp(tmp)
  1574. proc genRdVar(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1575. # gfNodeAddr and gfNode are mutually exclusive
  1576. assert card(flags * {gfNodeAddr, gfNode}) < 2
  1577. let s = n.sym
  1578. if s.isGlobal:
  1579. let isImportcVar = importcCondVar(s)
  1580. if sfCompileTime in s.flags or c.mode == emRepl or isImportcVar:
  1581. discard
  1582. elif s.position == 0:
  1583. cannotEval(c, n)
  1584. if s.position == 0:
  1585. if importcCond(c, s) or isImportcVar: c.importcSym(n.info, s)
  1586. else: genGlobalInit(c, n, s)
  1587. if dest < 0: dest = c.getTemp(n.typ)
  1588. assert s.typ != nil
  1589. if gfNodeAddr in flags:
  1590. if isImportcVar:
  1591. c.gABx(n, opcLdGlobalAddrDerefFFI, dest, s.position)
  1592. else:
  1593. c.gABx(n, opcLdGlobalAddr, dest, s.position)
  1594. elif isImportcVar:
  1595. c.gABx(n, opcLdGlobalDerefFFI, dest, s.position)
  1596. elif fitsRegister(s.typ) and gfNode notin flags:
  1597. var cc = c.getTemp(n.typ)
  1598. c.gABx(n, opcLdGlobal, cc, s.position)
  1599. c.gABC(n, opcNodeToReg, dest, cc)
  1600. c.freeTemp(cc)
  1601. else:
  1602. c.gABx(n, opcLdGlobal, dest, s.position)
  1603. else:
  1604. if s.kind == skForVar and c.mode == emRepl: c.setSlot(s)
  1605. if s.position > 0 or (s.position == 0 and
  1606. s.kind in {skParam, skResult}):
  1607. if dest < 0:
  1608. dest = s.position + ord(s.kind == skParam)
  1609. internalAssert(c.config, c.prc.regInfo[dest].kind < slotSomeTemp)
  1610. else:
  1611. # we need to generate an assignment:
  1612. let requiresCopy = c.prc.regInfo[dest].kind >= slotSomeTemp and
  1613. gfIsParam notin flags
  1614. genAsgn(c, dest, n, requiresCopy)
  1615. else:
  1616. # see tests/t99bott for an example that triggers it:
  1617. cannotEval(c, n)
  1618. template needsRegLoad(): untyped =
  1619. {gfNode, gfNodeAddr} * flags == {} and
  1620. fitsRegister(n.typ.skipTypes({tyVar, tyLent, tyStatic}))
  1621. proc genArrAccessOpcode(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode;
  1622. flags: TGenFlags) =
  1623. let a = c.genx(n[0], flags)
  1624. let b = c.genIndex(n[1], n[0].typ)
  1625. if dest < 0: dest = c.getTemp(n.typ)
  1626. if opc in {opcLdArrAddr, opcLdStrIdxAddr} and gfNodeAddr in flags:
  1627. c.gABC(n, opc, dest, a, b)
  1628. elif needsRegLoad():
  1629. var cc = c.getTemp(n.typ)
  1630. c.gABC(n, opc, cc, a, b)
  1631. c.gABC(n, opcNodeToReg, dest, cc)
  1632. c.freeTemp(cc)
  1633. else:
  1634. #message(c.config, n.info, warnUser, "argh")
  1635. #echo "FLAGS ", flags, " ", fitsRegister(n.typ), " ", typeToString(n.typ)
  1636. c.gABC(n, opc, dest, a, b)
  1637. c.freeTemp(a)
  1638. c.freeTemp(b)
  1639. proc genObjAccessAux(c: PCtx; n: PNode; a, b: int, dest: var TDest; flags: TGenFlags) =
  1640. if dest < 0: dest = c.getTemp(n.typ)
  1641. if {gfNodeAddr} * flags != {}:
  1642. c.gABC(n, opcLdObjAddr, dest, a, b)
  1643. elif needsRegLoad():
  1644. var cc = c.getTemp(n.typ)
  1645. c.gABC(n, opcLdObj, cc, a, b)
  1646. c.gABC(n, opcNodeToReg, dest, cc)
  1647. c.freeTemp(cc)
  1648. else:
  1649. c.gABC(n, opcLdObj, dest, a, b)
  1650. c.freeTemp(a)
  1651. proc genObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1652. genObjAccessAux(c, n, c.genx(n[0], flags), genField(c, n[1]), dest, flags)
  1653. proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1654. internalAssert c.config, n.kind == nkCheckedFieldExpr
  1655. # nkDotExpr to access the requested field
  1656. let accessExpr = n[0]
  1657. # nkCall to check if the discriminant is valid
  1658. var checkExpr = n[1]
  1659. let negCheck = checkExpr[0].sym.magic == mNot
  1660. if negCheck:
  1661. checkExpr = checkExpr[^1]
  1662. # Discriminant symbol
  1663. let disc = checkExpr[2]
  1664. internalAssert c.config, disc.sym.kind == skField
  1665. # Load the object in `dest`
  1666. c.gen(accessExpr[0], dest, flags)
  1667. # Load the discriminant
  1668. var discVal = c.getTemp(disc.typ)
  1669. c.gABC(n, opcLdObj, discVal, dest, genField(c, disc))
  1670. # Check if its value is contained in the supplied set
  1671. let setLit = c.genx(checkExpr[1])
  1672. var rs = c.getTemp(getSysType(c.graph, n.info, tyBool))
  1673. c.gABC(n, opcContainsSet, rs, setLit, discVal)
  1674. c.freeTemp(setLit)
  1675. # If the check fails let the user know
  1676. let lab1 = c.xjmp(n, if negCheck: opcFJmp else: opcTJmp, rs)
  1677. c.freeTemp(rs)
  1678. let strType = getSysType(c.graph, n.info, tyString)
  1679. var msgReg: TDest = c.getTemp(strType)
  1680. let fieldName = $accessExpr[1]
  1681. let msg = genFieldDefect(c.config, fieldName, disc.sym)
  1682. let strLit = newStrNode(msg, accessExpr[1].info)
  1683. strLit.typ = strType
  1684. c.genLit(strLit, msgReg)
  1685. c.gABC(n, opcInvalidField, msgReg, discVal)
  1686. c.freeTemp(discVal)
  1687. c.freeTemp(msgReg)
  1688. c.patch(lab1)
  1689. proc genCheckedObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1690. var objR: TDest = -1
  1691. genCheckedObjAccessAux(c, n, objR, flags)
  1692. let accessExpr = n[0]
  1693. # Field symbol
  1694. var field = accessExpr[1]
  1695. internalAssert c.config, field.sym.kind == skField
  1696. # Load the content now
  1697. if dest < 0: dest = c.getTemp(n.typ)
  1698. let fieldPos = genField(c, field)
  1699. if {gfNodeAddr} * flags != {}:
  1700. c.gABC(n, opcLdObjAddr, dest, objR, fieldPos)
  1701. elif needsRegLoad():
  1702. var cc = c.getTemp(accessExpr.typ)
  1703. c.gABC(n, opcLdObj, cc, objR, fieldPos)
  1704. c.gABC(n, opcNodeToReg, dest, cc)
  1705. c.freeTemp(cc)
  1706. else:
  1707. c.gABC(n, opcLdObj, dest, objR, fieldPos)
  1708. c.freeTemp(objR)
  1709. proc genArrAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1710. let arrayType = n[0].typ.skipTypes(abstractVarRange-{tyTypeDesc}).kind
  1711. case arrayType
  1712. of tyString, tyCstring:
  1713. let opc = if gfNodeAddr in flags: opcLdStrIdxAddr else: opcLdStrIdx
  1714. genArrAccessOpcode(c, n, dest, opc, flags)
  1715. of tyTuple:
  1716. c.genObjAccessAux(n, c.genx(n[0], flags), int n[1].intVal, dest, flags)
  1717. of tyTypeDesc:
  1718. c.genTypeLit(n.typ, dest)
  1719. else:
  1720. let opc = if gfNodeAddr in flags: opcLdArrAddr else: opcLdArr
  1721. genArrAccessOpcode(c, n, dest, opc, flags)
  1722. proc getNullValueAux(t: PType; obj: PNode, result: PNode; conf: ConfigRef; currPosition: var int) =
  1723. if t != nil and t.baseClass != nil:
  1724. let b = skipTypes(t.baseClass, skipPtrs)
  1725. getNullValueAux(b, b.n, result, conf, currPosition)
  1726. case obj.kind
  1727. of nkRecList:
  1728. for i in 0..<obj.len: getNullValueAux(nil, obj[i], result, conf, currPosition)
  1729. of nkRecCase:
  1730. getNullValueAux(nil, obj[0], result, conf, currPosition)
  1731. for i in 1..<obj.len:
  1732. getNullValueAux(nil, lastSon(obj[i]), result, conf, currPosition)
  1733. of nkSym:
  1734. let field = newNodeI(nkExprColonExpr, result.info)
  1735. field.add(obj)
  1736. let value = getNullValue(obj.sym.typ, result.info, conf)
  1737. value.flags.incl nfSkipFieldChecking
  1738. field.add(value)
  1739. result.add field
  1740. doAssert obj.sym.position == currPosition
  1741. inc currPosition
  1742. else: globalError(conf, result.info, "cannot create null element for: " & $obj)
  1743. proc getNullValue(typ: PType, info: TLineInfo; conf: ConfigRef): PNode =
  1744. var t = skipTypes(typ, abstractRange+{tyStatic, tyOwned}-{tyTypeDesc})
  1745. case t.kind
  1746. of tyBool, tyEnum, tyChar, tyInt..tyInt64:
  1747. result = newNodeIT(nkIntLit, info, t)
  1748. of tyUInt..tyUInt64:
  1749. result = newNodeIT(nkUIntLit, info, t)
  1750. of tyFloat..tyFloat128:
  1751. result = newNodeIT(nkFloatLit, info, t)
  1752. of tyString:
  1753. result = newNodeIT(nkStrLit, info, t)
  1754. result.strVal = ""
  1755. of tyCstring, tyVar, tyLent, tyPointer, tyPtr, tyUntyped,
  1756. tyTyped, tyTypeDesc, tyRef, tyNil:
  1757. result = newNodeIT(nkNilLit, info, t)
  1758. of tyProc:
  1759. if t.callConv != ccClosure:
  1760. result = newNodeIT(nkNilLit, info, t)
  1761. else:
  1762. result = newNodeIT(nkTupleConstr, info, t)
  1763. result.add(newNodeIT(nkNilLit, info, t))
  1764. result.add(newNodeIT(nkNilLit, info, t))
  1765. of tyObject:
  1766. result = newNodeIT(nkObjConstr, info, t)
  1767. result.add(newNodeIT(nkEmpty, info, t))
  1768. # initialize inherited fields, and all in the correct order:
  1769. var currPosition = 0
  1770. getNullValueAux(t, t.n, result, conf, currPosition)
  1771. of tyArray:
  1772. result = newNodeIT(nkBracket, info, t)
  1773. for i in 0..<toInt(lengthOrd(conf, t)):
  1774. result.add getNullValue(elemType(t), info, conf)
  1775. of tyTuple:
  1776. result = newNodeIT(nkTupleConstr, info, t)
  1777. for a in t.kids:
  1778. result.add getNullValue(a, info, conf)
  1779. of tySet:
  1780. result = newNodeIT(nkCurly, info, t)
  1781. of tySequence, tyOpenArray:
  1782. result = newNodeIT(nkBracket, info, t)
  1783. else:
  1784. globalError(conf, info, "cannot create null element for: " & $t.kind)
  1785. result = newNodeI(nkEmpty, info)
  1786. proc genVarSection(c: PCtx; n: PNode) =
  1787. for a in n:
  1788. if a.kind == nkCommentStmt: continue
  1789. #assert(a[0].kind == nkSym) can happen for transformed vars
  1790. if a.kind == nkVarTuple:
  1791. for i in 0..<a.len-2:
  1792. if a[i].kind == nkSym:
  1793. if not a[i].sym.isGlobal: setSlot(c, a[i].sym)
  1794. checkCanEval(c, a[i])
  1795. c.gen(lowerTupleUnpacking(c.graph, a, c.idgen, c.getOwner))
  1796. elif a[0].kind == nkSym:
  1797. let s = a[0].sym
  1798. checkCanEval(c, a[0])
  1799. if s.isGlobal:
  1800. let runtimeAccessToCompileTime = c.mode == emRepl and
  1801. sfCompileTime in s.flags and s.position > 0
  1802. if s.position == 0:
  1803. if importcCond(c, s): c.importcSym(a.info, s)
  1804. else:
  1805. let sa = getNullValue(s.typ, a.info, c.config)
  1806. #if s.ast.isNil: getNullValue(s.typ, a.info)
  1807. #else: s.ast
  1808. assert sa.kind != nkCall
  1809. c.globals.add(sa)
  1810. s.position = c.globals.len
  1811. if runtimeAccessToCompileTime:
  1812. discard
  1813. elif a[2].kind != nkEmpty:
  1814. let tmp = c.genx(a[0], {gfNodeAddr})
  1815. let val = c.genx(a[2])
  1816. c.genAdditionalCopy(a[2], opcWrDeref, tmp, 0, val)
  1817. c.freeTemp(val)
  1818. c.freeTemp(tmp)
  1819. elif not importcCondVar(s) and not (s.typ.kind == tyProc and s.typ.callConv == ccClosure) and
  1820. sfPure notin s.flags: # fixes #10938
  1821. # there is a pre-existing issue with closure types in VM
  1822. # if `(var s: proc () = default(proc ()); doAssert s == nil)` works for you;
  1823. # you might remove the second condition.
  1824. # the problem is that closure types are tuples in VM, but the types of its children
  1825. # shouldn't have the same type as closure types.
  1826. let tmp = c.genx(a[0], {gfNodeAddr})
  1827. let sa = getNullValue(s.typ, a.info, c.config)
  1828. let val = c.genx(sa)
  1829. c.genAdditionalCopy(sa, opcWrDeref, tmp, 0, val)
  1830. c.freeTemp(val)
  1831. c.freeTemp(tmp)
  1832. else:
  1833. setSlot(c, s)
  1834. if a[2].kind == nkEmpty:
  1835. c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ))
  1836. else:
  1837. assert s.typ != nil
  1838. if not fitsRegister(s.typ):
  1839. c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ))
  1840. let le = a[0]
  1841. assert le.typ != nil
  1842. if not fitsRegister(le.typ) and s.kind in {skResult, skVar, skParam}:
  1843. var cc = c.getTemp(le.typ)
  1844. gen(c, a[2], cc)
  1845. c.gABC(le, whichAsgnOpc(le), s.position.TRegister, cc)
  1846. c.freeTemp(cc)
  1847. else:
  1848. gen(c, a[2], s.position.TRegister)
  1849. else:
  1850. # assign to a[0]; happens for closures
  1851. if a[2].kind == nkEmpty:
  1852. let tmp = genx(c, a[0])
  1853. c.gABx(a, ldNullOpcode(a[0].typ), tmp, c.genType(a[0].typ))
  1854. c.freeTemp(tmp)
  1855. else:
  1856. genAsgn(c, a[0], a[2], true)
  1857. proc genArrayConstr(c: PCtx, n: PNode, dest: var TDest) =
  1858. if dest < 0: dest = c.getTemp(n.typ)
  1859. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1860. let intType = getSysType(c.graph, n.info, tyInt)
  1861. let seqType = n.typ.skipTypes(abstractVar-{tyTypeDesc})
  1862. if seqType.kind == tySequence:
  1863. var tmp = c.getTemp(intType)
  1864. c.gABx(n, opcLdImmInt, tmp, n.len)
  1865. c.gABx(n, opcNewSeq, dest, c.genType(seqType))
  1866. c.gABx(n, opcNewSeq, tmp, 0)
  1867. c.freeTemp(tmp)
  1868. if n.len > 0:
  1869. var tmp = getTemp(c, intType)
  1870. c.gABx(n, opcLdNullReg, tmp, c.genType(intType))
  1871. for x in n:
  1872. let a = c.genx(x)
  1873. c.preventFalseAlias(n, opcWrArr, dest, tmp, a)
  1874. c.gABI(n, opcAddImmInt, tmp, tmp, 1)
  1875. c.freeTemp(a)
  1876. c.freeTemp(tmp)
  1877. proc genSetConstr(c: PCtx, n: PNode, dest: var TDest) =
  1878. if dest < 0: dest = c.getTemp(n.typ)
  1879. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1880. for x in n:
  1881. if x.kind == nkRange:
  1882. let a = c.genx(x[0])
  1883. let b = c.genx(x[1])
  1884. c.gABC(n, opcInclRange, dest, a, b)
  1885. c.freeTemp(b)
  1886. c.freeTemp(a)
  1887. else:
  1888. let a = c.genx(x)
  1889. c.gABC(n, opcIncl, dest, a)
  1890. c.freeTemp(a)
  1891. proc genObjConstr(c: PCtx, n: PNode, dest: var TDest) =
  1892. if tfUnion in n.typ.flags: # bug #22708 # bug #13481
  1893. globalError(c.config, n.info, "object with '{.union.}' pragmas is not supported by VM")
  1894. if dest < 0: dest = c.getTemp(n.typ)
  1895. let t = n.typ.skipTypes(abstractRange+{tyOwned}-{tyTypeDesc})
  1896. if t.kind == tyRef:
  1897. c.gABx(n, opcNew, dest, c.genType(t.elementType))
  1898. else:
  1899. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1900. for i in 1..<n.len:
  1901. let it = n[i]
  1902. if it.kind == nkExprColonExpr and it[0].kind == nkSym:
  1903. let idx = genField(c, it[0])
  1904. let tmp = c.genx(it[1])
  1905. c.preventFalseAlias(it[1], opcWrObj,
  1906. dest, idx, tmp)
  1907. c.freeTemp(tmp)
  1908. else:
  1909. globalError(c.config, n.info, "invalid object constructor")
  1910. proc genTupleConstr(c: PCtx, n: PNode, dest: var TDest) =
  1911. if dest < 0: dest = c.getTemp(n.typ)
  1912. if n.typ.kind != tyTypeDesc:
  1913. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1914. # XXX x = (x.old, 22) produces wrong code ... stupid self assignments
  1915. for i in 0..<n.len:
  1916. let it = n[i]
  1917. if it.kind == nkExprColonExpr:
  1918. let idx = genField(c, it[0])
  1919. let tmp = c.genx(it[1])
  1920. c.preventFalseAlias(it[1], opcWrObj,
  1921. dest, idx, tmp)
  1922. c.freeTemp(tmp)
  1923. else:
  1924. let tmp = c.genx(it)
  1925. c.preventFalseAlias(it, opcWrObj, dest, i.TRegister, tmp)
  1926. c.freeTemp(tmp)
  1927. proc genProc*(c: PCtx; s: PSym): int
  1928. proc toKey(s: PSym): string =
  1929. result = ""
  1930. var s = s
  1931. while s != nil:
  1932. result.add s.name.s
  1933. if s.owner != nil:
  1934. if sfFromGeneric in s.flags:
  1935. s = s.instantiatedFrom.owner
  1936. else:
  1937. s = s.owner
  1938. result.add "."
  1939. else:
  1940. break
  1941. proc procIsCallback(c: PCtx; s: PSym): bool =
  1942. if s.offset < -1: return true
  1943. let key = toKey(s)
  1944. if c.callbackIndex.contains(key):
  1945. let index = c.callbackIndex[key]
  1946. doAssert s.offset == -1
  1947. s.offset = -2'i32 - index.int32
  1948. result = true
  1949. else:
  1950. result = false
  1951. proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {}) =
  1952. when defined(nimCompilerStacktraceHints):
  1953. setFrameMsg c.config$n.info & " " & $n.kind & " " & $flags
  1954. case n.kind
  1955. of nkSym:
  1956. let s = n.sym
  1957. checkCanEval(c, n)
  1958. case s.kind
  1959. of skVar, skForVar, skTemp, skLet, skResult:
  1960. genRdVar(c, n, dest, flags)
  1961. of skParam:
  1962. if s.typ.kind == tyTypeDesc:
  1963. genTypeLit(c, s.typ.skipTypes({tyTypeDesc}), dest)
  1964. else:
  1965. genRdVar(c, n, dest, flags)
  1966. of skProc, skFunc, skConverter, skMacro, skTemplate, skMethod, skIterator:
  1967. # 'skTemplate' is only allowed for 'getAst' support:
  1968. if s.kind == skIterator and s.typ.callConv == TCallingConvention.ccClosure:
  1969. globalError(c.config, n.info, "Closure iterators are not supported by VM!")
  1970. if procIsCallback(c, s): discard
  1971. elif importcCond(c, s): c.importcSym(n.info, s)
  1972. genLit(c, n, dest)
  1973. of skConst:
  1974. let constVal = if s.astdef != nil: s.astdef else: s.typ.n
  1975. if dontInlineConstant(n, constVal):
  1976. genLit(c, constVal, dest)
  1977. else:
  1978. gen(c, constVal, dest)
  1979. of skEnumField:
  1980. # we never reach this case - as of the time of this comment,
  1981. # skEnumField is folded to an int in semfold.nim, but this code
  1982. # remains for robustness
  1983. if dest < 0: dest = c.getTemp(n.typ)
  1984. if s.position >= low(int16) and s.position <= high(int16):
  1985. c.gABx(n, opcLdImmInt, dest, s.position)
  1986. else:
  1987. var lit = genLiteral(c, newIntNode(nkIntLit, s.position))
  1988. c.gABx(n, opcLdConst, dest, lit)
  1989. of skType:
  1990. genTypeLit(c, s.typ, dest)
  1991. of skGenericParam:
  1992. if c.prc.sym != nil and c.prc.sym.kind == skMacro:
  1993. genRdVar(c, n, dest, flags)
  1994. else:
  1995. globalError(c.config, n.info, "cannot generate code for: " & s.name.s)
  1996. else:
  1997. globalError(c.config, n.info, "cannot generate code for: " & s.name.s)
  1998. of nkCallKinds:
  1999. if n[0].kind == nkSym:
  2000. let s = n[0].sym
  2001. if s.magic != mNone:
  2002. genMagic(c, n, dest, s.magic)
  2003. elif s.kind == skMethod:
  2004. localError(c.config, n.info, "cannot call method " & s.name.s &
  2005. " at compile time")
  2006. else:
  2007. genCall(c, n, dest)
  2008. clearDest(c, n, dest)
  2009. else:
  2010. genCall(c, n, dest)
  2011. clearDest(c, n, dest)
  2012. of nkCharLit..nkInt64Lit:
  2013. if isInt16Lit(n):
  2014. if dest < 0: dest = c.getTemp(n.typ)
  2015. c.gABx(n, opcLdImmInt, dest, n.intVal.int)
  2016. else:
  2017. genLit(c, n, dest)
  2018. of nkUIntLit..pred(nkNilLit): genLit(c, n, dest)
  2019. of nkNilLit:
  2020. if not n.typ.isEmptyType: genLit(c, getNullValue(n.typ, n.info, c.config), dest)
  2021. else: unused(c, n, dest)
  2022. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  2023. unused(c, n, dest)
  2024. genAsgn(c, n[0], n[1], n.kind == nkAsgn)
  2025. of nkDotExpr: genObjAccess(c, n, dest, flags)
  2026. of nkCheckedFieldExpr: genCheckedObjAccess(c, n, dest, flags)
  2027. of nkBracketExpr: genArrAccess(c, n, dest, flags)
  2028. of nkDerefExpr, nkHiddenDeref: genDeref(c, n, dest, flags)
  2029. of nkAddr, nkHiddenAddr: genAddr(c, n, dest, flags)
  2030. of nkIfStmt, nkIfExpr: genIf(c, n, dest)
  2031. of nkWhenStmt:
  2032. # This is "when nimvm" node. Chose the first branch.
  2033. gen(c, n[0][1], dest)
  2034. of nkCaseStmt: genCase(c, n, dest)
  2035. of nkWhileStmt:
  2036. unused(c, n, dest)
  2037. genWhile(c, n)
  2038. of nkBlockExpr, nkBlockStmt: genBlock(c, n, dest)
  2039. of nkReturnStmt:
  2040. genReturn(c, n)
  2041. of nkRaiseStmt:
  2042. genRaise(c, n)
  2043. of nkBreakStmt:
  2044. genBreak(c, n)
  2045. of nkTryStmt, nkHiddenTryStmt: genTry(c, n, dest)
  2046. of nkStmtList:
  2047. #unused(c, n, dest)
  2048. # XXX Fix this bug properly, lexim triggers it
  2049. for x in n: gen(c, x)
  2050. of nkStmtListExpr:
  2051. for i in 0..<n.len-1: gen(c, n[i])
  2052. gen(c, n[^1], dest, flags)
  2053. of nkPragmaBlock:
  2054. gen(c, n.lastSon, dest, flags)
  2055. of nkDiscardStmt:
  2056. unused(c, n, dest)
  2057. gen(c, n[0])
  2058. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  2059. genConv(c, n, n[1], dest)
  2060. of nkObjDownConv:
  2061. genConv(c, n, n[0], dest)
  2062. of nkObjUpConv:
  2063. genConv(c, n, n[0], dest)
  2064. of nkVarSection, nkLetSection:
  2065. unused(c, n, dest)
  2066. genVarSection(c, n)
  2067. of nkLambdaKinds:
  2068. #let s = n[namePos].sym
  2069. #discard genProc(c, s)
  2070. genLit(c, newSymNode(n[namePos].sym), dest)
  2071. of nkChckRangeF, nkChckRange64, nkChckRange:
  2072. let
  2073. tmp0 = c.genx(n[0])
  2074. tmp1 = c.genx(n[1])
  2075. tmp2 = c.genx(n[2])
  2076. c.gABC(n, opcRangeChck, tmp0, tmp1, tmp2)
  2077. c.freeTemp(tmp1)
  2078. c.freeTemp(tmp2)
  2079. if dest >= 0:
  2080. gABC(c, n, whichAsgnOpc(n), dest, tmp0)
  2081. c.freeTemp(tmp0)
  2082. else:
  2083. dest = tmp0
  2084. of nkEmpty, nkCommentStmt, nkTypeSection, nkConstSection, nkPragma,
  2085. nkTemplateDef, nkIncludeStmt, nkImportStmt, nkFromStmt, nkExportStmt,
  2086. nkMixinStmt, nkBindStmt, declarativeDefs, nkMacroDef:
  2087. unused(c, n, dest)
  2088. of nkStringToCString, nkCStringToString:
  2089. gen(c, n[0], dest)
  2090. of nkBracket: genArrayConstr(c, n, dest)
  2091. of nkCurly: genSetConstr(c, n, dest)
  2092. of nkObjConstr: genObjConstr(c, n, dest)
  2093. of nkPar, nkClosure, nkTupleConstr: genTupleConstr(c, n, dest)
  2094. of nkCast:
  2095. if allowCast in c.features:
  2096. genConv(c, n, n[1], dest, opcCast)
  2097. else:
  2098. genCastIntFloat(c, n, dest)
  2099. of nkTypeOfExpr:
  2100. genTypeLit(c, n.typ, dest)
  2101. of nkComesFrom:
  2102. discard "XXX to implement for better stack traces"
  2103. else:
  2104. if n.typ != nil and n.typ.isCompileTimeOnly:
  2105. genTypeLit(c, n.typ, dest)
  2106. else:
  2107. globalError(c.config, n.info, "cannot generate VM code for " & $n)
  2108. proc removeLastEof(c: PCtx) =
  2109. let last = c.code.len-1
  2110. if last >= 0 and c.code[last].opcode == opcEof:
  2111. # overwrite last EOF:
  2112. assert c.code.len == c.debug.len
  2113. c.code.setLen(last)
  2114. c.debug.setLen(last)
  2115. proc genStmt*(c: PCtx; n: PNode): int =
  2116. c.removeLastEof
  2117. result = c.code.len
  2118. var d: TDest = -1
  2119. c.gen(n, d)
  2120. c.gABC(n, opcEof)
  2121. if d >= 0:
  2122. globalError(c.config, n.info, "VM problem: dest register is set")
  2123. proc genExpr*(c: PCtx; n: PNode, requiresValue = true): int =
  2124. c.removeLastEof
  2125. result = c.code.len
  2126. var d: TDest = -1
  2127. c.gen(n, d)
  2128. if d < 0:
  2129. if requiresValue:
  2130. globalError(c.config, n.info, "VM problem: dest register is not set")
  2131. d = 0
  2132. c.gABC(n, opcEof, d)
  2133. #echo renderTree(n)
  2134. #c.echoCode(result)
  2135. proc genParams(c: PCtx; params: PNode) =
  2136. # res.sym.position is already 0
  2137. setLen(c.prc.regInfo, max(params.len, 1))
  2138. c.prc.regInfo[0] = (inUse: true, kind: slotFixedVar)
  2139. for i in 1..<params.len:
  2140. c.prc.regInfo[i] = (inUse: true, kind: slotFixedLet)
  2141. proc finalJumpTarget(c: PCtx; pc, diff: int) =
  2142. internalAssert(c.config, regBxMin < diff and diff < regBxMax)
  2143. let oldInstr = c.code[pc]
  2144. # opcode and regA stay the same:
  2145. c.code[pc] = ((oldInstr.TInstrType and ((regOMask shl regOShift) or (regAMask shl regAShift))).TInstrType or
  2146. TInstrType(diff+wordExcess) shl regBxShift).TInstr
  2147. proc genGenericParams(c: PCtx; gp: PNode) =
  2148. var base = c.prc.regInfo.len
  2149. setLen c.prc.regInfo, base + gp.len
  2150. for i in 0..<gp.len:
  2151. var param = gp[i].sym
  2152. param.position = base + i # XXX: fix this earlier; make it consistent with templates
  2153. c.prc.regInfo[base + i] = (inUse: true, kind: slotFixedLet)
  2154. proc optimizeJumps(c: PCtx; start: int) =
  2155. const maxIterations = 10
  2156. for i in start..<c.code.len:
  2157. let opc = c.code[i].opcode
  2158. case opc
  2159. of opcTJmp, opcFJmp:
  2160. var reg = c.code[i].regA
  2161. var d = i + c.code[i].jmpDiff
  2162. for iters in countdown(maxIterations, 0):
  2163. case c.code[d].opcode
  2164. of opcJmp:
  2165. d += c.code[d].jmpDiff
  2166. of opcTJmp, opcFJmp:
  2167. if c.code[d].regA != reg: break
  2168. # tjmp x, 23
  2169. # ...
  2170. # tjmp x, 12
  2171. # -- we know 'x' is true, and so can jump to 12+13:
  2172. if c.code[d].opcode == opc:
  2173. d += c.code[d].jmpDiff
  2174. else:
  2175. # tjmp x, 23
  2176. # fjmp x, 22
  2177. # We know 'x' is true so skip to the next instruction:
  2178. d += 1
  2179. else: break
  2180. if d != i + c.code[i].jmpDiff:
  2181. c.finalJumpTarget(i, d - i)
  2182. of opcJmp, opcJmpBack:
  2183. var d = i + c.code[i].jmpDiff
  2184. var iters = maxIterations
  2185. while c.code[d].opcode == opcJmp and iters > 0:
  2186. d += c.code[d].jmpDiff
  2187. dec iters
  2188. if c.code[d].opcode == opcRet:
  2189. # optimize 'jmp to ret' to 'ret' here
  2190. c.code[i] = c.code[d]
  2191. elif d != i + c.code[i].jmpDiff:
  2192. c.finalJumpTarget(i, d - i)
  2193. else: discard
  2194. proc genProc(c: PCtx; s: PSym): int =
  2195. let
  2196. pos = c.procToCodePos.getOrDefault(s.id)
  2197. wasNotGenProcBefore = pos == 0
  2198. noRegistersAllocated = s.offset == -1
  2199. if wasNotGenProcBefore or noRegistersAllocated:
  2200. # xxx: the noRegisterAllocated check is required in order to avoid issues
  2201. # where nimsuggest can crash due as a macro with pos will be loaded
  2202. # but it doesn't have offsets for register allocations see:
  2203. # https://github.com/nim-lang/Nim/issues/18385
  2204. # Improvements and further use of IC should remove the need for this.
  2205. #if s.name.s == "outterMacro" or s.name.s == "innerProc":
  2206. # echo "GENERATING CODE FOR ", s.name.s
  2207. let last = c.code.len-1
  2208. var eofInstr: TInstr = default(TInstr)
  2209. if last >= 0 and c.code[last].opcode == opcEof:
  2210. eofInstr = c.code[last]
  2211. c.code.setLen(last)
  2212. c.debug.setLen(last)
  2213. #c.removeLastEof
  2214. result = c.code.len+1 # skip the jump instruction
  2215. c.procToCodePos[s.id] = result
  2216. # thanks to the jmp we can add top level statements easily and also nest
  2217. # procs easily:
  2218. let body = transformBody(c.graph, c.idgen, s, if isCompileTimeProc(s): {} else: {useCache})
  2219. let procStart = c.xjmp(body, opcJmp, 0)
  2220. var p = PProc(blocks: @[], sym: s)
  2221. let oldPrc = c.prc
  2222. c.prc = p
  2223. # iterate over the parameters and allocate space for them:
  2224. genParams(c, s.typ.n)
  2225. # allocate additional space for any generically bound parameters
  2226. if s.kind == skMacro and s.isGenericRoutineStrict:
  2227. genGenericParams(c, s.ast[genericParamsPos])
  2228. if tfCapturesEnv in s.typ.flags:
  2229. #let env = s.ast[paramsPos].lastSon.sym
  2230. #assert env.position == 2
  2231. c.prc.regInfo.add (inUse: true, kind: slotFixedLet)
  2232. gen(c, body)
  2233. # generate final 'return' statement:
  2234. c.gABC(body, opcRet)
  2235. c.patch(procStart)
  2236. c.gABC(body, opcEof, eofInstr.regA)
  2237. c.optimizeJumps(result)
  2238. s.offset = c.prc.regInfo.len.int32
  2239. #if s.name.s == "main" or s.name.s == "[]":
  2240. # echo renderTree(body)
  2241. # c.echoCode(result)
  2242. c.prc = oldPrc
  2243. else:
  2244. c.prc.regInfo.setLen s.offset
  2245. result = pos