PPC: Generalize rematerialization handling.
[luajit-2.0.git] / src / lj_asm.c
blob7ee9fd2f21634b78382ff4c35c4baec05c5422f7
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 #else
165 #error "Missing instruction emitter for target CPU"
166 #endif
168 /* -- Register allocator debugging ---------------------------------------- */
170 /* #define LUAJIT_DEBUG_RA */
172 #ifdef LUAJIT_DEBUG_RA
174 #include <stdio.h>
175 #include <stdarg.h>
177 #define RIDNAME(name) #name,
178 static const char *const ra_regname[] = {
179 GPRDEF(RIDNAME)
180 FPRDEF(RIDNAME)
181 VRIDDEF(RIDNAME)
182 NULL
184 #undef RIDNAME
186 static char ra_dbg_buf[65536];
187 static char *ra_dbg_p;
188 static char *ra_dbg_merge;
189 static MCode *ra_dbg_mcp;
191 static void ra_dstart(void)
193 ra_dbg_p = ra_dbg_buf;
194 ra_dbg_merge = NULL;
195 ra_dbg_mcp = NULL;
198 static void ra_dflush(void)
200 fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
201 ra_dstart();
204 static void ra_dprintf(ASMState *as, const char *fmt, ...)
206 char *p;
207 va_list argp;
208 va_start(argp, fmt);
209 p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
210 ra_dbg_mcp = NULL;
211 p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
212 for (;;) {
213 const char *e = strchr(fmt, '$');
214 if (e == NULL) break;
215 memcpy(p, fmt, (size_t)(e-fmt));
216 p += e-fmt;
217 if (e[1] == 'r') {
218 Reg r = va_arg(argp, Reg) & RID_MASK;
219 if (r <= RID_MAX) {
220 const char *q;
221 for (q = ra_regname[r]; *q; q++)
222 *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
223 } else {
224 *p++ = '?';
225 lua_assert(0);
227 } else if (e[1] == 'f' || e[1] == 'i') {
228 IRRef ref;
229 if (e[1] == 'f')
230 ref = va_arg(argp, IRRef);
231 else
232 ref = va_arg(argp, IRIns *) - as->ir;
233 if (ref >= REF_BIAS)
234 p += sprintf(p, "%04d", ref - REF_BIAS);
235 else
236 p += sprintf(p, "K%03d", REF_BIAS - ref);
237 } else if (e[1] == 's') {
238 uint32_t slot = va_arg(argp, uint32_t);
239 p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
240 } else if (e[1] == 'x') {
241 p += sprintf(p, "%08x", va_arg(argp, int32_t));
242 } else {
243 lua_assert(0);
245 fmt = e+2;
247 va_end(argp);
248 while (*fmt)
249 *p++ = *fmt++;
250 *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
251 if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
252 fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
253 p = ra_dbg_buf;
255 ra_dbg_p = p;
258 #define RA_DBG_START() ra_dstart()
259 #define RA_DBG_FLUSH() ra_dflush()
260 #define RA_DBG_REF() \
261 do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
262 ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
263 #define RA_DBGX(x) ra_dprintf x
265 #else
266 #define RA_DBG_START() ((void)0)
267 #define RA_DBG_FLUSH() ((void)0)
268 #define RA_DBG_REF() ((void)0)
269 #define RA_DBGX(x) ((void)0)
270 #endif
272 /* -- Register allocator -------------------------------------------------- */
274 #define ra_free(as, r) rset_set(as->freeset, (r))
275 #define ra_modified(as, r) rset_set(as->modset, (r))
276 #define ra_weak(as, r) rset_set(as->weakset, (r))
277 #define ra_noweak(as, r) rset_clear(as->weakset, (r))
279 #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
281 /* Setup register allocator. */
282 static void ra_setup(ASMState *as)
284 Reg r;
285 /* Initially all regs (except the stack pointer) are free for use. */
286 as->freeset = RSET_INIT;
287 as->modset = RSET_EMPTY;
288 as->weakset = RSET_EMPTY;
289 as->phiset = RSET_EMPTY;
290 memset(as->phireg, 0, sizeof(as->phireg));
291 for (r = RID_MIN_GPR; r < RID_MAX; r++)
292 as->cost[r] = REGCOST(~0u, 0u);
295 /* Rematerialize constants. */
296 static Reg ra_rematk(ASMState *as, IRRef ref)
298 IRIns *ir;
299 Reg r;
300 if (ra_iskref(ref)) {
301 r = ra_krefreg(ref);
302 lua_assert(!rset_test(as->freeset, r));
303 ra_free(as, r);
304 ra_modified(as, r);
305 emit_loadi(as, r, ra_krefk(as, ref));
306 return r;
308 ir = IR(ref);
309 r = ir->r;
310 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
311 ra_free(as, r);
312 ra_modified(as, r);
313 ir->r = RID_INIT; /* Do not keep any hint. */
314 RA_DBGX((as, "remat $i $r", ir, r));
315 #if !LJ_SOFTFP
316 if (ir->o == IR_KNUM) {
317 emit_loadn(as, r, ir_knum(ir));
318 } else
319 #endif
320 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
321 ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
322 emit_getgl(as, r, jit_base);
323 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
324 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
325 emit_getgl(as, r, jit_L);
326 #if LJ_64
327 } else if (ir->o == IR_KINT64) {
328 emit_loadu64(as, r, ir_kint64(ir)->u64);
329 #endif
330 } else {
331 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
332 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
333 emit_loadi(as, r, ir->i);
335 return r;
338 /* Force a spill. Allocate a new spill slot if needed. */
339 static int32_t ra_spill(ASMState *as, IRIns *ir)
341 int32_t slot = ir->s;
342 if (!ra_hasspill(slot)) {
343 if (irt_is64(ir->t)) {
344 slot = as->evenspill;
345 as->evenspill += 2;
346 } else if (as->oddspill) {
347 slot = as->oddspill;
348 as->oddspill = 0;
349 } else {
350 slot = as->evenspill;
351 as->oddspill = slot+1;
352 as->evenspill += 2;
354 if (as->evenspill > 256)
355 lj_trace_err(as->J, LJ_TRERR_SPILLOV);
356 ir->s = (uint8_t)slot;
358 return sps_scale(slot);
361 /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
362 static Reg ra_releasetmp(ASMState *as, IRRef ref)
364 IRIns *ir = IR(ref);
365 Reg r = ir->r;
366 lua_assert(ra_hasreg(r) && !ra_hasspill(ir->s));
367 ra_free(as, r);
368 ra_modified(as, r);
369 ir->r = RID_INIT;
370 return r;
373 /* Restore a register (marked as free). Rematerialize or force a spill. */
374 static Reg ra_restore(ASMState *as, IRRef ref)
376 if (emit_canremat(ref)) {
377 return ra_rematk(as, ref);
378 } else {
379 IRIns *ir = IR(ref);
380 int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
381 Reg r = ir->r;
382 lua_assert(ra_hasreg(r));
383 ra_sethint(ir->r, r); /* Keep hint. */
384 ra_free(as, r);
385 if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
386 ra_modified(as, r);
387 RA_DBGX((as, "restore $i $r", ir, r));
388 emit_spload(as, ir, r, ofs);
390 return r;
394 /* Save a register to a spill slot. */
395 static void ra_save(ASMState *as, IRIns *ir, Reg r)
397 RA_DBGX((as, "save $i $r", ir, r));
398 emit_spstore(as, ir, r, sps_scale(ir->s));
401 #define MINCOST(name) \
402 if (rset_test(RSET_ALL, RID_##name) && \
403 LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
404 cost = as->cost[RID_##name];
406 /* Evict the register with the lowest cost, forcing a restore. */
407 static Reg ra_evict(ASMState *as, RegSet allow)
409 IRRef ref;
410 RegCost cost = ~(RegCost)0;
411 lua_assert(allow != RSET_EMPTY);
412 if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
413 GPRDEF(MINCOST)
414 } else {
415 FPRDEF(MINCOST)
417 ref = regcost_ref(cost);
418 lua_assert(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins));
419 /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
420 if (!irref_isk(ref) && (as->weakset & allow)) {
421 IRIns *ir = IR(ref);
422 if (!rset_test(as->weakset, ir->r))
423 ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
425 return ra_restore(as, ref);
428 /* Pick any register (marked as free). Evict on-demand. */
429 static Reg ra_pick(ASMState *as, RegSet allow)
431 RegSet pick = as->freeset & allow;
432 if (!pick)
433 return ra_evict(as, allow);
434 else
435 return rset_picktop(pick);
438 /* Get a scratch register (marked as free). */
439 static Reg ra_scratch(ASMState *as, RegSet allow)
441 Reg r = ra_pick(as, allow);
442 ra_modified(as, r);
443 RA_DBGX((as, "scratch $r", r));
444 return r;
447 /* Evict all registers from a set (if not free). */
448 static void ra_evictset(ASMState *as, RegSet drop)
450 as->modset |= drop;
451 drop &= ~as->freeset;
452 while (drop) {
453 Reg r = rset_pickbot(drop);
454 ra_restore(as, regcost_ref(as->cost[r]));
455 rset_clear(drop, r);
456 checkmclim(as);
460 /* Evict (rematerialize) all registers allocated to constants. */
461 static void ra_evictk(ASMState *as)
463 RegSet work;
464 #if !LJ_SOFTFP
465 work = ~as->freeset & RSET_FPR;
466 while (work) {
467 Reg r = rset_pickbot(work);
468 IRRef ref = regcost_ref(as->cost[r]);
469 if (emit_canremat(ref) && irref_isk(ref)) {
470 ra_rematk(as, ref);
471 checkmclim(as);
473 rset_clear(work, r);
475 #endif
476 work = ~as->freeset & RSET_GPR;
477 while (work) {
478 Reg r = rset_pickbot(work);
479 IRRef ref = regcost_ref(as->cost[r]);
480 if (emit_canremat(ref) && irref_isk(ref)) {
481 ra_rematk(as, ref);
482 checkmclim(as);
484 rset_clear(work, r);
488 #ifdef RID_NUM_KREF
489 /* Allocate a register for a constant. */
490 static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
492 /* First try to find a register which already holds the same constant. */
493 RegSet pick, work = ~as->freeset & RSET_GPR;
494 Reg r;
495 while (work) {
496 IRRef ref;
497 r = rset_pickbot(work);
498 ref = regcost_ref(as->cost[r]);
499 if (ref < ASMREF_L &&
500 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
501 return r;
502 rset_clear(work, r);
504 pick = as->freeset & allow;
505 if (pick) {
506 /* Constants should preferably get unmodified registers. */
507 if ((pick & ~as->modset))
508 pick &= ~as->modset;
509 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
510 } else {
511 r = ra_evict(as, allow);
513 RA_DBGX((as, "allock $x $r", k, r));
514 ra_setkref(as, r, k);
515 rset_clear(as->freeset, r);
516 ra_noweak(as, r);
517 return r;
520 /* Allocate a specific register for a constant. */
521 static void ra_allockreg(ASMState *as, int32_t k, Reg r)
523 Reg kr = ra_allock(as, k, RID2RSET(r));
524 if (kr != r) {
525 IRIns irdummy;
526 irdummy.t.irt = IRT_INT;
527 ra_scratch(as, RID2RSET(r));
528 emit_movrr(as, &irdummy, r, kr);
531 #else
532 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
533 #endif
535 /* Allocate a register for ref from the allowed set of registers.
536 ** Note: this function assumes the ref does NOT have a register yet!
537 ** Picks an optimal register, sets the cost and marks the register as non-free.
539 static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
541 IRIns *ir = IR(ref);
542 RegSet pick = as->freeset & allow;
543 Reg r;
544 lua_assert(ra_noreg(ir->r));
545 if (pick) {
546 /* First check register hint from propagation or PHI. */
547 if (ra_hashint(ir->r)) {
548 r = ra_gethint(ir->r);
549 if (rset_test(pick, r)) /* Use hint register if possible. */
550 goto found;
551 /* Rematerialization is cheaper than missing a hint. */
552 if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
553 ra_rematk(as, regcost_ref(as->cost[r]));
554 goto found;
556 RA_DBGX((as, "hintmiss $f $r", ref, r));
558 /* Invariants should preferably get unmodified registers. */
559 if (ref < as->loopref && !irt_isphi(ir->t)) {
560 if ((pick & ~as->modset))
561 pick &= ~as->modset;
562 r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
563 } else {
564 /* We've got plenty of regs, so get callee-save regs if possible. */
565 if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
566 pick &= ~RSET_SCRATCH;
567 r = rset_picktop(pick);
569 } else {
570 r = ra_evict(as, allow);
572 found:
573 RA_DBGX((as, "alloc $f $r", ref, r));
574 ir->r = (uint8_t)r;
575 rset_clear(as->freeset, r);
576 ra_noweak(as, r);
577 as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
578 return r;
581 /* Allocate a register on-demand. */
582 static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
584 Reg r = IR(ref)->r;
585 /* Note: allow is ignored if the register is already allocated. */
586 if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
587 ra_noweak(as, r);
588 return r;
591 /* Rename register allocation and emit move. */
592 static void ra_rename(ASMState *as, Reg down, Reg up)
594 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]);
595 IRIns *ir = IR(ref);
596 ir->r = (uint8_t)up;
597 as->cost[down] = 0;
598 lua_assert((down < RID_MAX_GPR) == (up < RID_MAX_GPR));
599 lua_assert(!rset_test(as->freeset, down) && rset_test(as->freeset, up));
600 ra_free(as, down); /* 'down' is free ... */
601 ra_modified(as, down);
602 rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
603 ra_noweak(as, up);
604 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
605 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
606 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
607 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno);
608 ren = tref_ref(lj_ir_emit(as->J));
609 as->ir = as->T->ir; /* The IR may have been reallocated. */
610 IR(ren)->r = (uint8_t)down;
611 IR(ren)->s = SPS_NONE;
615 /* Pick a destination register (marked as free).
616 ** Caveat: allow is ignored if there's already a destination register.
617 ** Use ra_destreg() to get a specific register.
619 static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
621 Reg dest = ir->r;
622 if (ra_hasreg(dest)) {
623 ra_free(as, dest);
624 ra_modified(as, dest);
625 } else {
626 if (ra_hashint(dest) && rset_test(as->freeset, ra_gethint(dest))) {
627 dest = ra_gethint(dest);
628 ra_modified(as, dest);
629 RA_DBGX((as, "dest $r", dest));
630 } else {
631 dest = ra_scratch(as, allow);
633 ir->r = dest;
635 if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
636 return dest;
639 /* Force a specific destination register (marked as free). */
640 static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
642 Reg dest = ra_dest(as, ir, RID2RSET(r));
643 if (dest != r) {
644 ra_scratch(as, RID2RSET(r));
645 emit_movrr(as, ir, dest, r);
649 #if LJ_TARGET_X86ORX64
650 /* Propagate dest register to left reference. Emit moves as needed.
651 ** This is a required fixup step for all 2-operand machine instructions.
653 static void ra_left(ASMState *as, Reg dest, IRRef lref)
655 IRIns *ir = IR(lref);
656 Reg left = ir->r;
657 if (ra_noreg(left)) {
658 if (irref_isk(lref)) {
659 if (ir->o == IR_KNUM) {
660 cTValue *tv = ir_knum(ir);
661 /* FP remat needs a load except for +0. Still better than eviction. */
662 if (tvispzero(tv) || !(as->freeset & RSET_FPR)) {
663 emit_loadn(as, dest, tv);
664 return;
666 #if LJ_64
667 } else if (ir->o == IR_KINT64) {
668 emit_loadu64(as, dest, ir_kint64(ir)->u64);
669 return;
670 #endif
671 } else {
672 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
673 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
674 emit_loadi(as, dest, ir->i);
675 return;
678 if (!ra_hashint(left) && !iscrossref(as, lref))
679 ra_sethint(ir->r, dest); /* Propagate register hint. */
680 left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
682 ra_noweak(as, left);
683 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
684 if (dest != left) {
685 /* Use register renaming if dest is the PHI reg. */
686 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
687 ra_modified(as, left);
688 ra_rename(as, left, dest);
689 } else {
690 emit_movrr(as, ir, dest, left);
694 #else
695 /* Similar to ra_left, except we override any hints. */
696 static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
698 IRIns *ir = IR(lref);
699 Reg left = ir->r;
700 if (ra_noreg(left)) {
701 ra_sethint(ir->r, dest); /* Propagate register hint. */
702 left = ra_allocref(as, lref,
703 (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
705 ra_noweak(as, left);
706 if (dest != left) {
707 /* Use register renaming if dest is the PHI reg. */
708 if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
709 ra_modified(as, left);
710 ra_rename(as, left, dest);
711 } else {
712 emit_movrr(as, ir, dest, left);
716 #endif
718 #if !LJ_TARGET_X86ORX64
719 /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
720 static void ra_destpair(ASMState *as, IRIns *ir)
722 Reg destlo = ir->r, desthi = (ir+1)->r;
723 /* First spill unrelated refs blocking the destination registers. */
724 if (!rset_test(as->freeset, RID_RETLO) &&
725 destlo != RID_RETLO && desthi != RID_RETLO)
726 ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
727 if (!rset_test(as->freeset, RID_RETHI) &&
728 destlo != RID_RETHI && desthi != RID_RETHI)
729 ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
730 /* Next free the destination registers (if any). */
731 if (ra_hasreg(destlo)) {
732 ra_free(as, destlo);
733 ra_modified(as, destlo);
734 } else {
735 destlo = RID_RETLO;
737 if (ra_hasreg(desthi)) {
738 ra_free(as, desthi);
739 ra_modified(as, desthi);
740 } else {
741 desthi = RID_RETHI;
743 /* Check for conflicts and shuffle the registers as needed. */
744 if (destlo == RID_RETHI) {
745 if (desthi == RID_RETLO) {
746 emit_movrr(as, ir, RID_RETHI, RID_TMP);
747 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
748 emit_movrr(as, ir, RID_TMP, RID_RETLO);
749 } else {
750 emit_movrr(as, ir, RID_RETHI, RID_RETLO);
751 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
753 } else if (desthi == RID_RETLO) {
754 emit_movrr(as, ir, RID_RETLO, RID_RETHI);
755 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
756 } else {
757 if (desthi != RID_RETHI) emit_movrr(as, ir, desthi, RID_RETHI);
758 if (destlo != RID_RETLO) emit_movrr(as, ir, destlo, RID_RETLO);
760 /* Restore spill slots (if any). */
761 if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
762 if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
764 #endif
766 /* -- Snapshot handling --------- ----------------------------------------- */
768 /* Can we rematerialize a KNUM instead of forcing a spill? */
769 static int asm_snap_canremat(ASMState *as)
771 Reg r;
772 for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
773 if (irref_isk(regcost_ref(as->cost[r])))
774 return 1;
775 return 0;
778 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
779 static void asm_snap_alloc1(ASMState *as, IRRef ref)
781 IRIns *ir = IR(ref);
782 if (!ra_used(ir)) {
783 RegSet allow = (!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR;
784 /* Get a weak register if we have a free one or can rematerialize. */
785 if ((as->freeset & allow) ||
786 (allow == RSET_FPR && asm_snap_canremat(as))) {
787 Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
788 if (!irt_isphi(ir->t))
789 ra_weak(as, r); /* But mark it as weakly referenced. */
790 checkmclim(as);
791 RA_DBGX((as, "snapreg $f $r", ref, ir->r));
792 } else {
793 ra_spill(as, ir); /* Otherwise force a spill slot. */
794 RA_DBGX((as, "snapspill $f $s", ref, ir->s));
799 /* Allocate refs escaping to a snapshot. */
800 static void asm_snap_alloc(ASMState *as)
802 SnapShot *snap = &as->T->snap[as->snapno];
803 SnapEntry *map = &as->T->snapmap[snap->mapofs];
804 MSize n, nent = snap->nent;
805 for (n = 0; n < nent; n++) {
806 SnapEntry sn = map[n];
807 IRRef ref = snap_ref(sn);
808 if (!irref_isk(ref)) {
809 asm_snap_alloc1(as, ref);
810 if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM))
811 asm_snap_alloc1(as, ref+1);
816 /* All guards for a snapshot use the same exitno. This is currently the
817 ** same as the snapshot number. Since the exact origin of the exit cannot
818 ** be determined, all guards for the same snapshot must exit with the same
819 ** RegSP mapping.
820 ** A renamed ref which has been used in a prior guard for the same snapshot
821 ** would cause an inconsistency. The easy way out is to force a spill slot.
823 static int asm_snap_checkrename(ASMState *as, IRRef ren)
825 SnapShot *snap = &as->T->snap[as->snapno];
826 SnapEntry *map = &as->T->snapmap[snap->mapofs];
827 MSize n, nent = snap->nent;
828 for (n = 0; n < nent; n++) {
829 SnapEntry sn = map[n];
830 IRRef ref = snap_ref(sn);
831 if (ref == ren || (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM) && ++ref == ren)) {
832 IRIns *ir = IR(ref);
833 ra_spill(as, ir); /* Register renamed, so force a spill slot. */
834 RA_DBGX((as, "snaprensp $f $s", ref, ir->s));
835 return 1; /* Found. */
838 return 0; /* Not found. */
841 /* Prepare snapshot for next guard instruction. */
842 static void asm_snap_prep(ASMState *as)
844 if (as->curins < as->snapref) {
845 do {
846 lua_assert(as->snapno != 0);
847 as->snapno--;
848 as->snapref = as->T->snap[as->snapno].ref;
849 } while (as->curins < as->snapref);
850 asm_snap_alloc(as);
851 as->snaprename = as->T->nins;
852 } else {
853 /* Process any renames above the highwater mark. */
854 for (; as->snaprename < as->T->nins; as->snaprename++) {
855 IRIns *ir = IR(as->snaprename);
856 if (asm_snap_checkrename(as, ir->op1))
857 ir->op2 = REF_BIAS-1; /* Kill rename. */
862 /* -- Miscellaneous helpers ----------------------------------------------- */
864 /* Collect arguments from CALL* and CARG instructions. */
865 static void asm_collectargs(ASMState *as, IRIns *ir,
866 const CCallInfo *ci, IRRef *args)
868 uint32_t n = CCI_NARGS(ci);
869 lua_assert(n <= CCI_NARGS_MAX);
870 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
871 while (n-- > 1) {
872 ir = IR(ir->op1);
873 lua_assert(ir->o == IR_CARG);
874 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
876 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
877 lua_assert(IR(ir->op1)->o != IR_CARG);
880 /* Reconstruct CCallInfo flags for CALLX*. */
881 static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
883 uint32_t nargs = 0;
884 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
885 IRIns *ira = IR(ir->op1);
886 nargs++;
887 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
889 /* NYI: fastcall etc. */
890 return (nargs | (ir->t.irt << CCI_OTSHIFT));
893 /* Get extent of the stack for a snapshot. */
894 static BCReg asm_stack_extent(ASMState *as, SnapShot *snap, BCReg *ptopslot)
896 SnapEntry *map = &as->T->snapmap[snap->mapofs];
897 MSize n, nent = snap->nent;
898 BCReg baseslot = 0, topslot = 0;
899 /* Must check all frames to find topslot (outer can be larger than inner). */
900 for (n = 0; n < nent; n++) {
901 SnapEntry sn = map[n];
902 if ((sn & SNAP_FRAME)) {
903 IRIns *ir = IR(snap_ref(sn));
904 GCfunc *fn = ir_kfunc(ir);
905 if (isluafunc(fn)) {
906 BCReg s = snap_slot(sn);
907 BCReg fs = s + funcproto(fn)->framesize;
908 if (fs > topslot) topslot = fs;
909 baseslot = s;
913 *ptopslot = topslot;
914 return baseslot;
917 /* Calculate stack adjustment. */
918 static int32_t asm_stack_adjust(ASMState *as)
920 if (as->evenspill <= SPS_FIXED)
921 return 0;
922 return sps_scale(sps_align(as->evenspill));
925 /* Must match with hash*() in lj_tab.c. */
926 static uint32_t ir_khash(IRIns *ir)
928 uint32_t lo, hi;
929 if (irt_isstr(ir->t)) {
930 return ir_kstr(ir)->hash;
931 } else if (irt_isnum(ir->t)) {
932 lo = ir_knum(ir)->u32.lo;
933 hi = ir_knum(ir)->u32.hi << 1;
934 } else if (irt_ispri(ir->t)) {
935 lua_assert(!irt_isnil(ir->t));
936 return irt_type(ir->t)-IRT_FALSE;
937 } else {
938 lua_assert(irt_isgcv(ir->t));
939 lo = u32ptr(ir_kgc(ir));
940 hi = lo + HASH_BIAS;
942 return hashrot(lo, hi);
945 #if !LJ_TARGET_X86ORX64 && LJ_TARGET_OSX
946 void sys_icache_invalidate(void *start, size_t len);
947 #endif
949 #if LJ_TARGET_LINUX && LJ_TARGET_PPC
950 #include <dlfcn.h>
951 static void (*asm_ppc_cache_flush)(MCode *start, MCode *end);
952 static void asm_dummy_cache_flush(MCode *start, MCode *end)
954 UNUSED(start); UNUSED(end);
956 #endif
958 /* Flush instruction cache. */
959 static void asm_cache_flush(MCode *start, MCode *end)
961 VG_INVALIDATE(start, (char *)end-(char *)start);
962 #if LJ_TARGET_X86ORX64
963 UNUSED(start); UNUSED(end);
964 #elif LJ_TARGET_OSX
965 sys_icache_invalidate(start, end-start);
966 #elif LJ_TARGET_LINUX && LJ_TARGET_PPC
967 if (!asm_ppc_cache_flush) {
968 void *vdso = dlopen("linux-vdso32.so.1", RTLD_LAZY);
969 if (!vdso || !(asm_ppc_cache_flush = dlsym(vdso, "__kernel_sync_dicache")))
970 asm_ppc_cache_flush = asm_dummy_cache_flush;
972 asm_ppc_cache_flush(start, end);
973 #elif defined(__GNUC__) && !LJ_TARGET_PPC
974 __clear_cache(start, end);
975 #else
976 #error "Missing builtin to flush instruction cache"
977 #endif
980 /* -- Allocations --------------------------------------------------------- */
982 static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
983 static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
985 static void asm_snew(ASMState *as, IRIns *ir)
987 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
988 IRRef args[3];
989 args[0] = ASMREF_L; /* lua_State *L */
990 args[1] = ir->op1; /* const char *str */
991 args[2] = ir->op2; /* size_t len */
992 as->gcsteps++;
993 asm_setupresult(as, ir, ci); /* GCstr * */
994 asm_gencall(as, ci, args);
997 static void asm_tnew(ASMState *as, IRIns *ir)
999 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
1000 IRRef args[2];
1001 args[0] = ASMREF_L; /* lua_State *L */
1002 args[1] = ASMREF_TMP1; /* uint32_t ahsize */
1003 as->gcsteps++;
1004 asm_setupresult(as, ir, ci); /* GCtab * */
1005 asm_gencall(as, ci, args);
1006 ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
1009 static void asm_tdup(ASMState *as, IRIns *ir)
1011 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
1012 IRRef args[2];
1013 args[0] = ASMREF_L; /* lua_State *L */
1014 args[1] = ir->op1; /* const GCtab *kt */
1015 as->gcsteps++;
1016 asm_setupresult(as, ir, ci); /* GCtab * */
1017 asm_gencall(as, ci, args);
1020 /* -- PHI and loop handling ----------------------------------------------- */
1022 /* Break a PHI cycle by renaming to a free register (evict if needed). */
1023 static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
1024 RegSet allow)
1026 RegSet candidates = blocked & allow;
1027 if (candidates) { /* If this register file has candidates. */
1028 /* Note: the set for ra_pick cannot be empty, since each register file
1029 ** has some registers never allocated to PHIs.
1031 Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
1032 if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
1033 candidates = candidates & ~blockedby;
1034 down = rset_picktop(candidates); /* Pick candidate PHI register. */
1035 ra_rename(as, down, up); /* And rename it to the free register. */
1039 /* PHI register shuffling.
1041 ** The allocator tries hard to preserve PHI register assignments across
1042 ** the loop body. Most of the time this loop does nothing, since there
1043 ** are no register mismatches.
1045 ** If a register mismatch is detected and ...
1046 ** - the register is currently free: rename it.
1047 ** - the register is blocked by an invariant: restore/remat and rename it.
1048 ** - Otherwise the register is used by another PHI, so mark it as blocked.
1050 ** The renames are order-sensitive, so just retry the loop if a register
1051 ** is marked as blocked, but has been freed in the meantime. A cycle is
1052 ** detected if all of the blocked registers are allocated. To break the
1053 ** cycle rename one of them to a free register and retry.
1055 ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
1057 static void asm_phi_shuffle(ASMState *as)
1059 RegSet work;
1061 /* Find and resolve PHI register mismatches. */
1062 for (;;) {
1063 RegSet blocked = RSET_EMPTY;
1064 RegSet blockedby = RSET_EMPTY;
1065 RegSet phiset = as->phiset;
1066 while (phiset) { /* Check all left PHI operand registers. */
1067 Reg r = rset_pickbot(phiset);
1068 IRIns *irl = IR(as->phireg[r]);
1069 Reg left = irl->r;
1070 if (r != left) { /* Mismatch? */
1071 if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
1072 IRRef ref = regcost_ref(as->cost[r]);
1073 /* Blocked by other PHI (w/reg)? */
1074 if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
1075 rset_set(blocked, r);
1076 if (ra_hasreg(left))
1077 rset_set(blockedby, left);
1078 left = RID_NONE;
1079 } else { /* Otherwise grab register from invariant. */
1080 ra_restore(as, ref);
1081 checkmclim(as);
1084 if (ra_hasreg(left)) {
1085 ra_rename(as, left, r);
1086 checkmclim(as);
1089 rset_clear(phiset, r);
1091 if (!blocked) break; /* Finished. */
1092 if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
1093 asm_phi_break(as, blocked, blockedby, RSET_GPR);
1094 if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
1095 checkmclim(as);
1096 } /* Else retry some more renames. */
1099 /* Restore/remat invariants whose registers are modified inside the loop. */
1100 work = as->modset & ~(as->freeset | as->phiset);
1101 while (work) {
1102 Reg r = rset_pickbot(work);
1103 ra_restore(as, regcost_ref(as->cost[r]));
1104 rset_clear(work, r);
1105 checkmclim(as);
1108 /* Allocate and save all unsaved PHI regs and clear marks. */
1109 work = as->phiset;
1110 while (work) {
1111 Reg r = rset_picktop(work);
1112 IRRef lref = as->phireg[r];
1113 IRIns *ir = IR(lref);
1114 if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
1115 irt_clearmark(ir->t); /* Handled here, so clear marker now. */
1116 ra_alloc1(as, lref, RID2RSET(r));
1117 ra_save(as, ir, r); /* Save to spill slot inside the loop. */
1118 checkmclim(as);
1120 rset_clear(work, r);
1124 /* Emit renames for left PHIs which are only spilled outside the loop. */
1125 static void asm_phi_fixup(ASMState *as)
1127 RegSet work = as->phiset;
1128 while (work) {
1129 Reg r = rset_picktop(work);
1130 IRRef lref = as->phireg[r];
1131 IRIns *ir = IR(lref);
1132 /* Left PHI gained a spill slot before the loop? */
1133 if (irt_ismarked(ir->t) && ra_hasspill(ir->s)) {
1134 IRRef ren;
1135 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
1136 ren = tref_ref(lj_ir_emit(as->J));
1137 as->ir = as->T->ir; /* The IR may have been reallocated. */
1138 IR(ren)->r = (uint8_t)r;
1139 IR(ren)->s = SPS_NONE;
1141 irt_clearmark(ir->t); /* Always clear marker. */
1142 rset_clear(work, r);
1146 /* Setup right PHI reference. */
1147 static void asm_phi(ASMState *as, IRIns *ir)
1149 RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
1150 ~as->phiset;
1151 RegSet afree = (as->freeset & allow);
1152 IRIns *irl = IR(ir->op1);
1153 IRIns *irr = IR(ir->op2);
1154 /* Spill slot shuffling is not implemented yet (but rarely needed). */
1155 if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
1156 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1157 /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
1158 if ((afree & (afree-1))) { /* Two or more free registers? */
1159 Reg r;
1160 if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
1161 r = ra_allocref(as, ir->op2, allow);
1162 } else { /* Duplicate right PHI, need a copy (rare). */
1163 r = ra_scratch(as, allow);
1164 emit_movrr(as, irr, r, irr->r);
1166 ir->r = (uint8_t)r;
1167 rset_set(as->phiset, r);
1168 as->phireg[r] = (IRRef1)ir->op1;
1169 irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
1170 if (ra_noreg(irl->r))
1171 ra_sethint(irl->r, r); /* Set register hint for left PHI. */
1172 } else { /* Otherwise allocate a spill slot. */
1173 /* This is overly restrictive, but it triggers only on synthetic code. */
1174 if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
1175 lj_trace_err(as->J, LJ_TRERR_NYIPHI);
1176 ra_spill(as, ir);
1177 irl->s = irr->s = ir->s; /* Sync left/right PHI spill slots. */
1181 static void asm_gc_check(ASMState *as);
1182 static void asm_loop_fixup(ASMState *as);
1184 /* Middle part of a loop. */
1185 static void asm_loop(ASMState *as)
1187 /* LOOP is a guard, so the snapno is up to date. */
1188 as->loopsnapno = as->snapno;
1189 if (as->gcsteps)
1190 asm_gc_check(as);
1191 /* LOOP marks the transition from the variant to the invariant part. */
1192 as->flagmcp = as->invmcp = NULL;
1193 as->sectref = 0;
1194 if (!neverfuse(as)) as->fuseref = 0;
1195 asm_phi_shuffle(as);
1196 asm_loop_fixup(as);
1197 as->mcloop = as->mcp;
1198 RA_DBGX((as, "===== LOOP ====="));
1199 if (!as->realign) RA_DBG_FLUSH();
1202 /* -- Target-specific assembler ------------------------------------------- */
1204 #if LJ_TARGET_X86ORX64
1205 #include "lj_asm_x86.h"
1206 #elif LJ_TARGET_ARM
1207 #include "lj_asm_arm.h"
1208 #else
1209 #error "Missing instruction emitter for target CPU"
1210 #endif
1212 /* -- Head of trace ------------------------------------------------------- */
1214 /* Head of a root trace. */
1215 static void asm_head_root(ASMState *as)
1217 int32_t spadj;
1218 asm_head_root_base(as);
1219 emit_setvmstate(as, (int32_t)as->T->traceno);
1220 spadj = asm_stack_adjust(as);
1221 as->T->spadjust = (uint16_t)spadj;
1222 emit_spsub(as, spadj);
1223 /* Root traces assume a checked stack for the starting proto. */
1224 as->T->topslot = gcref(as->T->startpt)->pt.framesize;
1227 /* Get RegSP for parent slot. */
1228 static LJ_AINLINE RegSP asm_head_parentrs(ASMState *as, IRIns *ir)
1230 #if LJ_SOFTFP
1231 if (ir->o == IR_HIOP) return as->parentmaphi[(ir-1)->op1];
1232 #endif
1233 return as->parentmap[ir->op1];
1236 /* Head of a side trace.
1238 ** The current simplistic algorithm requires that all slots inherited
1239 ** from the parent are live in a register between pass 2 and pass 3. This
1240 ** avoids the complexity of stack slot shuffling. But of course this may
1241 ** overflow the register set in some cases and cause the dreaded error:
1242 ** "NYI: register coalescing too complex". A refined algorithm is needed.
1244 static void asm_head_side(ASMState *as)
1246 IRRef1 sloadins[RID_MAX];
1247 RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
1248 RegSet live = RSET_EMPTY; /* Live parent registers. */
1249 IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
1250 int32_t spadj, spdelta;
1251 int pass2 = 0;
1252 int pass3 = 0;
1253 IRRef i;
1255 allow = asm_head_side_base(as, irp, allow);
1257 /* Scan all parent SLOADs and collect register dependencies. */
1258 for (i = as->stopins; i > REF_BASE; i--) {
1259 IRIns *ir = IR(i);
1260 RegSP rs;
1261 lua_assert((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
1262 (LJ_SOFTFP && ir->o == IR_HIOP));
1263 rs = asm_head_parentrs(as, ir);
1264 if (ra_hasreg(ir->r)) {
1265 rset_clear(allow, ir->r);
1266 if (ra_hasspill(ir->s))
1267 ra_save(as, ir, ir->r);
1268 } else if (ra_hasspill(ir->s)) {
1269 irt_setmark(ir->t);
1270 pass2 = 1;
1272 if (ir->r == rs) { /* Coalesce matching registers right now. */
1273 ra_free(as, ir->r);
1274 } else if (ra_hasspill(regsp_spill(rs))) {
1275 if (ra_hasreg(ir->r))
1276 pass3 = 1;
1277 } else if (ra_used(ir)) {
1278 sloadins[rs] = (IRRef1)i;
1279 rset_set(live, rs); /* Block live parent register. */
1283 /* Calculate stack frame adjustment. */
1284 spadj = asm_stack_adjust(as);
1285 spdelta = spadj - (int32_t)as->parent->spadjust;
1286 if (spdelta < 0) { /* Don't shrink the stack frame. */
1287 spadj = (int32_t)as->parent->spadjust;
1288 spdelta = 0;
1290 as->T->spadjust = (uint16_t)spadj;
1292 /* Reload spilled target registers. */
1293 if (pass2) {
1294 for (i = as->stopins; i > REF_BASE; i--) {
1295 IRIns *ir = IR(i);
1296 if (irt_ismarked(ir->t)) {
1297 RegSet mask;
1298 Reg r;
1299 RegSP rs;
1300 irt_clearmark(ir->t);
1301 rs = asm_head_parentrs(as, ir);
1302 if (!ra_hasspill(regsp_spill(rs)))
1303 ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
1304 else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
1305 continue; /* Same spill slot, do nothing. */
1306 mask = ((!LJ_SOFTFP && irt_isnum(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
1307 if (mask == RSET_EMPTY)
1308 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1309 r = ra_allocref(as, i, mask);
1310 ra_save(as, ir, r);
1311 rset_clear(allow, r);
1312 if (r == rs) { /* Coalesce matching registers right now. */
1313 ra_free(as, r);
1314 rset_clear(live, r);
1315 } else if (ra_hasspill(regsp_spill(rs))) {
1316 pass3 = 1;
1318 checkmclim(as);
1323 /* Store trace number and adjust stack frame relative to the parent. */
1324 emit_setvmstate(as, (int32_t)as->T->traceno);
1325 emit_spsub(as, spdelta);
1327 #if !LJ_TARGET_X86ORX64
1328 /* Restore BASE register from parent spill slot. */
1329 if (ra_hasspill(irp->s))
1330 emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
1331 #endif
1333 /* Restore target registers from parent spill slots. */
1334 if (pass3) {
1335 RegSet work = ~as->freeset & RSET_ALL;
1336 while (work) {
1337 Reg r = rset_pickbot(work);
1338 IRIns *ir = IR(regcost_ref(as->cost[r]));
1339 RegSP rs = asm_head_parentrs(as, ir);
1340 rset_clear(work, r);
1341 if (ra_hasspill(regsp_spill(rs))) {
1342 int32_t ofs = sps_scale(regsp_spill(rs));
1343 ra_free(as, r);
1344 emit_spload(as, ir, r, ofs);
1345 checkmclim(as);
1350 /* Shuffle registers to match up target regs with parent regs. */
1351 for (;;) {
1352 RegSet work;
1354 /* Repeatedly coalesce free live registers by moving to their target. */
1355 while ((work = as->freeset & live) != RSET_EMPTY) {
1356 Reg rp = rset_pickbot(work);
1357 IRIns *ir = IR(sloadins[rp]);
1358 rset_clear(live, rp);
1359 rset_clear(allow, rp);
1360 ra_free(as, ir->r);
1361 emit_movrr(as, ir, ir->r, rp);
1362 checkmclim(as);
1365 /* We're done if no live registers remain. */
1366 if (live == RSET_EMPTY)
1367 break;
1369 /* Break cycles by renaming one target to a temp. register. */
1370 if (live & RSET_GPR) {
1371 RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
1372 if (tmpset == RSET_EMPTY)
1373 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1374 ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
1376 if (!LJ_SOFTFP && (live & RSET_FPR)) {
1377 RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
1378 if (tmpset == RSET_EMPTY)
1379 lj_trace_err(as->J, LJ_TRERR_NYICOAL);
1380 ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
1382 checkmclim(as);
1383 /* Continue with coalescing to fix up the broken cycle(s). */
1386 /* Inherit top stack slot already checked by parent trace. */
1387 as->T->topslot = as->parent->topslot;
1388 if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
1389 #ifdef EXITSTATE_CHECKEXIT
1390 /* Highest exit + 1 indicates stack check. */
1391 ExitNo exitno = as->T->nsnap;
1392 #else
1393 /* Reuse the parent exit in the context of the parent trace. */
1394 ExitNo exitno = as->J->exitno;
1395 #endif
1396 as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
1397 asm_stack_check(as, as->topslot, irp, allow & RSET_GPR, exitno);
1401 /* -- Tail of trace ------------------------------------------------------- */
1403 /* Link to another trace. */
1404 static void asm_tail_link(ASMState *as)
1406 SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
1407 SnapShot *snap = &as->T->snap[snapno];
1408 BCReg baseslot = asm_stack_extent(as, snap, &as->topslot);
1410 checkmclim(as);
1411 ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
1413 if (as->T->link == 0) {
1414 /* Setup fixed registers for exit to interpreter. */
1415 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]);
1416 int32_t mres;
1417 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1418 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1419 if (bc_isret(bc_op(*retpc)))
1420 pc = retpc;
1422 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1423 ra_allockreg(as, i32ptr(pc), RID_LPC);
1424 mres = (int32_t)(snap->nslots - baseslot);
1425 switch (bc_op(*pc)) {
1426 case BC_CALLM: case BC_CALLMT:
1427 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break;
1428 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1429 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1430 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
1432 ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
1433 } else if (baseslot) {
1434 /* Save modified BASE for linking to trace with higher start frame. */
1435 emit_setgl(as, RID_BASE, jit_base);
1437 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1439 /* Sync the interpreter state with the on-trace state. */
1440 asm_stack_restore(as, snap);
1442 /* Root traces that grow the stack need to check the stack at the end. */
1443 if (!as->parent && as->topslot)
1444 asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
1447 /* -- Trace setup --------------------------------------------------------- */
1449 /* Clear reg/sp for all instructions and add register hints. */
1450 static void asm_setup_regsp(ASMState *as)
1452 GCtrace *T = as->T;
1453 IRRef i, nins;
1454 int inloop;
1455 #if LJ_TARGET_ARM
1456 uint32_t rload = 0xa6402a64;
1457 #endif
1459 ra_setup(as);
1461 /* Clear reg/sp for constants. */
1462 for (i = T->nk; i < REF_BIAS; i++)
1463 IR(i)->prev = REGSP_INIT;
1465 /* REF_BASE is used for implicit references to the BASE register. */
1466 IR(REF_BASE)->prev = REGSP_HINT(RID_BASE);
1468 nins = T->nins;
1469 if (IR(nins-1)->o == IR_RENAME) {
1470 do { nins--; } while (IR(nins-1)->o == IR_RENAME);
1471 T->nins = nins; /* Remove any renames left over from ASM restart. */
1473 as->snaprename = nins;
1474 as->snapref = nins;
1475 as->snapno = T->nsnap;
1477 as->stopins = REF_BASE;
1478 as->orignins = nins;
1479 as->curins = nins;
1481 inloop = 0;
1482 as->evenspill = SPS_FIRST;
1483 for (i = REF_FIRST; i < nins; i++) {
1484 IRIns *ir = IR(i);
1485 switch (ir->o) {
1486 case IR_LOOP:
1487 inloop = 1;
1488 break;
1489 /* Set hints for slot loads from a parent trace. */
1490 case IR_SLOAD:
1491 if ((ir->op2 & IRSLOAD_PARENT)) {
1492 RegSP rs = as->parentmap[ir->op1];
1493 lua_assert(regsp_used(rs));
1494 as->stopins = i;
1495 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1496 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1497 continue;
1500 #if LJ_TARGET_ARM
1501 if ((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP) {
1502 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1503 rload = lj_ror(rload, 4);
1504 continue;
1506 #endif
1507 break;
1508 #if LJ_TARGET_ARM
1509 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1510 ir->prev = (uint16_t)REGSP_HINT((rload & 15));
1511 rload = lj_ror(rload, 4);
1512 continue;
1513 #endif
1514 case IR_CALLXS: {
1515 CCallInfo ci;
1516 ci.flags = asm_callx_flags(as, ir);
1517 ir->prev = asm_setup_call_slots(as, ir, &ci);
1518 if (inloop)
1519 as->modset |= RSET_SCRATCH;
1520 continue;
1522 case IR_CALLN: case IR_CALLL: case IR_CALLS: {
1523 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1524 ir->prev = asm_setup_call_slots(as, ir, ci);
1525 if (inloop)
1526 as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
1527 (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
1528 continue;
1530 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1531 case IR_HIOP:
1532 switch ((ir-1)->o) {
1533 #if LJ_SOFTFP
1534 case IR_SLOAD:
1535 if (((ir-1)->op2 & IRSLOAD_PARENT)) {
1536 RegSP rs = as->parentmaphi[(ir-1)->op1];
1537 lua_assert(regsp_used(rs));
1538 as->stopins = i;
1539 if (!ra_hasspill(regsp_spill(rs)) && ra_hasreg(regsp_reg(rs))) {
1540 ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
1541 continue;
1544 #if LJ_TARGET_ARM
1545 /* fallthrough */
1546 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1547 if (ra_hashint((ir-1)->r)) {
1548 ir->prev = (ir-1)->prev + 1;
1549 continue;
1551 #endif
1552 break;
1553 #endif
1554 #if LJ_NEED_FP64
1555 case IR_CONV:
1556 if (irt_isfp((ir-1)->t)) {
1557 ir->prev = REGSP_HINT(RID_FPRET);
1558 continue;
1560 /* fallthrough */
1561 #endif
1562 case IR_CALLN: case IR_CALLXS:
1563 #if LJ_SOFTFP
1564 case IR_MIN: case IR_MAX:
1565 #endif
1566 #if LJ_BE
1567 (ir-1)->prev = REGSP_HINT(RID_RETLO);
1568 #endif
1569 ir->prev = REGSP_HINT(RID_RETHI);
1570 continue;
1571 default:
1572 break;
1574 break;
1575 #endif
1576 #if LJ_SOFTFP
1577 case IR_MIN: case IR_MAX:
1578 if ((ir+1)->o != IR_HIOP) break;
1579 /* fallthrough */
1580 #endif
1581 /* C calls evict all scratch regs and return results in RID_RET. */
1582 case IR_SNEW: case IR_XSNEW: case IR_NEWREF:
1583 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1584 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1585 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR:
1586 ir->prev = REGSP_HINT(RID_RET);
1587 if (inloop)
1588 as->modset = RSET_SCRATCH;
1589 continue;
1590 case IR_STRTO: case IR_OBAR:
1591 if (inloop)
1592 as->modset = RSET_SCRATCH;
1593 break;
1594 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1595 case IR_ATAN2: case IR_LDEXP:
1596 #endif
1597 case IR_POW:
1598 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1599 #if LJ_TARGET_X86ORX64
1600 ir->prev = REGSP_HINT(RID_XMM0);
1601 if (inloop)
1602 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX);
1603 #else
1604 ir->prev = REGSP_HINT(RID_FPRET);
1605 if (inloop)
1606 as->modset |= RSET_SCRATCH;
1607 #endif
1608 continue;
1610 /* fallthrough for integer POW */
1611 case IR_DIV: case IR_MOD:
1612 if (!irt_isnum(ir->t)) {
1613 ir->prev = REGSP_HINT(RID_RET);
1614 if (inloop)
1615 as->modset |= (RSET_SCRATCH & RSET_GPR);
1616 continue;
1618 break;
1619 case IR_FPMATH:
1620 #if LJ_TARGET_X86ORX64
1621 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */
1622 ir->prev = REGSP_HINT(RID_XMM0);
1623 #if !LJ_64
1624 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */
1625 as->evenspill = 4;
1626 #endif
1627 if (inloop)
1628 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1629 continue;
1630 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1631 ir->prev = REGSP_HINT(RID_XMM0);
1632 if (inloop)
1633 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1634 continue;
1636 break;
1637 #else
1638 ir->prev = REGSP_HINT(RID_FPRET);
1639 if (inloop)
1640 as->modset |= RSET_SCRATCH;
1641 continue;
1642 #endif
1643 #if LJ_TARGET_X86ORX64
1644 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1645 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
1646 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1647 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1648 if (inloop)
1649 rset_set(as->modset, RID_ECX);
1651 break;
1652 #endif
1653 /* Do not propagate hints across type conversions. */
1654 case IR_TOBIT:
1655 break;
1656 case IR_CONV:
1657 if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
1658 (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
1659 break;
1660 /* fallthrough */
1661 default:
1662 /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
1663 if (irref_isk(ir->op2) && !irref_isk(ir->op1)) {
1664 ir->prev = IR(ir->op1)->prev;
1665 continue;
1667 break;
1669 ir->prev = REGSP_INIT;
1671 if ((as->evenspill & 1))
1672 as->oddspill = as->evenspill++;
1673 else
1674 as->oddspill = 0;
1677 /* -- Assembler core ------------------------------------------------------ */
1679 /* Assemble a trace. */
1680 void lj_asm_trace(jit_State *J, GCtrace *T)
1682 ASMState as_;
1683 ASMState *as = &as_;
1684 MCode *origtop;
1686 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1687 J->cur.nins = lj_ir_nextins(J);
1688 J->cur.ir[J->cur.nins].o = IR_NOP;
1690 /* Setup initial state. Copy some fields to reduce indirections. */
1691 as->J = J;
1692 as->T = T;
1693 as->ir = T->ir;
1694 as->flags = J->flags;
1695 as->loopref = J->loopref;
1696 as->realign = NULL;
1697 as->loopinv = 0;
1698 if (J->parent) {
1699 as->parent = traceref(J, J->parent);
1700 lj_snap_regspmap(as->parentmap, as->parent, J->exitno, 0);
1701 #if LJ_SOFTFP
1702 lj_snap_regspmap(as->parentmaphi, as->parent, J->exitno, 1);
1703 #endif
1704 } else {
1705 as->parent = NULL;
1707 /* Reserve MCode memory. */
1708 as->mctop = origtop = lj_mcode_reserve(J, &as->mcbot);
1709 as->mcp = as->mctop;
1710 as->mclim = as->mcbot + MCLIM_REDZONE;
1711 asm_setup_target(as);
1713 do {
1714 as->mcp = as->mctop;
1715 as->curins = T->nins;
1716 RA_DBG_START();
1717 RA_DBGX((as, "===== STOP ====="));
1719 /* General trace setup. Emit tail of trace. */
1720 asm_tail_prep(as);
1721 as->mcloop = NULL;
1722 as->flagmcp = NULL;
1723 as->topslot = 0;
1724 as->gcsteps = 0;
1725 as->sectref = as->loopref;
1726 as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
1727 asm_setup_regsp(as);
1728 if (!as->loopref)
1729 asm_tail_link(as);
1731 /* Assemble a trace in linear backwards order. */
1732 for (as->curins--; as->curins > as->stopins; as->curins--) {
1733 IRIns *ir = IR(as->curins);
1734 lua_assert(!(LJ_32 && irt_isint64(ir->t))); /* Handled by SPLIT. */
1735 if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
1736 continue; /* Dead-code elimination can be soooo easy. */
1737 if (irt_isguard(ir->t))
1738 asm_snap_prep(as);
1739 RA_DBG_REF();
1740 checkmclim(as);
1741 asm_ir(as, ir);
1743 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1745 /* Emit head of trace. */
1746 RA_DBG_REF();
1747 checkmclim(as);
1748 if (as->gcsteps) {
1749 as->curins = as->T->snap[0].ref;
1750 asm_snap_prep(as); /* The GC check is a guard. */
1751 asm_gc_check(as);
1753 ra_evictk(as);
1754 if (as->parent)
1755 asm_head_side(as);
1756 else
1757 asm_head_root(as);
1758 asm_phi_fixup(as);
1760 RA_DBGX((as, "===== START ===="));
1761 RA_DBG_FLUSH();
1762 if (as->freeset != RSET_ALL)
1763 lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
1765 /* Set trace entry point before fixing up tail to allow link to self. */
1766 T->mcode = as->mcp;
1767 T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
1768 if (!as->loopref)
1769 asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
1770 T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
1771 asm_cache_flush(T->mcode, origtop);
1774 #undef IR
1776 #endif