Keep maximum frame extent in snap->topslot.
[luajit-2.0.git] / src / lj_asm.c
blob16671a8a0ad644a6ae7deccff49ba91f95cd743d
1 /*
2 ** IR assembler (SSA IR -> machine code).
3 ** Copyright (C) 2005-2011 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 /* Define this if you want to run LuaJIT with Valgrind. */
151 #ifdef LUAJIT_USE_VALGRIND
152 #include <valgrind/valgrind.h>
153 #define VG_INVALIDATE(p, sz) VALGRIND_DISCARD_TRANSLATIONS(p, sz)
154 #else
155 #define VG_INVALIDATE(p, sz) ((void)0)
156 #endif
158 /* -- Target-specific instruction emitter --------------------------------- */
160 #if LJ_TARGET_X86ORX64
161 #include "lj_emit_x86.h"
162 #elif LJ_TARGET_ARM
163 #include "lj_emit_arm.h"
164 #elif LJ_TARGET_PPC
165 #include "lj_emit_ppc.h"
166 #else
167 #error "Missing instruction emitter for target CPU"
168 #endif
170 /* -- Register allocator debugging ---------------------------------------- */
172 /* #define LUAJIT_DEBUG_RA */
174 #ifdef LUAJIT_DEBUG_RA
176 #include <stdio.h>
177 #include <stdarg.h>
179 #define RIDNAME(name) #name,
180 static const char *const ra_regname[] = {
181 GPRDEF(RIDNAME)
182 FPRDEF(RIDNAME)
183 VRIDDEF(RIDNAME)
184 NULL
186 #undef RIDNAME
188 static char ra_dbg_buf[65536];
189 static char *ra_dbg_p;
190 static char *ra_dbg_merge;
191 static MCode *ra_dbg_mcp;
193 static void ra_dstart(void)
195 ra_dbg_p = ra_dbg_buf;
196 ra_dbg_merge = NULL;
197 ra_dbg_mcp = NULL;
200 static void ra_dflush(void)
202 fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
203 ra_dstart();
206 static void ra_dprintf(ASMState *as, const char *fmt, ...)
208 char *p;
209 va_list argp;
210 va_start(argp, fmt);
211 p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
212 ra_dbg_mcp = NULL;
213 p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
214 for (;;) {
215 const char *e = strchr(fmt, '$');
216 if (e == NULL) break;
217 memcpy(p, fmt, (size_t)(e-fmt));
218 p += e-fmt;
219 if (e[1] == 'r') {
220 Reg r = va_arg(argp, Reg) & RID_MASK;
221 if (r <= RID_MAX) {
222 const char *q;
223 for (q = ra_regname[r]; *q; q++)
224 *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
225 } else {
226 *p++ = '?';
227 lua_assert(0);
229 } else if (e[1] == 'f' || e[1] == 'i') {
230 IRRef ref;
231 if (e[1] == 'f')
232 ref = va_arg(argp, IRRef);
233 else
234 ref = va_arg(argp, IRIns *) - as->ir;
235 if (ref >= REF_BIAS)
236 p += sprintf(p, "%04d", ref - REF_BIAS);
237 else
238 p += sprintf(p, "K%03d", REF_BIAS - ref);
239 } else if (e[1] == 's') {
240 uint32_t slot = va_arg(argp, uint32_t);
241 p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
242 } else if (e[1] == 'x') {
243 p += sprintf(p, "%08x", va_arg(argp, int32_t));
244 } else {
245 lua_assert(0);
247 fmt = e+2;
249 va_end(argp);
250 while (*fmt)
251 *p++ = *fmt++;
252 *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
253 if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
254 fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
255 p = ra_dbg_buf;
257 ra_dbg_p = p;
260 #define RA_DBG_START() ra_dstart()
261 #define RA_DBG_FLUSH() ra_dflush()
262 #define RA_DBG_REF() \
263 do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
264 ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
265 #define RA_DBGX(x) ra_dprintf x
267 #else
268 #define RA_DBG_START() ((void)0)
269 #define RA_DBG_FLUSH() ((void)0)
270 #define RA_DBG_REF() ((void)0)
271 #define RA_DBGX(x) ((void)0)
272 #endif
274 /* -- Register allocator -------------------------------------------------- */
276 #define ra_free(as, r) rset_set(as->freeset, (r))
277 #define ra_modified(as, r) rset_set(as->modset, (r))
278 #define ra_weak(as, r) rset_set(as->weakset, (r))
279 #define ra_noweak(as, r) rset_clear(as->weakset, (r))
281 #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
283 /* Setup register allocator. */
284 static void ra_setup(ASMState *as)
286 Reg r;
287 /* Initially all regs (except the stack pointer) are free for use. */
288 as->freeset = RSET_INIT;
289 as->modset = RSET_EMPTY;
290 as->weakset = RSET_EMPTY;
291 as->phiset = RSET_EMPTY;
292 memset(as->phireg, 0, sizeof(as->phireg));
293 for (r = RID_MIN_GPR; r < RID_MAX; r++)
294 as->cost[r] = REGCOST(~0u, 0u);
297 /* Rematerialize constants. */
298 static Reg ra_rematk(ASMState *as, IRRef ref)
300 IRIns *ir;
301 Reg r;
302 if (ra_iskref(ref)) {
303 r = ra_krefreg(ref);
304 lua_assert(!rset_test(as->freeset, r));
305 ra_free(as, r);
306 ra_modified(as, r);
307 emit_loadi(as, r, ra_krefk(as, ref));
308 return r;
310 ir = IR(ref);
311 r = ir->r;
312 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
313 ra_free(as, r);
314 ra_modified(as, r);
315 ir->r = RID_INIT; /* Do not keep any hint. */
316 RA_DBGX((as, "remat $i $r", ir, r));
317 #if !LJ_SOFTFP
318 if (ir->o == IR_KNUM) {
319 emit_loadn(as, r, ir_knum(ir));
320 } else
321 #endif
322 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
323 ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
324 emit_getgl(as, r, jit_base);
325 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
326 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
327 emit_getgl(as, r, jit_L);
328 #if LJ_64
329 } else if (ir->o == IR_KINT64) {
330 emit_loadu64(as, r, ir_kint64(ir)->u64);
331 #endif
332 } else {
333 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
334 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
335 emit_loadi(as, r, ir->i);
337 return r;
340 /* Force a spill. Allocate a new spill slot if needed. */
341 static int32_t ra_spill(ASMState *as, IRIns *ir)
343 int32_t slot = ir->s;
344 if (!ra_hasspill(slot)) {
345 if (irt_is64(ir->t)) {
346 slot = as->evenspill;
347 as->evenspill += 2;
348 } else if (as->oddspill) {
349 slot = as->oddspill;
350 as->oddspill = 0;
351 } else {
352 slot = as->evenspill;
353 as->oddspill = slot+1;
354 as->evenspill += 2;
356 if (as->evenspill > 256)
357 lj_trace_err(as->J, LJ_TRERR_SPILLOV);
358 ir->s = (uint8_t)slot;
360 return sps_scale(slot);
363 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
364 static Reg ra_releasetmp(ASMState *as, IRRef ref)
366 IRIns *ir = IR(ref);
367 Reg r = ir->r;
368 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
369 ra_free(as, r);
370 ra_modified(as, r);
371 ir->r = RID_INIT;
372 return r;
375 /* Restore a register (marked as free). Rematerialize or force a spill. */
376 static Reg ra_restore(ASMState *as, IRRef ref)
378 if (emit_canremat(ref)) {
379 return ra_rematk(as, ref);
380 } else {
381 IRIns *ir = IR(ref);
382 int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
383 Reg r = ir->r;
384 lua_assert(ra_hasreg(r));
385 ra_sethint(ir->r, r); /* Keep hint. */
386 ra_free(as, r);
387 if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
388 ra_modified(as, r);
389 RA_DBGX((as, "restore $i $r", ir, r));
390 emit_spload(as, ir, r, ofs);
392 return r;
396 /* Save a register to a spill slot. */
397 static void ra_save(ASMState *as, IRIns *ir, Reg r)
399 RA_DBGX((as, "save $i $r", ir, r));
400 emit_spstore(as, ir, r, sps_scale(ir->s));
403 #define MINCOST(name) \
404 if (rset_test(RSET_ALL, RID_##name) && \
405 LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
406 cost = as->cost[RID_##name];
408 /* Evict the register with the lowest cost, forcing a restore. */
409 static Reg ra_evict(ASMState *as, RegSet allow)
411 IRRef ref;
412 RegCost cost = ~(RegCost)0;
413 lua_assert(allow != RSET_EMPTY);
414 if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
415 GPRDEF(MINCOST)
416 } else {
417 FPRDEF(MINCOST)
419 ref = regcost_ref(cost);
420 lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
421 /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
422 if (!irref_isk(ref) && (as->weakset & allow)) {
423 IRIns *ir = IR(ref);
424 if (!rset_test(as->weakset, ir->r))
425 ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
427 return ra_restore(as, ref);
430 /* Pick any register (marked as free). Evict on-demand. */
431 static Reg ra_pick(ASMState *as, RegSet allow)
433 RegSet pick = as->freeset & allow;
434 if (!pick)
435 return ra_evict(as, allow);
436 else
437 return rset_picktop(pick);
440 /* Get a scratch register (marked as free). */
441 static Reg ra_scratch(ASMState *as, RegSet allow)
443 Reg r = ra_pick(as, allow);
444 ra_modified(as, r);
445 RA_DBGX((as, "scratch $r", r));
446 return r;
449 /* Evict all registers from a set (if not free). */
450 static void ra_evictset(ASMState *as, RegSet drop)
452 as->modset |= drop;
453 drop &= ~as->freeset;
454 while (drop) {
455 Reg r = rset_pickbot(drop);
456 ra_restore(as, regcost_ref(as->cost[r]));
457 rset_clear(drop, r);
458 checkmclim(as);
462 /* Evict (rematerialize) all registers allocated to constants. */
463 static void ra_evictk(ASMState *as)
465 RegSet work;
466 #if !LJ_SOFTFP
467 work = ~as->freeset & RSET_FPR;
468 while (work) {
469 Reg r = rset_pickbot(work);
470 IRRef ref = regcost_ref(as->cost[r]);
471 if (emit_canremat(ref) && irref_isk(ref)) {
472 ra_rematk(as, ref);
473 checkmclim(as);
475 rset_clear(work, r);
477 #endif
478 work = ~as->freeset & RSET_GPR;
479 while (work) {
480 Reg r = rset_pickbot(work);
481 IRRef ref = regcost_ref(as->cost[r]);
482 if (emit_canremat(ref) && irref_isk(ref)) {
483 ra_rematk(as, ref);
484 checkmclim(as);
486 rset_clear(work, r);
490 #ifdef RID_NUM_KREF
491 /* Allocate a register for a constant. */
492 static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
494 /* First try to find a register which already holds the same constant. */
495 RegSet pick, work = ~as->freeset & RSET_GPR;
496 Reg r;
497 while (work) {
498 IRRef ref;
499 r = rset_pickbot(work);
500 ref = regcost_ref(as->cost[r]);
501 if (ref < ASMREF_L &&
502 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
503 return r;
504 rset_clear(work, r);
506 pick = as->freeset & allow;
507 if (pick) {
508 /* Constants should preferably get unmodified registers. */
509 if ((pick & ~as->modset))
510 pick &= ~as->modset;
511 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
512 } else {
513 r = ra_evict(as, allow);
515 RA_DBGX((as, "allock $x $r", k, r));
516 ra_setkref(as, r, k);
517 rset_clear(as->freeset, r);
518 ra_noweak(as, r);
519 return r;
522 /* Allocate a specific register for a constant. */
523 static void ra_allockreg(ASMState *as, int32_t k, Reg r)
525 Reg kr = ra_allock(as, k, RID2RSET(r));
526 if (kr != r) {
527 IRIns irdummy;
528 irdummy.t.irt = IRT_INT;
529 ra_scratch(as, RID2RSET(r));
530 emit_movrr(as, &irdummy, r, kr);
533 #else
534 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
535 #endif
537 /* Allocate a register for ref from the allowed set of registers.
538 ** Note: this function assumes the ref does NOT have a register yet!
539 ** Picks an optimal register, sets the cost and marks the register as non-free.
541 static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
543 IRIns *ir = IR(ref);
544 RegSet pick = as->freeset & allow;
545 Reg r;
546 lua_assert(ra_noreg(ir->r));
547 if (pick) {
548 /* First check register hint from propagation or PHI. */
549 if (ra_hashint(ir->r)) {
550 r = ra_gethint(ir->r);
551 if (rset_test(pick, r)) /* Use hint register if possible. */
552 goto found;
553 /* Rematerialization is cheaper than missing a hint. */
554 if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
555 ra_rematk(as, regcost_ref(as->cost[r]));
556 goto found;
558 RA_DBGX((as, "hintmiss $f $r", ref, r));
560 /* Invariants should preferably get unmodified registers. */
561 if (ref < as->loopref && !irt_isphi(ir->t)) {
562 if ((pick & ~as->modset))
563 pick &= ~as->modset;
564 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
565 } else {
566 /* We've got plenty of regs, so get callee-save regs if possible. */
567 if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
568 pick &= ~RSET_SCRATCH;
569 r = rset_picktop(pick);
571 } else {
572 r = ra_evict(as, allow);
574 found:
575 RA_DBGX((as, "alloc $f $r", ref, r));
576 ir->r = (uint8_t)r;
577 rset_clear(as->freeset, r);
578 ra_noweak(as, r);
579 as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
580 return r;
583 /* Allocate a register on-demand. */
584 static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
586 Reg r = IR(ref)->r;
587 /* Note: allow is ignored if the register is already allocated. */
588 if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
589 ra_noweak(as, r);
590 return r;
593 /* Rename register allocation and emit move. */
594 static void ra_rename(ASMState *as, Reg down, Reg up)
596 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
597 IRIns *ir = IR(ref);
598 ir->r = (uint8_t)up;
599 as->cost[down] = 0;
600 lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
601 lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
602 ra_free(as, down); /* 'down' is free ... */
603 ra_modified(as, down);
604 rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
605 ra_noweak(as, up);
606 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
607 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
608 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
609 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
610 ren = tref_ref(lj_ir_emit(as->J));
611 as->ir = as->T->ir; /* The IR may have been reallocated. */
612 IR(ren)->r = (uint8_t)down;
613 IR(ren)->s = SPS_NONE;
617 /* Pick a destination register (marked as free).
618 ** Caveat: allow is ignored if there's already a destination register.
619 ** Use ra_destreg() to get a specific register.
621 static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
623 Reg dest = ir->r;
624 if (ra_hasreg(dest)) {
625 ra_free(as, dest);
626 ra_modified(as, dest);
627 } else {
628 if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
629 dest = ra_gethint(dest);
630 ra_modified(as, dest);
631 RA_DBGX((as, "dest $r", dest));
632 } else {
633 dest = ra_scratch(as, allow);
635 ir->r = dest;
637 if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
638 return dest;
641 /* Force a specific destination register (marked as free). */
642 static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
644 Reg dest = ra_dest(as, ir, RID2RSET(r));
645 if (dest != r) {
646 ra_scratch(as, RID2RSET(r));
647 emit_movrr(as, ir, dest, r);
651 #if LJ_TARGET_X86ORX64
652 /* Propagate dest register to left reference. Emit moves as needed.
653 ** This is a required fixup step for all 2-operand machine instructions.
655 static void ra_left(ASMState *as, Reg dest, IRRef lref)
657 IRIns *ir = IR(lref);
658 Reg left = ir->r;
659 if (ra_noreg(left)) {
660 if (irref_isk(lref)) {
661 if (ir->o == IR_KNUM) {
662 cTValue *tv = ir_knum(ir);
663 /* FP remat needs a load except for +0. Still better than eviction. */
664 if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
665 emit_loadn(as, dest, tv);
666 return;
668 #if LJ_64
669 } else if (ir->o == IR_KINT64) {
670 emit_loadu64(as, dest, ir_kint64(ir)->u64);
671 return;
672 #endif
673 } else {
674 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
675 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
676 emit_loadi(as, dest, ir->i);
677 return;
680 if (!ra_hashint(left) && !iscrossref(as, lref))
681 ra_sethint(ir->r, dest); /* Propagate register hint. */
682 left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
684 ra_noweak(as, left);
685 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
686 if (dest != left) {
687 /* Use register renaming if dest is the PHI reg. */
688 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
689 ra_modified(as, left);
690 ra_rename(as, left, dest);
691 } else {
692 emit_movrr(as, ir, dest, left);
696 #else
697 /* Similar to ra_left, except we override any hints. */
698 static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
700 IRIns *ir = IR(lref);
701 Reg left = ir->r;
702 if (ra_noreg(left)) {
703 ra_sethint(ir->r, dest); /* Propagate register hint. */
704 left = ra_allocref(as, lref,
705 (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
707 ra_noweak(as, left);
708 if (dest != left) {
709 /* Use register renaming if dest is the PHI reg. */
710 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
711 ra_modified(as, left);
712 ra_rename(as, left, dest);
713 } else {
714 emit_movrr(as, ir, dest, left);
718 #endif
720 #if !LJ_TARGET_X86ORX64
721 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
722 static void ra_destpair(ASMState *as, IRIns *ir)
724 Reg destlo = ir->r, desthi = (ir+1)->r;
725 /* First spill unrelated refs blocking the destination registers. */
726 if (!rset_test(as->freeset, RID_RETLO) &&
727 destlo != RID_RETLO && desthi != RID_RETLO)
728 ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
729 if (!rset_test(as->freeset, RID_RETHI) &&
730 destlo != RID_RETHI && desthi != RID_RETHI)
731 ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
732 /* Next free the destination registers (if any). */
733 if (ra_hasreg(destlo)) {
734 ra_free(as, destlo);
735 ra_modified(as, destlo);
736 } else {
737 destlo = RID_RETLO;
739 if (ra_hasreg(desthi)) {
740 ra_free(as, desthi);
741 ra_modified(as, desthi);
742 } else {
743 desthi = RID_RETHI;
745 /* Check for conflicts and shuffle the registers as needed. */
746 if (destlo == RID_RETHI) {
747 if (desthi == RID_RETLO) {
748 emit_movrr(as, ir, RID_RETHI, RID_TMP);
749 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
750 emit_movrr(as, ir, RID_TMP, RID_RETLO);
751 } else {
752 emit_movrr(as, ir, RID_RETHI, RID_RETLO);
753 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
755 } else if (desthi == RID_RETLO) {
756 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
757 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
758 } else {
759 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
760 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
762 /* Restore spill slots (if any). */
763 if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
764 if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
766 #endif
768 /* -- Snapshot handling --------- ----------------------------------------- */
770 /* Can we rematerialize a KNUM instead of forcing a spill? */
771 static int asm_snap_canremat(ASMState *as)
773 Reg r;
774 for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
775 if (irref_isk(regcost_ref(as->cost[r])))
776 return 1;
777 return 0;
780 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
781 static void asm_snap_alloc1(ASMState *as, IRRef ref)
783 IRIns *ir = IR(ref);
784 if (!ra_used(ir)) {
785 RegSet allow = (!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR;
786 /* Get a weak register if we have a free one or can rematerialize. */
787 if ((as->freeset & allow) ||
788 (allow == RSET_FPR && asm_snap_canremat(as))) {
789 Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
790 if (!irt_isphi(ir->t))
791 ra_weak(as, r); /* But mark it as weakly referenced. */
792 checkmclim(as);
793 RA_DBGX((as, "snapreg $f $r", ref, ir->r));
794 } else {
795 ra_spill(as, ir); /* Otherwise force a spill slot. */
796 RA_DBGX((as, "snapspill $f $s", ref, ir->s));
801 /* Allocate refs escaping to a snapshot. */
802 static void asm_snap_alloc(ASMState *as)
804 SnapShot *snap = &as->T->snap[as->snapno];
805 SnapEntry *map = &as->T->snapmap[snap->mapofs];
806 MSize n, nent = snap->nent;
807 for (n = 0; n < nent; n++) {
808 SnapEntry sn = map[n];
809 IRRef ref = snap_ref(sn);
810 if (!irref_isk(ref)) {
811 asm_snap_alloc1(as, ref);
812 if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
813 lua_assert(irt_type(IR(ref+1)->t) == IRT_SOFTFP);
814 asm_snap_alloc1(as, ref+1);
820 /* All guards for a snapshot use the same exitno. This is currently the
821 ** same as the snapshot number. Since the exact origin of the exit cannot
822 ** be determined, all guards for the same snapshot must exit with the same
823 ** RegSP mapping.
824 ** A renamed ref which has been used in a prior guard for the same snapshot
825 ** would cause an inconsistency. The easy way out is to force a spill slot.
827 static int asm_snap_checkrename(ASMState *as, IRRef ren)
829 SnapShot *snap = &as->T->snap[as->snapno];
830 SnapEntry *map = &as->T->snapmap[snap->mapofs];
831 MSize n, nent = snap->nent;
832 for (n = 0; n < nent; n++) {
833 SnapEntry sn = map[n];
834 IRRef ref = snap_ref(sn);
835 if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
836 IRIns *ir = IR(ref);
837 ra_spill(as, ir); /* Register renamed, so force a spill slot. */
838 RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
839 return 1; /* Found. */
842 return 0; /* Not found. */
845 /* Prepare snapshot for next guard instruction. */
846 static void asm_snap_prep(ASMState *as)
848 if (as->curins < as->snapref) {
849 do {
850 lua_assert(as->snapno != 0);
851 as->snapno--;
852 as->snapref = as->T->snap[as->snapno].ref;
853 } while (as->curins < as->snapref);
854 asm_snap_alloc(as);
855 as->snaprename = as->T->nins;
856 } else {
857 /* Process any renames above the highwater mark. */
858 for (; as->snaprename < as->T->nins; as->snaprename++) {
859 IRIns *ir = IR(as->snaprename);
860 if (asm_snap_checkrename(as, ir->op1))
861 ir->op2 = REF_BIAS-1; /* Kill rename. */
866 /* -- Miscellaneous helpers ----------------------------------------------- */
868 /* Collect arguments from CALL* and CARG instructions. */
869 static void asm_collectargs(ASMState *as, IRIns *ir,
870 const CCallInfo *ci, IRRef *args)
872 uint32_t n = CCI_NARGS(ci);
873 lua_assert(n <= CCI_NARGS_MAX);
874 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
875 while (n-- > 1) {
876 ir = IR(ir->op1);
877 lua_assert(ir->o == IR_CARG);
878 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
880 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
881 lua_assert(IR(ir->op1)->o != IR_CARG);
884 /* Reconstruct CCallInfo flags for CALLX*. */
885 static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
887 uint32_t nargs = 0;
888 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
889 IRIns *ira = IR(ir->op1);
890 nargs++;
891 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
893 #if LJ_HASFFI
894 if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
895 CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
896 CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
897 nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
898 #if LJ_TARGET_X86
899 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
900 #endif
902 #endif
903 return (nargs | (ir->t.irt << CCI_OTSHIFT));
906 /* Calculate stack adjustment. */
907 static int32_t asm_stack_adjust(ASMState *as)
909 if (as->evenspill <= SPS_FIXED)
910 return 0;
911 return sps_scale(sps_align(as->evenspill));
914 /* Must match with hash*() in lj_tab.c. */
915 static uint32_t ir_khash(IRIns *ir)
917 uint32_t lo, hi;
918 if (irt_isstr(ir->t)) {
919 return ir_kstr(ir)->hash;
920 } else if (irt_isnum(ir->t)) {
921 lo = ir_knum(ir)->u32.lo;
922 hi = ir_knum(ir)->u32.hi << 1;
923 } else if (irt_ispri(ir->t)) {
924 lua_assert(!irt_isnil(ir->t));
925 return irt_type(ir->t)-IRT_FALSE;
926 } else {
927 lua_assert(irt_isgcv(ir->t));
928 lo = u32ptr(ir_kgc(ir));
929 hi = lo + HASH_BIAS;
931 return hashrot(lo, hi);
934 #if !LJ_TARGET_X86ORX64 && LJ_TARGET_OSX
935 void sys_icache_invalidate(void *start, size_t len);
936 #endif
938 #if LJ_TARGET_LINUX && LJ_TARGET_PPC
939 #include <dlfcn.h>
940 static void (*asm_ppc_cache_flush)(MCode *start, MCode *end);
941 static void asm_dummy_cache_flush(MCode *start, MCode *end)
943 UNUSED(start); UNUSED(end);
945 #endif
947 /* Flush instruction cache. */
948 static void asm_cache_flush(MCode *start, MCode *end)
950 VG_INVALIDATE(start, (char *)end-(char *)start);
951 #if LJ_TARGET_X86ORX64
952 UNUSED(start); UNUSED(end);
953 #elif LJ_TARGET_OSX
954 sys_icache_invalidate(start, end-start);
955 #elif LJ_TARGET_LINUX && LJ_TARGET_PPC
956 if (!asm_ppc_cache_flush) {
957 void *vdso = dlopen("linux-vdso32.so.1", RTLD_LAZY);
958 if (!vdso || !(asm_ppc_cache_flush = dlsym(vdso, "__kernel_sync_dicache")))
959 asm_ppc_cache_flush = asm_dummy_cache_flush;
961 asm_ppc_cache_flush(start, end);
962 #elif defined(__GNUC__) && !LJ_TARGET_PPC
963 __clear_cache(start, end);
964 #else
965 #error "Missing builtin to flush instruction cache"
966 #endif
969 /* -- Allocations --------------------------------------------------------- */
971 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
972 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
974 static void asm_snew(ASMState *as, IRIns *ir)
976 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
977 IRRef args[3];
978 args[0] = ASMREF_L; /* lua_State *L */
979 args[1] = ir->op1; /* const char *str */
980 args[2] = ir->op2; /* size_t len */
981 as->gcsteps++;
982 asm_setupresult(as, ir, ci); /* GCstr * */
983 asm_gencall(as, ci, args);
986 static void asm_tnew(ASMState *as, IRIns *ir)
988 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
989 IRRef args[2];
990 args[0] = ASMREF_L; /* lua_State *L */
991 args[1] = ASMREF_TMP1; /* uint32_t ahsize */
992 as->gcsteps++;
993 asm_setupresult(as, ir, ci); /* GCtab * */
994 asm_gencall(as, ci, args);
995 ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
998 static void asm_tdup(ASMState *as, IRIns *ir)
1000 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
1001 IRRef args[2];
1002 args[0] = ASMREF_L; /* lua_State *L */
1003 args[1] = ir->op1; /* const GCtab *kt */
1004 as->gcsteps++;
1005 asm_setupresult(as, ir, ci); /* GCtab * */
1006 asm_gencall(as, ci, args);
1009 /* -- PHI and loop handling ----------------------------------------------- */
1011 /* Break a PHI cycle by renaming to a free register (evict if needed). */
1012 static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
1013 RegSet allow)
1015 RegSet candidates = blocked & allow;
1016 if (candidates) { /* If this register file has candidates. */
1017 /* Note: the set for ra_pick cannot be empty, since each register file
1018 ** has some registers never allocated to PHIs.
1020 Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
1021 if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
1022 candidates = candidates & ~blockedby;
1023 down = rset_picktop(candidates); /* Pick candidate PHI register. */
1024 ra_rename(as, down, up); /* And rename it to the free register. */
1028 /* PHI register shuffling.
1030 ** The allocator tries hard to preserve PHI register assignments across
1031 ** the loop body. Most of the time this loop does nothing, since there
1032 ** are no register mismatches.
1034 ** If a register mismatch is detected and ...
1035 ** - the register is currently free: rename it.
1036 ** - the register is blocked by an invariant: restore/remat and rename it.
1037 ** - Otherwise the register is used by another PHI, so mark it as blocked.
1039 ** The renames are order-sensitive, so just retry the loop if a register
1040 ** is marked as blocked, but has been freed in the meantime. A cycle is
1041 ** detected if all of the blocked registers are allocated. To break the
1042 ** cycle rename one of them to a free register and retry.
1044 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1046 static void asm_phi_shuffle(ASMState *as)
1048 RegSet work;
1050 /* Find and resolve PHI register mismatches. */
1051 for (;;) {
1052 RegSet blocked = RSET_EMPTY;
1053 RegSet blockedby = RSET_EMPTY;
1054 RegSet phiset = as->phiset;
1055 while (phiset) { /* Check all left PHI operand registers. */
1056 Reg r = rset_pickbot(phiset);
1057 IRIns *irl = IR(as->phireg[r]);
1058 Reg left = irl->r;
1059 if (r != left) { /* Mismatch? */
1060 if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
1061 IRRef ref = regcost_ref(as->cost[r]);
1062 /* Blocked by other PHI (w/reg)? */
1063 if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
1064 rset_set(blocked, r);
1065 if (ra_hasreg(left))
1066 rset_set(blockedby, left);
1067 left = RID_NONE;
1068 } else { /* Otherwise grab register from invariant. */
1069 ra_restore(as, ref);
1070 checkmclim(as);
1073 if (ra_hasreg(left)) {
1074 ra_rename(as, left, r);
1075 checkmclim(as);
1078 rset_clear(phiset, r);
1080 if (!blocked) break; /* Finished. */
1081 if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
1082 asm_phi_break(as, blocked, blockedby, RSET_GPR);
1083 if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
1084 checkmclim(as);
1085 } /* Else retry some more renames. */
1088 /* Restore/remat invariants whose registers are modified inside the loop. */
1089 work = as->modset & ~(as->freeset | as->phiset);
1090 while (work) {
1091 Reg r = rset_pickbot(work);
1092 ra_restore(as, regcost_ref(as->cost[r]));
1093 rset_clear(work, r);
1094 checkmclim(as);
1097 /* Allocate and save all unsaved PHI regs and clear marks. */
1098 work = as->phiset;
1099 while (work) {
1100 Reg r = rset_picktop(work);
1101 IRRef lref = as->phireg[r];
1102 IRIns *ir = IR(lref);
1103 if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
1104 irt_clearmark(ir->t); /* Handled here, so clear marker now. */
1105 ra_alloc1(as, lref, RID2RSET(r));
1106 ra_save(as, ir, r); /* Save to spill slot inside the loop. */
1107 checkmclim(as);
1109 rset_clear(work, r);
1113 /* Emit renames for left PHIs which are only spilled outside the loop. */
1114 static void asm_phi_fixup(ASMState *as)
1116 RegSet work = as->phiset;
1117 while (work) {
1118 Reg r = rset_picktop(work);
1119 IRRef lref = as->phireg[r];
1120 IRIns *ir = IR(lref);
1121 /* Left PHI gained a spill slot before the loop? */
1122 if (irt_ismarked(ir->t) && ra_hasspill(ir->s)) {
1123 IRRef ren;
1124 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
1125 ren = tref_ref(lj_ir_emit(as->J));
1126 as->ir = as->T->ir; /* The IR may have been reallocated. */
1127 IR(ren)->r = (uint8_t)r;
1128 IR(ren)->s = SPS_NONE;
1130 irt_clearmark(ir->t); /* Always clear marker. */
1131 rset_clear(work, r);
1135 /* Setup right PHI reference. */
1136 static void asm_phi(ASMState *as, IRIns *ir)
1138 RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1139 ~as->phiset;
1140 RegSet afree = (as->freeset & allow);
1141 IRIns *irl = IR(ir->op1);
1142 IRIns *irr = IR(ir->op2);
1143 /* Spill slot shuffling is not implemented yet (but rarely needed). */
1144 if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
1145 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1146 /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1147 if ((afree & (afree-1))) { /* Two or more free registers? */
1148 Reg r;
1149 if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
1150 r = ra_allocref(as, ir->op2, allow);
1151 } else { /* Duplicate right PHI, need a copy (rare). */
1152 r = ra_scratch(as, allow);
1153 emit_movrr(as, irr, r, irr->r);
1155 ir->r = (uint8_t)r;
1156 rset_set(as->phiset, r);
1157 as->phireg[r] = (IRRef1)ir->op1;
1158 irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
1159 if (ra_noreg(irl->r))
1160 ra_sethint(irl->r, r); /* Set register hint for left PHI. */
1161 } else { /* Otherwise allocate a spill slot. */
1162 /* This is overly restrictive, but it triggers only on synthetic code. */
1163 if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
1164 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1165 ra_spill(as, ir);
1166 irl->s = irr->s = ir->s; /* Sync left/right PHI spill slots. */
1170 static void asm_gc_check(ASMState *as);
1171 static void asm_loop_fixup(ASMState *as);
1173 /* Middle part of a loop. */
1174 static void asm_loop(ASMState *as)
1176 /* LOOP is a guard, so the snapno is up to date. */
1177 as->loopsnapno = as->snapno;
1178 if (as->gcsteps)
1179 asm_gc_check(as);
1180 /* LOOP marks the transition from the variant to the invariant part. */
1181 as->flagmcp = as->invmcp = NULL;
1182 as->sectref = 0;
1183 if (!neverfuse(as)) as->fuseref = 0;
1184 asm_phi_shuffle(as);
1185 asm_loop_fixup(as);
1186 as->mcloop = as->mcp;
1187 RA_DBGX((as, "===== LOOP ====="));
1188 if (!as->realign) RA_DBG_FLUSH();
1191 /* -- Target-specific assembler ------------------------------------------- */
1193 #if LJ_TARGET_X86ORX64
1194 #include "lj_asm_x86.h"
1195 #elif LJ_TARGET_ARM
1196 #include "lj_asm_arm.h"
1197 #elif LJ_TARGET_PPC
1198 #include "lj_asm_ppc.h"
1199 #else
1200 #error "Missing assembler for target CPU"
1201 #endif
1203 /* -- Head of trace ------------------------------------------------------- */
1205 /* Head of a root trace. */
1206 static void asm_head_root(ASMState *as)
1208 int32_t spadj;
1209 asm_head_root_base(as);
1210 emit_setvmstate(as, (int32_t)as->T->traceno);
1211 spadj = asm_stack_adjust(as);
1212 as->T->spadjust = (uint16_t)spadj;
1213 emit_spsub(as, spadj);
1214 /* Root traces assume a checked stack for the starting proto. */
1215 as->T->topslot = gcref(as->T->startpt)->pt.framesize;
1218 /* Get RegSP for parent slot. */
1219 static LJ_AINLINE RegSP asm_head_parentrs(ASMState *as, IRIns *ir)
1221 #if LJ_SOFTFP
1222 if (ir->o == IR_HIOP) return as->parentmaphi[(ir-1)->op1];
1223 #endif
1224 return as->parentmap[ir->op1];
1227 /* Head of a side trace.
1229 ** The current simplistic algorithm requires that all slots inherited
1230 ** from the parent are live in a register between pass 2 and pass 3. This
1231 ** avoids the complexity of stack slot shuffling. But of course this may
1232 ** overflow the register set in some cases and cause the dreaded error:
1233 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1235 static void asm_head_side(ASMState *as)
1237 IRRef1 sloadins[RID_MAX];
1238 RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
1239 RegSet live = RSET_EMPTY; /* Live parent registers. */
1240 IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
1241 int32_t spadj, spdelta;
1242 int pass2 = 0;
1243 int pass3 = 0;
1244 IRRef i;
1246 allow = asm_head_side_base(as, irp, allow);
1248 /* Scan all parent SLOADs and collect register dependencies. */
1249 for (i = as->stopins; i > REF_BASE; i--) {
1250 IRIns *ir = IR(i);
1251 RegSP rs;
1252 lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
1253 (LJ_SOFTFP && ir->o == IR_HIOP));
1254 rs = asm_head_parentrs(as, ir);
1255 if (ra_hasreg(ir->r)) {
1256 rset_clear(allow, ir->r);
1257 if (ra_hasspill(ir->s))
1258 ra_save(as, ir, ir->r);
1259 } else if (ra_hasspill(ir->s)) {
1260 irt_setmark(ir->t);
1261 pass2 = 1;
1263 if (ir->r == rs) { /* Coalesce matching registers right now. */
1264 ra_free(as, ir->r);
1265 } else if (ra_hasspill(regsp_spill(rs))) {
1266 if (ra_hasreg(ir->r))
1267 pass3 = 1;
1268 } else if (ra_used(ir)) {
1269 sloadins[rs] = (IRRef1)i;
1270 rset_set(live, rs); /* Block live parent register. */
1274 /* Calculate stack frame adjustment. */
1275 spadj = asm_stack_adjust(as);
1276 spdelta = spadj - (int32_t)as->parent->spadjust;
1277 if (spdelta < 0) { /* Don't shrink the stack frame. */
1278 spadj = (int32_t)as->parent->spadjust;
1279 spdelta = 0;
1281 as->T->spadjust = (uint16_t)spadj;
1283 /* Reload spilled target registers. */
1284 if (pass2) {
1285 for (i = as->stopins; i > REF_BASE; i--) {
1286 IRIns *ir = IR(i);
1287 if (irt_ismarked(ir->t)) {
1288 RegSet mask;
1289 Reg r;
1290 RegSP rs;
1291 irt_clearmark(ir->t);
1292 rs = asm_head_parentrs(as, ir);
1293 if (!ra_hasspill(regsp_spill(rs)))
1294 ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
1295 else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1296 continue; /* Same spill slot, do nothing. */
1297 mask = ((!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1298 if (mask == RSET_EMPTY)
1299 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1300 r = ra_allocref(as, i, mask);
1301 ra_save(as, ir, r);
1302 rset_clear(allow, r);
1303 if (r == rs) { /* Coalesce matching registers right now. */
1304 ra_free(as, r);
1305 rset_clear(live, r);
1306 } else if (ra_hasspill(regsp_spill(rs))) {
1307 pass3 = 1;
1309 checkmclim(as);
1314 /* Store trace number and adjust stack frame relative to the parent. */
1315 emit_setvmstate(as, (int32_t)as->T->traceno);
1316 emit_spsub(as, spdelta);
1318 #if !LJ_TARGET_X86ORX64
1319 /* Restore BASE register from parent spill slot. */
1320 if (ra_hasspill(irp->s))
1321 emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1322 #endif
1324 /* Restore target registers from parent spill slots. */
1325 if (pass3) {
1326 RegSet work = ~as->freeset & RSET_ALL;
1327 while (work) {
1328 Reg r = rset_pickbot(work);
1329 IRIns *ir = IR(regcost_ref(as->cost[r]));
1330 RegSP rs = asm_head_parentrs(as, ir);
1331 rset_clear(work, r);
1332 if (ra_hasspill(regsp_spill(rs))) {
1333 int32_t ofs = sps_scale(regsp_spill(rs));
1334 ra_free(as, r);
1335 emit_spload(as, ir, r, ofs);
1336 checkmclim(as);
1341 /* Shuffle registers to match up target regs with parent regs. */
1342 for (;;) {
1343 RegSet work;
1345 /* Repeatedly coalesce free live registers by moving to their target. */
1346 while ((work = as->freeset & live) != RSET_EMPTY) {
1347 Reg rp = rset_pickbot(work);
1348 IRIns *ir = IR(sloadins[rp]);
1349 rset_clear(live, rp);
1350 rset_clear(allow, rp);
1351 ra_free(as, ir->r);
1352 emit_movrr(as, ir, ir->r, rp);
1353 checkmclim(as);
1356 /* We're done if no live registers remain. */
1357 if (live == RSET_EMPTY)
1358 break;
1360 /* Break cycles by renaming one target to a temp. register. */
1361 if (live & RSET_GPR) {
1362 RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1363 if (tmpset == RSET_EMPTY)
1364 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1365 ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1367 if (!LJ_SOFTFP && (live & RSET_FPR)) {
1368 RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1369 if (tmpset == RSET_EMPTY)
1370 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1371 ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1373 checkmclim(as);
1374 /* Continue with coalescing to fix up the broken cycle(s). */
1377 /* Inherit top stack slot already checked by parent trace. */
1378 as->T->topslot = as->parent->topslot;
1379 if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
1380 #ifdef EXITSTATE_CHECKEXIT
1381 /* Highest exit + 1 indicates stack check. */
1382 ExitNo exitno = as->T->nsnap;
1383 #else
1384 /* Reuse the parent exit in the context of the parent trace. */
1385 ExitNo exitno = as->J->exitno;
1386 #endif
1387 as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
1388 asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1392 /* -- Tail of trace ------------------------------------------------------- */
1394 /* Get base slot for a snapshot. */
1395 static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1397 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1398 MSize n;
1399 for (n = snap->nent; n > 0; n--) {
1400 SnapEntry sn = map[n-1];
1401 if ((sn & SNAP_FRAME)) {
1402 *gotframe = 1;
1403 return snap_slot(sn);
1406 return 0;
1409 /* Link to another trace. */
1410 static void asm_tail_link(ASMState *as)
1412 SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
1413 SnapShot *snap = &as->T->snap[snapno];
1414 int gotframe = 0;
1415 BCReg baseslot = asm_baseslot(as, snap, &gotframe);
1417 as->topslot = snap->topslot;
1418 checkmclim(as);
1419 ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1421 if (as->T->link == 0) {
1422 /* Setup fixed registers for exit to interpreter. */
1423 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
1424 int32_t mres;
1425 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1426 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1427 if (bc_isret(bc_op(*retpc)))
1428 pc = retpc;
1430 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1431 ra_allockreg(as, i32ptr(pc), RID_LPC);
1432 mres = (int32_t)(snap->nslots - baseslot);
1433 switch (bc_op(*pc)) {
1434 case BC_CALLM: case BC_CALLMT:
1435 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
1436 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1437 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1438 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1440 ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
1441 } else if (baseslot) {
1442 /* Save modified BASE for linking to trace with higher start frame. */
1443 emit_setgl(as, RID_BASE, jit_base);
1445 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1447 /* Sync the interpreter state with the on-trace state. */
1448 asm_stack_restore(as, snap);
1450 /* Root traces that add frames need to check the stack at the end. */
1451 if (!as->parent && gotframe)
1452 asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1455 /* -- Trace setup --------------------------------------------------------- */
1457 /* Clear reg/sp for all instructions and add register hints. */
1458 static void asm_setup_regsp(ASMState *as)
1460 GCtrace *T = as->T;
1461 IRRef i, nins;
1462 int inloop;
1463 #if LJ_TARGET_ARM
1464 uint32_t rload = 0xa6402a64;
1465 #endif
1467 ra_setup(as);
1469 /* Clear reg/sp for constants. */
1470 for (i = T->nk; i < REF_BIAS; i++)
1471 IR(i)->prev = REGSP_INIT;
1473 /* REF_BASE is used for implicit references to the BASE register. */
1474 IR(REF_BASE)->prev = REGSP_HINT(RID_BASE);
1476 nins = T->nins;
1477 if (IR(nins-1)->o == IR_RENAME) {
1478 do { nins--; } while (IR(nins-1)->o == IR_RENAME);
1479 T->nins = nins; /* Remove any renames left over from ASM restart. */
1481 as->snaprename = nins;
1482 as->snapref = nins;
1483 as->snapno = T->nsnap;
1485 as->stopins = REF_BASE;
1486 as->orignins = nins;
1487 as->curins = nins;
1489 inloop = 0;
1490 as->evenspill = SPS_FIRST;
1491 for (i = REF_FIRST; i < nins; i++) {
1492 IRIns *ir = IR(i);
1493 switch (ir->o) {
1494 case IR_LOOP:
1495 inloop = 1;
1496 break;
1497 /* Set hints for slot loads from a parent trace. */
1498 case IR_SLOAD:
1499 if ((ir->op2 & IRSLOAD_PARENT)) {
1500 RegSP rs = as->parentmap[ir->op1];
1501 lua_assert(regsp_used(rs));
1502 as->stopins = i;
1503 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1504 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1505 continue;
1508 #if LJ_TARGET_ARM
1509 if ((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP) {
1510 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1511 rload = lj_ror(rload, 4);
1512 continue;
1514 #endif
1515 break;
1516 #if LJ_TARGET_ARM
1517 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1518 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1519 rload = lj_ror(rload, 4);
1520 continue;
1521 #endif
1522 case IR_CALLXS: {
1523 CCallInfo ci;
1524 ci.flags = asm_callx_flags(as, ir);
1525 ir->prev = asm_setup_call_slots(as, ir, &ci);
1526 if (inloop)
1527 as->modset |= RSET_SCRATCH;
1528 continue;
1530 case IR_CALLN: case IR_CALLL: case IR_CALLS: {
1531 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1532 ir->prev = asm_setup_call_slots(as, ir, ci);
1533 if (inloop)
1534 as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
1535 (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
1536 continue;
1538 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1539 case IR_HIOP:
1540 switch ((ir-1)->o) {
1541 #if LJ_SOFTFP
1542 case IR_SLOAD:
1543 if (((ir-1)->op2 & IRSLOAD_PARENT)) {
1544 RegSP rs = as->parentmaphi[(ir-1)->op1];
1545 lua_assert(regsp_used(rs));
1546 as->stopins = i;
1547 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1548 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1549 continue;
1552 #if LJ_TARGET_ARM
1553 /* fallthrough */
1554 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1555 if (ra_hashint((ir-1)->r)) {
1556 ir->prev = (ir-1)->prev + 1;
1557 continue;
1559 #endif
1560 break;
1561 #endif
1562 #if LJ_NEED_FP64
1563 case IR_CONV:
1564 if (irt_isfp((ir-1)->t)) {
1565 ir->prev = REGSP_HINT(RID_FPRET);
1566 continue;
1568 /* fallthrough */
1569 #endif
1570 case IR_CALLN: case IR_CALLXS:
1571 #if LJ_SOFTFP
1572 case IR_MIN: case IR_MAX:
1573 #endif
1574 #if LJ_BE
1575 (ir-1)->prev = REGSP_HINT(RID_RETLO);
1576 #endif
1577 ir->prev = REGSP_HINT(RID_RETHI);
1578 continue;
1579 default:
1580 break;
1582 break;
1583 #endif
1584 #if LJ_SOFTFP
1585 case IR_MIN: case IR_MAX:
1586 if ((ir+1)->o != IR_HIOP) break;
1587 /* fallthrough */
1588 #endif
1589 /* C calls evict all scratch regs and return results in RID_RET. */
1590 case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
1591 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1592 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1593 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
1594 ir->prev = REGSP_HINT(RID_RET);
1595 if (inloop)
1596 as->modset = RSET_SCRATCH;
1597 continue;
1598 case IR_STRTO: case IR_OBAR:
1599 if (inloop)
1600 as->modset = RSET_SCRATCH;
1601 break;
1602 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1603 case IR_ATAN2: case IR_LDEXP:
1604 #endif
1605 case IR_POW:
1606 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1607 #if LJ_TARGET_X86ORX64
1608 ir->prev = REGSP_HINT(RID_XMM0);
1609 if (inloop)
1610 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1611 #else
1612 ir->prev = REGSP_HINT(RID_FPRET);
1613 if (inloop)
1614 as->modset |= RSET_SCRATCH;
1615 #endif
1616 continue;
1618 /* fallthrough for integer POW */
1619 case IR_DIV: case IR_MOD:
1620 if (!irt_isnum(ir->t)) {
1621 ir->prev = REGSP_HINT(RID_RET);
1622 if (inloop)
1623 as->modset |= (RSET_SCRATCH & RSET_GPR);
1624 continue;
1626 break;
1627 case IR_FPMATH:
1628 #if LJ_TARGET_X86ORX64
1629 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
1630 ir->prev = REGSP_HINT(RID_XMM0);
1631 #if !LJ_64
1632 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
1633 as->evenspill = 4;
1634 #endif
1635 if (inloop)
1636 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1637 continue;
1638 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1639 ir->prev = REGSP_HINT(RID_XMM0);
1640 if (inloop)
1641 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1642 continue;
1644 break;
1645 #else
1646 ir->prev = REGSP_HINT(RID_FPRET);
1647 if (inloop)
1648 as->modset |= RSET_SCRATCH;
1649 continue;
1650 #endif
1651 #if LJ_TARGET_X86ORX64
1652 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1653 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
1654 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1655 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1656 if (inloop)
1657 rset_set(as->modset, RID_ECX);
1659 break;
1660 #endif
1661 /* Do not propagate hints across type conversions. */
1662 case IR_TOBIT:
1663 break;
1664 case IR_CONV:
1665 if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
1666 (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
1667 break;
1668 /* fallthrough */
1669 default:
1670 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1671 if (irref_isk(ir->op2) && !irref_isk(ir->op1)) {
1672 ir->prev = IR(ir->op1)->prev;
1673 continue;
1675 break;
1677 ir->prev = REGSP_INIT;
1679 if ((as->evenspill & 1))
1680 as->oddspill = as->evenspill++;
1681 else
1682 as->oddspill = 0;
1685 /* -- Assembler core ------------------------------------------------------ */
1687 /* Assemble a trace. */
1688 void lj_asm_trace(jit_State *J, GCtrace *T)
1690 ASMState as_;
1691 ASMState *as = &as_;
1692 MCode *origtop;
1694 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1695 J->cur.nins = lj_ir_nextins(J);
1696 J->cur.ir[J->cur.nins].o = IR_NOP;
1698 /* Setup initial state. Copy some fields to reduce indirections. */
1699 as->J = J;
1700 as->T = T;
1701 as->ir = T->ir;
1702 as->flags = J->flags;
1703 as->loopref = J->loopref;
1704 as->realign = NULL;
1705 as->loopinv = 0;
1706 if (J->parent) {
1707 as->parent = traceref(J, J->parent);
1708 lj_snap_regspmap(as->parentmap, as->parent, J->exitno, 0);
1709 #if LJ_SOFTFP
1710 lj_snap_regspmap(as->parentmaphi, as->parent, J->exitno, 1);
1711 #endif
1712 } else {
1713 as->parent = NULL;
1715 /* Reserve MCode memory. */
1716 as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
1717 as->mcp = as->mctop;
1718 as->mclim = as->mcbot + MCLIM_REDZONE;
1719 asm_setup_target(as);
1721 do {
1722 as->mcp = as->mctop;
1723 as->curins = T->nins;
1724 RA_DBG_START();
1725 RA_DBGX((as, "===== STOP ====="));
1727 /* General trace setup. Emit tail of trace. */
1728 asm_tail_prep(as);
1729 as->mcloop = NULL;
1730 as->flagmcp = NULL;
1731 as->topslot = 0;
1732 as->gcsteps = 0;
1733 as->sectref = as->loopref;
1734 as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
1735 asm_setup_regsp(as);
1736 if (!as->loopref)
1737 asm_tail_link(as);
1739 /* Assemble a trace in linear backwards order. */
1740 for (as->curins--; as->curins > as->stopins; as->curins--) {
1741 IRIns *ir = IR(as->curins);
1742 lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
1743 if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
1744 continue; /* Dead-code elimination can be soooo easy. */
1745 if (irt_isguard(ir->t))
1746 asm_snap_prep(as);
1747 RA_DBG_REF();
1748 checkmclim(as);
1749 asm_ir(as, ir);
1751 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1753 /* Emit head of trace. */
1754 RA_DBG_REF();
1755 checkmclim(as);
1756 if (as->gcsteps) {
1757 as->curins = as->T->snap[0].ref;
1758 asm_snap_prep(as); /* The GC check is a guard. */
1759 asm_gc_check(as);
1761 ra_evictk(as);
1762 if (as->parent)
1763 asm_head_side(as);
1764 else
1765 asm_head_root(as);
1766 asm_phi_fixup(as);
1768 RA_DBGX((as, "===== START ===="));
1769 RA_DBG_FLUSH();
1770 if (as->freeset != RSET_ALL)
1771 lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
1773 /* Set trace entry point before fixing up tail to allow link to self. */
1774 T->mcode = as->mcp;
1775 T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
1776 if (!as->loopref)
1777 asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
1778 T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
1779 asm_cache_flush(T->mcode, origtop);
1782 #undef IR
1784 #endif