Leave hook when resume catches error thrown from hook.
[luajit-2.0.git] / src / lj_asm.c
blob5f6becada2c0e980a5bb9022bb20d57f94de446b
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 int32_t 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 instruction to RegSP map. */
91 } ASMState;
93 #define IR(ref) (&as->ir[(ref)])
95 #define ASMREF_TMP1 REF_TRUE /* Temp. register. */
96 #define ASMREF_TMP2 REF_FALSE /* Temp. register. */
97 #define ASMREF_L REF_NIL /* Stores register for L. */
99 /* Check for variant to invariant references. */
100 #define iscrossref(as, ref) ((ref) < as->sectref)
102 /* Inhibit memory op fusion from variant to invariant references. */
103 #define FUSE_DISABLED (~(IRRef)0)
104 #define mayfuse(as, ref) ((ref) > as->fuseref)
105 #define neverfuse(as) (as->fuseref == FUSE_DISABLED)
106 #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
107 #define opisfusableload(o) \
108 ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
109 (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
111 /* Sparse limit checks using a red zone before the actual limit. */
112 #define MCLIM_REDZONE 64
113 #define checkmclim(as) \
114 if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as)
116 static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
118 lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
121 #ifdef RID_NUM_KREF
122 #define ra_iskref(ref) ((ref) < RID_NUM_KREF)
123 #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
124 #define ra_krefk(as, ref) (as->krefk[(ref)])
126 static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k)
128 IRRef ref = (IRRef)(r - RID_MIN_KREF);
129 as->krefk[ref] = k;
130 as->cost[r] = REGCOST(ref, ref);
133 #else
134 #define ra_iskref(ref) 0
135 #define ra_krefreg(ref) RID_MIN_GPR
136 #define ra_krefk(as, ref) 0
137 #endif
139 /* Arch-specific field offsets. */
140 static const uint8_t field_ofs[IRFL__MAX+1] = {
141 #define FLOFS(name, ofs) (uint8_t)(ofs),
142 IRFLDEF(FLOFS)
143 #undef FLOFS
147 /* -- Target-specific instruction emitter --------------------------------- */
149 #if LJ_TARGET_X86ORX64
150 #include "lj_emit_x86.h"
151 #elif LJ_TARGET_ARM
152 #include "lj_emit_arm.h"
153 #elif LJ_TARGET_PPC
154 #include "lj_emit_ppc.h"
155 #elif LJ_TARGET_MIPS
156 #include "lj_emit_mips.h"
157 #else
158 #error "Missing instruction emitter for target CPU"
159 #endif
161 /* -- Register allocator debugging ---------------------------------------- */
163 /* #define LUAJIT_DEBUG_RA */
165 #ifdef LUAJIT_DEBUG_RA
167 #include <stdio.h>
168 #include <stdarg.h>
170 #define RIDNAME(name) #name,
171 static const char *const ra_regname[] = {
172 GPRDEF(RIDNAME)
173 FPRDEF(RIDNAME)
174 VRIDDEF(RIDNAME)
175 NULL
177 #undef RIDNAME
179 static char ra_dbg_buf[65536];
180 static char *ra_dbg_p;
181 static char *ra_dbg_merge;
182 static MCode *ra_dbg_mcp;
184 static void ra_dstart(void)
186 ra_dbg_p = ra_dbg_buf;
187 ra_dbg_merge = NULL;
188 ra_dbg_mcp = NULL;
191 static void ra_dflush(void)
193 fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
194 ra_dstart();
197 static void ra_dprintf(ASMState *as, const char *fmt, ...)
199 char *p;
200 va_list argp;
201 va_start(argp, fmt);
202 p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
203 ra_dbg_mcp = NULL;
204 p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
205 for (;;) {
206 const char *e = strchr(fmt, '$');
207 if (e == NULL) break;
208 memcpy(p, fmt, (size_t)(e-fmt));
209 p += e-fmt;
210 if (e[1] == 'r') {
211 Reg r = va_arg(argp, Reg) & RID_MASK;
212 if (r <= RID_MAX) {
213 const char *q;
214 for (q = ra_regname[r]; *q; q++)
215 *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
216 } else {
217 *p++ = '?';
218 lua_assert(0);
220 } else if (e[1] == 'f' || e[1] == 'i') {
221 IRRef ref;
222 if (e[1] == 'f')
223 ref = va_arg(argp, IRRef);
224 else
225 ref = va_arg(argp, IRIns *) - as->ir;
226 if (ref >= REF_BIAS)
227 p += sprintf(p, "%04d", ref - REF_BIAS);
228 else
229 p += sprintf(p, "K%03d", REF_BIAS - ref);
230 } else if (e[1] == 's') {
231 uint32_t slot = va_arg(argp, uint32_t);
232 p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
233 } else if (e[1] == 'x') {
234 p += sprintf(p, "%08x", va_arg(argp, int32_t));
235 } else {
236 lua_assert(0);
238 fmt = e+2;
240 va_end(argp);
241 while (*fmt)
242 *p++ = *fmt++;
243 *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
244 if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
245 fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
246 p = ra_dbg_buf;
248 ra_dbg_p = p;
251 #define RA_DBG_START() ra_dstart()
252 #define RA_DBG_FLUSH() ra_dflush()
253 #define RA_DBG_REF() \
254 do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
255 ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
256 #define RA_DBGX(x) ra_dprintf x
258 #else
259 #define RA_DBG_START() ((void)0)
260 #define RA_DBG_FLUSH() ((void)0)
261 #define RA_DBG_REF() ((void)0)
262 #define RA_DBGX(x) ((void)0)
263 #endif
265 /* -- Register allocator -------------------------------------------------- */
267 #define ra_free(as, r) rset_set(as->freeset, (r))
268 #define ra_modified(as, r) rset_set(as->modset, (r))
269 #define ra_weak(as, r) rset_set(as->weakset, (r))
270 #define ra_noweak(as, r) rset_clear(as->weakset, (r))
272 #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
274 /* Setup register allocator. */
275 static void ra_setup(ASMState *as)
277 Reg r;
278 /* Initially all regs (except the stack pointer) are free for use. */
279 as->freeset = RSET_INIT;
280 as->modset = RSET_EMPTY;
281 as->weakset = RSET_EMPTY;
282 as->phiset = RSET_EMPTY;
283 memset(as->phireg, 0, sizeof(as->phireg));
284 for (r = RID_MIN_GPR; r < RID_MAX; r++)
285 as->cost[r] = REGCOST(~0u, 0u);
288 /* Rematerialize constants. */
289 static Reg ra_rematk(ASMState *as, IRRef ref)
291 IRIns *ir;
292 Reg r;
293 if (ra_iskref(ref)) {
294 r = ra_krefreg(ref);
295 lua_assert(!rset_test(as->freeset, r));
296 ra_free(as, r);
297 ra_modified(as, r);
298 emit_loadi(as, r, ra_krefk(as, ref));
299 return r;
301 ir = IR(ref);
302 r = ir->r;
303 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
304 ra_free(as, r);
305 ra_modified(as, r);
306 ir->r = RID_INIT; /* Do not keep any hint. */
307 RA_DBGX((as, "remat $i $r", ir, r));
308 #if !LJ_SOFTFP
309 if (ir->o == IR_KNUM) {
310 emit_loadn(as, r, ir_knum(ir));
311 } else
312 #endif
313 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
314 ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
315 emit_getgl(as, r, jit_base);
316 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
317 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
318 emit_getgl(as, r, jit_L);
319 #if LJ_64
320 } else if (ir->o == IR_KINT64) {
321 emit_loadu64(as, r, ir_kint64(ir)->u64);
322 #endif
323 } else {
324 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
325 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
326 emit_loadi(as, r, ir->i);
328 return r;
331 /* Force a spill. Allocate a new spill slot if needed. */
332 static int32_t ra_spill(ASMState *as, IRIns *ir)
334 int32_t slot = ir->s;
335 if (!ra_hasspill(slot)) {
336 if (irt_is64(ir->t)) {
337 slot = as->evenspill;
338 as->evenspill += 2;
339 } else if (as->oddspill) {
340 slot = as->oddspill;
341 as->oddspill = 0;
342 } else {
343 slot = as->evenspill;
344 as->oddspill = slot+1;
345 as->evenspill += 2;
347 if (as->evenspill > 256)
348 lj_trace_err(as->J, LJ_TRERR_SPILLOV);
349 ir->s = (uint8_t)slot;
351 return sps_scale(slot);
354 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
355 static Reg ra_releasetmp(ASMState *as, IRRef ref)
357 IRIns *ir = IR(ref);
358 Reg r = ir->r;
359 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
360 ra_free(as, r);
361 ra_modified(as, r);
362 ir->r = RID_INIT;
363 return r;
366 /* Restore a register (marked as free). Rematerialize or force a spill. */
367 static Reg ra_restore(ASMState *as, IRRef ref)
369 if (emit_canremat(ref)) {
370 return ra_rematk(as, ref);
371 } else {
372 IRIns *ir = IR(ref);
373 int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
374 Reg r = ir->r;
375 lua_assert(ra_hasreg(r));
376 ra_sethint(ir->r, r); /* Keep hint. */
377 ra_free(as, r);
378 if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
379 ra_modified(as, r);
380 RA_DBGX((as, "restore $i $r", ir, r));
381 emit_spload(as, ir, r, ofs);
383 return r;
387 /* Save a register to a spill slot. */
388 static void ra_save(ASMState *as, IRIns *ir, Reg r)
390 RA_DBGX((as, "save $i $r", ir, r));
391 emit_spstore(as, ir, r, sps_scale(ir->s));
394 #define MINCOST(name) \
395 if (rset_test(RSET_ALL, RID_##name) && \
396 LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
397 cost = as->cost[RID_##name];
399 /* Evict the register with the lowest cost, forcing a restore. */
400 static Reg ra_evict(ASMState *as, RegSet allow)
402 IRRef ref;
403 RegCost cost = ~(RegCost)0;
404 lua_assert(allow != RSET_EMPTY);
405 if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
406 GPRDEF(MINCOST)
407 } else {
408 FPRDEF(MINCOST)
410 ref = regcost_ref(cost);
411 lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
412 /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
413 if (!irref_isk(ref) && (as->weakset & allow)) {
414 IRIns *ir = IR(ref);
415 if (!rset_test(as->weakset, ir->r))
416 ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
418 return ra_restore(as, ref);
421 /* Pick any register (marked as free). Evict on-demand. */
422 static Reg ra_pick(ASMState *as, RegSet allow)
424 RegSet pick = as->freeset & allow;
425 if (!pick)
426 return ra_evict(as, allow);
427 else
428 return rset_picktop(pick);
431 /* Get a scratch register (marked as free). */
432 static Reg ra_scratch(ASMState *as, RegSet allow)
434 Reg r = ra_pick(as, allow);
435 ra_modified(as, r);
436 RA_DBGX((as, "scratch $r", r));
437 return r;
440 /* Evict all registers from a set (if not free). */
441 static void ra_evictset(ASMState *as, RegSet drop)
443 RegSet work;
444 as->modset |= drop;
445 #if !LJ_SOFTFP
446 work = (drop & ~as->freeset) & RSET_FPR;
447 while (work) {
448 Reg r = rset_pickbot(work);
449 ra_restore(as, regcost_ref(as->cost[r]));
450 rset_clear(work, r);
451 checkmclim(as);
453 #endif
454 work = (drop & ~as->freeset);
455 while (work) {
456 Reg r = rset_pickbot(work);
457 ra_restore(as, regcost_ref(as->cost[r]));
458 rset_clear(work, r);
459 checkmclim(as);
463 /* Evict (rematerialize) all registers allocated to constants. */
464 static void ra_evictk(ASMState *as)
466 RegSet work;
467 #if !LJ_SOFTFP
468 work = ~as->freeset & RSET_FPR;
469 while (work) {
470 Reg r = rset_pickbot(work);
471 IRRef ref = regcost_ref(as->cost[r]);
472 if (emit_canremat(ref) && irref_isk(ref)) {
473 ra_rematk(as, ref);
474 checkmclim(as);
476 rset_clear(work, r);
478 #endif
479 work = ~as->freeset & RSET_GPR;
480 while (work) {
481 Reg r = rset_pickbot(work);
482 IRRef ref = regcost_ref(as->cost[r]);
483 if (emit_canremat(ref) && irref_isk(ref)) {
484 ra_rematk(as, ref);
485 checkmclim(as);
487 rset_clear(work, r);
491 #ifdef RID_NUM_KREF
492 /* Allocate a register for a constant. */
493 static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
495 /* First try to find a register which already holds the same constant. */
496 RegSet pick, work = ~as->freeset & RSET_GPR;
497 Reg r;
498 while (work) {
499 IRRef ref;
500 r = rset_pickbot(work);
501 ref = regcost_ref(as->cost[r]);
502 if (ref < ASMREF_L &&
503 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
504 return r;
505 rset_clear(work, r);
507 pick = as->freeset & allow;
508 if (pick) {
509 /* Constants should preferably get unmodified registers. */
510 if ((pick & ~as->modset))
511 pick &= ~as->modset;
512 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
513 } else {
514 r = ra_evict(as, allow);
516 RA_DBGX((as, "allock $x $r", k, r));
517 ra_setkref(as, r, k);
518 rset_clear(as->freeset, r);
519 ra_noweak(as, r);
520 return r;
523 /* Allocate a specific register for a constant. */
524 static void ra_allockreg(ASMState *as, int32_t k, Reg r)
526 Reg kr = ra_allock(as, k, RID2RSET(r));
527 if (kr != r) {
528 IRIns irdummy;
529 irdummy.t.irt = IRT_INT;
530 ra_scratch(as, RID2RSET(r));
531 emit_movrr(as, &irdummy, r, kr);
534 #else
535 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
536 #endif
538 /* Allocate a register for ref from the allowed set of registers.
539 ** Note: this function assumes the ref does NOT have a register yet!
540 ** Picks an optimal register, sets the cost and marks the register as non-free.
542 static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
544 IRIns *ir = IR(ref);
545 RegSet pick = as->freeset & allow;
546 Reg r;
547 lua_assert(ra_noreg(ir->r));
548 if (pick) {
549 /* First check register hint from propagation or PHI. */
550 if (ra_hashint(ir->r)) {
551 r = ra_gethint(ir->r);
552 if (rset_test(pick, r)) /* Use hint register if possible. */
553 goto found;
554 /* Rematerialization is cheaper than missing a hint. */
555 if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
556 ra_rematk(as, regcost_ref(as->cost[r]));
557 goto found;
559 RA_DBGX((as, "hintmiss $f $r", ref, r));
561 /* Invariants should preferably get unmodified registers. */
562 if (ref < as->loopref && !irt_isphi(ir->t)) {
563 if ((pick & ~as->modset))
564 pick &= ~as->modset;
565 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
566 } else {
567 /* We've got plenty of regs, so get callee-save regs if possible. */
568 if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
569 pick &= ~RSET_SCRATCH;
570 r = rset_picktop(pick);
572 } else {
573 r = ra_evict(as, allow);
575 found:
576 RA_DBGX((as, "alloc $f $r", ref, r));
577 ir->r = (uint8_t)r;
578 rset_clear(as->freeset, r);
579 ra_noweak(as, r);
580 as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
581 return r;
584 /* Allocate a register on-demand. */
585 static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
587 Reg r = IR(ref)->r;
588 /* Note: allow is ignored if the register is already allocated. */
589 if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
590 ra_noweak(as, r);
591 return r;
594 /* Rename register allocation and emit move. */
595 static void ra_rename(ASMState *as, Reg down, Reg up)
597 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
598 IRIns *ir = IR(ref);
599 ir->r = (uint8_t)up;
600 as->cost[down] = 0;
601 lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
602 lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
603 ra_free(as, down); /* 'down' is free ... */
604 ra_modified(as, down);
605 rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
606 ra_noweak(as, up);
607 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
608 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
609 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
610 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
611 ren = tref_ref(lj_ir_emit(as->J));
612 as->ir = as->T->ir; /* The IR may have been reallocated. */
613 IR(ren)->r = (uint8_t)down;
614 IR(ren)->s = SPS_NONE;
618 /* Pick a destination register (marked as free).
619 ** Caveat: allow is ignored if there's already a destination register.
620 ** Use ra_destreg() to get a specific register.
622 static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
624 Reg dest = ir->r;
625 if (ra_hasreg(dest)) {
626 ra_free(as, dest);
627 ra_modified(as, dest);
628 } else {
629 if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
630 dest = ra_gethint(dest);
631 ra_modified(as, dest);
632 RA_DBGX((as, "dest $r", dest));
633 } else {
634 dest = ra_scratch(as, allow);
636 ir->r = dest;
638 if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
639 return dest;
642 /* Force a specific destination register (marked as free). */
643 static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
645 Reg dest = ra_dest(as, ir, RID2RSET(r));
646 if (dest != r) {
647 lua_assert(rset_test(as->freeset, r));
648 ra_modified(as, r);
649 emit_movrr(as, ir, dest, r);
653 #if LJ_TARGET_X86ORX64
654 /* Propagate dest register to left reference. Emit moves as needed.
655 ** This is a required fixup step for all 2-operand machine instructions.
657 static void ra_left(ASMState *as, Reg dest, IRRef lref)
659 IRIns *ir = IR(lref);
660 Reg left = ir->r;
661 if (ra_noreg(left)) {
662 if (irref_isk(lref)) {
663 if (ir->o == IR_KNUM) {
664 cTValue *tv = ir_knum(ir);
665 /* FP remat needs a load except for +0. Still better than eviction. */
666 if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
667 emit_loadn(as, dest, tv);
668 return;
670 #if LJ_64
671 } else if (ir->o == IR_KINT64) {
672 emit_loadu64(as, dest, ir_kint64(ir)->u64);
673 return;
674 #endif
675 } else {
676 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
677 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
678 emit_loadi(as, dest, ir->i);
679 return;
682 if (!ra_hashint(left) && !iscrossref(as, lref))
683 ra_sethint(ir->r, dest); /* Propagate register hint. */
684 left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
686 ra_noweak(as, left);
687 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
688 if (dest != left) {
689 /* Use register renaming if dest is the PHI reg. */
690 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
691 ra_modified(as, left);
692 ra_rename(as, left, dest);
693 } else {
694 emit_movrr(as, ir, dest, left);
698 #else
699 /* Similar to ra_left, except we override any hints. */
700 static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
702 IRIns *ir = IR(lref);
703 Reg left = ir->r;
704 if (ra_noreg(left)) {
705 ra_sethint(ir->r, dest); /* Propagate register hint. */
706 left = ra_allocref(as, lref,
707 (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
709 ra_noweak(as, left);
710 if (dest != left) {
711 /* Use register renaming if dest is the PHI reg. */
712 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
713 ra_modified(as, left);
714 ra_rename(as, left, dest);
715 } else {
716 emit_movrr(as, ir, dest, left);
720 #endif
722 #if !LJ_64
723 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
724 static void ra_destpair(ASMState *as, IRIns *ir)
726 Reg destlo = ir->r, desthi = (ir+1)->r;
727 /* First spill unrelated refs blocking the destination registers. */
728 if (!rset_test(as->freeset, RID_RETLO) &&
729 destlo != RID_RETLO && desthi != RID_RETLO)
730 ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
731 if (!rset_test(as->freeset, RID_RETHI) &&
732 destlo != RID_RETHI && desthi != RID_RETHI)
733 ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
734 /* Next free the destination registers (if any). */
735 if (ra_hasreg(destlo)) {
736 ra_free(as, destlo);
737 ra_modified(as, destlo);
738 } else {
739 destlo = RID_RETLO;
741 if (ra_hasreg(desthi)) {
742 ra_free(as, desthi);
743 ra_modified(as, desthi);
744 } else {
745 desthi = RID_RETHI;
747 /* Check for conflicts and shuffle the registers as needed. */
748 if (destlo == RID_RETHI) {
749 if (desthi == RID_RETLO) {
750 #if LJ_TARGET_X86
751 *--as->mcp = XI_XCHGa + RID_RETHI;
752 #else
753 emit_movrr(as, ir, RID_RETHI, RID_TMP);
754 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
755 emit_movrr(as, ir, RID_TMP, RID_RETLO);
756 #endif
757 } else {
758 emit_movrr(as, ir, RID_RETHI, RID_RETLO);
759 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
761 } else if (desthi == RID_RETLO) {
762 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
763 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
764 } else {
765 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
766 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
768 /* Restore spill slots (if any). */
769 if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
770 if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
772 #endif
774 /* -- Snapshot handling --------- ----------------------------------------- */
776 /* Can we rematerialize a KNUM instead of forcing a spill? */
777 static int asm_snap_canremat(ASMState *as)
779 Reg r;
780 for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
781 if (irref_isk(regcost_ref(as->cost[r])))
782 return 1;
783 return 0;
786 /* Check whether a sunk store corresponds to an allocation. */
787 static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs)
789 if (irs->s == 255) {
790 if (irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
791 irs->o == IR_FSTORE || irs->o == IR_XSTORE) {
792 IRIns *irk = IR(irs->op1);
793 if (irk->o == IR_AREF || irk->o == IR_HREFK)
794 irk = IR(irk->op1);
795 return (IR(irk->op1) == ira);
797 return 0;
798 } else {
799 return (ira + irs->s == irs); /* Quick check. */
803 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
804 static void asm_snap_alloc1(ASMState *as, IRRef ref)
806 IRIns *ir = IR(ref);
807 if (!irref_isk(ref) && (!(ra_used(ir) || ir->r == RID_SUNK))) {
808 if (ir->r == RID_SINK) {
809 ir->r = RID_SUNK;
810 #if LJ_HASFFI
811 if (ir->o == IR_CNEWI) { /* Allocate CNEWI value. */
812 asm_snap_alloc1(as, ir->op2);
813 if (LJ_32 && (ir+1)->o == IR_HIOP)
814 asm_snap_alloc1(as, (ir+1)->op2);
815 } else
816 #endif
817 { /* Allocate stored values for TNEW, TDUP and CNEW. */
818 IRIns *irs;
819 lua_assert(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW);
820 for (irs = IR(as->snapref-1); irs > ir; irs--)
821 if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) {
822 lua_assert(irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
823 irs->o == IR_FSTORE || irs->o == IR_XSTORE);
824 asm_snap_alloc1(as, irs->op2);
825 if (LJ_32 && (irs+1)->o == IR_HIOP)
826 asm_snap_alloc1(as, (irs+1)->op2);
829 } else {
830 RegSet allow;
831 if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) {
832 IRIns *irc;
833 for (irc = IR(as->curins); irc > ir; irc--)
834 if ((irc->op1 == ref || irc->op2 == ref) &&
835 !(irc->r == RID_SINK || irc->r == RID_SUNK))
836 goto nosink; /* Don't sink conversion if result is used. */
837 asm_snap_alloc1(as, ir->op1);
838 return;
840 nosink:
841 allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR;
842 if ((as->freeset & allow) ||
843 (allow == RSET_FPR && asm_snap_canremat(as))) {
844 /* Get a weak register if we have a free one or can rematerialize. */
845 Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
846 if (!irt_isphi(ir->t))
847 ra_weak(as, r); /* But mark it as weakly referenced. */
848 checkmclim(as);
849 RA_DBGX((as, "snapreg $f $r", ref, ir->r));
850 } else {
851 ra_spill(as, ir); /* Otherwise force a spill slot. */
852 RA_DBGX((as, "snapspill $f $s", ref, ir->s));
858 /* Allocate refs escaping to a snapshot. */
859 static void asm_snap_alloc(ASMState *as)
861 SnapShot *snap = &as->T->snap[as->snapno];
862 SnapEntry *map = &as->T->snapmap[snap->mapofs];
863 MSize n, nent = snap->nent;
864 for (n = 0; n < nent; n++) {
865 SnapEntry sn = map[n];
866 IRRef ref = snap_ref(sn);
867 if (!irref_isk(ref)) {
868 asm_snap_alloc1(as, ref);
869 if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
870 lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
871 asm_snap_alloc1(as, ref+1);
877 /* All guards for a snapshot use the same exitno. This is currently the
878 ** same as the snapshot number. Since the exact origin of the exit cannot
879 ** be determined, all guards for the same snapshot must exit with the same
880 ** RegSP mapping.
881 ** A renamed ref which has been used in a prior guard for the same snapshot
882 ** would cause an inconsistency. The easy way out is to force a spill slot.
884 static int asm_snap_checkrename(ASMState *as, IRRef ren)
886 SnapShot *snap = &as->T->snap[as->snapno];
887 SnapEntry *map = &as->T->snapmap[snap->mapofs];
888 MSize n, nent = snap->nent;
889 for (n = 0; n < nent; n++) {
890 SnapEntry sn = map[n];
891 IRRef ref = snap_ref(sn);
892 if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
893 IRIns *ir = IR(ref);
894 ra_spill(as, ir); /* Register renamed, so force a spill slot. */
895 RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
896 return 1; /* Found. */
899 return 0; /* Not found. */
902 /* Prepare snapshot for next guard instruction. */
903 static void asm_snap_prep(ASMState *as)
905 if (as->curins < as->snapref) {
906 do {
907 if (as->snapno == 0) return; /* Called by sunk stores before snap #0. */
908 as->snapno--;
909 as->snapref = as->T->snap[as->snapno].ref;
910 } while (as->curins < as->snapref);
911 asm_snap_alloc(as);
912 as->snaprename = as->T->nins;
913 } else {
914 /* Process any renames above the highwater mark. */
915 for (; as->snaprename < as->T->nins; as->snaprename++) {
916 IRIns *ir = IR(as->snaprename);
917 if (asm_snap_checkrename(as, ir->op1))
918 ir->op2 = REF_BIAS-1; /* Kill rename. */
923 /* -- Miscellaneous helpers ----------------------------------------------- */
925 /* Collect arguments from CALL* and CARG instructions. */
926 static void asm_collectargs(ASMState *as, IRIns *ir,
927 const CCallInfo *ci, IRRef *args)
929 uint32_t n = CCI_NARGS(ci);
930 lua_assert(n <= CCI_NARGS_MAX);
931 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
932 while (n-- > 1) {
933 ir = IR(ir->op1);
934 lua_assert(ir->o == IR_CARG);
935 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
937 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
938 lua_assert(IR(ir->op1)->o != IR_CARG);
941 /* Reconstruct CCallInfo flags for CALLX*. */
942 static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
944 uint32_t nargs = 0;
945 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
946 IRIns *ira = IR(ir->op1);
947 nargs++;
948 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
950 #if LJ_HASFFI
951 if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
952 CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
953 CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
954 nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
955 #if LJ_TARGET_X86
956 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
957 #endif
959 #endif
960 return (nargs | (ir->t.irt << CCI_OTSHIFT));
963 /* Calculate stack adjustment. */
964 static int32_t asm_stack_adjust(ASMState *as)
966 if (as->evenspill <= SPS_FIXED)
967 return 0;
968 return sps_scale(sps_align(as->evenspill));
971 /* Must match with hash*() in lj_tab.c. */
972 static uint32_t ir_khash(IRIns *ir)
974 uint32_t lo, hi;
975 if (irt_isstr(ir->t)) {
976 return ir_kstr(ir)->hash;
977 } else if (irt_isnum(ir->t)) {
978 lo = ir_knum(ir)->u32.lo;
979 hi = ir_knum(ir)->u32.hi << 1;
980 } else if (irt_ispri(ir->t)) {
981 lua_assert(!irt_isnil(ir->t));
982 return irt_type(ir->t)-IRT_FALSE;
983 } else {
984 lua_assert(irt_isgcv(ir->t));
985 lo = u32ptr(ir_kgc(ir));
986 hi = lo + HASH_BIAS;
988 return hashrot(lo, hi);
991 /* -- Allocations --------------------------------------------------------- */
993 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
994 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
996 static void asm_snew(ASMState *as, IRIns *ir)
998 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
999 IRRef args[3];
1000 args[0] = ASMREF_L; /* lua_State *L */
1001 args[1] = ir->op1; /* const char *str */
1002 args[2] = ir->op2; /* size_t len */
1003 as->gcsteps++;
1004 asm_setupresult(as, ir, ci); /* GCstr * */
1005 asm_gencall(as, ci, args);
1008 static void asm_tnew(ASMState *as, IRIns *ir)
1010 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
1011 IRRef args[2];
1012 args[0] = ASMREF_L; /* lua_State *L */
1013 args[1] = ASMREF_TMP1; /* uint32_t ahsize */
1014 as->gcsteps++;
1015 asm_setupresult(as, ir, ci); /* GCtab * */
1016 asm_gencall(as, ci, args);
1017 ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
1020 static void asm_tdup(ASMState *as, IRIns *ir)
1022 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
1023 IRRef args[2];
1024 args[0] = ASMREF_L; /* lua_State *L */
1025 args[1] = ir->op1; /* const GCtab *kt */
1026 as->gcsteps++;
1027 asm_setupresult(as, ir, ci); /* GCtab * */
1028 asm_gencall(as, ci, args);
1031 static void asm_gc_check(ASMState *as);
1033 /* Explicit GC step. */
1034 static void asm_gcstep(ASMState *as, IRIns *ir)
1036 IRIns *ira;
1037 for (ira = IR(as->stopins+1); ira < ir; ira++)
1038 if ((ira->o == IR_TNEW || ira->o == IR_TDUP ||
1039 (LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) &&
1040 ra_used(ira))
1041 as->gcsteps++;
1042 if (as->gcsteps)
1043 asm_gc_check(as);
1044 as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */
1047 /* -- PHI and loop handling ----------------------------------------------- */
1049 /* Break a PHI cycle by renaming to a free register (evict if needed). */
1050 static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
1051 RegSet allow)
1053 RegSet candidates = blocked & allow;
1054 if (candidates) { /* If this register file has candidates. */
1055 /* Note: the set for ra_pick cannot be empty, since each register file
1056 ** has some registers never allocated to PHIs.
1058 Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
1059 if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
1060 candidates = candidates & ~blockedby;
1061 down = rset_picktop(candidates); /* Pick candidate PHI register. */
1062 ra_rename(as, down, up); /* And rename it to the free register. */
1066 /* PHI register shuffling.
1068 ** The allocator tries hard to preserve PHI register assignments across
1069 ** the loop body. Most of the time this loop does nothing, since there
1070 ** are no register mismatches.
1072 ** If a register mismatch is detected and ...
1073 ** - the register is currently free: rename it.
1074 ** - the register is blocked by an invariant: restore/remat and rename it.
1075 ** - Otherwise the register is used by another PHI, so mark it as blocked.
1077 ** The renames are order-sensitive, so just retry the loop if a register
1078 ** is marked as blocked, but has been freed in the meantime. A cycle is
1079 ** detected if all of the blocked registers are allocated. To break the
1080 ** cycle rename one of them to a free register and retry.
1082 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1084 static void asm_phi_shuffle(ASMState *as)
1086 RegSet work;
1088 /* Find and resolve PHI register mismatches. */
1089 for (;;) {
1090 RegSet blocked = RSET_EMPTY;
1091 RegSet blockedby = RSET_EMPTY;
1092 RegSet phiset = as->phiset;
1093 while (phiset) { /* Check all left PHI operand registers. */
1094 Reg r = rset_pickbot(phiset);
1095 IRIns *irl = IR(as->phireg[r]);
1096 Reg left = irl->r;
1097 if (r != left) { /* Mismatch? */
1098 if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
1099 IRRef ref = regcost_ref(as->cost[r]);
1100 /* Blocked by other PHI (w/reg)? */
1101 if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
1102 rset_set(blocked, r);
1103 if (ra_hasreg(left))
1104 rset_set(blockedby, left);
1105 left = RID_NONE;
1106 } else { /* Otherwise grab register from invariant. */
1107 ra_restore(as, ref);
1108 checkmclim(as);
1111 if (ra_hasreg(left)) {
1112 ra_rename(as, left, r);
1113 checkmclim(as);
1116 rset_clear(phiset, r);
1118 if (!blocked) break; /* Finished. */
1119 if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
1120 asm_phi_break(as, blocked, blockedby, RSET_GPR);
1121 if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
1122 checkmclim(as);
1123 } /* Else retry some more renames. */
1126 /* Restore/remat invariants whose registers are modified inside the loop. */
1127 #if !LJ_SOFTFP
1128 work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR;
1129 while (work) {
1130 Reg r = rset_pickbot(work);
1131 ra_restore(as, regcost_ref(as->cost[r]));
1132 rset_clear(work, r);
1133 checkmclim(as);
1135 #endif
1136 work = as->modset & ~(as->freeset | as->phiset);
1137 while (work) {
1138 Reg r = rset_pickbot(work);
1139 ra_restore(as, regcost_ref(as->cost[r]));
1140 rset_clear(work, r);
1141 checkmclim(as);
1144 /* Allocate and save all unsaved PHI regs and clear marks. */
1145 work = as->phiset;
1146 while (work) {
1147 Reg r = rset_picktop(work);
1148 IRRef lref = as->phireg[r];
1149 IRIns *ir = IR(lref);
1150 if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
1151 irt_clearmark(ir->t); /* Handled here, so clear marker now. */
1152 ra_alloc1(as, lref, RID2RSET(r));
1153 ra_save(as, ir, r); /* Save to spill slot inside the loop. */
1154 checkmclim(as);
1156 rset_clear(work, r);
1160 /* Copy unsynced left/right PHI spill slots. Rarely needed. */
1161 static void asm_phi_copyspill(ASMState *as)
1163 int need = 0;
1164 IRIns *ir;
1165 for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--)
1166 if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s))
1167 need |= irt_isfp(ir->t) ? 2 : 1; /* Unsynced spill slot? */
1168 if ((need & 1)) { /* Copy integer spill slots. */
1169 #if !LJ_TARGET_X86ORX64
1170 Reg r = RID_TMP;
1171 #else
1172 Reg r = RID_RET;
1173 if ((as->freeset & RSET_GPR))
1174 r = rset_pickbot((as->freeset & RSET_GPR));
1175 else
1176 emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1177 #endif
1178 for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
1179 if (ra_hasspill(ir->s)) {
1180 IRIns *irl = IR(ir->op1);
1181 if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) {
1182 emit_spstore(as, irl, r, sps_scale(irl->s));
1183 emit_spload(as, ir, r, sps_scale(ir->s));
1187 #if LJ_TARGET_X86ORX64
1188 if (!rset_test(as->freeset, r))
1189 emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1190 #endif
1192 #if !LJ_SOFTFP
1193 if ((need & 2)) { /* Copy FP spill slots. */
1194 #if LJ_TARGET_X86
1195 Reg r = RID_XMM0;
1196 #else
1197 Reg r = RID_FPRET;
1198 #endif
1199 if ((as->freeset & RSET_FPR))
1200 r = rset_pickbot((as->freeset & RSET_FPR));
1201 if (!rset_test(as->freeset, r))
1202 emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1203 for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
1204 if (ra_hasspill(ir->s)) {
1205 IRIns *irl = IR(ir->op1);
1206 if (ra_hasspill(irl->s) && irt_isfp(ir->t)) {
1207 emit_spstore(as, irl, r, sps_scale(irl->s));
1208 emit_spload(as, ir, r, sps_scale(ir->s));
1212 if (!rset_test(as->freeset, r))
1213 emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
1215 #endif
1218 /* Emit renames for left PHIs which are only spilled outside the loop. */
1219 static void asm_phi_fixup(ASMState *as)
1221 RegSet work = as->phiset;
1222 while (work) {
1223 Reg r = rset_picktop(work);
1224 IRRef lref = as->phireg[r];
1225 IRIns *ir = IR(lref);
1226 /* Left PHI gained a spill slot before the loop? */
1227 if (irt_ismarked(ir->t) && ra_hasspill(ir->s)) {
1228 IRRef ren;
1229 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
1230 ren = tref_ref(lj_ir_emit(as->J));
1231 as->ir = as->T->ir; /* The IR may have been reallocated. */
1232 IR(ren)->r = (uint8_t)r;
1233 IR(ren)->s = SPS_NONE;
1235 irt_clearmark(ir->t); /* Always clear marker. */
1236 rset_clear(work, r);
1240 /* Setup right PHI reference. */
1241 static void asm_phi(ASMState *as, IRIns *ir)
1243 RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1244 ~as->phiset;
1245 RegSet afree = (as->freeset & allow);
1246 IRIns *irl = IR(ir->op1);
1247 IRIns *irr = IR(ir->op2);
1248 if (ir->r == RID_SINK) /* Sink PHI. */
1249 return;
1250 /* Spill slot shuffling is not implemented yet (but rarely needed). */
1251 if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
1252 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1253 /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1254 if ((afree & (afree-1))) { /* Two or more free registers? */
1255 Reg r;
1256 if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
1257 r = ra_allocref(as, ir->op2, allow);
1258 } else { /* Duplicate right PHI, need a copy (rare). */
1259 r = ra_scratch(as, allow);
1260 emit_movrr(as, irr, r, irr->r);
1262 ir->r = (uint8_t)r;
1263 rset_set(as->phiset, r);
1264 as->phireg[r] = (IRRef1)ir->op1;
1265 irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
1266 if (ra_noreg(irl->r))
1267 ra_sethint(irl->r, r); /* Set register hint for left PHI. */
1268 } else { /* Otherwise allocate a spill slot. */
1269 /* This is overly restrictive, but it triggers only on synthetic code. */
1270 if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
1271 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1272 ra_spill(as, ir);
1273 irr->s = ir->s; /* Set right PHI spill slot. Sync left slot later. */
1277 static void asm_loop_fixup(ASMState *as);
1279 /* Middle part of a loop. */
1280 static void asm_loop(ASMState *as)
1282 MCode *mcspill;
1283 /* LOOP is a guard, so the snapno is up to date. */
1284 as->loopsnapno = as->snapno;
1285 if (as->gcsteps)
1286 asm_gc_check(as);
1287 /* LOOP marks the transition from the variant to the invariant part. */
1288 as->flagmcp = as->invmcp = NULL;
1289 as->sectref = 0;
1290 if (!neverfuse(as)) as->fuseref = 0;
1291 asm_phi_shuffle(as);
1292 mcspill = as->mcp;
1293 asm_phi_copyspill(as);
1294 asm_loop_fixup(as);
1295 as->mcloop = as->mcp;
1296 RA_DBGX((as, "===== LOOP ====="));
1297 if (!as->realign) RA_DBG_FLUSH();
1298 if (as->mcp != mcspill)
1299 emit_jmp(as, mcspill);
1302 /* -- Target-specific assembler ------------------------------------------- */
1304 #if LJ_TARGET_X86ORX64
1305 #include "lj_asm_x86.h"
1306 #elif LJ_TARGET_ARM
1307 #include "lj_asm_arm.h"
1308 #elif LJ_TARGET_PPC
1309 #include "lj_asm_ppc.h"
1310 #elif LJ_TARGET_MIPS
1311 #include "lj_asm_mips.h"
1312 #else
1313 #error "Missing assembler for target CPU"
1314 #endif
1316 /* -- Head of trace ------------------------------------------------------- */
1318 /* Head of a root trace. */
1319 static void asm_head_root(ASMState *as)
1321 int32_t spadj;
1322 asm_head_root_base(as);
1323 emit_setvmstate(as, (int32_t)as->T->traceno);
1324 spadj = asm_stack_adjust(as);
1325 as->T->spadjust = (uint16_t)spadj;
1326 emit_spsub(as, spadj);
1327 /* Root traces assume a checked stack for the starting proto. */
1328 as->T->topslot = gcref(as->T->startpt)->pt.framesize;
1331 /* Head of a side trace.
1333 ** The current simplistic algorithm requires that all slots inherited
1334 ** from the parent are live in a register between pass 2 and pass 3. This
1335 ** avoids the complexity of stack slot shuffling. But of course this may
1336 ** overflow the register set in some cases and cause the dreaded error:
1337 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1339 static void asm_head_side(ASMState *as)
1341 IRRef1 sloadins[RID_MAX];
1342 RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
1343 RegSet live = RSET_EMPTY; /* Live parent registers. */
1344 IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
1345 int32_t spadj, spdelta;
1346 int pass2 = 0;
1347 int pass3 = 0;
1348 IRRef i;
1350 allow = asm_head_side_base(as, irp, allow);
1352 /* Scan all parent SLOADs and collect register dependencies. */
1353 for (i = as->stopins; i > REF_BASE; i--) {
1354 IRIns *ir = IR(i);
1355 RegSP rs;
1356 lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
1357 (LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL);
1358 rs = as->parentmap[i - REF_FIRST];
1359 if (ra_hasreg(ir->r)) {
1360 rset_clear(allow, ir->r);
1361 if (ra_hasspill(ir->s)) {
1362 ra_save(as, ir, ir->r);
1363 checkmclim(as);
1365 } else if (ra_hasspill(ir->s)) {
1366 irt_setmark(ir->t);
1367 pass2 = 1;
1369 if (ir->r == rs) { /* Coalesce matching registers right now. */
1370 ra_free(as, ir->r);
1371 } else if (ra_hasspill(regsp_spill(rs))) {
1372 if (ra_hasreg(ir->r))
1373 pass3 = 1;
1374 } else if (ra_used(ir)) {
1375 sloadins[rs] = (IRRef1)i;
1376 rset_set(live, rs); /* Block live parent register. */
1380 /* Calculate stack frame adjustment. */
1381 spadj = asm_stack_adjust(as);
1382 spdelta = spadj - (int32_t)as->parent->spadjust;
1383 if (spdelta < 0) { /* Don't shrink the stack frame. */
1384 spadj = (int32_t)as->parent->spadjust;
1385 spdelta = 0;
1387 as->T->spadjust = (uint16_t)spadj;
1389 /* Reload spilled target registers. */
1390 if (pass2) {
1391 for (i = as->stopins; i > REF_BASE; i--) {
1392 IRIns *ir = IR(i);
1393 if (irt_ismarked(ir->t)) {
1394 RegSet mask;
1395 Reg r;
1396 RegSP rs;
1397 irt_clearmark(ir->t);
1398 rs = as->parentmap[i - REF_FIRST];
1399 if (!ra_hasspill(regsp_spill(rs)))
1400 ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
1401 else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1402 continue; /* Same spill slot, do nothing. */
1403 mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1404 if (mask == RSET_EMPTY)
1405 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1406 r = ra_allocref(as, i, mask);
1407 ra_save(as, ir, r);
1408 rset_clear(allow, r);
1409 if (r == rs) { /* Coalesce matching registers right now. */
1410 ra_free(as, r);
1411 rset_clear(live, r);
1412 } else if (ra_hasspill(regsp_spill(rs))) {
1413 pass3 = 1;
1415 checkmclim(as);
1420 /* Store trace number and adjust stack frame relative to the parent. */
1421 emit_setvmstate(as, (int32_t)as->T->traceno);
1422 emit_spsub(as, spdelta);
1424 #if !LJ_TARGET_X86ORX64
1425 /* Restore BASE register from parent spill slot. */
1426 if (ra_hasspill(irp->s))
1427 emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1428 #endif
1430 /* Restore target registers from parent spill slots. */
1431 if (pass3) {
1432 RegSet work = ~as->freeset & RSET_ALL;
1433 while (work) {
1434 Reg r = rset_pickbot(work);
1435 IRRef ref = regcost_ref(as->cost[r]);
1436 RegSP rs = as->parentmap[ref - REF_FIRST];
1437 rset_clear(work, r);
1438 if (ra_hasspill(regsp_spill(rs))) {
1439 int32_t ofs = sps_scale(regsp_spill(rs));
1440 ra_free(as, r);
1441 emit_spload(as, IR(ref), r, ofs);
1442 checkmclim(as);
1447 /* Shuffle registers to match up target regs with parent regs. */
1448 for (;;) {
1449 RegSet work;
1451 /* Repeatedly coalesce free live registers by moving to their target. */
1452 while ((work = as->freeset & live) != RSET_EMPTY) {
1453 Reg rp = rset_pickbot(work);
1454 IRIns *ir = IR(sloadins[rp]);
1455 rset_clear(live, rp);
1456 rset_clear(allow, rp);
1457 ra_free(as, ir->r);
1458 emit_movrr(as, ir, ir->r, rp);
1459 checkmclim(as);
1462 /* We're done if no live registers remain. */
1463 if (live == RSET_EMPTY)
1464 break;
1466 /* Break cycles by renaming one target to a temp. register. */
1467 if (live & RSET_GPR) {
1468 RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1469 if (tmpset == RSET_EMPTY)
1470 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1471 ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1473 if (!LJ_SOFTFP && (live & RSET_FPR)) {
1474 RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1475 if (tmpset == RSET_EMPTY)
1476 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1477 ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1479 checkmclim(as);
1480 /* Continue with coalescing to fix up the broken cycle(s). */
1483 /* Inherit top stack slot already checked by parent trace. */
1484 as->T->topslot = as->parent->topslot;
1485 if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
1486 #ifdef EXITSTATE_CHECKEXIT
1487 /* Highest exit + 1 indicates stack check. */
1488 ExitNo exitno = as->T->nsnap;
1489 #else
1490 /* Reuse the parent exit in the context of the parent trace. */
1491 ExitNo exitno = as->J->exitno;
1492 #endif
1493 as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
1494 asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1498 /* -- Tail of trace ------------------------------------------------------- */
1500 /* Get base slot for a snapshot. */
1501 static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1503 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1504 MSize n;
1505 for (n = snap->nent; n > 0; n--) {
1506 SnapEntry sn = map[n-1];
1507 if ((sn & SNAP_FRAME)) {
1508 *gotframe = 1;
1509 return snap_slot(sn);
1512 return 0;
1515 /* Link to another trace. */
1516 static void asm_tail_link(ASMState *as)
1518 SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
1519 SnapShot *snap = &as->T->snap[snapno];
1520 int gotframe = 0;
1521 BCReg baseslot = asm_baseslot(as, snap, &gotframe);
1523 as->topslot = snap->topslot;
1524 checkmclim(as);
1525 ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1527 if (as->T->link == 0) {
1528 /* Setup fixed registers for exit to interpreter. */
1529 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
1530 int32_t mres;
1531 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1532 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1533 if (bc_isret(bc_op(*retpc)))
1534 pc = retpc;
1536 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1537 ra_allockreg(as, i32ptr(pc), RID_LPC);
1538 mres = (int32_t)(snap->nslots - baseslot);
1539 switch (bc_op(*pc)) {
1540 case BC_CALLM: case BC_CALLMT:
1541 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
1542 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1543 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1544 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1546 ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
1547 } else if (baseslot) {
1548 /* Save modified BASE for linking to trace with higher start frame. */
1549 emit_setgl(as, RID_BASE, jit_base);
1551 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1553 /* Sync the interpreter state with the on-trace state. */
1554 asm_stack_restore(as, snap);
1556 /* Root traces that add frames need to check the stack at the end. */
1557 if (!as->parent && gotframe)
1558 asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1561 /* -- Trace setup --------------------------------------------------------- */
1563 /* Clear reg/sp for all instructions and add register hints. */
1564 static void asm_setup_regsp(ASMState *as)
1566 GCtrace *T = as->T;
1567 int sink = T->sinktags;
1568 IRRef nins = T->nins;
1569 IRIns *ir, *lastir;
1570 int inloop;
1571 #if LJ_TARGET_ARM
1572 uint32_t rload = 0xa6402a64;
1573 #endif
1575 ra_setup(as);
1577 /* Clear reg/sp for constants. */
1578 for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++)
1579 ir->prev = REGSP_INIT;
1581 /* REF_BASE is used for implicit references to the BASE register. */
1582 lastir->prev = REGSP_HINT(RID_BASE);
1584 ir = IR(nins-1);
1585 if (ir->o == IR_RENAME) {
1586 do { ir--; nins--; } while (ir->o == IR_RENAME);
1587 T->nins = nins; /* Remove any renames left over from ASM restart. */
1589 as->snaprename = nins;
1590 as->snapref = nins;
1591 as->snapno = T->nsnap;
1593 as->stopins = REF_BASE;
1594 as->orignins = nins;
1595 as->curins = nins;
1597 /* Setup register hints for parent link instructions. */
1598 ir = IR(REF_FIRST);
1599 if (as->parent) {
1600 uint16_t *p;
1601 lastir = lj_snap_regspmap(as->parent, as->J->exitno, ir);
1602 if (lastir - ir > LJ_MAX_JSLOTS)
1603 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1604 as->stopins = (IRRef)((lastir-1) - as->ir);
1605 for (p = as->parentmap; ir < lastir; ir++) {
1606 RegSP rs = ir->prev;
1607 *p++ = (uint16_t)rs; /* Copy original parent RegSP to parentmap. */
1608 if (!ra_hasspill(regsp_spill(rs)))
1609 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1610 else
1611 ir->prev = REGSP_INIT;
1615 inloop = 0;
1616 as->evenspill = SPS_FIRST;
1617 for (lastir = IR(nins); ir < lastir; ir++) {
1618 if (sink) {
1619 if (ir->r == RID_SINK)
1620 continue;
1621 if (ir->r == RID_SUNK) { /* Revert after ASM restart. */
1622 ir->r = RID_SINK;
1623 continue;
1626 switch (ir->o) {
1627 case IR_LOOP:
1628 inloop = 1;
1629 break;
1630 #if LJ_TARGET_ARM
1631 case IR_SLOAD:
1632 if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP))
1633 break;
1634 /* fallthrough */
1635 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1636 if (!LJ_SOFTFP && irt_isnum(ir->t)) break;
1637 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1638 rload = lj_ror(rload, 4);
1639 continue;
1640 #endif
1641 case IR_CALLXS: {
1642 CCallInfo ci;
1643 ci.flags = asm_callx_flags(as, ir);
1644 ir->prev = asm_setup_call_slots(as, ir, &ci);
1645 if (inloop)
1646 as->modset |= RSET_SCRATCH;
1647 continue;
1649 case IR_CALLN: case IR_CALLL: case IR_CALLS: {
1650 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1651 ir->prev = asm_setup_call_slots(as, ir, ci);
1652 if (inloop)
1653 as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
1654 (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
1655 continue;
1657 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1658 case IR_HIOP:
1659 switch ((ir-1)->o) {
1660 #if LJ_SOFTFP && LJ_TARGET_ARM
1661 case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1662 if (ra_hashint((ir-1)->r)) {
1663 ir->prev = (ir-1)->prev + 1;
1664 continue;
1666 break;
1667 #endif
1668 #if !LJ_SOFTFP && LJ_NEED_FP64
1669 case IR_CONV:
1670 if (irt_isfp((ir-1)->t)) {
1671 ir->prev = REGSP_HINT(RID_FPRET);
1672 continue;
1674 /* fallthrough */
1675 #endif
1676 case IR_CALLN: case IR_CALLXS:
1677 #if LJ_SOFTFP
1678 case IR_MIN: case IR_MAX:
1679 #endif
1680 (ir-1)->prev = REGSP_HINT(RID_RETLO);
1681 ir->prev = REGSP_HINT(RID_RETHI);
1682 continue;
1683 default:
1684 break;
1686 break;
1687 #endif
1688 #if LJ_SOFTFP
1689 case IR_MIN: case IR_MAX:
1690 if ((ir+1)->o != IR_HIOP) break;
1691 /* fallthrough */
1692 #endif
1693 /* C calls evict all scratch regs and return results in RID_RET. */
1694 case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
1695 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1696 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1697 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
1698 ir->prev = REGSP_HINT(RID_RET);
1699 if (inloop)
1700 as->modset = RSET_SCRATCH;
1701 continue;
1702 case IR_STRTO: case IR_OBAR:
1703 if (inloop)
1704 as->modset = RSET_SCRATCH;
1705 break;
1706 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1707 case IR_ATAN2: case IR_LDEXP:
1708 #endif
1709 case IR_POW:
1710 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1711 #if LJ_TARGET_X86ORX64
1712 ir->prev = REGSP_HINT(RID_XMM0);
1713 if (inloop)
1714 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1715 #else
1716 ir->prev = REGSP_HINT(RID_FPRET);
1717 if (inloop)
1718 as->modset |= RSET_SCRATCH;
1719 #endif
1720 continue;
1722 /* fallthrough for integer POW */
1723 case IR_DIV: case IR_MOD:
1724 if (!irt_isnum(ir->t)) {
1725 ir->prev = REGSP_HINT(RID_RET);
1726 if (inloop)
1727 as->modset |= (RSET_SCRATCH & RSET_GPR);
1728 continue;
1730 break;
1731 case IR_FPMATH:
1732 #if LJ_TARGET_X86ORX64
1733 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
1734 ir->prev = REGSP_HINT(RID_XMM0);
1735 #if !LJ_64
1736 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
1737 as->evenspill = 4;
1738 #endif
1739 if (inloop)
1740 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1741 continue;
1742 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1743 ir->prev = REGSP_HINT(RID_XMM0);
1744 if (inloop)
1745 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1746 continue;
1748 break;
1749 #else
1750 ir->prev = REGSP_HINT(RID_FPRET);
1751 if (inloop)
1752 as->modset |= RSET_SCRATCH;
1753 continue;
1754 #endif
1755 #if LJ_TARGET_X86ORX64
1756 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1757 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
1758 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1759 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1760 if (inloop)
1761 rset_set(as->modset, RID_ECX);
1763 break;
1764 #endif
1765 /* Do not propagate hints across type conversions or loads. */
1766 case IR_TOBIT:
1767 case IR_XLOAD:
1768 #if !LJ_TARGET_ARM
1769 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1770 #endif
1771 break;
1772 case IR_CONV:
1773 if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
1774 (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
1775 break;
1776 /* fallthrough */
1777 default:
1778 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1779 if (irref_isk(ir->op2) && !irref_isk(ir->op1) &&
1780 ra_hashint(regsp_reg(IR(ir->op1)->prev))) {
1781 ir->prev = IR(ir->op1)->prev;
1782 continue;
1784 break;
1786 ir->prev = REGSP_INIT;
1788 if ((as->evenspill & 1))
1789 as->oddspill = as->evenspill++;
1790 else
1791 as->oddspill = 0;
1794 /* -- Assembler core ------------------------------------------------------ */
1796 /* Assemble a trace. */
1797 void lj_asm_trace(jit_State *J, GCtrace *T)
1799 ASMState as_;
1800 ASMState *as = &as_;
1801 MCode *origtop;
1803 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1804 J->cur.nins = lj_ir_nextins(J);
1805 J->cur.ir[J->cur.nins].o = IR_NOP;
1807 /* Setup initial state. Copy some fields to reduce indirections. */
1808 as->J = J;
1809 as->T = T;
1810 as->ir = T->ir;
1811 as->flags = J->flags;
1812 as->loopref = J->loopref;
1813 as->realign = NULL;
1814 as->loopinv = 0;
1815 as->parent = J->parent ? traceref(J, J->parent) : NULL;
1817 /* Reserve MCode memory. */
1818 as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
1819 as->mcp = as->mctop;
1820 as->mclim = as->mcbot + MCLIM_REDZONE;
1821 asm_setup_target(as);
1823 do {
1824 as->mcp = as->mctop;
1825 as->curins = T->nins;
1826 RA_DBG_START();
1827 RA_DBGX((as, "===== STOP ====="));
1829 /* General trace setup. Emit tail of trace. */
1830 asm_tail_prep(as);
1831 as->mcloop = NULL;
1832 as->flagmcp = NULL;
1833 as->topslot = 0;
1834 as->gcsteps = 0;
1835 as->sectref = as->loopref;
1836 as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
1837 asm_setup_regsp(as);
1838 if (!as->loopref)
1839 asm_tail_link(as);
1841 /* Assemble a trace in linear backwards order. */
1842 for (as->curins--; as->curins > as->stopins; as->curins--) {
1843 IRIns *ir = IR(as->curins);
1844 lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
1845 if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
1846 continue; /* Dead-code elimination can be soooo easy. */
1847 if (irt_isguard(ir->t))
1848 asm_snap_prep(as);
1849 RA_DBG_REF();
1850 checkmclim(as);
1851 asm_ir(as, ir);
1853 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1855 /* Emit head of trace. */
1856 RA_DBG_REF();
1857 checkmclim(as);
1858 if (as->gcsteps > 0) {
1859 as->curins = as->T->snap[0].ref;
1860 asm_snap_prep(as); /* The GC check is a guard. */
1861 asm_gc_check(as);
1863 ra_evictk(as);
1864 if (as->parent)
1865 asm_head_side(as);
1866 else
1867 asm_head_root(as);
1868 asm_phi_fixup(as);
1870 RA_DBGX((as, "===== START ===="));
1871 RA_DBG_FLUSH();
1872 if (as->freeset != RSET_ALL)
1873 lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
1875 /* Set trace entry point before fixing up tail to allow link to self. */
1876 T->mcode = as->mcp;
1877 T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
1878 if (!as->loopref)
1879 asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
1880 T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
1881 lj_mcode_sync(T->mcode, origtop);
1884 #undef IR
1886 #endif