src/lj_asm_x86.h - luajit-2.0-src

Global variables defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** x86/x64 IR assembler (SSA IR -> machine code).
  3. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
  4. */

  5. /* -- Guard handling ------------------------------------------------------ */

  6. /* Generate an exit stub group at the bottom of the reserved MCode memory. */
  7. static MCode *asm_exitstub_gen(ASMState *as, ExitNo group)
  8. {
  9.   ExitNo i, groupofs = (group*EXITSTUBS_PER_GROUP) & 0xff;
  10.   MCode *mxp = as->mcbot;
  11.   MCode *mxpstart = mxp;
  12.   if (mxp + (2+2)*EXITSTUBS_PER_GROUP+8+5 >= as->mctop)
  13.     asm_mclimit(as);
  14.   /* Push low byte of exitno for each exit stub. */
  15.   *mxp++ = XI_PUSHi8; *mxp++ = (MCode)groupofs;
  16.   for (i = 1; i < EXITSTUBS_PER_GROUP; i++) {
  17.     *mxp++ = XI_JMPs; *mxp++ = (MCode)((2+2)*(EXITSTUBS_PER_GROUP - i) - 2);
  18.     *mxp++ = XI_PUSHi8; *mxp++ = (MCode)(groupofs + i);
  19.   }
  20.   /* Push the high byte of the exitno for each exit stub group. */
  21.   *mxp++ = XI_PUSHi8; *mxp++ = (MCode)((group*EXITSTUBS_PER_GROUP)>>8);
  22.   /* Store DISPATCH at original stack slot 0. Account for the two push ops. */
  23.   *mxp++ = XI_MOVmi;
  24.   *mxp++ = MODRM(XM_OFS8, 0, RID_ESP);
  25.   *mxp++ = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
  26.   *mxp++ = 2*sizeof(void *);
  27.   *(int32_t *)mxp = ptr2addr(J2GG(as->J)->dispatch); mxp += 4;
  28.   /* Jump to exit handler which fills in the ExitState. */
  29.   *mxp++ = XI_JMP; mxp += 4;
  30.   *((int32_t *)(mxp-4)) = jmprel(mxp, (MCode *)(void *)lj_vm_exit_handler);
  31.   /* Commit the code for this group (even if assembly fails later on). */
  32.   lj_mcode_commitbot(as->J, mxp);
  33.   as->mcbot = mxp;
  34.   as->mclim = as->mcbot + MCLIM_REDZONE;
  35.   return mxpstart;
  36. }

  37. /* Setup all needed exit stubs. */
  38. static void asm_exitstub_setup(ASMState *as, ExitNo nexits)
  39. {
  40.   ExitNo i;
  41.   if (nexits >= EXITSTUBS_PER_GROUP*LJ_MAX_EXITSTUBGR)
  42.     lj_trace_err(as->J, LJ_TRERR_SNAPOV);
  43.   for (i = 0; i < (nexits+EXITSTUBS_PER_GROUP-1)/EXITSTUBS_PER_GROUP; i++)
  44.     if (as->J->exitstubgroup[i] == NULL)
  45.       as->J->exitstubgroup[i] = asm_exitstub_gen(as, i);
  46. }

  47. /* Emit conditional branch to exit for guard.
  48. ** It's important to emit this *after* all registers have been allocated,
  49. ** because rematerializations may invalidate the flags.
  50. */
  51. static void asm_guardcc(ASMState *as, int cc)
  52. {
  53.   MCode *target = exitstub_addr(as->J, as->snapno);
  54.   MCode *p = as->mcp;
  55.   if (LJ_UNLIKELY(p == as->invmcp)) {
  56.     as->loopinv = 1;
  57.     *(int32_t *)(p+1) = jmprel(p+5, target);
  58.     target = p;
  59.     cc ^= 1;
  60.     if (as->realign) {
  61.       emit_sjcc(as, cc, target);
  62.       return;
  63.     }
  64.   }
  65.   emit_jcc(as, cc, target);
  66. }

  67. /* -- Memory operand fusion ----------------------------------------------- */

  68. /* Limit linear search to this distance. Avoids O(n^2) behavior. */
  69. #define CONFLICT_SEARCH_LIM        31

  70. /* Check if a reference is a signed 32 bit constant. */
  71. static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
  72. {
  73.   if (irref_isk(ref)) {
  74.     IRIns *ir = IR(ref);
  75.     if (ir->o != IR_KINT64) {
  76.       *k = ir->i;
  77.       return 1;
  78.     } else if (checki32((int64_t)ir_kint64(ir)->u64)) {
  79.       *k = (int32_t)ir_kint64(ir)->u64;
  80.       return 1;
  81.     }
  82.   }
  83.   return 0;
  84. }

  85. /* Check if there's no conflicting instruction between curins and ref.
  86. ** Also avoid fusing loads if there are multiple references.
  87. */
  88. static int noconflict(ASMState *as, IRRef ref, IROp conflict, int noload)
  89. {
  90.   IRIns *ir = as->ir;
  91.   IRRef i = as->curins;
  92.   if (i > ref + CONFLICT_SEARCH_LIM)
  93.     return 0/* Give up, ref is too far away. */
  94.   while (--i > ref) {
  95.     if (ir[i].o == conflict)
  96.       return 0/* Conflict found. */
  97.     else if (!noload && (ir[i].op1 == ref || ir[i].op2 == ref))
  98.       return 0;
  99.   }
  100.   return 1/* Ok, no conflict. */
  101. }

  102. /* Fuse array base into memory operand. */
  103. static IRRef asm_fuseabase(ASMState *as, IRRef ref)
  104. {
  105.   IRIns *irb = IR(ref);
  106.   as->mrm.ofs = 0;
  107.   if (irb->o == IR_FLOAD) {
  108.     IRIns *ira = IR(irb->op1);
  109.     lua_assert(irb->op2 == IRFL_TAB_ARRAY);
  110.     /* We can avoid the FLOAD of t->array for colocated arrays. */
  111.     if (ira->o == IR_TNEW && ira->op1 <= LJ_MAX_COLOSIZE &&
  112.         !neverfuse(as) && noconflict(as, irb->op1, IR_NEWREF, 1)) {
  113.       as->mrm.ofs = (int32_t)sizeof(GCtab);  /* Ofs to colocated array. */
  114.       return irb->op1;  /* Table obj. */
  115.     }
  116.   } else if (irb->o == IR_ADD && irref_isk(irb->op2)) {
  117.     /* Fuse base offset (vararg load). */
  118.     as->mrm.ofs = IR(irb->op2)->i;
  119.     return irb->op1;
  120.   }
  121.   return ref;  /* Otherwise use the given array base. */
  122. }

  123. /* Fuse array reference into memory operand. */
  124. static void asm_fusearef(ASMState *as, IRIns *ir, RegSet allow)
  125. {
  126.   IRIns *irx;
  127.   lua_assert(ir->o == IR_AREF);
  128.   as->mrm.base = (uint8_t)ra_alloc1(as, asm_fuseabase(as, ir->op1), allow);
  129.   irx = IR(ir->op2);
  130.   if (irref_isk(ir->op2)) {
  131.     as->mrm.ofs += 8*irx->i;
  132.     as->mrm.idx = RID_NONE;
  133.   } else {
  134.     rset_clear(allow, as->mrm.base);
  135.     as->mrm.scale = XM_SCALE8;
  136.     /* Fuse a constant ADD (e.g. t[i+1]) into the offset.
  137.     ** Doesn't help much without ABCelim, but reduces register pressure.
  138.     */
  139.     if (!LJ_64 &&  /* Has bad effects with negative index on x64. */
  140.         mayfuse(as, ir->op2) && ra_noreg(irx->r) &&
  141.         irx->o == IR_ADD && irref_isk(irx->op2)) {
  142.       as->mrm.ofs += 8*IR(irx->op2)->i;
  143.       as->mrm.idx = (uint8_t)ra_alloc1(as, irx->op1, allow);
  144.     } else {
  145.       as->mrm.idx = (uint8_t)ra_alloc1(as, ir->op2, allow);
  146.     }
  147.   }
  148. }

  149. /* Fuse array/hash/upvalue reference into memory operand.
  150. ** Caveat: this may allocate GPRs for the base/idx registers. Be sure to
  151. ** pass the final allow mask, excluding any GPRs used for other inputs.
  152. ** In particular: 2-operand GPR instructions need to call ra_dest() first!
  153. */
  154. static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow)
  155. {
  156.   IRIns *ir = IR(ref);
  157.   if (ra_noreg(ir->r)) {
  158.     switch ((IROp)ir->o) {
  159.     case IR_AREF:
  160.       if (mayfuse(as, ref)) {
  161.         asm_fusearef(as, ir, allow);
  162.         return;
  163.       }
  164.       break;
  165.     case IR_HREFK:
  166.       if (mayfuse(as, ref)) {
  167.         as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow);
  168.         as->mrm.ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node));
  169.         as->mrm.idx = RID_NONE;
  170.         return;
  171.       }
  172.       break;
  173.     case IR_UREFC:
  174.       if (irref_isk(ir->op1)) {
  175.         GCfunc *fn = ir_kfunc(IR(ir->op1));
  176.         GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv;
  177.         as->mrm.ofs = ptr2addr(&uv->tv);
  178.         as->mrm.base = as->mrm.idx = RID_NONE;
  179.         return;
  180.       }
  181.       break;
  182.     default:
  183.       lua_assert(ir->o == IR_HREF || ir->o == IR_NEWREF || ir->o == IR_UREFO ||
  184.                  ir->o == IR_KKPTR);
  185.       break;
  186.     }
  187.   }
  188.   as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
  189.   as->mrm.ofs = 0;
  190.   as->mrm.idx = RID_NONE;
  191. }

  192. /* Fuse FLOAD/FREF reference into memory operand. */
  193. static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow)
  194. {
  195.   lua_assert(ir->o == IR_FLOAD || ir->o == IR_FREF);
  196.   as->mrm.ofs = field_ofs[ir->op2];
  197.   as->mrm.idx = RID_NONE;
  198.   if (irref_isk(ir->op1)) {
  199.     as->mrm.ofs += IR(ir->op1)->i;
  200.     as->mrm.base = RID_NONE;
  201.   } else {
  202.     as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow);
  203.   }
  204. }

  205. /* Fuse string reference into memory operand. */
  206. static void asm_fusestrref(ASMState *as, IRIns *ir, RegSet allow)
  207. {
  208.   IRIns *irr;
  209.   lua_assert(ir->o == IR_STRREF);
  210.   as->mrm.base = as->mrm.idx = RID_NONE;
  211.   as->mrm.scale = XM_SCALE1;
  212.   as->mrm.ofs = sizeof(GCstr);
  213.   if (irref_isk(ir->op1)) {
  214.     as->mrm.ofs += IR(ir->op1)->i;
  215.   } else {
  216.     Reg r = ra_alloc1(as, ir->op1, allow);
  217.     rset_clear(allow, r);
  218.     as->mrm.base = (uint8_t)r;
  219.   }
  220.   irr = IR(ir->op2);
  221.   if (irref_isk(ir->op2)) {
  222.     as->mrm.ofs += irr->i;
  223.   } else {
  224.     Reg r;
  225.     /* Fuse a constant add into the offset, e.g. string.sub(s, i+10). */
  226.     if (!LJ_64 &&  /* Has bad effects with negative index on x64. */
  227.         mayfuse(as, ir->op2) && irr->o == IR_ADD && irref_isk(irr->op2)) {
  228.       as->mrm.ofs += IR(irr->op2)->i;
  229.       r = ra_alloc1(as, irr->op1, allow);
  230.     } else {
  231.       r = ra_alloc1(as, ir->op2, allow);
  232.     }
  233.     if (as->mrm.base == RID_NONE)
  234.       as->mrm.base = (uint8_t)r;
  235.     else
  236.       as->mrm.idx = (uint8_t)r;
  237.   }
  238. }

  239. static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow)
  240. {
  241.   IRIns *ir = IR(ref);
  242.   as->mrm.idx = RID_NONE;
  243.   if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
  244.     as->mrm.ofs = ir->i;
  245.     as->mrm.base = RID_NONE;
  246.   } else if (ir->o == IR_STRREF) {
  247.     asm_fusestrref(as, ir, allow);
  248.   } else {
  249.     as->mrm.ofs = 0;
  250.     if (canfuse(as, ir) && ir->o == IR_ADD && ra_noreg(ir->r)) {
  251.       /* Gather (base+idx*sz)+ofs as emitted by cdata ptr/array indexing. */
  252.       IRIns *irx;
  253.       IRRef idx;
  254.       Reg r;
  255.       if (asm_isk32(as, ir->op2, &as->mrm.ofs)) {  /* Recognize x+ofs. */
  256.         ref = ir->op1;
  257.         ir = IR(ref);
  258.         if (!(ir->o == IR_ADD && canfuse(as, ir) && ra_noreg(ir->r)))
  259.           goto noadd;
  260.       }
  261.       as->mrm.scale = XM_SCALE1;
  262.       idx = ir->op1;
  263.       ref = ir->op2;
  264.       irx = IR(idx);
  265.       if (!(irx->o == IR_BSHL || irx->o == IR_ADD)) {  /* Try other operand. */
  266.         idx = ir->op2;
  267.         ref = ir->op1;
  268.         irx = IR(idx);
  269.       }
  270.       if (canfuse(as, irx) && ra_noreg(irx->r)) {
  271.         if (irx->o == IR_BSHL && irref_isk(irx->op2) && IR(irx->op2)->i <= 3) {
  272.           /* Recognize idx<<b with b = 0-3, corresponding to sz = (1),2,4,8. */
  273.           idx = irx->op1;
  274.           as->mrm.scale = (uint8_t)(IR(irx->op2)->i << 6);
  275.         } else if (irx->o == IR_ADD && irx->op1 == irx->op2) {
  276.           /* FOLD does idx*2 ==> idx<<1 ==> idx+idx. */
  277.           idx = irx->op1;
  278.           as->mrm.scale = XM_SCALE2;
  279.         }
  280.       }
  281.       r = ra_alloc1(as, idx, allow);
  282.       rset_clear(allow, r);
  283.       as->mrm.idx = (uint8_t)r;
  284.     }
  285.   noadd:
  286.     as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
  287.   }
  288. }

  289. /* Fuse load into memory operand. */
  290. static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
  291. {
  292.   IRIns *ir = IR(ref);
  293.   if (ra_hasreg(ir->r)) {
  294.     if (allow != RSET_EMPTY) {  /* Fast path. */
  295.       ra_noweak(as, ir->r);
  296.       return ir->r;
  297.     }
  298.   fusespill:
  299.     /* Force a spill if only memory operands are allowed (asm_x87load). */
  300.     as->mrm.base = RID_ESP;
  301.     as->mrm.ofs = ra_spill(as, ir);
  302.     as->mrm.idx = RID_NONE;
  303.     return RID_MRM;
  304.   }
  305.   if (ir->o == IR_KNUM) {
  306.     RegSet avail = as->freeset & ~as->modset & RSET_FPR;
  307.     lua_assert(allow != RSET_EMPTY);
  308.     if (!(avail & (avail-1))) {  /* Fuse if less than two regs available. */
  309.       as->mrm.ofs = ptr2addr(ir_knum(ir));
  310.       as->mrm.base = as->mrm.idx = RID_NONE;
  311.       return RID_MRM;
  312.     }
  313.   } else if (ir->o == IR_KINT64) {
  314.     RegSet avail = as->freeset & ~as->modset & RSET_GPR;
  315.     lua_assert(allow != RSET_EMPTY);
  316.     if (!(avail & (avail-1))) {  /* Fuse if less than two regs available. */
  317.       as->mrm.ofs = ptr2addr(ir_kint64(ir));
  318.       as->mrm.base = as->mrm.idx = RID_NONE;
  319.       return RID_MRM;
  320.     }
  321.   } else if (mayfuse(as, ref)) {
  322.     RegSet xallow = (allow & RSET_GPR) ? allow : RSET_GPR;
  323.     if (ir->o == IR_SLOAD) {
  324.       if (!(ir->op2 & (IRSLOAD_PARENT|IRSLOAD_CONVERT)) &&
  325.           noconflict(as, ref, IR_RETF, 0)) {
  326.         as->mrm.base = (uint8_t)ra_alloc1(as, REF_BASE, xallow);
  327.         as->mrm.ofs = 8*((int32_t)ir->op1-1) + ((ir->op2&IRSLOAD_FRAME)?4:0);
  328.         as->mrm.idx = RID_NONE;
  329.         return RID_MRM;
  330.       }
  331.     } else if (ir->o == IR_FLOAD) {
  332.       /* Generic fusion is only ok for 32 bit operand (but see asm_comp). */
  333.       if ((irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t)) &&
  334.           noconflict(as, ref, IR_FSTORE, 0)) {
  335.         asm_fusefref(as, ir, xallow);
  336.         return RID_MRM;
  337.       }
  338.     } else if (ir->o == IR_ALOAD || ir->o == IR_HLOAD || ir->o == IR_ULOAD) {
  339.       if (noconflict(as, ref, ir->o + IRDELTA_L2S, 0)) {
  340.         asm_fuseahuref(as, ir->op1, xallow);
  341.         return RID_MRM;
  342.       }
  343.     } else if (ir->o == IR_XLOAD) {
  344.       /* Generic fusion is not ok for 8/16 bit operands (but see asm_comp).
  345.       ** Fusing unaligned memory operands is ok on x86 (except for SIMD types).
  346.       */
  347.       if ((!irt_typerange(ir->t, IRT_I8, IRT_U16)) &&
  348.           noconflict(as, ref, IR_XSTORE, 0)) {
  349.         asm_fusexref(as, ir->op1, xallow);
  350.         return RID_MRM;
  351.       }
  352.     } else if (ir->o == IR_VLOAD) {
  353.       asm_fuseahuref(as, ir->op1, xallow);
  354.       return RID_MRM;
  355.     }
  356.   }
  357.   if (!(as->freeset & allow) && !irref_isk(ref) &&
  358.       (allow == RSET_EMPTY || ra_hasspill(ir->s) || iscrossref(as, ref)))
  359.     goto fusespill;
  360.   return ra_allocref(as, ref, allow);
  361. }

  362. #if LJ_64
  363. /* Don't fuse a 32 bit load into a 64 bit operation. */
  364. static Reg asm_fuseloadm(ASMState *as, IRRef ref, RegSet allow, int is64)
  365. {
  366.   if (is64 && !irt_is64(IR(ref)->t))
  367.     return ra_alloc1(as, ref, allow);
  368.   return asm_fuseload(as, ref, allow);
  369. }
  370. #else
  371. #define asm_fuseloadm(as, ref, allow, is64)  asm_fuseload(as, (ref), (allow))
  372. #endif

  373. /* -- Calls --------------------------------------------------------------- */

  374. /* Count the required number of stack slots for a call. */
  375. static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args)
  376. {
  377.   uint32_t i, nargs = CCI_XNARGS(ci);
  378.   int nslots = 0;
  379. #if LJ_64
  380.   if (LJ_ABI_WIN) {
  381.     nslots = (int)(nargs*2);  /* Only matters for more than four args. */
  382.   } else {
  383.     int ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR;
  384.     for (i = 0; i < nargs; i++)
  385.       if (args[i] && irt_isfp(IR(args[i])->t)) {
  386.         if (nfpr > 0) nfpr--; else nslots += 2;
  387.       } else {
  388.         if (ngpr > 0) ngpr--; else nslots += 2;
  389.       }
  390.   }
  391. #else
  392.   int ngpr = 0;
  393.   if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL)
  394.     ngpr = 2;
  395.   else if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL)
  396.     ngpr = 1;
  397.   for (i = 0; i < nargs; i++)
  398.     if (args[i] && irt_isfp(IR(args[i])->t)) {
  399.       nslots += irt_isnum(IR(args[i])->t) ? 2 : 1;
  400.     } else {
  401.       if (ngpr > 0) ngpr--; else nslots++;
  402.     }
  403. #endif
  404.   return nslots;
  405. }

  406. /* Generate a call to a C function. */
  407. static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
  408. {
  409.   uint32_t n, nargs = CCI_XNARGS(ci);
  410.   int32_t ofs = STACKARG_OFS;
  411. #if LJ_64
  412.   uint32_t gprs = REGARG_GPRS;
  413.   Reg fpr = REGARG_FIRSTFPR;
  414. #if !LJ_ABI_WIN
  415.   MCode *patchnfpr = NULL;
  416. #endif
  417. #else
  418.   uint32_t gprs = 0;
  419.   if ((ci->flags & CCI_CC_MASK) != CCI_CC_CDECL) {
  420.     if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL)
  421.       gprs = (REGARG_GPRS & 31);
  422.     else if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL)
  423.       gprs = REGARG_GPRS;
  424.   }
  425. #endif
  426.   if ((void *)ci->func)
  427.     emit_call(as, ci->func);
  428. #if LJ_64
  429.   if ((ci->flags & CCI_VARARG)) {  /* Special handling for vararg calls. */
  430. #if LJ_ABI_WIN
  431.     for (n = 0; n < 4 && n < nargs; n++) {
  432.       IRIns *ir = IR(args[n]);
  433.       if (irt_isfp(ir->t))  /* Duplicate FPRs in GPRs. */
  434.         emit_rr(as, XO_MOVDto, (irt_isnum(ir->t) ? REX_64 : 0) | (fpr+n),
  435.                 ((gprs >> (n*5)) & 31));  /* Either MOVD or MOVQ. */
  436.     }
  437. #else
  438.     patchnfpr = --as->mcp;  /* Indicate number of used FPRs in register al. */
  439.     *--as->mcp = XI_MOVrib | RID_EAX;
  440. #endif
  441.   }
  442. #endif
  443.   for (n = 0; n < nargs; n++) {  /* Setup args. */
  444.     IRRef ref = args[n];
  445.     IRIns *ir = IR(ref);
  446.     Reg r;
  447. #if LJ_64 && LJ_ABI_WIN
  448.     /* Windows/x64 argument registers are strictly positional. */
  449.     r = irt_isfp(ir->t) ? (fpr <= REGARG_LASTFPR ? fpr : 0) : (gprs & 31);
  450.     fpr++; gprs >>= 5;
  451. #elif LJ_64
  452.     /* POSIX/x64 argument registers are used in order of appearance. */
  453.     if (irt_isfp(ir->t)) {
  454.       r = fpr <= REGARG_LASTFPR ? fpr++ : 0;
  455.     } else {
  456.       r = gprs & 31; gprs >>= 5;
  457.     }
  458. #else
  459.     if (ref && irt_isfp(ir->t)) {
  460.       r = 0;
  461.     } else {
  462.       r = gprs & 31; gprs >>= 5;
  463.       if (!ref) continue;
  464.     }
  465. #endif
  466.     if (r) {  /* Argument is in a register. */
  467.       if (r < RID_MAX_GPR && ref < ASMREF_TMP1) {
  468. #if LJ_64
  469.         if (ir->o == IR_KINT64)
  470.           emit_loadu64(as, r, ir_kint64(ir)->u64);
  471.         else
  472. #endif
  473.           emit_loadi(as, r, ir->i);
  474.       } else {
  475.         lua_assert(rset_test(as->freeset, r));  /* Must have been evicted. */
  476.         if (ra_hasreg(ir->r)) {
  477.           ra_noweak(as, ir->r);
  478.           emit_movrr(as, ir, r, ir->r);
  479.         } else {
  480.           ra_allocref(as, ref, RID2RSET(r));
  481.         }
  482.       }
  483.     } else if (irt_isfp(ir->t)) {  /* FP argument is on stack. */
  484.       lua_assert(!(irt_isfloat(ir->t) && irref_isk(ref)));  /* No float k. */
  485.       if (LJ_32 && (ofs & 4) && irref_isk(ref)) {
  486.         /* Split stores for unaligned FP consts. */
  487.         emit_movmroi(as, RID_ESP, ofs, (int32_t)ir_knum(ir)->u32.lo);
  488.         emit_movmroi(as, RID_ESP, ofs+4, (int32_t)ir_knum(ir)->u32.hi);
  489.       } else {
  490.         r = ra_alloc1(as, ref, RSET_FPR);
  491.         emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto,
  492.                   r, RID_ESP, ofs);
  493.       }
  494.       ofs += (LJ_32 && irt_isfloat(ir->t)) ? 4 : 8;
  495.     } else/* Non-FP argument is on stack. */
  496.       if (LJ_32 && ref < ASMREF_TMP1) {
  497.         emit_movmroi(as, RID_ESP, ofs, ir->i);
  498.       } else {
  499.         r = ra_alloc1(as, ref, RSET_GPR);
  500.         emit_movtomro(as, REX_64 + r, RID_ESP, ofs);
  501.       }
  502.       ofs += sizeof(intptr_t);
  503.     }
  504.     checkmclim(as);
  505.   }
  506. #if LJ_64 && !LJ_ABI_WIN
  507.   if (patchnfpr) *patchnfpr = fpr - REGARG_FIRSTFPR;
  508. #endif
  509. }

  510. /* Setup result reg/sp for call. Evict scratch regs. */
  511. static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
  512. {
  513.   RegSet drop = RSET_SCRATCH;
  514.   int hiop = (LJ_32 && (ir+1)->o == IR_HIOP);
  515.   if ((ci->flags & CCI_NOFPRCLOBBER))
  516.     drop &= ~RSET_FPR;
  517.   if (ra_hasreg(ir->r))
  518.     rset_clear(drop, ir->r);  /* Dest reg handled below. */
  519.   if (hiop && ra_hasreg((ir+1)->r))
  520.     rset_clear(drop, (ir+1)->r);  /* Dest reg handled below. */
  521.   ra_evictset(as, drop);  /* Evictions must be performed first. */
  522.   if (ra_used(ir)) {
  523.     if (irt_isfp(ir->t)) {
  524.       int32_t ofs = sps_scale(ir->s);  /* Use spill slot or temp slots. */
  525. #if LJ_64
  526.       if ((ci->flags & CCI_CASTU64)) {
  527.         Reg dest = ir->r;
  528.         if (ra_hasreg(dest)) {
  529.           ra_free(as, dest);
  530.           ra_modified(as, dest);
  531.           emit_rr(as, XO_MOVD, dest|REX_64, RID_RET);  /* Really MOVQ. */
  532.         }
  533.         if (ofs) emit_movtomro(as, RID_RET|REX_64, RID_ESP, ofs);
  534.       } else {
  535.         ra_destreg(as, ir, RID_FPRET);
  536.       }
  537. #else
  538.       /* Number result is in x87 st0 for x86 calling convention. */
  539.       Reg dest = ir->r;
  540.       if (ra_hasreg(dest)) {
  541.         ra_free(as, dest);
  542.         ra_modified(as, dest);
  543.         emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS,
  544.                   dest, RID_ESP, ofs);
  545.       }
  546.       if ((ci->flags & CCI_CASTU64)) {
  547.         emit_movtomro(as, RID_RETLO, RID_ESP, ofs);
  548.         emit_movtomro(as, RID_RETHI, RID_ESP, ofs+4);
  549.       } else {
  550.         emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
  551.                   irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
  552.       }
  553. #endif
  554. #if LJ_32
  555.     } else if (hiop) {
  556.       ra_destpair(as, ir);
  557. #endif
  558.     } else {
  559.       lua_assert(!irt_ispri(ir->t));
  560.       ra_destreg(as, ir, RID_RET);
  561.     }
  562.   } else if (LJ_32 && irt_isfp(ir->t) && !(ci->flags & CCI_CASTU64)) {
  563.     emit_x87op(as, XI_FPOP);  /* Pop unused result from x87 st0. */
  564.   }
  565. }

  566. /* Return a constant function pointer or NULL for indirect calls. */
  567. static void *asm_callx_func(ASMState *as, IRIns *irf, IRRef func)
  568. {
  569. #if LJ_32
  570.   UNUSED(as);
  571.   if (irref_isk(func))
  572.     return (void *)irf->i;
  573. #else
  574.   if (irref_isk(func)) {
  575.     MCode *p;
  576.     if (irf->o == IR_KINT64)
  577.       p = (MCode *)(void *)ir_k64(irf)->u64;
  578.     else
  579.       p = (MCode *)(void *)(uintptr_t)(uint32_t)irf->i;
  580.     if (p - as->mcp == (int32_t)(p - as->mcp))
  581.       return p;  /* Call target is still in +-2GB range. */
  582.     /* Avoid the indirect case of emit_call(). Try to hoist func addr. */
  583.   }
  584. #endif
  585.   return NULL;
  586. }

  587. static void asm_callx(ASMState *as, IRIns *ir)
  588. {
  589.   IRRef args[CCI_NARGS_MAX*2];
  590.   CCallInfo ci;
  591.   IRRef func;
  592.   IRIns *irf;
  593.   int32_t spadj = 0;
  594.   ci.flags = asm_callx_flags(as, ir);
  595.   asm_collectargs(as, ir, &ci, args);
  596.   asm_setupresult(as, ir, &ci);
  597. #if LJ_32
  598.   /* Have to readjust stack after non-cdecl calls due to callee cleanup. */
  599.   if ((ci.flags & CCI_CC_MASK) != CCI_CC_CDECL)
  600.     spadj = 4 * asm_count_call_slots(as, &ci, args);
  601. #endif
  602.   func = ir->op2; irf = IR(func);
  603.   if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); }
  604.   ci.func = (ASMFunction)asm_callx_func(as, irf, func);
  605.   if (!(void *)ci.func) {
  606.     /* Use a (hoistable) non-scratch register for indirect calls. */
  607.     RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
  608.     Reg r = ra_alloc1(as, func, allow);
  609.     if (LJ_32) emit_spsub(as, spadj);  /* Above code may cause restores! */
  610.     emit_rr(as, XO_GROUP5, XOg_CALL, r);
  611.   } else if (LJ_32) {
  612.     emit_spsub(as, spadj);
  613.   }
  614.   asm_gencall(as, &ci, args);
  615. }

  616. /* -- Returns ------------------------------------------------------------- */

  617. /* Return to lower frame. Guard that it goes to the right spot. */
  618. static void asm_retf(ASMState *as, IRIns *ir)
  619. {
  620.   Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
  621.   void *pc = ir_kptr(IR(ir->op2));
  622.   int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
  623.   as->topslot -= (BCReg)delta;
  624.   if ((int32_t)as->topslot < 0) as->topslot = 0;
  625.   irt_setmark(IR(REF_BASE)->t);  /* Children must not coalesce with BASE reg. */
  626.   emit_setgl(as, base, jit_base);
  627.   emit_addptr(as, base, -8*delta);
  628.   asm_guardcc(as, CC_NE);
  629.   emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc));
  630. }

  631. /* -- Type conversions ---------------------------------------------------- */

  632. static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
  633. {
  634.   Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
  635.   Reg dest = ra_dest(as, ir, RSET_GPR);
  636.   asm_guardcc(as, CC_P);
  637.   asm_guardcc(as, CC_NE);
  638.   emit_rr(as, XO_UCOMISD, left, tmp);
  639.   emit_rr(as, XO_CVTSI2SD, tmp, dest);
  640.   emit_rr(as, XO_XORPS, tmp, tmp);  /* Avoid partial register stall. */
  641.   emit_rr(as, XO_CVTTSD2SI, dest, left);
  642.   /* Can't fuse since left is needed twice. */
  643. }

  644. static void asm_tobit(ASMState *as, IRIns *ir)
  645. {
  646.   Reg dest = ra_dest(as, ir, RSET_GPR);
  647.   Reg tmp = ra_noreg(IR(ir->op1)->r) ?
  648.               ra_alloc1(as, ir->op1, RSET_FPR) :
  649.               ra_scratch(as, RSET_FPR);
  650.   Reg right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp));
  651.   emit_rr(as, XO_MOVDto, tmp, dest);
  652.   emit_mrm(as, XO_ADDSD, tmp, right);
  653.   ra_left(as, tmp, ir->op1);
  654. }

  655. static void asm_conv(ASMState *as, IRIns *ir)
  656. {
  657.   IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK);
  658.   int st64 = (st == IRT_I64 || st == IRT_U64 || (LJ_64 && st == IRT_P64));
  659.   int stfp = (st == IRT_NUM || st == IRT_FLOAT);
  660.   IRRef lref = ir->op1;
  661.   lua_assert(irt_type(ir->t) != st);
  662.   lua_assert(!(LJ_32 && (irt_isint64(ir->t) || st64)));  /* Handled by SPLIT. */
  663.   if (irt_isfp(ir->t)) {
  664.     Reg dest = ra_dest(as, ir, RSET_FPR);
  665.     if (stfp) {  /* FP to FP conversion. */
  666.       Reg left = asm_fuseload(as, lref, RSET_FPR);
  667.       emit_mrm(as, st == IRT_NUM ? XO_CVTSD2SS : XO_CVTSS2SD, dest, left);
  668.       if (left == dest) return/* Avoid the XO_XORPS. */
  669.     } else if (LJ_32 && st == IRT_U32) {  /* U32 to FP conversion on x86. */
  670.       /* number = (2^52+2^51 .. u32) - (2^52+2^51) */
  671.       cTValue *k = lj_ir_k64_find(as->J, U64x(43380000,00000000));
  672.       Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest));
  673.       if (irt_isfloat(ir->t))
  674.         emit_rr(as, XO_CVTSD2SS, dest, dest);
  675.       emit_rr(as, XO_SUBSD, dest, bias);  /* Subtract 2^52+2^51 bias. */
  676.       emit_rr(as, XO_XORPS, dest, bias);  /* Merge bias and integer. */
  677.       emit_loadn(as, bias, k);
  678.       emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR));
  679.       return;
  680.     } else/* Integer to FP conversion. */
  681.       Reg left = (LJ_64 && (st == IRT_U32 || st == IRT_U64)) ?
  682.                  ra_alloc1(as, lref, RSET_GPR) :
  683.                  asm_fuseloadm(as, lref, RSET_GPR, st64);
  684.       if (LJ_64 && st == IRT_U64) {
  685.         MCLabel l_end = emit_label(as);
  686.         const void *k = lj_ir_k64_find(as->J, U64x(43f00000,00000000));
  687.         emit_rma(as, XO_ADDSD, dest, k);  /* Add 2^64 to compensate. */
  688.         emit_sjcc(as, CC_NS, l_end);
  689.         emit_rr(as, XO_TEST, left|REX_64, left);  /* Check if u64 >= 2^63. */
  690.       }
  691.       emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS,
  692.                dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left);
  693.     }
  694.     emit_rr(as, XO_XORPS, dest, dest);  /* Avoid partial register stall. */
  695.   } else if (stfp) {  /* FP to integer conversion. */
  696.     if (irt_isguard(ir->t)) {
  697.       /* Checked conversions are only supported from number to int. */
  698.       lua_assert(irt_isint(ir->t) && st == IRT_NUM);
  699.       asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR));
  700.     } else {
  701.       Reg dest = ra_dest(as, ir, RSET_GPR);
  702.       x86Op op = st == IRT_NUM ? XO_CVTTSD2SI : XO_CVTTSS2SI;
  703.       if (LJ_64 ? irt_isu64(ir->t) : irt_isu32(ir->t)) {
  704.         /* LJ_64: For inputs >= 2^63 add -2^64, convert again. */
  705.         /* LJ_32: For inputs >= 2^31 add -2^31, convert again and add 2^31. */
  706.         Reg tmp = ra_noreg(IR(lref)->r) ? ra_alloc1(as, lref, RSET_FPR) :
  707.                                           ra_scratch(as, RSET_FPR);
  708.         MCLabel l_end = emit_label(as);
  709.         if (LJ_32)
  710.           emit_gri(as, XG_ARITHi(XOg_ADD), dest, (int32_t)0x80000000);
  711.         emit_rr(as, op, dest|REX_64, tmp);
  712.         if (st == IRT_NUM)
  713.           emit_rma(as, XO_ADDSD, tmp, lj_ir_k64_find(as->J,
  714.                    LJ_64 ? U64x(c3f00000,00000000) : U64x(c1e00000,00000000)));
  715.         else
  716.           emit_rma(as, XO_ADDSS, tmp, lj_ir_k64_find(as->J,
  717.                    LJ_64 ? U64x(00000000,df800000) : U64x(00000000,cf000000)));
  718.         emit_sjcc(as, CC_NS, l_end);
  719.         emit_rr(as, XO_TEST, dest|REX_64, dest);  /* Check if dest negative. */
  720.         emit_rr(as, op, dest|REX_64, tmp);
  721.         ra_left(as, tmp, lref);
  722.       } else {
  723.         Reg left = asm_fuseload(as, lref, RSET_FPR);
  724.         if (LJ_64 && irt_isu32(ir->t))
  725.           emit_rr(as, XO_MOV, dest, dest);  /* Zero hiword. */
  726.         emit_mrm(as, op,
  727.                  dest|((LJ_64 &&
  728.                         (irt_is64(ir->t) || irt_isu32(ir->t))) ? REX_64 : 0),
  729.                  left);
  730.       }
  731.     }
  732.   } else if (st >= IRT_I8 && st <= IRT_U16) {  /* Extend to 32 bit integer. */
  733.     Reg left, dest = ra_dest(as, ir, RSET_GPR);
  734.     RegSet allow = RSET_GPR;
  735.     x86Op op;
  736.     lua_assert(irt_isint(ir->t) || irt_isu32(ir->t));
  737.     if (st == IRT_I8) {
  738.       op = XO_MOVSXb; allow = RSET_GPR8; dest |= FORCE_REX;
  739.     } else if (st == IRT_U8) {
  740.       op = XO_MOVZXb; allow = RSET_GPR8; dest |= FORCE_REX;
  741.     } else if (st == IRT_I16) {
  742.       op = XO_MOVSXw;
  743.     } else {
  744.       op = XO_MOVZXw;
  745.     }
  746.     left = asm_fuseload(as, lref, allow);
  747.     /* Add extra MOV if source is already in wrong register. */
  748.     if (!LJ_64 && left != RID_MRM && !rset_test(allow, left)) {
  749.       Reg tmp = ra_scratch(as, allow);
  750.       emit_rr(as, op, dest, tmp);
  751.       emit_rr(as, XO_MOV, tmp, left);
  752.     } else {
  753.       emit_mrm(as, op, dest, left);
  754.     }
  755.   } else/* 32/64 bit integer conversions. */
  756.     if (LJ_32) {  /* Only need to handle 32/32 bit no-op (cast) on x86. */
  757.       Reg dest = ra_dest(as, ir, RSET_GPR);
  758.       ra_left(as, dest, lref);  /* Do nothing, but may need to move regs. */
  759.     } else if (irt_is64(ir->t)) {
  760.       Reg dest = ra_dest(as, ir, RSET_GPR);
  761.       if (st64 || !(ir->op2 & IRCONV_SEXT)) {
  762.         /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */
  763.         ra_left(as, dest, lref);  /* Do nothing, but may need to move regs. */
  764.       } else/* 32 to 64 bit sign extension. */
  765.         Reg left = asm_fuseload(as, lref, RSET_GPR);
  766.         emit_mrm(as, XO_MOVSXd, dest|REX_64, left);
  767.       }
  768.     } else {
  769.       Reg dest = ra_dest(as, ir, RSET_GPR);
  770.       if (st64) {
  771.         Reg left = asm_fuseload(as, lref, RSET_GPR);
  772.         /* This is either a 32 bit reg/reg mov which zeroes the hiword
  773.         ** or a load of the loword from a 64 bit address.
  774.         */
  775.         emit_mrm(as, XO_MOV, dest, left);
  776.       } else/* 32/32 bit no-op (cast). */
  777.         ra_left(as, dest, lref);  /* Do nothing, but may need to move regs. */
  778.       }
  779.     }
  780.   }
  781. }

  782. #if LJ_32 && LJ_HASFFI
  783. /* No SSE conversions to/from 64 bit on x86, so resort to ugly x87 code. */

  784. /* 64 bit integer to FP conversion in 32 bit mode. */
  785. static void asm_conv_fp_int64(ASMState *as, IRIns *ir)
  786. {
  787.   Reg hi = ra_alloc1(as, ir->op1, RSET_GPR);
  788.   Reg lo = ra_alloc1(as, (ir-1)->op1, rset_exclude(RSET_GPR, hi));
  789.   int32_t ofs = sps_scale(ir->s);  /* Use spill slot or temp slots. */
  790.   Reg dest = ir->r;
  791.   if (ra_hasreg(dest)) {
  792.     ra_free(as, dest);
  793.     ra_modified(as, dest);
  794.     emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, dest, RID_ESP, ofs);
  795.   }
  796.   emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
  797.             irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
  798.   if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) {
  799.     /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */
  800.     MCLabel l_end = emit_label(as);
  801.     emit_rma(as, XO_FADDq, XOg_FADDq,
  802.              lj_ir_k64_find(as->J, U64x(43f00000,00000000)));
  803.     emit_sjcc(as, CC_NS, l_end);
  804.     emit_rr(as, XO_TEST, hi, hi);  /* Check if u64 >= 2^63. */
  805.   } else {
  806.     lua_assert(((ir-1)->op2 & IRCONV_SRCMASK) == IRT_I64);
  807.   }
  808.   emit_rmro(as, XO_FILDq, XOg_FILDq, RID_ESP, 0);
  809.   /* NYI: Avoid narrow-to-wide store-to-load forwarding stall. */
  810.   emit_rmro(as, XO_MOVto, hi, RID_ESP, 4);
  811.   emit_rmro(as, XO_MOVto, lo, RID_ESP, 0);
  812. }

  813. /* FP to 64 bit integer conversion in 32 bit mode. */
  814. static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
  815. {
  816.   IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
  817.   IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
  818.   Reg lo, hi;
  819.   lua_assert(st == IRT_NUM || st == IRT_FLOAT);
  820.   lua_assert(dt == IRT_I64 || dt == IRT_U64);
  821.   hi = ra_dest(as, ir, RSET_GPR);
  822.   lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi));
  823.   if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0);
  824.   /* NYI: Avoid wide-to-narrow store-to-load forwarding stall. */
  825.   if (!(as->flags & JIT_F_SSE3)) {  /* Set FPU rounding mode to default. */
  826.     emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 4);
  827.     emit_rmro(as, XO_MOVto, lo, RID_ESP, 4);
  828.     emit_gri(as, XG_ARITHi(XOg_AND), lo, 0xf3ff);
  829.   }
  830.   if (dt == IRT_U64) {
  831.     /* For inputs in [2^63,2^64-1] add -2^64 and convert again. */
  832.     MCLabel l_pop, l_end = emit_label(as);
  833.     emit_x87op(as, XI_FPOP);
  834.     l_pop = emit_label(as);
  835.     emit_sjmp(as, l_end);
  836.     emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
  837.     if ((as->flags & JIT_F_SSE3))
  838.       emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
  839.     else
  840.       emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
  841.     emit_rma(as, XO_FADDq, XOg_FADDq,
  842.              lj_ir_k64_find(as->J, U64x(c3f00000,00000000)));
  843.     emit_sjcc(as, CC_NS, l_pop);
  844.     emit_rr(as, XO_TEST, hi, hi);  /* Check if out-of-range (2^63). */
  845.   }
  846.   emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
  847.   if ((as->flags & JIT_F_SSE3)) {  /* Truncation is easy with SSE3. */
  848.     emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
  849.   } else/* Otherwise set FPU rounding mode to truncate before the store. */
  850.     emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
  851.     emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 0);
  852.     emit_rmro(as, XO_MOVtow, lo, RID_ESP, 0);
  853.     emit_rmro(as, XO_ARITHw(XOg_OR), lo, RID_ESP, 0);
  854.     emit_loadi(as, lo, 0xc00);
  855.     emit_rmro(as, XO_FNSTCW, XOg_FNSTCW, RID_ESP, 0);
  856.   }
  857.   if (dt == IRT_U64)
  858.     emit_x87op(as, XI_FDUP);
  859.   emit_mrm(as, st == IRT_NUM ? XO_FLDq : XO_FLDd,
  860.            st == IRT_NUM ? XOg_FLDq: XOg_FLDd,
  861.            asm_fuseload(as, ir->op1, RSET_EMPTY));
  862. }

  863. static void asm_conv64(ASMState *as, IRIns *ir)
  864. {
  865.   if (irt_isfp(ir->t))
  866.     asm_conv_fp_int64(as, ir);
  867.   else
  868.     asm_conv_int64_fp(as, ir);
  869. }
  870. #endif

  871. static void asm_strto(ASMState *as, IRIns *ir)
  872. {
  873.   /* Force a spill slot for the destination register (if any). */
  874.   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
  875.   IRRef args[2];
  876.   RegSet drop = RSET_SCRATCH;
  877.   if ((drop & RSET_FPR) != RSET_FPR && ra_hasreg(ir->r))
  878.     rset_set(drop, ir->r);  /* WIN64 doesn't spill all FPRs. */
  879.   ra_evictset(as, drop);
  880.   asm_guardcc(as, CC_E);
  881.   emit_rr(as, XO_TEST, RID_RET, RID_RET);  /* Test return status. */
  882.   args[0] = ir->op1;      /* GCstr *str */
  883.   args[1] = ASMREF_TMP1/* TValue *n  */
  884.   asm_gencall(as, ci, args);
  885.   /* Store the result to the spill slot or temp slots. */
  886.   emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
  887.             RID_ESP, sps_scale(ir->s));
  888. }

  889. /* -- Memory references --------------------------------------------------- */

  890. /* Get pointer to TValue. */
  891. static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
  892. {
  893.   IRIns *ir = IR(ref);
  894.   if (irt_isnum(ir->t)) {
  895.     /* For numbers use the constant itself or a spill slot as a TValue. */
  896.     if (irref_isk(ref))
  897.       emit_loada(as, dest, ir_knum(ir));
  898.     else
  899.       emit_rmro(as, XO_LEA, dest|REX_64, RID_ESP, ra_spill(as, ir));
  900.   } else {
  901.     /* Otherwise use g->tmptv to hold the TValue. */
  902.     if (!irref_isk(ref)) {
  903.       Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, dest));
  904.       emit_movtomro(as, REX_64IR(ir, src), dest, 0);
  905.     } else if (!irt_ispri(ir->t)) {
  906.       emit_movmroi(as, dest, 0, ir->i);
  907.     }
  908.     if (!(LJ_64 && irt_islightud(ir->t)))
  909.       emit_movmroi(as, dest, 4, irt_toitype(ir->t));
  910.     emit_loada(as, dest, &J2G(as->J)->tmptv);
  911.   }
  912. }

  913. static void asm_aref(ASMState *as, IRIns *ir)
  914. {
  915.   Reg dest = ra_dest(as, ir, RSET_GPR);
  916.   asm_fusearef(as, ir, RSET_GPR);
  917.   if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0))
  918.     emit_mrm(as, XO_LEA, dest, RID_MRM);
  919.   else if (as->mrm.base != dest)
  920.     emit_rr(as, XO_MOV, dest, as->mrm.base);
  921. }

  922. /* Inlined hash lookup. Specialized for key type and for const keys.
  923. ** The equivalent C code is:
  924. **   Node *n = hashkey(t, key);
  925. **   do {
  926. **     if (lj_obj_equal(&n->key, key)) return &n->val;
  927. **   } while ((n = nextnode(n)));
  928. **   return niltv(L);
  929. */
  930. static void asm_href(ASMState *as, IRIns *ir, IROp merge)
  931. {
  932.   RegSet allow = RSET_GPR;
  933.   int destused = ra_used(ir);
  934.   Reg dest = ra_dest(as, ir, allow);
  935.   Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest));
  936.   Reg key = RID_NONE, tmp = RID_NONE;
  937.   IRIns *irkey = IR(ir->op2);
  938.   int isk = irref_isk(ir->op2);
  939.   IRType1 kt = irkey->t;
  940.   uint32_t khash;
  941.   MCLabel l_end, l_loop, l_next;

  942.   if (!isk) {
  943.     rset_clear(allow, tab);
  944.     key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow);
  945.     if (!irt_isstr(kt))
  946.       tmp = ra_scratch(as, rset_exclude(allow, key));
  947.   }

  948.   /* Key not found in chain: jump to exit (if merged) or load niltv. */
  949.   l_end = emit_label(as);
  950.   if (merge == IR_NE)
  951.     asm_guardcc(as, CC_E);  /* XI_JMP is not found by lj_asm_patchexit. */
  952.   else if (destused)
  953.     emit_loada(as, dest, niltvg(J2G(as->J)));

  954.   /* Follow hash chain until the end. */
  955.   l_loop = emit_sjcc_label(as, CC_NZ);
  956.   emit_rr(as, XO_TEST, dest, dest);
  957.   emit_rmro(as, XO_MOV, dest, dest, offsetof(Node, next));
  958.   l_next = emit_label(as);

  959.   /* Type and value comparison. */
  960.   if (merge == IR_EQ)
  961.     asm_guardcc(as, CC_E);
  962.   else
  963.     emit_sjcc(as, CC_E, l_end);
  964.   if (irt_isnum(kt)) {
  965.     if (isk) {
  966.       /* Assumes -0.0 is already canonicalized to +0.0. */
  967.       emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo),
  968.                  (int32_t)ir_knum(irkey)->u32.lo);
  969.       emit_sjcc(as, CC_NE, l_next);
  970.       emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi),
  971.                  (int32_t)ir_knum(irkey)->u32.hi);
  972.     } else {
  973.       emit_sjcc(as, CC_P, l_next);
  974.       emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n));
  975.       emit_sjcc(as, CC_AE, l_next);
  976.       /* The type check avoids NaN penalties and complaints from Valgrind. */
  977. #if LJ_64
  978.       emit_u32(as, LJ_TISNUM);
  979.       emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it));
  980. #else
  981.       emit_i8(as, LJ_TISNUM);
  982.       emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
  983. #endif
  984.     }
  985. #if LJ_64
  986.   } else if (irt_islightud(kt)) {
  987.     emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64));
  988. #endif
  989.   } else {
  990.     if (!irt_ispri(kt)) {
  991.       lua_assert(irt_isaddr(kt));
  992.       if (isk)
  993.         emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.gcr),
  994.                    ptr2addr(ir_kgc(irkey)));
  995.       else
  996.         emit_rmro(as, XO_CMP, key, dest, offsetof(Node, key.gcr));
  997.       emit_sjcc(as, CC_NE, l_next);
  998.     }
  999.     lua_assert(!irt_isnil(kt));
  1000.     emit_i8(as, irt_toitype(kt));
  1001.     emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
  1002.   }
  1003.   emit_sfixup(as, l_loop);
  1004.   checkmclim(as);

  1005.   /* Load main position relative to tab->node into dest. */
  1006.   khash = isk ? ir_khash(irkey) : 1;
  1007.   if (khash == 0) {
  1008.     emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, node));
  1009.   } else {
  1010.     emit_rmro(as, XO_ARITH(XOg_ADD), dest, tab, offsetof(GCtab, node));
  1011.     if ((as->flags & JIT_F_PREFER_IMUL)) {
  1012.       emit_i8(as, sizeof(Node));
  1013.       emit_rr(as, XO_IMULi8, dest, dest);
  1014.     } else {
  1015.       emit_shifti(as, XOg_SHL, dest, 3);
  1016.       emit_rmrxo(as, XO_LEA, dest, dest, dest, XM_SCALE2, 0);
  1017.     }
  1018.     if (isk) {
  1019.       emit_gri(as, XG_ARITHi(XOg_AND), dest, (int32_t)khash);
  1020.       emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
  1021.     } else if (irt_isstr(kt)) {
  1022.       emit_rmro(as, XO_ARITH(XOg_AND), dest, key, offsetof(GCstr, hash));
  1023.       emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
  1024.     } else/* Must match with hashrot() in lj_tab.c. */
  1025.       emit_rmro(as, XO_ARITH(XOg_AND), dest, tab, offsetof(GCtab, hmask));
  1026.       emit_rr(as, XO_ARITH(XOg_SUB), dest, tmp);
  1027.       emit_shifti(as, XOg_ROL, tmp, HASH_ROT3);
  1028.       emit_rr(as, XO_ARITH(XOg_XOR), dest, tmp);
  1029.       emit_shifti(as, XOg_ROL, dest, HASH_ROT2);
  1030.       emit_rr(as, XO_ARITH(XOg_SUB), tmp, dest);
  1031.       emit_shifti(as, XOg_ROL, dest, HASH_ROT1);
  1032.       emit_rr(as, XO_ARITH(XOg_XOR), tmp, dest);
  1033.       if (irt_isnum(kt)) {
  1034.         emit_rr(as, XO_ARITH(XOg_ADD), dest, dest);
  1035. #if LJ_64
  1036.         emit_shifti(as, XOg_SHR|REX_64, dest, 32);
  1037.         emit_rr(as, XO_MOV, tmp, dest);
  1038.         emit_rr(as, XO_MOVDto, key|REX_64, dest);
  1039. #else
  1040.         emit_rmro(as, XO_MOV, dest, RID_ESP, ra_spill(as, irkey)+4);
  1041.         emit_rr(as, XO_MOVDto, key, tmp);
  1042. #endif
  1043.       } else {
  1044.         emit_rr(as, XO_MOV, tmp, key);
  1045.         emit_rmro(as, XO_LEA, dest, key, HASH_BIAS);
  1046.       }
  1047.     }
  1048.   }
  1049. }

  1050. static void asm_hrefk(ASMState *as, IRIns *ir)
  1051. {
  1052.   IRIns *kslot = IR(ir->op2);
  1053.   IRIns *irkey = IR(kslot->op1);
  1054.   int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node));
  1055.   Reg dest = ra_used(ir) ? ra_dest(as, ir, RSET_GPR) : RID_NONE;
  1056.   Reg node = ra_alloc1(as, ir->op1, RSET_GPR);
  1057. #if !LJ_64
  1058.   MCLabel l_exit;
  1059. #endif
  1060.   lua_assert(ofs % sizeof(Node) == 0);
  1061.   if (ra_hasreg(dest)) {
  1062.     if (ofs != 0) {
  1063.       if (dest == node && !(as->flags & JIT_F_LEA_AGU))
  1064.         emit_gri(as, XG_ARITHi(XOg_ADD), dest, ofs);
  1065.       else
  1066.         emit_rmro(as, XO_LEA, dest, node, ofs);
  1067.     } else if (dest != node) {
  1068.       emit_rr(as, XO_MOV, dest, node);
  1069.     }
  1070.   }
  1071.   asm_guardcc(as, CC_NE);
  1072. #if LJ_64
  1073.   if (!irt_ispri(irkey->t)) {
  1074.     Reg key = ra_scratch(as, rset_exclude(RSET_GPR, node));
  1075.     emit_rmro(as, XO_CMP, key|REX_64, node,
  1076.                ofs + (int32_t)offsetof(Node, key.u64));
  1077.     lua_assert(irt_isnum(irkey->t) || irt_isgcv(irkey->t));
  1078.     /* Assumes -0.0 is already canonicalized to +0.0. */
  1079.     emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 :
  1080.                           ((uint64_t)irt_toitype(irkey->t) << 32) |
  1081.                           (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey)));
  1082.   } else {
  1083.     lua_assert(!irt_isnil(irkey->t));
  1084.     emit_i8(as, irt_toitype(irkey->t));
  1085.     emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
  1086.               ofs + (int32_t)offsetof(Node, key.it));
  1087.   }
  1088. #else
  1089.   l_exit = emit_label(as);
  1090.   if (irt_isnum(irkey->t)) {
  1091.     /* Assumes -0.0 is already canonicalized to +0.0. */
  1092.     emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
  1093.                ofs + (int32_t)offsetof(Node, key.u32.lo),
  1094.                (int32_t)ir_knum(irkey)->u32.lo);
  1095.     emit_sjcc(as, CC_NE, l_exit);
  1096.     emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
  1097.                ofs + (int32_t)offsetof(Node, key.u32.hi),
  1098.                (int32_t)ir_knum(irkey)->u32.hi);
  1099.   } else {
  1100.     if (!irt_ispri(irkey->t)) {
  1101.       lua_assert(irt_isgcv(irkey->t));
  1102.       emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
  1103.                  ofs + (int32_t)offsetof(Node, key.gcr),
  1104.                  ptr2addr(ir_kgc(irkey)));
  1105.       emit_sjcc(as, CC_NE, l_exit);
  1106.     }
  1107.     lua_assert(!irt_isnil(irkey->t));
  1108.     emit_i8(as, irt_toitype(irkey->t));
  1109.     emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
  1110.               ofs + (int32_t)offsetof(Node, key.it));
  1111.   }
  1112. #endif
  1113. }

  1114. static void asm_uref(ASMState *as, IRIns *ir)
  1115. {
  1116.   /* NYI: Check that UREFO is still open and not aliasing a slot. */
  1117.   Reg dest = ra_dest(as, ir, RSET_GPR);
  1118.   if (irref_isk(ir->op1)) {
  1119.     GCfunc *fn = ir_kfunc(IR(ir->op1));
  1120.     MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
  1121.     emit_rma(as, XO_MOV, dest, v);
  1122.   } else {
  1123.     Reg uv = ra_scratch(as, RSET_GPR);
  1124.     Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
  1125.     if (ir->o == IR_UREFC) {
  1126.       emit_rmro(as, XO_LEA, dest, uv, offsetof(GCupval, tv));
  1127.       asm_guardcc(as, CC_NE);
  1128.       emit_i8(as, 1);
  1129.       emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed));
  1130.     } else {
  1131.       emit_rmro(as, XO_MOV, dest, uv, offsetof(GCupval, v));
  1132.     }
  1133.     emit_rmro(as, XO_MOV, uv, func,
  1134.               (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8));
  1135.   }
  1136. }

  1137. static void asm_fref(ASMState *as, IRIns *ir)
  1138. {
  1139.   Reg dest = ra_dest(as, ir, RSET_GPR);
  1140.   asm_fusefref(as, ir, RSET_GPR);
  1141.   emit_mrm(as, XO_LEA, dest, RID_MRM);
  1142. }

  1143. static void asm_strref(ASMState *as, IRIns *ir)
  1144. {
  1145.   Reg dest = ra_dest(as, ir, RSET_GPR);
  1146.   asm_fusestrref(as, ir, RSET_GPR);
  1147.   if (as->mrm.base == RID_NONE)
  1148.     emit_loadi(as, dest, as->mrm.ofs);
  1149.   else if (as->mrm.base == dest && as->mrm.idx == RID_NONE)
  1150.     emit_gri(as, XG_ARITHi(XOg_ADD), dest, as->mrm.ofs);
  1151.   else
  1152.     emit_mrm(as, XO_LEA, dest, RID_MRM);
  1153. }

  1154. /* -- Loads and stores ---------------------------------------------------- */

  1155. static void asm_fxload(ASMState *as, IRIns *ir)
  1156. {
  1157.   Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
  1158.   x86Op xo;
  1159.   if (ir->o == IR_FLOAD)
  1160.     asm_fusefref(as, ir, RSET_GPR);
  1161.   else
  1162.     asm_fusexref(as, ir->op1, RSET_GPR);
  1163.   /* ir->op2 is ignored -- unaligned loads are ok on x86. */
  1164.   switch (irt_type(ir->t)) {
  1165.   case IRT_I8: xo = XO_MOVSXb; break;
  1166.   case IRT_U8: xo = XO_MOVZXb; break;
  1167.   case IRT_I16: xo = XO_MOVSXw; break;
  1168.   case IRT_U16: xo = XO_MOVZXw; break;
  1169.   case IRT_NUM: xo = XO_MOVSD; break;
  1170.   case IRT_FLOAT: xo = XO_MOVSS; break;
  1171.   default:
  1172.     if (LJ_64 && irt_is64(ir->t))
  1173.       dest |= REX_64;
  1174.     else
  1175.       lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
  1176.     xo = XO_MOV;
  1177.     break;
  1178.   }
  1179.   emit_mrm(as, xo, dest, RID_MRM);
  1180. }

  1181. #define asm_fload(as, ir)        asm_fxload(as, ir)
  1182. #define asm_xload(as, ir)        asm_fxload(as, ir)

  1183. static void asm_fxstore(ASMState *as, IRIns *ir)
  1184. {
  1185.   RegSet allow = RSET_GPR;
  1186.   Reg src = RID_NONE, osrc = RID_NONE;
  1187.   int32_t k = 0;
  1188.   if (ir->r == RID_SINK)
  1189.     return;
  1190.   /* The IRT_I16/IRT_U16 stores should never be simplified for constant
  1191.   ** values since mov word [mem], imm16 has a length-changing prefix.
  1192.   */
  1193.   if (irt_isi16(ir->t) || irt_isu16(ir->t) || irt_isfp(ir->t) ||
  1194.       !asm_isk32(as, ir->op2, &k)) {
  1195.     RegSet allow8 = irt_isfp(ir->t) ? RSET_FPR :
  1196.                     (irt_isi8(ir->t) || irt_isu8(ir->t)) ? RSET_GPR8 : RSET_GPR;
  1197.     src = osrc = ra_alloc1(as, ir->op2, allow8);
  1198.     if (!LJ_64 && !rset_test(allow8, src)) {  /* Already in wrong register. */
  1199.       rset_clear(allow, osrc);
  1200.       src = ra_scratch(as, allow8);
  1201.     }
  1202.     rset_clear(allow, src);
  1203.   }
  1204.   if (ir->o == IR_FSTORE) {
  1205.     asm_fusefref(as, IR(ir->op1), allow);
  1206.   } else {
  1207.     asm_fusexref(as, ir->op1, allow);
  1208.     if (LJ_32 && ir->o == IR_HIOP) as->mrm.ofs += 4;
  1209.   }
  1210.   if (ra_hasreg(src)) {
  1211.     x86Op xo;
  1212.     switch (irt_type(ir->t)) {
  1213.     case IRT_I8: case IRT_U8: xo = XO_MOVtob; src |= FORCE_REX; break;
  1214.     case IRT_I16: case IRT_U16: xo = XO_MOVtow; break;
  1215.     case IRT_NUM: xo = XO_MOVSDto; break;
  1216.     case IRT_FLOAT: xo = XO_MOVSSto; break;
  1217. #if LJ_64
  1218.     case IRT_LIGHTUD: lua_assert(0);  /* NYI: mask 64 bit lightuserdata. */
  1219. #endif
  1220.     default:
  1221.       if (LJ_64 && irt_is64(ir->t))
  1222.         src |= REX_64;
  1223.       else
  1224.         lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
  1225.       xo = XO_MOVto;
  1226.       break;
  1227.     }
  1228.     emit_mrm(as, xo, src, RID_MRM);
  1229.     if (!LJ_64 && src != osrc) {
  1230.       ra_noweak(as, osrc);
  1231.       emit_rr(as, XO_MOV, src, osrc);
  1232.     }
  1233.   } else {
  1234.     if (irt_isi8(ir->t) || irt_isu8(ir->t)) {
  1235.       emit_i8(as, k);
  1236.       emit_mrm(as, XO_MOVmib, 0, RID_MRM);
  1237.     } else {
  1238.       lua_assert(irt_is64(ir->t) || irt_isint(ir->t) || irt_isu32(ir->t) ||
  1239.                  irt_isaddr(ir->t));
  1240.       emit_i32(as, k);
  1241.       emit_mrm(as, XO_MOVmi, REX_64IR(ir, 0), RID_MRM);
  1242.     }
  1243.   }
  1244. }

  1245. #define asm_fstore(as, ir)        asm_fxstore(as, ir)
  1246. #define asm_xstore(as, ir)        asm_fxstore(as, ir)

  1247. #if LJ_64
  1248. static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck)
  1249. {
  1250.   if (ra_used(ir) || typecheck) {
  1251.     Reg dest = ra_dest(as, ir, RSET_GPR);
  1252.     if (typecheck) {
  1253.       Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, dest));
  1254.       asm_guardcc(as, CC_NE);
  1255.       emit_i8(as, -2);
  1256.       emit_rr(as, XO_ARITHi8, XOg_CMP, tmp);
  1257.       emit_shifti(as, XOg_SAR|REX_64, tmp, 47);
  1258.       emit_rr(as, XO_MOV, tmp|REX_64, dest);
  1259.     }
  1260.     return dest;
  1261.   } else {
  1262.     return RID_NONE;
  1263.   }
  1264. }
  1265. #endif

  1266. static void asm_ahuvload(ASMState *as, IRIns *ir)
  1267. {
  1268.   lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) ||
  1269.              (LJ_DUALNUM && irt_isint(ir->t)));
  1270. #if LJ_64
  1271.   if (irt_islightud(ir->t)) {
  1272.     Reg dest = asm_load_lightud64(as, ir, 1);
  1273.     if (ra_hasreg(dest)) {
  1274.       asm_fuseahuref(as, ir->op1, RSET_GPR);
  1275.       emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM);
  1276.     }
  1277.     return;
  1278.   } else
  1279. #endif
  1280.   if (ra_used(ir)) {
  1281.     RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR;
  1282.     Reg dest = ra_dest(as, ir, allow);
  1283.     asm_fuseahuref(as, ir->op1, RSET_GPR);
  1284.     emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XO_MOVSD, dest, RID_MRM);
  1285.   } else {
  1286.     asm_fuseahuref(as, ir->op1, RSET_GPR);
  1287.   }
  1288.   /* Always do the type check, even if the load result is unused. */
  1289.   as->mrm.ofs += 4;
  1290.   asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE);
  1291.   if (LJ_64 && irt_type(ir->t) >= IRT_NUM) {
  1292.     lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t));
  1293.     emit_u32(as, LJ_TISNUM);
  1294.     emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM);
  1295.   } else {
  1296.     emit_i8(as, irt_toitype(ir->t));
  1297.     emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM);
  1298.   }
  1299. }

  1300. static void asm_ahustore(ASMState *as, IRIns *ir)
  1301. {
  1302.   if (ir->r == RID_SINK)
  1303.     return;
  1304.   if (irt_isnum(ir->t)) {
  1305.     Reg src = ra_alloc1(as, ir->op2, RSET_FPR);
  1306.     asm_fuseahuref(as, ir->op1, RSET_GPR);
  1307.     emit_mrm(as, XO_MOVSDto, src, RID_MRM);
  1308. #if LJ_64
  1309.   } else if (irt_islightud(ir->t)) {
  1310.     Reg src = ra_alloc1(as, ir->op2, RSET_GPR);
  1311.     asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src));
  1312.     emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM);
  1313. #endif
  1314.   } else {
  1315.     IRIns *irr = IR(ir->op2);
  1316.     RegSet allow = RSET_GPR;
  1317.     Reg src = RID_NONE;
  1318.     if (!irref_isk(ir->op2)) {
  1319.       src = ra_alloc1(as, ir->op2, allow);
  1320.       rset_clear(allow, src);
  1321.     }
  1322.     asm_fuseahuref(as, ir->op1, allow);
  1323.     if (ra_hasreg(src)) {
  1324.       emit_mrm(as, XO_MOVto, src, RID_MRM);
  1325.     } else if (!irt_ispri(irr->t)) {
  1326.       lua_assert(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t)));
  1327.       emit_i32(as, irr->i);
  1328.       emit_mrm(as, XO_MOVmi, 0, RID_MRM);
  1329.     }
  1330.     as->mrm.ofs += 4;
  1331.     emit_i32(as, (int32_t)irt_toitype(ir->t));
  1332.     emit_mrm(as, XO_MOVmi, 0, RID_MRM);
  1333.   }
  1334. }

  1335. static void asm_sload(ASMState *as, IRIns *ir)
  1336. {
  1337.   int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
  1338.   IRType1 t = ir->t;
  1339.   Reg base;
  1340.   lua_assert(!(ir->op2 & IRSLOAD_PARENT));  /* Handled by asm_head_side(). */
  1341.   lua_assert(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK));
  1342.   lua_assert(LJ_DUALNUM ||
  1343.              !irt_isint(t) || (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME)));
  1344.   if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) {
  1345.     Reg left = ra_scratch(as, RSET_FPR);
  1346.     asm_tointg(as, ir, left);  /* Frees dest reg. Do this before base alloc. */
  1347.     base = ra_alloc1(as, REF_BASE, RSET_GPR);
  1348.     emit_rmro(as, XO_MOVSD, left, base, ofs);
  1349.     t.irt = IRT_NUM;  /* Continue with a regular number type check. */
  1350. #if LJ_64
  1351.   } else if (irt_islightud(t)) {
  1352.     Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK));
  1353.     if (ra_hasreg(dest)) {
  1354.       base = ra_alloc1(as, REF_BASE, RSET_GPR);
  1355.       emit_rmro(as, XO_MOV, dest|REX_64, base, ofs);
  1356.     }
  1357.     return;
  1358. #endif
  1359.   } else if (ra_used(ir)) {
  1360.     RegSet allow = irt_isnum(t) ? RSET_FPR : RSET_GPR;
  1361.     Reg dest = ra_dest(as, ir, allow);
  1362.     base = ra_alloc1(as, REF_BASE, RSET_GPR);
  1363.     lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t));
  1364.     if ((ir->op2 & IRSLOAD_CONVERT)) {
  1365.       t.irt = irt_isint(t) ? IRT_NUM : IRT_INT;  /* Check for original type. */
  1366.       emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTTSD2SI, dest, base, ofs);
  1367.     } else {
  1368.       emit_rmro(as, irt_isnum(t) ? XO_MOVSD : XO_MOV, dest, base, ofs);
  1369.     }
  1370.   } else {
  1371.     if (!(ir->op2 & IRSLOAD_TYPECHECK))
  1372.       return/* No type check: avoid base alloc. */
  1373.     base = ra_alloc1(as, REF_BASE, RSET_GPR);
  1374.   }
  1375.   if ((ir->op2 & IRSLOAD_TYPECHECK)) {
  1376.     /* Need type check, even if the load result is unused. */
  1377.     asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE);
  1378.     if (LJ_64 && irt_type(t) >= IRT_NUM) {
  1379.       lua_assert(irt_isinteger(t) || irt_isnum(t));
  1380.       emit_u32(as, LJ_TISNUM);
  1381.       emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4);
  1382.     } else {
  1383.       emit_i8(as, irt_toitype(t));
  1384.       emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4);
  1385.     }
  1386.   }
  1387. }

  1388. /* -- Allocations --------------------------------------------------------- */

  1389. #if LJ_HASFFI
  1390. static void asm_cnew(ASMState *as, IRIns *ir)
  1391. {
  1392.   CTState *cts = ctype_ctsG(J2G(as->J));
  1393.   CTypeID id = (CTypeID)IR(ir->op1)->i;
  1394.   CTSize sz;
  1395.   CTInfo info = lj_ctype_info(cts, id, &sz);
  1396.   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
  1397.   IRRef args[4];
  1398.   lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));

  1399.   as->gcsteps++;
  1400.   asm_setupresult(as, ir, ci);  /* GCcdata * */

  1401.   /* Initialize immutable cdata object. */
  1402.   if (ir->o == IR_CNEWI) {
  1403.     RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
  1404. #if LJ_64
  1405.     Reg r64 = sz == 8 ? REX_64 : 0;
  1406.     if (irref_isk(ir->op2)) {
  1407.       IRIns *irk = IR(ir->op2);
  1408.       uint64_t k = irk->o == IR_KINT64 ? ir_k64(irk)->u64 :
  1409.                                          (uint64_t)(uint32_t)irk->i;
  1410.       if (sz == 4 || checki32((int64_t)k)) {
  1411.         emit_i32(as, (int32_t)k);
  1412.         emit_rmro(as, XO_MOVmi, r64, RID_RET, sizeof(GCcdata));
  1413.       } else {
  1414.         emit_movtomro(as, RID_ECX + r64, RID_RET, sizeof(GCcdata));
  1415.         emit_loadu64(as, RID_ECX, k);
  1416.       }
  1417.     } else {
  1418.       Reg r = ra_alloc1(as, ir->op2, allow);
  1419.       emit_movtomro(as, r + r64, RID_RET, sizeof(GCcdata));
  1420.     }
  1421. #else
  1422.     int32_t ofs = sizeof(GCcdata);
  1423.     if (sz == 8) {
  1424.       ofs += 4; ir++;
  1425.       lua_assert(ir->o == IR_HIOP);
  1426.     }
  1427.     do {
  1428.       if (irref_isk(ir->op2)) {
  1429.         emit_movmroi(as, RID_RET, ofs, IR(ir->op2)->i);
  1430.       } else {
  1431.         Reg r = ra_alloc1(as, ir->op2, allow);
  1432.         emit_movtomro(as, r, RID_RET, ofs);
  1433.         rset_clear(allow, r);
  1434.       }
  1435.       if (ofs == sizeof(GCcdata)) break;
  1436.       ofs -= 4; ir--;
  1437.     } while (1);
  1438. #endif
  1439.     lua_assert(sz == 4 || sz == 8);
  1440.   } else if (ir->op2 != REF_NIL) {  /* Create VLA/VLS/aligned cdata. */
  1441.     ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
  1442.     args[0] = ASMREF_L;     /* lua_State *L */
  1443.     args[1] = ir->op1;      /* CTypeID id   */
  1444.     args[2] = ir->op2;      /* CTSize sz    */
  1445.     args[3] = ASMREF_TMP1/* CTSize align */
  1446.     asm_gencall(as, ci, args);
  1447.     emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
  1448.     return;
  1449.   }

  1450.   /* Combine initialization of marked, gct and ctypeid. */
  1451.   emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked));
  1452.   emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX,
  1453.            (int32_t)((~LJ_TCDATA<<8)+(id<<16)));
  1454.   emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES);
  1455.   emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite);

  1456.   args[0] = ASMREF_L;     /* lua_State *L */
  1457.   args[1] = ASMREF_TMP1/* MSize size   */
  1458.   asm_gencall(as, ci, args);
  1459.   emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata)));
  1460. }
  1461. #else
  1462. #define asm_cnew(as, ir)        ((void)0)
  1463. #endif

  1464. /* -- Write barriers ------------------------------------------------------ */

  1465. static void asm_tbar(ASMState *as, IRIns *ir)
  1466. {
  1467.   Reg tab = ra_alloc1(as, ir->op1, RSET_GPR);
  1468.   Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab));
  1469.   MCLabel l_end = emit_label(as);
  1470.   emit_movtomro(as, tmp, tab, offsetof(GCtab, gclist));
  1471.   emit_setgl(as, tab, gc.grayagain);
  1472.   emit_getgl(as, tmp, gc.grayagain);
  1473.   emit_i8(as, ~LJ_GC_BLACK);
  1474.   emit_rmro(as, XO_ARITHib, XOg_AND, tab, offsetof(GCtab, marked));
  1475.   emit_sjcc(as, CC_Z, l_end);
  1476.   emit_i8(as, LJ_GC_BLACK);
  1477.   emit_rmro(as, XO_GROUP3b, XOg_TEST, tab, offsetof(GCtab, marked));
  1478. }

  1479. static void asm_obar(ASMState *as, IRIns *ir)
  1480. {
  1481.   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv];
  1482.   IRRef args[2];
  1483.   MCLabel l_end;
  1484.   Reg obj;
  1485.   /* No need for other object barriers (yet). */
  1486.   lua_assert(IR(ir->op1)->o == IR_UREFC);
  1487.   ra_evictset(as, RSET_SCRATCH);
  1488.   l_end = emit_label(as);
  1489.   args[0] = ASMREF_TMP1/* global_State *g */
  1490.   args[1] = ir->op1;      /* TValue *tv      */
  1491.   asm_gencall(as, ci, args);
  1492.   emit_loada(as, ra_releasetmp(as, ASMREF_TMP1), J2G(as->J));
  1493.   obj = IR(ir->op1)->r;
  1494.   emit_sjcc(as, CC_Z, l_end);
  1495.   emit_i8(as, LJ_GC_WHITES);
  1496.   if (irref_isk(ir->op2)) {
  1497.     GCobj *vp = ir_kgc(IR(ir->op2));
  1498.     emit_rma(as, XO_GROUP3b, XOg_TEST, &vp->gch.marked);
  1499.   } else {
  1500.     Reg val = ra_alloc1(as, ir->op2, rset_exclude(RSET_SCRATCH&RSET_GPR, obj));
  1501.     emit_rmro(as, XO_GROUP3b, XOg_TEST, val, (int32_t)offsetof(GChead, marked));
  1502.   }
  1503.   emit_sjcc(as, CC_Z, l_end);
  1504.   emit_i8(as, LJ_GC_BLACK);
  1505.   emit_rmro(as, XO_GROUP3b, XOg_TEST, obj,
  1506.             (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv));
  1507. }

  1508. /* -- FP/int arithmetic and logic operations ------------------------------ */

  1509. /* Load reference onto x87 stack. Force a spill to memory if needed. */
  1510. static void asm_x87load(ASMState *as, IRRef ref)
  1511. {
  1512.   IRIns *ir = IR(ref);
  1513.   if (ir->o == IR_KNUM) {
  1514.     cTValue *tv = ir_knum(ir);
  1515.     if (tvispzero(tv))  /* Use fldz only for +0. */
  1516.       emit_x87op(as, XI_FLDZ);
  1517.     else if (tvispone(tv))
  1518.       emit_x87op(as, XI_FLD1);
  1519.     else
  1520.       emit_rma(as, XO_FLDq, XOg_FLDq, tv);
  1521.   } else if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT && !ra_used(ir) &&
  1522.              !irref_isk(ir->op1) && mayfuse(as, ir->op1)) {
  1523.     IRIns *iri = IR(ir->op1);
  1524.     emit_rmro(as, XO_FILDd, XOg_FILDd, RID_ESP, ra_spill(as, iri));
  1525.   } else {
  1526.     emit_mrm(as, XO_FLDq, XOg_FLDq, asm_fuseload(as, ref, RSET_EMPTY));
  1527.   }
  1528. }

  1529. static void asm_fpmath(ASMState *as, IRIns *ir)
  1530. {
  1531.   IRFPMathOp fpm = (IRFPMathOp)ir->op2;
  1532.   if (fpm == IRFPM_SQRT) {
  1533.     Reg dest = ra_dest(as, ir, RSET_FPR);
  1534.     Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
  1535.     emit_mrm(as, XO_SQRTSD, dest, left);
  1536.   } else if (fpm <= IRFPM_TRUNC) {
  1537.     if (as->flags & JIT_F_SSE4_1) {  /* SSE4.1 has a rounding instruction. */
  1538.       Reg dest = ra_dest(as, ir, RSET_FPR);
  1539.       Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
  1540.       /* ROUNDSD has a 4-byte opcode which doesn't fit in x86Op.
  1541.       ** Let's pretend it's a 3-byte opcode, and compensate afterwards.
  1542.       ** This is atrocious, but the alternatives are much worse.
  1543.       */
  1544.       /* Round down/up/trunc == 1001/1010/1011. */
  1545.       emit_i8(as, 0x09 + fpm);
  1546.       emit_mrm(as, XO_ROUNDSD, dest, left);
  1547.       if (LJ_64 && as->mcp[1] != (MCode)(XO_ROUNDSD >> 16)) {
  1548.         as->mcp[0] = as->mcp[1]; as->mcp[1] = 0x0f/* Swap 0F and REX. */
  1549.       }
  1550.       *--as->mcp = 0x66/* 1st byte of ROUNDSD opcode. */
  1551.     } else/* Call helper functions for SSE2 variant. */
  1552.       /* The modified regs must match with the *.dasc implementation. */
  1553.       RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
  1554.       if (ra_hasreg(ir->r))
  1555.         rset_clear(drop, ir->r);  /* Dest reg handled below. */
  1556.       ra_evictset(as, drop);
  1557.       ra_destreg(as, ir, RID_XMM0);
  1558.       emit_call(as, fpm == IRFPM_FLOOR ? lj_vm_floor_sse :
  1559.                     fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse);
  1560.       ra_left(as, RID_XMM0, ir->op1);
  1561.     }
  1562.   } else if (fpm == IRFPM_EXP2 && asm_fpjoin_pow(as, ir)) {
  1563.     /* Rejoined to pow(). */
  1564.   } else {
  1565.     asm_callid(as, ir, IRCALL_lj_vm_floor + fpm);
  1566.   }
  1567. }

  1568. #define asm_atan2(as, ir)        asm_callid(as, ir, IRCALL_atan2)

  1569. static void asm_ldexp(ASMState *as, IRIns *ir)
  1570. {
  1571.   int32_t ofs = sps_scale(ir->s);  /* Use spill slot or temp slots. */
  1572.   Reg dest = ir->r;
  1573.   if (ra_hasreg(dest)) {
  1574.     ra_free(as, dest);
  1575.     ra_modified(as, dest);
  1576.     emit_rmro(as, XO_MOVSD, dest, RID_ESP, ofs);
  1577.   }
  1578.   emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs);
  1579.   emit_x87op(as, XI_FPOP1);
  1580.   emit_x87op(as, XI_FSCALE);
  1581.   asm_x87load(as, ir->op1);
  1582.   asm_x87load(as, ir->op2);
  1583. }

  1584. static void asm_fppowi(ASMState *as, IRIns *ir)
  1585. {
  1586.   /* The modified regs must match with the *.dasc implementation. */
  1587.   RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
  1588.   if (ra_hasreg(ir->r))
  1589.     rset_clear(drop, ir->r);  /* Dest reg handled below. */
  1590.   ra_evictset(as, drop);
  1591.   ra_destreg(as, ir, RID_XMM0);
  1592.   emit_call(as, lj_vm_powi_sse);
  1593.   ra_left(as, RID_XMM0, ir->op1);
  1594.   ra_left(as, RID_EAX, ir->op2);
  1595. }

  1596. static void asm_pow(ASMState *as, IRIns *ir)
  1597. {
  1598. #if LJ_64 && LJ_HASFFI
  1599.   if (!irt_isnum(ir->t))
  1600.     asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
  1601.                                           IRCALL_lj_carith_powu64);
  1602.   else
  1603. #endif
  1604.     asm_fppowi(as, ir);
  1605. }

  1606. static int asm_swapops(ASMState *as, IRIns *ir)
  1607. {
  1608.   IRIns *irl = IR(ir->op1);
  1609.   IRIns *irr = IR(ir->op2);
  1610.   lua_assert(ra_noreg(irr->r));
  1611.   if (!irm_iscomm(lj_ir_mode[ir->o]))
  1612.     return 0/* Can't swap non-commutative operations. */
  1613.   if (irref_isk(ir->op2))
  1614.     return 0/* Don't swap constants to the left. */
  1615.   if (ra_hasreg(irl->r))
  1616.     return 1/* Swap if left already has a register. */
  1617.   if (ra_samehint(ir->r, irr->r))
  1618.     return 1/* Swap if dest and right have matching hints. */
  1619.   if (as->curins > as->loopref) {  /* In variant part? */
  1620.     if (ir->op2 < as->loopref && !irt_isphi(irr->t))
  1621.       return 0/* Keep invariants on the right. */
  1622.     if (ir->op1 < as->loopref && !irt_isphi(irl->t))
  1623.       return 1/* Swap invariants to the right. */
  1624.   }
  1625.   if (opisfusableload(irl->o))
  1626.     return 1/* Swap fusable loads to the right. */
  1627.   return 0/* Otherwise don't swap. */
  1628. }

  1629. static void asm_fparith(ASMState *as, IRIns *ir, x86Op xo)
  1630. {
  1631.   IRRef lref = ir->op1;
  1632.   IRRef rref = ir->op2;
  1633.   RegSet allow = RSET_FPR;
  1634.   Reg dest;
  1635.   Reg right = IR(rref)->r;
  1636.   if (ra_hasreg(right)) {
  1637.     rset_clear(allow, right);
  1638.     ra_noweak(as, right);
  1639.   }
  1640.   dest = ra_dest(as, ir, allow);
  1641.   if (lref == rref) {
  1642.     right = dest;
  1643.   } else if (ra_noreg(right)) {
  1644.     if (asm_swapops(as, ir)) {
  1645.       IRRef tmp = lref; lref = rref; rref = tmp;
  1646.     }
  1647.     right = asm_fuseload(as, rref, rset_clear(allow, dest));
  1648.   }
  1649.   emit_mrm(as, xo, dest, right);
  1650.   ra_left(as, dest, lref);
  1651. }

  1652. static void asm_intarith(ASMState *as, IRIns *ir, x86Arith xa)
  1653. {
  1654.   IRRef lref = ir->op1;
  1655.   IRRef rref = ir->op2;
  1656.   RegSet allow = RSET_GPR;
  1657.   Reg dest, right;
  1658.   int32_t k = 0;
  1659.   if (as->flagmcp == as->mcp) {  /* Drop test r,r instruction. */
  1660.     MCode *p = as->mcp + ((LJ_64 && *as->mcp < XI_TESTb) ? 3 : 2);
  1661.     if ((p[1] & 15) < 14) {
  1662.       if ((p[1] & 15) >= 12) p[1] -= 4/* L <->S, NL <-> NS */
  1663.       as->flagmcp = NULL;
  1664.       as->mcp = p;
  1665.     }  /* else: cannot transform LE/NLE to cc without use of OF. */
  1666.   }
  1667.   right = IR(rref)->r;
  1668.   if (ra_hasreg(right)) {
  1669.     rset_clear(allow, right);
  1670.     ra_noweak(as, right);
  1671.   }
  1672.   dest = ra_dest(as, ir, allow);
  1673.   if (lref == rref) {
  1674.     right = dest;
  1675.   } else if (ra_noreg(right) && !asm_isk32(as, rref, &k)) {
  1676.     if (asm_swapops(as, ir)) {
  1677.       IRRef tmp = lref; lref = rref; rref = tmp;
  1678.     }
  1679.     right = asm_fuseloadm(as, rref, rset_clear(allow, dest), irt_is64(ir->t));
  1680.   }
  1681.   if (irt_isguard(ir->t))  /* For IR_ADDOV etc. */
  1682.     asm_guardcc(as, CC_O);
  1683.   if (xa != XOg_X_IMUL) {
  1684.     if (ra_hasreg(right))
  1685.       emit_mrm(as, XO_ARITH(xa), REX_64IR(ir, dest), right);
  1686.     else
  1687.       emit_gri(as, XG_ARITHi(xa), REX_64IR(ir, dest), k);
  1688.   } else if (ra_hasreg(right)) {  /* IMUL r, mrm. */
  1689.     emit_mrm(as, XO_IMUL, REX_64IR(ir, dest), right);
  1690.   } else/* IMUL r, r, k. */
  1691.     /* NYI: use lea/shl/add/sub (FOLD only does 2^k) depending on CPU. */
  1692.     Reg left = asm_fuseloadm(as, lref, RSET_GPR, irt_is64(ir->t));
  1693.     x86Op xo;
  1694.     if (checki8(k)) { emit_i8(as, k); xo = XO_IMULi8;
  1695.     } else { emit_i32(as, k); xo = XO_IMULi; }
  1696.     emit_mrm(as, xo, REX_64IR(ir, dest), left);
  1697.     return;
  1698.   }
  1699.   ra_left(as, dest, lref);
  1700. }

  1701. /* LEA is really a 4-operand ADD with an independent destination register,
  1702. ** up to two source registers and an immediate. One register can be scaled
  1703. ** by 1, 2, 4 or 8. This can be used to avoid moves or to fuse several
  1704. ** instructions.
  1705. **
  1706. ** Currently only a few common cases are supported:
  1707. ** - 3-operand ADD:    y = a+b; y = a+k   with a and b already allocated
  1708. ** - Left ADD fusion:  y = (a+b)+k; y = (a+k)+b
  1709. ** - Right ADD fusion: y = a+(b+k)
  1710. ** The ommited variants have already been reduced by FOLD.
  1711. **
  1712. ** There are more fusion opportunities, like gathering shifts or joining
  1713. ** common references. But these are probably not worth the trouble, since
  1714. ** array indexing is not decomposed and already makes use of all fields
  1715. ** of the ModRM operand.
  1716. */
  1717. static int asm_lea(ASMState *as, IRIns *ir)
  1718. {
  1719.   IRIns *irl = IR(ir->op1);
  1720.   IRIns *irr = IR(ir->op2);
  1721.   RegSet allow = RSET_GPR;
  1722.   Reg dest;
  1723.   as->mrm.base = as->mrm.idx = RID_NONE;
  1724.   as->mrm.scale = XM_SCALE1;
  1725.   as->mrm.ofs = 0;
  1726.   if (ra_hasreg(irl->r)) {
  1727.     rset_clear(allow, irl->r);
  1728.     ra_noweak(as, irl->r);
  1729.     as->mrm.base = irl->r;
  1730.     if (irref_isk(ir->op2) || ra_hasreg(irr->r)) {
  1731.       /* The PHI renaming logic does a better job in some cases. */
  1732.       if (ra_hasreg(ir->r) &&
  1733.           ((irt_isphi(irl->t) && as->phireg[ir->r] == ir->op1) ||
  1734.            (irt_isphi(irr->t) && as->phireg[ir->r] == ir->op2)))
  1735.         return 0;
  1736.       if (irref_isk(ir->op2)) {
  1737.         as->mrm.ofs = irr->i;
  1738.       } else {
  1739.         rset_clear(allow, irr->r);
  1740.         ra_noweak(as, irr->r);
  1741.         as->mrm.idx = irr->r;
  1742.       }
  1743.     } else if (irr->o == IR_ADD && mayfuse(as, ir->op2) &&
  1744.                irref_isk(irr->op2)) {
  1745.       Reg idx = ra_alloc1(as, irr->op1, allow);
  1746.       rset_clear(allow, idx);
  1747.       as->mrm.idx = (uint8_t)idx;
  1748.       as->mrm.ofs = IR(irr->op2)->i;
  1749.     } else {
  1750.       return 0;
  1751.     }
  1752.   } else if (ir->op1 != ir->op2 && irl->o == IR_ADD && mayfuse(as, ir->op1) &&
  1753.              (irref_isk(ir->op2) || irref_isk(irl->op2))) {
  1754.     Reg idx, base = ra_alloc1(as, irl->op1, allow);
  1755.     rset_clear(allow, base);
  1756.     as->mrm.base = (uint8_t)base;
  1757.     if (irref_isk(ir->op2)) {
  1758.       as->mrm.ofs = irr->i;
  1759.       idx = ra_alloc1(as, irl->op2, allow);
  1760.     } else {
  1761.       as->mrm.ofs = IR(irl->op2)->i;
  1762.       idx = ra_alloc1(as, ir->op2, allow);
  1763.     }
  1764.     rset_clear(allow, idx);
  1765.     as->mrm.idx = (uint8_t)idx;
  1766.   } else {
  1767.     return 0;
  1768.   }
  1769.   dest = ra_dest(as, ir, allow);
  1770.   emit_mrm(as, XO_LEA, dest, RID_MRM);
  1771.   return 1/* Success. */
  1772. }

  1773. static void asm_add(ASMState *as, IRIns *ir)
  1774. {
  1775.   if (irt_isnum(ir->t))
  1776.     asm_fparith(as, ir, XO_ADDSD);
  1777.   else if ((as->flags & JIT_F_LEA_AGU) || as->flagmcp == as->mcp ||
  1778.            irt_is64(ir->t) || !asm_lea(as, ir))
  1779.     asm_intarith(as, ir, XOg_ADD);
  1780. }

  1781. static void asm_sub(ASMState *as, IRIns *ir)
  1782. {
  1783.   if (irt_isnum(ir->t))
  1784.     asm_fparith(as, ir, XO_SUBSD);
  1785.   else  /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */
  1786.     asm_intarith(as, ir, XOg_SUB);
  1787. }

  1788. static void asm_mul(ASMState *as, IRIns *ir)
  1789. {
  1790.   if (irt_isnum(ir->t))
  1791.     asm_fparith(as, ir, XO_MULSD);
  1792.   else
  1793.     asm_intarith(as, ir, XOg_X_IMUL);
  1794. }

  1795. static void asm_div(ASMState *as, IRIns *ir)
  1796. {
  1797. #if LJ_64 && LJ_HASFFI
  1798.   if (!irt_isnum(ir->t))
  1799.     asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
  1800.                                           IRCALL_lj_carith_divu64);
  1801.   else
  1802. #endif
  1803.     asm_fparith(as, ir, XO_DIVSD);
  1804. }

  1805. static void asm_mod(ASMState *as, IRIns *ir)
  1806. {
  1807. #if LJ_64 && LJ_HASFFI
  1808.   if (!irt_isint(ir->t))
  1809.     asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
  1810.                                           IRCALL_lj_carith_modu64);
  1811.   else
  1812. #endif
  1813.     asm_callid(as, ir, IRCALL_lj_vm_modi);
  1814. }

  1815. static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg)
  1816. {
  1817.   Reg dest = ra_dest(as, ir, RSET_GPR);
  1818.   emit_rr(as, XO_GROUP3, REX_64IR(ir, xg), dest);
  1819.   ra_left(as, dest, ir->op1);
  1820. }

  1821. static void asm_neg(ASMState *as, IRIns *ir)
  1822. {
  1823.   if (irt_isnum(ir->t))
  1824.     asm_fparith(as, ir, XO_XORPS);
  1825.   else
  1826.     asm_neg_not(as, ir, XOg_NEG);
  1827. }

  1828. #define asm_abs(as, ir)                asm_fparith(as, ir, XO_ANDPS)

  1829. static void asm_intmin_max(ASMState *as, IRIns *ir, int cc)
  1830. {
  1831.   Reg right, dest = ra_dest(as, ir, RSET_GPR);
  1832.   IRRef lref = ir->op1, rref = ir->op2;
  1833.   if (irref_isk(rref)) { lref = rref; rref = ir->op1; }
  1834.   right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, dest));
  1835.   emit_rr(as, XO_CMOV + (cc<<24), REX_64IR(ir, dest), right);
  1836.   emit_rr(as, XO_CMP, REX_64IR(ir, dest), right);
  1837.   ra_left(as, dest, lref);
  1838. }

  1839. static void asm_min(ASMState *as, IRIns *ir)
  1840. {
  1841.   if (irt_isnum(ir->t))
  1842.     asm_fparith(as, ir, XO_MINSD);
  1843.   else
  1844.     asm_intmin_max(as, ir, CC_G);
  1845. }

  1846. static void asm_max(ASMState *as, IRIns *ir)
  1847. {
  1848.   if (irt_isnum(ir->t))
  1849.     asm_fparith(as, ir, XO_MAXSD);
  1850.   else
  1851.     asm_intmin_max(as, ir, CC_L);
  1852. }

  1853. /* Note: don't use LEA for overflow-checking arithmetic! */
  1854. #define asm_addov(as, ir)        asm_intarith(as, ir, XOg_ADD)
  1855. #define asm_subov(as, ir)        asm_intarith(as, ir, XOg_SUB)
  1856. #define asm_mulov(as, ir)        asm_intarith(as, ir, XOg_X_IMUL)

  1857. #define asm_bnot(as, ir)        asm_neg_not(as, ir, XOg_NOT)

  1858. static void asm_bswap(ASMState *as, IRIns *ir)
  1859. {
  1860.   Reg dest = ra_dest(as, ir, RSET_GPR);
  1861.   as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24),
  1862.                     REX_64IR(ir, 0), dest, 0, as->mcp, 1);
  1863.   ra_left(as, dest, ir->op1);
  1864. }

  1865. #define asm_band(as, ir)        asm_intarith(as, ir, XOg_AND)
  1866. #define asm_bor(as, ir)                asm_intarith(as, ir, XOg_OR)
  1867. #define asm_bxor(as, ir)        asm_intarith(as, ir, XOg_XOR)

  1868. static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs)
  1869. {
  1870.   IRRef rref = ir->op2;
  1871.   IRIns *irr = IR(rref);
  1872.   Reg dest;
  1873.   if (irref_isk(rref)) {  /* Constant shifts. */
  1874.     int shift;
  1875.     dest = ra_dest(as, ir, RSET_GPR);
  1876.     shift = irr->i & (irt_is64(ir->t) ? 63 : 31);
  1877.     switch (shift) {
  1878.     case 0: break;
  1879.     case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break;
  1880.     default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break;
  1881.     }
  1882.   } else/* Variable shifts implicitly use register cl (i.e. ecx). */
  1883.     Reg right;
  1884.     dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX));
  1885.     if (dest == RID_ECX) {
  1886.       dest = ra_scratch(as, rset_exclude(RSET_GPR, RID_ECX));
  1887.       emit_rr(as, XO_MOV, RID_ECX, dest);
  1888.     }
  1889.     right = irr->r;
  1890.     if (ra_noreg(right))
  1891.       right = ra_allocref(as, rref, RID2RSET(RID_ECX));
  1892.     else if (right != RID_ECX)
  1893.       ra_scratch(as, RID2RSET(RID_ECX));
  1894.     emit_rr(as, XO_SHIFTcl, REX_64IR(ir, xs), dest);
  1895.     ra_noweak(as, right);
  1896.     if (right != RID_ECX)
  1897.       emit_rr(as, XO_MOV, RID_ECX, right);
  1898.   }
  1899.   ra_left(as, dest, ir->op1);
  1900.   /*
  1901.   ** Note: avoid using the flags resulting from a shift or rotate!
  1902.   ** All of them cause a partial flag stall, except for r,1 shifts
  1903.   ** (but not rotates). And a shift count of 0 leaves the flags unmodified.
  1904.   */
  1905. }

  1906. #define asm_bshl(as, ir)        asm_bitshift(as, ir, XOg_SHL)
  1907. #define asm_bshr(as, ir)        asm_bitshift(as, ir, XOg_SHR)
  1908. #define asm_bsar(as, ir)        asm_bitshift(as, ir, XOg_SAR)
  1909. #define asm_brol(as, ir)        asm_bitshift(as, ir, XOg_ROL)
  1910. #define asm_bror(as, ir)        asm_bitshift(as, ir, XOg_ROR)

  1911. /* -- Comparisons --------------------------------------------------------- */

  1912. /* Virtual flags for unordered FP comparisons. */
  1913. #define VCC_U        0x1000                /* Unordered. */
  1914. #define VCC_P        0x2000                /* Needs extra CC_P branch. */
  1915. #define VCC_S        0x4000                /* Swap avoids CC_P branch. */
  1916. #define VCC_PS        (VCC_P|VCC_S)

  1917. /* Map of comparisons to flags. ORDER IR. */
  1918. #define COMPFLAGS(ci, cin, cu, cf)        ((ci)+((cu)<<4)+((cin)<<8)+(cf))
  1919. static const uint16_t asm_compmap[IR_ABC+1] = {
  1920.   /*                 signed non-eq unsigned flags */
  1921.   /* LT  */ COMPFLAGS(CC_GE, CC_G,  CC_AE, VCC_PS),
  1922.   /* GE  */ COMPFLAGS(CC_L,  CC_L,  CC_B,  0),
  1923.   /* LE  */ COMPFLAGS(CC_G,  CC_G,  CC_A,  VCC_PS),
  1924.   /* GT  */ COMPFLAGS(CC_LE, CC_L,  CC_BE, 0),
  1925.   /* ULT */ COMPFLAGS(CC_AE, CC_A,  CC_AE, VCC_U),
  1926.   /* UGE */ COMPFLAGS(CC_B,  CC_B,  CC_B,  VCC_U|VCC_PS),
  1927.   /* ULE */ COMPFLAGS(CC_A,  CC_A,  CC_A,  VCC_U),
  1928.   /* UGT */ COMPFLAGS(CC_BE, CC_B,  CC_BE, VCC_U|VCC_PS),
  1929.   /* EQ  */ COMPFLAGS(CC_NE, CC_NE, CC_NE, VCC_P),
  1930.   /* NE  */ COMPFLAGS(CC_E,  CC_E,  CC_E,  VCC_U|VCC_P),
  1931.   /* ABC */ COMPFLAGS(CC_BE, CC_B,  CC_BE, VCC_U|VCC_PS/* Same as UGT. */
  1932. };

  1933. /* FP and integer comparisons. */
  1934. static void asm_comp(ASMState *as, IRIns *ir)
  1935. {
  1936.   uint32_t cc = asm_compmap[ir->o];
  1937.   if (irt_isnum(ir->t)) {
  1938.     IRRef lref = ir->op1;
  1939.     IRRef rref = ir->op2;
  1940.     Reg left, right;
  1941.     MCLabel l_around;
  1942.     /*
  1943.     ** An extra CC_P branch is required to preserve ordered/unordered
  1944.     ** semantics for FP comparisons. This can be avoided by swapping
  1945.     ** the operands and inverting the condition (except for EQ and UNE).
  1946.     ** So always try to swap if possible.
  1947.     **
  1948.     ** Another option would be to swap operands to achieve better memory
  1949.     ** operand fusion. But it's unlikely that this outweighs the cost
  1950.     ** of the extra branches.
  1951.     */
  1952.     if (cc & VCC_S) {  /* Swap? */
  1953.       IRRef tmp = lref; lref = rref; rref = tmp;
  1954.       cc ^= (VCC_PS|(5<<4));  /* A <-> B, AE <-> BE, PS <-> none */
  1955.     }
  1956.     left = ra_alloc1(as, lref, RSET_FPR);
  1957.     right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left));
  1958.     l_around = emit_label(as);
  1959.     asm_guardcc(as, cc >> 4);
  1960.     if (cc & VCC_P) {  /* Extra CC_P branch required? */
  1961.       if (!(cc & VCC_U)) {
  1962.         asm_guardcc(as, CC_P);  /* Branch to exit for ordered comparisons. */
  1963.       } else if (l_around != as->invmcp) {
  1964.         emit_sjcc(as, CC_P, l_around);  /* Branch around for unordered. */
  1965.       } else {
  1966.         /* Patched to mcloop by asm_loop_fixup. */
  1967.         as->loopinv = 2;
  1968.         if (as->realign)
  1969.           emit_sjcc(as, CC_P, as->mcp);
  1970.         else
  1971.           emit_jcc(as, CC_P, as->mcp);
  1972.       }
  1973.     }
  1974.     emit_mrm(as, XO_UCOMISD, left, right);
  1975.   } else {
  1976.     IRRef lref = ir->op1, rref = ir->op2;
  1977.     IROp leftop = (IROp)(IR(lref)->o);
  1978.     Reg r64 = REX_64IR(ir, 0);
  1979.     int32_t imm = 0;
  1980.     lua_assert(irt_is64(ir->t) || irt_isint(ir->t) ||
  1981.                irt_isu32(ir->t) || irt_isaddr(ir->t) || irt_isu8(ir->t));
  1982.     /* Swap constants (only for ABC) and fusable loads to the right. */
  1983.     if (irref_isk(lref) || (!irref_isk(rref) && opisfusableload(leftop))) {
  1984.       if ((cc & 0xc) == 0xc) cc ^= 0x53/* L <-> G, LE <-> GE */
  1985.       else if ((cc & 0xa) == 0x2) cc ^= 0x55/* A <-> B, AE <-> BE */
  1986.       lref = ir->op2; rref = ir->op1;
  1987.     }
  1988.     if (asm_isk32(as, rref, &imm)) {
  1989.       IRIns *irl = IR(lref);
  1990.       /* Check wether we can use test ins. Not for unsigned, since CF=0. */
  1991.       int usetest = (imm == 0 && (cc & 0xa) != 0x2);
  1992.       if (usetest && irl->o == IR_BAND && irl+1 == ir && !ra_used(irl)) {
  1993.         /* Combine comp(BAND(ref, r/imm), 0) into test mrm, r/imm. */
  1994.         Reg right, left = RID_NONE;
  1995.         RegSet allow = RSET_GPR;
  1996.         if (!asm_isk32(as, irl->op2, &imm)) {
  1997.           left = ra_alloc1(as, irl->op2, allow);
  1998.           rset_clear(allow, left);
  1999.         } else/* Try to Fuse IRT_I8/IRT_U8 loads, too. See below. */
  2000.           IRIns *irll = IR(irl->op1);
  2001.           if (opisfusableload((IROp)irll->o) &&
  2002.               (irt_isi8(irll->t) || irt_isu8(irll->t))) {
  2003.             IRType1 origt = irll->t;  /* Temporarily flip types. */
  2004.             irll->t.irt = (irll->t.irt & ~IRT_TYPE) | IRT_INT;
  2005.             as->curins--;  /* Skip to BAND to avoid failing in noconflict(). */
  2006.             right = asm_fuseload(as, irl->op1, RSET_GPR);
  2007.             as->curins++;
  2008.             irll->t = origt;
  2009.             if (right != RID_MRM) goto test_nofuse;
  2010.             /* Fusion succeeded, emit test byte mrm, imm8. */
  2011.             asm_guardcc(as, cc);
  2012.             emit_i8(as, (imm & 0xff));
  2013.             emit_mrm(as, XO_GROUP3b, XOg_TEST, RID_MRM);
  2014.             return;
  2015.           }
  2016.         }
  2017.         as->curins--;  /* Skip to BAND to avoid failing in noconflict(). */
  2018.         right = asm_fuseloadm(as, irl->op1, allow, r64);
  2019.         as->curins++;  /* Undo the above. */
  2020.       test_nofuse:
  2021.         asm_guardcc(as, cc);
  2022.         if (ra_noreg(left)) {
  2023.           emit_i32(as, imm);
  2024.           emit_mrm(as, XO_GROUP3, r64 + XOg_TEST, right);
  2025.         } else {
  2026.           emit_mrm(as, XO_TEST, r64 + left, right);
  2027.         }
  2028.       } else {
  2029.         Reg left;
  2030.         if (opisfusableload((IROp)irl->o) &&
  2031.             ((irt_isu8(irl->t) && checku8(imm)) ||
  2032.              ((irt_isi8(irl->t) || irt_isi16(irl->t)) && checki8(imm)) ||
  2033.              (irt_isu16(irl->t) && checku16(imm) && checki8((int16_t)imm)))) {
  2034.           /* Only the IRT_INT case is fused by asm_fuseload.
  2035.           ** The IRT_I8/IRT_U8 loads and some IRT_I16/IRT_U16 loads
  2036.           ** are handled here.
  2037.           ** Note that cmp word [mem], imm16 should not be generated,
  2038.           ** since it has a length-changing prefix. Compares of a word
  2039.           ** against a sign-extended imm8 are ok, however.
  2040.           */
  2041.           IRType1 origt = irl->t;  /* Temporarily flip types. */
  2042.           irl->t.irt = (irl->t.irt & ~IRT_TYPE) | IRT_INT;
  2043.           left = asm_fuseload(as, lref, RSET_GPR);
  2044.           irl->t = origt;
  2045.           if (left == RID_MRM) {  /* Fusion succeeded? */
  2046.             if (irt_isu8(irl->t) || irt_isu16(irl->t))
  2047.               cc >>= 4/* Need unsigned compare. */
  2048.             asm_guardcc(as, cc);
  2049.             emit_i8(as, imm);
  2050.             emit_mrm(as, (irt_isi8(origt) || irt_isu8(origt)) ?
  2051.                          XO_ARITHib : XO_ARITHiw8, r64 + XOg_CMP, RID_MRM);
  2052.             return;
  2053.           }  /* Otherwise handle register case as usual. */
  2054.         } else {
  2055.           left = asm_fuseloadm(as, lref,
  2056.                                irt_isu8(ir->t) ? RSET_GPR8 : RSET_GPR, r64);
  2057.         }
  2058.         asm_guardcc(as, cc);
  2059.         if (usetest && left != RID_MRM) {
  2060.           /* Use test r,r instead of cmp r,0. */
  2061.           x86Op xo = XO_TEST;
  2062.           if (irt_isu8(ir->t)) {
  2063.             lua_assert(ir->o == IR_EQ || ir->o == IR_NE);
  2064.             xo = XO_TESTb;
  2065.             if (!rset_test(RSET_RANGE(RID_EAX, RID_EBX+1), left)) {
  2066.               if (LJ_64) {
  2067.                 left |= FORCE_REX;
  2068.               } else {
  2069.                 emit_i32(as, 0xff);
  2070.                 emit_mrm(as, XO_GROUP3, XOg_TEST, left);
  2071.                 return;
  2072.               }
  2073.             }
  2074.           }
  2075.           emit_rr(as, xo, r64 + left, left);
  2076.           if (irl+1 == ir)  /* Referencing previous ins? */
  2077.             as->flagmcp = as->mcp;  /* Set flag to drop test r,r if possible. */
  2078.         } else {
  2079.           emit_gmrmi(as, XG_ARITHi(XOg_CMP), r64 + left, imm);
  2080.         }
  2081.       }
  2082.     } else {
  2083.       Reg left = ra_alloc1(as, lref, RSET_GPR);
  2084.       Reg right = asm_fuseloadm(as, rref, rset_exclude(RSET_GPR, left), r64);
  2085.       asm_guardcc(as, cc);
  2086.       emit_mrm(as, XO_CMP, r64 + left, right);
  2087.     }
  2088.   }
  2089. }

  2090. #define asm_equal(as, ir)        asm_comp(as, ir)

  2091. #if LJ_32 && LJ_HASFFI
  2092. /* 64 bit integer comparisons in 32 bit mode. */
  2093. static void asm_comp_int64(ASMState *as, IRIns *ir)
  2094. {
  2095.   uint32_t cc = asm_compmap[(ir-1)->o];
  2096.   RegSet allow = RSET_GPR;
  2097.   Reg lefthi = RID_NONE, leftlo = RID_NONE;
  2098.   Reg righthi = RID_NONE, rightlo = RID_NONE;
  2099.   MCLabel l_around;
  2100.   x86ModRM mrm;

  2101.   as->curins--;  /* Skip loword ins. Avoids failing in noconflict(), too. */

  2102.   /* Allocate/fuse hiword operands. */
  2103.   if (irref_isk(ir->op2)) {
  2104.     lefthi = asm_fuseload(as, ir->op1, allow);
  2105.   } else {
  2106.     lefthi = ra_alloc1(as, ir->op1, allow);
  2107.     rset_clear(allow, lefthi);
  2108.     righthi = asm_fuseload(as, ir->op2, allow);
  2109.     if (righthi == RID_MRM) {
  2110.       if (as->mrm.base != RID_NONE) rset_clear(allow, as->mrm.base);
  2111.       if (as->mrm.idx != RID_NONE) rset_clear(allow, as->mrm.idx);
  2112.     } else {
  2113.       rset_clear(allow, righthi);
  2114.     }
  2115.   }
  2116.   mrm = as->mrm;  /* Save state for hiword instruction. */

  2117.   /* Allocate/fuse loword operands. */
  2118.   if (irref_isk((ir-1)->op2)) {
  2119.     leftlo = asm_fuseload(as, (ir-1)->op1, allow);
  2120.   } else {
  2121.     leftlo = ra_alloc1(as, (ir-1)->op1, allow);
  2122.     rset_clear(allow, leftlo);
  2123.     rightlo = asm_fuseload(as, (ir-1)->op2, allow);
  2124.   }

  2125.   /* All register allocations must be performed _before_ this point. */
  2126.   l_around = emit_label(as);
  2127.   as->invmcp = as->flagmcp = NULL/* Cannot use these optimizations. */

  2128.   /* Loword comparison and branch. */
  2129.   asm_guardcc(as, cc >> 4);  /* Always use unsigned compare for loword. */
  2130.   if (ra_noreg(rightlo)) {
  2131.     int32_t imm = IR((ir-1)->op2)->i;
  2132.     if (imm == 0 && ((cc >> 4) & 0xa) != 0x2 && leftlo != RID_MRM)
  2133.       emit_rr(as, XO_TEST, leftlo, leftlo);
  2134.     else
  2135.       emit_gmrmi(as, XG_ARITHi(XOg_CMP), leftlo, imm);
  2136.   } else {
  2137.     emit_mrm(as, XO_CMP, leftlo, rightlo);
  2138.   }

  2139.   /* Hiword comparison and branches. */
  2140.   if ((cc & 15) != CC_NE)
  2141.     emit_sjcc(as, CC_NE, l_around);  /* Hiword unequal: skip loword compare. */
  2142.   if ((cc & 15) != CC_E)
  2143.     asm_guardcc(as, cc >> 8);  /* Hiword compare without equality check. */
  2144.   as->mrm = mrm;  /* Restore state. */
  2145.   if (ra_noreg(righthi)) {
  2146.     int32_t imm = IR(ir->op2)->i;
  2147.     if (imm == 0 && (cc & 0xa) != 0x2 && lefthi != RID_MRM)
  2148.       emit_rr(as, XO_TEST, lefthi, lefthi);
  2149.     else
  2150.       emit_gmrmi(as, XG_ARITHi(XOg_CMP), lefthi, imm);
  2151.   } else {
  2152.     emit_mrm(as, XO_CMP, lefthi, righthi);
  2153.   }
  2154. }
  2155. #endif

  2156. /* -- Support for 64 bit ops in 32 bit mode ------------------------------- */

  2157. /* Hiword op of a split 64 bit op. Previous op must be the loword op. */
  2158. static void asm_hiop(ASMState *as, IRIns *ir)
  2159. {
  2160. #if LJ_32 && LJ_HASFFI
  2161.   /* HIOP is marked as a store because it needs its own DCE logic. */
  2162.   int uselo = ra_used(ir-1), usehi = ra_used(ir);  /* Loword/hiword used? */
  2163.   if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1;
  2164.   if ((ir-1)->o == IR_CONV) {  /* Conversions to/from 64 bit. */
  2165.     as->curins--;  /* Always skip the CONV. */
  2166.     if (usehi || uselo)
  2167.       asm_conv64(as, ir);
  2168.     return;
  2169.   } else if ((ir-1)->o <= IR_NE) {  /* 64 bit integer comparisons. ORDER IR. */
  2170.     asm_comp_int64(as, ir);
  2171.     return;
  2172.   } else if ((ir-1)->o == IR_XSTORE) {
  2173.     if ((ir-1)->r != RID_SINK)
  2174.       asm_fxstore(as, ir);
  2175.     return;
  2176.   }
  2177.   if (!usehi) return/* Skip unused hiword op for all remaining ops. */
  2178.   switch ((ir-1)->o) {
  2179.   case IR_ADD:
  2180.     as->flagmcp = NULL;
  2181.     as->curins--;
  2182.     asm_intarith(as, ir, XOg_ADC);
  2183.     asm_intarith(as, ir-1, XOg_ADD);
  2184.     break;
  2185.   case IR_SUB:
  2186.     as->flagmcp = NULL;
  2187.     as->curins--;
  2188.     asm_intarith(as, ir, XOg_SBB);
  2189.     asm_intarith(as, ir-1, XOg_SUB);
  2190.     break;
  2191.   case IR_NEG: {
  2192.     Reg dest = ra_dest(as, ir, RSET_GPR);
  2193.     emit_rr(as, XO_GROUP3, XOg_NEG, dest);
  2194.     emit_i8(as, 0);
  2195.     emit_rr(as, XO_ARITHi8, XOg_ADC, dest);
  2196.     ra_left(as, dest, ir->op1);
  2197.     as->curins--;
  2198.     asm_neg_not(as, ir-1, XOg_NEG);
  2199.     break;
  2200.     }
  2201.   case IR_CALLN:
  2202.   case IR_CALLXS:
  2203.     if (!uselo)
  2204.       ra_allocref(as, ir->op1, RID2RSET(RID_RETLO));  /* Mark lo op as used. */
  2205.     break;
  2206.   case IR_CNEWI:
  2207.     /* Nothing to do here. Handled by CNEWI itself. */
  2208.     break;
  2209.   default: lua_assert(0); break;
  2210.   }
  2211. #else
  2212.   UNUSED(as); UNUSED(ir); lua_assert(0);  /* Unused on x64 or without FFI. */
  2213. #endif
  2214. }

  2215. /* -- Profiling ----------------------------------------------------------- */

  2216. static void asm_prof(ASMState *as, IRIns *ir)
  2217. {
  2218.   UNUSED(ir);
  2219.   asm_guardcc(as, CC_NE);
  2220.   emit_i8(as, HOOK_PROFILE);
  2221.   emit_rma(as, XO_GROUP3b, XOg_TEST, &J2G(as->J)->hookmask);
  2222. }

  2223. /* -- Stack handling ------------------------------------------------------ */

  2224. /* Check Lua stack size for overflow. Use exit handler as fallback. */
  2225. static void asm_stack_check(ASMState *as, BCReg topslot,
  2226.                             IRIns *irp, RegSet allow, ExitNo exitno)
  2227. {
  2228.   /* Try to get an unused temp. register, otherwise spill/restore eax. */
  2229.   Reg pbase = irp ? irp->r : RID_BASE;
  2230.   Reg r = allow ? rset_pickbot(allow) : RID_EAX;
  2231.   emit_jcc(as, CC_B, exitstub_addr(as->J, exitno));
  2232.   if (allow == RSET_EMPTY/* Restore temp. register. */
  2233.     emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0);
  2234.   else
  2235.     ra_modified(as, r);
  2236.   emit_gri(as, XG_ARITHi(XOg_CMP), r, (int32_t)(8*topslot));
  2237.   if (ra_hasreg(pbase) && pbase != r)
  2238.     emit_rr(as, XO_ARITH(XOg_SUB), r, pbase);
  2239.   else
  2240.     emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE,
  2241.               ptr2addr(&J2G(as->J)->jit_base));
  2242.   emit_rmro(as, XO_MOV, r, r, offsetof(lua_State, maxstack));
  2243.   emit_getgl(as, r, cur_L);
  2244.   if (allow == RSET_EMPTY/* Spill temp. register. */
  2245.     emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0);
  2246. }

  2247. /* Restore Lua stack from on-trace state. */
  2248. static void asm_stack_restore(ASMState *as, SnapShot *snap)
  2249. {
  2250.   SnapEntry *map = &as->T->snapmap[snap->mapofs];
  2251.   SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1];
  2252.   MSize n, nent = snap->nent;
  2253.   /* Store the value of all modified slots to the Lua stack. */
  2254.   for (n = 0; n < nent; n++) {
  2255.     SnapEntry sn = map[n];
  2256.     BCReg s = snap_slot(sn);
  2257.     int32_t ofs = 8*((int32_t)s-1);
  2258.     IRRef ref = snap_ref(sn);
  2259.     IRIns *ir = IR(ref);
  2260.     if ((sn & SNAP_NORESTORE))
  2261.       continue;
  2262.     if (irt_isnum(ir->t)) {
  2263.       Reg src = ra_alloc1(as, ref, RSET_FPR);
  2264.       emit_rmro(as, XO_MOVSDto, src, RID_BASE, ofs);
  2265.     } else {
  2266.       lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) ||
  2267.                  (LJ_DUALNUM && irt_isinteger(ir->t)));
  2268.       if (!irref_isk(ref)) {
  2269.         Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE));
  2270.         emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs);
  2271.       } else if (!irt_ispri(ir->t)) {
  2272.         emit_movmroi(as, RID_BASE, ofs, ir->i);
  2273.       }
  2274.       if ((sn & (SNAP_CONT|SNAP_FRAME))) {
  2275.         if (s != 0/* Do not overwrite link to previous frame. */
  2276.           emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--));
  2277.       } else {
  2278.         if (!(LJ_64 && irt_islightud(ir->t)))
  2279.           emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t));
  2280.       }
  2281.     }
  2282.     checkmclim(as);
  2283.   }
  2284.   lua_assert(map + nent == flinks);
  2285. }

  2286. /* -- GC handling --------------------------------------------------------- */

  2287. /* Check GC threshold and do one or more GC steps. */
  2288. static void asm_gc_check(ASMState *as)
  2289. {
  2290.   const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit];
  2291.   IRRef args[2];
  2292.   MCLabel l_end;
  2293.   Reg tmp;
  2294.   ra_evictset(as, RSET_SCRATCH);
  2295.   l_end = emit_label(as);
  2296.   /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */
  2297.   asm_guardcc(as, CC_NE);  /* Assumes asm_snap_prep() already done. */
  2298.   emit_rr(as, XO_TEST, RID_RET, RID_RET);
  2299.   args[0] = ASMREF_TMP1/* global_State *g */
  2300.   args[1] = ASMREF_TMP2/* MSize steps     */
  2301.   asm_gencall(as, ci, args);
  2302.   tmp = ra_releasetmp(as, ASMREF_TMP1);
  2303.   emit_loada(as, tmp, J2G(as->J));
  2304.   emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), as->gcsteps);
  2305.   /* Jump around GC step if GC total < GC threshold. */
  2306.   emit_sjcc(as, CC_B, l_end);
  2307.   emit_opgl(as, XO_ARITH(XOg_CMP), tmp, gc.threshold);
  2308.   emit_getgl(as, tmp, gc.total);
  2309.   as->gcsteps = 0;
  2310.   checkmclim(as);
  2311. }

  2312. /* -- Loop handling ------------------------------------------------------- */

  2313. /* Fixup the loop branch. */
  2314. static void asm_loop_fixup(ASMState *as)
  2315. {
  2316.   MCode *p = as->mctop;
  2317.   MCode *target = as->mcp;
  2318.   if (as->realign) {  /* Realigned loops use short jumps. */
  2319.     as->realign = NULL/* Stop another retry. */
  2320.     lua_assert(((intptr_t)target & 15) == 0);
  2321.     if (as->loopinv) {  /* Inverted loop branch? */
  2322.       p -= 5;
  2323.       p[0] = XI_JMP;
  2324.       lua_assert(target - p >= -128);
  2325.       p[-1] = (MCode)(target - p);  /* Patch sjcc. */
  2326.       if (as->loopinv == 2)
  2327.         p[-3] = (MCode)(target - p + 2);  /* Patch opt. short jp. */
  2328.     } else {
  2329.       lua_assert(target - p >= -128);
  2330.       p[-1] = (MCode)(int8_t)(target - p);  /* Patch short jmp. */
  2331.       p[-2] = XI_JMPs;
  2332.     }
  2333.   } else {
  2334.     MCode *newloop;
  2335.     p[-5] = XI_JMP;
  2336.     if (as->loopinv) {  /* Inverted loop branch? */
  2337.       /* asm_guardcc already inverted the jcc and patched the jmp. */
  2338.       p -= 5;
  2339.       newloop = target+4;
  2340.       *(int32_t *)(p-4) = (int32_t)(target - p);  /* Patch jcc. */
  2341.       if (as->loopinv == 2) {
  2342.         *(int32_t *)(p-10) = (int32_t)(target - p + 6);  /* Patch opt. jp. */
  2343.         newloop = target+8;
  2344.       }
  2345.     } else/* Otherwise just patch jmp. */
  2346.       *(int32_t *)(p-4) = (int32_t)(target - p);
  2347.       newloop = target+3;
  2348.     }
  2349.     /* Realign small loops and shorten the loop branch. */
  2350.     if (newloop >= p - 128) {
  2351.       as->realign = newloop;  /* Force a retry and remember alignment. */
  2352.       as->curins = as->stopins;  /* Abort asm_trace now. */
  2353.       as->T->nins = as->orignins;  /* Remove any added renames. */
  2354.     }
  2355.   }
  2356. }

  2357. /* -- Head of trace ------------------------------------------------------- */

  2358. /* Coalesce BASE register for a root trace. */
  2359. static void asm_head_root_base(ASMState *as)
  2360. {
  2361.   IRIns *ir = IR(REF_BASE);
  2362.   Reg r = ir->r;
  2363.   if (ra_hasreg(r)) {
  2364.     ra_free(as, r);
  2365.     if (rset_test(as->modset, r) || irt_ismarked(ir->t))
  2366.       ir->r = RID_INIT/* No inheritance for modified BASE register. */
  2367.     if (r != RID_BASE)
  2368.       emit_rr(as, XO_MOV, r, RID_BASE);
  2369.   }
  2370. }

  2371. /* Coalesce or reload BASE register for a side trace. */
  2372. static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow)
  2373. {
  2374.   IRIns *ir = IR(REF_BASE);
  2375.   Reg r = ir->r;
  2376.   if (ra_hasreg(r)) {
  2377.     ra_free(as, r);
  2378.     if (rset_test(as->modset, r) || irt_ismarked(ir->t))
  2379.       ir->r = RID_INIT/* No inheritance for modified BASE register. */
  2380.     if (irp->r == r) {
  2381.       rset_clear(allow, r);  /* Mark same BASE register as coalesced. */
  2382.     } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) {
  2383.       rset_clear(allow, irp->r);
  2384.       emit_rr(as, XO_MOV, r, irp->r);  /* Move from coalesced parent reg. */
  2385.     } else {
  2386.       emit_getgl(as, r, jit_base);  /* Otherwise reload BASE. */
  2387.     }
  2388.   }
  2389.   return allow;
  2390. }

  2391. /* -- Tail of trace ------------------------------------------------------- */

  2392. /* Fixup the tail code. */
  2393. static void asm_tail_fixup(ASMState *as, TraceNo lnk)
  2394. {
  2395.   /* Note: don't use as->mcp swap + emit_*: emit_op overwrites more bytes. */
  2396.   MCode *p = as->mctop;
  2397.   MCode *target, *q;
  2398.   int32_t spadj = as->T->spadjust;
  2399.   if (spadj == 0) {
  2400.     p -= ((as->flags & JIT_F_LEA_AGU) ? 7 : 6) + (LJ_64 ? 1 : 0);
  2401.   } else {
  2402.     MCode *p1;
  2403.     /* Patch stack adjustment. */
  2404.     if (checki8(spadj)) {
  2405.       p -= 3;
  2406.       p1 = p-6;
  2407.       *p1 = (MCode)spadj;
  2408.     } else {
  2409.       p1 = p-9;
  2410.       *(int32_t *)p1 = spadj;
  2411.     }
  2412.     if ((as->flags & JIT_F_LEA_AGU)) {
  2413. #if LJ_64
  2414.       p1[-4] = 0x48;
  2415. #endif
  2416.       p1[-3] = (MCode)XI_LEA;
  2417.       p1[-2] = MODRM(checki8(spadj) ? XM_OFS8 : XM_OFS32, RID_ESP, RID_ESP);
  2418.       p1[-1] = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
  2419.     } else {
  2420. #if LJ_64
  2421.       p1[-3] = 0x48;
  2422. #endif
  2423.       p1[-2] = (MCode)(checki8(spadj) ? XI_ARITHi8 : XI_ARITHi);
  2424.       p1[-1] = MODRM(XM_REG, XOg_ADD, RID_ESP);
  2425.     }
  2426.   }
  2427.   /* Patch exit branch. */
  2428.   target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)lj_vm_exit_interp;
  2429.   *(int32_t *)(p-4) = jmprel(p, target);
  2430.   p[-5] = XI_JMP;
  2431.   /* Drop unused mcode tail. Fill with NOPs to make the prefetcher happy. */
  2432.   for (q = as->mctop-1; q >= p; q--)
  2433.     *q = XI_NOP;
  2434.   as->mctop = p;
  2435. }

  2436. /* Prepare tail of code. */
  2437. static void asm_tail_prep(ASMState *as)
  2438. {
  2439.   MCode *p = as->mctop;
  2440.   /* Realign and leave room for backwards loop branch or exit branch. */
  2441.   if (as->realign) {
  2442.     int i = ((int)(intptr_t)as->realign) & 15;
  2443.     /* Fill unused mcode tail with NOPs to make the prefetcher happy. */
  2444.     while (i-- > 0)
  2445.       *--p = XI_NOP;
  2446.     as->mctop = p;
  2447.     p -= (as->loopinv ? 5 : 2);  /* Space for short/near jmp. */
  2448.   } else {
  2449.     p -= 5/* Space for exit branch (near jmp). */
  2450.   }
  2451.   if (as->loopref) {
  2452.     as->invmcp = as->mcp = p;
  2453.   } else {
  2454.     /* Leave room for ESP adjustment: add esp, imm or lea esp, [esp+imm] */
  2455.     as->mcp = p - (((as->flags & JIT_F_LEA_AGU) ? 7 : 6)  + (LJ_64 ? 1 : 0));
  2456.     as->invmcp = NULL;
  2457.   }
  2458. }

  2459. /* -- Trace setup --------------------------------------------------------- */

  2460. /* Ensure there are enough stack slots for call arguments. */
  2461. static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
  2462. {
  2463.   IRRef args[CCI_NARGS_MAX*2];
  2464.   int nslots;
  2465.   asm_collectargs(as, ir, ci, args);
  2466.   nslots = asm_count_call_slots(as, ci, args);
  2467.   if (nslots > as->evenspill)  /* Leave room for args in stack slots. */
  2468.     as->evenspill = nslots;
  2469. #if LJ_64
  2470.   return irt_isfp(ir->t) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET);
  2471. #else
  2472.   return irt_isfp(ir->t) ? REGSP_INIT : REGSP_HINT(RID_RET);
  2473. #endif
  2474. }

  2475. /* Target-specific setup. */
  2476. static void asm_setup_target(ASMState *as)
  2477. {
  2478.   asm_exitstub_setup(as, as->T->nsnap);
  2479. }

  2480. /* -- Trace patching ------------------------------------------------------ */

  2481. /* Patch exit jumps of existing machine code to a new target. */
  2482. void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target)
  2483. {
  2484.   MCode *p = T->mcode;
  2485.   MCode *mcarea = lj_mcode_patch(J, p, 0);
  2486.   MSize len = T->szmcode;
  2487.   MCode *px = exitstub_addr(J, exitno) - 6;
  2488.   MCode *pe = p+len-6;
  2489.   uint32_t stateaddr = u32ptr(&J2G(J)->vmstate);
  2490.   if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px)
  2491.     *(int32_t *)(p+len-4) = jmprel(p+len, target);
  2492.   /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */
  2493.   for (; p < pe; p++)
  2494.     if (*(uint32_t *)(p+(LJ_64 ? 3 : 2)) == stateaddr && p[0] == XI_MOVmi) {
  2495.       p += LJ_64 ? 11 : 10;
  2496.       break;
  2497.     }
  2498.   lua_assert(p < pe);
  2499.   for (; p < pe; p++) {
  2500.     if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px) {
  2501.       *(int32_t *)(p+2) = jmprel(p+6, target);
  2502.       p += 5;
  2503.     }
  2504.   }
  2505.   lj_mcode_sync(T->mcode, T->mcode + T->szmcode);
  2506.   lj_mcode_patch(J, mcarea, 1);
  2507. }