vmgen.nim 82 KB

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