-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlcode.cpp
More file actions
1680 lines (1565 loc) · 51.4 KB
/
lcode.cpp
File metadata and controls
1680 lines (1565 loc) · 51.4 KB
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
/*
** $Id: lcode.c $
** Code generator for Lua
** See Copyright Notice in lua.h
*/
#define lcode_c
#define LUA_CORE
#include "lprefix.h"
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdlib>
#include "lua.h"
#include "ldebug.h"
#include "ldo.h"
#include "lgc.h"
#include "llex.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstring.h"
#include "ltable.h"
#include "lvm.h"
/* (note that expressions VJMP also have jumps.) */
inline bool hasjumps(const expdesc* e) noexcept {
return e->getTrueList() != e->getFalseList();
}
/* semantic error */
l_noret LexState::semerror(const char *fmt, ...) {
const char *msg;
va_list argp;
pushvfstring(getLuaState(), argp, fmt, msg);
getCurrentTokenRef().token = 0; /* remove "near <token>" from final message */
syntaxError(msg);
}
/*
** If expression is a numeric constant, fills 'v' with its value
** and returns 1. Otherwise, returns 0.
*/
static int tonumeral (const expdesc *e, TValue *v) {
if (hasjumps(e))
return 0; /* not a numeral */
switch (e->getKind()) {
case VKINT:
if (v) v->setInt(e->getIntValue());
return 1;
case VKFLT:
if (v) v->setFloat(e->getFloatValue());
return 1;
default: return 0;
}
}
/*
** Get the constant value from a constant expression
*/
TValue *FuncState::const2val(const expdesc *e) {
lua_assert(e->getKind() == VCONST);
return &getLexState()->getDyndata()->actvar()[e->getInfo()].k;
}
/*
** Return the previous instruction of the current code. If there
** may be a jump target between the current instruction and the
** previous one, return an invalid instruction (to avoid wrong
** optimizations).
*/
Instruction *FuncState::previousinstruction() {
static const Instruction invalidinstruction = ~(Instruction)0;
if (getPC() > getLastTarget())
return &getProto()->getCode()[getPC() - 1]; /* previous instruction */
else
return const_cast<Instruction*>(&invalidinstruction);
}
/*
** Gets the destination address of a jump instruction. Used to traverse
** a list of jumps.
*/
int FuncState::getjump(int position) {
int offset = InstructionView(getProto()->getCode()[position]).sj();
if (offset == NO_JUMP) /* point to itself represents end of list */
return NO_JUMP; /* end of list */
else
return (position+1)+offset; /* turn offset into absolute position */
}
/*
** Fix jump instruction at position 'pc' to jump to 'dest'.
** (Jump addresses are relative in Lua)
*/
void FuncState::fixjump(int position, int dest) {
Instruction *jmp = &getProto()->getCode()[position];
int offset = dest - (position + 1);
lua_assert(dest != NO_JUMP);
if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))
getLexState()->syntaxError("control structure too long");
lua_assert(InstructionView(*jmp).opcode() == OP_JMP);
SETARG_sJ(*jmp, offset);
}
/*
** Code a "conditional jump", that is, a test or comparison opcode
** followed by a jump. Return jump position.
*/
int FuncState::condjump(OpCode o, int A, int B, int C, int k) {
codeABCk(o, A, B, C, k);
return jump();
}
/*
** Returns the position of the instruction "controlling" a given
** jump (that is, its condition), or the jump itself if it is
** unconditional.
*/
Instruction *FuncState::getjumpcontrol(int position) {
Instruction *pi = &getProto()->getCode()[position];
if (position >= 1 && InstructionView(*(pi-1)).testTMode())
return pi-1;
else
return pi;
}
/*
** Patch destination register for a TESTSET instruction.
** If instruction in position 'node' is not a TESTSET, return 0 ("fails").
** Otherwise, if 'reg' is not 'NO_REG', set it as the destination
** register. Otherwise, change instruction to a simple 'TEST' (produces
** no register value)
*/
int FuncState::patchtestreg(int node, int reg) {
Instruction *i = getjumpcontrol(node);
if (InstructionView(*i).opcode() != OP_TESTSET)
return 0; /* cannot patch other instructions */
if (reg != NO_REG && reg != InstructionView(*i).b())
SETARG_A(*i, static_cast<unsigned int>(reg));
else {
/* no register to put value or register already has the value;
change instruction to simple test */
*i = CREATE_ABCk(OP_TEST, InstructionView(*i).b(), 0, 0, InstructionView(*i).k());
}
return 1;
}
/*
** Traverse a list of tests ensuring no one produces a value
*/
int FuncState::removevalues(int list) {
for (; list != NO_JUMP; list = getjump(list))
patchtestreg(list, NO_REG);
return list;
}
/*
** Traverse a list of tests, patching their destination address and
** registers: tests producing values jump to 'vtarget' (and put their
** values in 'reg'), other tests jump to 'dtarget'.
*/
void FuncState::patchlistaux(int list, int vtarget, int reg, int dtarget) {
while (list != NO_JUMP) {
int next = getjump(list);
if (patchtestreg(list, reg))
fixjump(list, vtarget);
else
fixjump(list, dtarget); /* jump to default target */
list = next;
}
}
/* limit for difference between lines in relative line info. */
#define LIMLINEDIFF 0x80
/*
** Save line info for a new instruction. If difference from last line
** does not fit in a byte, of after that many instructions, save a new
** absolute line info; (in that case, the special value 'ABSLINEINFO'
** in 'lineinfo' signals the existence of this absolute information.)
** Otherwise, store the difference from last line in 'lineinfo'.
*/
void FuncState::savelineinfo(Proto *proto, int line) {
int linedif = line - getPreviousLine();
int pcval = getPC() - 1; /* last instruction coded */
if (abs(linedif) >= LIMLINEDIFF || postIncrementInstructionsWithAbs() >= MAXIWTHABS) {
luaM_growvector(getLexState()->getLuaState(), proto->getAbsLineInfoRef(), getNAbsLineInfo(),
proto->getAbsLineInfoSizeRef(), AbsLineInfo, std::numeric_limits<int>::max(), "lines");
proto->getAbsLineInfo()[getNAbsLineInfo()].setPC(pcval);
proto->getAbsLineInfo()[postIncrementNAbsLineInfo()].setLine(line);
linedif = ABSLINEINFO; /* signal that there is absolute information */
setInstructionsWithAbs(1); /* restart counter */
}
luaM_growvector(getLexState()->getLuaState(), proto->getLineInfoRef(), pcval, proto->getLineInfoSizeRef(), ls_byte,
std::numeric_limits<int>::max(), "opcodes");
proto->getLineInfo()[pcval] = static_cast<ls_byte>(linedif);
setPreviousLine(line); /* last line saved */
}
/*
** Remove line information from the last instruction.
** If line information for that instruction is absolute, set 'iwthabs'
** above its max to force the new (replacing) instruction to have
** absolute line info, too.
*/
void FuncState::removelastlineinfo() {
Proto *proto = getProto();
int pcval = getPC() - 1; /* last instruction coded */
if (proto->getLineInfo()[pcval] != ABSLINEINFO) { /* relative line info? */
setPreviousLine(getPreviousLine() - proto->getLineInfo()[pcval]); /* correct last line saved */
decrementInstructionsWithAbs(); /* undo previous increment */
}
else { /* absolute line information */
lua_assert(proto->getAbsLineInfo()[getNAbsLineInfo() - 1].getPC() == pcval);
decrementNAbsLineInfo(); /* remove it */
setInstructionsWithAbs(MAXIWTHABS + 1); /* force next line info to be absolute */
}
}
/*
** Remove the last instruction created, correcting line information
** accordingly.
*/
void FuncState::removelastinstruction() {
removelastlineinfo();
decrementPC();
}
/*
** Format and emit an 'iAsBx' instruction.
*/
int FuncState::codeAsBx(OpCode o, int A, int Bc) {
int b = Bc + OFFSET_sBx;
lua_assert(getOpMode(o) == OpMode::iAsBx);
lua_assert(A <= MAXARG_A && b <= MAXARG_Bx);
return code(CREATE_ABx(o, A, b));
}
/*
** Emit an "extra argument" instruction (format 'iAx')
*/
int FuncState::codeextraarg(int A) {
lua_assert(A <= MAXARG_Ax);
return code(CREATE_Ax(OP_EXTRAARG, A));
}
/*
** Emit a "load constant" instruction, using either 'OP_LOADK'
** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'
** instruction with "extra argument".
*/
int FuncState::codek(int reg, int k) {
if (k <= MAXARG_Bx)
return codeABx(OP_LOADK, reg, k);
else {
int p = codeABx(OP_LOADKX, reg, 0);
codeextraarg(k);
return p;
}
}
/*
** Free register 'reg', if it is neither a constant index nor
** a local variable.
)
*/
void FuncState::freeRegister(int reg) {
if (reg >= luaY_nvarstack(this)) {
decrementFreeReg();
lua_assert(reg == getFreeReg());
}
}
/*
** Free two registers in proper order
*/
void FuncState::freeRegisters(int r1, int r2) {
if (r1 > r2) {
freeRegister(r1);
freeRegister(r2);
}
else {
freeRegister(r2);
freeRegister(r1);
}
}
/*
** Free register used by expression 'e' (if any)
*/
void FuncState::freeExpression(expdesc *e) {
if (e->getKind() == VNONRELOC)
freeRegister(e->getInfo());
}
/*
** Free registers used by expressions 'e1' and 'e2' (if any) in proper
** order.
*/
void FuncState::freeExpressions(expdesc *e1, expdesc *e2) {
int r1 = (e1->getKind() == VNONRELOC) ? e1->getInfo() : -1;
int r2 = (e2->getKind() == VNONRELOC) ? e2->getInfo() : -1;
freeRegisters(r1, r2);
}
/*
** Add constant 'v' to prototype's list of constants (field 'k').
*/
int FuncState::addk(Proto *proto, TValue *v) {
lua_State *L = getLexState()->getLuaState();
int oldsize = proto->getConstantsSize();
int k = getNK();
luaM_growvector(L, proto->getConstantsRef(), k, proto->getConstantsSizeRef(), TValue, MAXARG_Ax, "constants");
auto constantsSpan = proto->getConstantsSpan();
while (oldsize < static_cast<int>(constantsSpan.size()))
setnilvalue(&constantsSpan[oldsize++]);
constantsSpan[k] = *v;
incrementNK();
luaC_barrier(L, proto, v);
return k;
}
/*
** Use scanner's table to cache position of constants in constant list
** and try to reuse constants. Because some values should not be used
** as keys (nil cannot be a key, integer keys can collapse with float
** keys), the caller must provide a useful 'key' for indexing the cache.
*/
int FuncState::k2proto(TValue *key, TValue *v) {
TValue val;
Proto *proto = getProto();
LuaT tag = luaH_get(getKCache(), key, &val); /* query scanner table */
if (!tagisempty(tag)) { /* is there an index there? */
int k = cast_int(ivalue(&val));
/* collisions can happen only for float keys */
lua_assert(ttisfloat(key) || luaV_rawequalobj(&proto->getConstants()[k], v));
return k; /* reuse index */
}
else { /* constant not found; create a new entry */
int k = addk(proto, v);
/* cache it for reuse; numerical value does not need GC barrier;
table is not a metatable, so it does not need to invalidate cache */
val.setInt(k);
luaH_set(getLexState()->getLuaState(), getKCache(), key, &val);
return k;
}
}
/*
** Add a string to list of constants and return its index.
*/
int FuncState::stringK(TString *s) {
TValue o;
setsvalue(getLexState()->getLuaState(), &o, s);
return k2proto(&o, &o); /* use string itself as key */
}
/*
** Add an integer to list of constants and return its index.
*/
int FuncState::intK(lua_Integer n) {
TValue o;
o.setInt(n);
return k2proto(&o, &o); /* use integer itself as key */
}
/*
** Add a float to list of constants and return its index. Floats
** with integral values need a different key, to avoid collision
** with actual integers. To that end, we add to the number its smaller
** power-of-two fraction that is still significant in its scale.
** (For doubles, the fraction would be 2^-52).
** This method is not bulletproof: different numbers may generate the
** same key (e.g., very large numbers will overflow to 'inf') and for
** floats larger than 2^53 the result is still an integer. For those
** cases, just generate a new entry. At worst, this only wastes an entry
** with a duplicate.
*/
int FuncState::numberK(lua_Number r) {
TValue o, kv;
o.setFloat(r); /* value as a TValue */
if (r == 0) { /* handle zero as a special case */
setpvalue(&kv, this); /* use FuncState as index */
return k2proto(&kv, &o); /* cannot collide */
}
else {
const int nbm = l_floatatt(MANT_DIG);
const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1);
const lua_Number k = r * (1 + q); /* key */
lua_Integer ik;
kv.setFloat(k); /* key as a TValue */
if (!luaV_flttointeger(k, &ik, F2Imod::F2Ieq)) { /* not an integer value? */
int n = k2proto(&kv, &o); /* use key */
if (luaV_rawequalobj(&getProto()->getConstants()[n], &o)) /* correct value? */
return n;
}
/* else, either key is still an integer or there was a collision;
anyway, do not try to reuse constant; instead, create a new one */
return addk(getProto(), &o);
}
}
/*
** Add a false to list of constants and return its index.
*/
int FuncState::boolF() {
TValue o;
setbfvalue(&o);
return k2proto(&o, &o); /* use boolean itself as key */
}
/*
** Add a true to list of constants and return its index.
*/
int FuncState::boolT() {
TValue o;
setbtvalue(&o);
return k2proto(&o, &o); /* use boolean itself as key */
}
/*
** Add nil to list of constants and return its index.
*/
int FuncState::nilK() {
TValue k, v;
setnilvalue(&v);
/* cannot use nil as key; instead use table itself */
sethvalue(getLexState()->getLuaState(), &k, getKCache());
return k2proto(&k, &v);
}
/*
** Check whether 'i' can be stored in an 'sC' operand. Equivalent to
** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of
** overflows in the hidden addition inside 'int2sC'.
*/
static int fitsC (lua_Integer i) {
return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));
}
/*
** Check whether 'i' can be stored in an 'sBx' operand.
*/
static int fitsBx (lua_Integer i) {
return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);
}
void FuncState::floatCode(int reg, lua_Number flt) {
lua_Integer fi;
if (luaV_flttointeger(flt, &fi, F2Imod::F2Ieq) && fitsBx(fi))
codeAsBx(OP_LOADF, reg, cast_int(fi));
else
codek(reg, numberK(flt));
}
/*
** Convert a constant in 'v' into an expression description 'e'
*/
static void const2exp (TValue *v, expdesc *e) {
switch (ttypetag(v)) {
case LuaT::NUMINT:
e->setKind(VKINT); e->setIntValue(ivalue(v));
break;
case LuaT::NUMFLT:
e->setKind(VKFLT); e->setFloatValue(fltvalue(v));
break;
case LuaT::VFALSE:
e->setKind(VFALSE);
break;
case LuaT::VTRUE:
e->setKind(VTRUE);
break;
case LuaT::NIL:
e->setKind(VNIL);
break;
case LuaT::SHRSTR: case LuaT::LNGSTR:
e->setKind(VKSTR); e->setStringValue(tsvalue(v));
break;
default: lua_assert(0);
}
}
/*
** Convert a VKSTR to a VK
*/
int FuncState::str2K(expdesc *e) {
lua_assert(e->getKind() == VKSTR);
e->setInfo(stringK(e->getStringValue()));
e->setKind(VK);
return e->getInfo();
}
/*
** Ensure expression value is in register 'reg', making 'e' a
** non-relocatable expression.
** (Expression still may have jump lists.)
*/
void FuncState::discharge2reg(expdesc *e, int reg) {
dischargevars(e);
switch (e->getKind()) {
case VNIL: {
nil(reg, 1);
break;
}
case VFALSE: {
codeABC(OP_LOADFALSE, reg, 0, 0);
break;
}
case VTRUE: {
codeABC(OP_LOADTRUE, reg, 0, 0);
break;
}
case VKSTR: {
str2K(e);
} /* FALLTHROUGH */
case VK: {
codek(reg, e->getInfo());
break;
}
case VKFLT: {
floatCode(reg, e->getFloatValue());
break;
}
case VKINT: {
intCode(reg, e->getIntValue());
break;
}
case VRELOC: {
Instruction *instr = &getinstruction(this, e);
SETARG_A(*instr, static_cast<unsigned int>(reg)); /* instruction will put result in 'reg' */
break;
}
case VNONRELOC: {
if (reg != e->getInfo())
codeABC(OP_MOVE, reg, e->getInfo(), 0);
break;
}
default: {
lua_assert(e->getKind() == VJMP);
return; /* nothing to do... */
}
}
e->setInfo(reg);
e->setKind(VNONRELOC);
}
/*
** Ensure expression value is in a register, making 'e' a
** non-relocatable expression.
** (Expression still may have jump lists.)
*/
void FuncState::discharge2anyreg(expdesc *e) {
if (e->getKind() != VNONRELOC) { /* no fixed register yet? */
reserveregs(1); /* get a register */
discharge2reg(e, getFreeReg()-1); /* put value there */
}
}
int FuncState::code_loadbool(int A, OpCode op) {
getlabel(); /* those instructions may be jump targets */
return codeABC(op, A, 0, 0);
}
/*
** check whether list has any jump that do not produce a value
** or produce an inverted value
*/
int FuncState::need_value(int list) {
for (; list != NO_JUMP; list = getjump(list)) {
Instruction i = *getjumpcontrol(list);
if (InstructionView(i).opcode() != OP_TESTSET) return 1;
}
return 0; /* not found */
}
/*
** Ensures final expression result (which includes results from its
** jump lists) is in register 'reg'.
** If expression has jumps, need to patch these jumps either to
** its final position or to "load" instructions (for those tests
** that do not produce values).
*/
void FuncState::exp2reg(expdesc *e, int reg) {
discharge2reg(e, reg);
if (e->getKind() == VJMP) /* expression itself is a test? */
concat(e->getTrueListRef(), e->getInfo()); /* put this jump in 't' list */
if (hasjumps(e)) {
int p_f = NO_JUMP; /* position of an eventual LOAD false */
int p_t = NO_JUMP; /* position of an eventual LOAD true */
if (need_value(e->getTrueList()) || need_value(e->getFalseList())) {
int fj = (e->getKind() == VJMP) ? NO_JUMP : jump();
p_f = code_loadbool(reg, OP_LFALSESKIP); /* skip next inst. */
p_t = code_loadbool(reg, OP_LOADTRUE);
/* jump around these booleans if 'e' is not a test */
patchtohere(fj);
}
int final = getlabel(); /* position after whole expression */
patchlistaux(e->getFalseList(), final, reg, p_f);
patchlistaux(e->getTrueList(), final, reg, p_t);
}
e->setFalseList(NO_JUMP); e->setTrueList(NO_JUMP);
e->setInfo(reg);
e->setKind(VNONRELOC);
}
/*
** Try to make 'e' a K expression with an index in the range of R/K
** indices. Return true iff succeeded.
*/
int FuncState::exp2K(expdesc *e) {
if (!hasjumps(e)) {
int info;
switch (e->getKind()) { /* move constants to 'k' */
case VTRUE: info = boolT(); break;
case VFALSE: info = boolF(); break;
case VNIL: info = nilK(); break;
case VKINT: info = intK(e->getIntValue()); break;
case VKFLT: info = numberK(e->getFloatValue()); break;
case VKSTR: info = stringK(e->getStringValue()); break;
case VK: info = e->getInfo(); break;
default: return 0; /* not a constant */
}
if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
e->setKind(VK); /* make expression a 'K' expression */
e->setInfo(info);
return 1;
}
}
/* else, expression doesn't fit; leave it unchanged */
return 0;
}
/*
** Ensures final expression result is in a valid R/K index
** (that is, it is either in a register or in 'k' with an index
** in the range of R/K indices).
** Returns 1 iff expression is K.
*/
int FuncState::exp2RK(expdesc *e) {
if (exp2K(e))
return 1;
else { /* not a constant in the right range: put it in a register */
exp2anyreg(e);
return 0;
}
}
void FuncState::codeABRK(OpCode o, int A, int B, expdesc *ec) {
int k = exp2RK(ec);
codeABCk(o, A, B, ec->getInfo(), k);
}
/*
** Negate condition 'e' (where 'e' is a comparison).
*/
void FuncState::negatecondition(expdesc *e) {
Instruction *instr = getjumpcontrol(e->getInfo());
InstructionView view(*instr);
lua_assert(view.testTMode() && view.opcode() != OP_TESTSET &&
view.opcode() != OP_TEST);
SETARG_k(*instr, static_cast<unsigned int>(view.k() ^ 1));
}
/*
** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
** is true, code will jump if 'e' is true.) Return jump position.
** Optimize when 'e' is 'not' something, inverting the condition
** and removing the 'not'.
*/
int FuncState::jumponcond(expdesc *e, int cond) {
if (e->getKind() == VRELOC) {
Instruction ie = getinstruction(this, e);
if (InstructionView(ie).opcode() == OP_NOT) {
removelastinstruction(); /* remove previous OP_NOT */
return condjump(OP_TEST, InstructionView(ie).b(), 0, 0, !cond);
}
/* else go through */
}
discharge2anyreg(e);
freeExpression(e);
return condjump(OP_TESTSET, NO_REG, e->getInfo(), 0, cond);
}
/*
** Code 'not e', doing constant folding.
*/
void FuncState::codenot(expdesc *e) {
switch (e->getKind()) {
case VNIL: case VFALSE: {
e->setKind(VTRUE); /* true == not nil == not false */
break;
}
case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
e->setKind(VFALSE); /* false == not "x" == not 0.5 == not 1 == not true */
break;
}
case VJMP: {
negatecondition(e);
break;
}
case VRELOC:
case VNONRELOC: {
discharge2anyreg(e);
freeExpression(e);
e->setInfo(codeABC(OP_NOT, 0, e->getInfo(), 0));
e->setKind(VRELOC);
break;
}
default: lua_assert(0); /* cannot happen */
}
/* interchange true and false lists */
{ int temp = e->getFalseList(); e->setFalseList(e->getTrueList()); e->setTrueList(temp); }
removevalues(e->getFalseList()); /* values are useless when negated */
removevalues(e->getTrueList());
}
/*
** Check whether expression 'e' is a short literal string
*/
int FuncState::isKstr(expdesc *e) {
return (e->getKind() == VK && !hasjumps(e) && e->getInfo() <= MAXARG_B &&
ttisshrstring(&getProto()->getConstants()[e->getInfo()]));
}
/*
** Check whether expression 'e' is a literal integer.
*/
static bool isKint (expdesc *e) {
return (e->getKind() == VKINT && !hasjumps(e));
}
/*
** Check whether expression 'e' is a literal integer in
** proper range to fit in register C
*/
static bool isCint (expdesc *e) {
return isKint(e) && (l_castS2U(e->getIntValue()) <= l_castS2U(MAXARG_C));
}
/*
** Check whether expression 'e' is a literal integer in
** proper range to fit in register sC
*/
static bool isSCint (expdesc *e) {
return isKint(e) && fitsC(e->getIntValue());
}
/*
** Check whether expression 'e' is a literal integer or float in
** proper range to fit in a register (sB or sC).
*/
static bool isSCnumber (expdesc *e, int *pi, int *isfloat) {
lua_Integer i;
if (e->getKind() == VKINT)
i = e->getIntValue();
else if (e->getKind() == VKFLT && luaV_flttointeger(e->getFloatValue(), &i, F2Imod::F2Ieq))
*isfloat = 1;
else
return false; /* not a number */
if (!hasjumps(e) && fitsC(i)) {
*pi = int2sC(cast_int(i));
return true;
}
else
return false;
}
/*
** Return false if folding can raise an error.
** Bitwise operations need operands convertible to integers; division
** operations cannot have 0 as divisor.
*/
static bool validop (int op, TValue *v1, TValue *v2) {
switch (op) {
case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
lua_Integer i;
return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) &&
luaV_tointegerns(v2, &i, LUA_FLOORN2I));
}
case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
return (nvalue(v2) != 0);
default: return true; /* everything else is valid */
}
}
/*
** Try to "constant-fold" an operation; return 1 iff successful.
** (In this case, 'e1' has the final result.)
*/
int FuncState::constfolding(int op, expdesc *e1, const expdesc *e2) {
TValue v1, v2, res;
if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
return 0; /* non-numeric operands or not safe to fold */
if (!luaO_rawarith(getLexState()->getLuaState(), op, &v1, &v2, &res))
return 0; /* operation failed */
if (ttisinteger(&res)) {
e1->setKind(VKINT);
e1->setIntValue(ivalue(&res));
}
else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
lua_Number n = fltvalue(&res);
if (luai_numisnan(n) || n == 0)
return 0;
e1->setKind(VKFLT);
e1->setFloatValue(n);
}
return 1;
}
/*
** Convert a BinOpr to an OpCode (ORDER OPR - ORDER OP)
*/
static inline OpCode binopr2op (BinOpr opr, BinOpr baser, OpCode base) {
lua_assert(baser <= opr &&
((baser == BinOpr::OPR_ADD && opr <= BinOpr::OPR_SHR) ||
(baser == BinOpr::OPR_LT && opr <= BinOpr::OPR_LE)));
return static_cast<OpCode>((cast_int(opr) - cast_int(baser)) + cast_int(base));
}
/*
** Convert a UnOpr to an OpCode (ORDER OPR - ORDER OP)
*/
static inline OpCode unopr2op (UnOpr opr) {
return static_cast<OpCode>((cast_int(opr) - cast_int(UnOpr::OPR_MINUS)) +
cast_int(OP_UNM));
}
/*
** Convert a BinOpr to a tag method (ORDER OPR - ORDER TM)
*/
static inline TMS binopr2TM (BinOpr opr) {
lua_assert(BinOpr::OPR_ADD <= opr && opr <= BinOpr::OPR_SHR);
return static_cast<TMS>((cast_int(opr) - cast_int(BinOpr::OPR_ADD)) + cast_int(TMS::TM_ADD));
}
/*
** Emit code for unary expressions that "produce values"
** (everything but 'not').
** Expression to produce final result will be encoded in 'e'.
*/
void FuncState::codeunexpval(OpCode op, expdesc *e, int line) {
int r = exp2anyreg(e); /* opcodes operate only on registers */
freeExpression(e);
e->setInfo(codeABC(op, 0, r, 0)); /* generate opcode */
e->setKind(VRELOC); /* all those operations are relocatable */
fixline(line);
}
/*
** Emit code for binary expressions that "produce values"
** (everything but logical operators 'and'/'or' and comparison
** operators).
** Expression to produce final result will be encoded in 'e1'.
*/
void FuncState::finishbinexpval(expdesc *e1, expdesc *e2, OpCode op, int v2,
int flip, int line, OpCode mmop, TMS event) {
int v1 = exp2anyreg(e1);
int instrPos = codeABCk(op, 0, v1, v2, 0);
freeExpressions(e1, e2);
e1->setInfo(instrPos);
e1->setKind(VRELOC); /* all those operations are relocatable */
fixline(line);
codeABCk(mmop, v1, v2, cast_int(event), flip); /* metamethod */
fixline(line);
}
/*
** Emit code for binary expressions that "produce values" over
** two registers.
*/
void FuncState::codebinexpval(BinOpr opr, expdesc *e1, expdesc *e2, int line) {
OpCode op = binopr2op(opr, BinOpr::OPR_ADD, OP_ADD);
int v2 = exp2anyreg(e2); /* make sure 'e2' is in a register */
/* 'e1' must be already in a register or it is a constant */
lua_assert((VNIL <= e1->getKind() && e1->getKind() <= VKSTR) ||
e1->getKind() == VNONRELOC || e1->getKind() == VRELOC);
lua_assert(OP_ADD <= op && op <= OP_SHR);
finishbinexpval(e1, e2, op, v2, 0, line, OP_MMBIN, binopr2TM(opr));
}
/*
** Code binary operators with immediate operands.
*/
void FuncState::codebini(OpCode op, expdesc *e1, expdesc *e2, int flip,
int line, TMS event) {
int v2 = int2sC(cast_int(e2->getIntValue())); /* immediate operand */
lua_assert(e2->getKind() == VKINT);
finishbinexpval(e1, e2, op, v2, flip, line, OP_MMBINI, event);
}
/*
** Code binary operators with K operand.
*/
void FuncState::codebinK(BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) {
TMS event = binopr2TM(opr);
int v2 = e2->getInfo(); /* K index */
OpCode op = binopr2op(opr, BinOpr::OPR_ADD, OP_ADDK);
finishbinexpval(e1, e2, op, v2, flip, line, OP_MMBINK, event);
}
/* Try to code a binary operator negating its second operand.
** For the metamethod, 2nd operand must keep its original value.
*/
int FuncState::finishbinexpneg(expdesc *e1, expdesc *e2, OpCode op, int line, TMS event) {
if (!isKint(e2))
return 0; /* not an integer constant */
else {
lua_Integer i2 = e2->getIntValue();
if (!(fitsC(i2) && fitsC(-i2)))
return 0; /* not in the proper range */
else { /* operating a small integer constant */
int v2 = cast_int(i2);
finishbinexpval(e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
/* correct metamethod argument */
SETARG_B(getProto()->getCode()[getPC() - 1], static_cast<unsigned int>(int2sC(v2)));
return 1; /* successfully coded */
}
}
}
static void swapexps (expdesc *e1, expdesc *e2) {
expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
}
/*
** Code binary operators with no constant operand.
*/
void FuncState::codebinNoK(BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) {
if (flip)
swapexps(e1, e2); /* back to original order */
codebinexpval(opr, e1, e2, line); /* use standard operators */
}
/*
** Code arithmetic operators ('+', '-', ...). If second operand is a
** constant in the proper range, use variant opcodes with K operands.
*/
void FuncState::codearith(BinOpr opr, expdesc *e1, expdesc *e2, int flip, int line) {
if (tonumeral(e2, nullptr) && exp2K(e2)) /* K operand? */
codebinK(opr, e1, e2, flip, line);
else /* 'e2' is neither an immediate nor a K operand */
codebinNoK(opr, e1, e2, flip, line);
}
/*
** Code commutative operators ('+', '*'). If first operand is a
** numeric constant, change order of operands to try to use an
** immediate or K operator.
*/
void FuncState::codecommutative(BinOpr op, expdesc *e1, expdesc *e2, int line) {
int flip = 0;
if (tonumeral(e1, nullptr)) { /* is first operand a numeric constant? */
swapexps(e1, e2); /* change order */
flip = 1;
}
if (op == BinOpr::OPR_ADD && isSCint(e2)) /* immediate operand? */
codebini(OP_ADDI, e1, e2, flip, line, TMS::TM_ADD);
else
codearith(op, e1, e2, flip, line);
}
/*
** Code bitwise operations; they are all commutative, so the function
** tries to put an integer constant as the 2nd operand (a K operand).
*/
void FuncState::codebitwise(BinOpr opr, expdesc *e1, expdesc *e2, int line) {
int flip = 0;
if (e1->getKind() == VKINT) {
swapexps(e1, e2); /* 'e2' will be the constant operand */
flip = 1;
}
if (e2->getKind() == VKINT && exp2K(e2)) /* K operand? */
codebinK(opr, e1, e2, flip, line);
else /* no constants */
codebinNoK(opr, e1, e2, flip, line);
}
/*
** Emit code for order comparisons. When using an immediate operand,
** 'isfloat' tells whether the original value was a float.
*/
void FuncState::codeorder(BinOpr opr, expdesc *e1, expdesc *e2) {
int r1, r2;
int im;
int isfloat = 0;
OpCode op;
if (isSCnumber(e2, &im, &isfloat)) {
/* use immediate operand */
r1 = exp2anyreg(e1);
r2 = im;
op = binopr2op(opr, BinOpr::OPR_LT, OP_LTI);