dasm_x86.lua 57 KB

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