vmgen.nim 82 KB

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