vmgen.nim 83 KB

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