2 ** IR assembler (SSA IR -> machine code).
3 ** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h
22 #include "lj_ircall.h"
29 #include "lj_dispatch.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. */
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. */
87 int32_t krefk
[RID_NUM_KREF
];
89 IRRef1 phireg
[RID_MAX
]; /* PHI register references. */
90 uint16_t parentmap
[LJ_MAX_JSLOTS
]; /* Parent slot to RegSP map. */
92 uint16_t parentmaphi
[LJ_MAX_JSLOTS
]; /* Parent slot to hi RegSP map. */
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
));
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
);
133 as
->cost
[r
] = REGCOST(ref
, ref
);
137 #define ra_iskref(ref) 0
138 #define ra_krefreg(ref) RID_MIN_GPR
139 #define ra_krefk(as, ref) 0
142 /* Arch-specific field offsets. */
143 static const uint8_t field_ofs
[IRFL__MAX
+1] = {
144 #define FLOFS(name, ofs) (uint8_t)(ofs),
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)
155 #define VG_INVALIDATE(p, sz) ((void)0)
158 /* -- Target-specific instruction emitter --------------------------------- */
160 #if LJ_TARGET_X86ORX64
161 #include "lj_emit_x86.h"
163 #include "lj_emit_arm.h"
165 #error "Missing instruction emitter for target CPU"
168 /* -- Register allocator debugging ---------------------------------------- */
170 /* #define LUAJIT_DEBUG_RA */
172 #ifdef LUAJIT_DEBUG_RA
177 #define RIDNAME(name) #name,
178 static const char *const ra_regname
[] = {
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
;
198 static void ra_dflush(void)
200 fwrite(ra_dbg_buf
, 1, (size_t)(ra_dbg_p
-ra_dbg_buf
), stdout
);
204 static void ra_dprintf(ASMState
*as
, const char *fmt
, ...)
209 p
= ra_dbg_mcp
== as
->mcp
? ra_dbg_merge
: ra_dbg_p
;
211 p
+= sprintf(p
, "%08x \e[36m%04d ", (uintptr_t)as
->mcp
, as
->curins
-REF_BIAS
);
213 const char *e
= strchr(fmt
, '$');
214 if (e
== NULL
) break;
215 memcpy(p
, fmt
, (size_t)(e
-fmt
));
218 Reg r
= va_arg(argp
, Reg
) & RID_MASK
;
221 for (q
= ra_regname
[r
]; *q
; q
++)
222 *p
++ = *q
>= 'A' && *q
<= 'Z' ? *q
+ 0x20 : *q
;
227 } else if (e
[1] == 'f' || e
[1] == 'i') {
230 ref
= va_arg(argp
, IRRef
);
232 ref
= va_arg(argp
, IRIns
*) - as
->ir
;
234 p
+= sprintf(p
, "%04d", ref
- REF_BIAS
);
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));
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
);
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
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)
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
)
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
)
300 if (ra_iskref(ref
)) {
302 lua_assert(!rset_test(as
->freeset
, r
));
305 emit_loadi(as
, r
, ra_krefk(as
, ref
));
310 lua_assert(ra_hasreg(r
) && !ra_hasspill(ir
->s
));
313 ir
->r
= RID_INIT
; /* Do not keep any hint. */
314 RA_DBGX((as
, "remat $i $r", ir
, r
));
316 if (ir
->o
== IR_KNUM
) {
317 emit_loadn(as
, r
, ir_knum(ir
));
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
);
327 } else if (ir
->o
== IR_KINT64
) {
328 emit_loadu64(as
, r
, ir_kint64(ir
)->u64
);
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
);
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
;
346 } else if (as
->oddspill
) {
350 slot
= as
->evenspill
;
351 as
->oddspill
= slot
+1;
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
)
366 lua_assert(ra_hasreg(r
) && !ra_hasspill(ir
->s
));
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
);
380 int32_t ofs
= ra_spill(as
, ir
); /* Force a spill slot. */
382 lua_assert(ra_hasreg(r
));
383 ra_sethint(ir
->r
, r
); /* Keep hint. */
385 if (!rset_test(as
->weakset
, r
)) { /* Only restore non-weak references. */
387 RA_DBGX((as
, "restore $i $r", ir
, r
));
388 emit_spload(as
, ir
, r
, ofs
);
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
)
410 RegCost cost
= ~(RegCost
)0;
411 lua_assert(allow
!= RSET_EMPTY
);
412 if (RID_NUM_FPR
== 0 || allow
< RID2RSET(RID_MAX_GPR
)) {
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
)) {
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
;
433 return ra_evict(as
, allow
);
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
);
443 RA_DBGX((as
, "scratch $r", r
));
447 /* Evict all registers from a set (if not free). */
448 static void ra_evictset(ASMState
*as
, RegSet drop
)
451 drop
&= ~as
->freeset
;
453 Reg r
= rset_pickbot(drop
);
454 ra_restore(as
, regcost_ref(as
->cost
[r
]));
460 /* Evict (rematerialize) all registers allocated to constants. */
461 static void ra_evictk(ASMState
*as
)
465 work
= ~as
->freeset
& RSET_FPR
;
467 Reg r
= rset_pickbot(work
);
468 IRRef ref
= regcost_ref(as
->cost
[r
]);
469 if (emit_canremat(ref
) && irref_isk(ref
)) {
476 work
= ~as
->freeset
& RSET_GPR
;
478 Reg r
= rset_pickbot(work
);
479 IRRef ref
= regcost_ref(as
->cost
[r
]);
480 if (emit_canremat(ref
) && irref_isk(ref
)) {
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
;
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
))
504 pick
= as
->freeset
& allow
;
506 /* Constants should preferably get unmodified registers. */
507 if ((pick
& ~as
->modset
))
509 r
= rset_pickbot(pick
); /* Reduce conflicts with inverse allocation. */
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
);
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
));
526 irdummy
.t
.irt
= IRT_INT
;
527 ra_scratch(as
, RID2RSET(r
));
528 emit_movrr(as
, &irdummy
, r
, kr
);
532 #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
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
)
542 RegSet pick
= as
->freeset
& allow
;
544 lua_assert(ra_noreg(ir
->r
));
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. */
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
]));
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
))
562 r
= rset_pickbot(pick
); /* Reduce conflicts with inverse allocation. */
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
);
570 r
= ra_evict(as
, allow
);
573 RA_DBGX((as
, "alloc $f $r", ref
, r
));
575 rset_clear(as
->freeset
, r
);
577 as
->cost
[r
] = REGCOST_REF_T(ref
, irt_t(ir
->t
));
581 /* Allocate a register on-demand. */
582 static Reg
ra_alloc1(ASMState
*as
, IRRef ref
, RegSet allow
)
585 /* Note: allow is ignored if the register is already allocated. */
586 if (ra_noreg(r
)) r
= ra_allocref(as
, ref
, allow
);
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
]);
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. */
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
)
622 if (ra_hasreg(dest
)) {
624 ra_modified(as
, dest
);
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
));
631 dest
= ra_scratch(as
, allow
);
635 if (LJ_UNLIKELY(ra_hasspill(ir
->s
))) ra_save(as
, ir
, 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
));
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
);
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
);
667 } else if (ir
->o
== IR_KINT64
) {
668 emit_loadu64(as
, dest
, ir_kint64(ir
)->u64
);
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
);
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
);
683 /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
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
);
690 emit_movrr(as
, ir
, dest
, left
);
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
);
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
);
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
);
712 emit_movrr(as
, ir
, dest
, left
);
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
)) {
733 ra_modified(as
, destlo
);
737 if (ra_hasreg(desthi
)) {
739 ra_modified(as
, desthi
);
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
);
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
);
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
);
766 /* -- Snapshot handling --------- ----------------------------------------- */
768 /* Can we rematerialize a KNUM instead of forcing a spill? */
769 static int asm_snap_canremat(ASMState
*as
)
772 for (r
= RID_MIN_FPR
; r
< RID_MAX_FPR
; r
++)
773 if (irref_isk(regcost_ref(as
->cost
[r
])))
778 /* Allocate register or spill slot for a ref that escapes to a snapshot. */
779 static void asm_snap_alloc1(ASMState
*as
, IRRef ref
)
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. */
791 RA_DBGX((as
, "snapreg $f $r", ref
, ir
->r
));
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
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
)) {
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
) {
846 lua_assert(as
->snapno
!= 0);
848 as
->snapref
= as
->T
->snap
[as
->snapno
].ref
;
849 } while (as
->curins
< as
->snapref
);
851 as
->snaprename
= as
->T
->nins
;
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
--; }
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
)
884 if (ir
->op1
!= REF_NIL
) { /* Count number of arguments first. */
885 IRIns
*ira
= IR(ir
->op1
);
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
);
906 BCReg s
= snap_slot(sn
);
907 BCReg fs
= s
+ funcproto(fn
)->framesize
;
908 if (fs
> topslot
) topslot
= fs
;
917 /* Calculate stack adjustment. */
918 static int32_t asm_stack_adjust(ASMState
*as
)
920 if (as
->evenspill
<= SPS_FIXED
)
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
)
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
;
938 lua_assert(irt_isgcv(ir
->t
));
939 lo
= u32ptr(ir_kgc(ir
));
942 return hashrot(lo
, hi
);
945 #if !LJ_TARGET_X86ORX64 && LJ_TARGET_OSX
946 void sys_icache_invalidate(void *start
, size_t len
);
949 #if LJ_TARGET_LINUX && LJ_TARGET_PPC
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
);
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
);
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
);
976 #error "Missing builtin to flush instruction cache"
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
];
989 args
[0] = ASMREF_L
; /* lua_State *L */
990 args
[1] = ir
->op1
; /* const char *str */
991 args
[2] = ir
->op2
; /* size_t len */
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
];
1001 args
[0] = ASMREF_L
; /* lua_State *L */
1002 args
[1] = ASMREF_TMP1
; /* uint32_t ahsize */
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
];
1013 args
[0] = ASMREF_L
; /* lua_State *L */
1014 args
[1] = ir
->op1
; /* const GCtab *kt */
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
,
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
)
1061 /* Find and resolve PHI register mismatches. */
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
]);
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
);
1079 } else { /* Otherwise grab register from invariant. */
1080 ra_restore(as
, ref
);
1084 if (ra_hasreg(left
)) {
1085 ra_rename(as
, left
, r
);
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
);
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
);
1102 Reg r
= rset_pickbot(work
);
1103 ra_restore(as
, regcost_ref(as
->cost
[r
]));
1104 rset_clear(work
, r
);
1108 /* Allocate and save all unsaved PHI regs and clear marks. */
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. */
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
;
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
)) {
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
) &
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? */
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
);
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
);
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
;
1191 /* LOOP marks the transition from the variant to the invariant part. */
1192 as
->flagmcp
= as
->invmcp
= NULL
;
1194 if (!neverfuse(as
)) as
->fuseref
= 0;
1195 asm_phi_shuffle(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"
1207 #include "lj_asm_arm.h"
1209 #error "Missing instruction emitter for target CPU"
1212 /* -- Head of trace ------------------------------------------------------- */
1214 /* Head of a root trace. */
1215 static void asm_head_root(ASMState
*as
)
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
)
1231 if (ir
->o
== IR_HIOP
) return as
->parentmaphi
[(ir
-1)->op1
];
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
;
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
--) {
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
)) {
1272 if (ir
->r
== rs
) { /* Coalesce matching registers right now. */
1274 } else if (ra_hasspill(regsp_spill(rs
))) {
1275 if (ra_hasreg(ir
->r
))
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
;
1290 as
->T
->spadjust
= (uint16_t)spadj
;
1292 /* Reload spilled target registers. */
1294 for (i
= as
->stopins
; i
> REF_BASE
; i
--) {
1296 if (irt_ismarked(ir
->t
)) {
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
);
1311 rset_clear(allow
, r
);
1312 if (r
== rs
) { /* Coalesce matching registers right now. */
1314 rset_clear(live
, r
);
1315 } else if (ra_hasspill(regsp_spill(rs
))) {
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
));
1333 /* Restore target registers from parent spill slots. */
1335 RegSet work
= ~as
->freeset
& RSET_ALL
;
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
));
1344 emit_spload(as
, ir
, r
, ofs
);
1350 /* Shuffle registers to match up target regs with parent regs. */
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
);
1361 emit_movrr(as
, ir
, ir
->r
, rp
);
1365 /* We're done if no live registers remain. */
1366 if (live
== RSET_EMPTY
)
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
));
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
;
1393 /* Reuse the parent exit in the context of the parent trace. */
1394 ExitNo exitno
= as
->J
->exitno
;
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
);
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
]);
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
)))
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
)
1456 uint32_t rload
= 0xa6402a64;
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
);
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
;
1475 as
->snapno
= T
->nsnap
;
1477 as
->stopins
= REF_BASE
;
1478 as
->orignins
= nins
;
1482 as
->evenspill
= SPS_FIRST
;
1483 for (i
= REF_FIRST
; i
< nins
; i
++) {
1489 /* Set hints for slot loads from a parent trace. */
1491 if ((ir
->op2
& IRSLOAD_PARENT
)) {
1492 RegSP rs
= as
->parentmap
[ir
->op1
];
1493 lua_assert(regsp_used(rs
));
1495 if (!ra_hasspill(regsp_spill(rs
)) && ra_hasreg(regsp_reg(rs
))) {
1496 ir
->prev
= (uint16_t)REGSP_HINT(regsp_reg(rs
));
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);
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);
1516 ci
.flags
= asm_callx_flags(as
, ir
);
1517 ir
->prev
= asm_setup_call_slots(as
, ir
, &ci
);
1519 as
->modset
|= RSET_SCRATCH
;
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
);
1526 as
->modset
|= (ci
->flags
& CCI_NOFPRCLOBBER
) ?
1527 (RSET_SCRATCH
& ~RSET_FPR
) : RSET_SCRATCH
;
1530 #if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
1532 switch ((ir
-1)->o
) {
1535 if (((ir
-1)->op2
& IRSLOAD_PARENT
)) {
1536 RegSP rs
= as
->parentmaphi
[(ir
-1)->op1
];
1537 lua_assert(regsp_used(rs
));
1539 if (!ra_hasspill(regsp_spill(rs
)) && ra_hasreg(regsp_reg(rs
))) {
1540 ir
->prev
= (uint16_t)REGSP_HINT(regsp_reg(rs
));
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;
1556 if (irt_isfp((ir
-1)->t
)) {
1557 ir
->prev
= REGSP_HINT(RID_FPRET
);
1562 case IR_CALLN
: case IR_CALLXS
:
1564 case IR_MIN
: case IR_MAX
:
1567 (ir
-1)->prev
= REGSP_HINT(RID_RETLO
);
1569 ir
->prev
= REGSP_HINT(RID_RETHI
);
1577 case IR_MIN
: case IR_MAX
:
1578 if ((ir
+1)->o
!= IR_HIOP
) break;
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
);
1588 as
->modset
= RSET_SCRATCH
;
1590 case IR_STRTO
: case IR_OBAR
:
1592 as
->modset
= RSET_SCRATCH
;
1594 #if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP
1595 case IR_ATAN2
: case IR_LDEXP
:
1598 if (!LJ_SOFTFP
&& irt_isnum(ir
->t
)) {
1599 #if LJ_TARGET_X86ORX64
1600 ir
->prev
= REGSP_HINT(RID_XMM0
);
1602 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM1
+1)|RID2RSET(RID_EAX
);
1604 ir
->prev
= REGSP_HINT(RID_FPRET
);
1606 as
->modset
|= RSET_SCRATCH
;
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
);
1615 as
->modset
|= (RSET_SCRATCH
& RSET_GPR
);
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
);
1624 if (as
->evenspill
< 4) /* Leave room for 16 byte scratch area. */
1628 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM2
+1)|RID2RSET(RID_EAX
);
1630 } else if (ir
->op2
<= IRFPM_TRUNC
&& !(as
->flags
& JIT_F_SSE4_1
)) {
1631 ir
->prev
= REGSP_HINT(RID_XMM0
);
1633 as
->modset
|= RSET_RANGE(RID_XMM0
, RID_XMM3
+1)|RID2RSET(RID_EAX
);
1638 ir
->prev
= REGSP_HINT(RID_FPRET
);
1640 as
->modset
|= RSET_SCRATCH
;
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
);
1649 rset_set(as
->modset
, RID_ECX
);
1653 /* Do not propagate hints across type conversions. */
1657 if (irt_isfp(ir
->t
) || (ir
->op2
& IRCONV_SRCMASK
) == IRT_NUM
||
1658 (ir
->op2
& IRCONV_SRCMASK
) == IRT_FLOAT
)
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
;
1669 ir
->prev
= REGSP_INIT
;
1671 if ((as
->evenspill
& 1))
1672 as
->oddspill
= as
->evenspill
++;
1677 /* -- Assembler core ------------------------------------------------------ */
1679 /* Assemble a trace. */
1680 void lj_asm_trace(jit_State
*J
, GCtrace
*T
)
1683 ASMState
*as
= &as_
;
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. */
1694 as
->flags
= J
->flags
;
1695 as
->loopref
= J
->loopref
;
1699 as
->parent
= traceref(J
, J
->parent
);
1700 lj_snap_regspmap(as
->parentmap
, as
->parent
, J
->exitno
, 0);
1702 lj_snap_regspmap(as
->parentmaphi
, as
->parent
, J
->exitno
, 1);
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
);
1714 as
->mcp
= as
->mctop
;
1715 as
->curins
= T
->nins
;
1717 RA_DBGX((as
, "===== STOP ====="));
1719 /* General trace setup. Emit tail of trace. */
1725 as
->sectref
= as
->loopref
;
1726 as
->fuseref
= (as
->flags
& JIT_F_OPT_FUSE
) ? as
->loopref
: FUSE_DISABLED
;
1727 asm_setup_regsp(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
))
1743 } while (as
->realign
); /* Retry in case the MCode needs to be realigned. */
1745 /* Emit head of trace. */
1749 as
->curins
= as
->T
->snap
[0].ref
;
1750 asm_snap_prep(as
); /* The GC check is a guard. */
1760 RA_DBGX((as
, "===== START ===="));
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. */
1767 T
->mcloop
= as
->mcloop
? (MSize
)((char *)as
->mcloop
- (char *)as
->mcp
) : 0;
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
);