dasm_x86.lua 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  1. ------------------------------------------------------------------------------
  2. -- DynASM x86/x64 module.
  3. --
  4. -- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
  5. -- See dynasm.lua for full copyright notice.
  6. ------------------------------------------------------------------------------
  7. local x64 = x64
  8. -- Module information:
  9. local _info = {
  10. arch = x64 and "x64" or "x86",
  11. description = "DynASM x86/x64 module",
  12. version = "1.3.0",
  13. vernum = 10300,
  14. release = "2011-05-05",
  15. author = "Mike Pall",
  16. license = "MIT",
  17. }
  18. -- Exported glue functions for the arch-specific module.
  19. local _M = { _info = _info }
  20. -- Cache library functions.
  21. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
  22. local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable
  23. local _s = string
  24. local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
  25. local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub
  26. local concat, sort = table.concat, table.sort
  27. local bit = bit or require("bit")
  28. local band, shl, shr = bit.band, bit.lshift, bit.rshift
  29. -- Inherited tables and callbacks.
  30. local g_opt, g_arch
  31. local wline, werror, wfatal, wwarn
  32. -- Action name list.
  33. -- CHECK: Keep this in sync with the C code!
  34. local action_names = {
  35. -- int arg, 1 buffer pos:
  36. "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB",
  37. -- action arg (1 byte), int arg, 1 buffer pos (reg/num):
  38. "VREG", "SPACE", -- !x64: VREG support NYI.
  39. -- ptrdiff_t arg, 1 buffer pos (address): !x64
  40. "SETLABEL", "REL_A",
  41. -- action arg (1 byte) or int arg, 2 buffer pos (link, offset):
  42. "REL_LG", "REL_PC",
  43. -- action arg (1 byte) or int arg, 1 buffer pos (link):
  44. "IMM_LG", "IMM_PC",
  45. -- action arg (1 byte) or int arg, 1 buffer pos (offset):
  46. "LABEL_LG", "LABEL_PC",
  47. -- action arg (1 byte), 1 buffer pos (offset):
  48. "ALIGN",
  49. -- action args (2 bytes), no buffer pos.
  50. "EXTERN",
  51. -- action arg (1 byte), no buffer pos.
  52. "ESC",
  53. -- no action arg, no buffer pos.
  54. "MARK",
  55. -- action arg (1 byte), no buffer pos, terminal action:
  56. "SECTION",
  57. -- no args, no buffer pos, terminal action:
  58. "STOP"
  59. }
  60. -- Maximum number of section buffer positions for dasm_put().
  61. -- CHECK: Keep this in sync with the C code!
  62. local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
  63. -- Action name -> action number (dynamically generated below).
  64. local map_action = {}
  65. -- First action number. Everything below does not need to be escaped.
  66. local actfirst = 256-#action_names
  67. -- Action list buffer and string (only used to remove dupes).
  68. local actlist = {}
  69. local actstr = ""
  70. -- Argument list for next dasm_put(). Start with offset 0 into action list.
  71. local actargs = { 0 }
  72. -- Current number of section buffer positions for dasm_put().
  73. local secpos = 1
  74. ------------------------------------------------------------------------------
  75. -- Compute action numbers for action names.
  76. for n,name in ipairs(action_names) do
  77. local num = actfirst + n - 1
  78. map_action[name] = num
  79. end
  80. -- Dump action names and numbers.
  81. local function dumpactions(out)
  82. out:write("DynASM encoding engine action codes:\n")
  83. for n,name in ipairs(action_names) do
  84. local num = map_action[name]
  85. out:write(format(" %-10s %02X %d\n", name, num, num))
  86. end
  87. out:write("\n")
  88. end
  89. -- Write action list buffer as a huge static C array.
  90. local function writeactions(out, name)
  91. local nn = #actlist
  92. local last = actlist[nn] or 255
  93. actlist[nn] = nil -- Remove last byte.
  94. if nn == 0 then nn = 1 end
  95. out:write("static const unsigned char ", name, "[", nn, "] = {\n")
  96. local s = " "
  97. for n,b in ipairs(actlist) do
  98. s = s..b..","
  99. if #s >= 75 then
  100. assert(out:write(s, "\n"))
  101. s = " "
  102. end
  103. end
  104. out:write(s, last, "\n};\n\n") -- Add last byte back.
  105. end
  106. ------------------------------------------------------------------------------
  107. -- Add byte to action list.
  108. local function wputxb(n)
  109. assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range")
  110. actlist[#actlist+1] = n
  111. end
  112. -- Add action to list with optional arg. Advance buffer pos, too.
  113. local function waction(action, a, num)
  114. wputxb(assert(map_action[action], "bad action name `"..action.."'"))
  115. if a then actargs[#actargs+1] = a end
  116. if a or num then secpos = secpos + (num or 1) end
  117. end
  118. -- Add call to embedded DynASM C code.
  119. local function wcall(func, args)
  120. wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true)
  121. end
  122. -- Delete duplicate action list chunks. A tad slow, but so what.
  123. local function dedupechunk(offset)
  124. local al, as = actlist, actstr
  125. local chunk = char(unpack(al, offset+1, #al))
  126. local orig = find(as, chunk, 1, true)
  127. if orig then
  128. actargs[1] = orig-1 -- Replace with original offset.
  129. for i=offset+1,#al do al[i] = nil end -- Kill dupe.
  130. else
  131. actstr = as..chunk
  132. end
  133. end
  134. -- Flush action list (intervening C code or buffer pos overflow).
  135. local function wflush(term)
  136. local offset = actargs[1]
  137. if #actlist == offset then return end -- Nothing to flush.
  138. if not term then waction("STOP") end -- Terminate action list.
  139. dedupechunk(offset)
  140. wcall("put", actargs) -- Add call to dasm_put().
  141. actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
  142. secpos = 1 -- The actionlist offset occupies a buffer position, too.
  143. end
  144. -- Put escaped byte.
  145. local function wputb(n)
  146. if n >= actfirst then waction("ESC") end -- Need to escape byte.
  147. wputxb(n)
  148. end
  149. ------------------------------------------------------------------------------
  150. -- Global label name -> global label number. With auto assignment on 1st use.
  151. local next_global = 10
  152. local map_global = setmetatable({}, { __index = function(t, name)
  153. if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end
  154. local n = next_global
  155. if n > 246 then werror("too many global labels") end
  156. next_global = n + 1
  157. t[name] = n
  158. return n
  159. end})
  160. -- Dump global labels.
  161. local function dumpglobals(out, lvl)
  162. local t = {}
  163. for name, n in pairs(map_global) do t[n] = name end
  164. out:write("Global labels:\n")
  165. for i=10,next_global-1 do
  166. out:write(format(" %s\n", t[i]))
  167. end
  168. out:write("\n")
  169. end
  170. -- Write global label enum.
  171. local function writeglobals(out, prefix)
  172. local t = {}
  173. for name, n in pairs(map_global) do t[n] = name end
  174. out:write("enum {\n")
  175. for i=10,next_global-1 do
  176. out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n")
  177. end
  178. out:write(" ", prefix, "_MAX\n};\n")
  179. end
  180. -- Write global label names.
  181. local function writeglobalnames(out, name)
  182. local t = {}
  183. for name, n in pairs(map_global) do t[n] = name end
  184. out:write("static const char *const ", name, "[] = {\n")
  185. for i=10,next_global-1 do
  186. out:write(" \"", t[i], "\",\n")
  187. end
  188. out:write(" (const char *)0\n};\n")
  189. end
  190. ------------------------------------------------------------------------------
  191. -- Extern label name -> extern label number. With auto assignment on 1st use.
  192. local next_extern = -1
  193. local map_extern = setmetatable({}, { __index = function(t, name)
  194. -- No restrictions on the name for now.
  195. local n = next_extern
  196. if n < -256 then werror("too many extern labels") end
  197. next_extern = n - 1
  198. t[name] = n
  199. return n
  200. end})
  201. -- Dump extern labels.
  202. local function dumpexterns(out, lvl)
  203. local t = {}
  204. for name, n in pairs(map_extern) do t[-n] = name end
  205. out:write("Extern labels:\n")
  206. for i=1,-next_extern-1 do
  207. out:write(format(" %s\n", t[i]))
  208. end
  209. out:write("\n")
  210. end
  211. -- Write extern label names.
  212. local function writeexternnames(out, name)
  213. local t = {}
  214. for name, n in pairs(map_extern) do t[-n] = name end
  215. out:write("static const char *const ", name, "[] = {\n")
  216. for i=1,-next_extern-1 do
  217. out:write(" \"", t[i], "\",\n")
  218. end
  219. out:write(" (const char *)0\n};\n")
  220. end
  221. ------------------------------------------------------------------------------
  222. -- Arch-specific maps.
  223. local map_archdef = {} -- Ext. register name -> int. name.
  224. local map_reg_rev = {} -- Int. register name -> ext. name.
  225. local map_reg_num = {} -- Int. register name -> register number.
  226. local map_reg_opsize = {} -- Int. register name -> operand size.
  227. local map_reg_valid_base = {} -- Int. register name -> valid base register?
  228. local map_reg_valid_index = {} -- Int. register name -> valid index register?
  229. local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex.
  230. local reg_list = {} -- Canonical list of int. register names.
  231. local map_type = {} -- Type name -> { ctype, reg }
  232. local ctypenum = 0 -- Type number (for _PTx macros).
  233. local addrsize = x64 and "q" or "d" -- Size for address operands.
  234. -- Helper functions to fill register maps.
  235. local function mkrmap(sz, cl, names)
  236. local cname = format("@%s", sz)
  237. reg_list[#reg_list+1] = cname
  238. map_archdef[cl] = cname
  239. map_reg_rev[cname] = cl
  240. map_reg_num[cname] = -1
  241. map_reg_opsize[cname] = sz
  242. if sz == addrsize or sz == "d" then
  243. map_reg_valid_base[cname] = true
  244. map_reg_valid_index[cname] = true
  245. end
  246. if names then
  247. for n,name in ipairs(names) do
  248. local iname = format("@%s%x", sz, n-1)
  249. reg_list[#reg_list+1] = iname
  250. map_archdef[name] = iname
  251. map_reg_rev[iname] = name
  252. map_reg_num[iname] = n-1
  253. map_reg_opsize[iname] = sz
  254. if sz == "b" and n > 4 then map_reg_needrex[iname] = false end
  255. if sz == addrsize or sz == "d" then
  256. map_reg_valid_base[iname] = true
  257. map_reg_valid_index[iname] = true
  258. end
  259. end
  260. end
  261. for i=0,(x64 and sz ~= "f") and 15 or 7 do
  262. local needrex = sz == "b" and i > 3
  263. local iname = format("@%s%x%s", sz, i, needrex and "R" or "")
  264. if needrex then map_reg_needrex[iname] = true end
  265. local name
  266. if sz == "o" then name = format("xmm%d", i)
  267. elseif sz == "f" then name = format("st%d", i)
  268. else name = format("r%d%s", i, sz == addrsize and "" or sz) end
  269. map_archdef[name] = iname
  270. if not map_reg_rev[iname] then
  271. reg_list[#reg_list+1] = iname
  272. map_reg_rev[iname] = name
  273. map_reg_num[iname] = i
  274. map_reg_opsize[iname] = sz
  275. if sz == addrsize or sz == "d" then
  276. map_reg_valid_base[iname] = true
  277. map_reg_valid_index[iname] = true
  278. end
  279. end
  280. end
  281. reg_list[#reg_list+1] = ""
  282. end
  283. -- Integer registers (qword, dword, word and byte sized).
  284. if x64 then
  285. mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"})
  286. end
  287. mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"})
  288. mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"})
  289. mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"})
  290. map_reg_valid_index[map_archdef.esp] = false
  291. if x64 then map_reg_valid_index[map_archdef.rsp] = false end
  292. map_archdef["Ra"] = "@"..addrsize
  293. -- FP registers (internally tword sized, but use "f" as operand size).
  294. mkrmap("f", "Rf")
  295. -- SSE registers (oword sized, but qword and dword accessible).
  296. mkrmap("o", "xmm")
  297. -- Operand size prefixes to codes.
  298. local map_opsize = {
  299. byte = "b", word = "w", dword = "d", qword = "q", oword = "o", tword = "t",
  300. aword = addrsize,
  301. }
  302. -- Operand size code to number.
  303. local map_opsizenum = {
  304. b = 1, w = 2, d = 4, q = 8, o = 16, t = 10,
  305. }
  306. -- Operand size code to name.
  307. local map_opsizename = {
  308. b = "byte", w = "word", d = "dword", q = "qword", o = "oword", t = "tword",
  309. f = "fpword",
  310. }
  311. -- Valid index register scale factors.
  312. local map_xsc = {
  313. ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3,
  314. }
  315. -- Condition codes.
  316. local map_cc = {
  317. o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7,
  318. s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15,
  319. c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7,
  320. pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15,
  321. }
  322. -- Reverse defines for registers.
  323. function _M.revdef(s)
  324. return gsub(s, "@%w+", map_reg_rev)
  325. end
  326. -- Dump register names and numbers
  327. local function dumpregs(out)
  328. out:write("Register names, sizes and internal numbers:\n")
  329. for _,reg in ipairs(reg_list) do
  330. if reg == "" then
  331. out:write("\n")
  332. else
  333. local name = map_reg_rev[reg]
  334. local num = map_reg_num[reg]
  335. local opsize = map_opsizename[map_reg_opsize[reg]]
  336. out:write(format(" %-5s %-8s %s\n", name, opsize,
  337. num < 0 and "(variable)" or num))
  338. end
  339. end
  340. end
  341. ------------------------------------------------------------------------------
  342. -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC).
  343. local function wputlabel(aprefix, imm, num)
  344. if type(imm) == "number" then
  345. if imm < 0 then
  346. waction("EXTERN")
  347. wputxb(aprefix == "IMM_" and 0 or 1)
  348. imm = -imm-1
  349. else
  350. waction(aprefix.."LG", nil, num);
  351. end
  352. wputxb(imm)
  353. else
  354. waction(aprefix.."PC", imm, num)
  355. end
  356. end
  357. -- Put signed byte or arg.
  358. local function wputsbarg(n)
  359. if type(n) == "number" then
  360. if n < -128 or n > 127 then
  361. werror("signed immediate byte out of range")
  362. end
  363. if n < 0 then n = n + 256 end
  364. wputb(n)
  365. else waction("IMM_S", n) end
  366. end
  367. -- Put unsigned byte or arg.
  368. local function wputbarg(n)
  369. if type(n) == "number" then
  370. if n < 0 or n > 255 then
  371. werror("unsigned immediate byte out of range")
  372. end
  373. wputb(n)
  374. else waction("IMM_B", n) end
  375. end
  376. -- Put unsigned word or arg.
  377. local function wputwarg(n)
  378. if type(n) == "number" then
  379. if shr(n, 16) ~= 0 then
  380. werror("unsigned immediate word out of range")
  381. end
  382. wputb(band(n, 255)); wputb(shr(n, 8));
  383. else waction("IMM_W", n) end
  384. end
  385. -- Put signed or unsigned dword or arg.
  386. local function wputdarg(n)
  387. local tn = type(n)
  388. if tn == "number" then
  389. wputb(band(n, 255))
  390. wputb(band(shr(n, 8), 255))
  391. wputb(band(shr(n, 16), 255))
  392. wputb(shr(n, 24))
  393. elseif tn == "table" then
  394. wputlabel("IMM_", n[1], 1)
  395. else
  396. waction("IMM_D", n)
  397. end
  398. end
  399. -- Put operand-size dependent number or arg (defaults to dword).
  400. local function wputszarg(sz, n)
  401. if not sz or sz == "d" or sz == "q" then wputdarg(n)
  402. elseif sz == "w" then wputwarg(n)
  403. elseif sz == "b" then wputbarg(n)
  404. elseif sz == "s" then wputsbarg(n)
  405. else werror("bad operand size") end
  406. end
  407. -- Put multi-byte opcode with operand-size dependent modifications.
  408. local function wputop(sz, op, rex)
  409. local r
  410. if rex ~= 0 and not x64 then werror("bad operand size") end
  411. if sz == "w" then wputb(102) end
  412. -- Needs >32 bit numbers, but only for crc32 eax, word [ebx]
  413. if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end
  414. if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end
  415. if op >= 65536 then
  416. if rex ~= 0 then
  417. local opc3 = band(op, 0xffff00)
  418. if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then
  419. wputb(64 + band(rex, 15)); rex = 0
  420. end
  421. end
  422. wputb(shr(op, 16)); op = band(op, 0xffff)
  423. end
  424. if op >= 256 then
  425. local b = shr(op, 8)
  426. if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0 end
  427. wputb(b)
  428. op = band(op, 255)
  429. end
  430. if rex ~= 0 then wputb(64 + band(rex, 15)) end
  431. if sz == "b" then op = op - 1 end
  432. wputb(op)
  433. end
  434. -- Put ModRM or SIB formatted byte.
  435. local function wputmodrm(m, s, rm, vs, vrm)
  436. assert(m < 4 and s < 16 and rm < 16, "bad modrm operands")
  437. wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7))
  438. end
  439. -- Put ModRM/SIB plus optional displacement.
  440. local function wputmrmsib(t, imark, s, vsreg)
  441. local vreg, vxreg
  442. local reg, xreg = t.reg, t.xreg
  443. if reg and reg < 0 then reg = 0; vreg = t.vreg end
  444. if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end
  445. if s < 0 then s = 0 end
  446. -- Register mode.
  447. if sub(t.mode, 1, 1) == "r" then
  448. wputmodrm(3, s, reg)
  449. if vsreg then waction("VREG", vsreg); wputxb(2) end
  450. if vreg then waction("VREG", vreg); wputxb(0) end
  451. return
  452. end
  453. local disp = t.disp
  454. local tdisp = type(disp)
  455. -- No base register?
  456. if not reg then
  457. local riprel = false
  458. if xreg then
  459. -- Indexed mode with index register only.
  460. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp)
  461. wputmodrm(0, s, 4)
  462. if imark == "I" then waction("MARK") end
  463. if vsreg then waction("VREG", vsreg); wputxb(2) end
  464. wputmodrm(t.xsc, xreg, 5)
  465. if vxreg then waction("VREG", vxreg); wputxb(3) end
  466. else
  467. -- Pure 32 bit displacement.
  468. if x64 and tdisp ~= "table" then
  469. wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp)
  470. if imark == "I" then waction("MARK") end
  471. wputmodrm(0, 4, 5)
  472. else
  473. riprel = x64
  474. wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp)
  475. if imark == "I" then waction("MARK") end
  476. end
  477. if vsreg then waction("VREG", vsreg); wputxb(2) end
  478. end
  479. if riprel then -- Emit rip-relative displacement.
  480. if match("UWSiI", imark) then
  481. werror("NYI: rip-relative displacement followed by immediate")
  482. end
  483. -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f.
  484. wputlabel("REL_", disp[1], 2)
  485. else
  486. wputdarg(disp)
  487. end
  488. return
  489. end
  490. local m
  491. if tdisp == "number" then -- Check displacement size at assembly time.
  492. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too)
  493. if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0]
  494. elseif disp >= -128 and disp <= 127 then m = 1
  495. else m = 2 end
  496. elseif tdisp == "table" then
  497. m = 2
  498. end
  499. -- Index register present or esp as base register: need SIB encoding.
  500. if xreg or band(reg, 7) == 4 then
  501. wputmodrm(m or 2, s, 4) -- ModRM.
  502. if m == nil or imark == "I" then waction("MARK") end
  503. if vsreg then waction("VREG", vsreg); wputxb(2) end
  504. wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB.
  505. if vxreg then waction("VREG", vxreg); wputxb(3) end
  506. if vreg then waction("VREG", vreg); wputxb(1) end
  507. else
  508. wputmodrm(m or 2, s, reg) -- ModRM.
  509. if (imark == "I" and (m == 1 or m == 2)) or
  510. (m == nil and (vsreg or vreg)) then waction("MARK") end
  511. if vsreg then waction("VREG", vsreg); wputxb(2) end
  512. if vreg then waction("VREG", vreg); wputxb(1) end
  513. end
  514. -- Put displacement.
  515. if m == 1 then wputsbarg(disp)
  516. elseif m == 2 then wputdarg(disp)
  517. elseif m == nil then waction("DISP", disp) end
  518. end
  519. ------------------------------------------------------------------------------
  520. -- Return human-readable operand mode string.
  521. local function opmodestr(op, args)
  522. local m = {}
  523. for i=1,#args do
  524. local a = args[i]
  525. m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?")
  526. end
  527. return op.." "..concat(m, ",")
  528. end
  529. -- Convert number to valid integer or nil.
  530. local function toint(expr)
  531. local n = tonumber(expr)
  532. if n then
  533. if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then
  534. werror("bad integer number `"..expr.."'")
  535. end
  536. return n
  537. end
  538. end
  539. -- Parse immediate expression.
  540. local function immexpr(expr)
  541. -- &expr (pointer)
  542. if sub(expr, 1, 1) == "&" then
  543. return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2))
  544. end
  545. local prefix = sub(expr, 1, 2)
  546. -- =>expr (pc label reference)
  547. if prefix == "=>" then
  548. return "iJ", sub(expr, 3)
  549. end
  550. -- ->name (global label reference)
  551. if prefix == "->" then
  552. return "iJ", map_global[sub(expr, 3)]
  553. end
  554. -- [<>][1-9] (local label reference)
  555. local dir, lnum = match(expr, "^([<>])([1-9])$")
  556. if dir then -- Fwd: 247-255, Bkwd: 1-9.
  557. return "iJ", lnum + (dir == ">" and 246 or 0)
  558. end
  559. local extname = match(expr, "^extern%s+(%S+)$")
  560. if extname then
  561. return "iJ", map_extern[extname]
  562. end
  563. -- expr (interpreted as immediate)
  564. return "iI", expr
  565. end
  566. -- Parse displacement expression: +-num, +-expr, +-opsize*num
  567. local function dispexpr(expr)
  568. local disp = expr == "" and 0 or toint(expr)
  569. if disp then return disp end
  570. local c, dispt = match(expr, "^([+-])%s*(.+)$")
  571. if c == "+" then
  572. expr = dispt
  573. elseif not c then
  574. werror("bad displacement expression `"..expr.."'")
  575. end
  576. local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$")
  577. local ops, imm = map_opsize[opsize], toint(tailops)
  578. if ops and imm then
  579. if c == "-" then imm = -imm end
  580. return imm*map_opsizenum[ops]
  581. end
  582. local mode, iexpr = immexpr(dispt)
  583. if mode == "iJ" then
  584. if c == "-" then werror("cannot invert label reference") end
  585. return { iexpr }
  586. end
  587. return expr -- Need to return original signed expression.
  588. end
  589. -- Parse register or type expression.
  590. local function rtexpr(expr)
  591. if not expr then return end
  592. local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$")
  593. local tp = map_type[tname or expr]
  594. if tp then
  595. local reg = ovreg or tp.reg
  596. local rnum = map_reg_num[reg]
  597. if not rnum then
  598. werror("type `"..(tname or expr).."' needs a register override")
  599. end
  600. if not map_reg_valid_base[reg] then
  601. werror("bad base register override `"..(map_reg_rev[reg] or reg).."'")
  602. end
  603. return reg, rnum, tp
  604. end
  605. return expr, map_reg_num[expr]
  606. end
  607. -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }.
  608. local function parseoperand(param)
  609. local t = {}
  610. local expr = param
  611. local opsize, tailops = match(param, "^(%w+)%s*(.+)$")
  612. if opsize then
  613. t.opsize = map_opsize[opsize]
  614. if t.opsize then expr = tailops end
  615. end
  616. local br = match(expr, "^%[%s*(.-)%s*%]$")
  617. repeat
  618. if br then
  619. t.mode = "xm"
  620. -- [disp]
  621. t.disp = toint(br)
  622. if t.disp then
  623. t.mode = x64 and "xm" or "xmO"
  624. break
  625. end
  626. -- [reg...]
  627. local tp
  628. local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$")
  629. reg, t.reg, tp = rtexpr(reg)
  630. if not t.reg then
  631. -- [expr]
  632. t.mode = x64 and "xm" or "xmO"
  633. t.disp = dispexpr("+"..br)
  634. break
  635. end
  636. if t.reg == -1 then
  637. t.vreg, tailr = match(tailr, "^(%b())(.*)$")
  638. if not t.vreg then werror("bad variable register expression") end
  639. end
  640. -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr]
  641. local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$")
  642. if xsc then
  643. if not map_reg_valid_index[reg] then
  644. werror("bad index register `"..map_reg_rev[reg].."'")
  645. end
  646. t.xsc = map_xsc[xsc]
  647. t.xreg = t.reg
  648. t.vxreg = t.vreg
  649. t.reg = nil
  650. t.vreg = nil
  651. t.disp = dispexpr(tailsc)
  652. break
  653. end
  654. if not map_reg_valid_base[reg] then
  655. werror("bad base register `"..map_reg_rev[reg].."'")
  656. end
  657. -- [reg] or [reg+-disp]
  658. t.disp = toint(tailr) or (tailr == "" and 0)
  659. if t.disp then break end
  660. -- [reg+xreg...]
  661. local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$")
  662. xreg, t.xreg, tp = rtexpr(xreg)
  663. if not t.xreg then
  664. -- [reg+-expr]
  665. t.disp = dispexpr(tailr)
  666. break
  667. end
  668. if not map_reg_valid_index[xreg] then
  669. werror("bad index register `"..map_reg_rev[xreg].."'")
  670. end
  671. if t.xreg == -1 then
  672. t.vxreg, tailx = match(tailx, "^(%b())(.*)$")
  673. if not t.vxreg then werror("bad variable register expression") end
  674. end
  675. -- [reg+xreg*xsc...]
  676. local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$")
  677. if xsc then
  678. t.xsc = map_xsc[xsc]
  679. tailx = tailsc
  680. end
  681. -- [...] or [...+-disp] or [...+-expr]
  682. t.disp = dispexpr(tailx)
  683. else
  684. -- imm or opsize*imm
  685. local imm = toint(expr)
  686. if not imm and sub(expr, 1, 1) == "*" and t.opsize then
  687. imm = toint(sub(expr, 2))
  688. if imm then
  689. imm = imm * map_opsizenum[t.opsize]
  690. t.opsize = nil
  691. end
  692. end
  693. if imm then
  694. if t.opsize then werror("bad operand size override") end
  695. local m = "i"
  696. if imm == 1 then m = m.."1" end
  697. if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end
  698. if imm >= -128 and imm <= 127 then m = m.."S" end
  699. t.imm = imm
  700. t.mode = m
  701. break
  702. end
  703. local tp
  704. local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$")
  705. reg, t.reg, tp = rtexpr(reg)
  706. if t.reg then
  707. if t.reg == -1 then
  708. t.vreg, tailr = match(tailr, "^(%b())(.*)$")
  709. if not t.vreg then werror("bad variable register expression") end
  710. end
  711. -- reg
  712. if tailr == "" then
  713. if t.opsize then werror("bad operand size override") end
  714. t.opsize = map_reg_opsize[reg]
  715. if t.opsize == "f" then
  716. t.mode = t.reg == 0 and "fF" or "f"
  717. else
  718. if reg == "@w4" or (x64 and reg == "@d4") then
  719. wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'"))
  720. end
  721. t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm")
  722. end
  723. t.needrex = map_reg_needrex[reg]
  724. break
  725. end
  726. -- type[idx], type[idx].field, type->field -> [reg+offset_expr]
  727. if not tp then werror("bad operand `"..param.."'") end
  728. t.mode = "xm"
  729. t.disp = format(tp.ctypefmt, tailr)
  730. else
  731. t.mode, t.imm = immexpr(expr)
  732. if sub(t.mode, -1) == "J" then
  733. if t.opsize and t.opsize ~= addrsize then
  734. werror("bad operand size override")
  735. end
  736. t.opsize = addrsize
  737. end
  738. end
  739. end
  740. until true
  741. return t
  742. end
  743. ------------------------------------------------------------------------------
  744. -- x86 Template String Description
  745. -- ===============================
  746. --
  747. -- Each template string is a list of [match:]pattern pairs,
  748. -- separated by "|". The first match wins. No match means a
  749. -- bad or unsupported combination of operand modes or sizes.
  750. --
  751. -- The match part and the ":" is omitted if the operation has
  752. -- no operands. Otherwise the first N characters are matched
  753. -- against the mode strings of each of the N operands.
  754. --
  755. -- The mode string for each operand type is (see parseoperand()):
  756. -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl
  757. -- FP register: "f", +"F" for st0
  758. -- Index operand: "xm", +"O" for [disp] (pure offset)
  759. -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1,
  760. -- +"I" for arg, +"P" for pointer
  761. -- Any: +"J" for valid jump targets
  762. --
  763. -- So a match character "m" (mixed) matches both an integer register
  764. -- and an index operand (to be encoded with the ModRM/SIB scheme).
  765. -- But "r" matches only a register and "x" only an index operand
  766. -- (e.g. for FP memory access operations).
  767. --
  768. -- The operand size match string starts right after the mode match
  769. -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty.
  770. -- The effective data size of the operation is matched against this list.
  771. --
  772. -- If only the regular "b", "w", "d", "q", "t" operand sizes are
  773. -- present, then all operands must be the same size. Unspecified sizes
  774. -- are ignored, but at least one operand must have a size or the pattern
  775. -- won't match (use the "byte", "word", "dword", "qword", "tword"
  776. -- operand size overrides. E.g.: mov dword [eax], 1).
  777. --
  778. -- If the list has a "1" or "2" prefix, the operand size is taken
  779. -- from the respective operand and any other operand sizes are ignored.
  780. -- If the list contains only ".", all operand sizes are ignored.
  781. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes
  782. -- are compared to the match.
  783. --
  784. -- E.g. "rrdw" matches for either two dword registers or two word
  785. -- registers. "Fx2dq" matches an st0 operand plus an index operand
  786. -- pointing to a dword (float) or qword (double).
  787. --
  788. -- Every character after the ":" is part of the pattern string:
  789. -- Hex chars are accumulated to form the opcode (left to right).
  790. -- "n" disables the standard opcode mods
  791. -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q")
  792. -- "X" Force REX.W.
  793. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode.
  794. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand.
  795. -- The spare 3 bits are either filled with the last hex digit or
  796. -- the result from a previous "r"/"R". The opcode is restored.
  797. --
  798. -- All of the following characters force a flush of the opcode:
  799. -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand.
  800. -- "S" stores a signed 8 bit immediate from the last operand.
  801. -- "U" stores an unsigned 8 bit immediate from the last operand.
  802. -- "W" stores an unsigned 16 bit immediate from the last operand.
  803. -- "i" stores an operand sized immediate from the last operand.
  804. -- "I" dito, but generates an action code to optionally modify
  805. -- the opcode (+2) for a signed 8 bit immediate.
  806. -- "J" generates one of the REL action codes from the last operand.
  807. --
  808. ------------------------------------------------------------------------------
  809. -- Template strings for x86 instructions. Ordered by first opcode byte.
  810. -- Unimplemented opcodes (deliberate omissions) are marked with *.
  811. local map_op = {
  812. -- 00-05: add...
  813. -- 06: *push es
  814. -- 07: *pop es
  815. -- 08-0D: or...
  816. -- 0E: *push cs
  817. -- 0F: two byte opcode prefix
  818. -- 10-15: adc...
  819. -- 16: *push ss
  820. -- 17: *pop ss
  821. -- 18-1D: sbb...
  822. -- 1E: *push ds
  823. -- 1F: *pop ds
  824. -- 20-25: and...
  825. es_0 = "26",
  826. -- 27: *daa
  827. -- 28-2D: sub...
  828. cs_0 = "2E",
  829. -- 2F: *das
  830. -- 30-35: xor...
  831. ss_0 = "36",
  832. -- 37: *aaa
  833. -- 38-3D: cmp...
  834. ds_0 = "3E",
  835. -- 3F: *aas
  836. inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m",
  837. dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m",
  838. push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or
  839. "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i",
  840. pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m",
  841. -- 60: *pusha, *pushad, *pushaw
  842. -- 61: *popa, *popad, *popaw
  843. -- 62: *bound rdw,x
  844. -- 63: x86: *arpl mw,rw
  845. movsxd_2 = x64 and "rm/qd:63rM",
  846. fs_0 = "64",
  847. gs_0 = "65",
  848. o16_0 = "66",
  849. a16_0 = not x64 and "67" or nil,
  850. a32_0 = x64 and "67",
  851. -- 68: push idw
  852. -- 69: imul rdw,mdw,idw
  853. -- 6A: push ib
  854. -- 6B: imul rdw,mdw,S
  855. -- 6C: *insb
  856. -- 6D: *insd, *insw
  857. -- 6E: *outsb
  858. -- 6F: *outsd, *outsw
  859. -- 70-7F: jcc lb
  860. -- 80: add... mb,i
  861. -- 81: add... mdw,i
  862. -- 82: *undefined
  863. -- 83: add... mdw,S
  864. test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi",
  865. -- 86: xchg rb,mb
  866. -- 87: xchg rdw,mdw
  867. -- 88: mov mb,r
  868. -- 89: mov mdw,r
  869. -- 8A: mov r,mb
  870. -- 8B: mov r,mdw
  871. -- 8C: *mov mdw,seg
  872. lea_2 = "rx1dq:8DrM",
  873. -- 8E: *mov seg,mdw
  874. -- 8F: pop mdw
  875. nop_0 = "90",
  876. xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm",
  877. cbw_0 = "6698",
  878. cwde_0 = "98",
  879. cdqe_0 = "4898",
  880. cwd_0 = "6699",
  881. cdq_0 = "99",
  882. cqo_0 = "4899",
  883. -- 9A: *call iw:idw
  884. wait_0 = "9B",
  885. fwait_0 = "9B",
  886. pushf_0 = "9C",
  887. pushfd_0 = not x64 and "9C",
  888. pushfq_0 = x64 and "9C",
  889. popf_0 = "9D",
  890. popfd_0 = not x64 and "9D",
  891. popfq_0 = x64 and "9D",
  892. sahf_0 = "9E",
  893. lahf_0 = "9F",
  894. mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi",
  895. movsb_0 = "A4",
  896. movsw_0 = "66A5",
  897. movsd_0 = "A5",
  898. cmpsb_0 = "A6",
  899. cmpsw_0 = "66A7",
  900. cmpsd_0 = "A7",
  901. -- A8: test Rb,i
  902. -- A9: test Rdw,i
  903. stosb_0 = "AA",
  904. stosw_0 = "66AB",
  905. stosd_0 = "AB",
  906. lodsb_0 = "AC",
  907. lodsw_0 = "66AD",
  908. lodsd_0 = "AD",
  909. scasb_0 = "AE",
  910. scasw_0 = "66AF",
  911. scasd_0 = "AF",
  912. -- B0-B7: mov rb,i
  913. -- B8-BF: mov rdw,i
  914. -- C0: rol... mb,i
  915. -- C1: rol... mdw,i
  916. ret_1 = "i.:nC2W",
  917. ret_0 = "C3",
  918. -- C4: *les rdw,mq
  919. -- C5: *lds rdw,mq
  920. -- C6: mov mb,i
  921. -- C7: mov mdw,i
  922. -- C8: *enter iw,ib
  923. leave_0 = "C9",
  924. -- CA: *retf iw
  925. -- CB: *retf
  926. int3_0 = "CC",
  927. int_1 = "i.:nCDU",
  928. into_0 = "CE",
  929. -- CF: *iret
  930. -- D0: rol... mb,1
  931. -- D1: rol... mdw,1
  932. -- D2: rol... mb,cl
  933. -- D3: rol... mb,cl
  934. -- D4: *aam ib
  935. -- D5: *aad ib
  936. -- D6: *salc
  937. -- D7: *xlat
  938. -- D8-DF: floating point ops
  939. -- E0: *loopne
  940. -- E1: *loope
  941. -- E2: *loop
  942. -- E3: *jcxz, *jecxz
  943. -- E4: *in Rb,ib
  944. -- E5: *in Rdw,ib
  945. -- E6: *out ib,Rb
  946. -- E7: *out ib,Rdw
  947. call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J",
  948. jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB
  949. -- EA: *jmp iw:idw
  950. -- EB: jmp ib
  951. -- EC: *in Rb,dx
  952. -- ED: *in Rdw,dx
  953. -- EE: *out dx,Rb
  954. -- EF: *out dx,Rdw
  955. -- F0: *lock
  956. int1_0 = "F1",
  957. repne_0 = "F2",
  958. repnz_0 = "F2",
  959. rep_0 = "F3",
  960. repe_0 = "F3",
  961. repz_0 = "F3",
  962. -- F4: *hlt
  963. cmc_0 = "F5",
  964. -- F6: test... mb,i; div... mb
  965. -- F7: test... mdw,i; div... mdw
  966. clc_0 = "F8",
  967. stc_0 = "F9",
  968. -- FA: *cli
  969. cld_0 = "FC",
  970. std_0 = "FD",
  971. -- FE: inc... mb
  972. -- FF: inc... mdw
  973. -- misc ops
  974. not_1 = "m:F72m",
  975. neg_1 = "m:F73m",
  976. mul_1 = "m:F74m",
  977. imul_1 = "m:F75m",
  978. div_1 = "m:F76m",
  979. idiv_1 = "m:F77m",
  980. imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi",
  981. imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi",
  982. movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:",
  983. movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:",
  984. bswap_1 = "rqd:0FC8r",
  985. bsf_2 = "rmqdw:0FBCrM",
  986. bsr_2 = "rmqdw:0FBDrM",
  987. bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU",
  988. btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU",
  989. btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU",
  990. bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU",
  991. rdtsc_0 = "0F31", -- P1+
  992. cpuid_0 = "0FA2", -- P1+
  993. -- floating point ops
  994. fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m",
  995. fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m",
  996. fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m",
  997. fpop_0 = "DDD8", -- Alias for fstp st0.
  998. fist_1 = "xw:nDF2m|xd:DB2m",
  999. fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m",
  1000. fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m",
  1001. fxch_0 = "D9C9",
  1002. fxch_1 = "ff:D9C8r",
  1003. fxch_2 = "fFf:D9C8r|Fff:D9C8R",
  1004. fucom_1 = "ff:DDE0r",
  1005. fucom_2 = "Fff:DDE0R",
  1006. fucomp_1 = "ff:DDE8r",
  1007. fucomp_2 = "Fff:DDE8R",
  1008. fucomi_1 = "ff:DBE8r", -- P6+
  1009. fucomi_2 = "Fff:DBE8R", -- P6+
  1010. fucomip_1 = "ff:DFE8r", -- P6+
  1011. fucomip_2 = "Fff:DFE8R", -- P6+
  1012. fcomi_1 = "ff:DBF0r", -- P6+
  1013. fcomi_2 = "Fff:DBF0R", -- P6+
  1014. fcomip_1 = "ff:DFF0r", -- P6+
  1015. fcomip_2 = "Fff:DFF0R", -- P6+
  1016. fucompp_0 = "DAE9",
  1017. fcompp_0 = "DED9",
  1018. fldcw_1 = "xw:nD95m",
  1019. fstcw_1 = "xw:n9BD97m",
  1020. fnstcw_1 = "xw:nD97m",
  1021. fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m",
  1022. fnstsw_1 = "Rw:nDFE0|xw:nDD7m",
  1023. fclex_0 = "9BDBE2",
  1024. fnclex_0 = "DBE2",
  1025. fnop_0 = "D9D0",
  1026. -- D9D1-D9DF: unassigned
  1027. fchs_0 = "D9E0",
  1028. fabs_0 = "D9E1",
  1029. -- D9E2: unassigned
  1030. -- D9E3: unassigned
  1031. ftst_0 = "D9E4",
  1032. fxam_0 = "D9E5",
  1033. -- D9E6: unassigned
  1034. -- D9E7: unassigned
  1035. fld1_0 = "D9E8",
  1036. fldl2t_0 = "D9E9",
  1037. fldl2e_0 = "D9EA",
  1038. fldpi_0 = "D9EB",
  1039. fldlg2_0 = "D9EC",
  1040. fldln2_0 = "D9ED",
  1041. fldz_0 = "D9EE",
  1042. -- D9EF: unassigned
  1043. f2xm1_0 = "D9F0",
  1044. fyl2x_0 = "D9F1",
  1045. fptan_0 = "D9F2",
  1046. fpatan_0 = "D9F3",
  1047. fxtract_0 = "D9F4",
  1048. fprem1_0 = "D9F5",
  1049. fdecstp_0 = "D9F6",
  1050. fincstp_0 = "D9F7",
  1051. fprem_0 = "D9F8",
  1052. fyl2xp1_0 = "D9F9",
  1053. fsqrt_0 = "D9FA",
  1054. fsincos_0 = "D9FB",
  1055. frndint_0 = "D9FC",
  1056. fscale_0 = "D9FD",
  1057. fsin_0 = "D9FE",
  1058. fcos_0 = "D9FF",
  1059. -- SSE, SSE2
  1060. andnpd_2 = "rmo:660F55rM",
  1061. andnps_2 = "rmo:0F55rM",
  1062. andpd_2 = "rmo:660F54rM",
  1063. andps_2 = "rmo:0F54rM",
  1064. clflush_1 = "x.:0FAE7m",
  1065. cmppd_3 = "rmio:660FC2rMU",
  1066. cmpps_3 = "rmio:0FC2rMU",
  1067. cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:",
  1068. cmpss_3 = "rrio:F30FC2rMU|rxi/od:",
  1069. comisd_2 = "rro:660F2FrM|rx/oq:",
  1070. comiss_2 = "rro:0F2FrM|rx/od:",
  1071. cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:",
  1072. cvtdq2ps_2 = "rmo:0F5BrM",
  1073. cvtpd2dq_2 = "rmo:F20FE6rM",
  1074. cvtpd2ps_2 = "rmo:660F5ArM",
  1075. cvtpi2pd_2 = "rx/oq:660F2ArM",
  1076. cvtpi2ps_2 = "rx/oq:0F2ArM",
  1077. cvtps2dq_2 = "rmo:660F5BrM",
  1078. cvtps2pd_2 = "rro:0F5ArM|rx/oq:",
  1079. cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:",
  1080. cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:",
  1081. cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM",
  1082. cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM",
  1083. cvtss2sd_2 = "rro:F30F5ArM|rx/od:",
  1084. cvtss2si_2 = "rr/do:F20F2CrM|rr/qo:|rxd:|rx/qd:",
  1085. cvttpd2dq_2 = "rmo:660FE6rM",
  1086. cvttps2dq_2 = "rmo:F30F5BrM",
  1087. cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:",
  1088. cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:",
  1089. ldmxcsr_1 = "xd:0FAE2m",
  1090. lfence_0 = "0FAEE8",
  1091. maskmovdqu_2 = "rro:660FF7rM",
  1092. mfence_0 = "0FAEF0",
  1093. movapd_2 = "rmo:660F28rM|mro:660F29Rm",
  1094. movaps_2 = "rmo:0F28rM|mro:0F29Rm",
  1095. movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:",
  1096. movdqa_2 = "rmo:660F6FrM|mro:660F7FRm",
  1097. movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm",
  1098. movhlps_2 = "rro:0F12rM",
  1099. movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm",
  1100. movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm",
  1101. movlhps_2 = "rro:0F16rM",
  1102. movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm",
  1103. movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm",
  1104. movmskpd_2 = "rr/do:660F50rM",
  1105. movmskps_2 = "rr/do:0F50rM",
  1106. movntdq_2 = "xro:660FE7Rm",
  1107. movnti_2 = "xrqd:0FC3Rm",
  1108. movntpd_2 = "xro:660F2BRm",
  1109. movntps_2 = "xro:0F2BRm",
  1110. movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm",
  1111. movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm",
  1112. movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm",
  1113. movupd_2 = "rmo:660F10rM|mro:660F11Rm",
  1114. movups_2 = "rmo:0F10rM|mro:0F11Rm",
  1115. orpd_2 = "rmo:660F56rM",
  1116. orps_2 = "rmo:0F56rM",
  1117. packssdw_2 = "rmo:660F6BrM",
  1118. packsswb_2 = "rmo:660F63rM",
  1119. packuswb_2 = "rmo:660F67rM",
  1120. paddb_2 = "rmo:660FFCrM",
  1121. paddd_2 = "rmo:660FFErM",
  1122. paddq_2 = "rmo:660FD4rM",
  1123. paddsb_2 = "rmo:660FECrM",
  1124. paddsw_2 = "rmo:660FEDrM",
  1125. paddusb_2 = "rmo:660FDCrM",
  1126. paddusw_2 = "rmo:660FDDrM",
  1127. paddw_2 = "rmo:660FFDrM",
  1128. pand_2 = "rmo:660FDBrM",
  1129. pandn_2 = "rmo:660FDFrM",
  1130. pause_0 = "F390",
  1131. pavgb_2 = "rmo:660FE0rM",
  1132. pavgw_2 = "rmo:660FE3rM",
  1133. pcmpeqb_2 = "rmo:660F74rM",
  1134. pcmpeqd_2 = "rmo:660F76rM",
  1135. pcmpeqw_2 = "rmo:660F75rM",
  1136. pcmpgtb_2 = "rmo:660F64rM",
  1137. pcmpgtd_2 = "rmo:660F66rM",
  1138. pcmpgtw_2 = "rmo:660F65rM",
  1139. pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nrMU", -- Mem op: SSE4.1 only.
  1140. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:",
  1141. pmaddwd_2 = "rmo:660FF5rM",
  1142. pmaxsw_2 = "rmo:660FEErM",
  1143. pmaxub_2 = "rmo:660FDErM",
  1144. pminsw_2 = "rmo:660FEArM",
  1145. pminub_2 = "rmo:660FDArM",
  1146. pmovmskb_2 = "rr/do:660FD7rM",
  1147. pmulhuw_2 = "rmo:660FE4rM",
  1148. pmulhw_2 = "rmo:660FE5rM",
  1149. pmullw_2 = "rmo:660FD5rM",
  1150. pmuludq_2 = "rmo:660FF4rM",
  1151. por_2 = "rmo:660FEBrM",
  1152. prefetchnta_1 = "xb:n0F180m",
  1153. prefetcht0_1 = "xb:n0F181m",
  1154. prefetcht1_1 = "xb:n0F182m",
  1155. prefetcht2_1 = "xb:n0F183m",
  1156. psadbw_2 = "rmo:660FF6rM",
  1157. pshufd_3 = "rmio:660F70rMU",
  1158. pshufhw_3 = "rmio:F30F70rMU",
  1159. pshuflw_3 = "rmio:F20F70rMU",
  1160. pslld_2 = "rmo:660FF2rM|rio:660F726mU",
  1161. pslldq_2 = "rio:660F737mU",
  1162. psllq_2 = "rmo:660FF3rM|rio:660F736mU",
  1163. psllw_2 = "rmo:660FF1rM|rio:660F716mU",
  1164. psrad_2 = "rmo:660FE2rM|rio:660F724mU",
  1165. psraw_2 = "rmo:660FE1rM|rio:660F714mU",
  1166. psrld_2 = "rmo:660FD2rM|rio:660F722mU",
  1167. psrldq_2 = "rio:660F733mU",
  1168. psrlq_2 = "rmo:660FD3rM|rio:660F732mU",
  1169. psrlw_2 = "rmo:660FD1rM|rio:660F712mU",
  1170. psubb_2 = "rmo:660FF8rM",
  1171. psubd_2 = "rmo:660FFArM",
  1172. psubq_2 = "rmo:660FFBrM",
  1173. psubsb_2 = "rmo:660FE8rM",
  1174. psubsw_2 = "rmo:660FE9rM",
  1175. psubusb_2 = "rmo:660FD8rM",
  1176. psubusw_2 = "rmo:660FD9rM",
  1177. psubw_2 = "rmo:660FF9rM",
  1178. punpckhbw_2 = "rmo:660F68rM",
  1179. punpckhdq_2 = "rmo:660F6ArM",
  1180. punpckhqdq_2 = "rmo:660F6DrM",
  1181. punpckhwd_2 = "rmo:660F69rM",
  1182. punpcklbw_2 = "rmo:660F60rM",
  1183. punpckldq_2 = "rmo:660F62rM",
  1184. punpcklqdq_2 = "rmo:660F6CrM",
  1185. punpcklwd_2 = "rmo:660F61rM",
  1186. pxor_2 = "rmo:660FEFrM",
  1187. rcpps_2 = "rmo:0F53rM",
  1188. rcpss_2 = "rro:F30F53rM|rx/od:",
  1189. rsqrtps_2 = "rmo:0F52rM",
  1190. rsqrtss_2 = "rmo:F30F52rM",
  1191. sfence_0 = "0FAEF8",
  1192. shufpd_3 = "rmio:660FC6rMU",
  1193. shufps_3 = "rmio:0FC6rMU",
  1194. stmxcsr_1 = "xd:0FAE3m",
  1195. ucomisd_2 = "rro:660F2ErM|rx/oq:",
  1196. ucomiss_2 = "rro:0F2ErM|rx/od:",
  1197. unpckhpd_2 = "rmo:660F15rM",
  1198. unpckhps_2 = "rmo:0F15rM",
  1199. unpcklpd_2 = "rmo:660F14rM",
  1200. unpcklps_2 = "rmo:0F14rM",
  1201. xorpd_2 = "rmo:660F57rM",
  1202. xorps_2 = "rmo:0F57rM",
  1203. -- SSE3 ops
  1204. fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m",
  1205. addsubpd_2 = "rmo:660FD0rM",
  1206. addsubps_2 = "rmo:F20FD0rM",
  1207. haddpd_2 = "rmo:660F7CrM",
  1208. haddps_2 = "rmo:F20F7CrM",
  1209. hsubpd_2 = "rmo:660F7DrM",
  1210. hsubps_2 = "rmo:F20F7DrM",
  1211. lddqu_2 = "rxo:F20FF0rM",
  1212. movddup_2 = "rmo:F20F12rM",
  1213. movshdup_2 = "rmo:F30F16rM",
  1214. movsldup_2 = "rmo:F30F12rM",
  1215. -- SSSE3 ops
  1216. pabsb_2 = "rmo:660F381CrM",
  1217. pabsd_2 = "rmo:660F381ErM",
  1218. pabsw_2 = "rmo:660F381DrM",
  1219. palignr_3 = "rmio:660F3A0FrMU",
  1220. phaddd_2 = "rmo:660F3802rM",
  1221. phaddsw_2 = "rmo:660F3803rM",
  1222. phaddw_2 = "rmo:660F3801rM",
  1223. phsubd_2 = "rmo:660F3806rM",
  1224. phsubsw_2 = "rmo:660F3807rM",
  1225. phsubw_2 = "rmo:660F3805rM",
  1226. pmaddubsw_2 = "rmo:660F3804rM",
  1227. pmulhrsw_2 = "rmo:660F380BrM",
  1228. pshufb_2 = "rmo:660F3800rM",
  1229. psignb_2 = "rmo:660F3808rM",
  1230. psignd_2 = "rmo:660F380ArM",
  1231. psignw_2 = "rmo:660F3809rM",
  1232. -- SSE4.1 ops
  1233. blendpd_3 = "rmio:660F3A0DrMU",
  1234. blendps_3 = "rmio:660F3A0CrMU",
  1235. blendvpd_3 = "rmRo:660F3815rM",
  1236. blendvps_3 = "rmRo:660F3814rM",
  1237. dppd_3 = "rmio:660F3A41rMU",
  1238. dpps_3 = "rmio:660F3A40rMU",
  1239. extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU",
  1240. insertps_3 = "rrio:660F3A41rMU|rxi/od:",
  1241. movntdqa_2 = "rmo:660F382ArM",
  1242. mpsadbw_3 = "rmio:660F3A42rMU",
  1243. packusdw_2 = "rmo:660F382BrM",
  1244. pblendvb_3 = "rmRo:660F3810rM",
  1245. pblendw_3 = "rmio:660F3A0ErMU",
  1246. pcmpeqq_2 = "rmo:660F3829rM",
  1247. pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:",
  1248. pextrd_3 = "mri/do:660F3A16RmU",
  1249. pextrq_3 = "mri/qo:660F3A16RmU",
  1250. -- pextrw is SSE2, mem operand is SSE4.1 only
  1251. phminposuw_2 = "rmo:660F3841rM",
  1252. pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:",
  1253. pinsrd_3 = "rmi/od:660F3A22rMU",
  1254. pinsrq_3 = "rmi/oq:660F3A22rXMU",
  1255. pmaxsb_2 = "rmo:660F383CrM",
  1256. pmaxsd_2 = "rmo:660F383DrM",
  1257. pmaxud_2 = "rmo:660F383FrM",
  1258. pmaxuw_2 = "rmo:660F383ErM",
  1259. pminsb_2 = "rmo:660F3838rM",
  1260. pminsd_2 = "rmo:660F3839rM",
  1261. pminud_2 = "rmo:660F383BrM",
  1262. pminuw_2 = "rmo:660F383ArM",
  1263. pmovsxbd_2 = "rro:660F3821rM|rx/od:",
  1264. pmovsxbq_2 = "rro:660F3822rM|rx/ow:",
  1265. pmovsxbw_2 = "rro:660F3820rM|rx/oq:",
  1266. pmovsxdq_2 = "rro:660F3825rM|rx/oq:",
  1267. pmovsxwd_2 = "rro:660F3823rM|rx/oq:",
  1268. pmovsxwq_2 = "rro:660F3824rM|rx/od:",
  1269. pmovzxbd_2 = "rro:660F3831rM|rx/od:",
  1270. pmovzxbq_2 = "rro:660F3832rM|rx/ow:",
  1271. pmovzxbw_2 = "rro:660F3830rM|rx/oq:",
  1272. pmovzxdq_2 = "rro:660F3835rM|rx/oq:",
  1273. pmovzxwd_2 = "rro:660F3833rM|rx/oq:",
  1274. pmovzxwq_2 = "rro:660F3834rM|rx/od:",
  1275. pmuldq_2 = "rmo:660F3828rM",
  1276. pmulld_2 = "rmo:660F3840rM",
  1277. ptest_2 = "rmo:660F3817rM",
  1278. roundpd_3 = "rmio:660F3A09rMU",
  1279. roundps_3 = "rmio:660F3A08rMU",
  1280. roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:",
  1281. roundss_3 = "rrio:660F3A0ArMU|rxi/od:",
  1282. -- SSE4.2 ops
  1283. crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:",
  1284. pcmpestri_3 = "rmio:660F3A61rMU",
  1285. pcmpestrm_3 = "rmio:660F3A60rMU",
  1286. pcmpgtq_2 = "rmo:660F3837rM",
  1287. pcmpistri_3 = "rmio:660F3A63rMU",
  1288. pcmpistrm_3 = "rmio:660F3A62rMU",
  1289. popcnt_2 = "rmqdw:F30FB8rM",
  1290. -- SSE4a
  1291. extrq_2 = "rro:660F79rM",
  1292. extrq_3 = "riio:660F780mUU",
  1293. insertq_2 = "rro:F20F79rM",
  1294. insertq_4 = "rriio:F20F78rMUU",
  1295. lzcnt_2 = "rmqdw:F30FBDrM",
  1296. movntsd_2 = "xr/qo:nF20F2BRm",
  1297. movntss_2 = "xr/do:F30F2BRm",
  1298. -- popcnt is also in SSE4.2
  1299. }
  1300. ------------------------------------------------------------------------------
  1301. -- Arithmetic ops.
  1302. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3,
  1303. ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do
  1304. local n8 = shl(n, 3)
  1305. map_op[name.."_2"] = format(
  1306. "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi",
  1307. 1+n8, 3+n8, n, n, 5+n8, n)
  1308. end
  1309. -- Shift ops.
  1310. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3,
  1311. shl = 4, shr = 5, sar = 7, sal = 4 } do
  1312. map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n)
  1313. end
  1314. -- Conditional ops.
  1315. for cc,n in pairs(map_cc) do
  1316. map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X
  1317. map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n)
  1318. map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+
  1319. end
  1320. -- FP arithmetic ops.
  1321. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3,
  1322. sub = 4, subr = 5, div = 6, divr = 7 } do
  1323. local nc = 0xc0 + shl(n, 3)
  1324. local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8))
  1325. local fn = "f"..name
  1326. map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n)
  1327. if n == 2 or n == 3 then
  1328. map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n)
  1329. else
  1330. map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n)
  1331. map_op[fn.."p_1"] = format("ff:DE%02Xr", nr)
  1332. map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr)
  1333. end
  1334. map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n)
  1335. end
  1336. -- FP conditional moves.
  1337. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do
  1338. local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6)
  1339. map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+
  1340. map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+
  1341. end
  1342. -- SSE FP arithmetic ops.
  1343. for name,n in pairs{ sqrt = 1, add = 8, mul = 9,
  1344. sub = 12, min = 13, div = 14, max = 15 } do
  1345. map_op[name.."ps_2"] = format("rmo:0F5%XrM", n)
  1346. map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n)
  1347. map_op[name.."pd_2"] = format("rmo:660F5%XrM", n)
  1348. map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n)
  1349. end
  1350. ------------------------------------------------------------------------------
  1351. -- Process pattern string.
  1352. local function dopattern(pat, args, sz, op, needrex)
  1353. local digit, addin
  1354. local opcode = 0
  1355. local szov = sz
  1356. local narg = 1
  1357. local rex = 0
  1358. -- Limit number of section buffer positions used by a single dasm_put().
  1359. -- A single opcode needs a maximum of 5 positions.
  1360. if secpos+5 > maxsecpos then wflush() end
  1361. -- Process each character.
  1362. for c in gmatch(pat.."|", ".") do
  1363. if match(c, "%x") then -- Hex digit.
  1364. digit = byte(c) - 48
  1365. if digit > 48 then digit = digit - 39
  1366. elseif digit > 16 then digit = digit - 7 end
  1367. opcode = opcode*16 + digit
  1368. addin = nil
  1369. elseif c == "n" then -- Disable operand size mods for opcode.
  1370. szov = nil
  1371. elseif c == "X" then -- Force REX.W.
  1372. rex = 8
  1373. elseif c == "r" then -- Merge 1st operand regno. into opcode.
  1374. addin = args[1]; opcode = opcode + (addin.reg % 8)
  1375. if narg < 2 then narg = 2 end
  1376. elseif c == "R" then -- Merge 2nd operand regno. into opcode.
  1377. addin = args[2]; opcode = opcode + (addin.reg % 8)
  1378. narg = 3
  1379. elseif c == "m" or c == "M" then -- Encode ModRM/SIB.
  1380. local s
  1381. if addin then
  1382. s = addin.reg
  1383. opcode = opcode - band(s, 7) -- Undo regno opcode merge.
  1384. else
  1385. s = band(opcode, 15) -- Undo last digit.
  1386. opcode = shr(opcode, 4)
  1387. end
  1388. local nn = c == "m" and 1 or 2
  1389. local t = args[nn]
  1390. if narg <= nn then narg = nn + 1 end
  1391. if szov == "q" and rex == 0 then rex = rex + 8 end
  1392. if t.reg and t.reg > 7 then rex = rex + 1 end
  1393. if t.xreg and t.xreg > 7 then rex = rex + 2 end
  1394. if s > 7 then rex = rex + 4 end
  1395. if needrex then rex = rex + 16 end
  1396. wputop(szov, opcode, rex); opcode = nil
  1397. local imark = sub(pat, -1) -- Force a mark (ugly).
  1398. -- Put ModRM/SIB with regno/last digit as spare.
  1399. wputmrmsib(t, imark, s, addin and addin.vreg)
  1400. addin = nil
  1401. else
  1402. if opcode then -- Flush opcode.
  1403. if szov == "q" and rex == 0 then rex = rex + 8 end
  1404. if needrex then rex = rex + 16 end
  1405. if addin and addin.reg == -1 then
  1406. wputop(szov, opcode - 7, rex)
  1407. waction("VREG", addin.vreg); wputxb(0)
  1408. else
  1409. if addin and addin.reg > 7 then rex = rex + 1 end
  1410. wputop(szov, opcode, rex)
  1411. end
  1412. opcode = nil
  1413. end
  1414. if c == "|" then break end
  1415. if c == "o" then -- Offset (pure 32 bit displacement).
  1416. wputdarg(args[1].disp); if narg < 2 then narg = 2 end
  1417. elseif c == "O" then
  1418. wputdarg(args[2].disp); narg = 3
  1419. else
  1420. -- Anything else is an immediate operand.
  1421. local a = args[narg]
  1422. narg = narg + 1
  1423. local mode, imm = a.mode, a.imm
  1424. if mode == "iJ" and not match("iIJ", c) then
  1425. werror("bad operand size for label")
  1426. end
  1427. if c == "S" then
  1428. wputsbarg(imm)
  1429. elseif c == "U" then
  1430. wputbarg(imm)
  1431. elseif c == "W" then
  1432. wputwarg(imm)
  1433. elseif c == "i" or c == "I" then
  1434. if mode == "iJ" then
  1435. wputlabel("IMM_", imm, 1)
  1436. elseif mode == "iI" and c == "I" then
  1437. waction(sz == "w" and "IMM_WB" or "IMM_DB", imm)
  1438. else
  1439. wputszarg(sz, imm)
  1440. end
  1441. elseif c == "J" then
  1442. if mode == "iPJ" then
  1443. waction("REL_A", imm) -- !x64 (secpos)
  1444. else
  1445. wputlabel("REL_", imm, 2)
  1446. end
  1447. else
  1448. werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'")
  1449. end
  1450. end
  1451. end
  1452. end
  1453. end
  1454. ------------------------------------------------------------------------------
  1455. -- Mapping of operand modes to short names. Suppress output with '#'.
  1456. local map_modename = {
  1457. r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm",
  1458. f = "stx", F = "st0", J = "lbl", ["1"] = "1",
  1459. I = "#", S = "#", O = "#",
  1460. }
  1461. -- Return a table/string showing all possible operand modes.
  1462. local function templatehelp(template, nparams)
  1463. if nparams == 0 then return "" end
  1464. local t = {}
  1465. for tm in gmatch(template, "[^%|]+") do
  1466. local s = map_modename[sub(tm, 1, 1)]
  1467. s = s..gsub(sub(tm, 2, nparams), ".", function(c)
  1468. return ", "..map_modename[c]
  1469. end)
  1470. if not match(s, "#") then t[#t+1] = s end
  1471. end
  1472. return t
  1473. end
  1474. -- Match operand modes against mode match part of template.
  1475. local function matchtm(tm, args)
  1476. for i=1,#args do
  1477. if not match(args[i].mode, sub(tm, i, i)) then return end
  1478. end
  1479. return true
  1480. end
  1481. -- Handle opcodes defined with template strings.
  1482. map_op[".template__"] = function(params, template, nparams)
  1483. if not params then return templatehelp(template, nparams) end
  1484. local args = {}
  1485. -- Zero-operand opcodes have no match part.
  1486. if #params == 0 then
  1487. dopattern(template, args, "d", params.op, nil)
  1488. return
  1489. end
  1490. -- Determine common operand size (coerce undefined size) or flag as mixed.
  1491. local sz, szmix, needrex
  1492. for i,p in ipairs(params) do
  1493. args[i] = parseoperand(p)
  1494. local nsz = args[i].opsize
  1495. if nsz then
  1496. if sz and sz ~= nsz then szmix = true else sz = nsz end
  1497. end
  1498. local nrex = args[i].needrex
  1499. if nrex ~= nil then
  1500. if needrex == nil then
  1501. needrex = nrex
  1502. elseif needrex ~= nrex then
  1503. werror("bad mix of byte-addressable registers")
  1504. end
  1505. end
  1506. end
  1507. -- Try all match:pattern pairs (separated by '|').
  1508. local gotmatch, lastpat
  1509. for tm in gmatch(template, "[^%|]+") do
  1510. -- Split off size match (starts after mode match) and pattern string.
  1511. local szm, pat = match(tm, "^(.-):(.*)$", #args+1)
  1512. if pat == "" then pat = lastpat else lastpat = pat end
  1513. if matchtm(tm, args) then
  1514. local prefix = sub(szm, 1, 1)
  1515. if prefix == "/" then -- Match both operand sizes.
  1516. if args[1].opsize == sub(szm, 2, 2) and
  1517. args[2].opsize == sub(szm, 3, 3) then
  1518. dopattern(pat, args, sz, params.op, needrex) -- Process pattern.
  1519. return
  1520. end
  1521. else -- Match common operand size.
  1522. local szp = sz
  1523. if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes.
  1524. if prefix == "1" then szp = args[1].opsize; szmix = nil
  1525. elseif prefix == "2" then szp = args[2].opsize; szmix = nil end
  1526. if not szmix and (prefix == "." or match(szm, szp or "#")) then
  1527. dopattern(pat, args, szp, params.op, needrex) -- Process pattern.
  1528. return
  1529. end
  1530. end
  1531. gotmatch = true
  1532. end
  1533. end
  1534. local msg = "bad operand mode"
  1535. if gotmatch then
  1536. if szmix then
  1537. msg = "mixed operand size"
  1538. else
  1539. msg = sz and "bad operand size" or "missing operand size"
  1540. end
  1541. end
  1542. werror(msg.." in `"..opmodestr(params.op, args).."'")
  1543. end
  1544. ------------------------------------------------------------------------------
  1545. -- x64-specific opcode for 64 bit immediates and displacements.
  1546. if x64 then
  1547. function map_op.mov64_2(params)
  1548. if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end
  1549. if secpos+2 > maxsecpos then wflush() end
  1550. local opcode, op64, sz, rex
  1551. local op64 = match(params[1], "^%[%s*(.-)%s*%]$")
  1552. if op64 then
  1553. local a = parseoperand(params[2])
  1554. if a.mode ~= "rmR" then werror("bad operand mode") end
  1555. sz = a.opsize
  1556. rex = sz == "q" and 8 or 0
  1557. opcode = 0xa3
  1558. else
  1559. op64 = match(params[2], "^%[%s*(.-)%s*%]$")
  1560. local a = parseoperand(params[1])
  1561. if op64 then
  1562. if a.mode ~= "rmR" then werror("bad operand mode") end
  1563. sz = a.opsize
  1564. rex = sz == "q" and 8 or 0
  1565. opcode = 0xa1
  1566. else
  1567. if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then
  1568. werror("bad operand mode")
  1569. end
  1570. op64 = params[2]
  1571. opcode = 0xb8 + band(a.reg, 7) -- !x64: no VREG support.
  1572. rex = a.reg > 7 and 9 or 8
  1573. end
  1574. end
  1575. wputop(sz, opcode, rex)
  1576. waction("IMM_D", format("(unsigned int)(%s)", op64))
  1577. waction("IMM_D", format("(unsigned int)((%s)>>32)", op64))
  1578. end
  1579. end
  1580. ------------------------------------------------------------------------------
  1581. -- Pseudo-opcodes for data storage.
  1582. local function op_data(params)
  1583. if not params then return "imm..." end
  1584. local sz = sub(params.op, 2, 2)
  1585. if sz == "a" then sz = addrsize end
  1586. for _,p in ipairs(params) do
  1587. local a = parseoperand(p)
  1588. if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then
  1589. werror("bad mode or size in `"..p.."'")
  1590. end
  1591. if a.mode == "iJ" then
  1592. wputlabel("IMM_", a.imm, 1)
  1593. else
  1594. wputszarg(sz, a.imm)
  1595. end
  1596. if secpos+2 > maxsecpos then wflush() end
  1597. end
  1598. end
  1599. map_op[".byte_*"] = op_data
  1600. map_op[".sbyte_*"] = op_data
  1601. map_op[".word_*"] = op_data
  1602. map_op[".dword_*"] = op_data
  1603. map_op[".aword_*"] = op_data
  1604. ------------------------------------------------------------------------------
  1605. -- Pseudo-opcode to mark the position where the action list is to be emitted.
  1606. map_op[".actionlist_1"] = function(params)
  1607. if not params then return "cvar" end
  1608. local name = params[1] -- No syntax check. You get to keep the pieces.
  1609. wline(function(out) writeactions(out, name) end)
  1610. end
  1611. -- Pseudo-opcode to mark the position where the global enum is to be emitted.
  1612. map_op[".globals_1"] = function(params)
  1613. if not params then return "prefix" end
  1614. local prefix = params[1] -- No syntax check. You get to keep the pieces.
  1615. wline(function(out) writeglobals(out, prefix) end)
  1616. end
  1617. -- Pseudo-opcode to mark the position where the global names are to be emitted.
  1618. map_op[".globalnames_1"] = function(params)
  1619. if not params then return "cvar" end
  1620. local name = params[1] -- No syntax check. You get to keep the pieces.
  1621. wline(function(out) writeglobalnames(out, name) end)
  1622. end
  1623. -- Pseudo-opcode to mark the position where the extern names are to be emitted.
  1624. map_op[".externnames_1"] = function(params)
  1625. if not params then return "cvar" end
  1626. local name = params[1] -- No syntax check. You get to keep the pieces.
  1627. wline(function(out) writeexternnames(out, name) end)
  1628. end
  1629. ------------------------------------------------------------------------------
  1630. -- Label pseudo-opcode (converted from trailing colon form).
  1631. map_op[".label_2"] = function(params)
  1632. if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end
  1633. if secpos+2 > maxsecpos then wflush() end
  1634. local a = parseoperand(params[1])
  1635. local mode, imm = a.mode, a.imm
  1636. if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then
  1637. -- Local label (1: ... 9:) or global label (->global:).
  1638. waction("LABEL_LG", nil, 1)
  1639. wputxb(imm)
  1640. elseif mode == "iJ" then
  1641. -- PC label (=>pcexpr:).
  1642. waction("LABEL_PC", imm)
  1643. else
  1644. werror("bad label definition")
  1645. end
  1646. -- SETLABEL must immediately follow LABEL_LG/LABEL_PC.
  1647. local addr = params[2]
  1648. if addr then
  1649. local a = parseoperand(addr)
  1650. if a.mode == "iPJ" then
  1651. waction("SETLABEL", a.imm)
  1652. else
  1653. werror("bad label assignment")
  1654. end
  1655. end
  1656. end
  1657. map_op[".label_1"] = map_op[".label_2"]
  1658. ------------------------------------------------------------------------------
  1659. -- Alignment pseudo-opcode.
  1660. map_op[".align_1"] = function(params)
  1661. if not params then return "numpow2" end
  1662. if secpos+1 > maxsecpos then wflush() end
  1663. local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]]
  1664. if align then
  1665. local x = align
  1666. -- Must be a power of 2 in the range (2 ... 256).
  1667. for i=1,8 do
  1668. x = x / 2
  1669. if x == 1 then
  1670. waction("ALIGN", nil, 1)
  1671. wputxb(align-1) -- Action byte is 2**n-1.
  1672. return
  1673. end
  1674. end
  1675. end
  1676. werror("bad alignment")
  1677. end
  1678. -- Spacing pseudo-opcode.
  1679. map_op[".space_2"] = function(params)
  1680. if not params then return "num [, filler]" end
  1681. if secpos+1 > maxsecpos then wflush() end
  1682. waction("SPACE", params[1])
  1683. local fill = params[2]
  1684. if fill then
  1685. fill = tonumber(fill)
  1686. if not fill or fill < 0 or fill > 255 then werror("bad filler") end
  1687. end
  1688. wputxb(fill or 0)
  1689. end
  1690. map_op[".space_1"] = map_op[".space_2"]
  1691. ------------------------------------------------------------------------------
  1692. -- Pseudo-opcode for (primitive) type definitions (map to C types).
  1693. map_op[".type_3"] = function(params, nparams)
  1694. if not params then
  1695. return nparams == 2 and "name, ctype" or "name, ctype, reg"
  1696. end
  1697. local name, ctype, reg = params[1], params[2], params[3]
  1698. if not match(name, "^[%a_][%w_]*$") then
  1699. werror("bad type name `"..name.."'")
  1700. end
  1701. local tp = map_type[name]
  1702. if tp then
  1703. werror("duplicate type `"..name.."'")
  1704. end
  1705. if reg and not map_reg_valid_base[reg] then
  1706. werror("bad base register `"..(map_reg_rev[reg] or reg).."'")
  1707. end
  1708. -- Add #type to defines. A bit unclean to put it in map_archdef.
  1709. map_archdef["#"..name] = "sizeof("..ctype..")"
  1710. -- Add new type and emit shortcut define.
  1711. local num = ctypenum + 1
  1712. map_type[name] = {
  1713. ctype = ctype,
  1714. ctypefmt = format("Dt%X(%%s)", num),
  1715. reg = reg,
  1716. }
  1717. wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
  1718. ctypenum = num
  1719. end
  1720. map_op[".type_2"] = map_op[".type_3"]
  1721. -- Dump type definitions.
  1722. local function dumptypes(out, lvl)
  1723. local t = {}
  1724. for name in pairs(map_type) do t[#t+1] = name end
  1725. sort(t)
  1726. out:write("Type definitions:\n")
  1727. for _,name in ipairs(t) do
  1728. local tp = map_type[name]
  1729. local reg = tp.reg and map_reg_rev[tp.reg] or ""
  1730. out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
  1731. end
  1732. out:write("\n")
  1733. end
  1734. ------------------------------------------------------------------------------
  1735. -- Set the current section.
  1736. function _M.section(num)
  1737. waction("SECTION")
  1738. wputxb(num)
  1739. wflush(true) -- SECTION is a terminal action.
  1740. end
  1741. ------------------------------------------------------------------------------
  1742. -- Dump architecture description.
  1743. function _M.dumparch(out)
  1744. out:write(format("DynASM %s version %s, released %s\n\n",
  1745. _info.arch, _info.version, _info.release))
  1746. dumpregs(out)
  1747. dumpactions(out)
  1748. end
  1749. -- Dump all user defined elements.
  1750. function _M.dumpdef(out, lvl)
  1751. dumptypes(out, lvl)
  1752. dumpglobals(out, lvl)
  1753. dumpexterns(out, lvl)
  1754. end
  1755. ------------------------------------------------------------------------------
  1756. -- Pass callbacks from/to the DynASM core.
  1757. function _M.passcb(wl, we, wf, ww)
  1758. wline, werror, wfatal, wwarn = wl, we, wf, ww
  1759. return wflush
  1760. end
  1761. -- Setup the arch-specific module.
  1762. function _M.setup(arch, opt)
  1763. g_arch, g_opt = arch, opt
  1764. end
  1765. -- Merge the core maps and the arch-specific maps.
  1766. function _M.mergemaps(map_coreop, map_def)
  1767. setmetatable(map_op, { __index = map_coreop })
  1768. setmetatable(map_def, { __index = map_archdef })
  1769. return map_op, map_def
  1770. end
  1771. return _M
  1772. ------------------------------------------------------------------------------