Fix handling of alignment arguments (nil) to CALLX.
[luajit-2.0.git] / src / lj_asm_x86.h
blob2edfe6e6f93eec3afdeba567f7083ed421c6fdaa
1 /*
2 ** x86/x64 IR assembler (SSA IR -> machine code).
3 ** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h
4 */
6 /* -- Guard handling ------------------------------------------------------ */
8 /* Generate an exit stub group at the bottom of the reserved MCode memory. */
9 static MCode *asm_exitstub_gen(ASMState *as, ExitNo group)
11 ExitNo i, groupofs = (group*EXITSTUBS_PER_GROUP) & 0xff;
12 MCode *mxp = as->mcbot;
13 MCode *mxpstart = mxp;
14 if (mxp + (2+2)*EXITSTUBS_PER_GROUP+8+5 >= as->mctop)
15 asm_mclimit(as);
16 /* Push low byte of exitno for each exit stub. */
17 *mxp++ = XI_PUSHi8; *mxp++ = (MCode)groupofs;
18 for (i = 1; i < EXITSTUBS_PER_GROUP; i++) {
19 *mxp++ = XI_JMPs; *mxp++ = (MCode)((2+2)*(EXITSTUBS_PER_GROUP - i) - 2);
20 *mxp++ = XI_PUSHi8; *mxp++ = (MCode)(groupofs + i);
22 /* Push the high byte of the exitno for each exit stub group. */
23 *mxp++ = XI_PUSHi8; *mxp++ = (MCode)((group*EXITSTUBS_PER_GROUP)>>8);
24 /* Store DISPATCH at original stack slot 0. Account for the two push ops. */
25 *mxp++ = XI_MOVmi;
26 *mxp++ = MODRM(XM_OFS8, 0, RID_ESP);
27 *mxp++ = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
28 *mxp++ = 2*sizeof(void *);
29 *(int32_t *)mxp = ptr2addr(J2GG(as->J)->dispatch); mxp += 4;
30 /* Jump to exit handler which fills in the ExitState. */
31 *mxp++ = XI_JMP; mxp += 4;
32 *((int32_t *)(mxp-4)) = jmprel(mxp, (MCode *)(void *)lj_vm_exit_handler);
33 /* Commit the code for this group (even if assembly fails later on). */
34 lj_mcode_commitbot(as->J, mxp);
35 as->mcbot = mxp;
36 as->mclim = as->mcbot + MCLIM_REDZONE;
37 return mxpstart;
40 /* Setup all needed exit stubs. */
41 static void asm_exitstub_setup(ASMState *as, ExitNo nexits)
43 ExitNo i;
44 if (nexits >= EXITSTUBS_PER_GROUP*LJ_MAX_EXITSTUBGR)
45 lj_trace_err(as->J, LJ_TRERR_SNAPOV);
46 for (i = 0; i < (nexits+EXITSTUBS_PER_GROUP-1)/EXITSTUBS_PER_GROUP; i++)
47 if (as->J->exitstubgroup[i] == NULL)
48 as->J->exitstubgroup[i] = asm_exitstub_gen(as, i);
51 /* Emit conditional branch to exit for guard.
52 ** It's important to emit this *after* all registers have been allocated,
53 ** because rematerializations may invalidate the flags.
55 static void asm_guardcc(ASMState *as, int cc)
57 MCode *target = exitstub_addr(as->J, as->snapno);
58 MCode *p = as->mcp;
59 if (LJ_UNLIKELY(p == as->invmcp)) {
60 as->loopinv = 1;
61 *(int32_t *)(p+1) = jmprel(p+5, target);
62 target = p;
63 cc ^= 1;
64 if (as->realign) {
65 emit_sjcc(as, cc, target);
66 return;
69 emit_jcc(as, cc, target);
72 /* -- Memory operand fusion ----------------------------------------------- */
74 /* Limit linear search to this distance. Avoids O(n^2) behavior. */
75 #define CONFLICT_SEARCH_LIM 31
77 /* Check if a reference is a signed 32 bit constant. */
78 static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
80 if (irref_isk(ref)) {
81 IRIns *ir = IR(ref);
82 if (ir->o != IR_KINT64) {
83 *k = ir->i;
84 return 1;
85 } else if (checki32((int64_t)ir_kint64(ir)->u64)) {
86 *k = (int32_t)ir_kint64(ir)->u64;
87 return 1;
90 return 0;
93 /* Check if there's no conflicting instruction between curins and ref.
94 ** Also avoid fusing loads if there are multiple references.
96 static int noconflict(ASMState *as, IRRef ref, IROp conflict, int noload)
98 IRIns *ir = as->ir;
99 IRRef i = as->curins;
100 if (i > ref + CONFLICT_SEARCH_LIM)
101 return 0; /* Give up, ref is too far away. */
102 while (--i > ref) {
103 if (ir[i].o == conflict)
104 return 0; /* Conflict found. */
105 else if (!noload && (ir[i].op1 == ref || ir[i].op2 == ref))
106 return 0;
108 return 1; /* Ok, no conflict. */
111 /* Fuse array base into memory operand. */
112 static IRRef asm_fuseabase(ASMState *as, IRRef ref)
114 IRIns *irb = IR(ref);
115 as->mrm.ofs = 0;
116 if (irb->o == IR_FLOAD) {
117 IRIns *ira = IR(irb->op1);
118 lua_assert(irb->op2 == IRFL_TAB_ARRAY);
119 /* We can avoid the FLOAD of t->array for colocated arrays. */
120 if (ira->o == IR_TNEW && ira->op1 <= LJ_MAX_COLOSIZE &&
121 !neverfuse(as) && noconflict(as, irb->op1, IR_NEWREF, 1)) {
122 as->mrm.ofs = (int32_t)sizeof(GCtab); /* Ofs to colocated array. */
123 return irb->op1; /* Table obj. */
125 } else if (irb->o == IR_ADD && irref_isk(irb->op2)) {
126 /* Fuse base offset (vararg load). */
127 as->mrm.ofs = IR(irb->op2)->i;
128 return irb->op1;
130 return ref; /* Otherwise use the given array base. */
133 /* Fuse array reference into memory operand. */
134 static void asm_fusearef(ASMState *as, IRIns *ir, RegSet allow)
136 IRIns *irx;
137 lua_assert(ir->o == IR_AREF);
138 as->mrm.base = (uint8_t)ra_alloc1(as, asm_fuseabase(as, ir->op1), allow);
139 irx = IR(ir->op2);
140 if (irref_isk(ir->op2)) {
141 as->mrm.ofs += 8*irx->i;
142 as->mrm.idx = RID_NONE;
143 } else {
144 rset_clear(allow, as->mrm.base);
145 as->mrm.scale = XM_SCALE8;
146 /* Fuse a constant ADD (e.g. t[i+1]) into the offset.
147 ** Doesn't help much without ABCelim, but reduces register pressure.
149 if (!LJ_64 && /* Has bad effects with negative index on x64. */
150 mayfuse(as, ir->op2) && ra_noreg(irx->r) &&
151 irx->o == IR_ADD && irref_isk(irx->op2)) {
152 as->mrm.ofs += 8*IR(irx->op2)->i;
153 as->mrm.idx = (uint8_t)ra_alloc1(as, irx->op1, allow);
154 } else {
155 as->mrm.idx = (uint8_t)ra_alloc1(as, ir->op2, allow);
160 /* Fuse array/hash/upvalue reference into memory operand.
161 ** Caveat: this may allocate GPRs for the base/idx registers. Be sure to
162 ** pass the final allow mask, excluding any GPRs used for other inputs.
163 ** In particular: 2-operand GPR instructions need to call ra_dest() first!
165 static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow)
167 IRIns *ir = IR(ref);
168 if (ra_noreg(ir->r)) {
169 switch ((IROp)ir->o) {
170 case IR_AREF:
171 if (mayfuse(as, ref)) {
172 asm_fusearef(as, ir, allow);
173 return;
175 break;
176 case IR_HREFK:
177 if (mayfuse(as, ref)) {
178 as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow);
179 as->mrm.ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node));
180 as->mrm.idx = RID_NONE;
181 return;
183 break;
184 case IR_UREFC:
185 if (irref_isk(ir->op1)) {
186 GCfunc *fn = ir_kfunc(IR(ir->op1));
187 GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv;
188 as->mrm.ofs = ptr2addr(&uv->tv);
189 as->mrm.base = as->mrm.idx = RID_NONE;
190 return;
192 break;
193 default:
194 lua_assert(ir->o == IR_HREF || ir->o == IR_NEWREF || ir->o == IR_UREFO ||
195 ir->o == IR_KKPTR);
196 break;
199 as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
200 as->mrm.ofs = 0;
201 as->mrm.idx = RID_NONE;
204 /* Fuse FLOAD/FREF reference into memory operand. */
205 static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow)
207 lua_assert(ir->o == IR_FLOAD || ir->o == IR_FREF);
208 as->mrm.ofs = field_ofs[ir->op2];
209 as->mrm.idx = RID_NONE;
210 if (irref_isk(ir->op1)) {
211 as->mrm.ofs += IR(ir->op1)->i;
212 as->mrm.base = RID_NONE;
213 } else {
214 as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow);
218 /* Fuse string reference into memory operand. */
219 static void asm_fusestrref(ASMState *as, IRIns *ir, RegSet allow)
221 IRIns *irr;
222 lua_assert(ir->o == IR_STRREF);
223 as->mrm.base = as->mrm.idx = RID_NONE;
224 as->mrm.scale = XM_SCALE1;
225 as->mrm.ofs = sizeof(GCstr);
226 if (irref_isk(ir->op1)) {
227 as->mrm.ofs += IR(ir->op1)->i;
228 } else {
229 Reg r = ra_alloc1(as, ir->op1, allow);
230 rset_clear(allow, r);
231 as->mrm.base = (uint8_t)r;
233 irr = IR(ir->op2);
234 if (irref_isk(ir->op2)) {
235 as->mrm.ofs += irr->i;
236 } else {
237 Reg r;
238 /* Fuse a constant add into the offset, e.g. string.sub(s, i+10). */
239 if (!LJ_64 && /* Has bad effects with negative index on x64. */
240 mayfuse(as, ir->op2) && irr->o == IR_ADD && irref_isk(irr->op2)) {
241 as->mrm.ofs += IR(irr->op2)->i;
242 r = ra_alloc1(as, irr->op1, allow);
243 } else {
244 r = ra_alloc1(as, ir->op2, allow);
246 if (as->mrm.base == RID_NONE)
247 as->mrm.base = (uint8_t)r;
248 else
249 as->mrm.idx = (uint8_t)r;
253 static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow)
255 IRIns *ir = IR(ref);
256 as->mrm.idx = RID_NONE;
257 if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
258 as->mrm.ofs = ir->i;
259 as->mrm.base = RID_NONE;
260 } else if (ir->o == IR_STRREF) {
261 asm_fusestrref(as, ir, allow);
262 } else {
263 as->mrm.ofs = 0;
264 if (canfuse(as, ir) && ir->o == IR_ADD && ra_noreg(ir->r)) {
265 /* Gather (base+idx*sz)+ofs as emitted by cdata ptr/array indexing. */
266 IRIns *irx;
267 IRRef idx;
268 Reg r;
269 if (asm_isk32(as, ir->op2, &as->mrm.ofs)) { /* Recognize x+ofs. */
270 ref = ir->op1;
271 ir = IR(ref);
272 if (!(ir->o == IR_ADD && canfuse(as, ir) && ra_noreg(ir->r)))
273 goto noadd;
275 as->mrm.scale = XM_SCALE1;
276 idx = ir->op1;
277 ref = ir->op2;
278 irx = IR(idx);
279 if (!(irx->o == IR_BSHL || irx->o == IR_ADD)) { /* Try other operand. */
280 idx = ir->op2;
281 ref = ir->op1;
282 irx = IR(idx);
284 if (canfuse(as, irx) && ra_noreg(irx->r)) {
285 if (irx->o == IR_BSHL && irref_isk(irx->op2) && IR(irx->op2)->i <= 3) {
286 /* Recognize idx<<b with b = 0-3, corresponding to sz = (1),2,4,8. */
287 idx = irx->op1;
288 as->mrm.scale = (uint8_t)(IR(irx->op2)->i << 6);
289 } else if (irx->o == IR_ADD && irx->op1 == irx->op2) {
290 /* FOLD does idx*2 ==> idx<<1 ==> idx+idx. */
291 idx = irx->op1;
292 as->mrm.scale = XM_SCALE2;
295 r = ra_alloc1(as, idx, allow);
296 rset_clear(allow, r);
297 as->mrm.idx = (uint8_t)r;
299 noadd:
300 as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
304 /* Fuse load into memory operand. */
305 static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
307 IRIns *ir = IR(ref);
308 if (ra_hasreg(ir->r)) {
309 if (allow != RSET_EMPTY) { /* Fast path. */
310 ra_noweak(as, ir->r);
311 return ir->r;
313 fusespill:
314 /* Force a spill if only memory operands are allowed (asm_x87load). */
315 as->mrm.base = RID_ESP;
316 as->mrm.ofs = ra_spill(as, ir);
317 as->mrm.idx = RID_NONE;
318 return RID_MRM;
320 if (ir->o == IR_KNUM) {
321 RegSet avail = as->freeset & ~as->modset & RSET_FPR;
322 lua_assert(allow != RSET_EMPTY);
323 if (!(avail & (avail-1))) { /* Fuse if less than two regs available. */
324 as->mrm.ofs = ptr2addr(ir_knum(ir));
325 as->mrm.base = as->mrm.idx = RID_NONE;
326 return RID_MRM;
328 } else if (mayfuse(as, ref)) {
329 RegSet xallow = (allow & RSET_GPR) ? allow : RSET_GPR;
330 if (ir->o == IR_SLOAD) {
331 if (!(ir->op2 & (IRSLOAD_PARENT|IRSLOAD_CONVERT)) &&
332 noconflict(as, ref, IR_RETF, 0)) {
333 as->mrm.base = (uint8_t)ra_alloc1(as, REF_BASE, xallow);
334 as->mrm.ofs = 8*((int32_t)ir->op1-1) + ((ir->op2&IRSLOAD_FRAME)?4:0);
335 as->mrm.idx = RID_NONE;
336 return RID_MRM;
338 } else if (ir->o == IR_FLOAD) {
339 /* Generic fusion is only ok for 32 bit operand (but see asm_comp). */
340 if ((irt_isint(ir->t) || irt_isaddr(ir->t)) &&
341 noconflict(as, ref, IR_FSTORE, 0)) {
342 asm_fusefref(as, ir, xallow);
343 return RID_MRM;
345 } else if (ir->o == IR_ALOAD || ir->o == IR_HLOAD || ir->o == IR_ULOAD) {
346 if (noconflict(as, ref, ir->o + IRDELTA_L2S, 0)) {
347 asm_fuseahuref(as, ir->op1, xallow);
348 return RID_MRM;
350 } else if (ir->o == IR_XLOAD) {
351 /* Generic fusion is not ok for 8/16 bit operands (but see asm_comp).
352 ** Fusing unaligned memory operands is ok on x86 (except for SIMD types).
354 if ((!irt_typerange(ir->t, IRT_I8, IRT_U16)) &&
355 noconflict(as, ref, IR_XSTORE, 0)) {
356 asm_fusexref(as, ir->op1, xallow);
357 return RID_MRM;
359 } else if (ir->o == IR_VLOAD) {
360 asm_fuseahuref(as, ir->op1, xallow);
361 return RID_MRM;
364 if (!(as->freeset & allow) &&
365 (allow == RSET_EMPTY || ra_hasspill(ir->s) || iscrossref(as, ref)))
366 goto fusespill;
367 return ra_allocref(as, ref, allow);
370 /* -- Calls --------------------------------------------------------------- */
372 /* Generate a call to a C function. */
373 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
375 uint32_t n, nargs = CCI_NARGS(ci);
376 int32_t ofs = STACKARG_OFS;
377 uint32_t gprs = REGARG_GPRS;
378 #if LJ_64
379 Reg fpr = REGARG_FIRSTFPR;
380 #endif
381 lua_assert(!(nargs > 2 && (ci->flags&CCI_FASTCALL))); /* Avoid stack adj. */
382 if ((void *)ci->func)
383 emit_call(as, ci->func);
384 for (n = 0; n < nargs; n++) { /* Setup args. */
385 IRRef ref = args[n];
386 IRIns *ir = IR(ref);
387 Reg r;
388 #if LJ_64 && LJ_ABI_WIN
389 /* Windows/x64 argument registers are strictly positional. */
390 r = irt_isfp(ir->t) ? (fpr <= REGARG_LASTFPR ? fpr : 0) : (gprs & 31);
391 fpr++; gprs >>= 5;
392 #elif LJ_64
393 /* POSIX/x64 argument registers are used in order of appearance. */
394 if (irt_isfp(ir->t)) {
395 r = fpr <= REGARG_LASTFPR ? fpr : 0; fpr++;
396 } else {
397 r = gprs & 31; gprs >>= 5;
399 #else
400 if (irt_isfp(ir->t) || !(ci->flags & CCI_FASTCALL)) {
401 r = 0;
402 } else {
403 r = gprs & 31; gprs >>= 5;
405 #endif
406 if (r) { /* Argument is in a register. */
407 if (r < RID_MAX_GPR && ref < ASMREF_TMP1) {
408 #if LJ_64
409 if (ir->o == IR_KINT64)
410 emit_loadu64(as, r, ir_kint64(ir)->u64);
411 else
412 #endif
413 emit_loadi(as, r, ir->i);
414 } else {
415 lua_assert(rset_test(as->freeset, r)); /* Must have been evicted. */
416 if (ra_hasreg(ir->r)) {
417 ra_noweak(as, ir->r);
418 emit_movrr(as, ir, r, ir->r);
419 } else {
420 ra_allocref(as, ref, RID2RSET(r));
423 } else if (irt_isfp(ir->t)) { /* FP argument is on stack. */
424 lua_assert(!(irt_isfloat(ir->t) && irref_isk(ref))); /* No float k. */
425 if (LJ_32 && (ofs & 4) && irref_isk(ref)) {
426 /* Split stores for unaligned FP consts. */
427 emit_movmroi(as, RID_ESP, ofs, (int32_t)ir_knum(ir)->u32.lo);
428 emit_movmroi(as, RID_ESP, ofs+4, (int32_t)ir_knum(ir)->u32.hi);
429 } else {
430 r = ra_alloc1(as, ref, RSET_FPR);
431 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto,
432 r, RID_ESP, ofs);
434 ofs += (LJ_32 && irt_isfloat(ir->t)) ? 4 : 8;
435 } else { /* Non-FP argument is on stack. */
436 if (LJ_32 && ref < ASMREF_TMP1) {
437 emit_movmroi(as, RID_ESP, ofs, ir->i);
438 } else {
439 r = ra_alloc1(as, ref, RSET_GPR);
440 emit_movtomro(as, REX_64IR(ir, r), RID_ESP, ofs);
442 ofs += sizeof(intptr_t);
447 /* Setup result reg/sp for call. Evict scratch regs. */
448 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
450 RegSet drop = RSET_SCRATCH;
451 if ((ci->flags & CCI_NOFPRCLOBBER))
452 drop &= ~RSET_FPR;
453 if (ra_hasreg(ir->r))
454 rset_clear(drop, ir->r); /* Dest reg handled below. */
455 ra_evictset(as, drop); /* Evictions must be performed first. */
456 if (ra_used(ir)) {
457 if (irt_isfp(ir->t)) {
458 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
459 #if LJ_64
460 if ((ci->flags & CCI_CASTU64)) {
461 Reg dest = ir->r;
462 if (ra_hasreg(dest)) {
463 ra_free(as, dest);
464 ra_modified(as, dest);
465 emit_rr(as, XO_MOVD, dest|REX_64, RID_RET); /* Really MOVQ. */
467 if (ofs) emit_movtomro(as, RID_RET|REX_64, RID_ESP, ofs);
468 } else {
469 ra_destreg(as, ir, RID_FPRET);
471 #else
472 /* Number result is in x87 st0 for x86 calling convention. */
473 Reg dest = ir->r;
474 if (ra_hasreg(dest)) {
475 ra_free(as, dest);
476 ra_modified(as, dest);
477 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS,
478 dest, RID_ESP, ofs);
480 if ((ci->flags & CCI_CASTU64)) {
481 emit_movtomro(as, RID_RETLO, RID_ESP, ofs);
482 emit_movtomro(as, RID_RETHI, RID_ESP, ofs+4);
483 } else {
484 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
485 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
487 #endif
488 } else {
489 lua_assert(!irt_ispri(ir->t));
490 ra_destreg(as, ir, RID_RET);
492 } else if (LJ_32 && irt_isfp(ir->t)) {
493 emit_x87op(as, XI_FPOP); /* Pop unused result from x87 st0. */
497 static void asm_call(ASMState *as, IRIns *ir)
499 IRRef args[CCI_NARGS_MAX];
500 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
501 asm_collectargs(as, ir, ci, args);
502 asm_setupresult(as, ir, ci);
503 asm_gencall(as, ci, args);
506 static void asm_callx(ASMState *as, IRIns *ir)
508 IRRef args[CCI_NARGS_MAX];
509 CCallInfo ci;
510 IRIns *irf;
511 ci.flags = asm_callx_flags(as, ir);
512 asm_collectargs(as, ir, &ci, args);
513 asm_setupresult(as, ir, &ci);
514 irf = IR(ir->op2);
515 if (LJ_32 && irref_isk(ir->op2)) { /* Call to constant address on x86. */
516 ci.func = (ASMFunction)(void *)(uintptr_t)(uint32_t)irf->i;
517 } else {
518 /* Prefer a non-argument register or RID_RET for indirect calls. */
519 RegSet allow = (RSET_GPR & ~RSET_SCRATCH)|RID2RSET(RID_RET);
520 Reg r = ra_alloc1(as, ir->op2, allow);
521 emit_rr(as, XO_GROUP5, XOg_CALL, r);
522 ci.func = (ASMFunction)(void *)0;
524 asm_gencall(as, &ci, args);
527 /* -- Returns ------------------------------------------------------------- */
529 /* Return to lower frame. Guard that it goes to the right spot. */
530 static void asm_retf(ASMState *as, IRIns *ir)
532 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
533 void *pc = ir_kptr(IR(ir->op2));
534 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1));
535 as->topslot -= (BCReg)delta;
536 if ((int32_t)as->topslot < 0) as->topslot = 0;
537 emit_setgl(as, base, jit_base);
538 emit_addptr(as, base, -8*delta);
539 asm_guardcc(as, CC_NE);
540 emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc));
543 /* -- Type conversions ---------------------------------------------------- */
545 static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
547 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
548 Reg dest = ra_dest(as, ir, RSET_GPR);
549 asm_guardcc(as, CC_P);
550 asm_guardcc(as, CC_NE);
551 emit_rr(as, XO_UCOMISD, left, tmp);
552 emit_rr(as, XO_CVTSI2SD, tmp, dest);
553 if (!(as->flags & JIT_F_SPLIT_XMM))
554 emit_rr(as, XO_XORPS, tmp, tmp); /* Avoid partial register stall. */
555 emit_rr(as, XO_CVTTSD2SI, dest, left);
556 /* Can't fuse since left is needed twice. */
559 static void asm_tobit(ASMState *as, IRIns *ir)
561 Reg dest = ra_dest(as, ir, RSET_GPR);
562 Reg tmp = ra_noreg(IR(ir->op1)->r) ?
563 ra_alloc1(as, ir->op1, RSET_FPR) :
564 ra_scratch(as, RSET_FPR);
565 Reg right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp));
566 emit_rr(as, XO_MOVDto, tmp, dest);
567 emit_mrm(as, XO_ADDSD, tmp, right);
568 ra_left(as, tmp, ir->op1);
571 static void asm_conv(ASMState *as, IRIns *ir)
573 IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK);
574 int st64 = (st == IRT_I64 || st == IRT_U64 || (LJ_64 && st == IRT_P64));
575 int stfp = (st == IRT_NUM || st == IRT_FLOAT);
576 IRRef lref = ir->op1;
577 lua_assert(irt_type(ir->t) != st);
578 lua_assert(!(LJ_32 && (irt_isint64(ir->t) || st64))); /* Handled by SPLIT. */
579 if (irt_isfp(ir->t)) {
580 Reg dest = ra_dest(as, ir, RSET_FPR);
581 if (stfp) { /* FP to FP conversion. */
582 Reg left = asm_fuseload(as, lref, RSET_FPR);
583 emit_mrm(as, st == IRT_NUM ? XO_CVTSD2SS : XO_CVTSS2SD, dest, left);
584 if (left == dest) return; /* Avoid the XO_XORPS. */
585 } else if (LJ_32 && st == IRT_U32) { /* U32 to FP conversion on x86. */
586 /* number = (2^52+2^51 .. u32) - (2^52+2^51) */
587 cTValue *k = lj_ir_k64_find(as->J, U64x(43380000,00000000));
588 Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest));
589 if (irt_isfloat(ir->t))
590 emit_rr(as, XO_CVTSD2SS, dest, dest);
591 emit_rr(as, XO_SUBSD, dest, bias); /* Subtract 2^52+2^51 bias. */
592 emit_rr(as, XO_XORPS, dest, bias); /* Merge bias and integer. */
593 emit_loadn(as, bias, k);
594 emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR));
595 return;
596 } else { /* Integer to FP conversion. */
597 Reg left = (LJ_64 && (st == IRT_U32 || st == IRT_U64)) ?
598 ra_alloc1(as, lref, RSET_GPR) :
599 asm_fuseload(as, lref, RSET_GPR);
600 if (LJ_64 && st == IRT_U64) {
601 MCLabel l_end = emit_label(as);
602 const void *k = lj_ir_k64_find(as->J, U64x(43f00000,00000000));
603 emit_rma(as, XO_ADDSD, dest, k); /* Add 2^64 to compensate. */
604 emit_sjcc(as, CC_NS, l_end);
605 emit_rr(as, XO_TEST, left|REX_64, left); /* Check if u64 >= 2^63. */
607 emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS,
608 dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left);
610 if (!(as->flags & JIT_F_SPLIT_XMM))
611 emit_rr(as, XO_XORPS, dest, dest); /* Avoid partial register stall. */
612 } else if (stfp) { /* FP to integer conversion. */
613 if (irt_isguard(ir->t)) {
614 /* Checked conversions are only supported from number to int. */
615 lua_assert(irt_isint(ir->t) && st == IRT_NUM);
616 asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR));
617 } else {
618 Reg dest = ra_dest(as, ir, RSET_GPR);
619 x86Op op = st == IRT_NUM ?
620 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSD2SI : XO_CVTSD2SI) :
621 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSS2SI : XO_CVTSS2SI);
622 if (LJ_64 ? irt_isu64(ir->t) : irt_isu32(ir->t)) {
623 /* LJ_64: For inputs >= 2^63 add -2^64, convert again. */
624 /* LJ_32: For inputs >= 2^31 add -2^31, convert again and add 2^31. */
625 Reg tmp = ra_noreg(IR(lref)->r) ? ra_alloc1(as, lref, RSET_FPR) :
626 ra_scratch(as, RSET_FPR);
627 MCLabel l_end = emit_label(as);
628 if (LJ_32)
629 emit_gri(as, XG_ARITHi(XOg_ADD), dest, (int32_t)0x80000000);
630 emit_rr(as, op, dest|REX_64, tmp);
631 if (st == IRT_NUM)
632 emit_rma(as, XO_ADDSD, tmp, lj_ir_k64_find(as->J,
633 LJ_64 ? U64x(c3f00000,00000000) : U64x(c1e00000,00000000)));
634 else
635 emit_rma(as, XO_ADDSS, tmp, lj_ir_k64_find(as->J,
636 LJ_64 ? U64x(00000000,df800000) : U64x(00000000,cf000000)));
637 emit_sjcc(as, CC_NS, l_end);
638 emit_rr(as, XO_TEST, dest|REX_64, dest); /* Check if dest negative. */
639 emit_rr(as, op, dest|REX_64, tmp);
640 ra_left(as, tmp, lref);
641 } else {
642 Reg left = asm_fuseload(as, lref, RSET_FPR);
643 if (LJ_64 && irt_isu32(ir->t))
644 emit_rr(as, XO_MOV, dest, dest); /* Zero hiword. */
645 emit_mrm(as, op,
646 dest|((LJ_64 &&
647 (irt_is64(ir->t) || irt_isu32(ir->t))) ? REX_64 : 0),
648 left);
651 } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */
652 Reg left, dest = ra_dest(as, ir, RSET_GPR);
653 RegSet allow = RSET_GPR;
654 x86Op op;
655 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t));
656 if (st == IRT_I8) {
657 op = XO_MOVSXb; allow = RSET_GPR8; dest |= FORCE_REX;
658 } else if (st == IRT_U8) {
659 op = XO_MOVZXb; allow = RSET_GPR8; dest |= FORCE_REX;
660 } else if (st == IRT_I16) {
661 op = XO_MOVSXw;
662 } else {
663 op = XO_MOVZXw;
665 left = asm_fuseload(as, lref, allow);
666 /* Add extra MOV if source is already in wrong register. */
667 if (!LJ_64 && left != RID_MRM && !rset_test(allow, left)) {
668 Reg tmp = ra_scratch(as, allow);
669 emit_rr(as, op, dest, tmp);
670 emit_rr(as, XO_MOV, tmp, left);
671 } else {
672 emit_mrm(as, op, dest, left);
674 } else { /* 32/64 bit integer conversions. */
675 if (LJ_32) { /* Only need to handle 32/32 bit no-op (cast) on x86. */
676 Reg dest = ra_dest(as, ir, RSET_GPR);
677 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
678 } else if (irt_is64(ir->t)) {
679 Reg dest = ra_dest(as, ir, RSET_GPR);
680 if (st64 || !(ir->op2 & IRCONV_SEXT)) {
681 /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */
682 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
683 } else { /* 32 to 64 bit sign extension. */
684 Reg left = asm_fuseload(as, lref, RSET_GPR);
685 emit_mrm(as, XO_MOVSXd, dest|REX_64, left);
687 } else {
688 Reg dest = ra_dest(as, ir, RSET_GPR);
689 if (st64) {
690 Reg left = asm_fuseload(as, lref, RSET_GPR);
691 /* This is either a 32 bit reg/reg mov which zeroes the hiword
692 ** or a load of the loword from a 64 bit address.
694 emit_mrm(as, XO_MOV, dest, left);
695 } else { /* 32/32 bit no-op (cast). */
696 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
702 #if LJ_32 && LJ_HASFFI
703 /* No SSE conversions to/from 64 bit on x86, so resort to ugly x87 code. */
705 /* 64 bit integer to FP conversion in 32 bit mode. */
706 static void asm_conv_fp_int64(ASMState *as, IRIns *ir)
708 Reg hi = ra_alloc1(as, ir->op1, RSET_GPR);
709 Reg lo = ra_alloc1(as, (ir-1)->op1, rset_exclude(RSET_GPR, hi));
710 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
711 Reg dest = ir->r;
712 if (ra_hasreg(dest)) {
713 ra_free(as, dest);
714 ra_modified(as, dest);
715 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS,
716 dest, RID_ESP, ofs);
718 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
719 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
720 if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) {
721 /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */
722 MCLabel l_end = emit_label(as);
723 emit_rma(as, XO_FADDq, XOg_FADDq,
724 lj_ir_k64_find(as->J, U64x(43f00000,00000000)));
725 emit_sjcc(as, CC_NS, l_end);
726 emit_rr(as, XO_TEST, hi, hi); /* Check if u64 >= 2^63. */
727 } else {
728 lua_assert(((ir-1)->op2 & IRCONV_SRCMASK) == IRT_I64);
730 emit_rmro(as, XO_FILDq, XOg_FILDq, RID_ESP, 0);
731 /* NYI: Avoid narrow-to-wide store-to-load forwarding stall. */
732 emit_rmro(as, XO_MOVto, hi, RID_ESP, 4);
733 emit_rmro(as, XO_MOVto, lo, RID_ESP, 0);
736 /* FP to 64 bit integer conversion in 32 bit mode. */
737 static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
739 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
740 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
741 Reg lo, hi;
742 lua_assert(st == IRT_NUM || st == IRT_FLOAT);
743 lua_assert(dt == IRT_I64 || dt == IRT_U64);
744 lua_assert(((ir-1)->op2 & IRCONV_TRUNC));
745 hi = ra_dest(as, ir, RSET_GPR);
746 lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi));
747 if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0);
748 /* NYI: Avoid wide-to-narrow store-to-load forwarding stall. */
749 if (!(as->flags & JIT_F_SSE3)) { /* Set FPU rounding mode to default. */
750 emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 4);
751 emit_rmro(as, XO_MOVto, lo, RID_ESP, 4);
752 emit_gri(as, XG_ARITHi(XOg_AND), lo, 0xf3ff);
754 if (dt == IRT_U64) {
755 /* For inputs in [2^63,2^64-1] add -2^64 and convert again. */
756 MCLabel l_pop, l_end = emit_label(as);
757 emit_x87op(as, XI_FPOP);
758 l_pop = emit_label(as);
759 emit_sjmp(as, l_end);
760 emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
761 if ((as->flags & JIT_F_SSE3))
762 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
763 else
764 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
765 emit_rma(as, XO_FADDq, XOg_FADDq,
766 lj_ir_k64_find(as->J, U64x(c3f00000,00000000)));
767 emit_sjcc(as, CC_NS, l_pop);
768 emit_rr(as, XO_TEST, hi, hi); /* Check if out-of-range (2^63). */
770 emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
771 if ((as->flags & JIT_F_SSE3)) { /* Truncation is easy with SSE3. */
772 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
773 } else { /* Otherwise set FPU rounding mode to truncate before the store. */
774 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
775 emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 0);
776 emit_rmro(as, XO_MOVtow, lo, RID_ESP, 0);
777 emit_rmro(as, XO_ARITHw(XOg_OR), lo, RID_ESP, 0);
778 emit_loadi(as, lo, 0xc00);
779 emit_rmro(as, XO_FNSTCW, XOg_FNSTCW, RID_ESP, 0);
781 if (dt == IRT_U64)
782 emit_x87op(as, XI_FDUP);
783 emit_mrm(as, st == IRT_NUM ? XO_FLDq : XO_FLDd,
784 st == IRT_NUM ? XOg_FLDq: XOg_FLDd,
785 asm_fuseload(as, ir->op1, RSET_EMPTY));
787 #endif
789 static void asm_strto(ASMState *as, IRIns *ir)
791 /* Force a spill slot for the destination register (if any). */
792 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_tonum];
793 IRRef args[2];
794 RegSet drop = RSET_SCRATCH;
795 if ((drop & RSET_FPR) != RSET_FPR && ra_hasreg(ir->r))
796 rset_set(drop, ir->r); /* WIN64 doesn't spill all FPRs. */
797 ra_evictset(as, drop);
798 asm_guardcc(as, CC_E);
799 emit_rr(as, XO_TEST, RID_RET, RID_RET); /* Test return status. */
800 args[0] = ir->op1; /* GCstr *str */
801 args[1] = ASMREF_TMP1; /* TValue *n */
802 asm_gencall(as, ci, args);
803 /* Store the result to the spill slot or temp slots. */
804 emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
805 RID_ESP, sps_scale(ir->s));
808 static void asm_tostr(ASMState *as, IRIns *ir)
810 IRIns *irl = IR(ir->op1);
811 IRRef args[2];
812 args[0] = ASMREF_L;
813 as->gcsteps++;
814 if (irt_isnum(irl->t)) {
815 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum];
816 args[1] = ASMREF_TMP1; /* const lua_Number * */
817 asm_setupresult(as, ir, ci); /* GCstr * */
818 asm_gencall(as, ci, args);
819 emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
820 RID_ESP, ra_spill(as, irl));
821 } else {
822 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint];
823 args[1] = ir->op1; /* int32_t k */
824 asm_setupresult(as, ir, ci); /* GCstr * */
825 asm_gencall(as, ci, args);
829 /* -- Memory references --------------------------------------------------- */
831 static void asm_aref(ASMState *as, IRIns *ir)
833 Reg dest = ra_dest(as, ir, RSET_GPR);
834 asm_fusearef(as, ir, RSET_GPR);
835 if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0))
836 emit_mrm(as, XO_LEA, dest, RID_MRM);
837 else if (as->mrm.base != dest)
838 emit_rr(as, XO_MOV, dest, as->mrm.base);
841 /* Merge NE(HREF, niltv) check. */
842 static MCode *merge_href_niltv(ASMState *as, IRIns *ir)
844 /* Assumes nothing else generates NE of HREF. */
845 if ((ir[1].o == IR_NE || ir[1].o == IR_EQ) && ir[1].op1 == as->curins &&
846 ra_hasreg(ir->r)) {
847 MCode *p = as->mcp;
848 p += (LJ_64 && *p != XI_ARITHi) ? 7+6 : 6+6;
849 /* Ensure no loop branch inversion happened. */
850 if (p[-6] == 0x0f && p[-5] == XI_JCCn+(CC_NE^(ir[1].o & 1))) {
851 as->mcp = p; /* Kill cmp reg, imm32 + jz exit. */
852 return p + *(int32_t *)(p-4); /* Return exit address. */
855 return NULL;
858 /* Inlined hash lookup. Specialized for key type and for const keys.
859 ** The equivalent C code is:
860 ** Node *n = hashkey(t, key);
861 ** do {
862 ** if (lj_obj_equal(&n->key, key)) return &n->val;
863 ** } while ((n = nextnode(n)));
864 ** return niltv(L);
866 static void asm_href(ASMState *as, IRIns *ir)
868 MCode *nilexit = merge_href_niltv(as, ir); /* Do this before any restores. */
869 RegSet allow = RSET_GPR;
870 Reg dest = ra_dest(as, ir, allow);
871 Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest));
872 Reg key = RID_NONE, tmp = RID_NONE;
873 IRIns *irkey = IR(ir->op2);
874 int isk = irref_isk(ir->op2);
875 IRType1 kt = irkey->t;
876 uint32_t khash;
877 MCLabel l_end, l_loop, l_next;
879 if (!isk) {
880 rset_clear(allow, tab);
881 key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow);
882 if (!irt_isstr(kt))
883 tmp = ra_scratch(as, rset_exclude(allow, key));
886 /* Key not found in chain: jump to exit (if merged with NE) or load niltv. */
887 l_end = emit_label(as);
888 if (nilexit && ir[1].o == IR_NE) {
889 emit_jcc(as, CC_E, nilexit); /* XI_JMP is not found by lj_asm_patchexit. */
890 nilexit = NULL;
891 } else {
892 emit_loada(as, dest, niltvg(J2G(as->J)));
895 /* Follow hash chain until the end. */
896 l_loop = emit_sjcc_label(as, CC_NZ);
897 emit_rr(as, XO_TEST, dest, dest);
898 emit_rmro(as, XO_MOV, dest, dest, offsetof(Node, next));
899 l_next = emit_label(as);
901 /* Type and value comparison. */
902 if (nilexit)
903 emit_jcc(as, CC_E, nilexit);
904 else
905 emit_sjcc(as, CC_E, l_end);
906 if (irt_isnum(kt)) {
907 if (isk) {
908 /* Assumes -0.0 is already canonicalized to +0.0. */
909 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo),
910 (int32_t)ir_knum(irkey)->u32.lo);
911 emit_sjcc(as, CC_NE, l_next);
912 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi),
913 (int32_t)ir_knum(irkey)->u32.hi);
914 } else {
915 emit_sjcc(as, CC_P, l_next);
916 emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n));
917 emit_sjcc(as, CC_AE, l_next);
918 /* The type check avoids NaN penalties and complaints from Valgrind. */
919 #if LJ_64
920 emit_u32(as, LJ_TISNUM);
921 emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it));
922 #else
923 emit_i8(as, LJ_TISNUM);
924 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
925 #endif
927 #if LJ_64
928 } else if (irt_islightud(kt)) {
929 emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64));
930 #endif
931 } else {
932 if (!irt_ispri(kt)) {
933 lua_assert(irt_isaddr(kt));
934 if (isk)
935 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.gcr),
936 ptr2addr(ir_kgc(irkey)));
937 else
938 emit_rmro(as, XO_CMP, key, dest, offsetof(Node, key.gcr));
939 emit_sjcc(as, CC_NE, l_next);
941 lua_assert(!irt_isnil(kt));
942 emit_i8(as, irt_toitype(kt));
943 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
945 emit_sfixup(as, l_loop);
946 checkmclim(as);
948 /* Load main position relative to tab->node into dest. */
949 khash = isk ? ir_khash(irkey) : 1;
950 if (khash == 0) {
951 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, node));
952 } else {
953 emit_rmro(as, XO_ARITH(XOg_ADD), dest, tab, offsetof(GCtab, node));
954 if ((as->flags & JIT_F_PREFER_IMUL)) {
955 emit_i8(as, sizeof(Node));
956 emit_rr(as, XO_IMULi8, dest, dest);
957 } else {
958 emit_shifti(as, XOg_SHL, dest, 3);
959 emit_rmrxo(as, XO_LEA, dest, dest, dest, XM_SCALE2, 0);
961 if (isk) {
962 emit_gri(as, XG_ARITHi(XOg_AND), dest, (int32_t)khash);
963 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
964 } else if (irt_isstr(kt)) {
965 emit_rmro(as, XO_ARITH(XOg_AND), dest, key, offsetof(GCstr, hash));
966 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
967 } else { /* Must match with hashrot() in lj_tab.c. */
968 emit_rmro(as, XO_ARITH(XOg_AND), dest, tab, offsetof(GCtab, hmask));
969 emit_rr(as, XO_ARITH(XOg_SUB), dest, tmp);
970 emit_shifti(as, XOg_ROL, tmp, HASH_ROT3);
971 emit_rr(as, XO_ARITH(XOg_XOR), dest, tmp);
972 emit_shifti(as, XOg_ROL, dest, HASH_ROT2);
973 emit_rr(as, XO_ARITH(XOg_SUB), tmp, dest);
974 emit_shifti(as, XOg_ROL, dest, HASH_ROT1);
975 emit_rr(as, XO_ARITH(XOg_XOR), tmp, dest);
976 if (irt_isnum(kt)) {
977 emit_rr(as, XO_ARITH(XOg_ADD), dest, dest);
978 #if LJ_64
979 emit_shifti(as, XOg_SHR|REX_64, dest, 32);
980 emit_rr(as, XO_MOV, tmp, dest);
981 emit_rr(as, XO_MOVDto, key|REX_64, dest);
982 #else
983 emit_rmro(as, XO_MOV, dest, RID_ESP, ra_spill(as, irkey)+4);
984 emit_rr(as, XO_MOVDto, key, tmp);
985 #endif
986 } else {
987 emit_rr(as, XO_MOV, tmp, key);
988 emit_rmro(as, XO_LEA, dest, key, HASH_BIAS);
994 static void asm_hrefk(ASMState *as, IRIns *ir)
996 IRIns *kslot = IR(ir->op2);
997 IRIns *irkey = IR(kslot->op1);
998 int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node));
999 Reg dest = ra_used(ir) ? ra_dest(as, ir, RSET_GPR) : RID_NONE;
1000 Reg node = ra_alloc1(as, ir->op1, RSET_GPR);
1001 #if !LJ_64
1002 MCLabel l_exit;
1003 #endif
1004 lua_assert(ofs % sizeof(Node) == 0);
1005 if (ra_hasreg(dest)) {
1006 if (ofs != 0) {
1007 if (dest == node && !(as->flags & JIT_F_LEA_AGU))
1008 emit_gri(as, XG_ARITHi(XOg_ADD), dest, ofs);
1009 else
1010 emit_rmro(as, XO_LEA, dest, node, ofs);
1011 } else if (dest != node) {
1012 emit_rr(as, XO_MOV, dest, node);
1015 asm_guardcc(as, CC_NE);
1016 #if LJ_64
1017 if (!irt_ispri(irkey->t)) {
1018 Reg key = ra_scratch(as, rset_exclude(RSET_GPR, node));
1019 emit_rmro(as, XO_CMP, key|REX_64, node,
1020 ofs + (int32_t)offsetof(Node, key.u64));
1021 lua_assert(irt_isnum(irkey->t) || irt_isgcv(irkey->t));
1022 /* Assumes -0.0 is already canonicalized to +0.0. */
1023 emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 :
1024 ((uint64_t)irt_toitype(irkey->t) << 32) |
1025 (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey)));
1026 } else {
1027 lua_assert(!irt_isnil(irkey->t));
1028 emit_i8(as, irt_toitype(irkey->t));
1029 emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
1030 ofs + (int32_t)offsetof(Node, key.it));
1032 #else
1033 l_exit = emit_label(as);
1034 if (irt_isnum(irkey->t)) {
1035 /* Assumes -0.0 is already canonicalized to +0.0. */
1036 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1037 ofs + (int32_t)offsetof(Node, key.u32.lo),
1038 (int32_t)ir_knum(irkey)->u32.lo);
1039 emit_sjcc(as, CC_NE, l_exit);
1040 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1041 ofs + (int32_t)offsetof(Node, key.u32.hi),
1042 (int32_t)ir_knum(irkey)->u32.hi);
1043 } else {
1044 if (!irt_ispri(irkey->t)) {
1045 lua_assert(irt_isgcv(irkey->t));
1046 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1047 ofs + (int32_t)offsetof(Node, key.gcr),
1048 ptr2addr(ir_kgc(irkey)));
1049 emit_sjcc(as, CC_NE, l_exit);
1051 lua_assert(!irt_isnil(irkey->t));
1052 emit_i8(as, irt_toitype(irkey->t));
1053 emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
1054 ofs + (int32_t)offsetof(Node, key.it));
1056 #endif
1059 static void asm_newref(ASMState *as, IRIns *ir)
1061 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
1062 IRRef args[3];
1063 IRIns *irkey;
1064 Reg tmp;
1065 args[0] = ASMREF_L; /* lua_State *L */
1066 args[1] = ir->op1; /* GCtab *t */
1067 args[2] = ASMREF_TMP1; /* cTValue *key */
1068 asm_setupresult(as, ir, ci); /* TValue * */
1069 asm_gencall(as, ci, args);
1070 tmp = ra_releasetmp(as, ASMREF_TMP1);
1071 irkey = IR(ir->op2);
1072 if (irt_isnum(irkey->t)) {
1073 /* For numbers use the constant itself or a spill slot as a TValue. */
1074 if (irref_isk(ir->op2))
1075 emit_loada(as, tmp, ir_knum(irkey));
1076 else
1077 emit_rmro(as, XO_LEA, tmp|REX_64, RID_ESP, ra_spill(as, irkey));
1078 } else {
1079 /* Otherwise use g->tmptv to hold the TValue. */
1080 if (!irref_isk(ir->op2)) {
1081 Reg src = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, tmp));
1082 emit_movtomro(as, REX_64IR(irkey, src), tmp, 0);
1083 } else if (!irt_ispri(irkey->t)) {
1084 emit_movmroi(as, tmp, 0, irkey->i);
1086 if (!(LJ_64 && irt_islightud(irkey->t)))
1087 emit_movmroi(as, tmp, 4, irt_toitype(irkey->t));
1088 emit_loada(as, tmp, &J2G(as->J)->tmptv);
1092 static void asm_uref(ASMState *as, IRIns *ir)
1094 /* NYI: Check that UREFO is still open and not aliasing a slot. */
1095 Reg dest = ra_dest(as, ir, RSET_GPR);
1096 if (irref_isk(ir->op1)) {
1097 GCfunc *fn = ir_kfunc(IR(ir->op1));
1098 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
1099 emit_rma(as, XO_MOV, dest, v);
1100 } else {
1101 Reg uv = ra_scratch(as, RSET_GPR);
1102 Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
1103 if (ir->o == IR_UREFC) {
1104 emit_rmro(as, XO_LEA, dest, uv, offsetof(GCupval, tv));
1105 asm_guardcc(as, CC_NE);
1106 emit_i8(as, 1);
1107 emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed));
1108 } else {
1109 emit_rmro(as, XO_MOV, dest, uv, offsetof(GCupval, v));
1111 emit_rmro(as, XO_MOV, uv, func,
1112 (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8));
1116 static void asm_fref(ASMState *as, IRIns *ir)
1118 Reg dest = ra_dest(as, ir, RSET_GPR);
1119 asm_fusefref(as, ir, RSET_GPR);
1120 emit_mrm(as, XO_LEA, dest, RID_MRM);
1123 static void asm_strref(ASMState *as, IRIns *ir)
1125 Reg dest = ra_dest(as, ir, RSET_GPR);
1126 asm_fusestrref(as, ir, RSET_GPR);
1127 if (as->mrm.base == RID_NONE)
1128 emit_loadi(as, dest, as->mrm.ofs);
1129 else if (as->mrm.base == dest && as->mrm.idx == RID_NONE)
1130 emit_gri(as, XG_ARITHi(XOg_ADD), dest, as->mrm.ofs);
1131 else
1132 emit_mrm(as, XO_LEA, dest, RID_MRM);
1135 /* -- Loads and stores ---------------------------------------------------- */
1137 static void asm_fxload(ASMState *as, IRIns *ir)
1139 Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
1140 x86Op xo;
1141 if (ir->o == IR_FLOAD)
1142 asm_fusefref(as, ir, RSET_GPR);
1143 else
1144 asm_fusexref(as, ir->op1, RSET_GPR);
1145 /* ir->op2 is ignored -- unaligned loads are ok on x86. */
1146 switch (irt_type(ir->t)) {
1147 case IRT_I8: xo = XO_MOVSXb; break;
1148 case IRT_U8: xo = XO_MOVZXb; break;
1149 case IRT_I16: xo = XO_MOVSXw; break;
1150 case IRT_U16: xo = XO_MOVZXw; break;
1151 case IRT_NUM: xo = XMM_MOVRM(as); break;
1152 case IRT_FLOAT: xo = XO_MOVSS; break;
1153 default:
1154 if (LJ_64 && irt_is64(ir->t))
1155 dest |= REX_64;
1156 else
1157 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
1158 xo = XO_MOV;
1159 break;
1161 emit_mrm(as, xo, dest, RID_MRM);
1164 static void asm_fxstore(ASMState *as, IRIns *ir)
1166 RegSet allow = RSET_GPR;
1167 Reg src = RID_NONE, osrc = RID_NONE;
1168 int32_t k = 0;
1169 /* The IRT_I16/IRT_U16 stores should never be simplified for constant
1170 ** values since mov word [mem], imm16 has a length-changing prefix.
1172 if (irt_isi16(ir->t) || irt_isu16(ir->t) || irt_isfp(ir->t) ||
1173 !asm_isk32(as, ir->op2, &k)) {
1174 RegSet allow8 = irt_isfp(ir->t) ? RSET_FPR :
1175 (irt_isi8(ir->t) || irt_isu8(ir->t)) ? RSET_GPR8 : RSET_GPR;
1176 src = osrc = ra_alloc1(as, ir->op2, allow8);
1177 if (!LJ_64 && !rset_test(allow8, src)) { /* Already in wrong register. */
1178 rset_clear(allow, osrc);
1179 src = ra_scratch(as, allow8);
1181 rset_clear(allow, src);
1183 if (ir->o == IR_FSTORE)
1184 asm_fusefref(as, IR(ir->op1), allow);
1185 else
1186 asm_fusexref(as, ir->op1, allow);
1187 /* ir->op2 is ignored -- unaligned stores are ok on x86. */
1188 if (ra_hasreg(src)) {
1189 x86Op xo;
1190 switch (irt_type(ir->t)) {
1191 case IRT_I8: case IRT_U8: xo = XO_MOVtob; src |= FORCE_REX; break;
1192 case IRT_I16: case IRT_U16: xo = XO_MOVtow; break;
1193 case IRT_NUM: xo = XO_MOVSDto; break;
1194 case IRT_FLOAT: xo = XO_MOVSSto; break;
1195 #if LJ_64
1196 case IRT_LIGHTUD: lua_assert(0); /* NYI: mask 64 bit lightuserdata. */
1197 #endif
1198 default:
1199 if (LJ_64 && irt_is64(ir->t))
1200 src |= REX_64;
1201 else
1202 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
1203 xo = XO_MOVto;
1204 break;
1206 emit_mrm(as, xo, src, RID_MRM);
1207 if (!LJ_64 && src != osrc) {
1208 ra_noweak(as, osrc);
1209 emit_rr(as, XO_MOV, src, osrc);
1211 } else {
1212 if (irt_isi8(ir->t) || irt_isu8(ir->t)) {
1213 emit_i8(as, k);
1214 emit_mrm(as, XO_MOVmib, 0, RID_MRM);
1215 } else {
1216 lua_assert(irt_is64(ir->t) || irt_isint(ir->t) || irt_isu32(ir->t) ||
1217 irt_isaddr(ir->t));
1218 emit_i32(as, k);
1219 emit_mrm(as, XO_MOVmi, REX_64IR(ir, 0), RID_MRM);
1224 #if LJ_64
1225 static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck)
1227 if (ra_used(ir) || typecheck) {
1228 Reg dest = ra_dest(as, ir, RSET_GPR);
1229 if (typecheck) {
1230 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, dest));
1231 asm_guardcc(as, CC_NE);
1232 emit_i8(as, -2);
1233 emit_rr(as, XO_ARITHi8, XOg_CMP, tmp);
1234 emit_shifti(as, XOg_SAR|REX_64, tmp, 47);
1235 emit_rr(as, XO_MOV, tmp|REX_64, dest);
1237 return dest;
1238 } else {
1239 return RID_NONE;
1242 #endif
1244 static void asm_ahuvload(ASMState *as, IRIns *ir)
1246 lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) ||
1247 (LJ_DUALNUM && irt_isint(ir->t)));
1248 #if LJ_64
1249 if (irt_islightud(ir->t)) {
1250 Reg dest = asm_load_lightud64(as, ir, 1);
1251 if (ra_hasreg(dest)) {
1252 asm_fuseahuref(as, ir->op1, RSET_GPR);
1253 emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM);
1255 return;
1256 } else
1257 #endif
1258 if (ra_used(ir)) {
1259 RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR;
1260 Reg dest = ra_dest(as, ir, allow);
1261 asm_fuseahuref(as, ir->op1, RSET_GPR);
1262 emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XMM_MOVRM(as), dest, RID_MRM);
1263 } else {
1264 asm_fuseahuref(as, ir->op1, RSET_GPR);
1266 /* Always do the type check, even if the load result is unused. */
1267 as->mrm.ofs += 4;
1268 asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE);
1269 if (LJ_64 && irt_type(ir->t) >= IRT_NUM) {
1270 lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t));
1271 emit_u32(as, LJ_TISNUM);
1272 emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM);
1273 } else {
1274 emit_i8(as, irt_toitype(ir->t));
1275 emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM);
1279 static void asm_ahustore(ASMState *as, IRIns *ir)
1281 if (irt_isnum(ir->t)) {
1282 Reg src = ra_alloc1(as, ir->op2, RSET_FPR);
1283 asm_fuseahuref(as, ir->op1, RSET_GPR);
1284 emit_mrm(as, XO_MOVSDto, src, RID_MRM);
1285 #if LJ_64
1286 } else if (irt_islightud(ir->t)) {
1287 Reg src = ra_alloc1(as, ir->op2, RSET_GPR);
1288 asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src));
1289 emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM);
1290 #endif
1291 } else {
1292 IRIns *irr = IR(ir->op2);
1293 RegSet allow = RSET_GPR;
1294 Reg src = RID_NONE;
1295 if (!irref_isk(ir->op2)) {
1296 src = ra_alloc1(as, ir->op2, allow);
1297 rset_clear(allow, src);
1299 asm_fuseahuref(as, ir->op1, allow);
1300 if (ra_hasreg(src)) {
1301 emit_mrm(as, XO_MOVto, src, RID_MRM);
1302 } else if (!irt_ispri(irr->t)) {
1303 lua_assert(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t)));
1304 emit_i32(as, irr->i);
1305 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1307 as->mrm.ofs += 4;
1308 emit_i32(as, (int32_t)irt_toitype(ir->t));
1309 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1313 static void asm_sload(ASMState *as, IRIns *ir)
1315 int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
1316 IRType1 t = ir->t;
1317 Reg base;
1318 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */
1319 lua_assert(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK));
1320 lua_assert(LJ_DUALNUM ||
1321 !irt_isint(t) || (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME)));
1322 if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) {
1323 Reg left = ra_scratch(as, RSET_FPR);
1324 asm_tointg(as, ir, left); /* Frees dest reg. Do this before base alloc. */
1325 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1326 emit_rmro(as, XMM_MOVRM(as), left, base, ofs);
1327 t.irt = IRT_NUM; /* Continue with a regular number type check. */
1328 #if LJ_64
1329 } else if (irt_islightud(t)) {
1330 Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK));
1331 if (ra_hasreg(dest)) {
1332 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1333 emit_rmro(as, XO_MOV, dest|REX_64, base, ofs);
1335 return;
1336 #endif
1337 } else if (ra_used(ir)) {
1338 RegSet allow = irt_isnum(t) ? RSET_FPR : RSET_GPR;
1339 Reg dest = ra_dest(as, ir, allow);
1340 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1341 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t));
1342 if ((ir->op2 & IRSLOAD_CONVERT)) {
1343 t.irt = irt_isint(t) ? IRT_NUM : IRT_INT; /* Check for original type. */
1344 emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTSD2SI, dest, base, ofs);
1345 } else if (irt_isnum(t)) {
1346 emit_rmro(as, XMM_MOVRM(as), dest, base, ofs);
1347 } else {
1348 emit_rmro(as, XO_MOV, dest, base, ofs);
1350 } else {
1351 if (!(ir->op2 & IRSLOAD_TYPECHECK))
1352 return; /* No type check: avoid base alloc. */
1353 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1355 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1356 /* Need type check, even if the load result is unused. */
1357 asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE);
1358 if (LJ_64 && irt_type(t) >= IRT_NUM) {
1359 lua_assert(irt_isinteger(t) || irt_isnum(t));
1360 emit_u32(as, LJ_TISNUM);
1361 emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4);
1362 } else {
1363 emit_i8(as, irt_toitype(t));
1364 emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4);
1369 /* -- Allocations --------------------------------------------------------- */
1371 #if LJ_HASFFI
1372 static void asm_cnew(ASMState *as, IRIns *ir)
1374 CTState *cts = ctype_ctsG(J2G(as->J));
1375 CTypeID typeid = (CTypeID)IR(ir->op1)->i;
1376 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ?
1377 lj_ctype_size(cts, typeid) : (CTSize)IR(ir->op2)->i;
1378 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1379 IRRef args[2];
1380 lua_assert(sz != CTSIZE_INVALID);
1382 args[0] = ASMREF_L; /* lua_State *L */
1383 args[1] = ASMREF_TMP1; /* MSize size */
1384 as->gcsteps++;
1385 asm_setupresult(as, ir, ci); /* GCcdata * */
1387 /* Initialize immutable cdata object. */
1388 if (ir->o == IR_CNEWI) {
1389 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1390 #if LJ_64
1391 Reg r64 = sz == 8 ? REX_64 : 0;
1392 if (irref_isk(ir->op2)) {
1393 IRIns *irk = IR(ir->op2);
1394 uint64_t k = irk->o == IR_KINT64 ? ir_k64(irk)->u64 :
1395 (uint64_t)(uint32_t)irk->i;
1396 if (sz == 4 || checki32((int64_t)k)) {
1397 emit_i32(as, (int32_t)k);
1398 emit_rmro(as, XO_MOVmi, r64, RID_RET, sizeof(GCcdata));
1399 } else {
1400 emit_movtomro(as, RID_ECX + r64, RID_RET, sizeof(GCcdata));
1401 emit_loadu64(as, RID_ECX, k);
1403 } else {
1404 Reg r = ra_alloc1(as, ir->op2, allow);
1405 emit_movtomro(as, r + r64, RID_RET, sizeof(GCcdata));
1407 #else
1408 int32_t ofs = sizeof(GCcdata);
1409 if (sz == 8) {
1410 ofs += 4; ir++;
1411 lua_assert(ir->o == IR_HIOP);
1413 do {
1414 if (irref_isk(ir->op2)) {
1415 emit_movmroi(as, RID_RET, ofs, IR(ir->op2)->i);
1416 } else {
1417 Reg r = ra_alloc1(as, ir->op2, allow);
1418 emit_movtomro(as, r, RID_RET, ofs);
1419 rset_clear(allow, r);
1421 if (ofs == sizeof(GCcdata)) break;
1422 ofs -= 4; ir--;
1423 } while (1);
1424 #endif
1425 lua_assert(sz == 4 || sz == 8);
1428 /* Combine initialization of marked, gct and typeid. */
1429 emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked));
1430 emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX,
1431 (int32_t)((~LJ_TCDATA<<8)+(typeid<<16)));
1432 emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES);
1433 emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite);
1435 asm_gencall(as, ci, args);
1436 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata)));
1438 #else
1439 #define asm_cnew(as, ir) ((void)0)
1440 #endif
1442 /* -- Write barriers ------------------------------------------------------ */
1444 static void asm_tbar(ASMState *as, IRIns *ir)
1446 Reg tab = ra_alloc1(as, ir->op1, RSET_GPR);
1447 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab));
1448 MCLabel l_end = emit_label(as);
1449 emit_movtomro(as, tmp, tab, offsetof(GCtab, gclist));
1450 emit_setgl(as, tab, gc.grayagain);
1451 emit_getgl(as, tmp, gc.grayagain);
1452 emit_i8(as, ~LJ_GC_BLACK);
1453 emit_rmro(as, XO_ARITHib, XOg_AND, tab, offsetof(GCtab, marked));
1454 emit_sjcc(as, CC_Z, l_end);
1455 emit_i8(as, LJ_GC_BLACK);
1456 emit_rmro(as, XO_GROUP3b, XOg_TEST, tab, offsetof(GCtab, marked));
1459 static void asm_obar(ASMState *as, IRIns *ir)
1461 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv];
1462 IRRef args[2];
1463 MCLabel l_end;
1464 Reg obj;
1465 /* No need for other object barriers (yet). */
1466 lua_assert(IR(ir->op1)->o == IR_UREFC);
1467 ra_evictset(as, RSET_SCRATCH);
1468 l_end = emit_label(as);
1469 args[0] = ASMREF_TMP1; /* global_State *g */
1470 args[1] = ir->op1; /* TValue *tv */
1471 asm_gencall(as, ci, args);
1472 emit_loada(as, ra_releasetmp(as, ASMREF_TMP1), J2G(as->J));
1473 obj = IR(ir->op1)->r;
1474 emit_sjcc(as, CC_Z, l_end);
1475 emit_i8(as, LJ_GC_WHITES);
1476 if (irref_isk(ir->op2)) {
1477 GCobj *vp = ir_kgc(IR(ir->op2));
1478 emit_rma(as, XO_GROUP3b, XOg_TEST, &vp->gch.marked);
1479 } else {
1480 Reg val = ra_alloc1(as, ir->op2, rset_exclude(RSET_SCRATCH&RSET_GPR, obj));
1481 emit_rmro(as, XO_GROUP3b, XOg_TEST, val, (int32_t)offsetof(GChead, marked));
1483 emit_sjcc(as, CC_Z, l_end);
1484 emit_i8(as, LJ_GC_BLACK);
1485 emit_rmro(as, XO_GROUP3b, XOg_TEST, obj,
1486 (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv));
1489 /* -- FP/int arithmetic and logic operations ------------------------------ */
1491 /* Load reference onto x87 stack. Force a spill to memory if needed. */
1492 static void asm_x87load(ASMState *as, IRRef ref)
1494 IRIns *ir = IR(ref);
1495 if (ir->o == IR_KNUM) {
1496 cTValue *tv = ir_knum(ir);
1497 if (tvispzero(tv)) /* Use fldz only for +0. */
1498 emit_x87op(as, XI_FLDZ);
1499 else if (tvispone(tv))
1500 emit_x87op(as, XI_FLD1);
1501 else
1502 emit_rma(as, XO_FLDq, XOg_FLDq, tv);
1503 } else if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT && !ra_used(ir) &&
1504 !irref_isk(ir->op1) && mayfuse(as, ir->op1)) {
1505 IRIns *iri = IR(ir->op1);
1506 emit_rmro(as, XO_FILDd, XOg_FILDd, RID_ESP, ra_spill(as, iri));
1507 } else {
1508 emit_mrm(as, XO_FLDq, XOg_FLDq, asm_fuseload(as, ref, RSET_EMPTY));
1512 /* Try to rejoin pow from EXP2, MUL and LOG2 (if still unsplit). */
1513 static int fpmjoin_pow(ASMState *as, IRIns *ir)
1515 IRIns *irp = IR(ir->op1);
1516 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) {
1517 IRIns *irpp = IR(irp->op1);
1518 if (irpp == ir-2 && irpp->o == IR_FPMATH &&
1519 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) {
1520 /* The modified regs must match with the *.dasc implementation. */
1521 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1522 IRIns *irx;
1523 if (ra_hasreg(ir->r))
1524 rset_clear(drop, ir->r); /* Dest reg handled below. */
1525 ra_evictset(as, drop);
1526 ra_destreg(as, ir, RID_XMM0);
1527 emit_call(as, lj_vm_pow_sse);
1528 irx = IR(irpp->op1);
1529 if (ra_noreg(irx->r) && ra_gethint(irx->r) == RID_XMM1)
1530 irx->r = RID_INIT; /* Avoid allocating xmm1 for x. */
1531 ra_left(as, RID_XMM0, irpp->op1);
1532 ra_left(as, RID_XMM1, irp->op2);
1533 return 1;
1536 return 0;
1539 static void asm_fpmath(ASMState *as, IRIns *ir)
1541 IRFPMathOp fpm = ir->o == IR_FPMATH ? (IRFPMathOp)ir->op2 : IRFPM_OTHER;
1542 if (fpm == IRFPM_SQRT) {
1543 Reg dest = ra_dest(as, ir, RSET_FPR);
1544 Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
1545 emit_mrm(as, XO_SQRTSD, dest, left);
1546 } else if (fpm <= IRFPM_TRUNC) {
1547 if (as->flags & JIT_F_SSE4_1) { /* SSE4.1 has a rounding instruction. */
1548 Reg dest = ra_dest(as, ir, RSET_FPR);
1549 Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
1550 /* ROUNDSD has a 4-byte opcode which doesn't fit in x86Op.
1551 ** Let's pretend it's a 3-byte opcode, and compensate afterwards.
1552 ** This is atrocious, but the alternatives are much worse.
1554 /* Round down/up/trunc == 1001/1010/1011. */
1555 emit_i8(as, 0x09 + fpm);
1556 emit_mrm(as, XO_ROUNDSD, dest, left);
1557 if (LJ_64 && as->mcp[1] != (MCode)(XO_ROUNDSD >> 16)) {
1558 as->mcp[0] = as->mcp[1]; as->mcp[1] = 0x0f; /* Swap 0F and REX. */
1560 *--as->mcp = 0x66; /* 1st byte of ROUNDSD opcode. */
1561 } else { /* Call helper functions for SSE2 variant. */
1562 /* The modified regs must match with the *.dasc implementation. */
1563 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1564 if (ra_hasreg(ir->r))
1565 rset_clear(drop, ir->r); /* Dest reg handled below. */
1566 ra_evictset(as, drop);
1567 ra_destreg(as, ir, RID_XMM0);
1568 emit_call(as, fpm == IRFPM_FLOOR ? lj_vm_floor_sse :
1569 fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse);
1570 ra_left(as, RID_XMM0, ir->op1);
1572 } else if (fpm == IRFPM_EXP2 && fpmjoin_pow(as, ir)) {
1573 /* Rejoined to pow(). */
1574 } else { /* Handle x87 ops. */
1575 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
1576 Reg dest = ir->r;
1577 if (ra_hasreg(dest)) {
1578 ra_free(as, dest);
1579 ra_modified(as, dest);
1580 emit_rmro(as, XMM_MOVRM(as), dest, RID_ESP, ofs);
1582 emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs);
1583 switch (fpm) { /* st0 = lj_vm_*(st0) */
1584 case IRFPM_EXP: emit_call(as, lj_vm_exp_x87); break;
1585 case IRFPM_EXP2: emit_call(as, lj_vm_exp2_x87); break;
1586 case IRFPM_SIN: emit_x87op(as, XI_FSIN); break;
1587 case IRFPM_COS: emit_x87op(as, XI_FCOS); break;
1588 case IRFPM_TAN: emit_x87op(as, XI_FPOP); emit_x87op(as, XI_FPTAN); break;
1589 case IRFPM_LOG: case IRFPM_LOG2: case IRFPM_LOG10:
1590 /* Note: the use of fyl2xp1 would be pointless here. When computing
1591 ** log(1.0+eps) the precision is already lost after 1.0 is added.
1592 ** Subtracting 1.0 won't recover it. OTOH math.log1p would make sense.
1594 emit_x87op(as, XI_FYL2X); break;
1595 case IRFPM_OTHER:
1596 switch (ir->o) {
1597 case IR_ATAN2:
1598 emit_x87op(as, XI_FPATAN); asm_x87load(as, ir->op2); break;
1599 case IR_LDEXP:
1600 emit_x87op(as, XI_FPOP1); emit_x87op(as, XI_FSCALE); break;
1601 default: lua_assert(0); break;
1603 break;
1604 default: lua_assert(0); break;
1606 asm_x87load(as, ir->op1);
1607 switch (fpm) {
1608 case IRFPM_LOG: emit_x87op(as, XI_FLDLN2); break;
1609 case IRFPM_LOG2: emit_x87op(as, XI_FLD1); break;
1610 case IRFPM_LOG10: emit_x87op(as, XI_FLDLG2); break;
1611 case IRFPM_OTHER:
1612 if (ir->o == IR_LDEXP) asm_x87load(as, ir->op2);
1613 break;
1614 default: break;
1619 static void asm_fppowi(ASMState *as, IRIns *ir)
1621 /* The modified regs must match with the *.dasc implementation. */
1622 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1623 if (ra_hasreg(ir->r))
1624 rset_clear(drop, ir->r); /* Dest reg handled below. */
1625 ra_evictset(as, drop);
1626 ra_destreg(as, ir, RID_XMM0);
1627 emit_call(as, lj_vm_powi_sse);
1628 ra_left(as, RID_XMM0, ir->op1);
1629 ra_left(as, RID_EAX, ir->op2);
1632 #if LJ_64 && LJ_HASFFI
1633 static void asm_arith64(ASMState *as, IRIns *ir, IRCallID id)
1635 const CCallInfo *ci = &lj_ir_callinfo[id];
1636 IRRef args[2];
1637 args[0] = ir->op1;
1638 args[1] = ir->op2;
1639 asm_setupresult(as, ir, ci);
1640 asm_gencall(as, ci, args);
1642 #endif
1644 static void asm_intmod(ASMState *as, IRIns *ir)
1646 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_vm_modi];
1647 IRRef args[2];
1648 args[0] = ir->op1;
1649 args[1] = ir->op2;
1650 asm_setupresult(as, ir, ci);
1651 asm_gencall(as, ci, args);
1654 static int asm_swapops(ASMState *as, IRIns *ir)
1656 IRIns *irl = IR(ir->op1);
1657 IRIns *irr = IR(ir->op2);
1658 lua_assert(ra_noreg(irr->r));
1659 if (!irm_iscomm(lj_ir_mode[ir->o]))
1660 return 0; /* Can't swap non-commutative operations. */
1661 if (irref_isk(ir->op2))
1662 return 0; /* Don't swap constants to the left. */
1663 if (ra_hasreg(irl->r))
1664 return 1; /* Swap if left already has a register. */
1665 if (ra_samehint(ir->r, irr->r))
1666 return 1; /* Swap if dest and right have matching hints. */
1667 if (as->curins > as->loopref) { /* In variant part? */
1668 if (ir->op2 < as->loopref && !irt_isphi(irr->t))
1669 return 0; /* Keep invariants on the right. */
1670 if (ir->op1 < as->loopref && !irt_isphi(irl->t))
1671 return 1; /* Swap invariants to the right. */
1673 if (opisfusableload(irl->o))
1674 return 1; /* Swap fusable loads to the right. */
1675 return 0; /* Otherwise don't swap. */
1678 static void asm_fparith(ASMState *as, IRIns *ir, x86Op xo)
1680 IRRef lref = ir->op1;
1681 IRRef rref = ir->op2;
1682 RegSet allow = RSET_FPR;
1683 Reg dest;
1684 Reg right = IR(rref)->r;
1685 if (ra_hasreg(right)) {
1686 rset_clear(allow, right);
1687 ra_noweak(as, right);
1689 dest = ra_dest(as, ir, allow);
1690 if (lref == rref) {
1691 right = dest;
1692 } else if (ra_noreg(right)) {
1693 if (asm_swapops(as, ir)) {
1694 IRRef tmp = lref; lref = rref; rref = tmp;
1696 right = asm_fuseload(as, rref, rset_clear(allow, dest));
1698 emit_mrm(as, xo, dest, right);
1699 ra_left(as, dest, lref);
1702 static void asm_intarith(ASMState *as, IRIns *ir, x86Arith xa)
1704 IRRef lref = ir->op1;
1705 IRRef rref = ir->op2;
1706 RegSet allow = RSET_GPR;
1707 Reg dest, right;
1708 int32_t k = 0;
1709 if (as->flagmcp == as->mcp) { /* Drop test r,r instruction. */
1710 as->flagmcp = NULL;
1711 as->mcp += (LJ_64 && *as->mcp != XI_TEST) ? 3 : 2;
1713 right = IR(rref)->r;
1714 if (ra_hasreg(right)) {
1715 rset_clear(allow, right);
1716 ra_noweak(as, right);
1718 dest = ra_dest(as, ir, allow);
1719 if (lref == rref) {
1720 right = dest;
1721 } else if (ra_noreg(right) && !asm_isk32(as, rref, &k)) {
1722 if (asm_swapops(as, ir)) {
1723 IRRef tmp = lref; lref = rref; rref = tmp;
1725 right = asm_fuseload(as, rref, rset_clear(allow, dest));
1727 if (irt_isguard(ir->t)) /* For IR_ADDOV etc. */
1728 asm_guardcc(as, CC_O);
1729 if (xa != XOg_X_IMUL) {
1730 if (ra_hasreg(right))
1731 emit_mrm(as, XO_ARITH(xa), REX_64IR(ir, dest), right);
1732 else
1733 emit_gri(as, XG_ARITHi(xa), REX_64IR(ir, dest), k);
1734 } else if (ra_hasreg(right)) { /* IMUL r, mrm. */
1735 emit_mrm(as, XO_IMUL, REX_64IR(ir, dest), right);
1736 } else { /* IMUL r, r, k. */
1737 /* NYI: use lea/shl/add/sub (FOLD only does 2^k) depending on CPU. */
1738 Reg left = asm_fuseload(as, lref, RSET_GPR);
1739 x86Op xo;
1740 if (checki8(k)) { emit_i8(as, k); xo = XO_IMULi8;
1741 } else { emit_i32(as, k); xo = XO_IMULi; }
1742 emit_mrm(as, xo, REX_64IR(ir, dest), left);
1743 return;
1745 ra_left(as, dest, lref);
1748 /* LEA is really a 4-operand ADD with an independent destination register,
1749 ** up to two source registers and an immediate. One register can be scaled
1750 ** by 1, 2, 4 or 8. This can be used to avoid moves or to fuse several
1751 ** instructions.
1753 ** Currently only a few common cases are supported:
1754 ** - 3-operand ADD: y = a+b; y = a+k with a and b already allocated
1755 ** - Left ADD fusion: y = (a+b)+k; y = (a+k)+b
1756 ** - Right ADD fusion: y = a+(b+k)
1757 ** The ommited variants have already been reduced by FOLD.
1759 ** There are more fusion opportunities, like gathering shifts or joining
1760 ** common references. But these are probably not worth the trouble, since
1761 ** array indexing is not decomposed and already makes use of all fields
1762 ** of the ModRM operand.
1764 static int asm_lea(ASMState *as, IRIns *ir)
1766 IRIns *irl = IR(ir->op1);
1767 IRIns *irr = IR(ir->op2);
1768 RegSet allow = RSET_GPR;
1769 Reg dest;
1770 as->mrm.base = as->mrm.idx = RID_NONE;
1771 as->mrm.scale = XM_SCALE1;
1772 as->mrm.ofs = 0;
1773 if (ra_hasreg(irl->r)) {
1774 rset_clear(allow, irl->r);
1775 ra_noweak(as, irl->r);
1776 as->mrm.base = irl->r;
1777 if (irref_isk(ir->op2) || ra_hasreg(irr->r)) {
1778 /* The PHI renaming logic does a better job in some cases. */
1779 if (ra_hasreg(ir->r) &&
1780 ((irt_isphi(irl->t) && as->phireg[ir->r] == ir->op1) ||
1781 (irt_isphi(irr->t) && as->phireg[ir->r] == ir->op2)))
1782 return 0;
1783 if (irref_isk(ir->op2)) {
1784 as->mrm.ofs = irr->i;
1785 } else {
1786 rset_clear(allow, irr->r);
1787 ra_noweak(as, irr->r);
1788 as->mrm.idx = irr->r;
1790 } else if (irr->o == IR_ADD && mayfuse(as, ir->op2) &&
1791 irref_isk(irr->op2)) {
1792 Reg idx = ra_alloc1(as, irr->op1, allow);
1793 rset_clear(allow, idx);
1794 as->mrm.idx = (uint8_t)idx;
1795 as->mrm.ofs = IR(irr->op2)->i;
1796 } else {
1797 return 0;
1799 } else if (ir->op1 != ir->op2 && irl->o == IR_ADD && mayfuse(as, ir->op1) &&
1800 (irref_isk(ir->op2) || irref_isk(irl->op2))) {
1801 Reg idx, base = ra_alloc1(as, irl->op1, allow);
1802 rset_clear(allow, base);
1803 as->mrm.base = (uint8_t)base;
1804 if (irref_isk(ir->op2)) {
1805 as->mrm.ofs = irr->i;
1806 idx = ra_alloc1(as, irl->op2, allow);
1807 } else {
1808 as->mrm.ofs = IR(irl->op2)->i;
1809 idx = ra_alloc1(as, ir->op2, allow);
1811 rset_clear(allow, idx);
1812 as->mrm.idx = (uint8_t)idx;
1813 } else {
1814 return 0;
1816 dest = ra_dest(as, ir, allow);
1817 emit_mrm(as, XO_LEA, dest, RID_MRM);
1818 return 1; /* Success. */
1821 static void asm_add(ASMState *as, IRIns *ir)
1823 if (irt_isnum(ir->t))
1824 asm_fparith(as, ir, XO_ADDSD);
1825 else if ((as->flags & JIT_F_LEA_AGU) || as->flagmcp == as->mcp ||
1826 irt_is64(ir->t) || !asm_lea(as, ir))
1827 asm_intarith(as, ir, XOg_ADD);
1830 static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg)
1832 Reg dest = ra_dest(as, ir, RSET_GPR);
1833 emit_rr(as, XO_GROUP3, REX_64IR(ir, xg), dest);
1834 ra_left(as, dest, ir->op1);
1837 static void asm_min_max(ASMState *as, IRIns *ir, int cc)
1839 Reg right, dest = ra_dest(as, ir, RSET_GPR);
1840 IRRef lref = ir->op1, rref = ir->op2;
1841 if (irref_isk(rref)) { lref = rref; rref = ir->op1; }
1842 right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, dest));
1843 emit_rr(as, XO_CMOV + (cc<<24), REX_64IR(ir, dest), right);
1844 emit_rr(as, XO_CMP, REX_64IR(ir, dest), right);
1845 ra_left(as, dest, lref);
1848 static void asm_bitswap(ASMState *as, IRIns *ir)
1850 Reg dest = ra_dest(as, ir, RSET_GPR);
1851 as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24),
1852 REX_64IR(ir, dest), 0, 0, as->mcp, 1);
1853 ra_left(as, dest, ir->op1);
1856 static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs)
1858 IRRef rref = ir->op2;
1859 IRIns *irr = IR(rref);
1860 Reg dest;
1861 if (irref_isk(rref)) { /* Constant shifts. */
1862 int shift;
1863 dest = ra_dest(as, ir, RSET_GPR);
1864 shift = irr->i & (irt_is64(ir->t) ? 63 : 31);
1865 switch (shift) {
1866 case 0: break;
1867 case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break;
1868 default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break;
1870 } else { /* Variable shifts implicitly use register cl (i.e. ecx). */
1871 Reg right;
1872 dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX));
1873 if (dest == RID_ECX) {
1874 dest = ra_scratch(as, rset_exclude(RSET_GPR, RID_ECX));
1875 emit_rr(as, XO_MOV, RID_ECX, dest);
1877 right = irr->r;
1878 if (ra_noreg(right))
1879 right = ra_allocref(as, rref, RID2RSET(RID_ECX));
1880 else if (right != RID_ECX)
1881 ra_scratch(as, RID2RSET(RID_ECX));
1882 emit_rr(as, XO_SHIFTcl, REX_64IR(ir, xs), dest);
1883 if (right != RID_ECX) {
1884 ra_noweak(as, right);
1885 emit_rr(as, XO_MOV, RID_ECX, right);
1888 ra_left(as, dest, ir->op1);
1890 ** Note: avoid using the flags resulting from a shift or rotate!
1891 ** All of them cause a partial flag stall, except for r,1 shifts
1892 ** (but not rotates). And a shift count of 0 leaves the flags unmodified.
1896 /* -- Comparisons --------------------------------------------------------- */
1898 /* Virtual flags for unordered FP comparisons. */
1899 #define VCC_U 0x1000 /* Unordered. */
1900 #define VCC_P 0x2000 /* Needs extra CC_P branch. */
1901 #define VCC_S 0x4000 /* Swap avoids CC_P branch. */
1902 #define VCC_PS (VCC_P|VCC_S)
1904 /* Map of comparisons to flags. ORDER IR. */
1905 #define COMPFLAGS(ci, cin, cu, cf) ((ci)+((cu)<<4)+((cin)<<8)+(cf))
1906 static const uint16_t asm_compmap[IR_ABC+1] = {
1907 /* signed non-eq unsigned flags */
1908 /* LT */ COMPFLAGS(CC_GE, CC_G, CC_AE, VCC_PS),
1909 /* GE */ COMPFLAGS(CC_L, CC_L, CC_B, 0),
1910 /* LE */ COMPFLAGS(CC_G, CC_G, CC_A, VCC_PS),
1911 /* GT */ COMPFLAGS(CC_LE, CC_L, CC_BE, 0),
1912 /* ULT */ COMPFLAGS(CC_AE, CC_A, CC_AE, VCC_U),
1913 /* UGE */ COMPFLAGS(CC_B, CC_B, CC_B, VCC_U|VCC_PS),
1914 /* ULE */ COMPFLAGS(CC_A, CC_A, CC_A, VCC_U),
1915 /* UGT */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS),
1916 /* EQ */ COMPFLAGS(CC_NE, CC_NE, CC_NE, VCC_P),
1917 /* NE */ COMPFLAGS(CC_E, CC_E, CC_E, VCC_U|VCC_P),
1918 /* ABC */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS) /* Same as UGT. */
1921 /* FP and integer comparisons. */
1922 static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc)
1924 if (irt_isnum(ir->t)) {
1925 IRRef lref = ir->op1;
1926 IRRef rref = ir->op2;
1927 Reg left, right;
1928 MCLabel l_around;
1930 ** An extra CC_P branch is required to preserve ordered/unordered
1931 ** semantics for FP comparisons. This can be avoided by swapping
1932 ** the operands and inverting the condition (except for EQ and UNE).
1933 ** So always try to swap if possible.
1935 ** Another option would be to swap operands to achieve better memory
1936 ** operand fusion. But it's unlikely that this outweighs the cost
1937 ** of the extra branches.
1939 if (cc & VCC_S) { /* Swap? */
1940 IRRef tmp = lref; lref = rref; rref = tmp;
1941 cc ^= (VCC_PS|(5<<4)); /* A <-> B, AE <-> BE, PS <-> none */
1943 left = ra_alloc1(as, lref, RSET_FPR);
1944 right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left));
1945 l_around = emit_label(as);
1946 asm_guardcc(as, cc >> 4);
1947 if (cc & VCC_P) { /* Extra CC_P branch required? */
1948 if (!(cc & VCC_U)) {
1949 asm_guardcc(as, CC_P); /* Branch to exit for ordered comparisons. */
1950 } else if (l_around != as->invmcp) {
1951 emit_sjcc(as, CC_P, l_around); /* Branch around for unordered. */
1952 } else {
1953 /* Patched to mcloop by asm_loop_fixup. */
1954 as->loopinv = 2;
1955 if (as->realign)
1956 emit_sjcc(as, CC_P, as->mcp);
1957 else
1958 emit_jcc(as, CC_P, as->mcp);
1961 emit_mrm(as, XO_UCOMISD, left, right);
1962 } else {
1963 IRRef lref = ir->op1, rref = ir->op2;
1964 IROp leftop = (IROp)(IR(lref)->o);
1965 Reg r64 = REX_64IR(ir, 0);
1966 int32_t imm = 0;
1967 lua_assert(irt_is64(ir->t) || irt_isint(ir->t) || irt_isaddr(ir->t));
1968 /* Swap constants (only for ABC) and fusable loads to the right. */
1969 if (irref_isk(lref) || (!irref_isk(rref) && opisfusableload(leftop))) {
1970 if ((cc & 0xc) == 0xc) cc ^= 3; /* L <-> G, LE <-> GE */
1971 else if ((cc & 0xa) == 0x2) cc ^= 5; /* A <-> B, AE <-> BE */
1972 lref = ir->op2; rref = ir->op1;
1974 if (asm_isk32(as, rref, &imm)) {
1975 IRIns *irl = IR(lref);
1976 /* Check wether we can use test ins. Not for unsigned, since CF=0. */
1977 int usetest = (imm == 0 && (cc & 0xa) != 0x2);
1978 if (usetest && irl->o == IR_BAND && irl+1 == ir && !ra_used(irl)) {
1979 /* Combine comp(BAND(ref, r/imm), 0) into test mrm, r/imm. */
1980 Reg right, left = RID_NONE;
1981 RegSet allow = RSET_GPR;
1982 if (!asm_isk32(as, irl->op2, &imm)) {
1983 left = ra_alloc1(as, irl->op2, allow);
1984 rset_clear(allow, left);
1985 } else { /* Try to Fuse IRT_I8/IRT_U8 loads, too. See below. */
1986 IRIns *irll = IR(irl->op1);
1987 if (opisfusableload((IROp)irll->o) &&
1988 (irt_isi8(irll->t) || irt_isu8(irll->t))) {
1989 IRType1 origt = irll->t; /* Temporarily flip types. */
1990 irll->t.irt = (irll->t.irt & ~IRT_TYPE) | IRT_INT;
1991 as->curins--; /* Skip to BAND to avoid failing in noconflict(). */
1992 right = asm_fuseload(as, irl->op1, RSET_GPR);
1993 as->curins++;
1994 irll->t = origt;
1995 if (right != RID_MRM) goto test_nofuse;
1996 /* Fusion succeeded, emit test byte mrm, imm8. */
1997 asm_guardcc(as, cc);
1998 emit_i8(as, (imm & 0xff));
1999 emit_mrm(as, XO_GROUP3b, XOg_TEST, RID_MRM);
2000 return;
2003 as->curins--; /* Skip to BAND to avoid failing in noconflict(). */
2004 right = asm_fuseload(as, irl->op1, allow);
2005 as->curins++; /* Undo the above. */
2006 test_nofuse:
2007 asm_guardcc(as, cc);
2008 if (ra_noreg(left)) {
2009 emit_i32(as, imm);
2010 emit_mrm(as, XO_GROUP3, r64 + XOg_TEST, right);
2011 } else {
2012 emit_mrm(as, XO_TEST, r64 + left, right);
2014 } else {
2015 Reg left;
2016 if (opisfusableload((IROp)irl->o) &&
2017 ((irt_isu8(irl->t) && checku8(imm)) ||
2018 ((irt_isi8(irl->t) || irt_isi16(irl->t)) && checki8(imm)) ||
2019 (irt_isu16(irl->t) && checku16(imm) && checki8((int16_t)imm)))) {
2020 /* Only the IRT_INT case is fused by asm_fuseload.
2021 ** The IRT_I8/IRT_U8 loads and some IRT_I16/IRT_U16 loads
2022 ** are handled here.
2023 ** Note that cmp word [mem], imm16 should not be generated,
2024 ** since it has a length-changing prefix. Compares of a word
2025 ** against a sign-extended imm8 are ok, however.
2027 IRType1 origt = irl->t; /* Temporarily flip types. */
2028 irl->t.irt = (irl->t.irt & ~IRT_TYPE) | IRT_INT;
2029 left = asm_fuseload(as, lref, RSET_GPR);
2030 irl->t = origt;
2031 if (left == RID_MRM) { /* Fusion succeeded? */
2032 if (irt_isu8(irl->t) || irt_isu16(irl->t))
2033 cc >>= 4; /* Need unsigned compare. */
2034 asm_guardcc(as, cc);
2035 emit_i8(as, imm);
2036 emit_mrm(as, (irt_isi8(origt) || irt_isu8(origt)) ?
2037 XO_ARITHib : XO_ARITHiw8, r64 + XOg_CMP, RID_MRM);
2038 return;
2039 } /* Otherwise handle register case as usual. */
2040 } else {
2041 left = asm_fuseload(as, lref, RSET_GPR);
2043 asm_guardcc(as, cc);
2044 if (usetest && left != RID_MRM) {
2045 /* Use test r,r instead of cmp r,0. */
2046 emit_rr(as, XO_TEST, r64 + left, left);
2047 if (irl+1 == ir) /* Referencing previous ins? */
2048 as->flagmcp = as->mcp; /* Set flag to drop test r,r if possible. */
2049 } else {
2050 emit_gmrmi(as, XG_ARITHi(XOg_CMP), r64 + left, imm);
2053 } else {
2054 Reg left = ra_alloc1(as, lref, RSET_GPR);
2055 Reg right = asm_fuseload(as, rref, rset_exclude(RSET_GPR, left));
2056 asm_guardcc(as, cc);
2057 emit_mrm(as, XO_CMP, r64 + left, right);
2062 #if LJ_32 && LJ_HASFFI
2063 /* 64 bit integer comparisons in 32 bit mode. */
2064 static void asm_comp_int64(ASMState *as, IRIns *ir)
2066 uint32_t cc = asm_compmap[(ir-1)->o];
2067 RegSet allow = RSET_GPR;
2068 Reg lefthi = RID_NONE, leftlo = RID_NONE;
2069 Reg righthi = RID_NONE, rightlo = RID_NONE;
2070 MCLabel l_around;
2071 x86ModRM mrm;
2073 as->curins--; /* Skip loword ins. Avoids failing in noconflict(), too. */
2075 /* Allocate/fuse hiword operands. */
2076 if (irref_isk(ir->op2)) {
2077 lefthi = asm_fuseload(as, ir->op1, allow);
2078 } else {
2079 lefthi = ra_alloc1(as, ir->op1, allow);
2080 righthi = asm_fuseload(as, ir->op2, allow);
2081 if (righthi == RID_MRM) {
2082 if (as->mrm.base != RID_NONE) rset_clear(allow, as->mrm.base);
2083 if (as->mrm.idx != RID_NONE) rset_clear(allow, as->mrm.idx);
2084 } else {
2085 rset_clear(allow, righthi);
2088 mrm = as->mrm; /* Save state for hiword instruction. */
2090 /* Allocate/fuse loword operands. */
2091 if (irref_isk((ir-1)->op2)) {
2092 leftlo = asm_fuseload(as, (ir-1)->op1, allow);
2093 } else {
2094 leftlo = ra_alloc1(as, (ir-1)->op1, allow);
2095 rightlo = asm_fuseload(as, (ir-1)->op2, allow);
2096 if (rightlo == RID_MRM) {
2097 if (as->mrm.base != RID_NONE) rset_clear(allow, as->mrm.base);
2098 if (as->mrm.idx != RID_NONE) rset_clear(allow, as->mrm.idx);
2099 } else {
2100 rset_clear(allow, rightlo);
2104 /* All register allocations must be performed _before_ this point. */
2105 l_around = emit_label(as);
2106 as->invmcp = as->flagmcp = NULL; /* Cannot use these optimizations. */
2108 /* Loword comparison and branch. */
2109 asm_guardcc(as, cc >> 4); /* Always use unsigned compare for loword. */
2110 if (ra_noreg(rightlo)) {
2111 int32_t imm = IR((ir-1)->op2)->i;
2112 if (imm == 0 && ((cc >> 4) & 0xa) != 0x2 && leftlo != RID_MRM)
2113 emit_rr(as, XO_TEST, leftlo, leftlo);
2114 else
2115 emit_gmrmi(as, XG_ARITHi(XOg_CMP), leftlo, imm);
2116 } else {
2117 emit_mrm(as, XO_CMP, leftlo, rightlo);
2120 /* Hiword comparison and branches. */
2121 if ((cc & 15) != CC_NE)
2122 emit_sjcc(as, CC_NE, l_around); /* Hiword unequal: skip loword compare. */
2123 if ((cc & 15) != CC_E)
2124 asm_guardcc(as, cc >> 8); /* Hiword compare without equality check. */
2125 as->mrm = mrm; /* Restore state. */
2126 if (ra_noreg(righthi)) {
2127 int32_t imm = IR(ir->op2)->i;
2128 if (imm == 0 && (cc & 0xa) != 0x2 && lefthi != RID_MRM)
2129 emit_rr(as, XO_TEST, lefthi, lefthi);
2130 else
2131 emit_gmrmi(as, XG_ARITHi(XOg_CMP), lefthi, imm);
2132 } else {
2133 emit_mrm(as, XO_CMP, lefthi, righthi);
2136 #endif
2138 /* -- Support for 64 bit ops in 32 bit mode ------------------------------- */
2140 /* Hiword op of a split 64 bit op. Previous op must be the loword op. */
2141 static void asm_hiop(ASMState *as, IRIns *ir)
2143 #if LJ_32 && LJ_HASFFI
2144 /* HIOP is marked as a store because it needs its own DCE logic. */
2145 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */
2146 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1;
2147 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */
2148 if (usehi || uselo) {
2149 if (irt_isfp(ir->t))
2150 asm_conv_fp_int64(as, ir);
2151 else
2152 asm_conv_int64_fp(as, ir);
2154 as->curins--; /* Always skip the CONV. */
2155 return;
2156 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */
2157 asm_comp_int64(as, ir);
2158 return;
2160 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */
2161 switch ((ir-1)->o) {
2162 case IR_ADD:
2163 as->flagmcp = NULL;
2164 as->curins--;
2165 asm_intarith(as, ir, XOg_ADC);
2166 asm_intarith(as, ir-1, XOg_ADD);
2167 break;
2168 case IR_SUB:
2169 as->flagmcp = NULL;
2170 as->curins--;
2171 asm_intarith(as, ir, XOg_SBB);
2172 asm_intarith(as, ir-1, XOg_SUB);
2173 break;
2174 case IR_NEG: {
2175 Reg dest = ra_dest(as, ir, RSET_GPR);
2176 emit_rr(as, XO_GROUP3, XOg_NEG, dest);
2177 emit_i8(as, 0);
2178 emit_rr(as, XO_ARITHi8, XOg_ADC, dest);
2179 ra_left(as, dest, ir->op1);
2180 as->curins--;
2181 asm_neg_not(as, ir-1, XOg_NEG);
2182 break;
2184 case IR_CALLN:
2185 case IR_CALLXS:
2186 ra_destreg(as, ir, RID_RETHI);
2187 if (!uselo)
2188 ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark call as used. */
2189 break;
2190 case IR_CNEWI:
2191 /* Nothing to do here. Handled by CNEWI itself. */
2192 break;
2193 default: lua_assert(0); break;
2195 #else
2196 UNUSED(as); UNUSED(ir); lua_assert(0); /* Unused on x64 or without FFI. */
2197 #endif
2200 /* -- Stack handling ------------------------------------------------------ */
2202 /* Check Lua stack size for overflow. Use exit handler as fallback. */
2203 static void asm_stack_check(ASMState *as, BCReg topslot,
2204 IRIns *irp, RegSet allow, ExitNo exitno)
2206 /* Try to get an unused temp. register, otherwise spill/restore eax. */
2207 Reg pbase = irp ? irp->r : RID_BASE;
2208 Reg r = allow ? rset_pickbot(allow) : RID_EAX;
2209 emit_jcc(as, CC_B, exitstub_addr(as->J, exitno));
2210 if (allow == RSET_EMPTY) /* Restore temp. register. */
2211 emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0);
2212 else
2213 ra_modified(as, r);
2214 emit_gri(as, XG_ARITHi(XOg_CMP), r, (int32_t)(8*topslot));
2215 if (ra_hasreg(pbase) && pbase != r)
2216 emit_rr(as, XO_ARITH(XOg_SUB), r, pbase);
2217 else
2218 emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE,
2219 ptr2addr(&J2G(as->J)->jit_base));
2220 emit_rmro(as, XO_MOV, r, r, offsetof(lua_State, maxstack));
2221 emit_getgl(as, r, jit_L);
2222 if (allow == RSET_EMPTY) /* Spill temp. register. */
2223 emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0);
2226 /* Restore Lua stack from on-trace state. */
2227 static void asm_stack_restore(ASMState *as, SnapShot *snap)
2229 SnapEntry *map = &as->T->snapmap[snap->mapofs];
2230 MSize n, nent = snap->nent;
2231 SnapEntry *flinks = map + nent + snap->depth;
2232 /* Store the value of all modified slots to the Lua stack. */
2233 for (n = 0; n < nent; n++) {
2234 SnapEntry sn = map[n];
2235 BCReg s = snap_slot(sn);
2236 int32_t ofs = 8*((int32_t)s-1);
2237 IRRef ref = snap_ref(sn);
2238 IRIns *ir = IR(ref);
2239 if ((sn & SNAP_NORESTORE))
2240 continue;
2241 if (irt_isnum(ir->t)) {
2242 Reg src = ra_alloc1(as, ref, RSET_FPR);
2243 emit_rmro(as, XO_MOVSDto, src, RID_BASE, ofs);
2244 } else {
2245 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) ||
2246 (LJ_DUALNUM && irt_isinteger(ir->t)));
2247 if (!irref_isk(ref)) {
2248 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE));
2249 emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs);
2250 } else if (!irt_ispri(ir->t)) {
2251 emit_movmroi(as, RID_BASE, ofs, ir->i);
2253 if ((sn & (SNAP_CONT|SNAP_FRAME))) {
2254 if (s != 0) /* Do not overwrite link to previous frame. */
2255 emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--));
2256 } else {
2257 if (!(LJ_64 && irt_islightud(ir->t)))
2258 emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t));
2261 checkmclim(as);
2263 lua_assert(map + nent == flinks);
2266 /* -- GC handling --------------------------------------------------------- */
2268 /* Check GC threshold and do one or more GC steps. */
2269 static void asm_gc_check(ASMState *as)
2271 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit];
2272 IRRef args[2];
2273 MCLabel l_end;
2274 Reg tmp;
2275 ra_evictset(as, RSET_SCRATCH);
2276 l_end = emit_label(as);
2277 /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */
2278 asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */
2279 emit_rr(as, XO_TEST, RID_RET, RID_RET);
2280 args[0] = ASMREF_TMP1; /* global_State *g */
2281 args[1] = ASMREF_TMP2; /* MSize steps */
2282 asm_gencall(as, ci, args);
2283 tmp = ra_releasetmp(as, ASMREF_TMP1);
2284 emit_loada(as, tmp, J2G(as->J));
2285 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), (int32_t)as->gcsteps);
2286 /* Jump around GC step if GC total < GC threshold. */
2287 emit_sjcc(as, CC_B, l_end);
2288 emit_opgl(as, XO_ARITH(XOg_CMP), tmp, gc.threshold);
2289 emit_getgl(as, tmp, gc.total);
2290 as->gcsteps = 0;
2291 checkmclim(as);
2294 /* -- Loop handling ------------------------------------------------------- */
2296 /* Fixup the loop branch. */
2297 static void asm_loop_fixup(ASMState *as)
2299 MCode *p = as->mctop;
2300 MCode *target = as->mcp;
2301 if (as->realign) { /* Realigned loops use short jumps. */
2302 as->realign = NULL; /* Stop another retry. */
2303 lua_assert(((intptr_t)target & 15) == 0);
2304 if (as->loopinv) { /* Inverted loop branch? */
2305 p -= 5;
2306 p[0] = XI_JMP;
2307 lua_assert(target - p >= -128);
2308 p[-1] = (MCode)(target - p); /* Patch sjcc. */
2309 if (as->loopinv == 2)
2310 p[-3] = (MCode)(target - p + 2); /* Patch opt. short jp. */
2311 } else {
2312 lua_assert(target - p >= -128);
2313 p[-1] = (MCode)(int8_t)(target - p); /* Patch short jmp. */
2314 p[-2] = XI_JMPs;
2316 } else {
2317 MCode *newloop;
2318 p[-5] = XI_JMP;
2319 if (as->loopinv) { /* Inverted loop branch? */
2320 /* asm_guardcc already inverted the jcc and patched the jmp. */
2321 p -= 5;
2322 newloop = target+4;
2323 *(int32_t *)(p-4) = (int32_t)(target - p); /* Patch jcc. */
2324 if (as->loopinv == 2) {
2325 *(int32_t *)(p-10) = (int32_t)(target - p + 6); /* Patch opt. jp. */
2326 newloop = target+8;
2328 } else { /* Otherwise just patch jmp. */
2329 *(int32_t *)(p-4) = (int32_t)(target - p);
2330 newloop = target+3;
2332 /* Realign small loops and shorten the loop branch. */
2333 if (newloop >= p - 128) {
2334 as->realign = newloop; /* Force a retry and remember alignment. */
2335 as->curins = as->stopins; /* Abort asm_trace now. */
2336 as->T->nins = as->orignins; /* Remove any added renames. */
2341 /* -- Head of trace ------------------------------------------------------- */
2343 /* Coalesce BASE register for a root trace. */
2344 static void asm_head_root_base(ASMState *as)
2346 IRIns *ir = IR(REF_BASE);
2347 Reg r = ir->r;
2348 if (ra_hasreg(r)) {
2349 ra_free(as, r);
2350 if (rset_test(as->modset, r))
2351 ir->r = RID_INIT; /* No inheritance for modified BASE register. */
2352 if (r != RID_BASE)
2353 emit_rr(as, XO_MOV, r, RID_BASE);
2357 /* Coalesce or reload BASE register for a side trace. */
2358 static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow)
2360 IRIns *ir = IR(REF_BASE);
2361 Reg r = ir->r;
2362 if (ra_hasreg(r)) {
2363 ra_free(as, r);
2364 if (rset_test(as->modset, r))
2365 ir->r = RID_INIT; /* No inheritance for modified BASE register. */
2366 if (irp->r == r) {
2367 rset_clear(allow, r); /* Mark same BASE register as coalesced. */
2368 } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) {
2369 rset_clear(allow, irp->r);
2370 emit_rr(as, XO_MOV, r, irp->r); /* Move from coalesced parent reg. */
2371 } else {
2372 emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */
2375 return allow;
2378 /* -- Tail of trace ------------------------------------------------------- */
2380 /* Fixup the tail code. */
2381 static void asm_tail_fixup(ASMState *as, TraceNo lnk)
2383 /* Note: don't use as->mcp swap + emit_*: emit_op overwrites more bytes. */
2384 MCode *p = as->mctop;
2385 MCode *target, *q;
2386 int32_t spadj = as->T->spadjust;
2387 if (spadj == 0) {
2388 p -= ((as->flags & JIT_F_LEA_AGU) ? 7 : 6) + (LJ_64 ? 1 : 0);
2389 } else {
2390 MCode *p1;
2391 /* Patch stack adjustment. */
2392 if (checki8(spadj)) {
2393 p -= 3;
2394 p1 = p-6;
2395 *p1 = (MCode)spadj;
2396 } else {
2397 p1 = p-9;
2398 *(int32_t *)p1 = spadj;
2400 if ((as->flags & JIT_F_LEA_AGU)) {
2401 #if LJ_64
2402 p1[-4] = 0x48;
2403 #endif
2404 p1[-3] = (MCode)XI_LEA;
2405 p1[-2] = MODRM(checki8(spadj) ? XM_OFS8 : XM_OFS32, RID_ESP, RID_ESP);
2406 p1[-1] = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
2407 } else {
2408 #if LJ_64
2409 p1[-3] = 0x48;
2410 #endif
2411 p1[-2] = (MCode)(checki8(spadj) ? XI_ARITHi8 : XI_ARITHi);
2412 p1[-1] = MODRM(XM_REG, XOg_ADD, RID_ESP);
2415 /* Patch exit branch. */
2416 target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)lj_vm_exit_interp;
2417 *(int32_t *)(p-4) = jmprel(p, target);
2418 p[-5] = XI_JMP;
2419 /* Drop unused mcode tail. Fill with NOPs to make the prefetcher happy. */
2420 for (q = as->mctop-1; q >= p; q--)
2421 *q = XI_NOP;
2422 as->mctop = p;
2425 /* Prepare tail of code. */
2426 static void asm_tail_prep(ASMState *as)
2428 MCode *p = as->mctop;
2429 /* Realign and leave room for backwards loop branch or exit branch. */
2430 if (as->realign) {
2431 int i = ((int)(intptr_t)as->realign) & 15;
2432 /* Fill unused mcode tail with NOPs to make the prefetcher happy. */
2433 while (i-- > 0)
2434 *--p = XI_NOP;
2435 as->mctop = p;
2436 p -= (as->loopinv ? 5 : 2); /* Space for short/near jmp. */
2437 } else {
2438 p -= 5; /* Space for exit branch (near jmp). */
2440 if (as->loopref) {
2441 as->invmcp = as->mcp = p;
2442 } else {
2443 /* Leave room for ESP adjustment: add esp, imm or lea esp, [esp+imm] */
2444 as->mcp = p - (((as->flags & JIT_F_LEA_AGU) ? 7 : 6) + (LJ_64 ? 1 : 0));
2445 as->invmcp = NULL;
2449 /* -- Instruction dispatch ------------------------------------------------ */
2451 /* Assemble a single instruction. */
2452 static void asm_ir(ASMState *as, IRIns *ir)
2454 switch ((IROp)ir->o) {
2455 /* Miscellaneous ops. */
2456 case IR_LOOP: asm_loop(as); break;
2457 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
2458 case IR_USE:
2459 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
2460 case IR_PHI: asm_phi(as, ir); break;
2461 case IR_HIOP: asm_hiop(as, ir); break;
2463 /* Guarded assertions. */
2464 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
2465 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
2466 case IR_EQ: case IR_NE: case IR_ABC:
2467 asm_comp(as, ir, asm_compmap[ir->o]);
2468 break;
2470 case IR_RETF: asm_retf(as, ir); break;
2472 /* Bit ops. */
2473 case IR_BNOT: asm_neg_not(as, ir, XOg_NOT); break;
2474 case IR_BSWAP: asm_bitswap(as, ir); break;
2476 case IR_BAND: asm_intarith(as, ir, XOg_AND); break;
2477 case IR_BOR: asm_intarith(as, ir, XOg_OR); break;
2478 case IR_BXOR: asm_intarith(as, ir, XOg_XOR); break;
2480 case IR_BSHL: asm_bitshift(as, ir, XOg_SHL); break;
2481 case IR_BSHR: asm_bitshift(as, ir, XOg_SHR); break;
2482 case IR_BSAR: asm_bitshift(as, ir, XOg_SAR); break;
2483 case IR_BROL: asm_bitshift(as, ir, XOg_ROL); break;
2484 case IR_BROR: asm_bitshift(as, ir, XOg_ROR); break;
2486 /* Arithmetic ops. */
2487 case IR_ADD: asm_add(as, ir); break;
2488 case IR_SUB:
2489 if (irt_isnum(ir->t))
2490 asm_fparith(as, ir, XO_SUBSD);
2491 else /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */
2492 asm_intarith(as, ir, XOg_SUB);
2493 break;
2494 case IR_MUL:
2495 if (irt_isnum(ir->t))
2496 asm_fparith(as, ir, XO_MULSD);
2497 else
2498 asm_intarith(as, ir, XOg_X_IMUL);
2499 break;
2500 case IR_DIV:
2501 #if LJ_64 && LJ_HASFFI
2502 if (!irt_isnum(ir->t))
2503 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
2504 IRCALL_lj_carith_divu64);
2505 else
2506 #endif
2507 asm_fparith(as, ir, XO_DIVSD);
2508 break;
2509 case IR_MOD:
2510 #if LJ_64 && LJ_HASFFI
2511 if (!irt_isint(ir->t))
2512 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
2513 IRCALL_lj_carith_modu64);
2514 else
2515 #endif
2516 asm_intmod(as, ir);
2517 break;
2519 case IR_NEG:
2520 if (irt_isnum(ir->t))
2521 asm_fparith(as, ir, XO_XORPS);
2522 else
2523 asm_neg_not(as, ir, XOg_NEG);
2524 break;
2525 case IR_ABS: asm_fparith(as, ir, XO_ANDPS); break;
2527 case IR_MIN:
2528 if (irt_isnum(ir->t))
2529 asm_fparith(as, ir, XO_MINSD);
2530 else
2531 asm_min_max(as, ir, CC_G);
2532 break;
2533 case IR_MAX:
2534 if (irt_isnum(ir->t))
2535 asm_fparith(as, ir, XO_MAXSD);
2536 else
2537 asm_min_max(as, ir, CC_L);
2538 break;
2540 case IR_FPMATH: case IR_ATAN2: case IR_LDEXP:
2541 asm_fpmath(as, ir);
2542 break;
2543 case IR_POW:
2544 #if LJ_64 && LJ_HASFFI
2545 if (!irt_isnum(ir->t))
2546 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
2547 IRCALL_lj_carith_powu64);
2548 else
2549 #endif
2550 asm_fppowi(as, ir);
2551 break;
2553 /* Overflow-checking arithmetic ops. Note: don't use LEA here! */
2554 case IR_ADDOV: asm_intarith(as, ir, XOg_ADD); break;
2555 case IR_SUBOV: asm_intarith(as, ir, XOg_SUB); break;
2556 case IR_MULOV: asm_intarith(as, ir, XOg_X_IMUL); break;
2558 /* Memory references. */
2559 case IR_AREF: asm_aref(as, ir); break;
2560 case IR_HREF: asm_href(as, ir); break;
2561 case IR_HREFK: asm_hrefk(as, ir); break;
2562 case IR_NEWREF: asm_newref(as, ir); break;
2563 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
2564 case IR_FREF: asm_fref(as, ir); break;
2565 case IR_STRREF: asm_strref(as, ir); break;
2567 /* Loads and stores. */
2568 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2569 asm_ahuvload(as, ir);
2570 break;
2571 case IR_FLOAD: case IR_XLOAD: asm_fxload(as, ir); break;
2572 case IR_SLOAD: asm_sload(as, ir); break;
2574 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
2575 case IR_FSTORE: case IR_XSTORE: asm_fxstore(as, ir); break;
2577 /* Allocations. */
2578 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
2579 case IR_TNEW: asm_tnew(as, ir); break;
2580 case IR_TDUP: asm_tdup(as, ir); break;
2581 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
2583 /* Write barriers. */
2584 case IR_TBAR: asm_tbar(as, ir); break;
2585 case IR_OBAR: asm_obar(as, ir); break;
2587 /* Type conversions. */
2588 case IR_TOBIT: asm_tobit(as, ir); break;
2589 case IR_CONV: asm_conv(as, ir); break;
2590 case IR_TOSTR: asm_tostr(as, ir); break;
2591 case IR_STRTO: asm_strto(as, ir); break;
2593 /* Calls. */
2594 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
2595 case IR_CALLXS: asm_callx(as, ir); break;
2596 case IR_CARG: break;
2598 default:
2599 setintV(&as->J->errinfo, ir->o);
2600 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
2601 break;
2605 /* -- Trace setup --------------------------------------------------------- */
2607 /* Ensure there are enough stack slots for call arguments. */
2608 static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
2610 IRRef args[CCI_NARGS_MAX];
2611 uint32_t nargs = (int)CCI_NARGS(ci);
2612 int nslots = 0;
2613 asm_collectargs(as, ir, ci, args);
2614 #if LJ_64
2615 if (LJ_ABI_WIN) {
2616 nslots = (int)(nargs*2); /* Only matters for more than four args. */
2617 } else {
2618 uint32_t i;
2619 int ngpr = 6, nfpr = 8;
2620 for (i = 0; i < nargs; i++)
2621 if (args[i] && irt_isfp(IR(args[i])->t)) {
2622 if (nfpr > 0) nfpr--; else nslots += 2;
2623 } else {
2624 if (ngpr > 0) ngpr--; else nslots += 2;
2627 if (nslots > as->evenspill) /* Leave room for args in stack slots. */
2628 as->evenspill = nslots;
2629 return irt_isfp(ir->t) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET);
2630 #else
2631 if ((ci->flags & CCI_FASTCALL)) {
2632 lua_assert(nargs <= 2);
2633 } else {
2634 uint32_t i;
2635 for (i = 0; i < nargs; i++)
2636 nslots += (args[i] && irt_isnum(IR(args[i])->t)) ? 2 : 1;
2637 if (nslots > as->evenspill) /* Leave room for args. */
2638 as->evenspill = nslots;
2640 return irt_isfp(ir->t) ? REGSP_INIT : REGSP_HINT(RID_RET);
2641 #endif
2644 /* Target-specific setup. */
2645 static void asm_setup_target(ASMState *as)
2647 asm_exitstub_setup(as, as->T->nsnap);
2650 /* -- Trace patching ------------------------------------------------------ */
2652 /* Patch exit jumps of existing machine code to a new target. */
2653 void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target)
2655 MCode *p = T->mcode;
2656 MCode *mcarea = lj_mcode_patch(J, p, 0);
2657 MSize len = T->szmcode;
2658 MCode *px = exitstub_addr(J, exitno) - 6;
2659 MCode *pe = p+len-6;
2660 uint32_t stateaddr = u32ptr(&J2G(J)->vmstate);
2661 if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px)
2662 *(int32_t *)(p+len-4) = jmprel(p+len, target);
2663 /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */
2664 for (; p < pe; p++)
2665 if (*(uint32_t *)(p+(LJ_64 ? 3 : 2)) == stateaddr && p[0] == XI_MOVmi) {
2666 p += LJ_64 ? 11 : 10;
2667 break;
2669 lua_assert(p < pe);
2670 for (; p < pe; p++) {
2671 if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px) {
2672 *(int32_t *)(p+2) = jmprel(p+6, target);
2673 p += 5;
2676 lj_mcode_patch(J, mcarea, 1);
2677 VG_INVALIDATE(T->mcode, T->szmcode);