2 ** Trace recorder (bytecode -> SSA IR).
3 ** Copyright (C) 2005-2011 Mike Pall. See Copyright Notice in luajit.h
22 #include "lj_ircall.h"
25 #include "lj_record.h"
26 #include "lj_ffrecord.h"
28 #include "lj_dispatch.h"
31 /* Some local macros to save typing. Undef'd at the end. */
32 #define IR(ref) (&J->cur.ir[(ref)])
34 /* Pass IR on to next optimization in chain (FOLD). */
35 #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
37 /* Emit raw IR without passing through optimizations. */
38 #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
40 /* -- Sanity checks ------------------------------------------------------- */
43 /* Sanity check the whole IR -- sloooow. */
44 static void rec_check_ir(jit_State
*J
)
46 IRRef i
, nins
= J
->cur
.nins
, nk
= J
->cur
.nk
;
47 lua_assert(nk
<= REF_BIAS
&& nins
>= REF_BIAS
&& nins
< 65536);
48 for (i
= nins
-1; i
>= nk
; i
--) {
50 uint32_t mode
= lj_ir_mode
[ir
->o
];
53 switch (irm_op1(mode
)) {
54 case IRMnone
: lua_assert(op1
== 0); break;
55 case IRMref
: lua_assert(op1
>= nk
);
56 lua_assert(i
>= REF_BIAS
? op1
< i
: op1
> i
); break;
58 case IRMcst
: lua_assert(i
< REF_BIAS
); continue;
60 switch (irm_op2(mode
)) {
61 case IRMnone
: lua_assert(op2
== 0); break;
62 case IRMref
: lua_assert(op2
>= nk
);
63 lua_assert(i
>= REF_BIAS
? op2
< i
: op2
> i
); break;
65 case IRMcst
: lua_assert(0); break;
68 lua_assert(ir
->prev
>= nk
);
69 lua_assert(i
>= REF_BIAS
? ir
->prev
< i
: ir
->prev
> i
);
70 lua_assert(ir
->o
== IR_NOP
|| IR(ir
->prev
)->o
== ir
->o
);
75 /* Compare stack slots and frames of the recorder and the VM. */
76 static void rec_check_slots(jit_State
*J
)
78 BCReg s
, nslots
= J
->baseslot
+ J
->maxslot
;
80 cTValue
*base
= J
->L
->base
- J
->baseslot
;
81 lua_assert(J
->baseslot
>= 1 && J
->baseslot
< LJ_MAX_JSLOTS
);
82 lua_assert(J
->baseslot
== 1 || (J
->slot
[J
->baseslot
-1] & TREF_FRAME
));
83 lua_assert(nslots
< LJ_MAX_JSLOTS
);
84 for (s
= 0; s
< nslots
; s
++) {
87 cTValue
*tv
= &base
[s
];
88 IRRef ref
= tref_ref(tr
);
90 lua_assert(ref
>= J
->cur
.nk
&& ref
< J
->cur
.nins
);
92 lua_assert(irt_t(ir
->t
) == tref_t(tr
));
94 lua_assert(tref_isfunc(tr
));
95 } else if ((tr
& TREF_FRAME
)) {
96 GCfunc
*fn
= gco2func(frame_gc(tv
));
97 BCReg delta
= (BCReg
)(tv
- frame_prev(tv
));
98 lua_assert(tref_isfunc(tr
));
99 if (tref_isk(tr
)) lua_assert(fn
== ir_kfunc(ir
));
100 lua_assert(s
> delta
? (J
->slot
[s
-delta
] & TREF_FRAME
) : (s
== delta
));
102 } else if ((tr
& TREF_CONT
)) {
103 lua_assert(ir_kptr(ir
) == gcrefp(tv
->gcr
, void));
104 lua_assert((J
->slot
[s
+1] & TREF_FRAME
));
108 lua_assert(tref_isnumber(tr
)); /* Could be IRT_INT etc., too. */
110 lua_assert(itype2irt(tv
) == tref_type(tr
));
111 if (tref_isk(tr
)) { /* Compare constants. */
113 lj_ir_kvalue(J
->L
, &tvk
, ir
);
114 if (!(tvisnum(&tvk
) && tvisnan(&tvk
)))
115 lua_assert(lj_obj_equal(tv
, &tvk
));
117 lua_assert(tvisnum(tv
) && tvisnan(tv
));
122 lua_assert(J
->framedepth
== depth
);
126 /* -- Type handling and specialization ------------------------------------ */
128 /* Note: these functions return tagged references (TRef). */
130 /* Specialize a slot to a specific type. Note: slot can be negative! */
131 static TRef
sloadt(jit_State
*J
, int32_t slot
, IRType t
, int mode
)
133 /* Caller may set IRT_GUARD in t. */
134 TRef ref
= emitir_raw(IRT(IR_SLOAD
, t
), (int32_t)J
->baseslot
+slot
, mode
);
139 /* Specialize a slot to the runtime type. Note: slot can be negative! */
140 static TRef
sload(jit_State
*J
, int32_t slot
)
142 IRType t
= itype2irt(&J
->L
->base
[slot
]);
143 TRef ref
= emitir_raw(IRTG(IR_SLOAD
, t
), (int32_t)J
->baseslot
+slot
,
145 if (irtype_ispri(t
)) ref
= TREF_PRI(t
); /* Canonicalize primitive refs. */
150 /* Get TRef from slot. Load slot and specialize if not done already. */
151 #define getslot(J, s) (J->base[(s)] ? J->base[(s)] : sload(J, (int32_t)(s)))
153 /* Get TRef for current function. */
154 static TRef
getcurrf(jit_State
*J
)
158 lua_assert(J
->baseslot
== 1);
159 return sloadt(J
, -1, IRT_FUNC
, IRSLOAD_READONLY
);
162 /* Compare for raw object equality.
163 ** Returns 0 if the objects are the same.
164 ** Returns 1 if they are different, but the same type.
165 ** Returns 2 for two different types.
166 ** Comparisons between primitives always return 1 -- no caller cares about it.
168 int lj_record_objcmp(jit_State
*J
, TRef a
, TRef b
, cTValue
*av
, cTValue
*bv
)
170 int diff
= !lj_obj_equal(av
, bv
);
171 if (!tref_isk2(a
, b
)) { /* Shortcut, also handles primitives. */
172 IRType ta
= tref_isinteger(a
) ? IRT_INT
: tref_type(a
);
173 IRType tb
= tref_isinteger(b
) ? IRT_INT
: tref_type(b
);
175 /* Widen mixed number/int comparisons to number/number comparison. */
176 if (ta
== IRT_INT
&& tb
== IRT_NUM
) {
177 a
= emitir(IRTN(IR_CONV
), a
, IRCONV_NUM_INT
);
179 } else if (ta
== IRT_NUM
&& tb
== IRT_INT
) {
180 b
= emitir(IRTN(IR_CONV
), b
, IRCONV_NUM_INT
);
182 return 2; /* Two different types are never equal. */
185 emitir(IRTG(diff
? IR_NE
: IR_EQ
, ta
), a
, b
);
190 /* -- Record loop ops ----------------------------------------------------- */
194 LOOPEV_LEAVE
, /* Loop is left or not entered. */
195 LOOPEV_ENTERLO
, /* Loop is entered with a low iteration count left. */
196 LOOPEV_ENTER
/* Loop is entered. */
199 /* Canonicalize slots: convert integers to numbers. */
200 static void canonicalize_slots(jit_State
*J
)
203 if (LJ_DUALNUM
) return;
204 for (s
= J
->baseslot
+J
->maxslot
-1; s
>= 1; s
--) {
205 TRef tr
= J
->slot
[s
];
206 if (tref_isinteger(tr
)) {
207 IRIns
*ir
= IR(tref_ref(tr
));
208 if (!(ir
->o
== IR_SLOAD
&& (ir
->op2
& IRSLOAD_READONLY
)))
209 J
->slot
[s
] = emitir(IRTN(IR_CONV
), tr
, IRCONV_NUM_INT
);
214 /* Stop recording. */
215 static void rec_stop(jit_State
*J
, TraceLink linktype
, TraceNo lnk
)
218 J
->cur
.linktype
= (uint8_t)linktype
;
219 J
->cur
.link
= (uint16_t)lnk
;
220 /* Looping back at the same stack level? */
221 if (lnk
== J
->cur
.traceno
&& J
->framedepth
+ J
->retdepth
== 0) {
222 if ((J
->flags
& JIT_F_OPT_LOOP
)) /* Shall we try to create a loop? */
223 goto nocanon
; /* Do not canonicalize or we lose the narrowing. */
224 if (J
->cur
.root
) /* Otherwise ensure we always link to the root trace. */
225 J
->cur
.link
= J
->cur
.root
;
227 canonicalize_slots(J
);
229 /* Note: all loop ops must set J->pc to the following instruction! */
230 lj_snap_add(J
); /* Add loop snapshot. */
232 J
->mergesnap
= 1; /* In case recording continues. */
235 /* Search bytecode backwards for a int/num constant slot initializer. */
236 static TRef
find_kinit(jit_State
*J
, const BCIns
*endpc
, BCReg slot
, IRType t
)
238 /* This algorithm is rather simplistic and assumes quite a bit about
239 ** how the bytecode is generated. It works fine for FORI initializers,
240 ** but it won't necessarily work in other cases (e.g. iterator arguments).
241 ** It doesn't do anything fancy, either (like backpropagating MOVs).
243 const BCIns
*pc
, *startpc
= proto_bc(J
->pt
);
244 for (pc
= endpc
-1; pc
> startpc
; pc
--) {
246 BCOp op
= bc_op(ins
);
247 /* First try to find the last instruction that stores to this slot. */
248 if (bcmode_a(op
) == BCMbase
&& bc_a(ins
) <= slot
) {
249 return 0; /* Multiple results, e.g. from a CALL or KNIL. */
250 } else if (bcmode_a(op
) == BCMdst
&& bc_a(ins
) == slot
) {
251 if (op
== BC_KSHORT
|| op
== BC_KNUM
) { /* Found const. initializer. */
252 /* Now try to verify there's no forward jump across it. */
253 const BCIns
*kpc
= pc
;
254 for (; pc
> startpc
; pc
--)
255 if (bc_op(*pc
) == BC_JMP
) {
256 const BCIns
*target
= pc
+bc_j(*pc
)+1;
257 if (target
> kpc
&& target
<= endpc
)
258 return 0; /* Conditional assignment. */
260 if (op
== BC_KSHORT
) {
261 int32_t k
= (int32_t)(int16_t)bc_d(ins
);
262 return t
== IRT_INT
? lj_ir_kint(J
, k
) : lj_ir_knum(J
, (lua_Number
)k
);
264 cTValue
*tv
= proto_knumtv(J
->pt
, bc_d(ins
));
266 int32_t k
= numberVint(tv
);
267 if (tvisint(tv
) || numV(tv
) == (lua_Number
)k
) /* -0 is ok here. */
268 return lj_ir_kint(J
, k
);
269 return 0; /* Type mismatch. */
271 return lj_ir_knum(J
, numberVnum(tv
));
275 return 0; /* Non-constant initializer. */
278 return 0; /* No assignment to this slot found? */
281 /* Load and optionally convert a FORI argument from a slot. */
282 static TRef
fori_load(jit_State
*J
, BCReg slot
, IRType t
, int mode
)
284 int conv
= (tvisint(&J
->L
->base
[slot
]) != (t
==IRT_INT
)) ? IRSLOAD_CONVERT
: 0;
285 return sloadt(J
, (int32_t)slot
,
286 t
+ (((mode
& IRSLOAD_TYPECHECK
) ||
287 (conv
&& t
== IRT_INT
&& !(mode
>> 16))) ?
292 /* Peek before FORI to find a const initializer. Otherwise load from slot. */
293 static TRef
fori_arg(jit_State
*J
, const BCIns
*fori
, BCReg slot
,
296 TRef tr
= J
->base
[slot
];
298 tr
= find_kinit(J
, fori
, slot
, t
);
300 tr
= fori_load(J
, slot
, t
, mode
);
305 /* Return the direction of the FOR loop iterator.
306 ** It's important to exactly reproduce the semantics of the interpreter.
308 static int rec_for_direction(cTValue
*o
)
310 return (tvisint(o
) ? intV(o
) : (int32_t)o
->u32
.hi
) >= 0;
313 /* Simulate the runtime behavior of the FOR loop iterator. */
314 static LoopEvent
rec_for_iter(IROp
*op
, cTValue
*o
, int isforl
)
316 lua_Number stopv
= numberVnum(&o
[FORL_STOP
]);
317 lua_Number idxv
= numberVnum(&o
[FORL_IDX
]);
318 lua_Number stepv
= numberVnum(&o
[FORL_STEP
]);
321 if (rec_for_direction(&o
[FORL_STEP
])) {
324 return idxv
+ 2*stepv
> stopv
? LOOPEV_ENTERLO
: LOOPEV_ENTER
;
326 *op
= IR_GT
; return LOOPEV_LEAVE
;
330 return idxv
+ 2*stepv
< stopv
? LOOPEV_ENTERLO
: LOOPEV_ENTER
;
332 *op
= IR_LT
; return LOOPEV_LEAVE
;
336 /* Record checks for FOR loop overflow and step direction. */
337 static void rec_for_check(jit_State
*J
, IRType t
, int dir
,
338 TRef stop
, TRef step
, int init
)
340 if (!tref_isk(step
)) {
341 /* Non-constant step: need a guard for the direction. */
342 TRef zero
= (t
== IRT_INT
) ? lj_ir_kint(J
, 0) : lj_ir_knum_zero(J
);
343 emitir(IRTG(dir
? IR_GE
: IR_LT
, t
), step
, zero
);
344 /* Add hoistable overflow checks for a narrowed FORL index. */
345 if (init
&& t
== IRT_INT
) {
346 if (tref_isk(stop
)) {
347 /* Constant stop: optimize check away or to a range check for step. */
348 int32_t k
= IR(tref_ref(stop
))->i
;
351 emitir(IRTGI(IR_LE
), step
, lj_ir_kint(J
, (int32_t)0x7fffffff-k
));
354 emitir(IRTGI(IR_GE
), step
, lj_ir_kint(J
, (int32_t)0x80000000-k
));
357 /* Stop+step variable: need full overflow check. */
358 TRef tr
= emitir(IRTGI(IR_ADDOV
), step
, stop
);
359 emitir(IRTI(IR_USE
), tr
, 0); /* ADDOV is weak. Avoid dead result. */
362 } else if (init
&& t
== IRT_INT
&& !tref_isk(stop
)) {
363 /* Constant step: optimize overflow check to a range check for stop. */
364 int32_t k
= IR(tref_ref(step
))->i
;
365 k
= (int32_t)(dir
? 0x7fffffff : 0x80000000) - k
;
366 emitir(IRTGI(dir
? IR_LE
: IR_GE
), stop
, lj_ir_kint(J
, k
));
370 /* Record a FORL instruction. */
371 static void rec_for_loop(jit_State
*J
, const BCIns
*fori
, ScEvEntry
*scev
,
374 BCReg ra
= bc_a(*fori
);
375 cTValue
*tv
= &J
->L
->base
[ra
];
376 TRef idx
= J
->base
[ra
+FORL_IDX
];
377 IRType t
= idx
? tref_type(idx
) :
378 (init
|| LJ_DUALNUM
) ? lj_opt_narrow_forl(J
, tv
) : IRT_NUM
;
379 int mode
= IRSLOAD_INHERIT
+
380 ((!LJ_DUALNUM
|| tvisint(tv
) == (t
== IRT_INT
)) ? IRSLOAD_READONLY
: 0);
381 TRef stop
= fori_arg(J
, fori
, ra
+FORL_STOP
, t
, mode
);
382 TRef step
= fori_arg(J
, fori
, ra
+FORL_STEP
, t
, mode
);
383 int tc
, dir
= rec_for_direction(&tv
[FORL_STEP
]);
384 lua_assert(bc_op(*fori
) == BC_FORI
|| bc_op(*fori
) == BC_JFORI
);
387 scev
->stop
= tref_ref(stop
);
388 scev
->step
= tref_ref(step
);
389 rec_for_check(J
, t
, dir
, stop
, step
, init
);
390 scev
->start
= tref_ref(find_kinit(J
, fori
, ra
+FORL_IDX
, IRT_INT
));
392 !(scev
->start
&& irref_isk(scev
->stop
) && irref_isk(scev
->step
) &&
393 tvisint(&tv
[FORL_IDX
]) == (t
== IRT_INT
))) ?
394 IRSLOAD_TYPECHECK
: 0;
396 J
->base
[ra
+FORL_STOP
] = stop
;
397 J
->base
[ra
+FORL_STEP
] = step
;
400 idx
= fori_load(J
, ra
+FORL_IDX
, t
,
401 IRSLOAD_INHERIT
+ tc
+ (J
->scev
.start
<< 16));
403 J
->base
[ra
+FORL_IDX
] = idx
= emitir(IRT(IR_ADD
, t
), idx
, step
);
404 J
->base
[ra
+FORL_EXT
] = idx
;
405 scev
->idx
= tref_ref(idx
);
406 J
->maxslot
= ra
+FORL_EXT
+1;
409 /* Record FORL/JFORL or FORI/JFORI. */
410 static LoopEvent
rec_for(jit_State
*J
, const BCIns
*fori
, int isforl
)
412 BCReg ra
= bc_a(*fori
);
413 TValue
*tv
= &J
->L
->base
[ra
];
414 TRef
*tr
= &J
->base
[ra
];
419 if (isforl
) { /* Handle FORL/JFORL opcodes. */
420 TRef idx
= tr
[FORL_IDX
];
421 if (tref_ref(idx
) == J
->scev
.idx
) {
424 idx
= emitir(IRT(IR_ADD
, t
), idx
, J
->scev
.step
);
425 tr
[FORL_EXT
] = tr
[FORL_IDX
] = idx
;
428 rec_for_loop(J
, fori
, &scev
, 0);
432 } else { /* Handle FORI/JFORI opcodes. */
434 lj_meta_for(J
->L
, tv
);
435 t
= (LJ_DUALNUM
|| tref_isint(tr
[FORL_IDX
])) ? lj_opt_narrow_forl(J
, tv
) :
437 for (i
= FORL_IDX
; i
<= FORL_STEP
; i
++) {
438 if (!tr
[i
]) sload(J
, ra
+i
);
439 lua_assert(tref_isnumber_str(tr
[i
]));
440 if (tref_isstr(tr
[i
]))
441 tr
[i
] = emitir(IRTG(IR_STRTO
, IRT_NUM
), tr
[i
], 0);
443 if (!tref_isinteger(tr
[i
]))
444 tr
[i
] = emitir(IRTGI(IR_CONV
), tr
[i
], IRCONV_INT_NUM
|IRCONV_CHECK
);
446 if (!tref_isnum(tr
[i
]))
447 tr
[i
] = emitir(IRTN(IR_CONV
), tr
[i
], IRCONV_NUM_INT
);
450 tr
[FORL_EXT
] = tr
[FORL_IDX
];
451 stop
= tr
[FORL_STOP
];
452 rec_for_check(J
, t
, rec_for_direction(&tv
[FORL_STEP
]),
453 stop
, tr
[FORL_STEP
], 1);
456 ev
= rec_for_iter(&op
, tv
, isforl
);
457 if (ev
== LOOPEV_LEAVE
) {
458 J
->maxslot
= ra
+FORL_EXT
+1;
462 J
->pc
= fori
+bc_j(*fori
)+1;
466 emitir(IRTG(op
, t
), tr
[FORL_IDX
], stop
);
468 if (ev
== LOOPEV_LEAVE
) {
470 J
->pc
= fori
+bc_j(*fori
)+1;
472 J
->maxslot
= ra
+FORL_EXT
+1;
479 /* Record ITERL/JITERL. */
480 static LoopEvent
rec_iterl(jit_State
*J
, const BCIns iterins
)
482 BCReg ra
= bc_a(iterins
);
483 lua_assert(J
->base
[ra
] != 0);
484 if (!tref_isnil(J
->base
[ra
])) { /* Looping back? */
485 J
->base
[ra
-1] = J
->base
[ra
]; /* Copy result of ITERC to control var. */
486 J
->maxslot
= ra
-1+bc_b(J
->pc
[-1]);
487 J
->pc
+= bc_j(iterins
)+1;
496 /* Record LOOP/JLOOP. Now, that was easy. */
497 static LoopEvent
rec_loop(jit_State
*J
, BCReg ra
)
499 if (ra
< J
->maxslot
) J
->maxslot
= ra
;
504 /* Check if a loop repeatedly failed to trace because it didn't loop back. */
505 static int innerloopleft(jit_State
*J
, const BCIns
*pc
)
508 for (i
= 0; i
< PENALTY_SLOTS
; i
++)
509 if (mref(J
->penalty
[i
].pc
, const BCIns
) == pc
) {
510 if ((J
->penalty
[i
].reason
== LJ_TRERR_LLEAVE
||
511 J
->penalty
[i
].reason
== LJ_TRERR_LINNER
) &&
512 J
->penalty
[i
].val
>= 2*PENALTY_MIN
)
519 /* Handle the case when an interpreted loop op is hit. */
520 static void rec_loop_interp(jit_State
*J
, const BCIns
*pc
, LoopEvent ev
)
522 if (J
->parent
== 0) {
523 if (pc
== J
->startpc
&& J
->framedepth
+ J
->retdepth
== 0) {
525 if (ev
== LOOPEV_LEAVE
) /* Must loop back to form a root trace. */
526 lj_trace_err(J
, LJ_TRERR_LLEAVE
);
527 rec_stop(J
, LJ_TRLINK_LOOP
, J
->cur
.traceno
); /* Looping root trace. */
528 } else if (ev
!= LOOPEV_LEAVE
) { /* Entering inner loop? */
529 /* It's usually better to abort here and wait until the inner loop
530 ** is traced. But if the inner loop repeatedly didn't loop back,
531 ** this indicates a low trip count. In this case try unrolling
532 ** an inner loop even in a root trace. But it's better to be a bit
533 ** more conservative here and only do it for very short loops.
535 if (!innerloopleft(J
, pc
))
536 lj_trace_err(J
, LJ_TRERR_LINNER
); /* Root trace hit an inner loop. */
537 if ((ev
!= LOOPEV_ENTERLO
&&
538 J
->loopref
&& J
->cur
.nins
- J
->loopref
> 24) || --J
->loopunroll
< 0)
539 lj_trace_err(J
, LJ_TRERR_LUNROLL
); /* Limit loop unrolling. */
540 J
->loopref
= J
->cur
.nins
;
542 } else if (ev
!= LOOPEV_LEAVE
) { /* Side trace enters an inner loop. */
543 J
->loopref
= J
->cur
.nins
;
544 if (--J
->loopunroll
< 0)
545 lj_trace_err(J
, LJ_TRERR_LUNROLL
); /* Limit loop unrolling. */
546 } /* Side trace continues across a loop that's left or not entered. */
549 /* Handle the case when an already compiled loop op is hit. */
550 static void rec_loop_jit(jit_State
*J
, TraceNo lnk
, LoopEvent ev
)
552 if (J
->parent
== 0) { /* Root trace hit an inner loop. */
553 /* Better let the inner loop spawn a side trace back here. */
554 lj_trace_err(J
, LJ_TRERR_LINNER
);
555 } else if (ev
!= LOOPEV_LEAVE
) { /* Side trace enters a compiled loop. */
556 J
->instunroll
= 0; /* Cannot continue across a compiled loop op. */
557 if (J
->pc
== J
->startpc
&& J
->framedepth
+ J
->retdepth
== 0)
558 rec_stop(J
, LJ_TRLINK_LOOP
, J
->cur
.traceno
); /* Form an extra loop. */
560 rec_stop(J
, LJ_TRLINK_ROOT
, lnk
); /* Link to the loop. */
561 } /* Side trace continues across a loop that's left or not entered. */
564 /* -- Record calls and returns -------------------------------------------- */
566 /* Record call setup. */
567 static void rec_call_setup(jit_State
*J
, BCReg func
, ptrdiff_t nargs
)
570 TValue
*functv
= &J
->L
->base
[func
];
571 TRef trfunc
, *fbase
= &J
->base
[func
];
573 for (i
= 0; i
<= nargs
; i
++)
574 (void)getslot(J
, func
+i
); /* Ensure func and all args have a reference. */
575 if (!tref_isfunc(fbase
[0])) { /* Resolve __call metamethod. */
577 copyTV(J
->L
, &ix
.tabv
, functv
);
578 if (!lj_record_mm_lookup(J
, &ix
, MM_call
) || !tref_isfunc(ix
.mobj
))
579 lj_trace_err(J
, LJ_TRERR_NOMM
);
580 for (i
= ++nargs
; i
> 0; i
--) /* Shift arguments up. */
581 fbase
[i
] = fbase
[i
-1];
582 fbase
[0] = ix
.mobj
; /* Replace function. */
586 /* Specialize to the runtime value of the called function. */
587 trfunc
= lj_ir_kfunc(J
, funcV(functv
));
588 emitir(IRTG(IR_EQ
, IRT_FUNC
), fbase
[0], trfunc
);
589 fbase
[0] = trfunc
| TREF_FRAME
;
590 J
->maxslot
= (BCReg
)nargs
;
594 void lj_record_call(jit_State
*J
, BCReg func
, ptrdiff_t nargs
)
596 rec_call_setup(J
, func
, nargs
);
600 J
->baseslot
+= func
+1;
603 /* Record tail call. */
604 void lj_record_tailcall(jit_State
*J
, BCReg func
, ptrdiff_t nargs
)
606 rec_call_setup(J
, func
, nargs
);
607 if (frame_isvarg(J
->L
->base
- 1)) {
608 BCReg cbase
= (BCReg
)frame_delta(J
->L
->base
- 1);
609 if (--J
->framedepth
< 0)
610 lj_trace_err(J
, LJ_TRERR_NYIRETL
);
611 J
->baseslot
-= (BCReg
)cbase
;
615 /* Move func + args down. */
616 memmove(&J
->base
[-1], &J
->base
[func
], sizeof(TRef
)*(J
->maxslot
+1));
617 /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
618 /* Tailcalls can form a loop, so count towards the loop unroll limit. */
619 if (++J
->tailcalled
> J
->loopunroll
)
620 lj_trace_err(J
, LJ_TRERR_LUNROLL
);
623 /* Check unroll limits for down-recursion. */
624 static int check_downrec_unroll(jit_State
*J
, GCproto
*pt
)
627 for (ptref
= J
->chain
[IR_KGC
]; ptref
; ptref
= IR(ptref
)->prev
)
628 if (ir_kgc(IR(ptref
)) == obj2gco(pt
)) {
631 for (ref
= J
->chain
[IR_RETF
]; ref
; ref
= IR(ref
)->prev
)
632 if (IR(ref
)->op1
== ptref
)
635 if (J
->pc
== J
->startpc
) {
636 if (count
+ J
->tailcalled
> J
->param
[JIT_P_recunroll
])
639 lj_trace_err(J
, LJ_TRERR_DOWNREC
);
647 void lj_record_ret(jit_State
*J
, BCReg rbase
, ptrdiff_t gotresults
)
649 TValue
*frame
= J
->L
->base
- 1;
651 for (i
= 0; i
< gotresults
; i
++)
652 (void)getslot(J
, rbase
+i
); /* Ensure all results have a reference. */
653 while (frame_ispcall(frame
)) { /* Immediately resolve pcall() returns. */
654 BCReg cbase
= (BCReg
)frame_delta(frame
);
655 if (--J
->framedepth
< 0)
656 lj_trace_err(J
, LJ_TRERR_NYIRETL
);
657 lua_assert(J
->baseslot
> 1);
660 J
->baseslot
-= (BCReg
)cbase
;
662 J
->base
[--rbase
] = TREF_TRUE
; /* Prepend true to results. */
663 frame
= frame_prevd(frame
);
665 /* Return to lower frame via interpreter for unhandled cases. */
666 if (J
->framedepth
== 0 && J
->pt
&& bc_isret(bc_op(*J
->pc
)) &&
667 (!frame_islua(frame
) ||
668 (J
->parent
== 0 && !bc_isret(bc_op(J
->cur
.startins
))))) {
669 /* NYI: specialize to frame type and return directly, not via RET*. */
670 for (i
= -1; i
< (ptrdiff_t)rbase
; i
++)
671 J
->base
[i
] = 0; /* Purge dead slots. */
672 J
->maxslot
= rbase
+ (BCReg
)gotresults
;
673 rec_stop(J
, LJ_TRLINK_RETURN
, 0); /* Return to interpreter. */
676 if (frame_isvarg(frame
)) {
677 BCReg cbase
= (BCReg
)frame_delta(frame
);
678 if (--J
->framedepth
< 0) /* NYI: return of vararg func to lower frame. */
679 lj_trace_err(J
, LJ_TRERR_NYIRETL
);
680 lua_assert(J
->baseslot
> 1);
682 J
->baseslot
-= (BCReg
)cbase
;
684 frame
= frame_prevd(frame
);
686 if (frame_islua(frame
)) { /* Return to Lua frame. */
687 BCIns callins
= *(frame_pc(frame
)-1);
688 ptrdiff_t nresults
= bc_b(callins
) ? (ptrdiff_t)bc_b(callins
)-1 :gotresults
;
689 BCReg cbase
= bc_a(callins
);
690 GCproto
*pt
= funcproto(frame_func(frame
- (cbase
+1)));
691 if (J
->framedepth
== 0 && J
->pt
&& frame
== J
->L
->base
- 1) {
692 if (check_downrec_unroll(J
, pt
)) {
693 J
->maxslot
= (BCReg
)(rbase
+ gotresults
);
695 rec_stop(J
, LJ_TRLINK_DOWNREC
, J
->cur
.traceno
); /* Down-recursion. */
700 for (i
= 0; i
< nresults
; i
++) /* Adjust results. */
701 J
->base
[i
-1] = i
< gotresults
? J
->base
[rbase
+i
] : TREF_NIL
;
702 J
->maxslot
= cbase
+(BCReg
)nresults
;
703 if (J
->framedepth
> 0) { /* Return to a frame that is part of the trace. */
705 lua_assert(J
->baseslot
> cbase
+1);
706 J
->baseslot
-= cbase
+1;
708 } else if (J
->parent
== 0 && !bc_isret(bc_op(J
->cur
.startins
))) {
709 /* Return to lower frame would leave the loop in a root trace. */
710 lj_trace_err(J
, LJ_TRERR_LLEAVE
);
711 } else { /* Return to lower frame. Guard for the target we return to. */
712 TRef trpt
= lj_ir_kgc(J
, obj2gco(pt
), IRT_PROTO
);
713 TRef trpc
= lj_ir_kptr(J
, (void *)frame_pc(frame
));
714 emitir(IRTG(IR_RETF
, IRT_P32
), trpt
, trpc
);
717 lua_assert(J
->baseslot
== 1);
718 /* Shift result slots up and clear the slots of the new frame below. */
719 memmove(J
->base
+ cbase
, J
->base
-1, sizeof(TRef
)*nresults
);
720 memset(J
->base
-1, 0, sizeof(TRef
)*(cbase
+1));
722 } else if (frame_iscont(frame
)) { /* Return to continuation frame. */
723 ASMFunction cont
= frame_contf(frame
);
724 BCReg cbase
= (BCReg
)frame_delta(frame
);
725 if ((J
->framedepth
-= 2) < 0)
726 lj_trace_err(J
, LJ_TRERR_NYIRETL
);
727 J
->baseslot
-= (BCReg
)cbase
;
729 J
->maxslot
= cbase
-2;
730 if (cont
== lj_cont_ra
) {
731 /* Copy result to destination slot. */
732 BCReg dst
= bc_a(*(frame_contpc(frame
)-1));
733 J
->base
[dst
] = gotresults
? J
->base
[cbase
+rbase
] : TREF_NIL
;
734 if (dst
>= J
->maxslot
) J
->maxslot
= dst
+1;
735 } else if (cont
== lj_cont_nop
) {
736 /* Nothing to do here. */
737 } else if (cont
== lj_cont_cat
) {
740 /* Result type already specialized. */
741 lua_assert(cont
== lj_cont_condf
|| cont
== lj_cont_condt
);
744 lj_trace_err(J
, LJ_TRERR_NYIRETL
); /* NYI: handle return to C frame. */
746 lua_assert(J
->baseslot
>= 1);
749 /* -- Metamethod handling ------------------------------------------------- */
751 /* Prepare to record call to metamethod. */
752 static BCReg
rec_mm_prep(jit_State
*J
, ASMFunction cont
)
754 BCReg s
, top
= curr_proto(J
->L
)->framesize
;
756 setcont(&J
->L
->base
[top
], cont
);
758 trcont
= lj_ir_kptr(J
, (void *)((int64_t)cont
- (int64_t)lj_vm_asm_begin
));
760 trcont
= lj_ir_kptr(J
, (void *)cont
);
762 J
->base
[top
] = trcont
| TREF_CONT
;
764 for (s
= J
->maxslot
; s
< top
; s
++)
765 J
->base
[s
] = 0; /* Clear frame gap to avoid resurrecting previous refs. */
769 /* Record metamethod lookup. */
770 int lj_record_mm_lookup(jit_State
*J
, RecordIndex
*ix
, MMS mm
)
774 if (tref_istab(ix
->tab
)) {
775 mt
= tabref(tabV(&ix
->tabv
)->metatable
);
776 mix
.tab
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->tab
, IRFL_TAB_META
);
777 } else if (tref_isudata(ix
->tab
)) {
778 int udtype
= udataV(&ix
->tabv
)->udtype
;
779 mt
= tabref(udataV(&ix
->tabv
)->metatable
);
780 /* The metatables of special userdata objects are treated as immutable. */
781 if (udtype
!= UDTYPE_USERDATA
) {
783 if (LJ_HASFFI
&& udtype
== UDTYPE_FFI_CLIB
) {
784 /* Specialize to the C library namespace object. */
785 emitir(IRTG(IR_EQ
, IRT_P32
), ix
->tab
, lj_ir_kptr(J
, udataV(&ix
->tabv
)));
787 /* Specialize to the type of userdata. */
788 TRef tr
= emitir(IRT(IR_FLOAD
, IRT_U8
), ix
->tab
, IRFL_UDATA_UDTYPE
);
789 emitir(IRTGI(IR_EQ
), tr
, lj_ir_kint(J
, udtype
));
792 mo
= lj_tab_getstr(mt
, mmname_str(J2G(J
), mm
));
793 if (!mo
|| tvisnil(mo
))
794 return 0; /* No metamethod. */
795 /* Treat metamethod or index table as immutable, too. */
796 if (!(tvisfunc(mo
) || tvistab(mo
)))
797 lj_trace_err(J
, LJ_TRERR_BADTYPE
);
798 copyTV(J
->L
, &ix
->mobjv
, mo
);
799 ix
->mobj
= lj_ir_kgc(J
, gcV(mo
), tvisfunc(mo
) ? IRT_FUNC
: IRT_TAB
);
801 ix
->mt
= TREF_NIL
; /* Dummy value for comparison semantics. */
802 return 1; /* Got metamethod or index table. */
804 mix
.tab
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->tab
, IRFL_UDATA_META
);
806 /* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
807 mt
= tabref(basemt_obj(J2G(J
), &ix
->tabv
));
810 return 0; /* No metamethod. */
812 /* The cdata metatable is treated as immutable. */
813 if (LJ_HASFFI
&& tref_iscdata(ix
->tab
)) goto immutable_mt
;
814 ix
->mt
= mix
.tab
= lj_ir_ktab(J
, mt
);
817 ix
->mt
= mt
? mix
.tab
: TREF_NIL
;
818 emitir(IRTG(mt
? IR_NE
: IR_EQ
, IRT_TAB
), mix
.tab
, lj_ir_knull(J
, IRT_TAB
));
821 GCstr
*mmstr
= mmname_str(J2G(J
), mm
);
822 cTValue
*mo
= lj_tab_getstr(mt
, mmstr
);
823 if (mo
&& !tvisnil(mo
))
824 copyTV(J
->L
, &ix
->mobjv
, mo
);
826 settabV(J
->L
, &mix
.tabv
, mt
);
827 setstrV(J
->L
, &mix
.keyv
, mmstr
);
828 mix
.key
= lj_ir_kstr(J
, mmstr
);
831 ix
->mobj
= lj_record_idx(J
, &mix
);
832 return !tref_isnil(ix
->mobj
); /* 1 if metamethod found, 0 if not. */
834 return 0; /* No metamethod. */
837 /* Record call to arithmetic metamethod. */
838 static TRef
rec_mm_arith(jit_State
*J
, RecordIndex
*ix
, MMS mm
)
840 /* Set up metamethod call first to save ix->tab and ix->tabv. */
841 BCReg func
= rec_mm_prep(J
, lj_cont_ra
);
842 TRef
*base
= J
->base
+ func
;
843 TValue
*basev
= J
->L
->base
+ func
;
844 base
[1] = ix
->tab
; base
[2] = ix
->key
;
845 copyTV(J
->L
, basev
+1, &ix
->tabv
);
846 copyTV(J
->L
, basev
+2, &ix
->keyv
);
847 if (!lj_record_mm_lookup(J
, ix
, mm
)) { /* Lookup mm on 1st operand. */
850 copyTV(J
->L
, &ix
->tabv
, &ix
->keyv
);
851 if (lj_record_mm_lookup(J
, ix
, mm
)) /* Lookup mm on 2nd operand. */
854 lj_trace_err(J
, LJ_TRERR_NOMM
);
858 copyTV(J
->L
, basev
+0, &ix
->mobjv
);
859 lj_record_call(J
, func
, 2);
860 return 0; /* No result yet. */
863 /* Record call to __len metamethod. */
864 static TRef
rec_mm_len(jit_State
*J
, TRef tr
, TValue
*tv
)
868 copyTV(J
->L
, &ix
.tabv
, tv
);
869 if (lj_record_mm_lookup(J
, &ix
, MM_len
)) {
870 BCReg func
= rec_mm_prep(J
, lj_cont_ra
);
871 TRef
*base
= J
->base
+ func
;
872 TValue
*basev
= J
->L
->base
+ func
;
873 base
[0] = ix
.mobj
; copyTV(J
->L
, basev
+0, &ix
.mobjv
);
874 base
[1] = tr
; copyTV(J
->L
, basev
+1, tv
);
875 #ifdef LUAJIT_ENABLE_LUA52COMPAT
876 base
[2] = tr
; copyTV(J
->L
, basev
+2, tv
);
878 base
[2] = TREF_NIL
; setnilV(basev
+2);
880 lj_record_call(J
, func
, 2);
882 #ifdef LUAJIT_ENABLE_LUA52COMPAT
884 return lj_ir_call(J
, IRCALL_lj_tab_len
, tr
);
886 lj_trace_err(J
, LJ_TRERR_NOMM
);
888 return 0; /* No result yet. */
891 /* Call a comparison metamethod. */
892 static void rec_mm_callcomp(jit_State
*J
, RecordIndex
*ix
, int op
)
894 BCReg func
= rec_mm_prep(J
, (op
&1) ? lj_cont_condf
: lj_cont_condt
);
895 TRef
*base
= J
->base
+ func
;
896 TValue
*tv
= J
->L
->base
+ func
;
897 base
[0] = ix
->mobj
; base
[1] = ix
->val
; base
[2] = ix
->key
;
898 copyTV(J
->L
, tv
+0, &ix
->mobjv
);
899 copyTV(J
->L
, tv
+1, &ix
->valv
);
900 copyTV(J
->L
, tv
+2, &ix
->keyv
);
901 lj_record_call(J
, func
, 2);
904 /* Record call to equality comparison metamethod (for tab and udata only). */
905 static void rec_mm_equal(jit_State
*J
, RecordIndex
*ix
, int op
)
908 copyTV(J
->L
, &ix
->tabv
, &ix
->valv
);
909 if (lj_record_mm_lookup(J
, ix
, MM_eq
)) { /* Lookup mm on 1st operand. */
913 copyTV(J
->L
, &mo1v
, &ix
->mobjv
);
914 /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
916 if (tvistab(bv
) && tabref(tabV(bv
)->metatable
) == ix
->mtv
) {
917 TRef mt2
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->key
, IRFL_TAB_META
);
918 emitir(IRTG(IR_EQ
, IRT_TAB
), mt2
, ix
->mt
);
919 } else if (tvisudata(bv
) && tabref(udataV(bv
)->metatable
) == ix
->mtv
) {
920 TRef mt2
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->key
, IRFL_UDATA_META
);
921 emitir(IRTG(IR_EQ
, IRT_TAB
), mt2
, ix
->mt
);
922 } else { /* Lookup metamethod on 2nd operand and compare both. */
924 copyTV(J
->L
, &ix
->tabv
, bv
);
925 if (!lj_record_mm_lookup(J
, ix
, MM_eq
) ||
926 lj_record_objcmp(J
, mo1
, ix
->mobj
, &mo1v
, &ix
->mobjv
))
929 rec_mm_callcomp(J
, ix
, op
);
933 /* Record call to ordered comparison metamethods (for arbitrary objects). */
934 static void rec_mm_comp(jit_State
*J
, RecordIndex
*ix
, int op
)
937 copyTV(J
->L
, &ix
->tabv
, &ix
->valv
);
939 MMS mm
= (op
& 2) ? MM_le
: MM_lt
; /* Try __le + __lt or only __lt. */
940 if (lj_record_mm_lookup(J
, ix
, mm
)) { /* Lookup mm on 1st operand. */
944 copyTV(J
->L
, &mo1v
, &ix
->mobjv
);
945 /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
947 if (tvistab(bv
) && tabref(tabV(bv
)->metatable
) == ix
->mtv
) {
948 TRef mt2
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->key
, IRFL_TAB_META
);
949 emitir(IRTG(IR_EQ
, IRT_TAB
), mt2
, ix
->mt
);
950 } else if (tvisudata(bv
) && tabref(udataV(bv
)->metatable
) == ix
->mtv
) {
951 TRef mt2
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->key
, IRFL_UDATA_META
);
952 emitir(IRTG(IR_EQ
, IRT_TAB
), mt2
, ix
->mt
);
953 } else { /* Lookup metamethod on 2nd operand and compare both. */
955 copyTV(J
->L
, &ix
->tabv
, bv
);
956 if (!lj_record_mm_lookup(J
, ix
, mm
) ||
957 lj_record_objcmp(J
, mo1
, ix
->mobj
, &mo1v
, &ix
->mobjv
))
960 rec_mm_callcomp(J
, ix
, op
);
964 /* First lookup failed. Retry with __lt and swapped operands. */
965 if (!(op
& 2)) break; /* Already at __lt. Interpreter will throw. */
966 ix
->tab
= ix
->key
; ix
->key
= ix
->val
; ix
->val
= ix
->tab
;
967 copyTV(J
->L
, &ix
->tabv
, &ix
->keyv
);
968 copyTV(J
->L
, &ix
->keyv
, &ix
->valv
);
969 copyTV(J
->L
, &ix
->valv
, &ix
->tabv
);
975 /* Setup call to cdata comparison metamethod. */
976 static void rec_mm_comp_cdata(jit_State
*J
, RecordIndex
*ix
, int op
, MMS mm
)
979 if (tref_iscdata(ix
->val
)) {
981 copyTV(J
->L
, &ix
->tabv
, &ix
->valv
);
983 lua_assert(tref_iscdata(ix
->key
));
985 copyTV(J
->L
, &ix
->tabv
, &ix
->keyv
);
987 lj_record_mm_lookup(J
, ix
, mm
);
988 rec_mm_callcomp(J
, ix
, op
);
992 /* -- Indexed access ------------------------------------------------------ */
994 /* Record bounds-check. */
995 static void rec_idx_abc(jit_State
*J
, TRef asizeref
, TRef ikey
, uint32_t asize
)
997 /* Try to emit invariant bounds checks. */
998 if ((J
->flags
& (JIT_F_OPT_LOOP
|JIT_F_OPT_ABC
)) ==
999 (JIT_F_OPT_LOOP
|JIT_F_OPT_ABC
)) {
1000 IRRef ref
= tref_ref(ikey
);
1001 IRIns
*ir
= IR(ref
);
1004 /* Handle constant offsets. */
1005 if (ir
->o
== IR_ADD
&& irref_isk(ir
->op2
)) {
1007 ofs
= IR(ofsref
)->i
;
1011 /* Got scalar evolution analysis results for this reference? */
1012 if (ref
== J
->scev
.idx
) {
1014 lua_assert(irt_isint(J
->scev
.t
) && ir
->o
== IR_SLOAD
);
1015 stop
= numberVint(&(J
->L
->base
- J
->baseslot
)[ir
->op1
+ FORL_STOP
]);
1016 /* Runtime value for stop of loop is within bounds? */
1017 if ((int64_t)stop
+ ofs
< (int64_t)asize
) {
1018 /* Emit invariant bounds check for stop. */
1019 emitir(IRTG(IR_ABC
, IRT_P32
), asizeref
, ofs
== 0 ? J
->scev
.stop
:
1020 emitir(IRTI(IR_ADD
), J
->scev
.stop
, ofsref
));
1021 /* Emit invariant bounds check for start, if not const or negative. */
1022 if (!(J
->scev
.dir
&& J
->scev
.start
&&
1023 (int64_t)IR(J
->scev
.start
)->i
+ ofs
>= 0))
1024 emitir(IRTG(IR_ABC
, IRT_P32
), asizeref
, ikey
);
1029 emitir(IRTGI(IR_ABC
), asizeref
, ikey
); /* Emit regular bounds check. */
1032 /* Record indexed key lookup. */
1033 static TRef
rec_idx_key(jit_State
*J
, RecordIndex
*ix
)
1036 GCtab
*t
= tabV(&ix
->tabv
);
1037 ix
->oldv
= lj_tab_get(J
->L
, t
, &ix
->keyv
); /* Lookup previous value. */
1039 /* Integer keys are looked up in the array part first. */
1041 if (tref_isnumber(key
)) {
1042 int32_t k
= numberVint(&ix
->keyv
);
1043 if (!tvisint(&ix
->keyv
) && numV(&ix
->keyv
) != (lua_Number
)k
)
1045 if ((MSize
)k
< LJ_MAX_ASIZE
) { /* Potential array key? */
1046 TRef ikey
= lj_opt_narrow_index(J
, key
);
1047 TRef asizeref
= emitir(IRTI(IR_FLOAD
), ix
->tab
, IRFL_TAB_ASIZE
);
1048 if ((MSize
)k
< t
->asize
) { /* Currently an array key? */
1050 rec_idx_abc(J
, asizeref
, ikey
, t
->asize
);
1051 arrayref
= emitir(IRT(IR_FLOAD
, IRT_P32
), ix
->tab
, IRFL_TAB_ARRAY
);
1052 return emitir(IRT(IR_AREF
, IRT_P32
), arrayref
, ikey
);
1053 } else { /* Currently not in array (may be an array extension)? */
1054 emitir(IRTGI(IR_ULE
), asizeref
, ikey
); /* Inv. bounds check. */
1055 if (k
== 0 && tref_isk(key
))
1056 key
= lj_ir_knum_zero(J
); /* Canonicalize 0 or +-0.0 to +0.0. */
1057 /* And continue with the hash lookup. */
1059 } else if (!tref_isk(key
)) {
1060 /* We can rule out const numbers which failed the integerness test
1061 ** above. But all other numbers are potential array keys.
1063 if (t
->asize
== 0) { /* True sparse tables have an empty array part. */
1064 /* Guard that the array part stays empty. */
1065 TRef tmp
= emitir(IRTI(IR_FLOAD
), ix
->tab
, IRFL_TAB_ASIZE
);
1066 emitir(IRTGI(IR_EQ
), tmp
, lj_ir_kint(J
, 0));
1068 lj_trace_err(J
, LJ_TRERR_NYITMIX
);
1073 /* Otherwise the key is located in the hash part. */
1074 if (t
->hmask
== 0) { /* Shortcut for empty hash part. */
1075 /* Guard that the hash part stays empty. */
1076 TRef tmp
= emitir(IRTI(IR_FLOAD
), ix
->tab
, IRFL_TAB_HMASK
);
1077 emitir(IRTGI(IR_EQ
), tmp
, lj_ir_kint(J
, 0));
1078 return lj_ir_kkptr(J
, niltvg(J2G(J
)));
1080 if (tref_isinteger(key
)) /* Hash keys are based on numbers, not ints. */
1081 ix
->key
= key
= emitir(IRTN(IR_CONV
), key
, IRCONV_NUM_INT
);
1082 if (tref_isk(key
)) {
1083 /* Optimize lookup of constant hash keys. */
1084 MSize hslot
= (MSize
)((char *)ix
->oldv
- (char *)&noderef(t
->node
)[0].val
);
1085 if (t
->hmask
> 0 && hslot
<= t
->hmask
*(MSize
)sizeof(Node
) &&
1086 hslot
<= 65535*(MSize
)sizeof(Node
)) {
1088 TRef hm
= emitir(IRTI(IR_FLOAD
), ix
->tab
, IRFL_TAB_HMASK
);
1089 emitir(IRTGI(IR_EQ
), hm
, lj_ir_kint(J
, (int32_t)t
->hmask
));
1090 node
= emitir(IRT(IR_FLOAD
, IRT_P32
), ix
->tab
, IRFL_TAB_NODE
);
1091 kslot
= lj_ir_kslot(J
, key
, hslot
/ sizeof(Node
));
1092 return emitir(IRTG(IR_HREFK
, IRT_P32
), node
, kslot
);
1095 /* Fall back to a regular hash lookup. */
1096 return emitir(IRT(IR_HREF
, IRT_P32
), ix
->tab
, key
);
1099 /* Determine whether a key is NOT one of the fast metamethod names. */
1100 static int nommstr(jit_State
*J
, TRef key
)
1102 if (tref_isstr(key
)) {
1103 if (tref_isk(key
)) {
1104 GCstr
*str
= ir_kstr(IR(tref_ref(key
)));
1106 for (mm
= 0; mm
<= MM_FAST
; mm
++)
1107 if (mmname_str(J2G(J
), mm
) == str
)
1108 return 0; /* MUST be one the fast metamethod names. */
1110 return 0; /* Variable string key MAY be a metamethod name. */
1113 return 1; /* CANNOT be a metamethod name. */
1116 /* Record indexed load/store. */
1117 TRef
lj_record_idx(jit_State
*J
, RecordIndex
*ix
)
1120 IROp xrefop
, loadop
;
1123 while (!tref_istab(ix
->tab
)) { /* Handle non-table lookup. */
1124 /* Never call raw lj_record_idx() on non-table. */
1125 lua_assert(ix
->idxchain
!= 0);
1126 if (!lj_record_mm_lookup(J
, ix
, ix
->val
? MM_newindex
: MM_index
))
1127 lj_trace_err(J
, LJ_TRERR_NOMM
);
1129 if (tref_isfunc(ix
->mobj
)) { /* Handle metamethod call. */
1130 BCReg func
= rec_mm_prep(J
, ix
->val
? lj_cont_nop
: lj_cont_ra
);
1131 TRef
*base
= J
->base
+ func
;
1132 TValue
*tv
= J
->L
->base
+ func
;
1133 base
[0] = ix
->mobj
; base
[1] = ix
->tab
; base
[2] = ix
->key
;
1134 setfuncV(J
->L
, tv
+0, funcV(&ix
->mobjv
));
1135 copyTV(J
->L
, tv
+1, &ix
->tabv
);
1136 copyTV(J
->L
, tv
+2, &ix
->keyv
);
1139 copyTV(J
->L
, tv
+3, &ix
->valv
);
1140 lj_record_call(J
, func
, 3); /* mobj(tab, key, val) */
1143 lj_record_call(J
, func
, 2); /* res = mobj(tab, key) */
1144 return 0; /* No result yet. */
1147 /* Otherwise retry lookup with metaobject. */
1149 copyTV(J
->L
, &ix
->tabv
, &ix
->mobjv
);
1150 if (--ix
->idxchain
== 0)
1151 lj_trace_err(J
, LJ_TRERR_IDXLOOP
);
1154 /* First catch nil and NaN keys for tables. */
1155 if (tvisnil(&ix
->keyv
) || (tvisnum(&ix
->keyv
) && tvisnan(&ix
->keyv
))) {
1156 if (ix
->val
) /* Better fail early. */
1157 lj_trace_err(J
, LJ_TRERR_STORENN
);
1158 if (tref_isk(ix
->key
)) {
1159 if (ix
->idxchain
&& lj_record_mm_lookup(J
, ix
, MM_index
))
1165 /* Record the key lookup. */
1166 xref
= rec_idx_key(J
, ix
);
1167 xrefop
= IR(tref_ref(xref
))->o
;
1168 loadop
= xrefop
== IR_AREF
? IR_ALOAD
: IR_HLOAD
;
1169 /* The lj_meta_tset() inconsistency is gone, but better play safe. */
1170 oldv
= xrefop
== IR_KKPTR
? (cTValue
*)ir_kptr(IR(tref_ref(xref
))) : ix
->oldv
;
1172 if (ix
->val
== 0) { /* Indexed load */
1173 IRType t
= itype2irt(oldv
);
1175 if (oldv
== niltvg(J2G(J
))) {
1176 emitir(IRTG(IR_EQ
, IRT_P32
), xref
, lj_ir_kkptr(J
, niltvg(J2G(J
))));
1179 res
= emitir(IRTG(loadop
, t
), xref
, 0);
1181 if (t
== IRT_NIL
&& ix
->idxchain
&& lj_record_mm_lookup(J
, ix
, MM_index
))
1183 if (irtype_ispri(t
)) res
= TREF_PRI(t
); /* Canonicalize primitives. */
1185 } else { /* Indexed store. */
1186 GCtab
*mt
= tabref(tabV(&ix
->tabv
)->metatable
);
1187 int keybarrier
= tref_isgcv(ix
->key
) && !tref_isnil(ix
->val
);
1188 if (tvisnil(oldv
)) { /* Previous value was nil? */
1189 /* Need to duplicate the hasmm check for the early guards. */
1191 if (ix
->idxchain
&& mt
) {
1192 cTValue
*mo
= lj_tab_getstr(mt
, mmname_str(J2G(J
), MM_newindex
));
1193 hasmm
= mo
&& !tvisnil(mo
);
1196 emitir(IRTG(loadop
, IRT_NIL
), xref
, 0); /* Guard for nil value. */
1197 else if (xrefop
== IR_HREF
)
1198 emitir(IRTG(oldv
== niltvg(J2G(J
)) ? IR_EQ
: IR_NE
, IRT_P32
),
1199 xref
, lj_ir_kkptr(J
, niltvg(J2G(J
))));
1200 if (ix
->idxchain
&& lj_record_mm_lookup(J
, ix
, MM_newindex
)) {
1205 if (oldv
== niltvg(J2G(J
))) { /* Need to insert a new key. */
1207 if (tref_isinteger(key
)) /* NEWREF needs a TValue as a key. */
1208 key
= emitir(IRTN(IR_CONV
), key
, IRCONV_NUM_INT
);
1209 xref
= emitir(IRT(IR_NEWREF
, IRT_P32
), ix
->tab
, key
);
1210 keybarrier
= 0; /* NEWREF already takes care of the key barrier. */
1212 } else if (!lj_opt_fwd_wasnonnil(J
, loadop
, tref_ref(xref
))) {
1213 /* Cannot derive that the previous value was non-nil, must do checks. */
1214 if (xrefop
== IR_HREF
) /* Guard against store to niltv. */
1215 emitir(IRTG(IR_NE
, IRT_P32
), xref
, lj_ir_kkptr(J
, niltvg(J2G(J
))));
1216 if (ix
->idxchain
) { /* Metamethod lookup required? */
1217 /* A check for NULL metatable is cheaper (hoistable) than a load. */
1219 TRef mtref
= emitir(IRT(IR_FLOAD
, IRT_TAB
), ix
->tab
, IRFL_TAB_META
);
1220 emitir(IRTG(IR_EQ
, IRT_TAB
), mtref
, lj_ir_knull(J
, IRT_TAB
));
1222 IRType t
= itype2irt(oldv
);
1223 emitir(IRTG(loadop
, t
), xref
, 0); /* Guard for non-nil value. */
1227 keybarrier
= 0; /* Previous non-nil value kept the key alive. */
1229 /* Convert int to number before storing. */
1230 if (!LJ_DUALNUM
&& tref_isinteger(ix
->val
))
1231 ix
->val
= emitir(IRTN(IR_CONV
), ix
->val
, IRCONV_NUM_INT
);
1232 emitir(IRT(loadop
+IRDELTA_L2S
, tref_type(ix
->val
)), xref
, ix
->val
);
1233 if (keybarrier
|| tref_isgcv(ix
->val
))
1234 emitir(IRT(IR_TBAR
, IRT_NIL
), ix
->tab
, 0);
1235 /* Invalidate neg. metamethod cache for stores with certain string keys. */
1236 if (!nommstr(J
, ix
->key
)) {
1237 TRef fref
= emitir(IRT(IR_FREF
, IRT_P32
), ix
->tab
, IRFL_TAB_NOMM
);
1238 emitir(IRT(IR_FSTORE
, IRT_U8
), fref
, lj_ir_kint(J
, 0));
1245 /* -- Upvalue access ------------------------------------------------------ */
1247 /* Record upvalue load/store. */
1248 static TRef
rec_upvalue(jit_State
*J
, uint32_t uv
, TRef val
)
1250 GCupval
*uvp
= &gcref(J
->fn
->l
.uvptr
[uv
])->uv
;
1251 TRef fn
= getcurrf(J
);
1253 int needbarrier
= 0;
1254 /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
1255 uv
= (uv
<< 8) | (hashrot(uvp
->dhash
, uvp
->dhash
+ HASH_BIAS
) & 0xff);
1257 /* In current stack? */
1258 if (uvval(uvp
) >= tvref(J
->L
->stack
) &&
1259 uvval(uvp
) < tvref(J
->L
->maxstack
)) {
1260 int32_t slot
= (int32_t)(uvval(uvp
) - (J
->L
->base
- J
->baseslot
));
1261 if (slot
>= 0) { /* Aliases an SSA slot? */
1262 slot
-= (int32_t)J
->baseslot
; /* Note: slot number may be negative! */
1263 /* NYI: add IR to guard that it's still aliasing the same slot. */
1265 return getslot(J
, slot
);
1267 J
->base
[slot
] = val
;
1268 if (slot
>= (int32_t)J
->maxslot
) J
->maxslot
= (BCReg
)(slot
+1);
1273 uref
= tref_ref(emitir(IRTG(IR_UREFO
, IRT_P32
), fn
, uv
));
1276 uref
= tref_ref(emitir(IRTG(IR_UREFC
, IRT_P32
), fn
, uv
));
1278 if (val
== 0) { /* Upvalue load */
1279 IRType t
= itype2irt(uvval(uvp
));
1280 TRef res
= emitir(IRTG(IR_ULOAD
, t
), uref
, 0);
1281 if (irtype_ispri(t
)) res
= TREF_PRI(t
); /* Canonicalize primitive refs. */
1283 } else { /* Upvalue store. */
1284 /* Convert int to number before storing. */
1285 if (!LJ_DUALNUM
&& tref_isinteger(val
))
1286 val
= emitir(IRTN(IR_CONV
), val
, IRCONV_NUM_INT
);
1287 emitir(IRT(IR_USTORE
, tref_type(val
)), uref
, val
);
1288 if (needbarrier
&& tref_isgcv(val
))
1289 emitir(IRT(IR_OBAR
, IRT_NIL
), uref
, val
);
1295 /* -- Record calls to Lua functions --------------------------------------- */
1297 /* Check unroll limits for calls. */
1298 static void check_call_unroll(jit_State
*J
, TraceNo lnk
)
1300 IRRef fref
= tref_ref(J
->base
[-1]);
1303 for (s
= J
->baseslot
- 1; s
> 0; s
--)
1304 if ((J
->slot
[s
] & TREF_FRAME
) && tref_ref(J
->slot
[s
]) == fref
)
1306 if (J
->pc
== J
->startpc
) {
1307 if (count
+ J
->tailcalled
> J
->param
[JIT_P_recunroll
]) {
1309 if (J
->framedepth
+ J
->retdepth
== 0)
1310 rec_stop(J
, LJ_TRLINK_TAILREC
, J
->cur
.traceno
); /* Tail-recursion. */
1312 rec_stop(J
, LJ_TRLINK_UPREC
, J
->cur
.traceno
); /* Up-recursion. */
1315 if (count
> J
->param
[JIT_P_callunroll
]) {
1316 if (lnk
) { /* Possible tail- or up-recursion. */
1317 lj_trace_flush(J
, lnk
); /* Flush trace that only returns. */
1318 /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
1319 hotcount_set(J2GG(J
), J
->pc
+1, LJ_PRNG_BITS(J
, 4));
1321 lj_trace_err(J
, LJ_TRERR_CUNROLL
);
1326 /* Record Lua function setup. */
1327 static void rec_func_setup(jit_State
*J
)
1329 GCproto
*pt
= J
->pt
;
1330 BCReg s
, numparams
= pt
->numparams
;
1331 if ((pt
->flags
& PROTO_NOJIT
))
1332 lj_trace_err(J
, LJ_TRERR_CJITOFF
);
1333 if (J
->baseslot
+ pt
->framesize
>= LJ_MAX_JSLOTS
)
1334 lj_trace_err(J
, LJ_TRERR_STACKOV
);
1335 /* Fill up missing parameters with nil. */
1336 for (s
= J
->maxslot
; s
< numparams
; s
++)
1337 J
->base
[s
] = TREF_NIL
;
1338 /* The remaining slots should never be read before they are written. */
1339 J
->maxslot
= numparams
;
1342 /* Record Lua vararg function setup. */
1343 static void rec_func_vararg(jit_State
*J
)
1345 GCproto
*pt
= J
->pt
;
1346 BCReg s
, fixargs
, vframe
= J
->maxslot
+1;
1347 lua_assert((pt
->flags
& PROTO_VARARG
));
1348 if (J
->baseslot
+ vframe
+ pt
->framesize
>= LJ_MAX_JSLOTS
)
1349 lj_trace_err(J
, LJ_TRERR_STACKOV
);
1350 J
->base
[vframe
-1] = J
->base
[-1]; /* Copy function up. */
1351 /* Copy fixarg slots up and set their original slots to nil. */
1352 fixargs
= pt
->numparams
< J
->maxslot
? pt
->numparams
: J
->maxslot
;
1353 for (s
= 0; s
< fixargs
; s
++) {
1354 J
->base
[vframe
+s
] = J
->base
[s
];
1355 J
->base
[s
] = TREF_NIL
;
1357 J
->maxslot
= fixargs
;
1360 J
->baseslot
+= vframe
;
1363 /* Record entry to a Lua function. */
1364 static void rec_func_lua(jit_State
*J
)
1367 check_call_unroll(J
, 0);
1370 /* Record entry to an already compiled function. */
1371 static void rec_func_jit(jit_State
*J
, TraceNo lnk
)
1375 T
= traceref(J
, lnk
);
1376 if (T
->linktype
== LJ_TRLINK_RETURN
) { /* Trace returns to interpreter? */
1377 check_call_unroll(J
, lnk
);
1378 /* Temporarily unpatch JFUNC* to continue recording across function. */
1379 J
->patchins
= *J
->pc
;
1380 J
->patchpc
= (BCIns
*)J
->pc
;
1381 *J
->patchpc
= T
->startins
;
1384 J
->instunroll
= 0; /* Cannot continue across a compiled function. */
1385 if (J
->pc
== J
->startpc
&& J
->framedepth
+ J
->retdepth
== 0)
1386 rec_stop(J
, LJ_TRLINK_TAILREC
, J
->cur
.traceno
); /* Extra tail-recursion. */
1388 rec_stop(J
, LJ_TRLINK_ROOT
, lnk
); /* Link to the function. */
1391 /* -- Vararg handling ----------------------------------------------------- */
1393 /* Detect y = select(x, ...) idiom. */
1394 static int select_detect(jit_State
*J
)
1396 BCIns ins
= J
->pc
[1];
1397 if (bc_op(ins
) == BC_CALLM
&& bc_b(ins
) == 2 && bc_c(ins
) == 1) {
1398 cTValue
*func
= &J
->L
->base
[bc_a(ins
)];
1399 if (tvisfunc(func
) && funcV(func
)->c
.ffid
== FF_select
)
1405 /* Record vararg instruction. */
1406 static void rec_varg(jit_State
*J
, BCReg dst
, ptrdiff_t nresults
)
1408 int32_t numparams
= J
->pt
->numparams
;
1409 ptrdiff_t nvararg
= frame_delta(J
->L
->base
-1) - numparams
- 1;
1410 lua_assert(frame_isvarg(J
->L
->base
-1));
1411 if (J
->framedepth
> 0) { /* Simple case: varargs defined on-trace. */
1413 if (nvararg
< 0) nvararg
= 0;
1414 if (nresults
== -1) {
1416 J
->maxslot
= dst
+ (BCReg
)nvararg
;
1417 } else if (dst
+ nresults
> J
->maxslot
) {
1418 J
->maxslot
= dst
+ (BCReg
)nresults
;
1420 for (i
= 0; i
< nresults
; i
++) {
1421 J
->base
[dst
+i
] = i
< nvararg
? J
->base
[i
- nvararg
- 1] : TREF_NIL
;
1422 lua_assert(J
->base
[dst
+i
] != 0);
1424 } else { /* Unknown number of varargs passed to trace. */
1425 TRef fr
= emitir(IRTI(IR_SLOAD
), 0, IRSLOAD_READONLY
|IRSLOAD_FRAME
);
1426 int32_t frofs
= 8*(1+numparams
)+FRAME_VARG
;
1427 if (nresults
>= 0) { /* Known fixed number of results. */
1430 ptrdiff_t nload
= nvararg
>= nresults
? nresults
: nvararg
;
1432 if (nvararg
>= nresults
)
1433 emitir(IRTGI(IR_GE
), fr
, lj_ir_kint(J
, frofs
+8*(int32_t)nresults
));
1435 emitir(IRTGI(IR_EQ
), fr
, lj_ir_kint(J
, frame_ftsz(J
->L
->base
-1)));
1436 vbase
= emitir(IRTI(IR_SUB
), REF_BASE
, fr
);
1437 vbase
= emitir(IRT(IR_ADD
, IRT_P32
), vbase
, lj_ir_kint(J
, frofs
-8));
1438 for (i
= 0; i
< nload
; i
++) {
1439 IRType t
= itype2irt(&J
->L
->base
[i
-1-nvararg
]);
1440 TRef aref
= emitir(IRT(IR_AREF
, IRT_P32
),
1441 vbase
, lj_ir_kint(J
, (int32_t)i
));
1442 TRef tr
= emitir(IRTG(IR_VLOAD
, t
), aref
, 0);
1443 if (irtype_ispri(t
)) tr
= TREF_PRI(t
); /* Canonicalize primitives. */
1444 J
->base
[dst
+i
] = tr
;
1447 emitir(IRTGI(IR_LE
), fr
, lj_ir_kint(J
, frofs
));
1450 for (i
= nvararg
; i
< nresults
; i
++)
1451 J
->base
[dst
+i
] = TREF_NIL
;
1452 if (dst
+ (BCReg
)nresults
> J
->maxslot
)
1453 J
->maxslot
= dst
+ (BCReg
)nresults
;
1454 } else if (select_detect(J
)) { /* y = select(x, ...) */
1455 TRef tridx
= J
->base
[dst
-1];
1457 ptrdiff_t idx
= lj_ffrecord_select_mode(J
, tridx
, &J
->L
->base
[dst
-1]);
1458 if (idx
< 0) goto nyivarg
;
1459 if (idx
!= 0 && !tref_isinteger(tridx
))
1460 tridx
= emitir(IRTGI(IR_CONV
), tridx
, IRCONV_INT_NUM
|IRCONV_INDEX
);
1461 if (idx
!= 0 && tref_isk(tridx
)) {
1462 emitir(IRTGI(idx
<= nvararg
? IR_GE
: IR_LT
),
1463 fr
, lj_ir_kint(J
, frofs
+8*(int32_t)idx
));
1464 frofs
-= 8; /* Bias for 1-based index. */
1465 } else if (idx
<= nvararg
) { /* Compute size. */
1466 TRef tmp
= emitir(IRTI(IR_ADD
), fr
, lj_ir_kint(J
, -frofs
));
1468 emitir(IRTGI(IR_GE
), tmp
, lj_ir_kint(J
, 0));
1469 tr
= emitir(IRTI(IR_BSHR
), tmp
, lj_ir_kint(J
, 3));
1471 tridx
= emitir(IRTI(IR_ADD
), tridx
, lj_ir_kint(J
, -1));
1472 rec_idx_abc(J
, tr
, tridx
, (uint32_t)nvararg
);
1475 TRef tmp
= lj_ir_kint(J
, frofs
);
1477 TRef tmp2
= emitir(IRTI(IR_BSHL
), tridx
, lj_ir_kint(J
, 3));
1478 tmp
= emitir(IRTI(IR_ADD
), tmp2
, tmp
);
1480 tr
= lj_ir_kint(J
, 0);
1482 emitir(IRTGI(IR_LT
), fr
, tmp
);
1484 if (idx
!= 0 && idx
<= nvararg
) {
1486 TRef aref
, vbase
= emitir(IRTI(IR_SUB
), REF_BASE
, fr
);
1487 vbase
= emitir(IRT(IR_ADD
, IRT_P32
), vbase
, lj_ir_kint(J
, frofs
-8));
1488 t
= itype2irt(&J
->L
->base
[idx
-2-nvararg
]);
1489 aref
= emitir(IRT(IR_AREF
, IRT_P32
), vbase
, tridx
);
1490 tr
= emitir(IRTG(IR_VLOAD
, t
), aref
, 0);
1491 if (irtype_ispri(t
)) tr
= TREF_PRI(t
); /* Canonicalize primitives. */
1493 J
->base
[dst
-2] = tr
;
1495 J
->bcskip
= 2; /* Skip CALLM + select. */
1498 setintV(&J
->errinfo
, BC_VARG
);
1499 lj_trace_err_info(J
, LJ_TRERR_NYIBC
);
1504 /* -- Record allocations -------------------------------------------------- */
1506 static TRef
rec_tnew(jit_State
*J
, uint32_t ah
)
1508 uint32_t asize
= ah
& 0x7ff;
1509 uint32_t hbits
= ah
>> 11;
1510 if (asize
== 0x7ff) asize
= 0x801;
1511 return emitir(IRTG(IR_TNEW
, IRT_TAB
), asize
, hbits
);
1514 /* -- Record bytecode ops ------------------------------------------------- */
1516 /* Prepare for comparison. */
1517 static void rec_comp_prep(jit_State
*J
)
1519 /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
1520 if (J
->cur
.nsnap
== 1 && J
->cur
.snap
[0].ref
== J
->cur
.nins
)
1521 emitir_raw(IRT(IR_NOP
, IRT_NIL
), 0, 0);
1525 /* Fixup comparison. */
1526 static void rec_comp_fixup(jit_State
*J
, const BCIns
*pc
, int cond
)
1528 BCIns jmpins
= pc
[1];
1529 const BCIns
*npc
= pc
+ 2 + (cond
? bc_j(jmpins
) : 0);
1530 SnapShot
*snap
= &J
->cur
.snap
[J
->cur
.nsnap
-1];
1531 /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
1532 J
->cur
.snapmap
[snap
->mapofs
+ snap
->nent
] = SNAP_MKPC(npc
);
1534 if (bc_a(jmpins
) < J
->maxslot
) J
->maxslot
= bc_a(jmpins
);
1535 lj_snap_shrink(J
); /* Shrink last snapshot if possible. */
1538 /* Record the next bytecode instruction (_before_ it's executed). */
1539 void lj_record_ins(jit_State
*J
)
1548 /* Perform post-processing action before recording the next instruction. */
1549 if (LJ_UNLIKELY(J
->postproc
!= LJ_POST_NONE
)) {
1550 switch (J
->postproc
) {
1551 case LJ_POST_FIXCOMP
: /* Fixup comparison. */
1552 pc
= frame_pc(&J2G(J
)->tmptv
);
1553 rec_comp_fixup(J
, pc
, (!tvistruecond(&J2G(J
)->tmptv2
) ^ (bc_op(*pc
)&1)));
1555 case LJ_POST_FIXGUARD
: /* Fixup and emit pending guard. */
1556 if (!tvistruecond(&J2G(J
)->tmptv2
))
1557 J
->fold
.ins
.o
^= 1; /* Flip guard to opposite. */
1558 lj_opt_fold(J
); /* Emit pending guard. */
1560 case LJ_POST_FIXBOOL
:
1561 if (!tvistruecond(&J2G(J
)->tmptv2
)) {
1563 for (s
= 0; s
< J
->maxslot
; s
++) /* Fixup stack slot (if any). */
1564 if (J
->base
[s
] == TREF_TRUE
&& tvisfalse(&J
->L
->base
[s
])) {
1565 J
->base
[s
] = TREF_FALSE
;
1570 case LJ_POST_FFRETRY
: /* Suppress recording of retried fast function. */
1571 if (bc_op(*J
->pc
) >= BC__MAX
)
1574 default: lua_assert(0); break;
1576 J
->postproc
= LJ_POST_NONE
;
1579 /* Need snapshot before recording next bytecode (e.g. after a store). */
1587 /* Skip some bytecodes. */
1588 if (LJ_UNLIKELY(J
->bcskip
> 0)) {
1593 /* Record only closed loops for root traces. */
1595 if (J
->framedepth
== 0 &&
1596 (MSize
)((char *)pc
- (char *)J
->bc_min
) >= J
->bc_extent
)
1597 lj_trace_err(J
, LJ_TRERR_LLEAVE
);
1599 #ifdef LUA_USE_ASSERT
1604 /* Keep a copy of the runtime values of var/num/str operands. */
1605 #define rav (&ix.valv)
1606 #define rbv (&ix.tabv)
1607 #define rcv (&ix.keyv)
1614 switch (bcmode_a(op
)) {
1616 copyTV(J
->L
, rav
, &lbase
[ra
]); ix
.val
= ra
= getslot(J
, ra
); break;
1617 default: break; /* Handled later. */
1621 switch (bcmode_b(op
)) {
1622 case BCMnone
: rb
= 0; rc
= bc_d(ins
); break; /* Upgrade rc to 'rd'. */
1624 copyTV(J
->L
, rbv
, &lbase
[rb
]); ix
.tab
= rb
= getslot(J
, rb
); break;
1625 default: break; /* Handled later. */
1627 switch (bcmode_c(op
)) {
1629 copyTV(J
->L
, rcv
, &lbase
[rc
]); ix
.key
= rc
= getslot(J
, rc
); break;
1630 case BCMpri
: setitype(rcv
, ~rc
); ix
.key
= rc
= TREF_PRI(IRT_NIL
+rc
); break;
1631 case BCMnum
: { cTValue
*tv
= proto_knumtv(J
->pt
, rc
);
1632 copyTV(J
->L
, rcv
, tv
); ix
.key
= rc
= tvisint(tv
) ? lj_ir_kint(J
, intV(tv
)) :
1633 lj_ir_knumint(J
, numV(tv
)); } break;
1634 case BCMstr
: { GCstr
*s
= gco2str(proto_kgc(J
->pt
, ~(ptrdiff_t)rc
));
1635 setstrV(J
->L
, rcv
, s
); ix
.key
= rc
= lj_ir_kstr(J
, s
); } break;
1636 default: break; /* Handled later. */
1641 /* -- Comparison ops ---------------------------------------------------- */
1643 case BC_ISLT
: case BC_ISGE
: case BC_ISLE
: case BC_ISGT
:
1645 if (tref_iscdata(ra
) || tref_iscdata(rc
)) {
1646 rec_mm_comp_cdata(J
, &ix
, op
, ((int)op
& 2) ? MM_le
: MM_lt
);
1650 /* Emit nothing for two numeric or string consts. */
1651 if (!(tref_isk2(ra
,rc
) && tref_isnumber_str(ra
) && tref_isnumber_str(rc
))) {
1652 IRType ta
= tref_isinteger(ra
) ? IRT_INT
: tref_type(ra
);
1653 IRType tc
= tref_isinteger(rc
) ? IRT_INT
: tref_type(rc
);
1656 /* Widen mixed number/int comparisons to number/number comparison. */
1657 if (ta
== IRT_INT
&& tc
== IRT_NUM
) {
1658 ra
= emitir(IRTN(IR_CONV
), ra
, IRCONV_NUM_INT
);
1660 } else if (ta
== IRT_NUM
&& tc
== IRT_INT
) {
1661 rc
= emitir(IRTN(IR_CONV
), rc
, IRCONV_NUM_INT
);
1662 } else if (!((ta
== IRT_FALSE
|| ta
== IRT_TRUE
) &&
1663 (tc
== IRT_FALSE
|| tc
== IRT_TRUE
))) {
1664 break; /* Interpreter will throw for two different types. */
1668 irop
= (int)op
- (int)BC_ISLT
+ (int)IR_LT
;
1669 if (ta
== IRT_NUM
) {
1670 if ((irop
& 1)) irop
^= 4; /* ISGE/ISGT are unordered. */
1671 if (!lj_ir_numcmp(numberVnum(rav
), numberVnum(rcv
), (IROp
)irop
))
1673 } else if (ta
== IRT_INT
) {
1674 if (!lj_ir_numcmp(numberVnum(rav
), numberVnum(rcv
), (IROp
)irop
))
1676 } else if (ta
== IRT_STR
) {
1677 if (!lj_ir_strcmp(strV(rav
), strV(rcv
), (IROp
)irop
)) irop
^= 1;
1678 ra
= lj_ir_call(J
, IRCALL_lj_str_cmp
, ra
, rc
);
1679 rc
= lj_ir_kint(J
, 0);
1682 rec_mm_comp(J
, &ix
, (int)op
);
1685 emitir(IRTG(irop
, ta
), ra
, rc
);
1686 rec_comp_fixup(J
, J
->pc
, ((int)op
^ irop
) & 1);
1690 case BC_ISEQV
: case BC_ISNEV
:
1691 case BC_ISEQS
: case BC_ISNES
:
1692 case BC_ISEQN
: case BC_ISNEN
:
1693 case BC_ISEQP
: case BC_ISNEP
:
1695 if (tref_iscdata(ra
) || tref_iscdata(rc
)) {
1696 rec_mm_comp_cdata(J
, &ix
, op
, MM_eq
);
1700 /* Emit nothing for two non-table, non-udata consts. */
1701 if (!(tref_isk2(ra
, rc
) && !(tref_istab(ra
) || tref_isudata(ra
)))) {
1704 diff
= lj_record_objcmp(J
, ra
, rc
, rav
, rcv
);
1705 if (diff
== 1 && (tref_istab(ra
) || tref_isudata(ra
))) {
1706 /* Only check __eq if different, but the same type (table or udata). */
1707 rec_mm_equal(J
, &ix
, (int)op
);
1710 rec_comp_fixup(J
, J
->pc
, ((int)op
& 1) == !diff
);
1714 /* -- Unary test and copy ops ------------------------------------------- */
1716 case BC_ISTC
: case BC_ISFC
:
1717 if ((op
& 1) == tref_istruecond(rc
))
1718 rc
= 0; /* Don't store if condition is not true. */
1720 case BC_IST
: case BC_ISF
: /* Type specialization suffices. */
1721 if (bc_a(pc
[1]) < J
->maxslot
)
1722 J
->maxslot
= bc_a(pc
[1]); /* Shrink used slots. */
1725 /* -- Unary ops --------------------------------------------------------- */
1728 /* Type specialization already forces const result. */
1729 rc
= tref_istruecond(rc
) ? TREF_FALSE
: TREF_TRUE
;
1734 rc
= emitir(IRTI(IR_FLOAD
), rc
, IRFL_STR_LEN
);
1735 #ifndef LUAJIT_ENABLE_LUA52COMPAT
1736 else if (tref_istab(rc
))
1737 rc
= lj_ir_call(J
, IRCALL_lj_tab_len
, rc
);
1740 rc
= rec_mm_len(J
, rc
, rcv
);
1743 /* -- Arithmetic ops ---------------------------------------------------- */
1746 if (tref_isnumber_str(rc
)) {
1747 rc
= lj_opt_narrow_unm(J
, rc
, rcv
);
1750 copyTV(J
->L
, &ix
.tabv
, rcv
);
1751 rc
= rec_mm_arith(J
, &ix
, MM_unm
);
1755 case BC_ADDNV
: case BC_SUBNV
: case BC_MULNV
: case BC_DIVNV
: case BC_MODNV
:
1756 /* Swap rb/rc and rbv/rcv. rav is temp. */
1757 ix
.tab
= rc
; ix
.key
= rc
= rb
; rb
= ix
.tab
;
1758 copyTV(J
->L
, rav
, rbv
);
1759 copyTV(J
->L
, rbv
, rcv
);
1760 copyTV(J
->L
, rcv
, rav
);
1764 case BC_ADDVN
: case BC_SUBVN
: case BC_MULVN
: case BC_DIVVN
:
1765 case BC_ADDVV
: case BC_SUBVV
: case BC_MULVV
: case BC_DIVVV
: {
1766 MMS mm
= bcmode_mm(op
);
1767 if (tref_isnumber_str(rb
) && tref_isnumber_str(rc
))
1768 rc
= lj_opt_narrow_arith(J
, rb
, rc
, rbv
, rcv
,
1769 (int)mm
- (int)MM_add
+ (int)IR_ADD
);
1771 rc
= rec_mm_arith(J
, &ix
, mm
);
1775 case BC_MODVN
: case BC_MODVV
:
1777 if (tref_isnumber_str(rb
) && tref_isnumber_str(rc
))
1778 rc
= lj_opt_narrow_mod(J
, rb
, rc
, rcv
);
1780 rc
= rec_mm_arith(J
, &ix
, MM_mod
);
1784 if (tref_isnumber_str(rb
) && tref_isnumber_str(rc
))
1785 rc
= lj_opt_narrow_pow(J
, lj_ir_tonum(J
, rb
), rc
, rcv
);
1787 rc
= rec_mm_arith(J
, &ix
, MM_pow
);
1790 /* -- Constant and move ops --------------------------------------------- */
1793 /* Clear gap of method call to avoid resurrecting previous refs. */
1794 if (ra
> J
->maxslot
) J
->base
[ra
-1] = 0;
1796 case BC_KSTR
: case BC_KNUM
: case BC_KPRI
:
1799 rc
= lj_ir_kint(J
, (int32_t)(int16_t)rc
);
1803 J
->base
[ra
++] = TREF_NIL
;
1804 if (rc
>= J
->maxslot
) J
->maxslot
= rc
+1;
1808 rc
= lj_ir_kgc(J
, proto_kgc(J
->pt
, ~(ptrdiff_t)rc
), IRT_CDATA
);
1812 /* -- Upvalue and function ops ------------------------------------------ */
1815 rc
= rec_upvalue(J
, rc
, 0);
1817 case BC_USETV
: case BC_USETS
: case BC_USETN
: case BC_USETP
:
1818 rec_upvalue(J
, ra
, rc
);
1821 /* -- Table ops --------------------------------------------------------- */
1823 case BC_GGET
: case BC_GSET
:
1824 settabV(J
->L
, &ix
.tabv
, tabref(J
->fn
->l
.env
));
1825 ix
.tab
= emitir(IRT(IR_FLOAD
, IRT_TAB
), getcurrf(J
), IRFL_FUNC_ENV
);
1826 ix
.idxchain
= LJ_MAX_IDXCHAIN
;
1827 rc
= lj_record_idx(J
, &ix
);
1830 case BC_TGETB
: case BC_TSETB
:
1831 setintV(&ix
.keyv
, (int32_t)rc
);
1832 ix
.key
= lj_ir_kint(J
, (int32_t)rc
);
1834 case BC_TGETV
: case BC_TGETS
: case BC_TSETV
: case BC_TSETS
:
1835 ix
.idxchain
= LJ_MAX_IDXCHAIN
;
1836 rc
= lj_record_idx(J
, &ix
);
1840 rc
= rec_tnew(J
, rc
);
1843 rc
= emitir(IRTG(IR_TDUP
, IRT_TAB
),
1844 lj_ir_ktab(J
, gco2tab(proto_kgc(J
->pt
, ~(ptrdiff_t)rc
))), 0);
1847 /* -- Calls and vararg handling ----------------------------------------- */
1850 J
->base
[ra
] = getslot(J
, ra
-3);
1851 J
->base
[ra
+1] = getslot(J
, ra
-2);
1852 J
->base
[ra
+2] = getslot(J
, ra
-1);
1853 { /* Do the actual copy now because lj_record_call needs the values. */
1854 TValue
*b
= &J
->L
->base
[ra
];
1855 copyTV(J
->L
, b
, b
-3);
1856 copyTV(J
->L
, b
+1, b
-2);
1857 copyTV(J
->L
, b
+2, b
-1);
1859 lj_record_call(J
, ra
, (ptrdiff_t)rc
-1);
1862 /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
1864 rc
= (BCReg
)(J
->L
->top
- J
->L
->base
) - ra
;
1867 lj_record_call(J
, ra
, (ptrdiff_t)rc
-1);
1871 rc
= (BCReg
)(J
->L
->top
- J
->L
->base
) - ra
;
1874 lj_record_tailcall(J
, ra
, (ptrdiff_t)rc
-1);
1878 rec_varg(J
, ra
, (ptrdiff_t)rb
-1);
1881 /* -- Returns ----------------------------------------------------------- */
1884 /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
1885 rc
= (BCReg
)(J
->L
->top
- J
->L
->base
) - ra
+ 1;
1887 case BC_RET
: case BC_RET0
: case BC_RET1
:
1888 lj_record_ret(J
, ra
, (ptrdiff_t)rc
-1);
1891 /* -- Loops and branches ------------------------------------------------ */
1894 if (rec_for(J
, pc
, 0) != LOOPEV_LEAVE
)
1895 J
->loopref
= J
->cur
.nins
;
1898 lua_assert(bc_op(pc
[(ptrdiff_t)rc
-BCBIAS_J
]) == BC_JFORL
);
1899 if (rec_for(J
, pc
, 0) != LOOPEV_LEAVE
) /* Link to existing loop. */
1900 rec_stop(J
, LJ_TRLINK_ROOT
, bc_d(pc
[(ptrdiff_t)rc
-BCBIAS_J
]));
1901 /* Continue tracing if the loop is not entered. */
1905 rec_loop_interp(J
, pc
, rec_for(J
, pc
+((ptrdiff_t)rc
-BCBIAS_J
), 1));
1908 rec_loop_interp(J
, pc
, rec_iterl(J
, *pc
));
1911 rec_loop_interp(J
, pc
, rec_loop(J
, ra
));
1915 rec_loop_jit(J
, rc
, rec_for(J
, pc
+bc_j(traceref(J
, rc
)->startins
), 1));
1918 rec_loop_jit(J
, rc
, rec_iterl(J
, traceref(J
, rc
)->startins
));
1921 rec_loop_jit(J
, rc
, rec_loop(J
, ra
));
1929 lj_trace_err(J
, LJ_TRERR_BLACKL
);
1933 if (ra
< J
->maxslot
)
1934 J
->maxslot
= ra
; /* Shrink used slots. */
1937 /* -- Function headers -------------------------------------------------- */
1943 rec_func_jit(J
, rc
);
1951 lua_assert(0); /* Cannot happen. No hotcall counting for varag funcs. */
1956 lj_ffrecord_func(J
);
1960 if (op
>= BC__MAX
) {
1961 lj_ffrecord_func(J
);
1971 setintV(&J
->errinfo
, (int32_t)op
);
1972 lj_trace_err_info(J
, LJ_TRERR_NYIBC
);
1976 /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
1977 if (bcmode_a(op
) == BCMdst
&& rc
) {
1979 if (ra
>= J
->maxslot
) J
->maxslot
= ra
+1;
1986 /* Limit the number of recorded IR instructions. */
1987 if (J
->cur
.nins
> REF_FIRST
+(IRRef
)J
->param
[JIT_P_maxrecord
])
1988 lj_trace_err(J
, LJ_TRERR_TRACEOV
);
1991 /* -- Recording setup ----------------------------------------------------- */
1993 /* Setup recording for a root trace started by a hot loop. */
1994 static const BCIns
*rec_setup_root(jit_State
*J
)
1996 /* Determine the next PC and the bytecode range for the loop. */
1997 const BCIns
*pcj
, *pc
= J
->pc
;
1999 BCReg ra
= bc_a(ins
);
2000 switch (bc_op(ins
)) {
2002 J
->bc_extent
= (MSize
)(-bc_j(ins
))*sizeof(BCIns
);
2007 lua_assert(bc_op(pc
[-1]) == BC_ITERC
);
2008 J
->maxslot
= ra
+ bc_b(pc
[-1]) - 1;
2009 J
->bc_extent
= (MSize
)(-bc_j(ins
))*sizeof(BCIns
);
2011 lua_assert(bc_op(pc
[-1]) == BC_JMP
);
2015 /* Only check BC range for real loops, but not for "repeat until true". */
2016 pcj
= pc
+ bc_j(ins
);
2018 if (bc_op(ins
) == BC_JMP
&& bc_j(ins
) < 0) {
2019 J
->bc_min
= pcj
+1 + bc_j(ins
);
2020 J
->bc_extent
= (MSize
)(-bc_j(ins
))*sizeof(BCIns
);
2028 /* No bytecode range check for down-recursive root traces. */
2029 J
->maxslot
= ra
+ bc_d(ins
);
2032 /* No bytecode range check for root traces started by a hot call. */
2033 J
->maxslot
= J
->pt
->numparams
;
2043 /* Setup recording for a side trace. */
2044 static void rec_setup_side(jit_State
*J
, GCtrace
*T
)
2046 SnapShot
*snap
= &T
->snap
[J
->exitno
];
2047 SnapEntry
*map
= &T
->snapmap
[snap
->mapofs
];
2048 MSize n
, nent
= snap
->nent
;
2049 BloomFilter seen
= 0;
2050 /* Emit IR for slots inherited from parent snapshot. */
2051 for (n
= 0; n
< nent
; n
++) {
2052 SnapEntry sn
= map
[n
];
2053 IRRef ref
= snap_ref(sn
);
2054 BCReg s
= snap_slot(sn
);
2055 IRIns
*ir
= &T
->ir
[ref
];
2056 IRType t
= irt_type(ir
->t
);
2058 /* The bloom filter avoids O(nent^2) overhead for de-duping slots. */
2059 if (bloomtest(seen
, ref
)) {
2061 for (j
= 0; j
< n
; j
++)
2062 if (snap_ref(map
[j
]) == ref
) {
2063 tr
= J
->slot
[snap_slot(map
[j
])];
2067 bloomset(seen
, ref
);
2068 switch ((IROp
)ir
->o
) {
2069 /* Only have to deal with constants that can occur in stack slots. */
2070 case IR_KPRI
: tr
= TREF_PRI(t
); break;
2071 case IR_KINT
: tr
= lj_ir_kint(J
, ir
->i
); break;
2072 case IR_KGC
: tr
= lj_ir_kgc(J
, ir_kgc(ir
), irt_t(ir
->t
)); break;
2073 case IR_KNUM
: tr
= lj_ir_k64(J
, IR_KNUM
, ir_knum(ir
)); break;
2074 case IR_KINT64
: tr
= lj_ir_k64(J
, IR_KINT64
, ir_kint64(ir
)); break;
2075 case IR_KPTR
: tr
= lj_ir_kptr(J
, ir_kptr(ir
)); break; /* Continuation. */
2076 /* Inherited SLOADs don't need a guard or type check. */
2078 if (LJ_SOFTFP
&& (sn
& SNAP_SOFTFPNUM
)) t
= IRT_NUM
;
2079 tr
= emitir_raw(IRT(IR_SLOAD
, t
), s
,
2080 (ir
->op2
&IRSLOAD_READONLY
) | IRSLOAD_INHERIT
|IRSLOAD_PARENT
);
2082 /* Parent refs are already typed and don't need a guard. */
2084 if (LJ_SOFTFP
&& (sn
& SNAP_SOFTFPNUM
)) t
= IRT_NUM
;
2085 tr
= emitir_raw(IRT(IR_SLOAD
, t
), s
, IRSLOAD_INHERIT
|IRSLOAD_PARENT
);
2089 J
->slot
[s
] = tr
| (sn
&(SNAP_CONT
|SNAP_FRAME
)); /* Same as TREF_* flags. */
2090 if ((sn
& SNAP_FRAME
))
2093 J
->base
= J
->slot
+ J
->baseslot
;
2094 J
->maxslot
= snap
->nslots
- J
->baseslot
;
2095 J
->framedepth
= snap
->depth
;
2099 /* Setup for recording a new trace. */
2100 void lj_record_setup(jit_State
*J
)
2104 /* Initialize state related to current trace. */
2105 memset(J
->slot
, 0, sizeof(J
->slot
));
2106 memset(J
->chain
, 0, sizeof(J
->chain
));
2107 memset(J
->bpropcache
, 0, sizeof(J
->bpropcache
));
2108 J
->scev
.idx
= REF_NIL
;
2110 J
->baseslot
= 1; /* Invoking function is at base[-1]. */
2111 J
->base
= J
->slot
+ J
->baseslot
;
2116 J
->instunroll
= J
->param
[JIT_P_instunroll
];
2117 J
->loopunroll
= J
->param
[JIT_P_loopunroll
];
2121 J
->bc_min
= NULL
; /* Means no limit. */
2122 J
->bc_extent
= ~(MSize
)0;
2124 /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2125 emitir_raw(IRT(IR_BASE
, IRT_P32
), J
->parent
, J
->exitno
);
2126 for (i
= 0; i
<= 2; i
++) {
2127 IRIns
*ir
= IR(REF_NIL
-i
);
2129 ir
->t
.irt
= (uint8_t)(IRT_NIL
+i
);
2133 J
->cur
.nk
= REF_TRUE
;
2136 setmref(J
->cur
.startpc
, J
->pc
);
2137 if (J
->parent
) { /* Side trace. */
2138 GCtrace
*T
= traceref(J
, J
->parent
);
2139 TraceNo root
= T
->root
? T
->root
: J
->parent
;
2140 J
->cur
.root
= (uint16_t)root
;
2141 J
->cur
.startins
= BCINS_AD(BC_JMP
, 0, 0);
2142 /* Check whether we could at least potentially form an extra loop. */
2143 if (J
->exitno
== 0 && T
->snap
[0].nent
== 0) {
2144 /* We can narrow a FORL for some side traces, too. */
2145 if (J
->pc
> proto_bc(J
->pt
) && bc_op(J
->pc
[-1]) == BC_JFORI
&&
2146 bc_d(J
->pc
[bc_j(J
->pc
[-1])-1]) == root
) {
2148 rec_for_loop(J
, J
->pc
-1, &J
->scev
, 1);
2152 J
->startpc
= NULL
; /* Prevent forming an extra loop. */
2154 rec_setup_side(J
, T
);
2156 if (traceref(J
, J
->cur
.root
)->nchild
>= J
->param
[JIT_P_maxside
] ||
2157 T
->snap
[J
->exitno
].count
>= J
->param
[JIT_P_hotexit
] +
2158 J
->param
[JIT_P_tryside
]) {
2159 rec_stop(J
, LJ_TRLINK_INTERP
, 0);
2161 } else { /* Root trace. */
2163 J
->cur
.startins
= *J
->pc
;
2164 J
->pc
= rec_setup_root(J
);
2165 /* Note: the loop instruction itself is recorded at the end and not
2166 ** at the start! So snapshot #0 needs to point to the *next* instruction.
2169 if (bc_op(J
->cur
.startins
) == BC_FORL
)
2170 rec_for_loop(J
, J
->pc
-1, &J
->scev
, 1);
2171 if (1 + J
->pt
->framesize
>= LJ_MAX_JSLOTS
)
2172 lj_trace_err(J
, LJ_TRERR_STACKOV
);
2174 #ifdef LUAJIT_ENABLE_CHECKHOOK
2175 /* Regularly check for instruction/line hooks from compiled code and
2176 ** exit to the interpreter if the hooks are set.
2178 ** This is a compile-time option and disabled by default, since the
2179 ** hook checks may be quite expensive in tight loops.
2181 ** Note this is only useful if hooks are *not* set most of the time.
2182 ** Use this only if you want to *asynchronously* interrupt the execution.
2184 ** You can set the instruction hook via lua_sethook() with a count of 1
2185 ** from a signal handler or another native thread. Please have a look
2186 ** at the first few functions in luajit.c for an example (Ctrl-C handler).
2189 TRef tr
= emitir(IRT(IR_XLOAD
, IRT_U8
),
2190 lj_ir_kptr(J
, &J2G(J
)->hookmask
), IRXLOAD_VOLATILE
);
2191 tr
= emitir(IRTI(IR_BAND
), tr
, lj_ir_kint(J
, (LUA_MASKLINE
|LUA_MASKCOUNT
)));
2192 emitir(IRTGI(IR_EQ
), tr
, lj_ir_kint(J
, 0));