1/*
2** x86/x64 IR assembler (SSA IR -> machine code).
3** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6/* -- Guard handling ------------------------------------------------------ */
7
8/* Generate an exit stub group at the bottom of the reserved MCode memory. */
9static MCode *asm_exitstub_gen(ASMState *as, ExitNo group)
10{
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);
21 }
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;
38}
39
40/* Setup all needed exit stubs. */
41static void asm_exitstub_setup(ASMState *as, ExitNo nexits)
42{
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);
49}
50
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.
54*/
55static void asm_guardcc(ASMState *as, int cc)
56{
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;
67 }
68 }
69 emit_jcc(as, cc, target);
70}
71
72/* -- Memory operand fusion ----------------------------------------------- */
73
74/* Limit linear search to this distance. Avoids O(n^2) behavior. */
75#define CONFLICT_SEARCH_LIM 31
76
77/* Check if a reference is a signed 32 bit constant. */
78static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
79{
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;
88 }
89 }
90 return 0;
91}
92
93/* Check if there's no conflicting instruction between curins and ref.
94** Also avoid fusing loads if there are multiple references.
95*/
96static int noconflict(ASMState *as, IRRef ref, IROp conflict, int noload)
97{
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;
107 }
108 return 1; /* Ok, no conflict. */
109}
110
111/* Fuse array base into memory operand. */
112static IRRef asm_fuseabase(ASMState *as, IRRef ref)
113{
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. */
124 }
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;
129 }
130 return ref; /* Otherwise use the given array base. */
131}
132
133/* Fuse array reference into memory operand. */
134static void asm_fusearef(ASMState *as, IRIns *ir, RegSet allow)
135{
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.
148 */
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);
156 }
157 }
158}
159
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!
164*/
165static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow)
166{
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;
174 }
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;
182 }
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;
191 }
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;
197 }
198 }
199 as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
200 as->mrm.ofs = 0;
201 as->mrm.idx = RID_NONE;
202}
203
204/* Fuse FLOAD/FREF reference into memory operand. */
205static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow)
206{
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);
215 }
216}
217
218/* Fuse string reference into memory operand. */
219static void asm_fusestrref(ASMState *as, IRIns *ir, RegSet allow)
220{
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;
232 }
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);
245 }
246 if (as->mrm.base == RID_NONE)
247 as->mrm.base = (uint8_t)r;
248 else
249 as->mrm.idx = (uint8_t)r;
250 }
251}
252
253static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow)
254{
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;
274 }
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);
283 }
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;
293 }
294 }
295 r = ra_alloc1(as, idx, allow);
296 rset_clear(allow, r);
297 as->mrm.idx = (uint8_t)r;
298 }
299 noadd:
300 as->mrm.base = (uint8_t)ra_alloc1(as, ref, allow);
301 }
302}
303
304/* Fuse load into memory operand. */
305static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
306{
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;
312 }
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;
319 }
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;
327 }
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;
337 }
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_isu32(ir->t) || irt_isaddr(ir->t)) &&
341 noconflict(as, ref, IR_FSTORE, 0)) {
342 asm_fusefref(as, ir, xallow);
343 return RID_MRM;
344 }
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;
349 }
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).
353 */
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;
358 }
359 } else if (ir->o == IR_VLOAD) {
360 asm_fuseahuref(as, ir->op1, xallow);
361 return RID_MRM;
362 }
363 }
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);
368}
369
370#if LJ_64
371/* Don't fuse a 32 bit load into a 64 bit operation. */
372static Reg asm_fuseloadm(ASMState *as, IRRef ref, RegSet allow, int is64)
373{
374 if (is64 && !irt_is64(IR(ref)->t))
375 return ra_alloc1(as, ref, allow);
376 return asm_fuseload(as, ref, allow);
377}
378#else
379#define asm_fuseloadm(as, ref, allow, is64) asm_fuseload(as, (ref), (allow))
380#endif
381
382/* -- Calls --------------------------------------------------------------- */
383
384/* Count the required number of stack slots for a call. */
385static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args)
386{
387 uint32_t i, nargs = CCI_NARGS(ci);
388 int nslots = 0;
389#if LJ_64
390 if (LJ_ABI_WIN) {
391 nslots = (int)(nargs*2); /* Only matters for more than four args. */
392 } else {
393 int ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR;
394 for (i = 0; i < nargs; i++)
395 if (args[i] && irt_isfp(IR(args[i])->t)) {
396 if (nfpr > 0) nfpr--; else nslots += 2;
397 } else {
398 if (ngpr > 0) ngpr--; else nslots += 2;
399 }
400 }
401#else
402 int ngpr = 0;
403 if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL)
404 ngpr = 2;
405 else if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL)
406 ngpr = 1;
407 for (i = 0; i < nargs; i++)
408 if (args[i] && irt_isfp(IR(args[i])->t)) {
409 nslots += irt_isnum(IR(args[i])->t) ? 2 : 1;
410 } else {
411 if (ngpr > 0) ngpr--; else nslots++;
412 }
413#endif
414 return nslots;
415}
416
417/* Generate a call to a C function. */
418static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
419{
420 uint32_t n, nargs = CCI_NARGS(ci);
421 int32_t ofs = STACKARG_OFS;
422#if LJ_64
423 uint32_t gprs = REGARG_GPRS;
424 Reg fpr = REGARG_FIRSTFPR;
425#if !LJ_ABI_WIN
426 MCode *patchnfpr = NULL;
427#endif
428#else
429 uint32_t gprs = 0;
430 if ((ci->flags & CCI_CC_MASK) != CCI_CC_CDECL) {
431 if ((ci->flags & CCI_CC_MASK) == CCI_CC_THISCALL)
432 gprs = (REGARG_GPRS & 31);
433 else if ((ci->flags & CCI_CC_MASK) == CCI_CC_FASTCALL)
434 gprs = REGARG_GPRS;
435 }
436#endif
437 if ((void *)ci->func)
438 emit_call(as, ci->func);
439#if LJ_64
440 if ((ci->flags & CCI_VARARG)) { /* Special handling for vararg calls. */
441#if LJ_ABI_WIN
442 for (n = 0; n < 4 && n < nargs; n++) {
443 IRIns *ir = IR(args[n]);
444 if (irt_isfp(ir->t)) /* Duplicate FPRs in GPRs. */
445 emit_rr(as, XO_MOVDto, (irt_isnum(ir->t) ? REX_64 : 0) | (fpr+n),
446 ((gprs >> (n*5)) & 31)); /* Either MOVD or MOVQ. */
447 }
448#else
449 patchnfpr = --as->mcp; /* Indicate number of used FPRs in register al. */
450 *--as->mcp = XI_MOVrib | RID_EAX;
451#endif
452 }
453#endif
454 for (n = 0; n < nargs; n++) { /* Setup args. */
455 IRRef ref = args[n];
456 IRIns *ir = IR(ref);
457 Reg r;
458#if LJ_64 && LJ_ABI_WIN
459 /* Windows/x64 argument registers are strictly positional. */
460 r = irt_isfp(ir->t) ? (fpr <= REGARG_LASTFPR ? fpr : 0) : (gprs & 31);
461 fpr++; gprs >>= 5;
462#elif LJ_64
463 /* POSIX/x64 argument registers are used in order of appearance. */
464 if (irt_isfp(ir->t)) {
465 r = fpr <= REGARG_LASTFPR ? fpr++ : 0;
466 } else {
467 r = gprs & 31; gprs >>= 5;
468 }
469#else
470 if (ref && irt_isfp(ir->t)) {
471 r = 0;
472 } else {
473 r = gprs & 31; gprs >>= 5;
474 if (!ref) continue;
475 }
476#endif
477 if (r) { /* Argument is in a register. */
478 if (r < RID_MAX_GPR && ref < ASMREF_TMP1) {
479#if LJ_64
480 if (ir->o == IR_KINT64)
481 emit_loadu64(as, r, ir_kint64(ir)->u64);
482 else
483#endif
484 emit_loadi(as, r, ir->i);
485 } else {
486 lua_assert(rset_test(as->freeset, r)); /* Must have been evicted. */
487 if (ra_hasreg(ir->r)) {
488 ra_noweak(as, ir->r);
489 emit_movrr(as, ir, r, ir->r);
490 } else {
491 ra_allocref(as, ref, RID2RSET(r));
492 }
493 }
494 } else if (irt_isfp(ir->t)) { /* FP argument is on stack. */
495 lua_assert(!(irt_isfloat(ir->t) && irref_isk(ref))); /* No float k. */
496 if (LJ_32 && (ofs & 4) && irref_isk(ref)) {
497 /* Split stores for unaligned FP consts. */
498 emit_movmroi(as, RID_ESP, ofs, (int32_t)ir_knum(ir)->u32.lo);
499 emit_movmroi(as, RID_ESP, ofs+4, (int32_t)ir_knum(ir)->u32.hi);
500 } else {
501 r = ra_alloc1(as, ref, RSET_FPR);
502 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto,
503 r, RID_ESP, ofs);
504 }
505 ofs += (LJ_32 && irt_isfloat(ir->t)) ? 4 : 8;
506 } else { /* Non-FP argument is on stack. */
507 if (LJ_32 && ref < ASMREF_TMP1) {
508 emit_movmroi(as, RID_ESP, ofs, ir->i);
509 } else {
510 r = ra_alloc1(as, ref, RSET_GPR);
511 emit_movtomro(as, REX_64 + r, RID_ESP, ofs);
512 }
513 ofs += sizeof(intptr_t);
514 }
515 checkmclim(as);
516 }
517#if LJ_64 && !LJ_ABI_WIN
518 if (patchnfpr) *patchnfpr = fpr - REGARG_FIRSTFPR;
519#endif
520}
521
522/* Setup result reg/sp for call. Evict scratch regs. */
523static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
524{
525 RegSet drop = RSET_SCRATCH;
526 int hiop = (LJ_32 && (ir+1)->o == IR_HIOP);
527 if ((ci->flags & CCI_NOFPRCLOBBER))
528 drop &= ~RSET_FPR;
529 if (ra_hasreg(ir->r))
530 rset_clear(drop, ir->r); /* Dest reg handled below. */
531 if (hiop && ra_hasreg((ir+1)->r))
532 rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */
533 ra_evictset(as, drop); /* Evictions must be performed first. */
534 if (ra_used(ir)) {
535 if (irt_isfp(ir->t)) {
536 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
537#if LJ_64
538 if ((ci->flags & CCI_CASTU64)) {
539 Reg dest = ir->r;
540 if (ra_hasreg(dest)) {
541 ra_free(as, dest);
542 ra_modified(as, dest);
543 emit_rr(as, XO_MOVD, dest|REX_64, RID_RET); /* Really MOVQ. */
544 }
545 if (ofs) emit_movtomro(as, RID_RET|REX_64, RID_ESP, ofs);
546 } else {
547 ra_destreg(as, ir, RID_FPRET);
548 }
549#else
550 /* Number result is in x87 st0 for x86 calling convention. */
551 Reg dest = ir->r;
552 if (ra_hasreg(dest)) {
553 ra_free(as, dest);
554 ra_modified(as, dest);
555 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS,
556 dest, RID_ESP, ofs);
557 }
558 if ((ci->flags & CCI_CASTU64)) {
559 emit_movtomro(as, RID_RETLO, RID_ESP, ofs);
560 emit_movtomro(as, RID_RETHI, RID_ESP, ofs+4);
561 } else {
562 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
563 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
564 }
565#endif
566#if LJ_32
567 } else if (hiop) {
568 ra_destpair(as, ir);
569#endif
570 } else {
571 lua_assert(!irt_ispri(ir->t));
572 ra_destreg(as, ir, RID_RET);
573 }
574 } else if (LJ_32 && irt_isfp(ir->t)) {
575 emit_x87op(as, XI_FPOP); /* Pop unused result from x87 st0. */
576 }
577}
578
579static void asm_call(ASMState *as, IRIns *ir)
580{
581 IRRef args[CCI_NARGS_MAX];
582 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
583 asm_collectargs(as, ir, ci, args);
584 asm_setupresult(as, ir, ci);
585 asm_gencall(as, ci, args);
586}
587
588/* Return a constant function pointer or NULL for indirect calls. */
589static void *asm_callx_func(ASMState *as, IRIns *irf, IRRef func)
590{
591#if LJ_32
592 UNUSED(as);
593 if (irref_isk(func))
594 return (void *)irf->i;
595#else
596 if (irref_isk(func)) {
597 MCode *p;
598 if (irf->o == IR_KINT64)
599 p = (MCode *)(void *)ir_k64(irf)->u64;
600 else
601 p = (MCode *)(void *)(uintptr_t)(uint32_t)irf->i;
602 if (p - as->mcp == (int32_t)(p - as->mcp))
603 return p; /* Call target is still in +-2GB range. */
604 /* Avoid the indirect case of emit_call(). Try to hoist func addr. */
605 }
606#endif
607 return NULL;
608}
609
610static void asm_callx(ASMState *as, IRIns *ir)
611{
612 IRRef args[CCI_NARGS_MAX*2];
613 CCallInfo ci;
614 IRRef func;
615 IRIns *irf;
616 int32_t spadj = 0;
617 ci.flags = asm_callx_flags(as, ir);
618 asm_collectargs(as, ir, &ci, args);
619 asm_setupresult(as, ir, &ci);
620#if LJ_32
621 /* Have to readjust stack after non-cdecl calls due to callee cleanup. */
622 if ((ci.flags & CCI_CC_MASK) != CCI_CC_CDECL)
623 spadj = 4 * asm_count_call_slots(as, &ci, args);
624#endif
625 func = ir->op2; irf = IR(func);
626 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); }
627 ci.func = (ASMFunction)asm_callx_func(as, irf, func);
628 if (!(void *)ci.func) {
629 /* Use a (hoistable) non-scratch register for indirect calls. */
630 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
631 Reg r = ra_alloc1(as, func, allow);
632 if (LJ_32) emit_spsub(as, spadj); /* Above code may cause restores! */
633 emit_rr(as, XO_GROUP5, XOg_CALL, r);
634 } else if (LJ_32) {
635 emit_spsub(as, spadj);
636 }
637 asm_gencall(as, &ci, args);
638}
639
640/* -- Returns ------------------------------------------------------------- */
641
642/* Return to lower frame. Guard that it goes to the right spot. */
643static void asm_retf(ASMState *as, IRIns *ir)
644{
645 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
646 void *pc = ir_kptr(IR(ir->op2));
647 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1));
648 as->topslot -= (BCReg)delta;
649 if ((int32_t)as->topslot < 0) as->topslot = 0;
650 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
651 emit_setgl(as, base, jit_base);
652 emit_addptr(as, base, -8*delta);
653 asm_guardcc(as, CC_NE);
654 emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc));
655}
656
657/* -- Type conversions ---------------------------------------------------- */
658
659static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
660{
661 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
662 Reg dest = ra_dest(as, ir, RSET_GPR);
663 asm_guardcc(as, CC_P);
664 asm_guardcc(as, CC_NE);
665 emit_rr(as, XO_UCOMISD, left, tmp);
666 emit_rr(as, XO_CVTSI2SD, tmp, dest);
667 if (!(as->flags & JIT_F_SPLIT_XMM))
668 emit_rr(as, XO_XORPS, tmp, tmp); /* Avoid partial register stall. */
669 emit_rr(as, XO_CVTTSD2SI, dest, left);
670 /* Can't fuse since left is needed twice. */
671}
672
673static void asm_tobit(ASMState *as, IRIns *ir)
674{
675 Reg dest = ra_dest(as, ir, RSET_GPR);
676 Reg tmp = ra_noreg(IR(ir->op1)->r) ?
677 ra_alloc1(as, ir->op1, RSET_FPR) :
678 ra_scratch(as, RSET_FPR);
679 Reg right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp));
680 emit_rr(as, XO_MOVDto, tmp, dest);
681 emit_mrm(as, XO_ADDSD, tmp, right);
682 ra_left(as, tmp, ir->op1);
683}
684
685static void asm_conv(ASMState *as, IRIns *ir)
686{
687 IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK);
688 int st64 = (st == IRT_I64 || st == IRT_U64 || (LJ_64 && st == IRT_P64));
689 int stfp = (st == IRT_NUM || st == IRT_FLOAT);
690 IRRef lref = ir->op1;
691 lua_assert(irt_type(ir->t) != st);
692 lua_assert(!(LJ_32 && (irt_isint64(ir->t) || st64))); /* Handled by SPLIT. */
693 if (irt_isfp(ir->t)) {
694 Reg dest = ra_dest(as, ir, RSET_FPR);
695 if (stfp) { /* FP to FP conversion. */
696 Reg left = asm_fuseload(as, lref, RSET_FPR);
697 emit_mrm(as, st == IRT_NUM ? XO_CVTSD2SS : XO_CVTSS2SD, dest, left);
698 if (left == dest) return; /* Avoid the XO_XORPS. */
699 } else if (LJ_32 && st == IRT_U32) { /* U32 to FP conversion on x86. */
700 /* number = (2^52+2^51 .. u32) - (2^52+2^51) */
701 cTValue *k = lj_ir_k64_find(as->J, U64x(43380000,00000000));
702 Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest));
703 if (irt_isfloat(ir->t))
704 emit_rr(as, XO_CVTSD2SS, dest, dest);
705 emit_rr(as, XO_SUBSD, dest, bias); /* Subtract 2^52+2^51 bias. */
706 emit_rr(as, XO_XORPS, dest, bias); /* Merge bias and integer. */
707 emit_loadn(as, bias, k);
708 emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR));
709 return;
710 } else { /* Integer to FP conversion. */
711 Reg left = (LJ_64 && (st == IRT_U32 || st == IRT_U64)) ?
712 ra_alloc1(as, lref, RSET_GPR) :
713 asm_fuseloadm(as, lref, RSET_GPR, st64);
714 if (LJ_64 && st == IRT_U64) {
715 MCLabel l_end = emit_label(as);
716 const void *k = lj_ir_k64_find(as->J, U64x(43f00000,00000000));
717 emit_rma(as, XO_ADDSD, dest, k); /* Add 2^64 to compensate. */
718 emit_sjcc(as, CC_NS, l_end);
719 emit_rr(as, XO_TEST, left|REX_64, left); /* Check if u64 >= 2^63. */
720 }
721 emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS,
722 dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left);
723 }
724 if (!(as->flags & JIT_F_SPLIT_XMM))
725 emit_rr(as, XO_XORPS, dest, dest); /* Avoid partial register stall. */
726 } else if (stfp) { /* FP to integer conversion. */
727 if (irt_isguard(ir->t)) {
728 /* Checked conversions are only supported from number to int. */
729 lua_assert(irt_isint(ir->t) && st == IRT_NUM);
730 asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR));
731 } else {
732 Reg dest = ra_dest(as, ir, RSET_GPR);
733 x86Op op = st == IRT_NUM ?
734 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSD2SI : XO_CVTSD2SI) :
735 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSS2SI : XO_CVTSS2SI);
736 if (LJ_64 ? irt_isu64(ir->t) : irt_isu32(ir->t)) {
737 /* LJ_64: For inputs >= 2^63 add -2^64, convert again. */
738 /* LJ_32: For inputs >= 2^31 add -2^31, convert again and add 2^31. */
739 Reg tmp = ra_noreg(IR(lref)->r) ? ra_alloc1(as, lref, RSET_FPR) :
740 ra_scratch(as, RSET_FPR);
741 MCLabel l_end = emit_label(as);
742 if (LJ_32)
743 emit_gri(as, XG_ARITHi(XOg_ADD), dest, (int32_t)0x80000000);
744 emit_rr(as, op, dest|REX_64, tmp);
745 if (st == IRT_NUM)
746 emit_rma(as, XO_ADDSD, tmp, lj_ir_k64_find(as->J,
747 LJ_64 ? U64x(c3f00000,00000000) : U64x(c1e00000,00000000)));
748 else
749 emit_rma(as, XO_ADDSS, tmp, lj_ir_k64_find(as->J,
750 LJ_64 ? U64x(00000000,df800000) : U64x(00000000,cf000000)));
751 emit_sjcc(as, CC_NS, l_end);
752 emit_rr(as, XO_TEST, dest|REX_64, dest); /* Check if dest negative. */
753 emit_rr(as, op, dest|REX_64, tmp);
754 ra_left(as, tmp, lref);
755 } else {
756 Reg left = asm_fuseload(as, lref, RSET_FPR);
757 if (LJ_64 && irt_isu32(ir->t))
758 emit_rr(as, XO_MOV, dest, dest); /* Zero hiword. */
759 emit_mrm(as, op,
760 dest|((LJ_64 &&
761 (irt_is64(ir->t) || irt_isu32(ir->t))) ? REX_64 : 0),
762 left);
763 }
764 }
765 } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */
766 Reg left, dest = ra_dest(as, ir, RSET_GPR);
767 RegSet allow = RSET_GPR;
768 x86Op op;
769 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t));
770 if (st == IRT_I8) {
771 op = XO_MOVSXb; allow = RSET_GPR8; dest |= FORCE_REX;
772 } else if (st == IRT_U8) {
773 op = XO_MOVZXb; allow = RSET_GPR8; dest |= FORCE_REX;
774 } else if (st == IRT_I16) {
775 op = XO_MOVSXw;
776 } else {
777 op = XO_MOVZXw;
778 }
779 left = asm_fuseload(as, lref, allow);
780 /* Add extra MOV if source is already in wrong register. */
781 if (!LJ_64 && left != RID_MRM && !rset_test(allow, left)) {
782 Reg tmp = ra_scratch(as, allow);
783 emit_rr(as, op, dest, tmp);
784 emit_rr(as, XO_MOV, tmp, left);
785 } else {
786 emit_mrm(as, op, dest, left);
787 }
788 } else { /* 32/64 bit integer conversions. */
789 if (LJ_32) { /* Only need to handle 32/32 bit no-op (cast) on x86. */
790 Reg dest = ra_dest(as, ir, RSET_GPR);
791 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
792 } else if (irt_is64(ir->t)) {
793 Reg dest = ra_dest(as, ir, RSET_GPR);
794 if (st64 || !(ir->op2 & IRCONV_SEXT)) {
795 /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */
796 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
797 } else { /* 32 to 64 bit sign extension. */
798 Reg left = asm_fuseload(as, lref, RSET_GPR);
799 emit_mrm(as, XO_MOVSXd, dest|REX_64, left);
800 }
801 } else {
802 Reg dest = ra_dest(as, ir, RSET_GPR);
803 if (st64) {
804 Reg left = asm_fuseload(as, lref, RSET_GPR);
805 /* This is either a 32 bit reg/reg mov which zeroes the hiword
806 ** or a load of the loword from a 64 bit address.
807 */
808 emit_mrm(as, XO_MOV, dest, left);
809 } else { /* 32/32 bit no-op (cast). */
810 ra_left(as, dest, lref); /* Do nothing, but may need to move regs. */
811 }
812 }
813 }
814}
815
816#if LJ_32 && LJ_HASFFI
817/* No SSE conversions to/from 64 bit on x86, so resort to ugly x87 code. */
818
819/* 64 bit integer to FP conversion in 32 bit mode. */
820static void asm_conv_fp_int64(ASMState *as, IRIns *ir)
821{
822 Reg hi = ra_alloc1(as, ir->op1, RSET_GPR);
823 Reg lo = ra_alloc1(as, (ir-1)->op1, rset_exclude(RSET_GPR, hi));
824 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
825 Reg dest = ir->r;
826 if (ra_hasreg(dest)) {
827 ra_free(as, dest);
828 ra_modified(as, dest);
829 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS,
830 dest, RID_ESP, ofs);
831 }
832 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
833 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
834 if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) {
835 /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */
836 MCLabel l_end = emit_label(as);
837 emit_rma(as, XO_FADDq, XOg_FADDq,
838 lj_ir_k64_find(as->J, U64x(43f00000,00000000)));
839 emit_sjcc(as, CC_NS, l_end);
840 emit_rr(as, XO_TEST, hi, hi); /* Check if u64 >= 2^63. */
841 } else {
842 lua_assert(((ir-1)->op2 & IRCONV_SRCMASK) == IRT_I64);
843 }
844 emit_rmro(as, XO_FILDq, XOg_FILDq, RID_ESP, 0);
845 /* NYI: Avoid narrow-to-wide store-to-load forwarding stall. */
846 emit_rmro(as, XO_MOVto, hi, RID_ESP, 4);
847 emit_rmro(as, XO_MOVto, lo, RID_ESP, 0);
848}
849
850/* FP to 64 bit integer conversion in 32 bit mode. */
851static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
852{
853 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
854 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
855 Reg lo, hi;
856 lua_assert(st == IRT_NUM || st == IRT_FLOAT);
857 lua_assert(dt == IRT_I64 || dt == IRT_U64);
858 lua_assert(((ir-1)->op2 & IRCONV_TRUNC));
859 hi = ra_dest(as, ir, RSET_GPR);
860 lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi));
861 if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0);
862 /* NYI: Avoid wide-to-narrow store-to-load forwarding stall. */
863 if (!(as->flags & JIT_F_SSE3)) { /* Set FPU rounding mode to default. */
864 emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 4);
865 emit_rmro(as, XO_MOVto, lo, RID_ESP, 4);
866 emit_gri(as, XG_ARITHi(XOg_AND), lo, 0xf3ff);
867 }
868 if (dt == IRT_U64) {
869 /* For inputs in [2^63,2^64-1] add -2^64 and convert again. */
870 MCLabel l_pop, l_end = emit_label(as);
871 emit_x87op(as, XI_FPOP);
872 l_pop = emit_label(as);
873 emit_sjmp(as, l_end);
874 emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
875 if ((as->flags & JIT_F_SSE3))
876 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
877 else
878 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
879 emit_rma(as, XO_FADDq, XOg_FADDq,
880 lj_ir_k64_find(as->J, U64x(c3f00000,00000000)));
881 emit_sjcc(as, CC_NS, l_pop);
882 emit_rr(as, XO_TEST, hi, hi); /* Check if out-of-range (2^63). */
883 }
884 emit_rmro(as, XO_MOV, hi, RID_ESP, 4);
885 if ((as->flags & JIT_F_SSE3)) { /* Truncation is easy with SSE3. */
886 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
887 } else { /* Otherwise set FPU rounding mode to truncate before the store. */
888 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
889 emit_rmro(as, XO_FLDCW, XOg_FLDCW, RID_ESP, 0);
890 emit_rmro(as, XO_MOVtow, lo, RID_ESP, 0);
891 emit_rmro(as, XO_ARITHw(XOg_OR), lo, RID_ESP, 0);
892 emit_loadi(as, lo, 0xc00);
893 emit_rmro(as, XO_FNSTCW, XOg_FNSTCW, RID_ESP, 0);
894 }
895 if (dt == IRT_U64)
896 emit_x87op(as, XI_FDUP);
897 emit_mrm(as, st == IRT_NUM ? XO_FLDq : XO_FLDd,
898 st == IRT_NUM ? XOg_FLDq: XOg_FLDd,
899 asm_fuseload(as, ir->op1, RSET_EMPTY));
900}
901#endif
902
903static void asm_strto(ASMState *as, IRIns *ir)
904{
905 /* Force a spill slot for the destination register (if any). */
906 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
907 IRRef args[2];
908 RegSet drop = RSET_SCRATCH;
909 if ((drop & RSET_FPR) != RSET_FPR && ra_hasreg(ir->r))
910 rset_set(drop, ir->r); /* WIN64 doesn't spill all FPRs. */
911 ra_evictset(as, drop);
912 asm_guardcc(as, CC_E);
913 emit_rr(as, XO_TEST, RID_RET, RID_RET); /* Test return status. */
914 args[0] = ir->op1; /* GCstr *str */
915 args[1] = ASMREF_TMP1; /* TValue *n */
916 asm_gencall(as, ci, args);
917 /* Store the result to the spill slot or temp slots. */
918 emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
919 RID_ESP, sps_scale(ir->s));
920}
921
922static void asm_tostr(ASMState *as, IRIns *ir)
923{
924 IRIns *irl = IR(ir->op1);
925 IRRef args[2];
926 args[0] = ASMREF_L;
927 as->gcsteps++;
928 if (irt_isnum(irl->t)) {
929 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum];
930 args[1] = ASMREF_TMP1; /* const lua_Number * */
931 asm_setupresult(as, ir, ci); /* GCstr * */
932 asm_gencall(as, ci, args);
933 emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
934 RID_ESP, ra_spill(as, irl));
935 } else {
936 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint];
937 args[1] = ir->op1; /* int32_t k */
938 asm_setupresult(as, ir, ci); /* GCstr * */
939 asm_gencall(as, ci, args);
940 }
941}
942
943/* -- Memory references --------------------------------------------------- */
944
945static void asm_aref(ASMState *as, IRIns *ir)
946{
947 Reg dest = ra_dest(as, ir, RSET_GPR);
948 asm_fusearef(as, ir, RSET_GPR);
949 if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0))
950 emit_mrm(as, XO_LEA, dest, RID_MRM);
951 else if (as->mrm.base != dest)
952 emit_rr(as, XO_MOV, dest, as->mrm.base);
953}
954
955/* Merge NE(HREF, niltv) check. */
956static MCode *merge_href_niltv(ASMState *as, IRIns *ir)
957{
958 /* Assumes nothing else generates NE of HREF. */
959 if ((ir[1].o == IR_NE || ir[1].o == IR_EQ) && ir[1].op1 == as->curins &&
960 ra_hasreg(ir->r)) {
961 MCode *p = as->mcp;
962 p += (LJ_64 && *p != XI_ARITHi) ? 7+6 : 6+6;
963 /* Ensure no loop branch inversion happened. */
964 if (p[-6] == 0x0f && p[-5] == XI_JCCn+(CC_NE^(ir[1].o & 1))) {
965 as->mcp = p; /* Kill cmp reg, imm32 + jz exit. */
966 return p + *(int32_t *)(p-4); /* Return exit address. */
967 }
968 }
969 return NULL;
970}
971
972/* Inlined hash lookup. Specialized for key type and for const keys.
973** The equivalent C code is:
974** Node *n = hashkey(t, key);
975** do {
976** if (lj_obj_equal(&n->key, key)) return &n->val;
977** } while ((n = nextnode(n)));
978** return niltv(L);
979*/
980static void asm_href(ASMState *as, IRIns *ir)
981{
982 MCode *nilexit = merge_href_niltv(as, ir); /* Do this before any restores. */
983 RegSet allow = RSET_GPR;
984 Reg dest = ra_dest(as, ir, allow);
985 Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest));
986 Reg key = RID_NONE, tmp = RID_NONE;
987 IRIns *irkey = IR(ir->op2);
988 int isk = irref_isk(ir->op2);
989 IRType1 kt = irkey->t;
990 uint32_t khash;
991 MCLabel l_end, l_loop, l_next;
992
993 if (!isk) {
994 rset_clear(allow, tab);
995 key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow);
996 if (!irt_isstr(kt))
997 tmp = ra_scratch(as, rset_exclude(allow, key));
998 }
999
1000 /* Key not found in chain: jump to exit (if merged with NE) or load niltv. */
1001 l_end = emit_label(as);
1002 if (nilexit && ir[1].o == IR_NE) {
1003 emit_jcc(as, CC_E, nilexit); /* XI_JMP is not found by lj_asm_patchexit. */
1004 nilexit = NULL;
1005 } else {
1006 emit_loada(as, dest, niltvg(J2G(as->J)));
1007 }
1008
1009 /* Follow hash chain until the end. */
1010 l_loop = emit_sjcc_label(as, CC_NZ);
1011 emit_rr(as, XO_TEST, dest, dest);
1012 emit_rmro(as, XO_MOV, dest, dest, offsetof(Node, next));
1013 l_next = emit_label(as);
1014
1015 /* Type and value comparison. */
1016 if (nilexit)
1017 emit_jcc(as, CC_E, nilexit);
1018 else
1019 emit_sjcc(as, CC_E, l_end);
1020 if (irt_isnum(kt)) {
1021 if (isk) {
1022 /* Assumes -0.0 is already canonicalized to +0.0. */
1023 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo),
1024 (int32_t)ir_knum(irkey)->u32.lo);
1025 emit_sjcc(as, CC_NE, l_next);
1026 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi),
1027 (int32_t)ir_knum(irkey)->u32.hi);
1028 } else {
1029 emit_sjcc(as, CC_P, l_next);
1030 emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n));
1031 emit_sjcc(as, CC_AE, l_next);
1032 /* The type check avoids NaN penalties and complaints from Valgrind. */
1033#if LJ_64
1034 emit_u32(as, LJ_TISNUM);
1035 emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it));
1036#else
1037 emit_i8(as, LJ_TISNUM);
1038 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
1039#endif
1040 }
1041#if LJ_64
1042 } else if (irt_islightud(kt)) {
1043 emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64));
1044#endif
1045 } else {
1046 if (!irt_ispri(kt)) {
1047 lua_assert(irt_isaddr(kt));
1048 if (isk)
1049 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.gcr),
1050 ptr2addr(ir_kgc(irkey)));
1051 else
1052 emit_rmro(as, XO_CMP, key, dest, offsetof(Node, key.gcr));
1053 emit_sjcc(as, CC_NE, l_next);
1054 }
1055 lua_assert(!irt_isnil(kt));
1056 emit_i8(as, irt_toitype(kt));
1057 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
1058 }
1059 emit_sfixup(as, l_loop);
1060 checkmclim(as);
1061
1062 /* Load main position relative to tab->node into dest. */
1063 khash = isk ? ir_khash(irkey) : 1;
1064 if (khash == 0) {
1065 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, node));
1066 } else {
1067 emit_rmro(as, XO_ARITH(XOg_ADD), dest, tab, offsetof(GCtab, node));
1068 if ((as->flags & JIT_F_PREFER_IMUL)) {
1069 emit_i8(as, sizeof(Node));
1070 emit_rr(as, XO_IMULi8, dest, dest);
1071 } else {
1072 emit_shifti(as, XOg_SHL, dest, 3);
1073 emit_rmrxo(as, XO_LEA, dest, dest, dest, XM_SCALE2, 0);
1074 }
1075 if (isk) {
1076 emit_gri(as, XG_ARITHi(XOg_AND), dest, (int32_t)khash);
1077 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
1078 } else if (irt_isstr(kt)) {
1079 emit_rmro(as, XO_ARITH(XOg_AND), dest, key, offsetof(GCstr, hash));
1080 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, hmask));
1081 } else { /* Must match with hashrot() in lj_tab.c. */
1082 emit_rmro(as, XO_ARITH(XOg_AND), dest, tab, offsetof(GCtab, hmask));
1083 emit_rr(as, XO_ARITH(XOg_SUB), dest, tmp);
1084 emit_shifti(as, XOg_ROL, tmp, HASH_ROT3);
1085 emit_rr(as, XO_ARITH(XOg_XOR), dest, tmp);
1086 emit_shifti(as, XOg_ROL, dest, HASH_ROT2);
1087 emit_rr(as, XO_ARITH(XOg_SUB), tmp, dest);
1088 emit_shifti(as, XOg_ROL, dest, HASH_ROT1);
1089 emit_rr(as, XO_ARITH(XOg_XOR), tmp, dest);
1090 if (irt_isnum(kt)) {
1091 emit_rr(as, XO_ARITH(XOg_ADD), dest, dest);
1092#if LJ_64
1093 emit_shifti(as, XOg_SHR|REX_64, dest, 32);
1094 emit_rr(as, XO_MOV, tmp, dest);
1095 emit_rr(as, XO_MOVDto, key|REX_64, dest);
1096#else
1097 emit_rmro(as, XO_MOV, dest, RID_ESP, ra_spill(as, irkey)+4);
1098 emit_rr(as, XO_MOVDto, key, tmp);
1099#endif
1100 } else {
1101 emit_rr(as, XO_MOV, tmp, key);
1102 emit_rmro(as, XO_LEA, dest, key, HASH_BIAS);
1103 }
1104 }
1105 }
1106}
1107
1108static void asm_hrefk(ASMState *as, IRIns *ir)
1109{
1110 IRIns *kslot = IR(ir->op2);
1111 IRIns *irkey = IR(kslot->op1);
1112 int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node));
1113 Reg dest = ra_used(ir) ? ra_dest(as, ir, RSET_GPR) : RID_NONE;
1114 Reg node = ra_alloc1(as, ir->op1, RSET_GPR);
1115#if !LJ_64
1116 MCLabel l_exit;
1117#endif
1118 lua_assert(ofs % sizeof(Node) == 0);
1119 if (ra_hasreg(dest)) {
1120 if (ofs != 0) {
1121 if (dest == node && !(as->flags & JIT_F_LEA_AGU))
1122 emit_gri(as, XG_ARITHi(XOg_ADD), dest, ofs);
1123 else
1124 emit_rmro(as, XO_LEA, dest, node, ofs);
1125 } else if (dest != node) {
1126 emit_rr(as, XO_MOV, dest, node);
1127 }
1128 }
1129 asm_guardcc(as, CC_NE);
1130#if LJ_64
1131 if (!irt_ispri(irkey->t)) {
1132 Reg key = ra_scratch(as, rset_exclude(RSET_GPR, node));
1133 emit_rmro(as, XO_CMP, key|REX_64, node,
1134 ofs + (int32_t)offsetof(Node, key.u64));
1135 lua_assert(irt_isnum(irkey->t) || irt_isgcv(irkey->t));
1136 /* Assumes -0.0 is already canonicalized to +0.0. */
1137 emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 :
1138 ((uint64_t)irt_toitype(irkey->t) << 32) |
1139 (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey)));
1140 } else {
1141 lua_assert(!irt_isnil(irkey->t));
1142 emit_i8(as, irt_toitype(irkey->t));
1143 emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
1144 ofs + (int32_t)offsetof(Node, key.it));
1145 }
1146#else
1147 l_exit = emit_label(as);
1148 if (irt_isnum(irkey->t)) {
1149 /* Assumes -0.0 is already canonicalized to +0.0. */
1150 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1151 ofs + (int32_t)offsetof(Node, key.u32.lo),
1152 (int32_t)ir_knum(irkey)->u32.lo);
1153 emit_sjcc(as, CC_NE, l_exit);
1154 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1155 ofs + (int32_t)offsetof(Node, key.u32.hi),
1156 (int32_t)ir_knum(irkey)->u32.hi);
1157 } else {
1158 if (!irt_ispri(irkey->t)) {
1159 lua_assert(irt_isgcv(irkey->t));
1160 emit_gmroi(as, XG_ARITHi(XOg_CMP), node,
1161 ofs + (int32_t)offsetof(Node, key.gcr),
1162 ptr2addr(ir_kgc(irkey)));
1163 emit_sjcc(as, CC_NE, l_exit);
1164 }
1165 lua_assert(!irt_isnil(irkey->t));
1166 emit_i8(as, irt_toitype(irkey->t));
1167 emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
1168 ofs + (int32_t)offsetof(Node, key.it));
1169 }
1170#endif
1171}
1172
1173static void asm_newref(ASMState *as, IRIns *ir)
1174{
1175 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
1176 IRRef args[3];
1177 IRIns *irkey;
1178 Reg tmp;
1179 if (ir->r == RID_SINK)
1180 return;
1181 args[0] = ASMREF_L; /* lua_State *L */
1182 args[1] = ir->op1; /* GCtab *t */
1183 args[2] = ASMREF_TMP1; /* cTValue *key */
1184 asm_setupresult(as, ir, ci); /* TValue * */
1185 asm_gencall(as, ci, args);
1186 tmp = ra_releasetmp(as, ASMREF_TMP1);
1187 irkey = IR(ir->op2);
1188 if (irt_isnum(irkey->t)) {
1189 /* For numbers use the constant itself or a spill slot as a TValue. */
1190 if (irref_isk(ir->op2))
1191 emit_loada(as, tmp, ir_knum(irkey));
1192 else
1193 emit_rmro(as, XO_LEA, tmp|REX_64, RID_ESP, ra_spill(as, irkey));
1194 } else {
1195 /* Otherwise use g->tmptv to hold the TValue. */
1196 if (!irref_isk(ir->op2)) {
1197 Reg src = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, tmp));
1198 emit_movtomro(as, REX_64IR(irkey, src), tmp, 0);
1199 } else if (!irt_ispri(irkey->t)) {
1200 emit_movmroi(as, tmp, 0, irkey->i);
1201 }
1202 if (!(LJ_64 && irt_islightud(irkey->t)))
1203 emit_movmroi(as, tmp, 4, irt_toitype(irkey->t));
1204 emit_loada(as, tmp, &J2G(as->J)->tmptv);
1205 }
1206}
1207
1208static void asm_uref(ASMState *as, IRIns *ir)
1209{
1210 /* NYI: Check that UREFO is still open and not aliasing a slot. */
1211 Reg dest = ra_dest(as, ir, RSET_GPR);
1212 if (irref_isk(ir->op1)) {
1213 GCfunc *fn = ir_kfunc(IR(ir->op1));
1214 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
1215 emit_rma(as, XO_MOV, dest, v);
1216 } else {
1217 Reg uv = ra_scratch(as, RSET_GPR);
1218 Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
1219 if (ir->o == IR_UREFC) {
1220 emit_rmro(as, XO_LEA, dest, uv, offsetof(GCupval, tv));
1221 asm_guardcc(as, CC_NE);
1222 emit_i8(as, 1);
1223 emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed));
1224 } else {
1225 emit_rmro(as, XO_MOV, dest, uv, offsetof(GCupval, v));
1226 }
1227 emit_rmro(as, XO_MOV, uv, func,
1228 (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8));
1229 }
1230}
1231
1232static void asm_fref(ASMState *as, IRIns *ir)
1233{
1234 Reg dest = ra_dest(as, ir, RSET_GPR);
1235 asm_fusefref(as, ir, RSET_GPR);
1236 emit_mrm(as, XO_LEA, dest, RID_MRM);
1237}
1238
1239static void asm_strref(ASMState *as, IRIns *ir)
1240{
1241 Reg dest = ra_dest(as, ir, RSET_GPR);
1242 asm_fusestrref(as, ir, RSET_GPR);
1243 if (as->mrm.base == RID_NONE)
1244 emit_loadi(as, dest, as->mrm.ofs);
1245 else if (as->mrm.base == dest && as->mrm.idx == RID_NONE)
1246 emit_gri(as, XG_ARITHi(XOg_ADD), dest, as->mrm.ofs);
1247 else
1248 emit_mrm(as, XO_LEA, dest, RID_MRM);
1249}
1250
1251/* -- Loads and stores ---------------------------------------------------- */
1252
1253static void asm_fxload(ASMState *as, IRIns *ir)
1254{
1255 Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
1256 x86Op xo;
1257 if (ir->o == IR_FLOAD)
1258 asm_fusefref(as, ir, RSET_GPR);
1259 else
1260 asm_fusexref(as, ir->op1, RSET_GPR);
1261 /* ir->op2 is ignored -- unaligned loads are ok on x86. */
1262 switch (irt_type(ir->t)) {
1263 case IRT_I8: xo = XO_MOVSXb; break;
1264 case IRT_U8: xo = XO_MOVZXb; break;
1265 case IRT_I16: xo = XO_MOVSXw; break;
1266 case IRT_U16: xo = XO_MOVZXw; break;
1267 case IRT_NUM: xo = XMM_MOVRM(as); break;
1268 case IRT_FLOAT: xo = XO_MOVSS; break;
1269 default:
1270 if (LJ_64 && irt_is64(ir->t))
1271 dest |= REX_64;
1272 else
1273 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
1274 xo = XO_MOV;
1275 break;
1276 }
1277 emit_mrm(as, xo, dest, RID_MRM);
1278}
1279
1280static void asm_fxstore(ASMState *as, IRIns *ir)
1281{
1282 RegSet allow = RSET_GPR;
1283 Reg src = RID_NONE, osrc = RID_NONE;
1284 int32_t k = 0;
1285 if (ir->r == RID_SINK)
1286 return;
1287 /* The IRT_I16/IRT_U16 stores should never be simplified for constant
1288 ** values since mov word [mem], imm16 has a length-changing prefix.
1289 */
1290 if (irt_isi16(ir->t) || irt_isu16(ir->t) || irt_isfp(ir->t) ||
1291 !asm_isk32(as, ir->op2, &k)) {
1292 RegSet allow8 = irt_isfp(ir->t) ? RSET_FPR :
1293 (irt_isi8(ir->t) || irt_isu8(ir->t)) ? RSET_GPR8 : RSET_GPR;
1294 src = osrc = ra_alloc1(as, ir->op2, allow8);
1295 if (!LJ_64 && !rset_test(allow8, src)) { /* Already in wrong register. */
1296 rset_clear(allow, osrc);
1297 src = ra_scratch(as, allow8);
1298 }
1299 rset_clear(allow, src);
1300 }
1301 if (ir->o == IR_FSTORE) {
1302 asm_fusefref(as, IR(ir->op1), allow);
1303 } else {
1304 asm_fusexref(as, ir->op1, allow);
1305 if (LJ_32 && ir->o == IR_HIOP) as->mrm.ofs += 4;
1306 }
1307 if (ra_hasreg(src)) {
1308 x86Op xo;
1309 switch (irt_type(ir->t)) {
1310 case IRT_I8: case IRT_U8: xo = XO_MOVtob; src |= FORCE_REX; break;
1311 case IRT_I16: case IRT_U16: xo = XO_MOVtow; break;
1312 case IRT_NUM: xo = XO_MOVSDto; break;
1313 case IRT_FLOAT: xo = XO_MOVSSto; break;
1314#if LJ_64
1315 case IRT_LIGHTUD: lua_assert(0); /* NYI: mask 64 bit lightuserdata. */
1316#endif
1317 default:
1318 if (LJ_64 && irt_is64(ir->t))
1319 src |= REX_64;
1320 else
1321 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t) || irt_isaddr(ir->t));
1322 xo = XO_MOVto;
1323 break;
1324 }
1325 emit_mrm(as, xo, src, RID_MRM);
1326 if (!LJ_64 && src != osrc) {
1327 ra_noweak(as, osrc);
1328 emit_rr(as, XO_MOV, src, osrc);
1329 }
1330 } else {
1331 if (irt_isi8(ir->t) || irt_isu8(ir->t)) {
1332 emit_i8(as, k);
1333 emit_mrm(as, XO_MOVmib, 0, RID_MRM);
1334 } else {
1335 lua_assert(irt_is64(ir->t) || irt_isint(ir->t) || irt_isu32(ir->t) ||
1336 irt_isaddr(ir->t));
1337 emit_i32(as, k);
1338 emit_mrm(as, XO_MOVmi, REX_64IR(ir, 0), RID_MRM);
1339 }
1340 }
1341}
1342
1343#if LJ_64
1344static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck)
1345{
1346 if (ra_used(ir) || typecheck) {
1347 Reg dest = ra_dest(as, ir, RSET_GPR);
1348 if (typecheck) {
1349 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, dest));
1350 asm_guardcc(as, CC_NE);
1351 emit_i8(as, -2);
1352 emit_rr(as, XO_ARITHi8, XOg_CMP, tmp);
1353 emit_shifti(as, XOg_SAR|REX_64, tmp, 47);
1354 emit_rr(as, XO_MOV, tmp|REX_64, dest);
1355 }
1356 return dest;
1357 } else {
1358 return RID_NONE;
1359 }
1360}
1361#endif
1362
1363static void asm_ahuvload(ASMState *as, IRIns *ir)
1364{
1365 lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) ||
1366 (LJ_DUALNUM && irt_isint(ir->t)));
1367#if LJ_64
1368 if (irt_islightud(ir->t)) {
1369 Reg dest = asm_load_lightud64(as, ir, 1);
1370 if (ra_hasreg(dest)) {
1371 asm_fuseahuref(as, ir->op1, RSET_GPR);
1372 emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM);
1373 }
1374 return;
1375 } else
1376#endif
1377 if (ra_used(ir)) {
1378 RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR;
1379 Reg dest = ra_dest(as, ir, allow);
1380 asm_fuseahuref(as, ir->op1, RSET_GPR);
1381 emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XMM_MOVRM(as), dest, RID_MRM);
1382 } else {
1383 asm_fuseahuref(as, ir->op1, RSET_GPR);
1384 }
1385 /* Always do the type check, even if the load result is unused. */
1386 as->mrm.ofs += 4;
1387 asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE);
1388 if (LJ_64 && irt_type(ir->t) >= IRT_NUM) {
1389 lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t));
1390 emit_u32(as, LJ_TISNUM);
1391 emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM);
1392 } else {
1393 emit_i8(as, irt_toitype(ir->t));
1394 emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM);
1395 }
1396}
1397
1398static void asm_ahustore(ASMState *as, IRIns *ir)
1399{
1400 if (ir->r == RID_SINK)
1401 return;
1402 if (irt_isnum(ir->t)) {
1403 Reg src = ra_alloc1(as, ir->op2, RSET_FPR);
1404 asm_fuseahuref(as, ir->op1, RSET_GPR);
1405 emit_mrm(as, XO_MOVSDto, src, RID_MRM);
1406#if LJ_64
1407 } else if (irt_islightud(ir->t)) {
1408 Reg src = ra_alloc1(as, ir->op2, RSET_GPR);
1409 asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src));
1410 emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM);
1411#endif
1412 } else {
1413 IRIns *irr = IR(ir->op2);
1414 RegSet allow = RSET_GPR;
1415 Reg src = RID_NONE;
1416 if (!irref_isk(ir->op2)) {
1417 src = ra_alloc1(as, ir->op2, allow);
1418 rset_clear(allow, src);
1419 }
1420 asm_fuseahuref(as, ir->op1, allow);
1421 if (ra_hasreg(src)) {
1422 emit_mrm(as, XO_MOVto, src, RID_MRM);
1423 } else if (!irt_ispri(irr->t)) {
1424 lua_assert(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t)));
1425 emit_i32(as, irr->i);
1426 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1427 }
1428 as->mrm.ofs += 4;
1429 emit_i32(as, (int32_t)irt_toitype(ir->t));
1430 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1431 }
1432}
1433
1434static void asm_sload(ASMState *as, IRIns *ir)
1435{
1436 int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
1437 IRType1 t = ir->t;
1438 Reg base;
1439 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */
1440 lua_assert(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK));
1441 lua_assert(LJ_DUALNUM ||
1442 !irt_isint(t) || (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME)));
1443 if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) {
1444 Reg left = ra_scratch(as, RSET_FPR);
1445 asm_tointg(as, ir, left); /* Frees dest reg. Do this before base alloc. */
1446 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1447 emit_rmro(as, XMM_MOVRM(as), left, base, ofs);
1448 t.irt = IRT_NUM; /* Continue with a regular number type check. */
1449#if LJ_64
1450 } else if (irt_islightud(t)) {
1451 Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK));
1452 if (ra_hasreg(dest)) {
1453 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1454 emit_rmro(as, XO_MOV, dest|REX_64, base, ofs);
1455 }
1456 return;
1457#endif
1458 } else if (ra_used(ir)) {
1459 RegSet allow = irt_isnum(t) ? RSET_FPR : RSET_GPR;
1460 Reg dest = ra_dest(as, ir, allow);
1461 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1462 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t));
1463 if ((ir->op2 & IRSLOAD_CONVERT)) {
1464 t.irt = irt_isint(t) ? IRT_NUM : IRT_INT; /* Check for original type. */
1465 emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTSD2SI, dest, base, ofs);
1466 } else if (irt_isnum(t)) {
1467 emit_rmro(as, XMM_MOVRM(as), dest, base, ofs);
1468 } else {
1469 emit_rmro(as, XO_MOV, dest, base, ofs);
1470 }
1471 } else {
1472 if (!(ir->op2 & IRSLOAD_TYPECHECK))
1473 return; /* No type check: avoid base alloc. */
1474 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1475 }
1476 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1477 /* Need type check, even if the load result is unused. */
1478 asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE);
1479 if (LJ_64 && irt_type(t) >= IRT_NUM) {
1480 lua_assert(irt_isinteger(t) || irt_isnum(t));
1481 emit_u32(as, LJ_TISNUM);
1482 emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4);
1483 } else {
1484 emit_i8(as, irt_toitype(t));
1485 emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4);
1486 }
1487 }
1488}
1489
1490/* -- Allocations --------------------------------------------------------- */
1491
1492#if LJ_HASFFI
1493static void asm_cnew(ASMState *as, IRIns *ir)
1494{
1495 CTState *cts = ctype_ctsG(J2G(as->J));
1496 CTypeID ctypeid = (CTypeID)IR(ir->op1)->i;
1497 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ?
1498 lj_ctype_size(cts, ctypeid) : (CTSize)IR(ir->op2)->i;
1499 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1500 IRRef args[2];
1501 lua_assert(sz != CTSIZE_INVALID);
1502
1503 args[0] = ASMREF_L; /* lua_State *L */
1504 args[1] = ASMREF_TMP1; /* MSize size */
1505 as->gcsteps++;
1506 asm_setupresult(as, ir, ci); /* GCcdata * */
1507
1508 /* Initialize immutable cdata object. */
1509 if (ir->o == IR_CNEWI) {
1510 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1511#if LJ_64
1512 Reg r64 = sz == 8 ? REX_64 : 0;
1513 if (irref_isk(ir->op2)) {
1514 IRIns *irk = IR(ir->op2);
1515 uint64_t k = irk->o == IR_KINT64 ? ir_k64(irk)->u64 :
1516 (uint64_t)(uint32_t)irk->i;
1517 if (sz == 4 || checki32((int64_t)k)) {
1518 emit_i32(as, (int32_t)k);
1519 emit_rmro(as, XO_MOVmi, r64, RID_RET, sizeof(GCcdata));
1520 } else {
1521 emit_movtomro(as, RID_ECX + r64, RID_RET, sizeof(GCcdata));
1522 emit_loadu64(as, RID_ECX, k);
1523 }
1524 } else {
1525 Reg r = ra_alloc1(as, ir->op2, allow);
1526 emit_movtomro(as, r + r64, RID_RET, sizeof(GCcdata));
1527 }
1528#else
1529 int32_t ofs = sizeof(GCcdata);
1530 if (sz == 8) {
1531 ofs += 4; ir++;
1532 lua_assert(ir->o == IR_HIOP);
1533 }
1534 do {
1535 if (irref_isk(ir->op2)) {
1536 emit_movmroi(as, RID_RET, ofs, IR(ir->op2)->i);
1537 } else {
1538 Reg r = ra_alloc1(as, ir->op2, allow);
1539 emit_movtomro(as, r, RID_RET, ofs);
1540 rset_clear(allow, r);
1541 }
1542 if (ofs == sizeof(GCcdata)) break;
1543 ofs -= 4; ir--;
1544 } while (1);
1545#endif
1546 lua_assert(sz == 4 || sz == 8);
1547 }
1548
1549 /* Combine initialization of marked, gct and ctypeid. */
1550 emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked));
1551 emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX,
1552 (int32_t)((~LJ_TCDATA<<8)+(ctypeid<<16)));
1553 emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES);
1554 emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite);
1555
1556 asm_gencall(as, ci, args);
1557 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata)));
1558}
1559#else
1560#define asm_cnew(as, ir) ((void)0)
1561#endif
1562
1563/* -- Write barriers ------------------------------------------------------ */
1564
1565static void asm_tbar(ASMState *as, IRIns *ir)
1566{
1567 Reg tab = ra_alloc1(as, ir->op1, RSET_GPR);
1568 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab));
1569 MCLabel l_end = emit_label(as);
1570 emit_movtomro(as, tmp, tab, offsetof(GCtab, gclist));
1571 emit_setgl(as, tab, gc.grayagain);
1572 emit_getgl(as, tmp, gc.grayagain);
1573 emit_i8(as, ~LJ_GC_BLACK);
1574 emit_rmro(as, XO_ARITHib, XOg_AND, tab, offsetof(GCtab, marked));
1575 emit_sjcc(as, CC_Z, l_end);
1576 emit_i8(as, LJ_GC_BLACK);
1577 emit_rmro(as, XO_GROUP3b, XOg_TEST, tab, offsetof(GCtab, marked));
1578}
1579
1580static void asm_obar(ASMState *as, IRIns *ir)
1581{
1582 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv];
1583 IRRef args[2];
1584 MCLabel l_end;
1585 Reg obj;
1586 /* No need for other object barriers (yet). */
1587 lua_assert(IR(ir->op1)->o == IR_UREFC);
1588 ra_evictset(as, RSET_SCRATCH);
1589 l_end = emit_label(as);
1590 args[0] = ASMREF_TMP1; /* global_State *g */
1591 args[1] = ir->op1; /* TValue *tv */
1592 asm_gencall(as, ci, args);
1593 emit_loada(as, ra_releasetmp(as, ASMREF_TMP1), J2G(as->J));
1594 obj = IR(ir->op1)->r;
1595 emit_sjcc(as, CC_Z, l_end);
1596 emit_i8(as, LJ_GC_WHITES);
1597 if (irref_isk(ir->op2)) {
1598 GCobj *vp = ir_kgc(IR(ir->op2));
1599 emit_rma(as, XO_GROUP3b, XOg_TEST, &vp->gch.marked);
1600 } else {
1601 Reg val = ra_alloc1(as, ir->op2, rset_exclude(RSET_SCRATCH&RSET_GPR, obj));
1602 emit_rmro(as, XO_GROUP3b, XOg_TEST, val, (int32_t)offsetof(GChead, marked));
1603 }
1604 emit_sjcc(as, CC_Z, l_end);
1605 emit_i8(as, LJ_GC_BLACK);
1606 emit_rmro(as, XO_GROUP3b, XOg_TEST, obj,
1607 (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv));
1608}
1609
1610/* -- FP/int arithmetic and logic operations ------------------------------ */
1611
1612/* Load reference onto x87 stack. Force a spill to memory if needed. */
1613static void asm_x87load(ASMState *as, IRRef ref)
1614{
1615 IRIns *ir = IR(ref);
1616 if (ir->o == IR_KNUM) {
1617 cTValue *tv = ir_knum(ir);
1618 if (tvispzero(tv)) /* Use fldz only for +0. */
1619 emit_x87op(as, XI_FLDZ);
1620 else if (tvispone(tv))
1621 emit_x87op(as, XI_FLD1);
1622 else
1623 emit_rma(as, XO_FLDq, XOg_FLDq, tv);
1624 } else if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT && !ra_used(ir) &&
1625 !irref_isk(ir->op1) && mayfuse(as, ir->op1)) {
1626 IRIns *iri = IR(ir->op1);
1627 emit_rmro(as, XO_FILDd, XOg_FILDd, RID_ESP, ra_spill(as, iri));
1628 } else {
1629 emit_mrm(as, XO_FLDq, XOg_FLDq, asm_fuseload(as, ref, RSET_EMPTY));
1630 }
1631}
1632
1633/* Try to rejoin pow from EXP2, MUL and LOG2 (if still unsplit). */
1634static int fpmjoin_pow(ASMState *as, IRIns *ir)
1635{
1636 IRIns *irp = IR(ir->op1);
1637 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) {
1638 IRIns *irpp = IR(irp->op1);
1639 if (irpp == ir-2 && irpp->o == IR_FPMATH &&
1640 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) {
1641 /* The modified regs must match with the *.dasc implementation. */
1642 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1643 IRIns *irx;
1644 if (ra_hasreg(ir->r))
1645 rset_clear(drop, ir->r); /* Dest reg handled below. */
1646 ra_evictset(as, drop);
1647 ra_destreg(as, ir, RID_XMM0);
1648 emit_call(as, lj_vm_pow_sse);
1649 irx = IR(irpp->op1);
1650 if (ra_noreg(irx->r) && ra_gethint(irx->r) == RID_XMM1)
1651 irx->r = RID_INIT; /* Avoid allocating xmm1 for x. */
1652 ra_left(as, RID_XMM0, irpp->op1);
1653 ra_left(as, RID_XMM1, irp->op2);
1654 return 1;
1655 }
1656 }
1657 return 0;
1658}
1659
1660static void asm_fpmath(ASMState *as, IRIns *ir)
1661{
1662 IRFPMathOp fpm = ir->o == IR_FPMATH ? (IRFPMathOp)ir->op2 : IRFPM_OTHER;
1663 if (fpm == IRFPM_SQRT) {
1664 Reg dest = ra_dest(as, ir, RSET_FPR);
1665 Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
1666 emit_mrm(as, XO_SQRTSD, dest, left);
1667 } else if (fpm <= IRFPM_TRUNC) {
1668 if (as->flags & JIT_F_SSE4_1) { /* SSE4.1 has a rounding instruction. */
1669 Reg dest = ra_dest(as, ir, RSET_FPR);
1670 Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
1671 /* ROUNDSD has a 4-byte opcode which doesn't fit in x86Op.
1672 ** Let's pretend it's a 3-byte opcode, and compensate afterwards.
1673 ** This is atrocious, but the alternatives are much worse.
1674 */
1675 /* Round down/up/trunc == 1001/1010/1011. */
1676 emit_i8(as, 0x09 + fpm);
1677 emit_mrm(as, XO_ROUNDSD, dest, left);
1678 if (LJ_64 && as->mcp[1] != (MCode)(XO_ROUNDSD >> 16)) {
1679 as->mcp[0] = as->mcp[1]; as->mcp[1] = 0x0f; /* Swap 0F and REX. */
1680 }
1681 *--as->mcp = 0x66; /* 1st byte of ROUNDSD opcode. */
1682 } else { /* Call helper functions for SSE2 variant. */
1683 /* The modified regs must match with the *.dasc implementation. */
1684 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1685 if (ra_hasreg(ir->r))
1686 rset_clear(drop, ir->r); /* Dest reg handled below. */
1687 ra_evictset(as, drop);
1688 ra_destreg(as, ir, RID_XMM0);
1689 emit_call(as, fpm == IRFPM_FLOOR ? lj_vm_floor_sse :
1690 fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse);
1691 ra_left(as, RID_XMM0, ir->op1);
1692 }
1693 } else if (fpm == IRFPM_EXP2 && fpmjoin_pow(as, ir)) {
1694 /* Rejoined to pow(). */
1695 } else { /* Handle x87 ops. */
1696 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
1697 Reg dest = ir->r;
1698 if (ra_hasreg(dest)) {
1699 ra_free(as, dest);
1700 ra_modified(as, dest);
1701 emit_rmro(as, XMM_MOVRM(as), dest, RID_ESP, ofs);
1702 }
1703 emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs);
1704 switch (fpm) { /* st0 = lj_vm_*(st0) */
1705 case IRFPM_EXP: emit_call(as, lj_vm_exp_x87); break;
1706 case IRFPM_EXP2: emit_call(as, lj_vm_exp2_x87); break;
1707 case IRFPM_SIN: emit_x87op(as, XI_FSIN); break;
1708 case IRFPM_COS: emit_x87op(as, XI_FCOS); break;
1709 case IRFPM_TAN: emit_x87op(as, XI_FPOP); emit_x87op(as, XI_FPTAN); break;
1710 case IRFPM_LOG: case IRFPM_LOG2: case IRFPM_LOG10:
1711 /* Note: the use of fyl2xp1 would be pointless here. When computing
1712 ** log(1.0+eps) the precision is already lost after 1.0 is added.
1713 ** Subtracting 1.0 won't recover it. OTOH math.log1p would make sense.
1714 */
1715 emit_x87op(as, XI_FYL2X); break;
1716 case IRFPM_OTHER:
1717 switch (ir->o) {
1718 case IR_ATAN2:
1719 emit_x87op(as, XI_FPATAN); asm_x87load(as, ir->op2); break;
1720 case IR_LDEXP:
1721 emit_x87op(as, XI_FPOP1); emit_x87op(as, XI_FSCALE); break;
1722 default: lua_assert(0); break;
1723 }
1724 break;
1725 default: lua_assert(0); break;
1726 }
1727 asm_x87load(as, ir->op1);
1728 switch (fpm) {
1729 case IRFPM_LOG: emit_x87op(as, XI_FLDLN2); break;
1730 case IRFPM_LOG2: emit_x87op(as, XI_FLD1); break;
1731 case IRFPM_LOG10: emit_x87op(as, XI_FLDLG2); break;
1732 case IRFPM_OTHER:
1733 if (ir->o == IR_LDEXP) asm_x87load(as, ir->op2);
1734 break;
1735 default: break;
1736 }
1737 }
1738}
1739
1740static void asm_fppowi(ASMState *as, IRIns *ir)
1741{
1742 /* The modified regs must match with the *.dasc implementation. */
1743 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1744 if (ra_hasreg(ir->r))
1745 rset_clear(drop, ir->r); /* Dest reg handled below. */
1746 ra_evictset(as, drop);
1747 ra_destreg(as, ir, RID_XMM0);
1748 emit_call(as, lj_vm_powi_sse);
1749 ra_left(as, RID_XMM0, ir->op1);
1750 ra_left(as, RID_EAX, ir->op2);
1751}
1752
1753#if LJ_64 && LJ_HASFFI
1754static void asm_arith64(ASMState *as, IRIns *ir, IRCallID id)
1755{
1756 const CCallInfo *ci = &lj_ir_callinfo[id];
1757 IRRef args[2];
1758 args[0] = ir->op1;
1759 args[1] = ir->op2;
1760 asm_setupresult(as, ir, ci);
1761 asm_gencall(as, ci, args);
1762}
1763#endif
1764
1765static void asm_intmod(ASMState *as, IRIns *ir)
1766{
1767 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_vm_modi];
1768 IRRef args[2];
1769 args[0] = ir->op1;
1770 args[1] = ir->op2;
1771 asm_setupresult(as, ir, ci);
1772 asm_gencall(as, ci, args);
1773}
1774
1775static int asm_swapops(ASMState *as, IRIns *ir)
1776{
1777 IRIns *irl = IR(ir->op1);
1778 IRIns *irr = IR(ir->op2);
1779 lua_assert(ra_noreg(irr->r));
1780 if (!irm_iscomm(lj_ir_mode[ir->o]))
1781 return 0; /* Can't swap non-commutative operations. */
1782 if (irref_isk(ir->op2))
1783 return 0; /* Don't swap constants to the left. */
1784 if (ra_hasreg(irl->r))
1785 return 1; /* Swap if left already has a register. */
1786 if (ra_samehint(ir->r, irr->r))
1787 return 1; /* Swap if dest and right have matching hints. */
1788 if (as->curins > as->loopref) { /* In variant part? */
1789 if (ir->op2 < as->loopref && !irt_isphi(irr->t))
1790 return 0; /* Keep invariants on the right. */
1791 if (ir->op1 < as->loopref && !irt_isphi(irl->t))
1792 return 1; /* Swap invariants to the right. */
1793 }
1794 if (opisfusableload(irl->o))
1795 return 1; /* Swap fusable loads to the right. */
1796 return 0; /* Otherwise don't swap. */
1797}
1798
1799static void asm_fparith(ASMState *as, IRIns *ir, x86Op xo)
1800{
1801 IRRef lref = ir->op1;
1802 IRRef rref = ir->op2;
1803 RegSet allow = RSET_FPR;
1804 Reg dest;
1805 Reg right = IR(rref)->r;
1806 if (ra_hasreg(right)) {
1807 rset_clear(allow, right);
1808 ra_noweak(as, right);
1809 }
1810 dest = ra_dest(as, ir, allow);
1811 if (lref == rref) {
1812 right = dest;
1813 } else if (ra_noreg(right)) {
1814 if (asm_swapops(as, ir)) {
1815 IRRef tmp = lref; lref = rref; rref = tmp;
1816 }
1817 right = asm_fuseload(as, rref, rset_clear(allow, dest));
1818 }
1819 emit_mrm(as, xo, dest, right);
1820 ra_left(as, dest, lref);
1821}
1822
1823static void asm_intarith(ASMState *as, IRIns *ir, x86Arith xa)
1824{
1825 IRRef lref = ir->op1;
1826 IRRef rref = ir->op2;
1827 RegSet allow = RSET_GPR;
1828 Reg dest, right;
1829 int32_t k = 0;
1830 if (as->flagmcp == as->mcp) { /* Drop test r,r instruction. */
1831 as->flagmcp = NULL;
1832 as->mcp += (LJ_64 && *as->mcp < XI_TESTb) ? 3 : 2;
1833 }
1834 right = IR(rref)->r;
1835 if (ra_hasreg(right)) {
1836 rset_clear(allow, right);
1837 ra_noweak(as, right);
1838 }
1839 dest = ra_dest(as, ir, allow);
1840 if (lref == rref) {
1841 right = dest;
1842 } else if (ra_noreg(right) && !asm_isk32(as, rref, &k)) {
1843 if (asm_swapops(as, ir)) {
1844 IRRef tmp = lref; lref = rref; rref = tmp;
1845 }
1846 right = asm_fuseloadm(as, rref, rset_clear(allow, dest), irt_is64(ir->t));
1847 }
1848 if (irt_isguard(ir->t)) /* For IR_ADDOV etc. */
1849 asm_guardcc(as, CC_O);
1850 if (xa != XOg_X_IMUL) {
1851 if (ra_hasreg(right))
1852 emit_mrm(as, XO_ARITH(xa), REX_64IR(ir, dest), right);
1853 else
1854 emit_gri(as, XG_ARITHi(xa), REX_64IR(ir, dest), k);
1855 } else if (ra_hasreg(right)) { /* IMUL r, mrm. */
1856 emit_mrm(as, XO_IMUL, REX_64IR(ir, dest), right);
1857 } else { /* IMUL r, r, k. */
1858 /* NYI: use lea/shl/add/sub (FOLD only does 2^k) depending on CPU. */
1859 Reg left = asm_fuseloadm(as, lref, RSET_GPR, irt_is64(ir->t));
1860 x86Op xo;
1861 if (checki8(k)) { emit_i8(as, k); xo = XO_IMULi8;
1862 } else { emit_i32(as, k); xo = XO_IMULi; }
1863 emit_mrm(as, xo, REX_64IR(ir, dest), left);
1864 return;
1865 }
1866 ra_left(as, dest, lref);
1867}
1868
1869/* LEA is really a 4-operand ADD with an independent destination register,
1870** up to two source registers and an immediate. One register can be scaled
1871** by 1, 2, 4 or 8. This can be used to avoid moves or to fuse several
1872** instructions.
1873**
1874** Currently only a few common cases are supported:
1875** - 3-operand ADD: y = a+b; y = a+k with a and b already allocated
1876** - Left ADD fusion: y = (a+b)+k; y = (a+k)+b
1877** - Right ADD fusion: y = a+(b+k)
1878** The ommited variants have already been reduced by FOLD.
1879**
1880** There are more fusion opportunities, like gathering shifts or joining
1881** common references. But these are probably not worth the trouble, since
1882** array indexing is not decomposed and already makes use of all fields
1883** of the ModRM operand.
1884*/
1885static int asm_lea(ASMState *as, IRIns *ir)
1886{
1887 IRIns *irl = IR(ir->op1);
1888 IRIns *irr = IR(ir->op2);
1889 RegSet allow = RSET_GPR;
1890 Reg dest;
1891 as->mrm.base = as->mrm.idx = RID_NONE;
1892 as->mrm.scale = XM_SCALE1;
1893 as->mrm.ofs = 0;
1894 if (ra_hasreg(irl->r)) {
1895 rset_clear(allow, irl->r);
1896 ra_noweak(as, irl->r);
1897 as->mrm.base = irl->r;
1898 if (irref_isk(ir->op2) || ra_hasreg(irr->r)) {
1899 /* The PHI renaming logic does a better job in some cases. */
1900 if (ra_hasreg(ir->r) &&
1901 ((irt_isphi(irl->t) && as->phireg[ir->r] == ir->op1) ||
1902 (irt_isphi(irr->t) && as->phireg[ir->r] == ir->op2)))
1903 return 0;
1904 if (irref_isk(ir->op2)) {
1905 as->mrm.ofs = irr->i;
1906 } else {
1907 rset_clear(allow, irr->r);
1908 ra_noweak(as, irr->r);
1909 as->mrm.idx = irr->r;
1910 }
1911 } else if (irr->o == IR_ADD && mayfuse(as, ir->op2) &&
1912 irref_isk(irr->op2)) {
1913 Reg idx = ra_alloc1(as, irr->op1, allow);
1914 rset_clear(allow, idx);
1915 as->mrm.idx = (uint8_t)idx;
1916 as->mrm.ofs = IR(irr->op2)->i;
1917 } else {
1918 return 0;
1919 }
1920 } else if (ir->op1 != ir->op2 && irl->o == IR_ADD && mayfuse(as, ir->op1) &&
1921 (irref_isk(ir->op2) || irref_isk(irl->op2))) {
1922 Reg idx, base = ra_alloc1(as, irl->op1, allow);
1923 rset_clear(allow, base);
1924 as->mrm.base = (uint8_t)base;
1925 if (irref_isk(ir->op2)) {
1926 as->mrm.ofs = irr->i;
1927 idx = ra_alloc1(as, irl->op2, allow);
1928 } else {
1929 as->mrm.ofs = IR(irl->op2)->i;
1930 idx = ra_alloc1(as, ir->op2, allow);
1931 }
1932 rset_clear(allow, idx);
1933 as->mrm.idx = (uint8_t)idx;
1934 } else {
1935 return 0;
1936 }
1937 dest = ra_dest(as, ir, allow);
1938 emit_mrm(as, XO_LEA, dest, RID_MRM);
1939 return 1; /* Success. */
1940}
1941
1942static void asm_add(ASMState *as, IRIns *ir)
1943{
1944 if (irt_isnum(ir->t))
1945 asm_fparith(as, ir, XO_ADDSD);
1946 else if ((as->flags & JIT_F_LEA_AGU) || as->flagmcp == as->mcp ||
1947 irt_is64(ir->t) || !asm_lea(as, ir))
1948 asm_intarith(as, ir, XOg_ADD);
1949}
1950
1951static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg)
1952{
1953 Reg dest = ra_dest(as, ir, RSET_GPR);
1954 emit_rr(as, XO_GROUP3, REX_64IR(ir, xg), dest);
1955 ra_left(as, dest, ir->op1);
1956}
1957
1958static void asm_min_max(ASMState *as, IRIns *ir, int cc)
1959{
1960 Reg right, dest = ra_dest(as, ir, RSET_GPR);
1961 IRRef lref = ir->op1, rref = ir->op2;
1962 if (irref_isk(rref)) { lref = rref; rref = ir->op1; }
1963 right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, dest));
1964 emit_rr(as, XO_CMOV + (cc<<24), REX_64IR(ir, dest), right);
1965 emit_rr(as, XO_CMP, REX_64IR(ir, dest), right);
1966 ra_left(as, dest, lref);
1967}
1968
1969static void asm_bitswap(ASMState *as, IRIns *ir)
1970{
1971 Reg dest = ra_dest(as, ir, RSET_GPR);
1972 as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24),
1973 REX_64IR(ir, 0), dest, 0, as->mcp, 1);
1974 ra_left(as, dest, ir->op1);
1975}
1976
1977static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs)
1978{
1979 IRRef rref = ir->op2;
1980 IRIns *irr = IR(rref);
1981 Reg dest;
1982 if (irref_isk(rref)) { /* Constant shifts. */
1983 int shift;
1984 dest = ra_dest(as, ir, RSET_GPR);
1985 shift = irr->i & (irt_is64(ir->t) ? 63 : 31);
1986 switch (shift) {
1987 case 0: break;
1988 case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break;
1989 default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break;
1990 }
1991 } else { /* Variable shifts implicitly use register cl (i.e. ecx). */
1992 Reg right;
1993 dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX));
1994 if (dest == RID_ECX) {
1995 dest = ra_scratch(as, rset_exclude(RSET_GPR, RID_ECX));
1996 emit_rr(as, XO_MOV, RID_ECX, dest);
1997 }
1998 right = irr->r;
1999 if (ra_noreg(right))
2000 right = ra_allocref(as, rref, RID2RSET(RID_ECX));
2001 else if (right != RID_ECX)
2002 ra_scratch(as, RID2RSET(RID_ECX));
2003 emit_rr(as, XO_SHIFTcl, REX_64IR(ir, xs), dest);
2004 ra_noweak(as, right);
2005 if (right != RID_ECX)
2006 emit_rr(as, XO_MOV, RID_ECX, right);
2007 }
2008 ra_left(as, dest, ir->op1);
2009 /*
2010 ** Note: avoid using the flags resulting from a shift or rotate!
2011 ** All of them cause a partial flag stall, except for r,1 shifts
2012 ** (but not rotates). And a shift count of 0 leaves the flags unmodified.
2013 */
2014}
2015
2016/* -- Comparisons --------------------------------------------------------- */
2017
2018/* Virtual flags for unordered FP comparisons. */
2019#define VCC_U 0x1000 /* Unordered. */
2020#define VCC_P 0x2000 /* Needs extra CC_P branch. */
2021#define VCC_S 0x4000 /* Swap avoids CC_P branch. */
2022#define VCC_PS (VCC_P|VCC_S)
2023
2024/* Map of comparisons to flags. ORDER IR. */
2025#define COMPFLAGS(ci, cin, cu, cf) ((ci)+((cu)<<4)+((cin)<<8)+(cf))
2026static const uint16_t asm_compmap[IR_ABC+1] = {
2027 /* signed non-eq unsigned flags */
2028 /* LT */ COMPFLAGS(CC_GE, CC_G, CC_AE, VCC_PS),
2029 /* GE */ COMPFLAGS(CC_L, CC_L, CC_B, 0),
2030 /* LE */ COMPFLAGS(CC_G, CC_G, CC_A, VCC_PS),
2031 /* GT */ COMPFLAGS(CC_LE, CC_L, CC_BE, 0),
2032 /* ULT */ COMPFLAGS(CC_AE, CC_A, CC_AE, VCC_U),
2033 /* UGE */ COMPFLAGS(CC_B, CC_B, CC_B, VCC_U|VCC_PS),
2034 /* ULE */ COMPFLAGS(CC_A, CC_A, CC_A, VCC_U),
2035 /* UGT */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS),
2036 /* EQ */ COMPFLAGS(CC_NE, CC_NE, CC_NE, VCC_P),
2037 /* NE */ COMPFLAGS(CC_E, CC_E, CC_E, VCC_U|VCC_P),
2038 /* ABC */ COMPFLAGS(CC_BE, CC_B, CC_BE, VCC_U|VCC_PS) /* Same as UGT. */
2039};
2040
2041/* FP and integer comparisons. */
2042static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc)
2043{
2044 if (irt_isnum(ir->t)) {
2045 IRRef lref = ir->op1;
2046 IRRef rref = ir->op2;
2047 Reg left, right;
2048 MCLabel l_around;
2049 /*
2050 ** An extra CC_P branch is required to preserve ordered/unordered
2051 ** semantics for FP comparisons. This can be avoided by swapping
2052 ** the operands and inverting the condition (except for EQ and UNE).
2053 ** So always try to swap if possible.
2054 **
2055 ** Another option would be to swap operands to achieve better memory
2056 ** operand fusion. But it's unlikely that this outweighs the cost
2057 ** of the extra branches.
2058 */
2059 if (cc & VCC_S) { /* Swap? */
2060 IRRef tmp = lref; lref = rref; rref = tmp;
2061 cc ^= (VCC_PS|(5<<4)); /* A <-> B, AE <-> BE, PS <-> none */
2062 }
2063 left = ra_alloc1(as, lref, RSET_FPR);
2064 right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left));
2065 l_around = emit_label(as);
2066 asm_guardcc(as, cc >> 4);
2067 if (cc & VCC_P) { /* Extra CC_P branch required? */
2068 if (!(cc & VCC_U)) {
2069 asm_guardcc(as, CC_P); /* Branch to exit for ordered comparisons. */
2070 } else if (l_around != as->invmcp) {
2071 emit_sjcc(as, CC_P, l_around); /* Branch around for unordered. */
2072 } else {
2073 /* Patched to mcloop by asm_loop_fixup. */
2074 as->loopinv = 2;
2075 if (as->realign)
2076 emit_sjcc(as, CC_P, as->mcp);
2077 else
2078 emit_jcc(as, CC_P, as->mcp);
2079 }
2080 }
2081 emit_mrm(as, XO_UCOMISD, left, right);
2082 } else {
2083 IRRef lref = ir->op1, rref = ir->op2;
2084 IROp leftop = (IROp)(IR(lref)->o);
2085 Reg r64 = REX_64IR(ir, 0);
2086 int32_t imm = 0;
2087 lua_assert(irt_is64(ir->t) || irt_isint(ir->t) ||
2088 irt_isu32(ir->t) || irt_isaddr(ir->t) || irt_isu8(ir->t));
2089 /* Swap constants (only for ABC) and fusable loads to the right. */
2090 if (irref_isk(lref) || (!irref_isk(rref) && opisfusableload(leftop))) {
2091 if ((cc & 0xc) == 0xc) cc ^= 0x53; /* L <-> G, LE <-> GE */
2092 else if ((cc & 0xa) == 0x2) cc ^= 0x55; /* A <-> B, AE <-> BE */
2093 lref = ir->op2; rref = ir->op1;
2094 }
2095 if (asm_isk32(as, rref, &imm)) {
2096 IRIns *irl = IR(lref);
2097 /* Check wether we can use test ins. Not for unsigned, since CF=0. */
2098 int usetest = (imm == 0 && (cc & 0xa) != 0x2);
2099 if (usetest && irl->o == IR_BAND && irl+1 == ir && !ra_used(irl)) {
2100 /* Combine comp(BAND(ref, r/imm), 0) into test mrm, r/imm. */
2101 Reg right, left = RID_NONE;
2102 RegSet allow = RSET_GPR;
2103 if (!asm_isk32(as, irl->op2, &imm)) {
2104 left = ra_alloc1(as, irl->op2, allow);
2105 rset_clear(allow, left);
2106 } else { /* Try to Fuse IRT_I8/IRT_U8 loads, too. See below. */
2107 IRIns *irll = IR(irl->op1);
2108 if (opisfusableload((IROp)irll->o) &&
2109 (irt_isi8(irll->t) || irt_isu8(irll->t))) {
2110 IRType1 origt = irll->t; /* Temporarily flip types. */
2111 irll->t.irt = (irll->t.irt & ~IRT_TYPE) | IRT_INT;
2112 as->curins--; /* Skip to BAND to avoid failing in noconflict(). */
2113 right = asm_fuseload(as, irl->op1, RSET_GPR);
2114 as->curins++;
2115 irll->t = origt;
2116 if (right != RID_MRM) goto test_nofuse;
2117 /* Fusion succeeded, emit test byte mrm, imm8. */
2118 asm_guardcc(as, cc);
2119 emit_i8(as, (imm & 0xff));
2120 emit_mrm(as, XO_GROUP3b, XOg_TEST, RID_MRM);
2121 return;
2122 }
2123 }
2124 as->curins--; /* Skip to BAND to avoid failing in noconflict(). */
2125 right = asm_fuseloadm(as, irl->op1, allow, r64);
2126 as->curins++; /* Undo the above. */
2127 test_nofuse:
2128 asm_guardcc(as, cc);
2129 if (ra_noreg(left)) {
2130 emit_i32(as, imm);
2131 emit_mrm(as, XO_GROUP3, r64 + XOg_TEST, right);
2132 } else {
2133 emit_mrm(as, XO_TEST, r64 + left, right);
2134 }
2135 } else {
2136 Reg left;
2137 if (opisfusableload((IROp)irl->o) &&
2138 ((irt_isu8(irl->t) && checku8(imm)) ||
2139 ((irt_isi8(irl->t) || irt_isi16(irl->t)) && checki8(imm)) ||
2140 (irt_isu16(irl->t) && checku16(imm) && checki8((int16_t)imm)))) {
2141 /* Only the IRT_INT case is fused by asm_fuseload.
2142 ** The IRT_I8/IRT_U8 loads and some IRT_I16/IRT_U16 loads
2143 ** are handled here.
2144 ** Note that cmp word [mem], imm16 should not be generated,
2145 ** since it has a length-changing prefix. Compares of a word
2146 ** against a sign-extended imm8 are ok, however.
2147 */
2148 IRType1 origt = irl->t; /* Temporarily flip types. */
2149 irl->t.irt = (irl->t.irt & ~IRT_TYPE) | IRT_INT;
2150 left = asm_fuseload(as, lref, RSET_GPR);
2151 irl->t = origt;
2152 if (left == RID_MRM) { /* Fusion succeeded? */
2153 if (irt_isu8(irl->t) || irt_isu16(irl->t))
2154 cc >>= 4; /* Need unsigned compare. */
2155 asm_guardcc(as, cc);
2156 emit_i8(as, imm);
2157 emit_mrm(as, (irt_isi8(origt) || irt_isu8(origt)) ?
2158 XO_ARITHib : XO_ARITHiw8, r64 + XOg_CMP, RID_MRM);
2159 return;
2160 } /* Otherwise handle register case as usual. */
2161 } else {
2162 left = asm_fuseloadm(as, lref,
2163 irt_isu8(ir->t) ? RSET_GPR8 : RSET_GPR, r64);
2164 }
2165 asm_guardcc(as, cc);
2166 if (usetest && left != RID_MRM) {
2167 /* Use test r,r instead of cmp r,0. */
2168 x86Op xo = XO_TEST;
2169 if (irt_isu8(ir->t)) {
2170 lua_assert(ir->o == IR_EQ || ir->o == IR_NE);
2171 xo = XO_TESTb;
2172 if (!rset_test(RSET_RANGE(RID_EAX, RID_EBX+1), left)) {
2173 if (LJ_64) {
2174 left |= FORCE_REX;
2175 } else {
2176 emit_i32(as, 0xff);
2177 emit_mrm(as, XO_GROUP3, XOg_TEST, left);
2178 return;
2179 }
2180 }
2181 }
2182 emit_rr(as, xo, r64 + left, left);
2183 if (irl+1 == ir) /* Referencing previous ins? */
2184 as->flagmcp = as->mcp; /* Set flag to drop test r,r if possible. */
2185 } else {
2186 emit_gmrmi(as, XG_ARITHi(XOg_CMP), r64 + left, imm);
2187 }
2188 }
2189 } else {
2190 Reg left = ra_alloc1(as, lref, RSET_GPR);
2191 Reg right = asm_fuseloadm(as, rref, rset_exclude(RSET_GPR, left), r64);
2192 asm_guardcc(as, cc);
2193 emit_mrm(as, XO_CMP, r64 + left, right);
2194 }
2195 }
2196}
2197
2198#if LJ_32 && LJ_HASFFI
2199/* 64 bit integer comparisons in 32 bit mode. */
2200static void asm_comp_int64(ASMState *as, IRIns *ir)
2201{
2202 uint32_t cc = asm_compmap[(ir-1)->o];
2203 RegSet allow = RSET_GPR;
2204 Reg lefthi = RID_NONE, leftlo = RID_NONE;
2205 Reg righthi = RID_NONE, rightlo = RID_NONE;
2206 MCLabel l_around;
2207 x86ModRM mrm;
2208
2209 as->curins--; /* Skip loword ins. Avoids failing in noconflict(), too. */
2210
2211 /* Allocate/fuse hiword operands. */
2212 if (irref_isk(ir->op2)) {
2213 lefthi = asm_fuseload(as, ir->op1, allow);
2214 } else {
2215 lefthi = ra_alloc1(as, ir->op1, allow);
2216 rset_clear(allow, lefthi);
2217 righthi = asm_fuseload(as, ir->op2, allow);
2218 if (righthi == RID_MRM) {
2219 if (as->mrm.base != RID_NONE) rset_clear(allow, as->mrm.base);
2220 if (as->mrm.idx != RID_NONE) rset_clear(allow, as->mrm.idx);
2221 } else {
2222 rset_clear(allow, righthi);
2223 }
2224 }
2225 mrm = as->mrm; /* Save state for hiword instruction. */
2226
2227 /* Allocate/fuse loword operands. */
2228 if (irref_isk((ir-1)->op2)) {
2229 leftlo = asm_fuseload(as, (ir-1)->op1, allow);
2230 } else {
2231 leftlo = ra_alloc1(as, (ir-1)->op1, allow);
2232 rset_clear(allow, leftlo);
2233 rightlo = asm_fuseload(as, (ir-1)->op2, allow);
2234 }
2235
2236 /* All register allocations must be performed _before_ this point. */
2237 l_around = emit_label(as);
2238 as->invmcp = as->flagmcp = NULL; /* Cannot use these optimizations. */
2239
2240 /* Loword comparison and branch. */
2241 asm_guardcc(as, cc >> 4); /* Always use unsigned compare for loword. */
2242 if (ra_noreg(rightlo)) {
2243 int32_t imm = IR((ir-1)->op2)->i;
2244 if (imm == 0 && ((cc >> 4) & 0xa) != 0x2 && leftlo != RID_MRM)
2245 emit_rr(as, XO_TEST, leftlo, leftlo);
2246 else
2247 emit_gmrmi(as, XG_ARITHi(XOg_CMP), leftlo, imm);
2248 } else {
2249 emit_mrm(as, XO_CMP, leftlo, rightlo);
2250 }
2251
2252 /* Hiword comparison and branches. */
2253 if ((cc & 15) != CC_NE)
2254 emit_sjcc(as, CC_NE, l_around); /* Hiword unequal: skip loword compare. */
2255 if ((cc & 15) != CC_E)
2256 asm_guardcc(as, cc >> 8); /* Hiword compare without equality check. */
2257 as->mrm = mrm; /* Restore state. */
2258 if (ra_noreg(righthi)) {
2259 int32_t imm = IR(ir->op2)->i;
2260 if (imm == 0 && (cc & 0xa) != 0x2 && lefthi != RID_MRM)
2261 emit_rr(as, XO_TEST, lefthi, lefthi);
2262 else
2263 emit_gmrmi(as, XG_ARITHi(XOg_CMP), lefthi, imm);
2264 } else {
2265 emit_mrm(as, XO_CMP, lefthi, righthi);
2266 }
2267}
2268#endif
2269
2270/* -- Support for 64 bit ops in 32 bit mode ------------------------------- */
2271
2272/* Hiword op of a split 64 bit op. Previous op must be the loword op. */
2273static void asm_hiop(ASMState *as, IRIns *ir)
2274{
2275#if LJ_32 && LJ_HASFFI
2276 /* HIOP is marked as a store because it needs its own DCE logic. */
2277 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */
2278 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1;
2279 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */
2280 if (usehi || uselo) {
2281 if (irt_isfp(ir->t))
2282 asm_conv_fp_int64(as, ir);
2283 else
2284 asm_conv_int64_fp(as, ir);
2285 }
2286 as->curins--; /* Always skip the CONV. */
2287 return;
2288 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */
2289 asm_comp_int64(as, ir);
2290 return;
2291 } else if ((ir-1)->o == IR_XSTORE) {
2292 if ((ir-1)->r != RID_SINK)
2293 asm_fxstore(as, ir);
2294 return;
2295 }
2296 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */
2297 switch ((ir-1)->o) {
2298 case IR_ADD:
2299 as->flagmcp = NULL;
2300 as->curins--;
2301 asm_intarith(as, ir, XOg_ADC);
2302 asm_intarith(as, ir-1, XOg_ADD);
2303 break;
2304 case IR_SUB:
2305 as->flagmcp = NULL;
2306 as->curins--;
2307 asm_intarith(as, ir, XOg_SBB);
2308 asm_intarith(as, ir-1, XOg_SUB);
2309 break;
2310 case IR_NEG: {
2311 Reg dest = ra_dest(as, ir, RSET_GPR);
2312 emit_rr(as, XO_GROUP3, XOg_NEG, dest);
2313 emit_i8(as, 0);
2314 emit_rr(as, XO_ARITHi8, XOg_ADC, dest);
2315 ra_left(as, dest, ir->op1);
2316 as->curins--;
2317 asm_neg_not(as, ir-1, XOg_NEG);
2318 break;
2319 }
2320 case IR_CALLN:
2321 case IR_CALLXS:
2322 if (!uselo)
2323 ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */
2324 break;
2325 case IR_CNEWI:
2326 /* Nothing to do here. Handled by CNEWI itself. */
2327 break;
2328 default: lua_assert(0); break;
2329 }
2330#else
2331 UNUSED(as); UNUSED(ir); lua_assert(0); /* Unused on x64 or without FFI. */
2332#endif
2333}
2334
2335/* -- Stack handling ------------------------------------------------------ */
2336
2337/* Check Lua stack size for overflow. Use exit handler as fallback. */
2338static void asm_stack_check(ASMState *as, BCReg topslot,
2339 IRIns *irp, RegSet allow, ExitNo exitno)
2340{
2341 /* Try to get an unused temp. register, otherwise spill/restore eax. */
2342 Reg pbase = irp ? irp->r : RID_BASE;
2343 Reg r = allow ? rset_pickbot(allow) : RID_EAX;
2344 emit_jcc(as, CC_B, exitstub_addr(as->J, exitno));
2345 if (allow == RSET_EMPTY) /* Restore temp. register. */
2346 emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0);
2347 else
2348 ra_modified(as, r);
2349 emit_gri(as, XG_ARITHi(XOg_CMP), r, (int32_t)(8*topslot));
2350 if (ra_hasreg(pbase) && pbase != r)
2351 emit_rr(as, XO_ARITH(XOg_SUB), r, pbase);
2352 else
2353 emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE,
2354 ptr2addr(&J2G(as->J)->jit_base));
2355 emit_rmro(as, XO_MOV, r, r, offsetof(lua_State, maxstack));
2356 emit_getgl(as, r, jit_L);
2357 if (allow == RSET_EMPTY) /* Spill temp. register. */
2358 emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0);
2359}
2360
2361/* Restore Lua stack from on-trace state. */
2362static void asm_stack_restore(ASMState *as, SnapShot *snap)
2363{
2364 SnapEntry *map = &as->T->snapmap[snap->mapofs];
2365 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1];
2366 MSize n, nent = snap->nent;
2367 /* Store the value of all modified slots to the Lua stack. */
2368 for (n = 0; n < nent; n++) {
2369 SnapEntry sn = map[n];
2370 BCReg s = snap_slot(sn);
2371 int32_t ofs = 8*((int32_t)s-1);
2372 IRRef ref = snap_ref(sn);
2373 IRIns *ir = IR(ref);
2374 if ((sn & SNAP_NORESTORE))
2375 continue;
2376 if (irt_isnum(ir->t)) {
2377 Reg src = ra_alloc1(as, ref, RSET_FPR);
2378 emit_rmro(as, XO_MOVSDto, src, RID_BASE, ofs);
2379 } else {
2380 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) ||
2381 (LJ_DUALNUM && irt_isinteger(ir->t)));
2382 if (!irref_isk(ref)) {
2383 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE));
2384 emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs);
2385 } else if (!irt_ispri(ir->t)) {
2386 emit_movmroi(as, RID_BASE, ofs, ir->i);
2387 }
2388 if ((sn & (SNAP_CONT|SNAP_FRAME))) {
2389 if (s != 0) /* Do not overwrite link to previous frame. */
2390 emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--));
2391 } else {
2392 if (!(LJ_64 && irt_islightud(ir->t)))
2393 emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t));
2394 }
2395 }
2396 checkmclim(as);
2397 }
2398 lua_assert(map + nent == flinks);
2399}
2400
2401/* -- GC handling --------------------------------------------------------- */
2402
2403/* Check GC threshold and do one or more GC steps. */
2404static void asm_gc_check(ASMState *as)
2405{
2406 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit];
2407 IRRef args[2];
2408 MCLabel l_end;
2409 Reg tmp;
2410 ra_evictset(as, RSET_SCRATCH);
2411 l_end = emit_label(as);
2412 /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */
2413 asm_guardcc(as, CC_NE); /* Assumes asm_snap_prep() already done. */
2414 emit_rr(as, XO_TEST, RID_RET, RID_RET);
2415 args[0] = ASMREF_TMP1; /* global_State *g */
2416 args[1] = ASMREF_TMP2; /* MSize steps */
2417 asm_gencall(as, ci, args);
2418 tmp = ra_releasetmp(as, ASMREF_TMP1);
2419 emit_loada(as, tmp, J2G(as->J));
2420 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), as->gcsteps);
2421 /* Jump around GC step if GC total < GC threshold. */
2422 emit_sjcc(as, CC_B, l_end);
2423 emit_opgl(as, XO_ARITH(XOg_CMP), tmp, gc.threshold);
2424 emit_getgl(as, tmp, gc.total);
2425 as->gcsteps = 0;
2426 checkmclim(as);
2427}
2428
2429/* -- Loop handling ------------------------------------------------------- */
2430
2431/* Fixup the loop branch. */
2432static void asm_loop_fixup(ASMState *as)
2433{
2434 MCode *p = as->mctop;
2435 MCode *target = as->mcp;
2436 if (as->realign) { /* Realigned loops use short jumps. */
2437 as->realign = NULL; /* Stop another retry. */
2438 lua_assert(((intptr_t)target & 15) == 0);
2439 if (as->loopinv) { /* Inverted loop branch? */
2440 p -= 5;
2441 p[0] = XI_JMP;
2442 lua_assert(target - p >= -128);
2443 p[-1] = (MCode)(target - p); /* Patch sjcc. */
2444 if (as->loopinv == 2)
2445 p[-3] = (MCode)(target - p + 2); /* Patch opt. short jp. */
2446 } else {
2447 lua_assert(target - p >= -128);
2448 p[-1] = (MCode)(int8_t)(target - p); /* Patch short jmp. */
2449 p[-2] = XI_JMPs;
2450 }
2451 } else {
2452 MCode *newloop;
2453 p[-5] = XI_JMP;
2454 if (as->loopinv) { /* Inverted loop branch? */
2455 /* asm_guardcc already inverted the jcc and patched the jmp. */
2456 p -= 5;
2457 newloop = target+4;
2458 *(int32_t *)(p-4) = (int32_t)(target - p); /* Patch jcc. */
2459 if (as->loopinv == 2) {
2460 *(int32_t *)(p-10) = (int32_t)(target - p + 6); /* Patch opt. jp. */
2461 newloop = target+8;
2462 }
2463 } else { /* Otherwise just patch jmp. */
2464 *(int32_t *)(p-4) = (int32_t)(target - p);
2465 newloop = target+3;
2466 }
2467 /* Realign small loops and shorten the loop branch. */
2468 if (newloop >= p - 128) {
2469 as->realign = newloop; /* Force a retry and remember alignment. */
2470 as->curins = as->stopins; /* Abort asm_trace now. */
2471 as->T->nins = as->orignins; /* Remove any added renames. */
2472 }
2473 }
2474}
2475
2476/* -- Head of trace ------------------------------------------------------- */
2477
2478/* Coalesce BASE register for a root trace. */
2479static void asm_head_root_base(ASMState *as)
2480{
2481 IRIns *ir = IR(REF_BASE);
2482 Reg r = ir->r;
2483 if (ra_hasreg(r)) {
2484 ra_free(as, r);
2485 if (rset_test(as->modset, r) || irt_ismarked(ir->t))
2486 ir->r = RID_INIT; /* No inheritance for modified BASE register. */
2487 if (r != RID_BASE)
2488 emit_rr(as, XO_MOV, r, RID_BASE);
2489 }
2490}
2491
2492/* Coalesce or reload BASE register for a side trace. */
2493static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow)
2494{
2495 IRIns *ir = IR(REF_BASE);
2496 Reg r = ir->r;
2497 if (ra_hasreg(r)) {
2498 ra_free(as, r);
2499 if (rset_test(as->modset, r) || irt_ismarked(ir->t))
2500 ir->r = RID_INIT; /* No inheritance for modified BASE register. */
2501 if (irp->r == r) {
2502 rset_clear(allow, r); /* Mark same BASE register as coalesced. */
2503 } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) {
2504 rset_clear(allow, irp->r);
2505 emit_rr(as, XO_MOV, r, irp->r); /* Move from coalesced parent reg. */
2506 } else {
2507 emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */
2508 }
2509 }
2510 return allow;
2511}
2512
2513/* -- Tail of trace ------------------------------------------------------- */
2514
2515/* Fixup the tail code. */
2516static void asm_tail_fixup(ASMState *as, TraceNo lnk)
2517{
2518 /* Note: don't use as->mcp swap + emit_*: emit_op overwrites more bytes. */
2519 MCode *p = as->mctop;
2520 MCode *target, *q;
2521 int32_t spadj = as->T->spadjust;
2522 if (spadj == 0) {
2523 p -= ((as->flags & JIT_F_LEA_AGU) ? 7 : 6) + (LJ_64 ? 1 : 0);
2524 } else {
2525 MCode *p1;
2526 /* Patch stack adjustment. */
2527 if (checki8(spadj)) {
2528 p -= 3;
2529 p1 = p-6;
2530 *p1 = (MCode)spadj;
2531 } else {
2532 p1 = p-9;
2533 *(int32_t *)p1 = spadj;
2534 }
2535 if ((as->flags & JIT_F_LEA_AGU)) {
2536#if LJ_64
2537 p1[-4] = 0x48;
2538#endif
2539 p1[-3] = (MCode)XI_LEA;
2540 p1[-2] = MODRM(checki8(spadj) ? XM_OFS8 : XM_OFS32, RID_ESP, RID_ESP);
2541 p1[-1] = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
2542 } else {
2543#if LJ_64
2544 p1[-3] = 0x48;
2545#endif
2546 p1[-2] = (MCode)(checki8(spadj) ? XI_ARITHi8 : XI_ARITHi);
2547 p1[-1] = MODRM(XM_REG, XOg_ADD, RID_ESP);
2548 }
2549 }
2550 /* Patch exit branch. */
2551 target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)lj_vm_exit_interp;
2552 *(int32_t *)(p-4) = jmprel(p, target);
2553 p[-5] = XI_JMP;
2554 /* Drop unused mcode tail. Fill with NOPs to make the prefetcher happy. */
2555 for (q = as->mctop-1; q >= p; q--)
2556 *q = XI_NOP;
2557 as->mctop = p;
2558}
2559
2560/* Prepare tail of code. */
2561static void asm_tail_prep(ASMState *as)
2562{
2563 MCode *p = as->mctop;
2564 /* Realign and leave room for backwards loop branch or exit branch. */
2565 if (as->realign) {
2566 int i = ((int)(intptr_t)as->realign) & 15;
2567 /* Fill unused mcode tail with NOPs to make the prefetcher happy. */
2568 while (i-- > 0)
2569 *--p = XI_NOP;
2570 as->mctop = p;
2571 p -= (as->loopinv ? 5 : 2); /* Space for short/near jmp. */
2572 } else {
2573 p -= 5; /* Space for exit branch (near jmp). */
2574 }
2575 if (as->loopref) {
2576 as->invmcp = as->mcp = p;
2577 } else {
2578 /* Leave room for ESP adjustment: add esp, imm or lea esp, [esp+imm] */
2579 as->mcp = p - (((as->flags & JIT_F_LEA_AGU) ? 7 : 6) + (LJ_64 ? 1 : 0));
2580 as->invmcp = NULL;
2581 }
2582}
2583
2584/* -- Instruction dispatch ------------------------------------------------ */
2585
2586/* Assemble a single instruction. */
2587static void asm_ir(ASMState *as, IRIns *ir)
2588{
2589 switch ((IROp)ir->o) {
2590 /* Miscellaneous ops. */
2591 case IR_LOOP: asm_loop(as); break;
2592 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
2593 case IR_USE:
2594 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
2595 case IR_PHI: asm_phi(as, ir); break;
2596 case IR_HIOP: asm_hiop(as, ir); break;
2597 case IR_GCSTEP: asm_gcstep(as, ir); break;
2598
2599 /* Guarded assertions. */
2600 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
2601 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
2602 case IR_EQ: case IR_NE: case IR_ABC:
2603 asm_comp(as, ir, asm_compmap[ir->o]);
2604 break;
2605
2606 case IR_RETF: asm_retf(as, ir); break;
2607
2608 /* Bit ops. */
2609 case IR_BNOT: asm_neg_not(as, ir, XOg_NOT); break;
2610 case IR_BSWAP: asm_bitswap(as, ir); break;
2611
2612 case IR_BAND: asm_intarith(as, ir, XOg_AND); break;
2613 case IR_BOR: asm_intarith(as, ir, XOg_OR); break;
2614 case IR_BXOR: asm_intarith(as, ir, XOg_XOR); break;
2615
2616 case IR_BSHL: asm_bitshift(as, ir, XOg_SHL); break;
2617 case IR_BSHR: asm_bitshift(as, ir, XOg_SHR); break;
2618 case IR_BSAR: asm_bitshift(as, ir, XOg_SAR); break;
2619 case IR_BROL: asm_bitshift(as, ir, XOg_ROL); break;
2620 case IR_BROR: asm_bitshift(as, ir, XOg_ROR); break;
2621
2622 /* Arithmetic ops. */
2623 case IR_ADD: asm_add(as, ir); break;
2624 case IR_SUB:
2625 if (irt_isnum(ir->t))
2626 asm_fparith(as, ir, XO_SUBSD);
2627 else /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */
2628 asm_intarith(as, ir, XOg_SUB);
2629 break;
2630 case IR_MUL:
2631 if (irt_isnum(ir->t))
2632 asm_fparith(as, ir, XO_MULSD);
2633 else
2634 asm_intarith(as, ir, XOg_X_IMUL);
2635 break;
2636 case IR_DIV:
2637#if LJ_64 && LJ_HASFFI
2638 if (!irt_isnum(ir->t))
2639 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
2640 IRCALL_lj_carith_divu64);
2641 else
2642#endif
2643 asm_fparith(as, ir, XO_DIVSD);
2644 break;
2645 case IR_MOD:
2646#if LJ_64 && LJ_HASFFI
2647 if (!irt_isint(ir->t))
2648 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
2649 IRCALL_lj_carith_modu64);
2650 else
2651#endif
2652 asm_intmod(as, ir);
2653 break;
2654
2655 case IR_NEG:
2656 if (irt_isnum(ir->t))
2657 asm_fparith(as, ir, XO_XORPS);
2658 else
2659 asm_neg_not(as, ir, XOg_NEG);
2660 break;
2661 case IR_ABS: asm_fparith(as, ir, XO_ANDPS); break;
2662
2663 case IR_MIN:
2664 if (irt_isnum(ir->t))
2665 asm_fparith(as, ir, XO_MINSD);
2666 else
2667 asm_min_max(as, ir, CC_G);
2668 break;
2669 case IR_MAX:
2670 if (irt_isnum(ir->t))
2671 asm_fparith(as, ir, XO_MAXSD);
2672 else
2673 asm_min_max(as, ir, CC_L);
2674 break;
2675
2676 case IR_FPMATH: case IR_ATAN2: case IR_LDEXP:
2677 asm_fpmath(as, ir);
2678 break;
2679 case IR_POW:
2680#if LJ_64 && LJ_HASFFI
2681 if (!irt_isnum(ir->t))
2682 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
2683 IRCALL_lj_carith_powu64);
2684 else
2685#endif
2686 asm_fppowi(as, ir);
2687 break;
2688
2689 /* Overflow-checking arithmetic ops. Note: don't use LEA here! */
2690 case IR_ADDOV: asm_intarith(as, ir, XOg_ADD); break;
2691 case IR_SUBOV: asm_intarith(as, ir, XOg_SUB); break;
2692 case IR_MULOV: asm_intarith(as, ir, XOg_X_IMUL); break;
2693
2694 /* Memory references. */
2695 case IR_AREF: asm_aref(as, ir); break;
2696 case IR_HREF: asm_href(as, ir); break;
2697 case IR_HREFK: asm_hrefk(as, ir); break;
2698 case IR_NEWREF: asm_newref(as, ir); break;
2699 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
2700 case IR_FREF: asm_fref(as, ir); break;
2701 case IR_STRREF: asm_strref(as, ir); break;
2702
2703 /* Loads and stores. */
2704 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2705 asm_ahuvload(as, ir);
2706 break;
2707 case IR_FLOAD: case IR_XLOAD: asm_fxload(as, ir); break;
2708 case IR_SLOAD: asm_sload(as, ir); break;
2709
2710 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
2711 case IR_FSTORE: case IR_XSTORE: asm_fxstore(as, ir); break;
2712
2713 /* Allocations. */
2714 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
2715 case IR_TNEW: asm_tnew(as, ir); break;
2716 case IR_TDUP: asm_tdup(as, ir); break;
2717 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
2718
2719 /* Write barriers. */
2720 case IR_TBAR: asm_tbar(as, ir); break;
2721 case IR_OBAR: asm_obar(as, ir); break;
2722
2723 /* Type conversions. */
2724 case IR_TOBIT: asm_tobit(as, ir); break;
2725 case IR_CONV: asm_conv(as, ir); break;
2726 case IR_TOSTR: asm_tostr(as, ir); break;
2727 case IR_STRTO: asm_strto(as, ir); break;
2728
2729 /* Calls. */
2730 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
2731 case IR_CALLXS: asm_callx(as, ir); break;
2732 case IR_CARG: break;
2733
2734 default:
2735 setintV(&as->J->errinfo, ir->o);
2736 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
2737 break;
2738 }
2739}
2740
2741/* -- Trace setup --------------------------------------------------------- */
2742
2743/* Ensure there are enough stack slots for call arguments. */
2744static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
2745{
2746 IRRef args[CCI_NARGS_MAX*2];
2747 int nslots;
2748 asm_collectargs(as, ir, ci, args);
2749 nslots = asm_count_call_slots(as, ci, args);
2750 if (nslots > as->evenspill) /* Leave room for args in stack slots. */
2751 as->evenspill = nslots;
2752#if LJ_64
2753 return irt_isfp(ir->t) ? REGSP_HINT(RID_FPRET) : REGSP_HINT(RID_RET);
2754#else
2755 return irt_isfp(ir->t) ? REGSP_INIT : REGSP_HINT(RID_RET);
2756#endif
2757}
2758
2759/* Target-specific setup. */
2760static void asm_setup_target(ASMState *as)
2761{
2762 asm_exitstub_setup(as, as->T->nsnap);
2763}
2764
2765/* -- Trace patching ------------------------------------------------------ */
2766
2767/* Patch exit jumps of existing machine code to a new target. */
2768void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target)
2769{
2770 MCode *p = T->mcode;
2771 MCode *mcarea = lj_mcode_patch(J, p, 0);
2772 MSize len = T->szmcode;
2773 MCode *px = exitstub_addr(J, exitno) - 6;
2774 MCode *pe = p+len-6;
2775 uint32_t stateaddr = u32ptr(&J2G(J)->vmstate);
2776 if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px)
2777 *(int32_t *)(p+len-4) = jmprel(p+len, target);
2778 /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */
2779 for (; p < pe; p++)
2780 if (*(uint32_t *)(p+(LJ_64 ? 3 : 2)) == stateaddr && p[0] == XI_MOVmi) {
2781 p += LJ_64 ? 11 : 10;
2782 break;
2783 }
2784 lua_assert(p < pe);
2785 for (; p < pe; p++) {
2786 if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px) {
2787 *(int32_t *)(p+2) = jmprel(p+6, target);
2788 p += 5;
2789 }
2790 }
2791 lj_mcode_sync(T->mcode, T->mcode + T->szmcode);
2792 lj_mcode_patch(J, mcarea, 1);
2793}
2794
2795