vmgen.nim 76 KB

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