Add missing mcode limit check in assembler backend.
[luajit-2.0.git] / src / lj_asm.c
blob7c27a98f83cde381c33e4ea45ac795ae3ed064c1
1 /*
2 ** IR assembler (SSA IR -> machine code).
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #define lj_asm_c
7 #define LUA_CORE
9 #include "lj_obj.h"
11 #if LJ_HASJIT
13 #include "lj_gc.h"
14 #include "lj_str.h"
15 #include "lj_tab.h"
16 #include "lj_frame.h"
17 #if LJ_HASFFI
18 #include "lj_ctype.h"
19 #endif
20 #include "lj_ir.h"
21 #include "lj_jit.h"
22 #include "lj_ircall.h"
23 #include "lj_iropt.h"
24 #include "lj_mcode.h"
25 #include "lj_iropt.h"
26 #include "lj_trace.h"
27 #include "lj_snap.h"
28 #include "lj_asm.h"
29 #include "lj_dispatch.h"
30 #include "lj_vm.h"
31 #include "lj_target.h"
33 /* -- Assembler state and common macros ----------------------------------- */
35 /* Assembler state. */
36 typedef struct ASMState {
37 RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */
39 MCode *mcp; /* Current MCode pointer (grows down). */
40 MCode *mclim; /* Lower limit for MCode memory + red zone. */
42 IRIns *ir; /* Copy of pointer to IR instructions/constants. */
43 jit_State *J; /* JIT compiler state. */
45 #if LJ_TARGET_X86ORX64
46 x86ModRM mrm; /* Fused x86 address operand. */
47 #endif
49 RegSet freeset; /* Set of free registers. */
50 RegSet modset; /* Set of registers modified inside the loop. */
51 RegSet weakset; /* Set of weakly referenced registers. */
52 RegSet phiset; /* Set of PHI registers. */
54 uint32_t flags; /* Copy of JIT compiler flags. */
55 int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
57 int32_t evenspill; /* Next even spill slot. */
58 int32_t oddspill; /* Next odd spill slot (or 0). */
60 IRRef curins; /* Reference of current instruction. */
61 IRRef stopins; /* Stop assembly before hitting this instruction. */
62 IRRef orignins; /* Original T->nins. */
64 IRRef snapref; /* Current snapshot is active after this reference. */
65 IRRef snaprename; /* Rename highwater mark for snapshot check. */
66 SnapNo snapno; /* Current snapshot number. */
67 SnapNo loopsnapno; /* Loop snapshot number. */
69 IRRef fuseref; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
70 IRRef sectref; /* Section base reference (loopref or 0). */
71 IRRef loopref; /* Reference of LOOP instruction (or 0). */
73 BCReg topslot; /* Number of slots for stack check (unless 0). */
74 MSize gcsteps; /* Accumulated number of GC steps (per section). */
76 GCtrace *T; /* Trace to assemble. */
77 GCtrace *parent; /* Parent trace (or NULL). */
79 MCode *mcbot; /* Bottom of reserved MCode. */
80 MCode *mctop; /* Top of generated MCode. */
81 MCode *mcloop; /* Pointer to loop MCode (or NULL). */
82 MCode *invmcp; /* Points to invertible loop branch (or NULL). */
83 MCode *flagmcp; /* Pending opportunity to merge flag setting ins. */
84 MCode *realign; /* Realign loop if not NULL. */
86 #ifdef RID_NUM_KREF
87 int32_t krefk[RID_NUM_KREF];
88 #endif
89 IRRef1 phireg[RID_MAX]; /* PHI register references. */
90 uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent slot to RegSP map. */
91 #if LJ_SOFTFP
92 uint16_t parentmaphi[LJ_MAX_JSLOTS]; /* Parent slot to hi RegSP map. */
93 #endif
94 } ASMState;
96 #define IR(ref) (&as->ir[(ref)])
98 #define ASMREF_TMP1 REF_TRUE /* Temp. register. */
99 #define ASMREF_TMP2 REF_FALSE /* Temp. register. */
100 #define ASMREF_L REF_NIL /* Stores register for L. */
102 /* Check for variant to invariant references. */
103 #define iscrossref(as, ref) ((ref) < as->sectref)
105 /* Inhibit memory op fusion from variant to invariant references. */
106 #define FUSE_DISABLED (~(IRRef)0)
107 #define mayfuse(as, ref) ((ref) > as->fuseref)
108 #define neverfuse(as) (as->fuseref == FUSE_DISABLED)
109 #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
110 #define opisfusableload(o) \
111 ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
112 (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
114 /* Sparse limit checks using a red zone before the actual limit. */
115 #define MCLIM_REDZONE 64
116 #define checkmclim(as) \
117 if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as)
119 static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
121 lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
124 #ifdef RID_NUM_KREF
125 #define ra_iskref(ref) ((ref) < RID_NUM_KREF)
126 #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
127 #define ra_krefk(as, ref) (as->krefk[(ref)])
129 static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k)
131 IRRef ref = (IRRef)(r - RID_MIN_KREF);
132 as->krefk[ref] = k;
133 as->cost[r] = REGCOST(ref, ref);
136 #else
137 #define ra_iskref(ref) 0
138 #define ra_krefreg(ref) RID_MIN_GPR
139 #define ra_krefk(as, ref) 0
140 #endif
142 /* Arch-specific field offsets. */
143 static const uint8_t field_ofs[IRFL__MAX+1] = {
144 #define FLOFS(name, ofs) (uint8_t)(ofs),
145 IRFLDEF(FLOFS)
146 #undef FLOFS
150 /* -- Target-specific instruction emitter --------------------------------- */
152 #if LJ_TARGET_X86ORX64
153 #include "lj_emit_x86.h"
154 #elif LJ_TARGET_ARM
155 #include "lj_emit_arm.h"
156 #elif LJ_TARGET_PPC
157 #include "lj_emit_ppc.h"
158 #else
159 #error "Missing instruction emitter for target CPU"
160 #endif
162 /* -- Register allocator debugging ---------------------------------------- */
164 /* #define LUAJIT_DEBUG_RA */
166 #ifdef LUAJIT_DEBUG_RA
168 #include <stdio.h>
169 #include <stdarg.h>
171 #define RIDNAME(name) #name,
172 static const char *const ra_regname[] = {
173 GPRDEF(RIDNAME)
174 FPRDEF(RIDNAME)
175 VRIDDEF(RIDNAME)
176 NULL
178 #undef RIDNAME
180 static char ra_dbg_buf[65536];
181 static char *ra_dbg_p;
182 static char *ra_dbg_merge;
183 static MCode *ra_dbg_mcp;
185 static void ra_dstart(void)
187 ra_dbg_p = ra_dbg_buf;
188 ra_dbg_merge = NULL;
189 ra_dbg_mcp = NULL;
192 static void ra_dflush(void)
194 fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
195 ra_dstart();
198 static void ra_dprintf(ASMState *as, const char *fmt, ...)
200 char *p;
201 va_list argp;
202 va_start(argp, fmt);
203 p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
204 ra_dbg_mcp = NULL;
205 p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
206 for (;;) {
207 const char *e = strchr(fmt, '$');
208 if (e == NULL) break;
209 memcpy(p, fmt, (size_t)(e-fmt));
210 p += e-fmt;
211 if (e[1] == 'r') {
212 Reg r = va_arg(argp, Reg) & RID_MASK;
213 if (r <= RID_MAX) {
214 const char *q;
215 for (q = ra_regname[r]; *q; q++)
216 *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
217 } else {
218 *p++ = '?';
219 lua_assert(0);
221 } else if (e[1] == 'f' || e[1] == 'i') {
222 IRRef ref;
223 if (e[1] == 'f')
224 ref = va_arg(argp, IRRef);
225 else
226 ref = va_arg(argp, IRIns *) - as->ir;
227 if (ref >= REF_BIAS)
228 p += sprintf(p, "%04d", ref - REF_BIAS);
229 else
230 p += sprintf(p, "K%03d", REF_BIAS - ref);
231 } else if (e[1] == 's') {
232 uint32_t slot = va_arg(argp, uint32_t);
233 p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
234 } else if (e[1] == 'x') {
235 p += sprintf(p, "%08x", va_arg(argp, int32_t));
236 } else {
237 lua_assert(0);
239 fmt = e+2;
241 va_end(argp);
242 while (*fmt)
243 *p++ = *fmt++;
244 *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
245 if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
246 fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
247 p = ra_dbg_buf;
249 ra_dbg_p = p;
252 #define RA_DBG_START() ra_dstart()
253 #define RA_DBG_FLUSH() ra_dflush()
254 #define RA_DBG_REF() \
255 do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
256 ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
257 #define RA_DBGX(x) ra_dprintf x
259 #else
260 #define RA_DBG_START() ((void)0)
261 #define RA_DBG_FLUSH() ((void)0)
262 #define RA_DBG_REF() ((void)0)
263 #define RA_DBGX(x) ((void)0)
264 #endif
266 /* -- Register allocator -------------------------------------------------- */
268 #define ra_free(as, r) rset_set(as->freeset, (r))
269 #define ra_modified(as, r) rset_set(as->modset, (r))
270 #define ra_weak(as, r) rset_set(as->weakset, (r))
271 #define ra_noweak(as, r) rset_clear(as->weakset, (r))
273 #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
275 /* Setup register allocator. */
276 static void ra_setup(ASMState *as)
278 Reg r;
279 /* Initially all regs (except the stack pointer) are free for use. */
280 as->freeset = RSET_INIT;
281 as->modset = RSET_EMPTY;
282 as->weakset = RSET_EMPTY;
283 as->phiset = RSET_EMPTY;
284 memset(as->phireg, 0, sizeof(as->phireg));
285 for (r = RID_MIN_GPR; r < RID_MAX; r++)
286 as->cost[r] = REGCOST(~0u, 0u);
289 /* Rematerialize constants. */
290 static Reg ra_rematk(ASMState *as, IRRef ref)
292 IRIns *ir;
293 Reg r;
294 if (ra_iskref(ref)) {
295 r = ra_krefreg(ref);
296 lua_assert(!rset_test(as->freeset, r));
297 ra_free(as, r);
298 ra_modified(as, r);
299 emit_loadi(as, r, ra_krefk(as, ref));
300 return r;
302 ir = IR(ref);
303 r = ir->r;
304 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
305 ra_free(as, r);
306 ra_modified(as, r);
307 ir->r = RID_INIT; /* Do not keep any hint. */
308 RA_DBGX((as, "remat $i $r", ir, r));
309 #if !LJ_SOFTFP
310 if (ir->o == IR_KNUM) {
311 emit_loadn(as, r, ir_knum(ir));
312 } else
313 #endif
314 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
315 ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
316 emit_getgl(as, r, jit_base);
317 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
318 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
319 emit_getgl(as, r, jit_L);
320 #if LJ_64
321 } else if (ir->o == IR_KINT64) {
322 emit_loadu64(as, r, ir_kint64(ir)->u64);
323 #endif
324 } else {
325 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
326 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
327 emit_loadi(as, r, ir->i);
329 return r;
332 /* Force a spill. Allocate a new spill slot if needed. */
333 static int32_t ra_spill(ASMState *as, IRIns *ir)
335 int32_t slot = ir->s;
336 if (!ra_hasspill(slot)) {
337 if (irt_is64(ir->t)) {
338 slot = as->evenspill;
339 as->evenspill += 2;
340 } else if (as->oddspill) {
341 slot = as->oddspill;
342 as->oddspill = 0;
343 } else {
344 slot = as->evenspill;
345 as->oddspill = slot+1;
346 as->evenspill += 2;
348 if (as->evenspill > 256)
349 lj_trace_err(as->J, LJ_TRERR_SPILLOV);
350 ir->s = (uint8_t)slot;
352 return sps_scale(slot);
355 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
356 static Reg ra_releasetmp(ASMState *as, IRRef ref)
358 IRIns *ir = IR(ref);
359 Reg r = ir->r;
360 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
361 ra_free(as, r);
362 ra_modified(as, r);
363 ir->r = RID_INIT;
364 return r;
367 /* Restore a register (marked as free). Rematerialize or force a spill. */
368 static Reg ra_restore(ASMState *as, IRRef ref)
370 if (emit_canremat(ref)) {
371 return ra_rematk(as, ref);
372 } else {
373 IRIns *ir = IR(ref);
374 int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
375 Reg r = ir->r;
376 lua_assert(ra_hasreg(r));
377 ra_sethint(ir->r, r); /* Keep hint. */
378 ra_free(as, r);
379 if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
380 ra_modified(as, r);
381 RA_DBGX((as, "restore $i $r", ir, r));
382 emit_spload(as, ir, r, ofs);
384 return r;
388 /* Save a register to a spill slot. */
389 static void ra_save(ASMState *as, IRIns *ir, Reg r)
391 RA_DBGX((as, "save $i $r", ir, r));
392 emit_spstore(as, ir, r, sps_scale(ir->s));
395 #define MINCOST(name) \
396 if (rset_test(RSET_ALL, RID_##name) && \
397 LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
398 cost = as->cost[RID_##name];
400 /* Evict the register with the lowest cost, forcing a restore. */
401 static Reg ra_evict(ASMState *as, RegSet allow)
403 IRRef ref;
404 RegCost cost = ~(RegCost)0;
405 lua_assert(allow != RSET_EMPTY);
406 if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
407 GPRDEF(MINCOST)
408 } else {
409 FPRDEF(MINCOST)
411 ref = regcost_ref(cost);
412 lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
413 /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
414 if (!irref_isk(ref) && (as->weakset & allow)) {
415 IRIns *ir = IR(ref);
416 if (!rset_test(as->weakset, ir->r))
417 ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
419 return ra_restore(as, ref);
422 /* Pick any register (marked as free). Evict on-demand. */
423 static Reg ra_pick(ASMState *as, RegSet allow)
425 RegSet pick = as->freeset & allow;
426 if (!pick)
427 return ra_evict(as, allow);
428 else
429 return rset_picktop(pick);
432 /* Get a scratch register (marked as free). */
433 static Reg ra_scratch(ASMState *as, RegSet allow)
435 Reg r = ra_pick(as, allow);
436 ra_modified(as, r);
437 RA_DBGX((as, "scratch $r", r));
438 return r;
441 /* Evict all registers from a set (if not free). */
442 static void ra_evictset(ASMState *as, RegSet drop)
444 as->modset |= drop;
445 drop &= ~as->freeset;
446 while (drop) {
447 Reg r = rset_pickbot(drop);
448 ra_restore(as, regcost_ref(as->cost[r]));
449 rset_clear(drop, r);
450 checkmclim(as);
454 /* Evict (rematerialize) all registers allocated to constants. */
455 static void ra_evictk(ASMState *as)
457 RegSet work;
458 #if !LJ_SOFTFP
459 work = ~as->freeset & RSET_FPR;
460 while (work) {
461 Reg r = rset_pickbot(work);
462 IRRef ref = regcost_ref(as->cost[r]);
463 if (emit_canremat(ref) && irref_isk(ref)) {
464 ra_rematk(as, ref);
465 checkmclim(as);
467 rset_clear(work, r);
469 #endif
470 work = ~as->freeset & RSET_GPR;
471 while (work) {
472 Reg r = rset_pickbot(work);
473 IRRef ref = regcost_ref(as->cost[r]);
474 if (emit_canremat(ref) && irref_isk(ref)) {
475 ra_rematk(as, ref);
476 checkmclim(as);
478 rset_clear(work, r);
482 #ifdef RID_NUM_KREF
483 /* Allocate a register for a constant. */
484 static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
486 /* First try to find a register which already holds the same constant. */
487 RegSet pick, work = ~as->freeset & RSET_GPR;
488 Reg r;
489 while (work) {
490 IRRef ref;
491 r = rset_pickbot(work);
492 ref = regcost_ref(as->cost[r]);
493 if (ref < ASMREF_L &&
494 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
495 return r;
496 rset_clear(work, r);
498 pick = as->freeset & allow;
499 if (pick) {
500 /* Constants should preferably get unmodified registers. */
501 if ((pick & ~as->modset))
502 pick &= ~as->modset;
503 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
504 } else {
505 r = ra_evict(as, allow);
507 RA_DBGX((as, "allock $x $r", k, r));
508 ra_setkref(as, r, k);
509 rset_clear(as->freeset, r);
510 ra_noweak(as, r);
511 return r;
514 /* Allocate a specific register for a constant. */
515 static void ra_allockreg(ASMState *as, int32_t k, Reg r)
517 Reg kr = ra_allock(as, k, RID2RSET(r));
518 if (kr != r) {
519 IRIns irdummy;
520 irdummy.t.irt = IRT_INT;
521 ra_scratch(as, RID2RSET(r));
522 emit_movrr(as, &irdummy, r, kr);
525 #else
526 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
527 #endif
529 /* Allocate a register for ref from the allowed set of registers.
530 ** Note: this function assumes the ref does NOT have a register yet!
531 ** Picks an optimal register, sets the cost and marks the register as non-free.
533 static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
535 IRIns *ir = IR(ref);
536 RegSet pick = as->freeset & allow;
537 Reg r;
538 lua_assert(ra_noreg(ir->r));
539 if (pick) {
540 /* First check register hint from propagation or PHI. */
541 if (ra_hashint(ir->r)) {
542 r = ra_gethint(ir->r);
543 if (rset_test(pick, r)) /* Use hint register if possible. */
544 goto found;
545 /* Rematerialization is cheaper than missing a hint. */
546 if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
547 ra_rematk(as, regcost_ref(as->cost[r]));
548 goto found;
550 RA_DBGX((as, "hintmiss $f $r", ref, r));
552 /* Invariants should preferably get unmodified registers. */
553 if (ref < as->loopref && !irt_isphi(ir->t)) {
554 if ((pick & ~as->modset))
555 pick &= ~as->modset;
556 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
557 } else {
558 /* We've got plenty of regs, so get callee-save regs if possible. */
559 if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
560 pick &= ~RSET_SCRATCH;
561 r = rset_picktop(pick);
563 } else {
564 r = ra_evict(as, allow);
566 found:
567 RA_DBGX((as, "alloc $f $r", ref, r));
568 ir->r = (uint8_t)r;
569 rset_clear(as->freeset, r);
570 ra_noweak(as, r);
571 as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
572 return r;
575 /* Allocate a register on-demand. */
576 static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
578 Reg r = IR(ref)->r;
579 /* Note: allow is ignored if the register is already allocated. */
580 if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
581 ra_noweak(as, r);
582 return r;
585 /* Rename register allocation and emit move. */
586 static void ra_rename(ASMState *as, Reg down, Reg up)
588 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
589 IRIns *ir = IR(ref);
590 ir->r = (uint8_t)up;
591 as->cost[down] = 0;
592 lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
593 lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
594 ra_free(as, down); /* 'down' is free ... */
595 ra_modified(as, down);
596 rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
597 ra_noweak(as, up);
598 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
599 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
600 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
601 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
602 ren = tref_ref(lj_ir_emit(as->J));
603 as->ir = as->T->ir; /* The IR may have been reallocated. */
604 IR(ren)->r = (uint8_t)down;
605 IR(ren)->s = SPS_NONE;
609 /* Pick a destination register (marked as free).
610 ** Caveat: allow is ignored if there's already a destination register.
611 ** Use ra_destreg() to get a specific register.
613 static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
615 Reg dest = ir->r;
616 if (ra_hasreg(dest)) {
617 ra_free(as, dest);
618 ra_modified(as, dest);
619 } else {
620 if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
621 dest = ra_gethint(dest);
622 ra_modified(as, dest);
623 RA_DBGX((as, "dest $r", dest));
624 } else {
625 dest = ra_scratch(as, allow);
627 ir->r = dest;
629 if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
630 return dest;
633 /* Force a specific destination register (marked as free). */
634 static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
636 Reg dest = ra_dest(as, ir, RID2RSET(r));
637 if (dest != r) {
638 ra_scratch(as, RID2RSET(r));
639 emit_movrr(as, ir, dest, r);
643 #if LJ_TARGET_X86ORX64
644 /* Propagate dest register to left reference. Emit moves as needed.
645 ** This is a required fixup step for all 2-operand machine instructions.
647 static void ra_left(ASMState *as, Reg dest, IRRef lref)
649 IRIns *ir = IR(lref);
650 Reg left = ir->r;
651 if (ra_noreg(left)) {
652 if (irref_isk(lref)) {
653 if (ir->o == IR_KNUM) {
654 cTValue *tv = ir_knum(ir);
655 /* FP remat needs a load except for +0. Still better than eviction. */
656 if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
657 emit_loadn(as, dest, tv);
658 return;
660 #if LJ_64
661 } else if (ir->o == IR_KINT64) {
662 emit_loadu64(as, dest, ir_kint64(ir)->u64);
663 return;
664 #endif
665 } else {
666 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
667 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
668 emit_loadi(as, dest, ir->i);
669 return;
672 if (!ra_hashint(left) && !iscrossref(as, lref))
673 ra_sethint(ir->r, dest); /* Propagate register hint. */
674 left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
676 ra_noweak(as, left);
677 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
678 if (dest != left) {
679 /* Use register renaming if dest is the PHI reg. */
680 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
681 ra_modified(as, left);
682 ra_rename(as, left, dest);
683 } else {
684 emit_movrr(as, ir, dest, left);
688 #else
689 /* Similar to ra_left, except we override any hints. */
690 static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
692 IRIns *ir = IR(lref);
693 Reg left = ir->r;
694 if (ra_noreg(left)) {
695 ra_sethint(ir->r, dest); /* Propagate register hint. */
696 left = ra_allocref(as, lref,
697 (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
699 ra_noweak(as, left);
700 if (dest != left) {
701 /* Use register renaming if dest is the PHI reg. */
702 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
703 ra_modified(as, left);
704 ra_rename(as, left, dest);
705 } else {
706 emit_movrr(as, ir, dest, left);
710 #endif
712 #if !LJ_TARGET_X86ORX64
713 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
714 static void ra_destpair(ASMState *as, IRIns *ir)
716 Reg destlo = ir->r, desthi = (ir+1)->r;
717 /* First spill unrelated refs blocking the destination registers. */
718 if (!rset_test(as->freeset, RID_RETLO) &&
719 destlo != RID_RETLO && desthi != RID_RETLO)
720 ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
721 if (!rset_test(as->freeset, RID_RETHI) &&
722 destlo != RID_RETHI && desthi != RID_RETHI)
723 ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
724 /* Next free the destination registers (if any). */
725 if (ra_hasreg(destlo)) {
726 ra_free(as, destlo);
727 ra_modified(as, destlo);
728 } else {
729 destlo = RID_RETLO;
731 if (ra_hasreg(desthi)) {
732 ra_free(as, desthi);
733 ra_modified(as, desthi);
734 } else {
735 desthi = RID_RETHI;
737 /* Check for conflicts and shuffle the registers as needed. */
738 if (destlo == RID_RETHI) {
739 if (desthi == RID_RETLO) {
740 emit_movrr(as, ir, RID_RETHI, RID_TMP);
741 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
742 emit_movrr(as, ir, RID_TMP, RID_RETLO);
743 } else {
744 emit_movrr(as, ir, RID_RETHI, RID_RETLO);
745 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
747 } else if (desthi == RID_RETLO) {
748 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
749 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
750 } else {
751 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
752 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
754 /* Restore spill slots (if any). */
755 if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
756 if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
758 #endif
760 /* -- Snapshot handling --------- ----------------------------------------- */
762 /* Can we rematerialize a KNUM instead of forcing a spill? */
763 static int asm_snap_canremat(ASMState *as)
765 Reg r;
766 for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
767 if (irref_isk(regcost_ref(as->cost[r])))
768 return 1;
769 return 0;
772 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
773 static void asm_snap_alloc1(ASMState *as, IRRef ref)
775 IRIns *ir = IR(ref);
776 if (!ra_used(ir)) {
777 RegSet allow = (!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR;
778 /* Get a weak register if we have a free one or can rematerialize. */
779 if ((as->freeset & allow) ||
780 (allow == RSET_FPR && asm_snap_canremat(as))) {
781 Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
782 if (!irt_isphi(ir->t))
783 ra_weak(as, r); /* But mark it as weakly referenced. */
784 checkmclim(as);
785 RA_DBGX((as, "snapreg $f $r", ref, ir->r));
786 } else {
787 ra_spill(as, ir); /* Otherwise force a spill slot. */
788 RA_DBGX((as, "snapspill $f $s", ref, ir->s));
793 /* Allocate refs escaping to a snapshot. */
794 static void asm_snap_alloc(ASMState *as)
796 SnapShot *snap = &as->T->snap[as->snapno];
797 SnapEntry *map = &as->T->snapmap[snap->mapofs];
798 MSize n, nent = snap->nent;
799 for (n = 0; n < nent; n++) {
800 SnapEntry sn = map[n];
801 IRRef ref = snap_ref(sn);
802 if (!irref_isk(ref)) {
803 asm_snap_alloc1(as, ref);
804 if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
805 lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
806 asm_snap_alloc1(as, ref+1);
812 /* All guards for a snapshot use the same exitno. This is currently the
813 ** same as the snapshot number. Since the exact origin of the exit cannot
814 ** be determined, all guards for the same snapshot must exit with the same
815 ** RegSP mapping.
816 ** A renamed ref which has been used in a prior guard for the same snapshot
817 ** would cause an inconsistency. The easy way out is to force a spill slot.
819 static int asm_snap_checkrename(ASMState *as, IRRef ren)
821 SnapShot *snap = &as->T->snap[as->snapno];
822 SnapEntry *map = &as->T->snapmap[snap->mapofs];
823 MSize n, nent = snap->nent;
824 for (n = 0; n < nent; n++) {
825 SnapEntry sn = map[n];
826 IRRef ref = snap_ref(sn);
827 if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
828 IRIns *ir = IR(ref);
829 ra_spill(as, ir); /* Register renamed, so force a spill slot. */
830 RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
831 return 1; /* Found. */
834 return 0; /* Not found. */
837 /* Prepare snapshot for next guard instruction. */
838 static void asm_snap_prep(ASMState *as)
840 if (as->curins < as->snapref) {
841 do {
842 lua_assert(as->snapno != 0);
843 as->snapno--;
844 as->snapref = as->T->snap[as->snapno].ref;
845 } while (as->curins < as->snapref);
846 asm_snap_alloc(as);
847 as->snaprename = as->T->nins;
848 } else {
849 /* Process any renames above the highwater mark. */
850 for (; as->snaprename < as->T->nins; as->snaprename++) {
851 IRIns *ir = IR(as->snaprename);
852 if (asm_snap_checkrename(as, ir->op1))
853 ir->op2 = REF_BIAS-1; /* Kill rename. */
858 /* -- Miscellaneous helpers ----------------------------------------------- */
860 /* Collect arguments from CALL* and CARG instructions. */
861 static void asm_collectargs(ASMState *as, IRIns *ir,
862 const CCallInfo *ci, IRRef *args)
864 uint32_t n = CCI_NARGS(ci);
865 lua_assert(n <= CCI_NARGS_MAX);
866 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
867 while (n-- > 1) {
868 ir = IR(ir->op1);
869 lua_assert(ir->o == IR_CARG);
870 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
872 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
873 lua_assert(IR(ir->op1)->o != IR_CARG);
876 /* Reconstruct CCallInfo flags for CALLX*. */
877 static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
879 uint32_t nargs = 0;
880 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
881 IRIns *ira = IR(ir->op1);
882 nargs++;
883 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
885 #if LJ_HASFFI
886 if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
887 CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
888 CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
889 nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
890 #if LJ_TARGET_X86
891 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
892 #endif
894 #endif
895 return (nargs | (ir->t.irt << CCI_OTSHIFT));
898 /* Calculate stack adjustment. */
899 static int32_t asm_stack_adjust(ASMState *as)
901 if (as->evenspill <= SPS_FIXED)
902 return 0;
903 return sps_scale(sps_align(as->evenspill));
906 /* Must match with hash*() in lj_tab.c. */
907 static uint32_t ir_khash(IRIns *ir)
909 uint32_t lo, hi;
910 if (irt_isstr(ir->t)) {
911 return ir_kstr(ir)->hash;
912 } else if (irt_isnum(ir->t)) {
913 lo = ir_knum(ir)->u32.lo;
914 hi = ir_knum(ir)->u32.hi << 1;
915 } else if (irt_ispri(ir->t)) {
916 lua_assert(!irt_isnil(ir->t));
917 return irt_type(ir->t)-IRT_FALSE;
918 } else {
919 lua_assert(irt_isgcv(ir->t));
920 lo = u32ptr(ir_kgc(ir));
921 hi = lo + HASH_BIAS;
923 return hashrot(lo, hi);
926 /* -- Allocations --------------------------------------------------------- */
928 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
929 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
931 static void asm_snew(ASMState *as, IRIns *ir)
933 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
934 IRRef args[3];
935 args[0] = ASMREF_L; /* lua_State *L */
936 args[1] = ir->op1; /* const char *str */
937 args[2] = ir->op2; /* size_t len */
938 as->gcsteps++;
939 asm_setupresult(as, ir, ci); /* GCstr * */
940 asm_gencall(as, ci, args);
943 static void asm_tnew(ASMState *as, IRIns *ir)
945 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
946 IRRef args[2];
947 args[0] = ASMREF_L; /* lua_State *L */
948 args[1] = ASMREF_TMP1; /* uint32_t ahsize */
949 as->gcsteps++;
950 asm_setupresult(as, ir, ci); /* GCtab * */
951 asm_gencall(as, ci, args);
952 ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
955 static void asm_tdup(ASMState *as, IRIns *ir)
957 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
958 IRRef args[2];
959 args[0] = ASMREF_L; /* lua_State *L */
960 args[1] = ir->op1; /* const GCtab *kt */
961 as->gcsteps++;
962 asm_setupresult(as, ir, ci); /* GCtab * */
963 asm_gencall(as, ci, args);
966 /* -- PHI and loop handling ----------------------------------------------- */
968 /* Break a PHI cycle by renaming to a free register (evict if needed). */
969 static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
970 RegSet allow)
972 RegSet candidates = blocked & allow;
973 if (candidates) { /* If this register file has candidates. */
974 /* Note: the set for ra_pick cannot be empty, since each register file
975 ** has some registers never allocated to PHIs.
977 Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
978 if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
979 candidates = candidates & ~blockedby;
980 down = rset_picktop(candidates); /* Pick candidate PHI register. */
981 ra_rename(as, down, up); /* And rename it to the free register. */
985 /* PHI register shuffling.
987 ** The allocator tries hard to preserve PHI register assignments across
988 ** the loop body. Most of the time this loop does nothing, since there
989 ** are no register mismatches.
991 ** If a register mismatch is detected and ...
992 ** - the register is currently free: rename it.
993 ** - the register is blocked by an invariant: restore/remat and rename it.
994 ** - Otherwise the register is used by another PHI, so mark it as blocked.
996 ** The renames are order-sensitive, so just retry the loop if a register
997 ** is marked as blocked, but has been freed in the meantime. A cycle is
998 ** detected if all of the blocked registers are allocated. To break the
999 ** cycle rename one of them to a free register and retry.
1001 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1003 static void asm_phi_shuffle(ASMState *as)
1005 RegSet work;
1007 /* Find and resolve PHI register mismatches. */
1008 for (;;) {
1009 RegSet blocked = RSET_EMPTY;
1010 RegSet blockedby = RSET_EMPTY;
1011 RegSet phiset = as->phiset;
1012 while (phiset) { /* Check all left PHI operand registers. */
1013 Reg r = rset_pickbot(phiset);
1014 IRIns *irl = IR(as->phireg[r]);
1015 Reg left = irl->r;
1016 if (r != left) { /* Mismatch? */
1017 if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
1018 IRRef ref = regcost_ref(as->cost[r]);
1019 /* Blocked by other PHI (w/reg)? */
1020 if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
1021 rset_set(blocked, r);
1022 if (ra_hasreg(left))
1023 rset_set(blockedby, left);
1024 left = RID_NONE;
1025 } else { /* Otherwise grab register from invariant. */
1026 ra_restore(as, ref);
1027 checkmclim(as);
1030 if (ra_hasreg(left)) {
1031 ra_rename(as, left, r);
1032 checkmclim(as);
1035 rset_clear(phiset, r);
1037 if (!blocked) break; /* Finished. */
1038 if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
1039 asm_phi_break(as, blocked, blockedby, RSET_GPR);
1040 if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
1041 checkmclim(as);
1042 } /* Else retry some more renames. */
1045 /* Restore/remat invariants whose registers are modified inside the loop. */
1046 work = as->modset & ~(as->freeset | as->phiset);
1047 while (work) {
1048 Reg r = rset_pickbot(work);
1049 ra_restore(as, regcost_ref(as->cost[r]));
1050 rset_clear(work, r);
1051 checkmclim(as);
1054 /* Allocate and save all unsaved PHI regs and clear marks. */
1055 work = as->phiset;
1056 while (work) {
1057 Reg r = rset_picktop(work);
1058 IRRef lref = as->phireg[r];
1059 IRIns *ir = IR(lref);
1060 if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
1061 irt_clearmark(ir->t); /* Handled here, so clear marker now. */
1062 ra_alloc1(as, lref, RID2RSET(r));
1063 ra_save(as, ir, r); /* Save to spill slot inside the loop. */
1064 checkmclim(as);
1066 rset_clear(work, r);
1070 /* Emit renames for left PHIs which are only spilled outside the loop. */
1071 static void asm_phi_fixup(ASMState *as)
1073 RegSet work = as->phiset;
1074 while (work) {
1075 Reg r = rset_picktop(work);
1076 IRRef lref = as->phireg[r];
1077 IRIns *ir = IR(lref);
1078 /* Left PHI gained a spill slot before the loop? */
1079 if (irt_ismarked(ir->t) && ra_hasspill(ir->s)) {
1080 IRRef ren;
1081 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
1082 ren = tref_ref(lj_ir_emit(as->J));
1083 as->ir = as->T->ir; /* The IR may have been reallocated. */
1084 IR(ren)->r = (uint8_t)r;
1085 IR(ren)->s = SPS_NONE;
1087 irt_clearmark(ir->t); /* Always clear marker. */
1088 rset_clear(work, r);
1092 /* Setup right PHI reference. */
1093 static void asm_phi(ASMState *as, IRIns *ir)
1095 RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1096 ~as->phiset;
1097 RegSet afree = (as->freeset & allow);
1098 IRIns *irl = IR(ir->op1);
1099 IRIns *irr = IR(ir->op2);
1100 /* Spill slot shuffling is not implemented yet (but rarely needed). */
1101 if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
1102 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1103 /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1104 if ((afree & (afree-1))) { /* Two or more free registers? */
1105 Reg r;
1106 if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
1107 r = ra_allocref(as, ir->op2, allow);
1108 } else { /* Duplicate right PHI, need a copy (rare). */
1109 r = ra_scratch(as, allow);
1110 emit_movrr(as, irr, r, irr->r);
1112 ir->r = (uint8_t)r;
1113 rset_set(as->phiset, r);
1114 as->phireg[r] = (IRRef1)ir->op1;
1115 irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
1116 if (ra_noreg(irl->r))
1117 ra_sethint(irl->r, r); /* Set register hint for left PHI. */
1118 } else { /* Otherwise allocate a spill slot. */
1119 /* This is overly restrictive, but it triggers only on synthetic code. */
1120 if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
1121 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1122 ra_spill(as, ir);
1123 irl->s = irr->s = ir->s; /* Sync left/right PHI spill slots. */
1127 static void asm_gc_check(ASMState *as);
1128 static void asm_loop_fixup(ASMState *as);
1130 /* Middle part of a loop. */
1131 static void asm_loop(ASMState *as)
1133 /* LOOP is a guard, so the snapno is up to date. */
1134 as->loopsnapno = as->snapno;
1135 if (as->gcsteps)
1136 asm_gc_check(as);
1137 /* LOOP marks the transition from the variant to the invariant part. */
1138 as->flagmcp = as->invmcp = NULL;
1139 as->sectref = 0;
1140 if (!neverfuse(as)) as->fuseref = 0;
1141 asm_phi_shuffle(as);
1142 asm_loop_fixup(as);
1143 as->mcloop = as->mcp;
1144 RA_DBGX((as, "===== LOOP ====="));
1145 if (!as->realign) RA_DBG_FLUSH();
1148 /* -- Target-specific assembler ------------------------------------------- */
1150 #if LJ_TARGET_X86ORX64
1151 #include "lj_asm_x86.h"
1152 #elif LJ_TARGET_ARM
1153 #include "lj_asm_arm.h"
1154 #elif LJ_TARGET_PPC
1155 #include "lj_asm_ppc.h"
1156 #else
1157 #error "Missing assembler for target CPU"
1158 #endif
1160 /* -- Head of trace ------------------------------------------------------- */
1162 /* Head of a root trace. */
1163 static void asm_head_root(ASMState *as)
1165 int32_t spadj;
1166 asm_head_root_base(as);
1167 emit_setvmstate(as, (int32_t)as->T->traceno);
1168 spadj = asm_stack_adjust(as);
1169 as->T->spadjust = (uint16_t)spadj;
1170 emit_spsub(as, spadj);
1171 /* Root traces assume a checked stack for the starting proto. */
1172 as->T->topslot = gcref(as->T->startpt)->pt.framesize;
1175 /* Get RegSP for parent slot. */
1176 static LJ_AINLINE RegSP asm_head_parentrs(ASMState *as, IRIns *ir)
1178 #if LJ_SOFTFP
1179 if (ir->o == IR_HIOP) return as->parentmaphi[(ir-1)->op1];
1180 #endif
1181 return as->parentmap[ir->op1];
1184 /* Head of a side trace.
1186 ** The current simplistic algorithm requires that all slots inherited
1187 ** from the parent are live in a register between pass 2 and pass 3. This
1188 ** avoids the complexity of stack slot shuffling. But of course this may
1189 ** overflow the register set in some cases and cause the dreaded error:
1190 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1192 static void asm_head_side(ASMState *as)
1194 IRRef1 sloadins[RID_MAX];
1195 RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
1196 RegSet live = RSET_EMPTY; /* Live parent registers. */
1197 IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
1198 int32_t spadj, spdelta;
1199 int pass2 = 0;
1200 int pass3 = 0;
1201 IRRef i;
1203 allow = asm_head_side_base(as, irp, allow);
1205 /* Scan all parent SLOADs and collect register dependencies. */
1206 for (i = as->stopins; i > REF_BASE; i--) {
1207 IRIns *ir = IR(i);
1208 RegSP rs;
1209 lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
1210 (LJ_SOFTFP && ir->o == IR_HIOP));
1211 rs = asm_head_parentrs(as, ir);
1212 if (ra_hasreg(ir->r)) {
1213 rset_clear(allow, ir->r);
1214 if (ra_hasspill(ir->s)) {
1215 ra_save(as, ir, ir->r);
1216 checkmclim(as);
1218 } else if (ra_hasspill(ir->s)) {
1219 irt_setmark(ir->t);
1220 pass2 = 1;
1222 if (ir->r == rs) { /* Coalesce matching registers right now. */
1223 ra_free(as, ir->r);
1224 } else if (ra_hasspill(regsp_spill(rs))) {
1225 if (ra_hasreg(ir->r))
1226 pass3 = 1;
1227 } else if (ra_used(ir)) {
1228 sloadins[rs] = (IRRef1)i;
1229 rset_set(live, rs); /* Block live parent register. */
1233 /* Calculate stack frame adjustment. */
1234 spadj = asm_stack_adjust(as);
1235 spdelta = spadj - (int32_t)as->parent->spadjust;
1236 if (spdelta < 0) { /* Don't shrink the stack frame. */
1237 spadj = (int32_t)as->parent->spadjust;
1238 spdelta = 0;
1240 as->T->spadjust = (uint16_t)spadj;
1242 /* Reload spilled target registers. */
1243 if (pass2) {
1244 for (i = as->stopins; i > REF_BASE; i--) {
1245 IRIns *ir = IR(i);
1246 if (irt_ismarked(ir->t)) {
1247 RegSet mask;
1248 Reg r;
1249 RegSP rs;
1250 irt_clearmark(ir->t);
1251 rs = asm_head_parentrs(as, ir);
1252 if (!ra_hasspill(regsp_spill(rs)))
1253 ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
1254 else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1255 continue; /* Same spill slot, do nothing. */
1256 mask = ((!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1257 if (mask == RSET_EMPTY)
1258 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1259 r = ra_allocref(as, i, mask);
1260 ra_save(as, ir, r);
1261 rset_clear(allow, r);
1262 if (r == rs) { /* Coalesce matching registers right now. */
1263 ra_free(as, r);
1264 rset_clear(live, r);
1265 } else if (ra_hasspill(regsp_spill(rs))) {
1266 pass3 = 1;
1268 checkmclim(as);
1273 /* Store trace number and adjust stack frame relative to the parent. */
1274 emit_setvmstate(as, (int32_t)as->T->traceno);
1275 emit_spsub(as, spdelta);
1277 #if !LJ_TARGET_X86ORX64
1278 /* Restore BASE register from parent spill slot. */
1279 if (ra_hasspill(irp->s))
1280 emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1281 #endif
1283 /* Restore target registers from parent spill slots. */
1284 if (pass3) {
1285 RegSet work = ~as->freeset & RSET_ALL;
1286 while (work) {
1287 Reg r = rset_pickbot(work);
1288 IRIns *ir = IR(regcost_ref(as->cost[r]));
1289 RegSP rs = asm_head_parentrs(as, ir);
1290 rset_clear(work, r);
1291 if (ra_hasspill(regsp_spill(rs))) {
1292 int32_t ofs = sps_scale(regsp_spill(rs));
1293 ra_free(as, r);
1294 emit_spload(as, ir, r, ofs);
1295 checkmclim(as);
1300 /* Shuffle registers to match up target regs with parent regs. */
1301 for (;;) {
1302 RegSet work;
1304 /* Repeatedly coalesce free live registers by moving to their target. */
1305 while ((work = as->freeset & live) != RSET_EMPTY) {
1306 Reg rp = rset_pickbot(work);
1307 IRIns *ir = IR(sloadins[rp]);
1308 rset_clear(live, rp);
1309 rset_clear(allow, rp);
1310 ra_free(as, ir->r);
1311 emit_movrr(as, ir, ir->r, rp);
1312 checkmclim(as);
1315 /* We're done if no live registers remain. */
1316 if (live == RSET_EMPTY)
1317 break;
1319 /* Break cycles by renaming one target to a temp. register. */
1320 if (live & RSET_GPR) {
1321 RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1322 if (tmpset == RSET_EMPTY)
1323 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1324 ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1326 if (!LJ_SOFTFP && (live & RSET_FPR)) {
1327 RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1328 if (tmpset == RSET_EMPTY)
1329 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1330 ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1332 checkmclim(as);
1333 /* Continue with coalescing to fix up the broken cycle(s). */
1336 /* Inherit top stack slot already checked by parent trace. */
1337 as->T->topslot = as->parent->topslot;
1338 if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
1339 #ifdef EXITSTATE_CHECKEXIT
1340 /* Highest exit + 1 indicates stack check. */
1341 ExitNo exitno = as->T->nsnap;
1342 #else
1343 /* Reuse the parent exit in the context of the parent trace. */
1344 ExitNo exitno = as->J->exitno;
1345 #endif
1346 as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
1347 asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1351 /* -- Tail of trace ------------------------------------------------------- */
1353 /* Get base slot for a snapshot. */
1354 static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1356 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1357 MSize n;
1358 for (n = snap->nent; n > 0; n--) {
1359 SnapEntry sn = map[n-1];
1360 if ((sn & SNAP_FRAME)) {
1361 *gotframe = 1;
1362 return snap_slot(sn);
1365 return 0;
1368 /* Link to another trace. */
1369 static void asm_tail_link(ASMState *as)
1371 SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
1372 SnapShot *snap = &as->T->snap[snapno];
1373 int gotframe = 0;
1374 BCReg baseslot = asm_baseslot(as, snap, &gotframe);
1376 as->topslot = snap->topslot;
1377 checkmclim(as);
1378 ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1380 if (as->T->link == 0) {
1381 /* Setup fixed registers for exit to interpreter. */
1382 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
1383 int32_t mres;
1384 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1385 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1386 if (bc_isret(bc_op(*retpc)))
1387 pc = retpc;
1389 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1390 ra_allockreg(as, i32ptr(pc), RID_LPC);
1391 mres = (int32_t)(snap->nslots - baseslot);
1392 switch (bc_op(*pc)) {
1393 case BC_CALLM: case BC_CALLMT:
1394 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
1395 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1396 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1397 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1399 ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
1400 } else if (baseslot) {
1401 /* Save modified BASE for linking to trace with higher start frame. */
1402 emit_setgl(as, RID_BASE, jit_base);
1404 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1406 /* Sync the interpreter state with the on-trace state. */
1407 asm_stack_restore(as, snap);
1409 /* Root traces that add frames need to check the stack at the end. */
1410 if (!as->parent && gotframe)
1411 asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1414 /* -- Trace setup --------------------------------------------------------- */
1416 /* Clear reg/sp for all instructions and add register hints. */
1417 static void asm_setup_regsp(ASMState *as)
1419 GCtrace *T = as->T;
1420 IRRef i, nins;
1421 int inloop;
1422 #if LJ_TARGET_ARM
1423 uint32_t rload = 0xa6402a64;
1424 #endif
1426 ra_setup(as);
1428 /* Clear reg/sp for constants. */
1429 for (i = T->nk; i < REF_BIAS; i++)
1430 IR(i)->prev = REGSP_INIT;
1432 /* REF_BASE is used for implicit references to the BASE register. */
1433 IR(REF_BASE)->prev = REGSP_HINT(RID_BASE);
1435 nins = T->nins;
1436 if (IR(nins-1)->o == IR_RENAME) {
1437 do { nins--; } while (IR(nins-1)->o == IR_RENAME);
1438 T->nins = nins; /* Remove any renames left over from ASM restart. */
1440 as->snaprename = nins;
1441 as->snapref = nins;
1442 as->snapno = T->nsnap;
1444 as->stopins = REF_BASE;
1445 as->orignins = nins;
1446 as->curins = nins;
1448 inloop = 0;
1449 as->evenspill = SPS_FIRST;
1450 for (i = REF_FIRST; i < nins; i++) {
1451 IRIns *ir = IR(i);
1452 switch (ir->o) {
1453 case IR_LOOP:
1454 inloop = 1;
1455 break;
1456 /* Set hints for slot loads from a parent trace. */
1457 case IR_SLOAD:
1458 if ((ir->op2 & IRSLOAD_PARENT)) {
1459 RegSP rs = as->parentmap[ir->op1];
1460 lua_assert(regsp_used(rs));
1461 as->stopins = i;
1462 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1463 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1464 continue;
1467 #if LJ_TARGET_ARM
1468 if ((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP) {
1469 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1470 rload = lj_ror(rload, 4);
1471 continue;
1473 #endif
1474 break;
1475 #if LJ_TARGET_ARM
1476 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1477 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1478 rload = lj_ror(rload, 4);
1479 continue;
1480 #endif
1481 case IR_CALLXS: {
1482 CCallInfo ci;
1483 ci.flags = asm_callx_flags(as, ir);
1484 ir->prev = asm_setup_call_slots(as, ir, &ci);
1485 if (inloop)
1486 as->modset |= RSET_SCRATCH;
1487 continue;
1489 case IR_CALLN: case IR_CALLL: case IR_CALLS: {
1490 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1491 ir->prev = asm_setup_call_slots(as, ir, ci);
1492 if (inloop)
1493 as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
1494 (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
1495 continue;
1497 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1498 case IR_HIOP:
1499 switch ((ir-1)->o) {
1500 #if LJ_SOFTFP
1501 case IR_SLOAD:
1502 if (((ir-1)->op2 & IRSLOAD_PARENT)) {
1503 RegSP rs = as->parentmaphi[(ir-1)->op1];
1504 lua_assert(regsp_used(rs));
1505 as->stopins = i;
1506 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1507 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1508 continue;
1511 #if LJ_TARGET_ARM
1512 /* fallthrough */
1513 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1514 if (ra_hashint((ir-1)->r)) {
1515 ir->prev = (ir-1)->prev + 1;
1516 continue;
1518 #endif
1519 break;
1520 #endif
1521 #if LJ_NEED_FP64
1522 case IR_CONV:
1523 if (irt_isfp((ir-1)->t)) {
1524 ir->prev = REGSP_HINT(RID_FPRET);
1525 continue;
1527 /* fallthrough */
1528 #endif
1529 case IR_CALLN: case IR_CALLXS:
1530 #if LJ_SOFTFP
1531 case IR_MIN: case IR_MAX:
1532 #endif
1533 #if LJ_BE
1534 (ir-1)->prev = REGSP_HINT(RID_RETLO);
1535 #endif
1536 ir->prev = REGSP_HINT(RID_RETHI);
1537 continue;
1538 default:
1539 break;
1541 break;
1542 #endif
1543 #if LJ_SOFTFP
1544 case IR_MIN: case IR_MAX:
1545 if ((ir+1)->o != IR_HIOP) break;
1546 /* fallthrough */
1547 #endif
1548 /* C calls evict all scratch regs and return results in RID_RET. */
1549 case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
1550 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1551 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1552 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
1553 ir->prev = REGSP_HINT(RID_RET);
1554 if (inloop)
1555 as->modset = RSET_SCRATCH;
1556 continue;
1557 case IR_STRTO: case IR_OBAR:
1558 if (inloop)
1559 as->modset = RSET_SCRATCH;
1560 break;
1561 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1562 case IR_ATAN2: case IR_LDEXP:
1563 #endif
1564 case IR_POW:
1565 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1566 #if LJ_TARGET_X86ORX64
1567 ir->prev = REGSP_HINT(RID_XMM0);
1568 if (inloop)
1569 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1570 #else
1571 ir->prev = REGSP_HINT(RID_FPRET);
1572 if (inloop)
1573 as->modset |= RSET_SCRATCH;
1574 #endif
1575 continue;
1577 /* fallthrough for integer POW */
1578 case IR_DIV: case IR_MOD:
1579 if (!irt_isnum(ir->t)) {
1580 ir->prev = REGSP_HINT(RID_RET);
1581 if (inloop)
1582 as->modset |= (RSET_SCRATCH & RSET_GPR);
1583 continue;
1585 break;
1586 case IR_FPMATH:
1587 #if LJ_TARGET_X86ORX64
1588 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
1589 ir->prev = REGSP_HINT(RID_XMM0);
1590 #if !LJ_64
1591 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
1592 as->evenspill = 4;
1593 #endif
1594 if (inloop)
1595 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1596 continue;
1597 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1598 ir->prev = REGSP_HINT(RID_XMM0);
1599 if (inloop)
1600 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1601 continue;
1603 break;
1604 #else
1605 ir->prev = REGSP_HINT(RID_FPRET);
1606 if (inloop)
1607 as->modset |= RSET_SCRATCH;
1608 continue;
1609 #endif
1610 #if LJ_TARGET_X86ORX64
1611 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1612 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
1613 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1614 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1615 if (inloop)
1616 rset_set(as->modset, RID_ECX);
1618 break;
1619 #endif
1620 /* Do not propagate hints across type conversions. */
1621 case IR_TOBIT:
1622 break;
1623 case IR_CONV:
1624 if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
1625 (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
1626 break;
1627 /* fallthrough */
1628 default:
1629 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1630 if (irref_isk(ir->op2) && !irref_isk(ir->op1)) {
1631 ir->prev = IR(ir->op1)->prev;
1632 continue;
1634 break;
1636 ir->prev = REGSP_INIT;
1638 if ((as->evenspill & 1))
1639 as->oddspill = as->evenspill++;
1640 else
1641 as->oddspill = 0;
1644 /* -- Assembler core ------------------------------------------------------ */
1646 /* Assemble a trace. */
1647 void lj_asm_trace(jit_State *J, GCtrace *T)
1649 ASMState as_;
1650 ASMState *as = &as_;
1651 MCode *origtop;
1653 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1654 J->cur.nins = lj_ir_nextins(J);
1655 J->cur.ir[J->cur.nins].o = IR_NOP;
1657 /* Setup initial state. Copy some fields to reduce indirections. */
1658 as->J = J;
1659 as->T = T;
1660 as->ir = T->ir;
1661 as->flags = J->flags;
1662 as->loopref = J->loopref;
1663 as->realign = NULL;
1664 as->loopinv = 0;
1665 if (J->parent) {
1666 as->parent = traceref(J, J->parent);
1667 lj_snap_regspmap(as->parentmap, as->parent, J->exitno, 0);
1668 #if LJ_SOFTFP
1669 lj_snap_regspmap(as->parentmaphi, as->parent, J->exitno, 1);
1670 #endif
1671 } else {
1672 as->parent = NULL;
1674 /* Reserve MCode memory. */
1675 as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
1676 as->mcp = as->mctop;
1677 as->mclim = as->mcbot + MCLIM_REDZONE;
1678 asm_setup_target(as);
1680 do {
1681 as->mcp = as->mctop;
1682 as->curins = T->nins;
1683 RA_DBG_START();
1684 RA_DBGX((as, "===== STOP ====="));
1686 /* General trace setup. Emit tail of trace. */
1687 asm_tail_prep(as);
1688 as->mcloop = NULL;
1689 as->flagmcp = NULL;
1690 as->topslot = 0;
1691 as->gcsteps = 0;
1692 as->sectref = as->loopref;
1693 as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
1694 asm_setup_regsp(as);
1695 if (!as->loopref)
1696 asm_tail_link(as);
1698 /* Assemble a trace in linear backwards order. */
1699 for (as->curins--; as->curins > as->stopins; as->curins--) {
1700 IRIns *ir = IR(as->curins);
1701 lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
1702 if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
1703 continue; /* Dead-code elimination can be soooo easy. */
1704 if (irt_isguard(ir->t))
1705 asm_snap_prep(as);
1706 RA_DBG_REF();
1707 checkmclim(as);
1708 asm_ir(as, ir);
1710 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1712 /* Emit head of trace. */
1713 RA_DBG_REF();
1714 checkmclim(as);
1715 if (as->gcsteps) {
1716 as->curins = as->T->snap[0].ref;
1717 asm_snap_prep(as); /* The GC check is a guard. */
1718 asm_gc_check(as);
1720 ra_evictk(as);
1721 if (as->parent)
1722 asm_head_side(as);
1723 else
1724 asm_head_root(as);
1725 asm_phi_fixup(as);
1727 RA_DBGX((as, "===== START ===="));
1728 RA_DBG_FLUSH();
1729 if (as->freeset != RSET_ALL)
1730 lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
1732 /* Set trace entry point before fixing up tail to allow link to self. */
1733 T->mcode = as->mcp;
1734 T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
1735 if (!as->loopref)
1736 asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
1737 T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
1738 lj_mcode_sync(T->mcode, origtop);
1741 #undef IR
1743 #endif