-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlj_record.c
2247 lines (2103 loc) · 72.7 KB
/
lj_record.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** Trace recorder (bytecode -> SSA IR).
** Copyright (C) 2005-2013 Mike Pall. See Copyright Notice in luajit.h
*/
#define lj_record_c
#define LUA_CORE
#include "lj_obj.h"
#if LJ_HASJIT
#include "lj_err.h"
#include "lj_str.h"
#include "lj_tab.h"
#include "lj_meta.h"
#include "lj_frame.h"
#if LJ_HASFFI
#include "lj_ctype.h"
#endif
#include "lj_bc.h"
#include "lj_ff.h"
#include "lj_ir.h"
#include "lj_jit.h"
#include "lj_ircall.h"
#include "lj_iropt.h"
#include "lj_trace.h"
#include "lj_record.h"
#include "lj_ffrecord.h"
#include "lj_snap.h"
#include "lj_dispatch.h"
#include "lj_vm.h"
/* Some local macros to save typing. Undef'd at the end. */
#define IR(ref) (&J->cur.ir[(ref)])
/* Pass IR on to next optimization in chain (FOLD). */
#define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
/* Emit raw IR without passing through optimizations. */
#define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
/* -- Sanity checks ------------------------------------------------------- */
#ifdef LUA_USE_ASSERT
/* Sanity check the whole IR -- sloooow. */
static void rec_check_ir(jit_State *J)
{
IRRef i, nins = J->cur.nins, nk = J->cur.nk;
lua_assert(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536);
for (i = nins-1; i >= nk; i--) {
IRIns *ir = IR(i);
uint32_t mode = lj_ir_mode[ir->o];
IRRef op1 = ir->op1;
IRRef op2 = ir->op2;
switch (irm_op1(mode)) {
case IRMnone: lua_assert(op1 == 0); break;
case IRMref: lua_assert(op1 >= nk);
lua_assert(i >= REF_BIAS ? op1 < i : op1 > i); break;
case IRMlit: break;
case IRMcst: lua_assert(i < REF_BIAS); continue;
}
switch (irm_op2(mode)) {
case IRMnone: lua_assert(op2 == 0); break;
case IRMref: lua_assert(op2 >= nk);
lua_assert(i >= REF_BIAS ? op2 < i : op2 > i); break;
case IRMlit: break;
case IRMcst: lua_assert(0); break;
}
if (ir->prev) {
lua_assert(ir->prev >= nk);
lua_assert(i >= REF_BIAS ? ir->prev < i : ir->prev > i);
lua_assert(ir->o == IR_NOP || IR(ir->prev)->o == ir->o);
}
}
}
/* Compare stack slots and frames of the recorder and the VM. */
static void rec_check_slots(jit_State *J)
{
BCReg s, nslots = J->baseslot + J->maxslot;
int32_t depth = 0;
cTValue *base = J->L->base - J->baseslot;
lua_assert(J->baseslot >= 1 && J->baseslot < LJ_MAX_JSLOTS);
lua_assert(J->baseslot == 1 || (J->slot[J->baseslot-1] & TREF_FRAME));
lua_assert(nslots < LJ_MAX_JSLOTS);
for (s = 0; s < nslots; s++) {
TRef tr = J->slot[s];
if (tr) {
cTValue *tv = &base[s];
IRRef ref = tref_ref(tr);
IRIns *ir;
lua_assert(ref >= J->cur.nk && ref < J->cur.nins);
ir = IR(ref);
lua_assert(irt_t(ir->t) == tref_t(tr));
if (s == 0) {
lua_assert(tref_isfunc(tr));
} else if ((tr & TREF_FRAME)) {
GCfunc *fn = gco2func(frame_gc(tv));
BCReg delta = (BCReg)(tv - frame_prev(tv));
lua_assert(tref_isfunc(tr));
if (tref_isk(tr)) lua_assert(fn == ir_kfunc(ir));
lua_assert(s > delta ? (J->slot[s-delta] & TREF_FRAME) : (s == delta));
depth++;
} else if ((tr & TREF_CONT)) {
lua_assert(ir_kptr(ir) == gcrefp(tv->gcr, void));
lua_assert((J->slot[s+1] & TREF_FRAME));
depth++;
} else {
if (tvisnumber(tv))
lua_assert(tref_isnumber(tr)); /* Could be IRT_INT etc., too. */
else
lua_assert(itype2irt(tv) == tref_type(tr));
if (tref_isk(tr)) { /* Compare constants. */
TValue tvk;
lj_ir_kvalue(J->L, &tvk, ir);
if (!(tvisnum(&tvk) && tvisnan(&tvk)))
lua_assert(lj_obj_equal(tv, &tvk));
else
lua_assert(tvisnum(tv) && tvisnan(tv));
}
}
}
}
lua_assert(J->framedepth == depth);
}
#endif
/* -- Type handling and specialization ------------------------------------ */
/* Note: these functions return tagged references (TRef). */
/* Specialize a slot to a specific type. Note: slot can be negative! */
static TRef sloadt(jit_State *J, int32_t slot, IRType t, int mode)
{
/* Caller may set IRT_GUARD in t. */
TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
J->base[slot] = ref;
return ref;
}
/* Specialize a slot to the runtime type. Note: slot can be negative! */
static TRef sload(jit_State *J, int32_t slot)
{
IRType t = itype2irt(&J->L->base[slot]);
TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
IRSLOAD_TYPECHECK);
if (irtype_ispri(t)) ref = TREF_PRI(t); /* Canonicalize primitive refs. */
J->base[slot] = ref;
return ref;
}
/* Get TRef from slot. Load slot and specialize if not done already. */
#define getslot(J, s) (J->base[(s)] ? J->base[(s)] : sload(J, (int32_t)(s)))
/* Get TRef for current function. */
static TRef getcurrf(jit_State *J)
{
if (J->base[-1])
return J->base[-1];
lua_assert(J->baseslot == 1);
return sloadt(J, -1, IRT_FUNC, IRSLOAD_READONLY);
}
/* Compare for raw object equality.
** Returns 0 if the objects are the same.
** Returns 1 if they are different, but the same type.
** Returns 2 for two different types.
** Comparisons between primitives always return 1 -- no caller cares about it.
*/
int lj_record_objcmp(jit_State *J, TRef a, TRef b, cTValue *av, cTValue *bv)
{
int diff = !lj_obj_equal(av, bv);
if (!tref_isk2(a, b)) { /* Shortcut, also handles primitives. */
IRType ta = tref_isinteger(a) ? IRT_INT : tref_type(a);
IRType tb = tref_isinteger(b) ? IRT_INT : tref_type(b);
if (ta != tb) {
/* Widen mixed number/int comparisons to number/number comparison. */
if (ta == IRT_INT && tb == IRT_NUM) {
a = emitir(IRTN(IR_CONV), a, IRCONV_NUM_INT);
ta = IRT_NUM;
} else if (ta == IRT_NUM && tb == IRT_INT) {
b = emitir(IRTN(IR_CONV), b, IRCONV_NUM_INT);
} else {
return 2; /* Two different types are never equal. */
}
}
emitir(IRTG(diff ? IR_NE : IR_EQ, ta), a, b);
}
return diff;
}
/* Constify a value. Returns 0 for non-representable object types. */
TRef lj_record_constify(jit_State *J, cTValue *o)
{
if (tvisgcv(o))
return lj_ir_kgc(J, gcV(o), itype2irt(o));
else if (tvisint(o))
return lj_ir_kint(J, intV(o));
else if (tvisnum(o))
return lj_ir_knumint(J, numV(o));
else if (tvisbool(o))
return TREF_PRI(itype2irt(o));
else
return 0; /* Can't represent lightuserdata (pointless). */
}
/* -- Record loop ops ----------------------------------------------------- */
/* Loop event. */
typedef enum {
LOOPEV_LEAVE, /* Loop is left or not entered. */
LOOPEV_ENTERLO, /* Loop is entered with a low iteration count left. */
LOOPEV_ENTER /* Loop is entered. */
} LoopEvent;
/* Canonicalize slots: convert integers to numbers. */
static void canonicalize_slots(jit_State *J)
{
BCReg s;
if (LJ_DUALNUM) return;
for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
TRef tr = J->slot[s];
if (tref_isinteger(tr)) {
IRIns *ir = IR(tref_ref(tr));
if (!(ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_READONLY)))
J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
}
}
}
/* Stop recording. */
static void rec_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
{
lj_trace_end(J);
J->cur.linktype = (uint8_t)linktype;
J->cur.link = (uint16_t)lnk;
/* Looping back at the same stack level? */
if (lnk == J->cur.traceno && J->framedepth + J->retdepth == 0) {
if ((J->flags & JIT_F_OPT_LOOP)) /* Shall we try to create a loop? */
goto nocanon; /* Do not canonicalize or we lose the narrowing. */
if (J->cur.root) /* Otherwise ensure we always link to the root trace. */
J->cur.link = J->cur.root;
}
canonicalize_slots(J);
nocanon:
/* Note: all loop ops must set J->pc to the following instruction! */
lj_snap_add(J); /* Add loop snapshot. */
J->needsnap = 0;
J->mergesnap = 1; /* In case recording continues. */
}
/* Search bytecode backwards for a int/num constant slot initializer. */
static TRef find_kinit(jit_State *J, const BCIns *endpc, BCReg slot, IRType t)
{
/* This algorithm is rather simplistic and assumes quite a bit about
** how the bytecode is generated. It works fine for FORI initializers,
** but it won't necessarily work in other cases (e.g. iterator arguments).
** It doesn't do anything fancy, either (like backpropagating MOVs).
*/
const BCIns *pc, *startpc = proto_bc(J->pt);
for (pc = endpc-1; pc > startpc; pc--) {
BCIns ins = *pc;
BCOp op = bc_op(ins);
/* First try to find the last instruction that stores to this slot. */
if (bcmode_a(op) == BCMbase && bc_a(ins) <= slot) {
return 0; /* Multiple results, e.g. from a CALL or KNIL. */
} else if (bcmode_a(op) == BCMdst && bc_a(ins) == slot) {
if (op == BC_KSHORT || op == BC_KNUM) { /* Found const. initializer. */
/* Now try to verify there's no forward jump across it. */
const BCIns *kpc = pc;
for (; pc > startpc; pc--)
if (bc_op(*pc) == BC_JMP) {
const BCIns *target = pc+bc_j(*pc)+1;
if (target > kpc && target <= endpc)
return 0; /* Conditional assignment. */
}
if (op == BC_KSHORT) {
int32_t k = (int32_t)(int16_t)bc_d(ins);
return t == IRT_INT ? lj_ir_kint(J, k) : lj_ir_knum(J, (lua_Number)k);
} else {
cTValue *tv = proto_knumtv(J->pt, bc_d(ins));
if (t == IRT_INT) {
int32_t k = numberVint(tv);
if (tvisint(tv) || numV(tv) == (lua_Number)k) /* -0 is ok here. */
return lj_ir_kint(J, k);
return 0; /* Type mismatch. */
} else {
return lj_ir_knum(J, numberVnum(tv));
}
}
}
return 0; /* Non-constant initializer. */
}
}
return 0; /* No assignment to this slot found? */
}
/* Load and optionally convert a FORI argument from a slot. */
static TRef fori_load(jit_State *J, BCReg slot, IRType t, int mode)
{
int conv = (tvisint(&J->L->base[slot]) != (t==IRT_INT)) ? IRSLOAD_CONVERT : 0;
return sloadt(J, (int32_t)slot,
t + (((mode & IRSLOAD_TYPECHECK) ||
(conv && t == IRT_INT && !(mode >> 16))) ?
IRT_GUARD : 0),
mode + conv);
}
/* Peek before FORI to find a const initializer. Otherwise load from slot. */
static TRef fori_arg(jit_State *J, const BCIns *fori, BCReg slot,
IRType t, int mode)
{
TRef tr = J->base[slot];
if (!tr) {
tr = find_kinit(J, fori, slot, t);
if (!tr)
tr = fori_load(J, slot, t, mode);
}
return tr;
}
/* Return the direction of the FOR loop iterator.
** It's important to exactly reproduce the semantics of the interpreter.
*/
static int rec_for_direction(cTValue *o)
{
return (tvisint(o) ? intV(o) : (int32_t)o->u32.hi) >= 0;
}
/* Simulate the runtime behavior of the FOR loop iterator. */
static LoopEvent rec_for_iter(IROp *op, cTValue *o, int isforl)
{
lua_Number stopv = numberVnum(&o[FORL_STOP]);
lua_Number idxv = numberVnum(&o[FORL_IDX]);
lua_Number stepv = numberVnum(&o[FORL_STEP]);
if (isforl)
idxv += stepv;
if (rec_for_direction(&o[FORL_STEP])) {
if (idxv <= stopv) {
*op = IR_LE;
return idxv + 2*stepv > stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
}
*op = IR_GT; return LOOPEV_LEAVE;
} else {
if (stopv <= idxv) {
*op = IR_GE;
return idxv + 2*stepv < stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
}
*op = IR_LT; return LOOPEV_LEAVE;
}
}
/* Record checks for FOR loop overflow and step direction. */
static void rec_for_check(jit_State *J, IRType t, int dir,
TRef stop, TRef step, int init)
{
if (!tref_isk(step)) {
/* Non-constant step: need a guard for the direction. */
TRef zero = (t == IRT_INT) ? lj_ir_kint(J, 0) : lj_ir_knum_zero(J);
emitir(IRTG(dir ? IR_GE : IR_LT, t), step, zero);
/* Add hoistable overflow checks for a narrowed FORL index. */
if (init && t == IRT_INT) {
if (tref_isk(stop)) {
/* Constant stop: optimize check away or to a range check for step. */
int32_t k = IR(tref_ref(stop))->i;
if (dir) {
if (k > 0)
emitir(IRTGI(IR_LE), step, lj_ir_kint(J, (int32_t)0x7fffffff-k));
} else {
if (k < 0)
emitir(IRTGI(IR_GE), step, lj_ir_kint(J, (int32_t)0x80000000-k));
}
} else {
/* Stop+step variable: need full overflow check. */
TRef tr = emitir(IRTGI(IR_ADDOV), step, stop);
emitir(IRTI(IR_USE), tr, 0); /* ADDOV is weak. Avoid dead result. */
}
}
} else if (init && t == IRT_INT && !tref_isk(stop)) {
/* Constant step: optimize overflow check to a range check for stop. */
int32_t k = IR(tref_ref(step))->i;
k = (int32_t)(dir ? 0x7fffffff : 0x80000000) - k;
emitir(IRTGI(dir ? IR_LE : IR_GE), stop, lj_ir_kint(J, k));
}
}
/* Record a FORL instruction. */
static void rec_for_loop(jit_State *J, const BCIns *fori, ScEvEntry *scev,
int init)
{
BCReg ra = bc_a(*fori);
cTValue *tv = &J->L->base[ra];
TRef idx = J->base[ra+FORL_IDX];
IRType t = idx ? tref_type(idx) :
(init || LJ_DUALNUM) ? lj_opt_narrow_forl(J, tv) : IRT_NUM;
int mode = IRSLOAD_INHERIT +
((!LJ_DUALNUM || tvisint(tv) == (t == IRT_INT)) ? IRSLOAD_READONLY : 0);
TRef stop = fori_arg(J, fori, ra+FORL_STOP, t, mode);
TRef step = fori_arg(J, fori, ra+FORL_STEP, t, mode);
int tc, dir = rec_for_direction(&tv[FORL_STEP]);
lua_assert(bc_op(*fori) == BC_FORI || bc_op(*fori) == BC_JFORI);
scev->t.irt = t;
scev->dir = dir;
scev->stop = tref_ref(stop);
scev->step = tref_ref(step);
rec_for_check(J, t, dir, stop, step, init);
scev->start = tref_ref(find_kinit(J, fori, ra+FORL_IDX, IRT_INT));
tc = (LJ_DUALNUM &&
!(scev->start && irref_isk(scev->stop) && irref_isk(scev->step) &&
tvisint(&tv[FORL_IDX]) == (t == IRT_INT))) ?
IRSLOAD_TYPECHECK : 0;
if (tc) {
J->base[ra+FORL_STOP] = stop;
J->base[ra+FORL_STEP] = step;
}
if (!idx)
idx = fori_load(J, ra+FORL_IDX, t,
IRSLOAD_INHERIT + tc + (J->scev.start << 16));
if (!init)
J->base[ra+FORL_IDX] = idx = emitir(IRT(IR_ADD, t), idx, step);
J->base[ra+FORL_EXT] = idx;
scev->idx = tref_ref(idx);
J->maxslot = ra+FORL_EXT+1;
}
/* Record FORL/JFORL or FORI/JFORI. */
static LoopEvent rec_for(jit_State *J, const BCIns *fori, int isforl)
{
BCReg ra = bc_a(*fori);
TValue *tv = &J->L->base[ra];
TRef *tr = &J->base[ra];
IROp op;
LoopEvent ev;
TRef stop;
IRType t;
if (isforl) { /* Handle FORL/JFORL opcodes. */
TRef idx = tr[FORL_IDX];
if (tref_ref(idx) == J->scev.idx) {
t = J->scev.t.irt;
stop = J->scev.stop;
idx = emitir(IRT(IR_ADD, t), idx, J->scev.step);
tr[FORL_EXT] = tr[FORL_IDX] = idx;
} else {
ScEvEntry scev;
rec_for_loop(J, fori, &scev, 0);
t = scev.t.irt;
stop = scev.stop;
}
} else { /* Handle FORI/JFORI opcodes. */
BCReg i;
lj_meta_for(J->L, tv);
t = (LJ_DUALNUM || tref_isint(tr[FORL_IDX])) ? lj_opt_narrow_forl(J, tv) :
IRT_NUM;
for (i = FORL_IDX; i <= FORL_STEP; i++) {
if (!tr[i]) sload(J, ra+i);
lua_assert(tref_isnumber_str(tr[i]));
if (tref_isstr(tr[i]))
tr[i] = emitir(IRTG(IR_STRTO, IRT_NUM), tr[i], 0);
if (t == IRT_INT) {
if (!tref_isinteger(tr[i]))
tr[i] = emitir(IRTGI(IR_CONV), tr[i], IRCONV_INT_NUM|IRCONV_CHECK);
} else {
if (!tref_isnum(tr[i]))
tr[i] = emitir(IRTN(IR_CONV), tr[i], IRCONV_NUM_INT);
}
}
tr[FORL_EXT] = tr[FORL_IDX];
stop = tr[FORL_STOP];
rec_for_check(J, t, rec_for_direction(&tv[FORL_STEP]),
stop, tr[FORL_STEP], 1);
}
ev = rec_for_iter(&op, tv, isforl);
if (ev == LOOPEV_LEAVE) {
J->maxslot = ra+FORL_EXT+1;
J->pc = fori+1;
} else {
J->maxslot = ra;
J->pc = fori+bc_j(*fori)+1;
}
lj_snap_add(J);
emitir(IRTG(op, t), tr[FORL_IDX], stop);
if (ev == LOOPEV_LEAVE) {
J->maxslot = ra;
J->pc = fori+bc_j(*fori)+1;
} else {
J->maxslot = ra+FORL_EXT+1;
J->pc = fori+1;
}
J->needsnap = 1;
return ev;
}
/* Record ITERL/JITERL. */
static LoopEvent rec_iterl(jit_State *J, const BCIns iterins)
{
BCReg ra = bc_a(iterins);
lua_assert(J->base[ra] != 0);
if (!tref_isnil(J->base[ra])) { /* Looping back? */
J->base[ra-1] = J->base[ra]; /* Copy result of ITERC to control var. */
J->maxslot = ra-1+bc_b(J->pc[-1]);
J->pc += bc_j(iterins)+1;
return LOOPEV_ENTER;
} else {
J->maxslot = ra-3;
J->pc++;
return LOOPEV_LEAVE;
}
}
/* Record LOOP/JLOOP. Now, that was easy. */
static LoopEvent rec_loop(jit_State *J, BCReg ra)
{
if (ra < J->maxslot) J->maxslot = ra;
J->pc++;
return LOOPEV_ENTER;
}
/* Check if a loop repeatedly failed to trace because it didn't loop back. */
static int innerloopleft(jit_State *J, const BCIns *pc)
{
ptrdiff_t i;
for (i = 0; i < PENALTY_SLOTS; i++)
if (mref(J->penalty[i].pc, const BCIns) == pc) {
if ((J->penalty[i].reason == LJ_TRERR_LLEAVE ||
J->penalty[i].reason == LJ_TRERR_LINNER) &&
J->penalty[i].val >= 2*PENALTY_MIN)
return 1;
break;
}
return 0;
}
/* Handle the case when an interpreted loop op is hit. */
static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
{
if (J->parent == 0) {
if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
/* Same loop? */
if (ev == LOOPEV_LEAVE) /* Must loop back to form a root trace. */
lj_trace_err(J, LJ_TRERR_LLEAVE);
rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping root trace. */
} else if (ev != LOOPEV_LEAVE) { /* Entering inner loop? */
/* It's usually better to abort here and wait until the inner loop
** is traced. But if the inner loop repeatedly didn't loop back,
** this indicates a low trip count. In this case try unrolling
** an inner loop even in a root trace. But it's better to be a bit
** more conservative here and only do it for very short loops.
*/
if (bc_j(*pc) != -1 && !innerloopleft(J, pc))
lj_trace_err(J, LJ_TRERR_LINNER); /* Root trace hit an inner loop. */
if ((ev != LOOPEV_ENTERLO &&
J->loopref && J->cur.nins - J->loopref > 24) || --J->loopunroll < 0)
lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
J->loopref = J->cur.nins;
}
} else if (ev != LOOPEV_LEAVE) { /* Side trace enters an inner loop. */
J->loopref = J->cur.nins;
if (--J->loopunroll < 0)
lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
} /* Side trace continues across a loop that's left or not entered. */
}
/* Handle the case when an already compiled loop op is hit. */
static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev)
{
if (J->parent == 0) { /* Root trace hit an inner loop. */
/* Better let the inner loop spawn a side trace back here. */
lj_trace_err(J, LJ_TRERR_LINNER);
} else if (ev != LOOPEV_LEAVE) { /* Side trace enters a compiled loop. */
J->instunroll = 0; /* Cannot continue across a compiled loop op. */
if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Form an extra loop. */
else
rec_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the loop. */
} /* Side trace continues across a loop that's left or not entered. */
}
/* -- Record calls and returns -------------------------------------------- */
/* Specialize to the runtime value of the called function or its prototype. */
static TRef rec_call_specialize(jit_State *J, GCfunc *fn, TRef tr)
{
TRef kfunc;
if (isluafunc(fn)) {
GCproto *pt = funcproto(fn);
/* Too many closures created? Probably not a monomorphic function. */
if (pt->flags >= PROTO_CLC_POLY) { /* Specialize to prototype instead. */
TRef trpt = emitir(IRT(IR_FLOAD, IRT_P32), tr, IRFL_FUNC_PC);
emitir(IRTG(IR_EQ, IRT_P32), trpt, lj_ir_kptr(J, proto_bc(pt)));
(void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); /* Prevent GC of proto. */
return tr;
}
}
/* Otherwise specialize to the function (closure) value itself. */
kfunc = lj_ir_kfunc(J, fn);
emitir(IRTG(IR_EQ, IRT_FUNC), tr, kfunc);
return kfunc;
}
/* Record call setup. */
static void rec_call_setup(jit_State *J, BCReg func, ptrdiff_t nargs)
{
RecordIndex ix;
TValue *functv = &J->L->base[func];
TRef *fbase = &J->base[func];
ptrdiff_t i;
for (i = 0; i <= nargs; i++)
(void)getslot(J, func+i); /* Ensure func and all args have a reference. */
if (!tref_isfunc(fbase[0])) { /* Resolve __call metamethod. */
ix.tab = fbase[0];
copyTV(J->L, &ix.tabv, functv);
if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj))
lj_trace_err(J, LJ_TRERR_NOMM);
for (i = ++nargs; i > 0; i--) /* Shift arguments up. */
fbase[i] = fbase[i-1];
fbase[0] = ix.mobj; /* Replace function. */
functv = &ix.mobjv;
}
fbase[0] = TREF_FRAME | rec_call_specialize(J, funcV(functv), fbase[0]);
J->maxslot = (BCReg)nargs;
}
/* Record call. */
void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs)
{
rec_call_setup(J, func, nargs);
/* Bump frame. */
J->framedepth++;
J->base += func+1;
J->baseslot += func+1;
}
/* Record tail call. */
void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
{
rec_call_setup(J, func, nargs);
if (frame_isvarg(J->L->base - 1)) {
BCReg cbase = (BCReg)frame_delta(J->L->base - 1);
if (--J->framedepth < 0)
lj_trace_err(J, LJ_TRERR_NYIRETL);
J->baseslot -= (BCReg)cbase;
J->base -= cbase;
func += cbase;
}
/* Move func + args down. */
memmove(&J->base[-1], &J->base[func], sizeof(TRef)*(J->maxslot+1));
/* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
/* Tailcalls can form a loop, so count towards the loop unroll limit. */
if (++J->tailcalled > J->loopunroll)
lj_trace_err(J, LJ_TRERR_LUNROLL);
}
/* Check unroll limits for down-recursion. */
static int check_downrec_unroll(jit_State *J, GCproto *pt)
{
IRRef ptref;
for (ptref = J->chain[IR_KGC]; ptref; ptref = IR(ptref)->prev)
if (ir_kgc(IR(ptref)) == obj2gco(pt)) {
int count = 0;
IRRef ref;
for (ref = J->chain[IR_RETF]; ref; ref = IR(ref)->prev)
if (IR(ref)->op1 == ptref)
count++;
if (count) {
if (J->pc == J->startpc) {
if (count + J->tailcalled > J->param[JIT_P_recunroll])
return 1;
} else {
lj_trace_err(J, LJ_TRERR_DOWNREC);
}
}
}
return 0;
}
/* Record return. */
void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
{
TValue *frame = J->L->base - 1;
ptrdiff_t i;
for (i = 0; i < gotresults; i++)
(void)getslot(J, rbase+i); /* Ensure all results have a reference. */
while (frame_ispcall(frame)) { /* Immediately resolve pcall() returns. */
BCReg cbase = (BCReg)frame_delta(frame);
if (--J->framedepth < 0)
lj_trace_err(J, LJ_TRERR_NYIRETL);
lua_assert(J->baseslot > 1);
gotresults++;
rbase += cbase;
J->baseslot -= (BCReg)cbase;
J->base -= cbase;
J->base[--rbase] = TREF_TRUE; /* Prepend true to results. */
frame = frame_prevd(frame);
}
/* Return to lower frame via interpreter for unhandled cases. */
if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
(!frame_islua(frame) ||
(J->parent == 0 && !bc_isret(bc_op(J->cur.startins))))) {
/* NYI: specialize to frame type and return directly, not via RET*. */
for (i = -1; i < (ptrdiff_t)rbase; i++)
J->base[i] = 0; /* Purge dead slots. */
J->maxslot = rbase + (BCReg)gotresults;
rec_stop(J, LJ_TRLINK_RETURN, 0); /* Return to interpreter. */
return;
}
if (frame_isvarg(frame)) {
BCReg cbase = (BCReg)frame_delta(frame);
if (--J->framedepth < 0) /* NYI: return of vararg func to lower frame. */
lj_trace_err(J, LJ_TRERR_NYIRETL);
lua_assert(J->baseslot > 1);
rbase += cbase;
J->baseslot -= (BCReg)cbase;
J->base -= cbase;
frame = frame_prevd(frame);
}
if (frame_islua(frame)) { /* Return to Lua frame. */
BCIns callins = *(frame_pc(frame)-1);
ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
BCReg cbase = bc_a(callins);
GCproto *pt = funcproto(frame_func(frame - (cbase+1)));
if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
if (check_downrec_unroll(J, pt)) {
J->maxslot = (BCReg)(rbase + gotresults);
lj_snap_purge(J);
rec_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno); /* Down-recursion. */
return;
}
lj_snap_add(J);
}
for (i = 0; i < nresults; i++) /* Adjust results. */
J->base[i-1] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
J->maxslot = cbase+(BCReg)nresults;
if (J->framedepth > 0) { /* Return to a frame that is part of the trace. */
J->framedepth--;
lua_assert(J->baseslot > cbase+1);
J->baseslot -= cbase+1;
J->base -= cbase+1;
} else if (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))) {
/* Return to lower frame would leave the loop in a root trace. */
lj_trace_err(J, LJ_TRERR_LLEAVE);
} else { /* Return to lower frame. Guard for the target we return to. */
TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
emitir(IRTG(IR_RETF, IRT_P32), trpt, trpc);
J->retdepth++;
J->needsnap = 1;
lua_assert(J->baseslot == 1);
/* Shift result slots up and clear the slots of the new frame below. */
memmove(J->base + cbase, J->base-1, sizeof(TRef)*nresults);
memset(J->base-1, 0, sizeof(TRef)*(cbase+1));
}
} else if (frame_iscont(frame)) { /* Return to continuation frame. */
ASMFunction cont = frame_contf(frame);
BCReg cbase = (BCReg)frame_delta(frame);
if ((J->framedepth -= 2) < 0)
lj_trace_err(J, LJ_TRERR_NYIRETL);
J->baseslot -= (BCReg)cbase;
J->base -= cbase;
J->maxslot = cbase-2;
if (cont == lj_cont_ra) {
/* Copy result to destination slot. */
BCReg dst = bc_a(*(frame_contpc(frame)-1));
J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
if (dst >= J->maxslot) J->maxslot = dst+1;
} else if (cont == lj_cont_nop) {
/* Nothing to do here. */
} else if (cont == lj_cont_cat) {
lua_assert(0);
} else {
/* Result type already specialized. */
lua_assert(cont == lj_cont_condf || cont == lj_cont_condt);
}
} else {
lj_trace_err(J, LJ_TRERR_NYIRETL); /* NYI: handle return to C frame. */
}
lua_assert(J->baseslot >= 1);
}
/* -- Metamethod handling ------------------------------------------------- */
/* Prepare to record call to metamethod. */
static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
{
BCReg s, top = curr_proto(J->L)->framesize;
TRef trcont;
setcont(&J->L->base[top], cont);
#if LJ_64
trcont = lj_ir_kptr(J, (void *)((int64_t)cont - (int64_t)lj_vm_asm_begin));
#else
trcont = lj_ir_kptr(J, (void *)cont);
#endif
J->base[top] = trcont | TREF_CONT;
J->framedepth++;
for (s = J->maxslot; s < top; s++)
J->base[s] = 0; /* Clear frame gap to avoid resurrecting previous refs. */
return top+1;
}
/* Record metamethod lookup. */
int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
{
RecordIndex mix;
GCtab *mt;
if (tref_istab(ix->tab)) {
mt = tabref(tabV(&ix->tabv)->metatable);
mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
} else if (tref_isudata(ix->tab)) {
int udtype = udataV(&ix->tabv)->udtype;
mt = tabref(udataV(&ix->tabv)->metatable);
/* The metatables of special userdata objects are treated as immutable. */
if (udtype != UDTYPE_USERDATA) {
cTValue *mo;
if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
/* Specialize to the C library namespace object. */
emitir(IRTG(IR_EQ, IRT_P32), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
} else {
/* Specialize to the type of userdata. */
TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, udtype));
}
immutable_mt:
mo = lj_tab_getstr(mt, mmname_str(J2G(J), mm));
if (!mo || tvisnil(mo))
return 0; /* No metamethod. */
/* Treat metamethod or index table as immutable, too. */
if (!(tvisfunc(mo) || tvistab(mo)))
lj_trace_err(J, LJ_TRERR_BADTYPE);
copyTV(J->L, &ix->mobjv, mo);
ix->mobj = lj_ir_kgc(J, gcV(mo), tvisfunc(mo) ? IRT_FUNC : IRT_TAB);
ix->mtv = mt;
ix->mt = TREF_NIL; /* Dummy value for comparison semantics. */
return 1; /* Got metamethod or index table. */
}
mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_UDATA_META);
} else {
/* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
mt = tabref(basemt_obj(J2G(J), &ix->tabv));
if (mt == NULL) {
ix->mt = TREF_NIL;
return 0; /* No metamethod. */
}
/* The cdata metatable is treated as immutable. */
if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
ix->mt = mix.tab = lj_ir_ktab(J, mt);
goto nocheck;
}
ix->mt = mt ? mix.tab : TREF_NIL;
emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mix.tab, lj_ir_knull(J, IRT_TAB));
nocheck:
if (mt) {
GCstr *mmstr = mmname_str(J2G(J), mm);
cTValue *mo = lj_tab_getstr(mt, mmstr);
if (mo && !tvisnil(mo))
copyTV(J->L, &ix->mobjv, mo);
ix->mtv = mt;
settabV(J->L, &mix.tabv, mt);
setstrV(J->L, &mix.keyv, mmstr);
mix.key = lj_ir_kstr(J, mmstr);
mix.val = 0;
mix.idxchain = 0;
ix->mobj = lj_record_idx(J, &mix);
return !tref_isnil(ix->mobj); /* 1 if metamethod found, 0 if not. */
}
return 0; /* No metamethod. */
}
/* Record call to arithmetic metamethod. */
static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
{
/* Set up metamethod call first to save ix->tab and ix->tabv. */
BCReg func = rec_mm_prep(J, lj_cont_ra);
TRef *base = J->base + func;
TValue *basev = J->L->base + func;
base[1] = ix->tab; base[2] = ix->key;
copyTV(J->L, basev+1, &ix->tabv);
copyTV(J->L, basev+2, &ix->keyv);
if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
if (mm != MM_unm) {
ix->tab = ix->key;
copyTV(J->L, &ix->tabv, &ix->keyv);
if (lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
goto ok;
}
lj_trace_err(J, LJ_TRERR_NOMM);
}
ok:
base[0] = ix->mobj;
copyTV(J->L, basev+0, &ix->mobjv);
lj_record_call(J, func, 2);
return 0; /* No result yet. */
}
/* Record call to __len metamethod. */
static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
{
RecordIndex ix;
ix.tab = tr;
copyTV(J->L, &ix.tabv, tv);
if (lj_record_mm_lookup(J, &ix, MM_len)) {
BCReg func = rec_mm_prep(J, lj_cont_ra);
TRef *base = J->base + func;
TValue *basev = J->L->base + func;
base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv);
base[1] = tr; copyTV(J->L, basev+1, tv);
#if LJ_52
base[2] = tr; copyTV(J->L, basev+2, tv);
#else
base[2] = TREF_NIL; setnilV(basev+2);
#endif
lj_record_call(J, func, 2);
} else {
if (LJ_52 && tref_istab(tr))
return lj_ir_call(J, IRCALL_lj_tab_len, tr);
lj_trace_err(J, LJ_TRERR_NOMM);
}
return 0; /* No result yet. */
}
/* Call a comparison metamethod. */
static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
{
BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
TRef *base = J->base + func;
TValue *tv = J->L->base + func;
base[0] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
copyTV(J->L, tv+0, &ix->mobjv);
copyTV(J->L, tv+1, &ix->valv);
copyTV(J->L, tv+2, &ix->keyv);
lj_record_call(J, func, 2);
}
/* Record call to equality comparison metamethod (for tab and udata only). */
static void rec_mm_equal(jit_State *J, RecordIndex *ix, int op)
{
ix->tab = ix->val;
copyTV(J->L, &ix->tabv, &ix->valv);
if (lj_record_mm_lookup(J, ix, MM_eq)) { /* Lookup mm on 1st operand. */
cTValue *bv;
TRef mo1 = ix->mobj;
TValue mo1v;
copyTV(J->L, &mo1v, &ix->mobjv);
/* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
bv = &ix->keyv;
if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
} else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
} else { /* Lookup metamethod on 2nd operand and compare both. */
ix->tab = ix->key;
copyTV(J->L, &ix->tabv, bv);
if (!lj_record_mm_lookup(J, ix, MM_eq) ||
lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
return;
}
rec_mm_callcomp(J, ix, op);
}
}
/* Record call to ordered comparison metamethods (for arbitrary objects). */
static void rec_mm_comp(jit_State *J, RecordIndex *ix, int op)
{
ix->tab = ix->val;
copyTV(J->L, &ix->tabv, &ix->valv);
while (1) {
MMS mm = (op & 2) ? MM_le : MM_lt; /* Try __le + __lt or only __lt. */
#if LJ_52
if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
ix->tab = ix->key;
copyTV(J->L, &ix->tabv, &ix->keyv);
if (!lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
goto nomatch;
}
rec_mm_callcomp(J, ix, op);
return;
#else
if (lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
cTValue *bv;
TRef mo1 = ix->mobj;
TValue mo1v;
copyTV(J->L, &mo1v, &ix->mobjv);
/* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
bv = &ix->keyv;
if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
} else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
} else { /* Lookup metamethod on 2nd operand and compare both. */
ix->tab = ix->key;
copyTV(J->L, &ix->tabv, bv);
if (!lj_record_mm_lookup(J, ix, mm) ||
lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
goto nomatch;