1 /*
2 ** $Id: lcode.c $
3 ** Code generator for Lua
4 ** See Copyright Notice in lua.h
5 */
6
7 #define lcode_c
8 #define LUA_CORE
9
10 #include "lprefix.h"
11
12
13 #include <limits.h>
14 #include <math.h>
15 #include <stdlib.h>
16
17 #include "lua.h"
18
19 #include "lcode.h"
20 #include "ldebug.h"
21 #include "ldo.h"
22 #include "lgc.h"
23 #include "llex.h"
24 #include "lmem.h"
25 #include "lobject.h"
26 #include "lopcodes.h"
27 #include "lparser.h"
28 #include "lstring.h"
29 #include "ltable.h"
30 #include "lvm.h"
31
32
33 /* Maximum number of registers in a Lua function (must fit in 8 bits) */
34 #define MAXREGS 255
35
36
37 #define hasjumps(e) ((e)->t != (e)->f)
38
39
40 static int codesJ (FuncState *fs, OpCode o, int sj, int k);
41
42
43
44 /* semantic error */
luaK_semerror(LexState * ls,const char * msg)45 l_noret luaK_semerror (LexState *ls, const char *msg) {
46 ls->t.token = 0; /* remove "near <token>" from final message */
47 luaX_syntaxerror(ls, msg);
48 }
49
50
51 /*
52 ** If expression is a numeric constant, fills 'v' with its value
53 ** and returns 1. Otherwise, returns 0.
54 */
tonumeral(const expdesc * e,TValue * v)55 static int tonumeral (const expdesc *e, TValue *v) {
56 if (hasjumps(e))
57 return 0; /* not a numeral */
58 switch (e->k) {
59 case VKINT:
60 if (v) setivalue(v, e->u.ival);
61 return 1;
62 case VKFLT:
63 if (v) setfltvalue(v, e->u.nval);
64 return 1;
65 default: return 0;
66 }
67 }
68
69
70 /*
71 ** Get the constant value from a constant expression
72 */
const2val(FuncState * fs,const expdesc * e)73 static TValue *const2val (FuncState *fs, const expdesc *e) {
74 lua_assert(e->k == VCONST);
75 return &fs->ls->dyd->actvar.arr[e->u.info].k;
76 }
77
78
79 /*
80 ** If expression is a constant, fills 'v' with its value
81 ** and returns 1. Otherwise, returns 0.
82 */
luaK_exp2const(FuncState * fs,const expdesc * e,TValue * v)83 int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {
84 if (hasjumps(e))
85 return 0; /* not a constant */
86 switch (e->k) {
87 case VFALSE:
88 setbfvalue(v);
89 return 1;
90 case VTRUE:
91 setbtvalue(v);
92 return 1;
93 case VNIL:
94 setnilvalue(v);
95 return 1;
96 case VKSTR: {
97 setsvalue(fs->ls->L, v, e->u.strval);
98 return 1;
99 }
100 case VCONST: {
101 setobj(fs->ls->L, v, const2val(fs, e));
102 return 1;
103 }
104 default: return tonumeral(e, v);
105 }
106 }
107
108
109 /*
110 ** Return the previous instruction of the current code. If there
111 ** may be a jump target between the current instruction and the
112 ** previous one, return an invalid instruction (to avoid wrong
113 ** optimizations).
114 */
previousinstruction(FuncState * fs)115 static Instruction *previousinstruction (FuncState *fs) {
116 static const Instruction invalidinstruction = ~(Instruction)0;
117 if (fs->pc > fs->lasttarget)
118 return &fs->f->code[fs->pc - 1]; /* previous instruction */
119 else
120 return cast(Instruction*, &invalidinstruction);
121 }
122
123
124 /*
125 ** Create a OP_LOADNIL instruction, but try to optimize: if the previous
126 ** instruction is also OP_LOADNIL and ranges are compatible, adjust
127 ** range of previous instruction instead of emitting a new one. (For
128 ** instance, 'local a; local b' will generate a single opcode.)
129 */
luaK_nil(FuncState * fs,int from,int n)130 void luaK_nil (FuncState *fs, int from, int n) {
131 int l = from + n - 1; /* last register to set nil */
132 Instruction *previous = previousinstruction(fs);
133 if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */
134 int pfrom = GETARG_A(*previous); /* get previous range */
135 int pl = pfrom + GETARG_B(*previous);
136 if ((pfrom <= from && from <= pl + 1) ||
137 (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
138 if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
139 if (pl > l) l = pl; /* l = max(l, pl) */
140 SETARG_A(*previous, from);
141 SETARG_B(*previous, l - from);
142 return;
143 } /* else go through */
144 }
145 luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
146 }
147
148
149 /*
150 ** Gets the destination address of a jump instruction. Used to traverse
151 ** a list of jumps.
152 */
getjump(FuncState * fs,int pc)153 static int getjump (FuncState *fs, int pc) {
154 int offset = GETARG_sJ(fs->f->code[pc]);
155 if (offset == NO_JUMP) /* point to itself represents end of list */
156 return NO_JUMP; /* end of list */
157 else
158 return (pc+1)+offset; /* turn offset into absolute position */
159 }
160
161
162 /*
163 ** Fix jump instruction at position 'pc' to jump to 'dest'.
164 ** (Jump addresses are relative in Lua)
165 */
fixjump(FuncState * fs,int pc,int dest)166 static void fixjump (FuncState *fs, int pc, int dest) {
167 Instruction *jmp = &fs->f->code[pc];
168 int offset = dest - (pc + 1);
169 lua_assert(dest != NO_JUMP);
170 if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))
171 luaX_syntaxerror(fs->ls, "control structure too long");
172 lua_assert(GET_OPCODE(*jmp) == OP_JMP);
173 SETARG_sJ(*jmp, offset);
174 }
175
176
177 /*
178 ** Concatenate jump-list 'l2' into jump-list 'l1'
179 */
luaK_concat(FuncState * fs,int * l1,int l2)180 void luaK_concat (FuncState *fs, int *l1, int l2) {
181 if (l2 == NO_JUMP) return; /* nothing to concatenate? */
182 else if (*l1 == NO_JUMP) /* no original list? */
183 *l1 = l2; /* 'l1' points to 'l2' */
184 else {
185 int list = *l1;
186 int next;
187 while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
188 list = next;
189 fixjump(fs, list, l2); /* last element links to 'l2' */
190 }
191 }
192
193
194 /*
195 ** Create a jump instruction and return its position, so its destination
196 ** can be fixed later (with 'fixjump').
197 */
luaK_jump(FuncState * fs)198 int luaK_jump (FuncState *fs) {
199 return codesJ(fs, OP_JMP, NO_JUMP, 0);
200 }
201
202
203 /*
204 ** Code a 'return' instruction
205 */
luaK_ret(FuncState * fs,int first,int nret)206 void luaK_ret (FuncState *fs, int first, int nret) {
207 OpCode op;
208 switch (nret) {
209 case 0: op = OP_RETURN0; break;
210 case 1: op = OP_RETURN1; break;
211 default: op = OP_RETURN; break;
212 }
213 luaK_codeABC(fs, op, first, nret + 1, 0);
214 }
215
216
217 /*
218 ** Code a "conditional jump", that is, a test or comparison opcode
219 ** followed by a jump. Return jump position.
220 */
condjump(FuncState * fs,OpCode op,int A,int B,int C,int k)221 static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) {
222 luaK_codeABCk(fs, op, A, B, C, k);
223 return luaK_jump(fs);
224 }
225
226
227 /*
228 ** returns current 'pc' and marks it as a jump target (to avoid wrong
229 ** optimizations with consecutive instructions not in the same basic block).
230 */
luaK_getlabel(FuncState * fs)231 int luaK_getlabel (FuncState *fs) {
232 fs->lasttarget = fs->pc;
233 return fs->pc;
234 }
235
236
237 /*
238 ** Returns the position of the instruction "controlling" a given
239 ** jump (that is, its condition), or the jump itself if it is
240 ** unconditional.
241 */
getjumpcontrol(FuncState * fs,int pc)242 static Instruction *getjumpcontrol (FuncState *fs, int pc) {
243 Instruction *pi = &fs->f->code[pc];
244 if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
245 return pi-1;
246 else
247 return pi;
248 }
249
250
251 /*
252 ** Patch destination register for a TESTSET instruction.
253 ** If instruction in position 'node' is not a TESTSET, return 0 ("fails").
254 ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination
255 ** register. Otherwise, change instruction to a simple 'TEST' (produces
256 ** no register value)
257 */
patchtestreg(FuncState * fs,int node,int reg)258 static int patchtestreg (FuncState *fs, int node, int reg) {
259 Instruction *i = getjumpcontrol(fs, node);
260 if (GET_OPCODE(*i) != OP_TESTSET)
261 return 0; /* cannot patch other instructions */
262 if (reg != NO_REG && reg != GETARG_B(*i))
263 SETARG_A(*i, reg);
264 else {
265 /* no register to put value or register already has the value;
266 change instruction to simple test */
267 *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i));
268 }
269 return 1;
270 }
271
272
273 /*
274 ** Traverse a list of tests ensuring no one produces a value
275 */
removevalues(FuncState * fs,int list)276 static void removevalues (FuncState *fs, int list) {
277 for (; list != NO_JUMP; list = getjump(fs, list))
278 patchtestreg(fs, list, NO_REG);
279 }
280
281
282 /*
283 ** Traverse a list of tests, patching their destination address and
284 ** registers: tests producing values jump to 'vtarget' (and put their
285 ** values in 'reg'), other tests jump to 'dtarget'.
286 */
patchlistaux(FuncState * fs,int list,int vtarget,int reg,int dtarget)287 static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
288 int dtarget) {
289 while (list != NO_JUMP) {
290 int next = getjump(fs, list);
291 if (patchtestreg(fs, list, reg))
292 fixjump(fs, list, vtarget);
293 else
294 fixjump(fs, list, dtarget); /* jump to default target */
295 list = next;
296 }
297 }
298
299
300 /*
301 ** Path all jumps in 'list' to jump to 'target'.
302 ** (The assert means that we cannot fix a jump to a forward address
303 ** because we only know addresses once code is generated.)
304 */
luaK_patchlist(FuncState * fs,int list,int target)305 void luaK_patchlist (FuncState *fs, int list, int target) {
306 lua_assert(target <= fs->pc);
307 patchlistaux(fs, list, target, NO_REG, target);
308 }
309
310
luaK_patchtohere(FuncState * fs,int list)311 void luaK_patchtohere (FuncState *fs, int list) {
312 int hr = luaK_getlabel(fs); /* mark "here" as a jump target */
313 luaK_patchlist(fs, list, hr);
314 }
315
316
317 /*
318 ** MAXimum number of successive Instructions WiTHout ABSolute line
319 ** information.
320 */
321 #if !defined(MAXIWTHABS)
322 #define MAXIWTHABS 120
323 #endif
324
325
326 /* limit for difference between lines in relative line info. */
327 #define LIMLINEDIFF 0x80
328
329
330 /*
331 ** Save line info for a new instruction. If difference from last line
332 ** does not fit in a byte, of after that many instructions, save a new
333 ** absolute line info; (in that case, the special value 'ABSLINEINFO'
334 ** in 'lineinfo' signals the existence of this absolute information.)
335 ** Otherwise, store the difference from last line in 'lineinfo'.
336 */
savelineinfo(FuncState * fs,Proto * f,int line)337 static void savelineinfo (FuncState *fs, Proto *f, int line) {
338 int linedif = line - fs->previousline;
339 int pc = fs->pc - 1; /* last instruction coded */
340 if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ > MAXIWTHABS) {
341 luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,
342 f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines");
343 f->abslineinfo[fs->nabslineinfo].pc = pc;
344 f->abslineinfo[fs->nabslineinfo++].line = line;
345 linedif = ABSLINEINFO; /* signal that there is absolute information */
346 fs->iwthabs = 0; /* restart counter */
347 }
348 luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,
349 MAX_INT, "opcodes");
350 f->lineinfo[pc] = linedif;
351 fs->previousline = line; /* last line saved */
352 }
353
354
355 /*
356 ** Remove line information from the last instruction.
357 ** If line information for that instruction is absolute, set 'iwthabs'
358 ** above its max to force the new (replacing) instruction to have
359 ** absolute line info, too.
360 */
removelastlineinfo(FuncState * fs)361 static void removelastlineinfo (FuncState *fs) {
362 Proto *f = fs->f;
363 int pc = fs->pc - 1; /* last instruction coded */
364 if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */
365 fs->previousline -= f->lineinfo[pc]; /* correct last line saved */
366 fs->iwthabs--; /* undo previous increment */
367 }
368 else { /* absolute line information */
369 lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc);
370 fs->nabslineinfo--; /* remove it */
371 fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */
372 }
373 }
374
375
376 /*
377 ** Remove the last instruction created, correcting line information
378 ** accordingly.
379 */
removelastinstruction(FuncState * fs)380 static void removelastinstruction (FuncState *fs) {
381 removelastlineinfo(fs);
382 fs->pc--;
383 }
384
385
386 /*
387 ** Emit instruction 'i', checking for array sizes and saving also its
388 ** line information. Return 'i' position.
389 */
luaK_code(FuncState * fs,Instruction i)390 int luaK_code (FuncState *fs, Instruction i) {
391 Proto *f = fs->f;
392 /* put new instruction in code array */
393 luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
394 MAX_INT, "opcodes");
395 f->code[fs->pc++] = i;
396 savelineinfo(fs, f, fs->ls->lastline);
397 return fs->pc - 1; /* index of new instruction */
398 }
399
400
401 /*
402 ** Format and emit an 'iABC' instruction. (Assertions check consistency
403 ** of parameters versus opcode.)
404 */
luaK_codeABCk(FuncState * fs,OpCode o,int a,int b,int c,int k)405 int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) {
406 lua_assert(getOpMode(o) == iABC);
407 lua_assert(a <= MAXARG_A && b <= MAXARG_B &&
408 c <= MAXARG_C && (k & ~1) == 0);
409 return luaK_code(fs, CREATE_ABCk(o, a, b, c, k));
410 }
411
412
413 /*
414 ** Format and emit an 'iABx' instruction.
415 */
luaK_codeABx(FuncState * fs,OpCode o,int a,unsigned int bc)416 int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
417 lua_assert(getOpMode(o) == iABx);
418 lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
419 return luaK_code(fs, CREATE_ABx(o, a, bc));
420 }
421
422
423 /*
424 ** Format and emit an 'iAsBx' instruction.
425 */
luaK_codeAsBx(FuncState * fs,OpCode o,int a,int bc)426 int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) {
427 unsigned int b = bc + OFFSET_sBx;
428 lua_assert(getOpMode(o) == iAsBx);
429 lua_assert(a <= MAXARG_A && b <= MAXARG_Bx);
430 return luaK_code(fs, CREATE_ABx(o, a, b));
431 }
432
433
434 /*
435 ** Format and emit an 'isJ' instruction.
436 */
codesJ(FuncState * fs,OpCode o,int sj,int k)437 static int codesJ (FuncState *fs, OpCode o, int sj, int k) {
438 unsigned int j = sj + OFFSET_sJ;
439 lua_assert(getOpMode(o) == isJ);
440 lua_assert(j <= MAXARG_sJ && (k & ~1) == 0);
441 return luaK_code(fs, CREATE_sJ(o, j, k));
442 }
443
444
445 /*
446 ** Emit an "extra argument" instruction (format 'iAx')
447 */
codeextraarg(FuncState * fs,int a)448 static int codeextraarg (FuncState *fs, int a) {
449 lua_assert(a <= MAXARG_Ax);
450 return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
451 }
452
453
454 /*
455 ** Emit a "load constant" instruction, using either 'OP_LOADK'
456 ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'
457 ** instruction with "extra argument".
458 */
luaK_codek(FuncState * fs,int reg,int k)459 static int luaK_codek (FuncState *fs, int reg, int k) {
460 if (k <= MAXARG_Bx)
461 return luaK_codeABx(fs, OP_LOADK, reg, k);
462 else {
463 int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
464 codeextraarg(fs, k);
465 return p;
466 }
467 }
468
469
470 /*
471 ** Check register-stack level, keeping track of its maximum size
472 ** in field 'maxstacksize'
473 */
luaK_checkstack(FuncState * fs,int n)474 void luaK_checkstack (FuncState *fs, int n) {
475 int newstack = fs->freereg + n;
476 if (newstack > fs->f->maxstacksize) {
477 if (newstack >= MAXREGS)
478 luaX_syntaxerror(fs->ls,
479 "function or expression needs too many registers");
480 fs->f->maxstacksize = cast_byte(newstack);
481 }
482 }
483
484
485 /*
486 ** Reserve 'n' registers in register stack
487 */
luaK_reserveregs(FuncState * fs,int n)488 void luaK_reserveregs (FuncState *fs, int n) {
489 luaK_checkstack(fs, n);
490 fs->freereg += n;
491 }
492
493
494 /*
495 ** Free register 'reg', if it is neither a constant index nor
496 ** a local variable.
497 )
498 */
freereg(FuncState * fs,int reg)499 static void freereg (FuncState *fs, int reg) {
500 if (reg >= luaY_nvarstack(fs)) {
501 fs->freereg--;
502 lua_assert(reg == fs->freereg);
503 }
504 }
505
506
507 /*
508 ** Free two registers in proper order
509 */
freeregs(FuncState * fs,int r1,int r2)510 static void freeregs (FuncState *fs, int r1, int r2) {
511 if (r1 > r2) {
512 freereg(fs, r1);
513 freereg(fs, r2);
514 }
515 else {
516 freereg(fs, r2);
517 freereg(fs, r1);
518 }
519 }
520
521
522 /*
523 ** Free register used by expression 'e' (if any)
524 */
freeexp(FuncState * fs,expdesc * e)525 static void freeexp (FuncState *fs, expdesc *e) {
526 if (e->k == VNONRELOC)
527 freereg(fs, e->u.info);
528 }
529
530
531 /*
532 ** Free registers used by expressions 'e1' and 'e2' (if any) in proper
533 ** order.
534 */
freeexps(FuncState * fs,expdesc * e1,expdesc * e2)535 static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {
536 int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1;
537 int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1;
538 freeregs(fs, r1, r2);
539 }
540
541
542 /*
543 ** Add constant 'v' to prototype's list of constants (field 'k').
544 ** Use scanner's table to cache position of constants in constant list
545 ** and try to reuse constants. Because some values should not be used
546 ** as keys (nil cannot be a key, integer keys can collapse with float
547 ** keys), the caller must provide a useful 'key' for indexing the cache.
548 */
addk(FuncState * fs,TValue * key,TValue * v)549 static int addk (FuncState *fs, TValue *key, TValue *v) {
550 lua_State *L = fs->ls->L;
551 Proto *f = fs->f;
552 TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */
553 int k, oldsize;
554 if (ttisinteger(idx)) { /* is there an index there? */
555 k = cast_int(ivalue(idx));
556 /* correct value? (warning: must distinguish floats from integers!) */
557 if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) &&
558 luaV_rawequalobj(&f->k[k], v))
559 return k; /* reuse index */
560 }
561 /* constant not found; create a new entry */
562 oldsize = f->sizek;
563 k = fs->nk;
564 /* numerical value does not need GC barrier;
565 table has no metatable, so it does not need to invalidate cache */
566 setivalue(idx, k);
567 luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
568 while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
569 setobj(L, &f->k[k], v);
570 fs->nk++;
571 luaC_barrier(L, f, v);
572 return k;
573 }
574
575
576 /*
577 ** Add a string to list of constants and return its index.
578 */
stringK(FuncState * fs,TString * s)579 static int stringK (FuncState *fs, TString *s) {
580 TValue o;
581 setsvalue(fs->ls->L, &o, s);
582 return addk(fs, &o, &o); /* use string itself as key */
583 }
584
585
586 /*
587 ** Add an integer to list of constants and return its index.
588 ** Integers use userdata as keys to avoid collision with floats with
589 ** same value; conversion to 'void*' is used only for hashing, so there
590 ** are no "precision" problems.
591 */
luaK_intK(FuncState * fs,lua_Integer n)592 static int luaK_intK (FuncState *fs, lua_Integer n) {
593 TValue k, o;
594 setpvalue(&k, cast_voidp(cast_sizet(n)));
595 setivalue(&o, n);
596 return addk(fs, &k, &o);
597 }
598
599 /*
600 ** Add a float to list of constants and return its index.
601 */
luaK_numberK(FuncState * fs,lua_Number r)602 static int luaK_numberK (FuncState *fs, lua_Number r) {
603 TValue o;
604 setfltvalue(&o, r);
605 return addk(fs, &o, &o); /* use number itself as key */
606 }
607
608
609 /*
610 ** Add a false to list of constants and return its index.
611 */
boolF(FuncState * fs)612 static int boolF (FuncState *fs) {
613 TValue o;
614 setbfvalue(&o);
615 return addk(fs, &o, &o); /* use boolean itself as key */
616 }
617
618
619 /*
620 ** Add a true to list of constants and return its index.
621 */
boolT(FuncState * fs)622 static int boolT (FuncState *fs) {
623 TValue o;
624 setbtvalue(&o);
625 return addk(fs, &o, &o); /* use boolean itself as key */
626 }
627
628
629 /*
630 ** Add nil to list of constants and return its index.
631 */
nilK(FuncState * fs)632 static int nilK (FuncState *fs) {
633 TValue k, v;
634 setnilvalue(&v);
635 /* cannot use nil as key; instead use table itself to represent nil */
636 sethvalue(fs->ls->L, &k, fs->ls->h);
637 return addk(fs, &k, &v);
638 }
639
640
641 /*
642 ** Check whether 'i' can be stored in an 'sC' operand. Equivalent to
643 ** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of
644 ** overflows in the hidden addition inside 'int2sC'.
645 */
fitsC(lua_Integer i)646 static int fitsC (lua_Integer i) {
647 return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));
648 }
649
650
651 /*
652 ** Check whether 'i' can be stored in an 'sBx' operand.
653 */
fitsBx(lua_Integer i)654 static int fitsBx (lua_Integer i) {
655 return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);
656 }
657
658
luaK_int(FuncState * fs,int reg,lua_Integer i)659 void luaK_int (FuncState *fs, int reg, lua_Integer i) {
660 if (fitsBx(i))
661 luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i));
662 else
663 luaK_codek(fs, reg, luaK_intK(fs, i));
664 }
665
666
luaK_float(FuncState * fs,int reg,lua_Number f)667 static void luaK_float (FuncState *fs, int reg, lua_Number f) {
668 lua_Integer fi;
669 if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi))
670 luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
671 else
672 luaK_codek(fs, reg, luaK_numberK(fs, f));
673 }
674
675
676 /*
677 ** Convert a constant in 'v' into an expression description 'e'
678 */
const2exp(TValue * v,expdesc * e)679 static void const2exp (TValue *v, expdesc *e) {
680 switch (ttypetag(v)) {
681 case LUA_VNUMINT:
682 e->k = VKINT; e->u.ival = ivalue(v);
683 break;
684 case LUA_VNUMFLT:
685 e->k = VKFLT; e->u.nval = fltvalue(v);
686 break;
687 case LUA_VFALSE:
688 e->k = VFALSE;
689 break;
690 case LUA_VTRUE:
691 e->k = VTRUE;
692 break;
693 case LUA_VNIL:
694 e->k = VNIL;
695 break;
696 case LUA_VSHRSTR: case LUA_VLNGSTR:
697 e->k = VKSTR; e->u.strval = tsvalue(v);
698 break;
699 default: lua_assert(0);
700 }
701 }
702
703
704 /*
705 ** Fix an expression to return the number of results 'nresults'.
706 ** 'e' must be a multi-ret expression (function call or vararg).
707 */
luaK_setreturns(FuncState * fs,expdesc * e,int nresults)708 void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
709 Instruction *pc = &getinstruction(fs, e);
710 if (e->k == VCALL) /* expression is an open function call? */
711 SETARG_C(*pc, nresults + 1);
712 else {
713 lua_assert(e->k == VVARARG);
714 SETARG_C(*pc, nresults + 1);
715 SETARG_A(*pc, fs->freereg);
716 luaK_reserveregs(fs, 1);
717 }
718 }
719
720
721 /*
722 ** Convert a VKSTR to a VK
723 */
str2K(FuncState * fs,expdesc * e)724 static void str2K (FuncState *fs, expdesc *e) {
725 lua_assert(e->k == VKSTR);
726 e->u.info = stringK(fs, e->u.strval);
727 e->k = VK;
728 }
729
730
731 /*
732 ** Fix an expression to return one result.
733 ** If expression is not a multi-ret expression (function call or
734 ** vararg), it already returns one result, so nothing needs to be done.
735 ** Function calls become VNONRELOC expressions (as its result comes
736 ** fixed in the base register of the call), while vararg expressions
737 ** become VRELOC (as OP_VARARG puts its results where it wants).
738 ** (Calls are created returning one result, so that does not need
739 ** to be fixed.)
740 */
luaK_setoneret(FuncState * fs,expdesc * e)741 void luaK_setoneret (FuncState *fs, expdesc *e) {
742 if (e->k == VCALL) { /* expression is an open function call? */
743 /* already returns 1 value */
744 lua_assert(GETARG_C(getinstruction(fs, e)) == 2);
745 e->k = VNONRELOC; /* result has fixed position */
746 e->u.info = GETARG_A(getinstruction(fs, e));
747 }
748 else if (e->k == VVARARG) {
749 SETARG_C(getinstruction(fs, e), 2);
750 e->k = VRELOC; /* can relocate its simple result */
751 }
752 }
753
754
755 /*
756 ** Ensure that expression 'e' is not a variable (nor a constant).
757 ** (Expression still may have jump lists.)
758 */
luaK_dischargevars(FuncState * fs,expdesc * e)759 void luaK_dischargevars (FuncState *fs, expdesc *e) {
760 switch (e->k) {
761 case VCONST: {
762 const2exp(const2val(fs, e), e);
763 break;
764 }
765 case VLOCAL: { /* already in a register */
766 e->u.info = e->u.var.sidx;
767 e->k = VNONRELOC; /* becomes a non-relocatable value */
768 break;
769 }
770 case VUPVAL: { /* move value to some (pending) register */
771 e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
772 e->k = VRELOC;
773 break;
774 }
775 case VINDEXUP: {
776 e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);
777 e->k = VRELOC;
778 break;
779 }
780 case VINDEXI: {
781 freereg(fs, e->u.ind.t);
782 e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);
783 e->k = VRELOC;
784 break;
785 }
786 case VINDEXSTR: {
787 freereg(fs, e->u.ind.t);
788 e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);
789 e->k = VRELOC;
790 break;
791 }
792 case VINDEXED: {
793 freeregs(fs, e->u.ind.t, e->u.ind.idx);
794 e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);
795 e->k = VRELOC;
796 break;
797 }
798 case VVARARG: case VCALL: {
799 luaK_setoneret(fs, e);
800 break;
801 }
802 default: break; /* there is one value available (somewhere) */
803 }
804 }
805
806
807 /*
808 ** Ensures expression value is in register 'reg' (and therefore
809 ** 'e' will become a non-relocatable expression).
810 ** (Expression still may have jump lists.)
811 */
discharge2reg(FuncState * fs,expdesc * e,int reg)812 static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
813 luaK_dischargevars(fs, e);
814 switch (e->k) {
815 case VNIL: {
816 luaK_nil(fs, reg, 1);
817 break;
818 }
819 case VFALSE: {
820 luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0);
821 break;
822 }
823 case VTRUE: {
824 luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0);
825 break;
826 }
827 case VKSTR: {
828 str2K(fs, e);
829 } /* FALLTHROUGH */
830 case VK: {
831 luaK_codek(fs, reg, e->u.info);
832 break;
833 }
834 case VKFLT: {
835 luaK_float(fs, reg, e->u.nval);
836 break;
837 }
838 case VKINT: {
839 luaK_int(fs, reg, e->u.ival);
840 break;
841 }
842 case VRELOC: {
843 Instruction *pc = &getinstruction(fs, e);
844 SETARG_A(*pc, reg); /* instruction will put result in 'reg' */
845 break;
846 }
847 case VNONRELOC: {
848 if (reg != e->u.info)
849 luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
850 break;
851 }
852 default: {
853 lua_assert(e->k == VJMP);
854 return; /* nothing to do... */
855 }
856 }
857 e->u.info = reg;
858 e->k = VNONRELOC;
859 }
860
861
862 /*
863 ** Ensures expression value is in any register.
864 ** (Expression still may have jump lists.)
865 */
discharge2anyreg(FuncState * fs,expdesc * e)866 static void discharge2anyreg (FuncState *fs, expdesc *e) {
867 if (e->k != VNONRELOC) { /* no fixed register yet? */
868 luaK_reserveregs(fs, 1); /* get a register */
869 discharge2reg(fs, e, fs->freereg-1); /* put value there */
870 }
871 }
872
873
code_loadbool(FuncState * fs,int A,OpCode op)874 static int code_loadbool (FuncState *fs, int A, OpCode op) {
875 luaK_getlabel(fs); /* those instructions may be jump targets */
876 return luaK_codeABC(fs, op, A, 0, 0);
877 }
878
879
880 /*
881 ** check whether list has any jump that do not produce a value
882 ** or produce an inverted value
883 */
need_value(FuncState * fs,int list)884 static int need_value (FuncState *fs, int list) {
885 for (; list != NO_JUMP; list = getjump(fs, list)) {
886 Instruction i = *getjumpcontrol(fs, list);
887 if (GET_OPCODE(i) != OP_TESTSET) return 1;
888 }
889 return 0; /* not found */
890 }
891
892
893 /*
894 ** Ensures final expression result (which includes results from its
895 ** jump lists) is in register 'reg'.
896 ** If expression has jumps, need to patch these jumps either to
897 ** its final position or to "load" instructions (for those tests
898 ** that do not produce values).
899 */
exp2reg(FuncState * fs,expdesc * e,int reg)900 static void exp2reg (FuncState *fs, expdesc *e, int reg) {
901 discharge2reg(fs, e, reg);
902 if (e->k == VJMP) /* expression itself is a test? */
903 luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
904 if (hasjumps(e)) {
905 int final; /* position after whole expression */
906 int p_f = NO_JUMP; /* position of an eventual LOAD false */
907 int p_t = NO_JUMP; /* position of an eventual LOAD true */
908 if (need_value(fs, e->t) || need_value(fs, e->f)) {
909 int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
910 p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */
911 p_t = code_loadbool(fs, reg, OP_LOADTRUE);
912 /* jump around these booleans if 'e' is not a test */
913 luaK_patchtohere(fs, fj);
914 }
915 final = luaK_getlabel(fs);
916 patchlistaux(fs, e->f, final, reg, p_f);
917 patchlistaux(fs, e->t, final, reg, p_t);
918 }
919 e->f = e->t = NO_JUMP;
920 e->u.info = reg;
921 e->k = VNONRELOC;
922 }
923
924
925 /*
926 ** Ensures final expression result is in next available register.
927 */
luaK_exp2nextreg(FuncState * fs,expdesc * e)928 void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
929 luaK_dischargevars(fs, e);
930 freeexp(fs, e);
931 luaK_reserveregs(fs, 1);
932 exp2reg(fs, e, fs->freereg - 1);
933 }
934
935
936 /*
937 ** Ensures final expression result is in some (any) register
938 ** and return that register.
939 */
luaK_exp2anyreg(FuncState * fs,expdesc * e)940 int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
941 luaK_dischargevars(fs, e);
942 if (e->k == VNONRELOC) { /* expression already has a register? */
943 if (!hasjumps(e)) /* no jumps? */
944 return e->u.info; /* result is already in a register */
945 if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */
946 exp2reg(fs, e, e->u.info); /* put final result in it */
947 return e->u.info;
948 }
949 }
950 luaK_exp2nextreg(fs, e); /* otherwise, use next available register */
951 return e->u.info;
952 }
953
954
955 /*
956 ** Ensures final expression result is either in a register
957 ** or in an upvalue.
958 */
luaK_exp2anyregup(FuncState * fs,expdesc * e)959 void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
960 if (e->k != VUPVAL || hasjumps(e))
961 luaK_exp2anyreg(fs, e);
962 }
963
964
965 /*
966 ** Ensures final expression result is either in a register
967 ** or it is a constant.
968 */
luaK_exp2val(FuncState * fs,expdesc * e)969 void luaK_exp2val (FuncState *fs, expdesc *e) {
970 if (hasjumps(e))
971 luaK_exp2anyreg(fs, e);
972 else
973 luaK_dischargevars(fs, e);
974 }
975
976
977 /*
978 ** Try to make 'e' a K expression with an index in the range of R/K
979 ** indices. Return true iff succeeded.
980 */
luaK_exp2K(FuncState * fs,expdesc * e)981 static int luaK_exp2K (FuncState *fs, expdesc *e) {
982 if (!hasjumps(e)) {
983 int info;
984 switch (e->k) { /* move constants to 'k' */
985 case VTRUE: info = boolT(fs); break;
986 case VFALSE: info = boolF(fs); break;
987 case VNIL: info = nilK(fs); break;
988 case VKINT: info = luaK_intK(fs, e->u.ival); break;
989 case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
990 case VKSTR: info = stringK(fs, e->u.strval); break;
991 case VK: info = e->u.info; break;
992 default: return 0; /* not a constant */
993 }
994 if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
995 e->k = VK; /* make expression a 'K' expression */
996 e->u.info = info;
997 return 1;
998 }
999 }
1000 /* else, expression doesn't fit; leave it unchanged */
1001 return 0;
1002 }
1003
1004
1005 /*
1006 ** Ensures final expression result is in a valid R/K index
1007 ** (that is, it is either in a register or in 'k' with an index
1008 ** in the range of R/K indices).
1009 ** Returns 1 iff expression is K.
1010 */
luaK_exp2RK(FuncState * fs,expdesc * e)1011 int luaK_exp2RK (FuncState *fs, expdesc *e) {
1012 if (luaK_exp2K(fs, e))
1013 return 1;
1014 else { /* not a constant in the right range: put it in a register */
1015 luaK_exp2anyreg(fs, e);
1016 return 0;
1017 }
1018 }
1019
1020
codeABRK(FuncState * fs,OpCode o,int a,int b,expdesc * ec)1021 static void codeABRK (FuncState *fs, OpCode o, int a, int b,
1022 expdesc *ec) {
1023 int k = luaK_exp2RK(fs, ec);
1024 luaK_codeABCk(fs, o, a, b, ec->u.info, k);
1025 }
1026
1027
1028 /*
1029 ** Generate code to store result of expression 'ex' into variable 'var'.
1030 */
luaK_storevar(FuncState * fs,expdesc * var,expdesc * ex)1031 void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
1032 switch (var->k) {
1033 case VLOCAL: {
1034 freeexp(fs, ex);
1035 exp2reg(fs, ex, var->u.var.sidx); /* compute 'ex' into proper place */
1036 return;
1037 }
1038 case VUPVAL: {
1039 int e = luaK_exp2anyreg(fs, ex);
1040 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
1041 break;
1042 }
1043 case VINDEXUP: {
1044 codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);
1045 break;
1046 }
1047 case VINDEXI: {
1048 codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);
1049 break;
1050 }
1051 case VINDEXSTR: {
1052 codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);
1053 break;
1054 }
1055 case VINDEXED: {
1056 codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);
1057 break;
1058 }
1059 default: lua_assert(0); /* invalid var kind to store */
1060 }
1061 freeexp(fs, ex);
1062 }
1063
1064
1065 /*
1066 ** Emit SELF instruction (convert expression 'e' into 'e:key(e,').
1067 */
luaK_self(FuncState * fs,expdesc * e,expdesc * key)1068 void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
1069 int ereg;
1070 luaK_exp2anyreg(fs, e);
1071 ereg = e->u.info; /* register where 'e' was placed */
1072 freeexp(fs, e);
1073 e->u.info = fs->freereg; /* base register for op_self */
1074 e->k = VNONRELOC; /* self expression has a fixed register */
1075 luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
1076 codeABRK(fs, OP_SELF, e->u.info, ereg, key);
1077 freeexp(fs, key);
1078 }
1079
1080
1081 /*
1082 ** Negate condition 'e' (where 'e' is a comparison).
1083 */
negatecondition(FuncState * fs,expdesc * e)1084 static void negatecondition (FuncState *fs, expdesc *e) {
1085 Instruction *pc = getjumpcontrol(fs, e->u.info);
1086 lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
1087 GET_OPCODE(*pc) != OP_TEST);
1088 SETARG_k(*pc, (GETARG_k(*pc) ^ 1));
1089 }
1090
1091
1092 /*
1093 ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
1094 ** is true, code will jump if 'e' is true.) Return jump position.
1095 ** Optimize when 'e' is 'not' something, inverting the condition
1096 ** and removing the 'not'.
1097 */
jumponcond(FuncState * fs,expdesc * e,int cond)1098 static int jumponcond (FuncState *fs, expdesc *e, int cond) {
1099 if (e->k == VRELOC) {
1100 Instruction ie = getinstruction(fs, e);
1101 if (GET_OPCODE(ie) == OP_NOT) {
1102 removelastinstruction(fs); /* remove previous OP_NOT */
1103 return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);
1104 }
1105 /* else go through */
1106 }
1107 discharge2anyreg(fs, e);
1108 freeexp(fs, e);
1109 return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);
1110 }
1111
1112
1113 /*
1114 ** Emit code to go through if 'e' is true, jump otherwise.
1115 */
luaK_goiftrue(FuncState * fs,expdesc * e)1116 void luaK_goiftrue (FuncState *fs, expdesc *e) {
1117 int pc; /* pc of new jump */
1118 luaK_dischargevars(fs, e);
1119 switch (e->k) {
1120 case VJMP: { /* condition? */
1121 negatecondition(fs, e); /* jump when it is false */
1122 pc = e->u.info; /* save jump position */
1123 break;
1124 }
1125 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
1126 pc = NO_JUMP; /* always true; do nothing */
1127 break;
1128 }
1129 default: {
1130 pc = jumponcond(fs, e, 0); /* jump when false */
1131 break;
1132 }
1133 }
1134 luaK_concat(fs, &e->f, pc); /* insert new jump in false list */
1135 luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */
1136 e->t = NO_JUMP;
1137 }
1138
1139
1140 /*
1141 ** Emit code to go through if 'e' is false, jump otherwise.
1142 */
luaK_goiffalse(FuncState * fs,expdesc * e)1143 void luaK_goiffalse (FuncState *fs, expdesc *e) {
1144 int pc; /* pc of new jump */
1145 luaK_dischargevars(fs, e);
1146 switch (e->k) {
1147 case VJMP: {
1148 pc = e->u.info; /* already jump if true */
1149 break;
1150 }
1151 case VNIL: case VFALSE: {
1152 pc = NO_JUMP; /* always false; do nothing */
1153 break;
1154 }
1155 default: {
1156 pc = jumponcond(fs, e, 1); /* jump if true */
1157 break;
1158 }
1159 }
1160 luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */
1161 luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */
1162 e->f = NO_JUMP;
1163 }
1164
1165
1166 /*
1167 ** Code 'not e', doing constant folding.
1168 */
codenot(FuncState * fs,expdesc * e)1169 static void codenot (FuncState *fs, expdesc *e) {
1170 switch (e->k) {
1171 case VNIL: case VFALSE: {
1172 e->k = VTRUE; /* true == not nil == not false */
1173 break;
1174 }
1175 case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
1176 e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
1177 break;
1178 }
1179 case VJMP: {
1180 negatecondition(fs, e);
1181 break;
1182 }
1183 case VRELOC:
1184 case VNONRELOC: {
1185 discharge2anyreg(fs, e);
1186 freeexp(fs, e);
1187 e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
1188 e->k = VRELOC;
1189 break;
1190 }
1191 default: lua_assert(0); /* cannot happen */
1192 }
1193 /* interchange true and false lists */
1194 { int temp = e->f; e->f = e->t; e->t = temp; }
1195 removevalues(fs, e->f); /* values are useless when negated */
1196 removevalues(fs, e->t);
1197 }
1198
1199
1200 /*
1201 ** Check whether expression 'e' is a small literal string
1202 */
isKstr(FuncState * fs,expdesc * e)1203 static int isKstr (FuncState *fs, expdesc *e) {
1204 return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B &&
1205 ttisshrstring(&fs->f->k[e->u.info]));
1206 }
1207
1208 /*
1209 ** Check whether expression 'e' is a literal integer.
1210 */
luaK_isKint(expdesc * e)1211 int luaK_isKint (expdesc *e) {
1212 return (e->k == VKINT && !hasjumps(e));
1213 }
1214
1215
1216 /*
1217 ** Check whether expression 'e' is a literal integer in
1218 ** proper range to fit in register C
1219 */
isCint(expdesc * e)1220 static int isCint (expdesc *e) {
1221 return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));
1222 }
1223
1224
1225 /*
1226 ** Check whether expression 'e' is a literal integer in
1227 ** proper range to fit in register sC
1228 */
isSCint(expdesc * e)1229 static int isSCint (expdesc *e) {
1230 return luaK_isKint(e) && fitsC(e->u.ival);
1231 }
1232
1233
1234 /*
1235 ** Check whether expression 'e' is a literal integer or float in
1236 ** proper range to fit in a register (sB or sC).
1237 */
isSCnumber(expdesc * e,int * pi,int * isfloat)1238 static int isSCnumber (expdesc *e, int *pi, int *isfloat) {
1239 lua_Integer i;
1240 if (e->k == VKINT)
1241 i = e->u.ival;
1242 else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq))
1243 *isfloat = 1;
1244 else
1245 return 0; /* not a number */
1246 if (!hasjumps(e) && fitsC(i)) {
1247 *pi = int2sC(cast_int(i));
1248 return 1;
1249 }
1250 else
1251 return 0;
1252 }
1253
1254
1255 /*
1256 ** Create expression 't[k]'. 't' must have its final result already in a
1257 ** register or upvalue. Upvalues can only be indexed by literal strings.
1258 ** Keys can be literal strings in the constant table or arbitrary
1259 ** values in registers.
1260 */
luaK_indexed(FuncState * fs,expdesc * t,expdesc * k)1261 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
1262 if (k->k == VKSTR)
1263 str2K(fs, k);
1264 lua_assert(!hasjumps(t) &&
1265 (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL));
1266 if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */
1267 luaK_exp2anyreg(fs, t); /* put it in a register */
1268 if (t->k == VUPVAL) {
1269 t->u.ind.t = t->u.info; /* upvalue index */
1270 t->u.ind.idx = k->u.info; /* literal string */
1271 t->k = VINDEXUP;
1272 }
1273 else {
1274 /* register index of the table */
1275 t->u.ind.t = (t->k == VLOCAL) ? t->u.var.sidx: t->u.info;
1276 if (isKstr(fs, k)) {
1277 t->u.ind.idx = k->u.info; /* literal string */
1278 t->k = VINDEXSTR;
1279 }
1280 else if (isCint(k)) {
1281 t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */
1282 t->k = VINDEXI;
1283 }
1284 else {
1285 t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */
1286 t->k = VINDEXED;
1287 }
1288 }
1289 }
1290
1291
1292 /*
1293 ** Return false if folding can raise an error.
1294 ** Bitwise operations need operands convertible to integers; division
1295 ** operations cannot have 0 as divisor.
1296 */
validop(int op,TValue * v1,TValue * v2)1297 static int validop (int op, TValue *v1, TValue *v2) {
1298 switch (op) {
1299 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
1300 case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
1301 lua_Integer i;
1302 return (tointegerns(v1, &i) && tointegerns(v2, &i));
1303 }
1304 case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
1305 return (nvalue(v2) != 0);
1306 default: return 1; /* everything else is valid */
1307 }
1308 }
1309
1310
1311 /*
1312 ** Try to "constant-fold" an operation; return 1 iff successful.
1313 ** (In this case, 'e1' has the final result.)
1314 */
constfolding(FuncState * fs,int op,expdesc * e1,const expdesc * e2)1315 static int constfolding (FuncState *fs, int op, expdesc *e1,
1316 const expdesc *e2) {
1317 TValue v1, v2, res;
1318 if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
1319 return 0; /* non-numeric operands or not safe to fold */
1320 luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
1321 if (ttisinteger(&res)) {
1322 e1->k = VKINT;
1323 e1->u.ival = ivalue(&res);
1324 }
1325 else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
1326 lua_Number n = fltvalue(&res);
1327 if (luai_numisnan(n) || n == 0)
1328 return 0;
1329 e1->k = VKFLT;
1330 e1->u.nval = n;
1331 }
1332 return 1;
1333 }
1334
1335
1336 /*
1337 ** Emit code for unary expressions that "produce values"
1338 ** (everything but 'not').
1339 ** Expression to produce final result will be encoded in 'e'.
1340 */
codeunexpval(FuncState * fs,OpCode op,expdesc * e,int line)1341 static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
1342 int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */
1343 freeexp(fs, e);
1344 e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */
1345 e->k = VRELOC; /* all those operations are relocatable */
1346 luaK_fixline(fs, line);
1347 }
1348
1349
1350 /*
1351 ** Emit code for binary expressions that "produce values"
1352 ** (everything but logical operators 'and'/'or' and comparison
1353 ** operators).
1354 ** Expression to produce final result will be encoded in 'e1'.
1355 */
finishbinexpval(FuncState * fs,expdesc * e1,expdesc * e2,OpCode op,int v2,int flip,int line,OpCode mmop,TMS event)1356 static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
1357 OpCode op, int v2, int flip, int line,
1358 OpCode mmop, TMS event) {
1359 int v1 = luaK_exp2anyreg(fs, e1);
1360 int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0);
1361 freeexps(fs, e1, e2);
1362 e1->u.info = pc;
1363 e1->k = VRELOC; /* all those operations are relocatable */
1364 luaK_fixline(fs, line);
1365 luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */
1366 luaK_fixline(fs, line);
1367 }
1368
1369
1370 /*
1371 ** Emit code for binary expressions that "produce values" over
1372 ** two registers.
1373 */
codebinexpval(FuncState * fs,OpCode op,expdesc * e1,expdesc * e2,int line)1374 static void codebinexpval (FuncState *fs, OpCode op,
1375 expdesc *e1, expdesc *e2, int line) {
1376 int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */
1377 lua_assert(OP_ADD <= op && op <= OP_SHR);
1378 finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN,
1379 cast(TMS, (op - OP_ADD) + TM_ADD));
1380 }
1381
1382
1383 /*
1384 ** Code binary operators with immediate operands.
1385 */
codebini(FuncState * fs,OpCode op,expdesc * e1,expdesc * e2,int flip,int line,TMS event)1386 static void codebini (FuncState *fs, OpCode op,
1387 expdesc *e1, expdesc *e2, int flip, int line,
1388 TMS event) {
1389 int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */
1390 lua_assert(e2->k == VKINT);
1391 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event);
1392 }
1393
1394
1395 /* Try to code a binary operator negating its second operand.
1396 ** For the metamethod, 2nd operand must keep its original value.
1397 */
finishbinexpneg(FuncState * fs,expdesc * e1,expdesc * e2,OpCode op,int line,TMS event)1398 static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,
1399 OpCode op, int line, TMS event) {
1400 if (!luaK_isKint(e2))
1401 return 0; /* not an integer constant */
1402 else {
1403 lua_Integer i2 = e2->u.ival;
1404 if (!(fitsC(i2) && fitsC(-i2)))
1405 return 0; /* not in the proper range */
1406 else { /* operating a small integer constant */
1407 int v2 = cast_int(i2);
1408 finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
1409 /* correct metamethod argument */
1410 SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2));
1411 return 1; /* successfully coded */
1412 }
1413 }
1414 }
1415
1416
swapexps(expdesc * e1,expdesc * e2)1417 static void swapexps (expdesc *e1, expdesc *e2) {
1418 expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
1419 }
1420
1421
1422 /*
1423 ** Code arithmetic operators ('+', '-', ...). If second operand is a
1424 ** constant in the proper range, use variant opcodes with K operands.
1425 */
codearith(FuncState * fs,BinOpr opr,expdesc * e1,expdesc * e2,int flip,int line)1426 static void codearith (FuncState *fs, BinOpr opr,
1427 expdesc *e1, expdesc *e2, int flip, int line) {
1428 TMS event = cast(TMS, opr + TM_ADD);
1429 if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */
1430 int v2 = e2->u.info; /* K index */
1431 OpCode op = cast(OpCode, opr + OP_ADDK);
1432 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event);
1433 }
1434 else { /* 'e2' is neither an immediate nor a K operand */
1435 OpCode op = cast(OpCode, opr + OP_ADD);
1436 if (flip)
1437 swapexps(e1, e2); /* back to original order */
1438 codebinexpval(fs, op, e1, e2, line); /* use standard operators */
1439 }
1440 }
1441
1442
1443 /*
1444 ** Code commutative operators ('+', '*'). If first operand is a
1445 ** numeric constant, change order of operands to try to use an
1446 ** immediate or K operator.
1447 */
codecommutative(FuncState * fs,BinOpr op,expdesc * e1,expdesc * e2,int line)1448 static void codecommutative (FuncState *fs, BinOpr op,
1449 expdesc *e1, expdesc *e2, int line) {
1450 int flip = 0;
1451 if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
1452 swapexps(e1, e2); /* change order */
1453 flip = 1;
1454 }
1455 if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */
1456 codebini(fs, cast(OpCode, OP_ADDI), e1, e2, flip, line, TM_ADD);
1457 else
1458 codearith(fs, op, e1, e2, flip, line);
1459 }
1460
1461
1462 /*
1463 ** Code bitwise operations; they are all associative, so the function
1464 ** tries to put an integer constant as the 2nd operand (a K operand).
1465 */
codebitwise(FuncState * fs,BinOpr opr,expdesc * e1,expdesc * e2,int line)1466 static void codebitwise (FuncState *fs, BinOpr opr,
1467 expdesc *e1, expdesc *e2, int line) {
1468 int flip = 0;
1469 int v2;
1470 OpCode op;
1471 if (e1->k == VKINT && luaK_exp2RK(fs, e1)) {
1472 swapexps(e1, e2); /* 'e2' will be the constant operand */
1473 flip = 1;
1474 }
1475 else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */
1476 op = cast(OpCode, opr + OP_ADD);
1477 codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */
1478 return;
1479 }
1480 v2 = e2->u.info; /* index in K array */
1481 op = cast(OpCode, opr + OP_ADDK);
1482 lua_assert(ttisinteger(&fs->f->k[v2]));
1483 finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK,
1484 cast(TMS, opr + TM_ADD));
1485 }
1486
1487
1488 /*
1489 ** Emit code for order comparisons. When using an immediate operand,
1490 ** 'isfloat' tells whether the original value was a float.
1491 */
codeorder(FuncState * fs,OpCode op,expdesc * e1,expdesc * e2)1492 static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
1493 int r1, r2;
1494 int im;
1495 int isfloat = 0;
1496 if (isSCnumber(e2, &im, &isfloat)) {
1497 /* use immediate operand */
1498 r1 = luaK_exp2anyreg(fs, e1);
1499 r2 = im;
1500 op = cast(OpCode, (op - OP_LT) + OP_LTI);
1501 }
1502 else if (isSCnumber(e1, &im, &isfloat)) {
1503 /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
1504 r1 = luaK_exp2anyreg(fs, e2);
1505 r2 = im;
1506 op = (op == OP_LT) ? OP_GTI : OP_GEI;
1507 }
1508 else { /* regular case, compare two registers */
1509 r1 = luaK_exp2anyreg(fs, e1);
1510 r2 = luaK_exp2anyreg(fs, e2);
1511 }
1512 freeexps(fs, e1, e2);
1513 e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);
1514 e1->k = VJMP;
1515 }
1516
1517
1518 /*
1519 ** Emit code for equality comparisons ('==', '~=').
1520 ** 'e1' was already put as RK by 'luaK_infix'.
1521 */
codeeq(FuncState * fs,BinOpr opr,expdesc * e1,expdesc * e2)1522 static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
1523 int r1, r2;
1524 int im;
1525 int isfloat = 0; /* not needed here, but kept for symmetry */
1526 OpCode op;
1527 if (e1->k != VNONRELOC) {
1528 lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
1529 swapexps(e1, e2);
1530 }
1531 r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */
1532 if (isSCnumber(e2, &im, &isfloat)) {
1533 op = OP_EQI;
1534 r2 = im; /* immediate operand */
1535 }
1536 else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */
1537 op = OP_EQK;
1538 r2 = e2->u.info; /* constant index */
1539 }
1540 else {
1541 op = OP_EQ; /* will compare two registers */
1542 r2 = luaK_exp2anyreg(fs, e2);
1543 }
1544 freeexps(fs, e1, e2);
1545 e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));
1546 e1->k = VJMP;
1547 }
1548
1549
1550 /*
1551 ** Apply prefix operation 'op' to expression 'e'.
1552 */
luaK_prefix(FuncState * fs,UnOpr op,expdesc * e,int line)1553 void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
1554 static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
1555 luaK_dischargevars(fs, e);
1556 switch (op) {
1557 case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
1558 if (constfolding(fs, op + LUA_OPUNM, e, &ef))
1559 break;
1560 /* else */ /* FALLTHROUGH */
1561 case OPR_LEN:
1562 codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line);
1563 break;
1564 case OPR_NOT: codenot(fs, e); break;
1565 default: lua_assert(0);
1566 }
1567 }
1568
1569
1570 /*
1571 ** Process 1st operand 'v' of binary operation 'op' before reading
1572 ** 2nd operand.
1573 */
luaK_infix(FuncState * fs,BinOpr op,expdesc * v)1574 void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
1575 luaK_dischargevars(fs, v);
1576 switch (op) {
1577 case OPR_AND: {
1578 luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
1579 break;
1580 }
1581 case OPR_OR: {
1582 luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */
1583 break;
1584 }
1585 case OPR_CONCAT: {
1586 luaK_exp2nextreg(fs, v); /* operand must be on the stack */
1587 break;
1588 }
1589 case OPR_ADD: case OPR_SUB:
1590 case OPR_MUL: case OPR_DIV: case OPR_IDIV:
1591 case OPR_MOD: case OPR_POW:
1592 case OPR_BAND: case OPR_BOR: case OPR_BXOR:
1593 case OPR_SHL: case OPR_SHR: {
1594 if (!tonumeral(v, NULL))
1595 luaK_exp2anyreg(fs, v);
1596 /* else keep numeral, which may be folded with 2nd operand */
1597 break;
1598 }
1599 case OPR_EQ: case OPR_NE: {
1600 if (!tonumeral(v, NULL))
1601 luaK_exp2RK(fs, v);
1602 /* else keep numeral, which may be an immediate operand */
1603 break;
1604 }
1605 case OPR_LT: case OPR_LE:
1606 case OPR_GT: case OPR_GE: {
1607 int dummy, dummy2;
1608 if (!isSCnumber(v, &dummy, &dummy2))
1609 luaK_exp2anyreg(fs, v);
1610 /* else keep numeral, which may be an immediate operand */
1611 break;
1612 }
1613 default: lua_assert(0);
1614 }
1615 }
1616
1617 /*
1618 ** Create code for '(e1 .. e2)'.
1619 ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',
1620 ** because concatenation is right associative), merge both CONCATs.
1621 */
codeconcat(FuncState * fs,expdesc * e1,expdesc * e2,int line)1622 static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
1623 Instruction *ie2 = previousinstruction(fs);
1624 if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */
1625 int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */
1626 lua_assert(e1->u.info + 1 == GETARG_A(*ie2));
1627 freeexp(fs, e2);
1628 SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */
1629 SETARG_B(*ie2, n + 1); /* will concatenate one more element */
1630 }
1631 else { /* 'e2' is not a concatenation */
1632 luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */
1633 freeexp(fs, e2);
1634 luaK_fixline(fs, line);
1635 }
1636 }
1637
1638
1639 /*
1640 ** Finalize code for binary operation, after reading 2nd operand.
1641 */
luaK_posfix(FuncState * fs,BinOpr opr,expdesc * e1,expdesc * e2,int line)1642 void luaK_posfix (FuncState *fs, BinOpr opr,
1643 expdesc *e1, expdesc *e2, int line) {
1644 luaK_dischargevars(fs, e2);
1645 if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2))
1646 return; /* done by folding */
1647 switch (opr) {
1648 case OPR_AND: {
1649 lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */
1650 luaK_concat(fs, &e2->f, e1->f);
1651 *e1 = *e2;
1652 break;
1653 }
1654 case OPR_OR: {
1655 lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */
1656 luaK_concat(fs, &e2->t, e1->t);
1657 *e1 = *e2;
1658 break;
1659 }
1660 case OPR_CONCAT: { /* e1 .. e2 */
1661 luaK_exp2nextreg(fs, e2);
1662 codeconcat(fs, e1, e2, line);
1663 break;
1664 }
1665 case OPR_ADD: case OPR_MUL: {
1666 codecommutative(fs, opr, e1, e2, line);
1667 break;
1668 }
1669 case OPR_SUB: {
1670 if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB))
1671 break; /* coded as (r1 + -I) */
1672 /* ELSE */
1673 } /* FALLTHROUGH */
1674 case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: {
1675 codearith(fs, opr, e1, e2, 0, line);
1676 break;
1677 }
1678 case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
1679 codebitwise(fs, opr, e1, e2, line);
1680 break;
1681 }
1682 case OPR_SHL: {
1683 if (isSCint(e1)) {
1684 swapexps(e1, e2);
1685 codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */
1686 }
1687 else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) {
1688 /* coded as (r1 >> -I) */;
1689 }
1690 else /* regular case (two registers) */
1691 codebinexpval(fs, OP_SHL, e1, e2, line);
1692 break;
1693 }
1694 case OPR_SHR: {
1695 if (isSCint(e2))
1696 codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */
1697 else /* regular case (two registers) */
1698 codebinexpval(fs, OP_SHR, e1, e2, line);
1699 break;
1700 }
1701 case OPR_EQ: case OPR_NE: {
1702 codeeq(fs, opr, e1, e2);
1703 break;
1704 }
1705 case OPR_LT: case OPR_LE: {
1706 OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ);
1707 codeorder(fs, op, e1, e2);
1708 break;
1709 }
1710 case OPR_GT: case OPR_GE: {
1711 /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */
1712 OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ);
1713 swapexps(e1, e2);
1714 codeorder(fs, op, e1, e2);
1715 break;
1716 }
1717 default: lua_assert(0);
1718 }
1719 }
1720
1721
1722 /*
1723 ** Change line information associated with current position, by removing
1724 ** previous info and adding it again with new line.
1725 */
luaK_fixline(FuncState * fs,int line)1726 void luaK_fixline (FuncState *fs, int line) {
1727 removelastlineinfo(fs);
1728 savelineinfo(fs, fs->f, line);
1729 }
1730
1731
luaK_settablesize(FuncState * fs,int pc,int ra,int asize,int hsize)1732 void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) {
1733 Instruction *inst = &fs->f->code[pc];
1734 int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */
1735 int extra = asize / (MAXARG_C + 1); /* higher bits of array size */
1736 int rc = asize % (MAXARG_C + 1); /* lower bits of array size */
1737 int k = (extra > 0); /* true iff needs extra argument */
1738 *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k);
1739 *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);
1740 }
1741
1742
1743 /*
1744 ** Emit a SETLIST instruction.
1745 ** 'base' is register that keeps table;
1746 ** 'nelems' is #table plus those to be stored now;
1747 ** 'tostore' is number of values (in registers 'base + 1',...) to add to
1748 ** table (or LUA_MULTRET to add up to stack top).
1749 */
luaK_setlist(FuncState * fs,int base,int nelems,int tostore)1750 void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
1751 lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);
1752 if (tostore == LUA_MULTRET)
1753 tostore = 0;
1754 if (nelems <= MAXARG_C)
1755 luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems);
1756 else {
1757 int extra = nelems / (MAXARG_C + 1);
1758 nelems %= (MAXARG_C + 1);
1759 luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1);
1760 codeextraarg(fs, extra);
1761 }
1762 fs->freereg = base + 1; /* free registers with list values */
1763 }
1764
1765
1766 /*
1767 ** return the final target of a jump (skipping jumps to jumps)
1768 */
finaltarget(Instruction * code,int i)1769 static int finaltarget (Instruction *code, int i) {
1770 int count;
1771 for (count = 0; count < 100; count++) { /* avoid infinite loops */
1772 Instruction pc = code[i];
1773 if (GET_OPCODE(pc) != OP_JMP)
1774 break;
1775 else
1776 i += GETARG_sJ(pc) + 1;
1777 }
1778 return i;
1779 }
1780
1781
1782 /*
1783 ** Do a final pass over the code of a function, doing small peephole
1784 ** optimizations and adjustments.
1785 */
luaK_finish(FuncState * fs)1786 void luaK_finish (FuncState *fs) {
1787 int i;
1788 Proto *p = fs->f;
1789 for (i = 0; i < fs->pc; i++) {
1790 Instruction *pc = &p->code[i];
1791 lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc));
1792 switch (GET_OPCODE(*pc)) {
1793 case OP_RETURN0: case OP_RETURN1: {
1794 if (!(fs->needclose || p->is_vararg))
1795 break; /* no extra work */
1796 /* else use OP_RETURN to do the extra work */
1797 SET_OPCODE(*pc, OP_RETURN);
1798 } /* FALLTHROUGH */
1799 case OP_RETURN: case OP_TAILCALL: {
1800 if (fs->needclose)
1801 SETARG_k(*pc, 1); /* signal that it needs to close */
1802 if (p->is_vararg)
1803 SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */
1804 break;
1805 }
1806 case OP_JMP: {
1807 int target = finaltarget(p->code, i);
1808 fixjump(fs, i, target);
1809 break;
1810 }
1811 default: break;
1812 }
1813 }
1814 }
1815