vmgen.nim 79 KB

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