1 /*
2 ** $Id: lcode.c,v 2.99 2014/12/29 16:49:25 roberto Exp $
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 <math.h>
14 #include <stdlib.h>
15 
16 #include "lua.h"
17 
18 #include "lcode.h"
19 #include "ldebug.h"
20 #include "ldo.h"
21 #include "lgc.h"
22 #include "llex.h"
23 #include "lmem.h"
24 #include "lobject.h"
25 #include "lopcodes.h"
26 #include "lparser.h"
27 #include "lstring.h"
28 #include "ltable.h"
29 #include "lvm.h"
30 
31 
32 /* Maximum number of registers in a Lua function */
33 #define MAXREGS		250
34 
35 
36 #define hasjumps(e)	((e)->t != (e)->f)
37 
38 
tonumeral(expdesc * e,TValue * v)39 static int tonumeral(expdesc *e, TValue *v) {
40   if (e->t != NO_JUMP || e->f != NO_JUMP)
41     return 0;  /* not a numeral */
42   switch (e->k) {
43     case VKINT:
44       if (v) setivalue(v, e->u.ival);
45       return 1;
46     case VKFLT:
47       if (v) setfltvalue(v, e->u.nval);
48       return 1;
49     default: return 0;
50   }
51 }
52 
53 
luaK_nil(FuncState * fs,int from,int n)54 void luaK_nil (FuncState *fs, int from, int n) {
55   Instruction *previous;
56   int l = from + n - 1;  /* last register to set nil */
57   if (fs->pc > fs->lasttarget) {  /* no jumps to current position? */
58     previous = &fs->f->code[fs->pc-1];
59     if (GET_OPCODE(*previous) == OP_LOADNIL) {
60       int pfrom = GETARG_A(*previous);
61       int pl = pfrom + GETARG_B(*previous);
62       if ((pfrom <= from && from <= pl + 1) ||
63           (from <= pfrom && pfrom <= l + 1)) {  /* can connect both? */
64         if (pfrom < from) from = pfrom;  /* from = min(from, pfrom) */
65         if (pl > l) l = pl;  /* l = max(l, pl) */
66         SETARG_A(*previous, from);
67         SETARG_B(*previous, l - from);
68         return;
69       }
70     }  /* else go through */
71   }
72   luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0);  /* else no optimization */
73 }
74 
75 
luaK_jump(FuncState * fs)76 int luaK_jump (FuncState *fs) {
77   int jpc = fs->jpc;  /* save list of jumps to here */
78   int j;
79   fs->jpc = NO_JUMP;
80   j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
81   luaK_concat(fs, &j, jpc);  /* keep them on hold */
82   return j;
83 }
84 
85 
luaK_ret(FuncState * fs,int first,int nret)86 void luaK_ret (FuncState *fs, int first, int nret) {
87   luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
88 }
89 
90 
condjump(FuncState * fs,OpCode op,int A,int B,int C)91 static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
92   luaK_codeABC(fs, op, A, B, C);
93   return luaK_jump(fs);
94 }
95 
96 
fixjump(FuncState * fs,int pc,int dest)97 static void fixjump (FuncState *fs, int pc, int dest) {
98   Instruction *jmp = &fs->f->code[pc];
99   int offset = dest-(pc+1);
100   lua_assert(dest != NO_JUMP);
101   if (abs(offset) > MAXARG_sBx)
102     luaX_syntaxerror(fs->ls, "control structure too long");
103   SETARG_sBx(*jmp, offset);
104 }
105 
106 
107 /*
108 ** returns current 'pc' and marks it as a jump target (to avoid wrong
109 ** optimizations with consecutive instructions not in the same basic block).
110 */
luaK_getlabel(FuncState * fs)111 int luaK_getlabel (FuncState *fs) {
112   fs->lasttarget = fs->pc;
113   return fs->pc;
114 }
115 
116 
getjump(FuncState * fs,int pc)117 static int getjump (FuncState *fs, int pc) {
118   int offset = GETARG_sBx(fs->f->code[pc]);
119   if (offset == NO_JUMP)  /* point to itself represents end of list */
120     return NO_JUMP;  /* end of list */
121   else
122     return (pc+1)+offset;  /* turn offset into absolute position */
123 }
124 
125 
getjumpcontrol(FuncState * fs,int pc)126 static Instruction *getjumpcontrol (FuncState *fs, int pc) {
127   Instruction *pi = &fs->f->code[pc];
128   if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
129     return pi-1;
130   else
131     return pi;
132 }
133 
134 
135 /*
136 ** check whether list has any jump that do not produce a value
137 ** (or produce an inverted value)
138 */
need_value(FuncState * fs,int list)139 static int need_value (FuncState *fs, int list) {
140   for (; list != NO_JUMP; list = getjump(fs, list)) {
141     Instruction i = *getjumpcontrol(fs, list);
142     if (GET_OPCODE(i) != OP_TESTSET) return 1;
143   }
144   return 0;  /* not found */
145 }
146 
147 
patchtestreg(FuncState * fs,int node,int reg)148 static int patchtestreg (FuncState *fs, int node, int reg) {
149   Instruction *i = getjumpcontrol(fs, node);
150   if (GET_OPCODE(*i) != OP_TESTSET)
151     return 0;  /* cannot patch other instructions */
152   if (reg != NO_REG && reg != GETARG_B(*i))
153     SETARG_A(*i, reg);
154   else  /* no register to put value or register already has the value */
155     *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
156 
157   return 1;
158 }
159 
160 
removevalues(FuncState * fs,int list)161 static void removevalues (FuncState *fs, int list) {
162   for (; list != NO_JUMP; list = getjump(fs, list))
163       patchtestreg(fs, list, NO_REG);
164 }
165 
166 
patchlistaux(FuncState * fs,int list,int vtarget,int reg,int dtarget)167 static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
168                           int dtarget) {
169   while (list != NO_JUMP) {
170     int next = getjump(fs, list);
171     if (patchtestreg(fs, list, reg))
172       fixjump(fs, list, vtarget);
173     else
174       fixjump(fs, list, dtarget);  /* jump to default target */
175     list = next;
176   }
177 }
178 
179 
dischargejpc(FuncState * fs)180 static void dischargejpc (FuncState *fs) {
181   patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
182   fs->jpc = NO_JUMP;
183 }
184 
185 
luaK_patchlist(FuncState * fs,int list,int target)186 void luaK_patchlist (FuncState *fs, int list, int target) {
187   if (target == fs->pc)
188     luaK_patchtohere(fs, list);
189   else {
190     lua_assert(target < fs->pc);
191     patchlistaux(fs, list, target, NO_REG, target);
192   }
193 }
194 
195 
luaK_patchclose(FuncState * fs,int list,int level)196 void luaK_patchclose (FuncState *fs, int list, int level) {
197   level++;  /* argument is +1 to reserve 0 as non-op */
198   while (list != NO_JUMP) {
199     int next = getjump(fs, list);
200     lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP &&
201                 (GETARG_A(fs->f->code[list]) == 0 ||
202                  GETARG_A(fs->f->code[list]) >= level));
203     SETARG_A(fs->f->code[list], level);
204     list = next;
205   }
206 }
207 
208 
luaK_patchtohere(FuncState * fs,int list)209 void luaK_patchtohere (FuncState *fs, int list) {
210   luaK_getlabel(fs);
211   luaK_concat(fs, &fs->jpc, list);
212 }
213 
214 
luaK_concat(FuncState * fs,int * l1,int l2)215 void luaK_concat (FuncState *fs, int *l1, int l2) {
216   if (l2 == NO_JUMP) return;
217   else if (*l1 == NO_JUMP)
218     *l1 = l2;
219   else {
220     int list = *l1;
221     int next;
222     while ((next = getjump(fs, list)) != NO_JUMP)  /* find last element */
223       list = next;
224     fixjump(fs, list, l2);
225   }
226 }
227 
228 
luaK_code(FuncState * fs,Instruction i)229 static int luaK_code (FuncState *fs, Instruction i) {
230   Proto *f = fs->f;
231   dischargejpc(fs);  /* 'pc' will change */
232   /* put new instruction in code array */
233   luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
234                   MAX_INT, "opcodes");
235   f->code[fs->pc] = i;
236   /* save corresponding line information */
237   luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
238                   MAX_INT, "opcodes");
239   f->lineinfo[fs->pc] = fs->ls->lastline;
240   return fs->pc++;
241 }
242 
243 
luaK_codeABC(FuncState * fs,OpCode o,int a,int b,int c)244 int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
245   lua_assert(getOpMode(o) == iABC);
246   lua_assert(getBMode(o) != OpArgN || b == 0);
247   lua_assert(getCMode(o) != OpArgN || c == 0);
248   lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C);
249   return luaK_code(fs, CREATE_ABC(o, a, b, c));
250 }
251 
252 
luaK_codeABx(FuncState * fs,OpCode o,int a,unsigned int bc)253 int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
254   lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
255   lua_assert(getCMode(o) == OpArgN);
256   lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
257   return luaK_code(fs, CREATE_ABx(o, a, bc));
258 }
259 
260 
codeextraarg(FuncState * fs,int a)261 static int codeextraarg (FuncState *fs, int a) {
262   lua_assert(a <= MAXARG_Ax);
263   return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
264 }
265 
266 
luaK_codek(FuncState * fs,int reg,int k)267 int luaK_codek (FuncState *fs, int reg, int k) {
268   if (k <= MAXARG_Bx)
269     return luaK_codeABx(fs, OP_LOADK, reg, k);
270   else {
271     int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
272     codeextraarg(fs, k);
273     return p;
274   }
275 }
276 
277 
luaK_checkstack(FuncState * fs,int n)278 void luaK_checkstack (FuncState *fs, int n) {
279   int newstack = fs->freereg + n;
280   if (newstack > fs->f->maxstacksize) {
281     if (newstack >= MAXREGS)
282       luaX_syntaxerror(fs->ls, "function or expression too complex");
283     fs->f->maxstacksize = cast_byte(newstack);
284   }
285 }
286 
287 
luaK_reserveregs(FuncState * fs,int n)288 void luaK_reserveregs (FuncState *fs, int n) {
289   luaK_checkstack(fs, n);
290   fs->freereg += n;
291 }
292 
293 
freereg(FuncState * fs,int reg)294 static void freereg (FuncState *fs, int reg) {
295   if (!ISK(reg) && reg >= fs->nactvar) {
296     fs->freereg--;
297     lua_assert(reg == fs->freereg);
298   }
299 }
300 
301 
freeexp(FuncState * fs,expdesc * e)302 static void freeexp (FuncState *fs, expdesc *e) {
303   if (e->k == VNONRELOC)
304     freereg(fs, e->u.info);
305 }
306 
307 
308 /*
309 ** Use scanner's table to cache position of constants in constant list
310 ** and try to reuse constants
311 */
addk(FuncState * fs,TValue * key,TValue * v)312 static int addk (FuncState *fs, TValue *key, TValue *v) {
313   lua_State *L = fs->ls->L;
314   Proto *f = fs->f;
315   TValue *idx = luaH_set(L, fs->ls->h, key);  /* index scanner table */
316   int k, oldsize;
317   if (ttisinteger(idx)) {  /* is there an index there? */
318     k = cast_int(ivalue(idx));
319     /* correct value? (warning: must distinguish floats from integers!) */
320     if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&
321                       luaV_rawequalobj(&f->k[k], v))
322       return k;  /* reuse index */
323   }
324   /* constant not found; create a new entry */
325   oldsize = f->sizek;
326   k = fs->nk;
327   /* numerical value does not need GC barrier;
328      table has no metatable, so it does not need to invalidate cache */
329   setivalue(idx, k);
330   luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
331   while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
332   setobj(L, &f->k[k], v);
333   fs->nk++;
334   luaC_barrier(L, f, v);
335   return k;
336 }
337 
338 
luaK_stringK(FuncState * fs,TString * s)339 int luaK_stringK (FuncState *fs, TString *s) {
340   TValue o;
341   setsvalue(fs->ls->L, &o, s);
342   return addk(fs, &o, &o);
343 }
344 
345 
346 /*
347 ** Integers use userdata as keys to avoid collision with floats with same
348 ** value; conversion to 'void*' used only for hashing, no "precision"
349 ** problems
350 */
luaK_intK(FuncState * fs,lua_Integer n)351 int luaK_intK (FuncState *fs, lua_Integer n) {
352   TValue k, o;
353   setpvalue(&k, cast(void*, cast(size_t, n)));
354   setivalue(&o, n);
355   return addk(fs, &k, &o);
356 }
357 
358 
luaK_numberK(FuncState * fs,lua_Number r)359 static int luaK_numberK (FuncState *fs, lua_Number r) {
360   TValue o;
361   setfltvalue(&o, r);
362   return addk(fs, &o, &o);
363 }
364 
365 
boolK(FuncState * fs,int b)366 static int boolK (FuncState *fs, int b) {
367   TValue o;
368   setbvalue(&o, b);
369   return addk(fs, &o, &o);
370 }
371 
372 
nilK(FuncState * fs)373 static int nilK (FuncState *fs) {
374   TValue k, v;
375   setnilvalue(&v);
376   /* cannot use nil as key; instead use table itself to represent nil */
377   sethvalue(fs->ls->L, &k, fs->ls->h);
378   return addk(fs, &k, &v);
379 }
380 
381 
luaK_setreturns(FuncState * fs,expdesc * e,int nresults)382 void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
383   if (e->k == VCALL) {  /* expression is an open function call? */
384     SETARG_C(getcode(fs, e), nresults+1);
385   }
386   else if (e->k == VVARARG) {
387     SETARG_B(getcode(fs, e), nresults+1);
388     SETARG_A(getcode(fs, e), fs->freereg);
389     luaK_reserveregs(fs, 1);
390   }
391 }
392 
393 
luaK_setoneret(FuncState * fs,expdesc * e)394 void luaK_setoneret (FuncState *fs, expdesc *e) {
395   if (e->k == VCALL) {  /* expression is an open function call? */
396     e->k = VNONRELOC;
397     e->u.info = GETARG_A(getcode(fs, e));
398   }
399   else if (e->k == VVARARG) {
400     SETARG_B(getcode(fs, e), 2);
401     e->k = VRELOCABLE;  /* can relocate its simple result */
402   }
403 }
404 
405 
luaK_dischargevars(FuncState * fs,expdesc * e)406 void luaK_dischargevars (FuncState *fs, expdesc *e) {
407   switch (e->k) {
408     case VLOCAL: {
409       e->k = VNONRELOC;
410       break;
411     }
412     case VUPVAL: {
413       e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
414       e->k = VRELOCABLE;
415       break;
416     }
417     case VINDEXED: {
418       OpCode op = OP_GETTABUP;  /* assume 't' is in an upvalue */
419       freereg(fs, e->u.ind.idx);
420       if (e->u.ind.vt == VLOCAL) {  /* 't' is in a register? */
421         freereg(fs, e->u.ind.t);
422         op = OP_GETTABLE;
423       }
424       e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx);
425       e->k = VRELOCABLE;
426       break;
427     }
428     case VVARARG:
429     case VCALL: {
430       luaK_setoneret(fs, e);
431       break;
432     }
433     default: break;  /* there is one value available (somewhere) */
434   }
435 }
436 
437 
code_label(FuncState * fs,int A,int b,int jump)438 static int code_label (FuncState *fs, int A, int b, int jump) {
439   luaK_getlabel(fs);  /* those instructions may be jump targets */
440   return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
441 }
442 
443 
discharge2reg(FuncState * fs,expdesc * e,int reg)444 static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
445   luaK_dischargevars(fs, e);
446   switch (e->k) {
447     case VNIL: {
448       luaK_nil(fs, reg, 1);
449       break;
450     }
451     case VFALSE: case VTRUE: {
452       luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
453       break;
454     }
455     case VK: {
456       luaK_codek(fs, reg, e->u.info);
457       break;
458     }
459     case VKFLT: {
460       luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));
461       break;
462     }
463     case VKINT: {
464       luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));
465       break;
466     }
467     case VRELOCABLE: {
468       Instruction *pc = &getcode(fs, e);
469       SETARG_A(*pc, reg);
470       break;
471     }
472     case VNONRELOC: {
473       if (reg != e->u.info)
474         luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
475       break;
476     }
477     default: {
478       lua_assert(e->k == VVOID || e->k == VJMP);
479       return;  /* nothing to do... */
480     }
481   }
482   e->u.info = reg;
483   e->k = VNONRELOC;
484 }
485 
486 
discharge2anyreg(FuncState * fs,expdesc * e)487 static void discharge2anyreg (FuncState *fs, expdesc *e) {
488   if (e->k != VNONRELOC) {
489     luaK_reserveregs(fs, 1);
490     discharge2reg(fs, e, fs->freereg-1);
491   }
492 }
493 
494 
exp2reg(FuncState * fs,expdesc * e,int reg)495 static void exp2reg (FuncState *fs, expdesc *e, int reg) {
496   discharge2reg(fs, e, reg);
497   if (e->k == VJMP)
498     luaK_concat(fs, &e->t, e->u.info);  /* put this jump in 't' list */
499   if (hasjumps(e)) {
500     int final;  /* position after whole expression */
501     int p_f = NO_JUMP;  /* position of an eventual LOAD false */
502     int p_t = NO_JUMP;  /* position of an eventual LOAD true */
503     if (need_value(fs, e->t) || need_value(fs, e->f)) {
504       int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
505       p_f = code_label(fs, reg, 0, 1);
506       p_t = code_label(fs, reg, 1, 0);
507       luaK_patchtohere(fs, fj);
508     }
509     final = luaK_getlabel(fs);
510     patchlistaux(fs, e->f, final, reg, p_f);
511     patchlistaux(fs, e->t, final, reg, p_t);
512   }
513   e->f = e->t = NO_JUMP;
514   e->u.info = reg;
515   e->k = VNONRELOC;
516 }
517 
518 
luaK_exp2nextreg(FuncState * fs,expdesc * e)519 void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
520   luaK_dischargevars(fs, e);
521   freeexp(fs, e);
522   luaK_reserveregs(fs, 1);
523   exp2reg(fs, e, fs->freereg - 1);
524 }
525 
526 
luaK_exp2anyreg(FuncState * fs,expdesc * e)527 int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
528   luaK_dischargevars(fs, e);
529   if (e->k == VNONRELOC) {
530     if (!hasjumps(e)) return e->u.info;  /* exp is already in a register */
531     if (e->u.info >= fs->nactvar) {  /* reg. is not a local? */
532       exp2reg(fs, e, e->u.info);  /* put value on it */
533       return e->u.info;
534     }
535   }
536   luaK_exp2nextreg(fs, e);  /* default */
537   return e->u.info;
538 }
539 
540 
luaK_exp2anyregup(FuncState * fs,expdesc * e)541 void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
542   if (e->k != VUPVAL || hasjumps(e))
543     luaK_exp2anyreg(fs, e);
544 }
545 
546 
luaK_exp2val(FuncState * fs,expdesc * e)547 void luaK_exp2val (FuncState *fs, expdesc *e) {
548   if (hasjumps(e))
549     luaK_exp2anyreg(fs, e);
550   else
551     luaK_dischargevars(fs, e);
552 }
553 
554 
luaK_exp2RK(FuncState * fs,expdesc * e)555 int luaK_exp2RK (FuncState *fs, expdesc *e) {
556   luaK_exp2val(fs, e);
557   switch (e->k) {
558     case VTRUE:
559     case VFALSE:
560     case VNIL: {
561       if (fs->nk <= MAXINDEXRK) {  /* constant fits in RK operand? */
562         e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE));
563         e->k = VK;
564         return RKASK(e->u.info);
565       }
566       else break;
567     }
568     case VKINT: {
569       e->u.info = luaK_intK(fs, e->u.ival);
570       e->k = VK;
571       goto vk;
572     }
573     case VKFLT: {
574       e->u.info = luaK_numberK(fs, e->u.nval);
575       e->k = VK;
576       /* go through */
577     }
578     case VK: {
579      vk:
580       if (e->u.info <= MAXINDEXRK)  /* constant fits in 'argC'? */
581         return RKASK(e->u.info);
582       else break;
583     }
584     default: break;
585   }
586   /* not a constant in the right range: put it in a register */
587   return luaK_exp2anyreg(fs, e);
588 }
589 
590 
luaK_storevar(FuncState * fs,expdesc * var,expdesc * ex)591 void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
592   switch (var->k) {
593     case VLOCAL: {
594       freeexp(fs, ex);
595       exp2reg(fs, ex, var->u.info);
596       return;
597     }
598     case VUPVAL: {
599       int e = luaK_exp2anyreg(fs, ex);
600       luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
601       break;
602     }
603     case VINDEXED: {
604       OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP;
605       int e = luaK_exp2RK(fs, ex);
606       luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e);
607       break;
608     }
609     default: {
610       lua_assert(0);  /* invalid var kind to store */
611       break;
612     }
613   }
614   freeexp(fs, ex);
615 }
616 
617 
luaK_self(FuncState * fs,expdesc * e,expdesc * key)618 void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
619   int ereg;
620   luaK_exp2anyreg(fs, e);
621   ereg = e->u.info;  /* register where 'e' was placed */
622   freeexp(fs, e);
623   e->u.info = fs->freereg;  /* base register for op_self */
624   e->k = VNONRELOC;
625   luaK_reserveregs(fs, 2);  /* function and 'self' produced by op_self */
626   luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));
627   freeexp(fs, key);
628 }
629 
630 
invertjump(FuncState * fs,expdesc * e)631 static void invertjump (FuncState *fs, expdesc *e) {
632   Instruction *pc = getjumpcontrol(fs, e->u.info);
633   lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
634                                            GET_OPCODE(*pc) != OP_TEST);
635   SETARG_A(*pc, !(GETARG_A(*pc)));
636 }
637 
638 
jumponcond(FuncState * fs,expdesc * e,int cond)639 static int jumponcond (FuncState *fs, expdesc *e, int cond) {
640   if (e->k == VRELOCABLE) {
641     Instruction ie = getcode(fs, e);
642     if (GET_OPCODE(ie) == OP_NOT) {
643       fs->pc--;  /* remove previous OP_NOT */
644       return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
645     }
646     /* else go through */
647   }
648   discharge2anyreg(fs, e);
649   freeexp(fs, e);
650   return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond);
651 }
652 
653 
luaK_goiftrue(FuncState * fs,expdesc * e)654 void luaK_goiftrue (FuncState *fs, expdesc *e) {
655   int pc;  /* pc of last jump */
656   luaK_dischargevars(fs, e);
657   switch (e->k) {
658     case VJMP: {
659       invertjump(fs, e);
660       pc = e->u.info;
661       break;
662     }
663     case VK: case VKFLT: case VKINT: case VTRUE: {
664       pc = NO_JUMP;  /* always true; do nothing */
665       break;
666     }
667     default: {
668       pc = jumponcond(fs, e, 0);
669       break;
670     }
671   }
672   luaK_concat(fs, &e->f, pc);  /* insert last jump in 'f' list */
673   luaK_patchtohere(fs, e->t);
674   e->t = NO_JUMP;
675 }
676 
677 
luaK_goiffalse(FuncState * fs,expdesc * e)678 void luaK_goiffalse (FuncState *fs, expdesc *e) {
679   int pc;  /* pc of last jump */
680   luaK_dischargevars(fs, e);
681   switch (e->k) {
682     case VJMP: {
683       pc = e->u.info;
684       break;
685     }
686     case VNIL: case VFALSE: {
687       pc = NO_JUMP;  /* always false; do nothing */
688       break;
689     }
690     default: {
691       pc = jumponcond(fs, e, 1);
692       break;
693     }
694   }
695   luaK_concat(fs, &e->t, pc);  /* insert last jump in 't' list */
696   luaK_patchtohere(fs, e->f);
697   e->f = NO_JUMP;
698 }
699 
700 
codenot(FuncState * fs,expdesc * e)701 static void codenot (FuncState *fs, expdesc *e) {
702   luaK_dischargevars(fs, e);
703   switch (e->k) {
704     case VNIL: case VFALSE: {
705       e->k = VTRUE;
706       break;
707     }
708     case VK: case VKFLT: case VKINT: case VTRUE: {
709       e->k = VFALSE;
710       break;
711     }
712     case VJMP: {
713       invertjump(fs, e);
714       break;
715     }
716     case VRELOCABLE:
717     case VNONRELOC: {
718       discharge2anyreg(fs, e);
719       freeexp(fs, e);
720       e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
721       e->k = VRELOCABLE;
722       break;
723     }
724     default: {
725       lua_assert(0);  /* cannot happen */
726       break;
727     }
728   }
729   /* interchange true and false lists */
730   { int temp = e->f; e->f = e->t; e->t = temp; }
731   removevalues(fs, e->f);
732   removevalues(fs, e->t);
733 }
734 
735 
luaK_indexed(FuncState * fs,expdesc * t,expdesc * k)736 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
737   lua_assert(!hasjumps(t));
738   t->u.ind.t = t->u.info;
739   t->u.ind.idx = luaK_exp2RK(fs, k);
740   t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL
741                                  : check_exp(vkisinreg(t->k), VLOCAL);
742   t->k = VINDEXED;
743 }
744 
745 
746 /*
747 ** return false if folding can raise an error
748 */
validop(int op,TValue * v1,TValue * v2)749 static int validop (int op, TValue *v1, TValue *v2) {
750   switch (op) {
751     case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
752     case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: {  /* conversion errors */
753       lua_Integer i;
754       return (tointeger(v1, &i) && tointeger(v2, &i));
755     }
756     case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD:  /* division by 0 */
757       return (nvalue(v2) != 0);
758     default: return 1;  /* everything else is valid */
759   }
760 }
761 
762 
763 /*
764 ** Try to "constant-fold" an operation; return 1 iff successful
765 */
constfolding(FuncState * fs,int op,expdesc * e1,expdesc * e2)766 static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
767   TValue v1, v2, res;
768   if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
769     return 0;  /* non-numeric operands or not safe to fold */
770   luaO_arith(fs->ls->L, op, &v1, &v2, &res);  /* does operation */
771   if (ttisinteger(&res)) {
772     e1->k = VKINT;
773     e1->u.ival = ivalue(&res);
774   }
775   else {  /* folds neither NaN nor 0.0 (to avoid collapsing with -0.0) */
776     lua_Number n = fltvalue(&res);
777     if (luai_numisnan(n) || n == 0)
778       return 0;
779     e1->k = VKFLT;
780     e1->u.nval = n;
781   }
782   return 1;
783 }
784 
785 
786 /*
787 ** Code for binary and unary expressions that "produce values"
788 ** (arithmetic operations, bitwise operations, concat, length). First
789 ** try to do constant folding (only for numeric [arithmetic and
790 ** bitwise] operations, which is what 'lua_arith' accepts).
791 ** Expression to produce final result will be encoded in 'e1'.
792 */
codeexpval(FuncState * fs,OpCode op,expdesc * e1,expdesc * e2,int line)793 static void codeexpval (FuncState *fs, OpCode op,
794                         expdesc *e1, expdesc *e2, int line) {
795   lua_assert(op >= OP_ADD);
796   if (op <= OP_BNOT && constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2))
797     return;  /* result has been folded */
798   else {
799     int o1, o2;
800     /* move operands to registers (if needed) */
801     if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) {  /* unary op? */
802       o2 = 0;  /* no second expression */
803       o1 = luaK_exp2anyreg(fs, e1);  /* cannot operate on constants */
804     }
805     else {  /* regular case (binary operators) */
806       o2 = luaK_exp2RK(fs, e2);  /* both operands are "RK" */
807       o1 = luaK_exp2RK(fs, e1);
808     }
809     if (o1 > o2) {  /* free registers in proper order */
810       freeexp(fs, e1);
811       freeexp(fs, e2);
812     }
813     else {
814       freeexp(fs, e2);
815       freeexp(fs, e1);
816     }
817     e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);  /* generate opcode */
818     e1->k = VRELOCABLE;  /* all those operations are relocable */
819     luaK_fixline(fs, line);
820   }
821 }
822 
823 
codecomp(FuncState * fs,OpCode op,int cond,expdesc * e1,expdesc * e2)824 static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
825                                                           expdesc *e2) {
826   int o1 = luaK_exp2RK(fs, e1);
827   int o2 = luaK_exp2RK(fs, e2);
828   freeexp(fs, e2);
829   freeexp(fs, e1);
830   if (cond == 0 && op != OP_EQ) {
831     int temp;  /* exchange args to replace by '<' or '<=' */
832     temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
833     cond = 1;
834   }
835   e1->u.info = condjump(fs, op, cond, o1, o2);
836   e1->k = VJMP;
837 }
838 
839 
luaK_prefix(FuncState * fs,UnOpr op,expdesc * e,int line)840 void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
841   expdesc e2;
842   e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
843   switch (op) {
844     case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
845       codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
846       break;
847     }
848     case OPR_NOT: codenot(fs, e); break;
849     default: lua_assert(0);
850   }
851 }
852 
853 
luaK_infix(FuncState * fs,BinOpr op,expdesc * v)854 void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
855   switch (op) {
856     case OPR_AND: {
857       luaK_goiftrue(fs, v);
858       break;
859     }
860     case OPR_OR: {
861       luaK_goiffalse(fs, v);
862       break;
863     }
864     case OPR_CONCAT: {
865       luaK_exp2nextreg(fs, v);  /* operand must be on the 'stack' */
866       break;
867     }
868     case OPR_ADD: case OPR_SUB:
869     case OPR_MUL: case OPR_DIV: case OPR_IDIV:
870     case OPR_MOD: case OPR_POW:
871     case OPR_BAND: case OPR_BOR: case OPR_BXOR:
872     case OPR_SHL: case OPR_SHR: {
873       if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v);
874       break;
875     }
876     default: {
877       luaK_exp2RK(fs, v);
878       break;
879     }
880   }
881 }
882 
883 
luaK_posfix(FuncState * fs,BinOpr op,expdesc * e1,expdesc * e2,int line)884 void luaK_posfix (FuncState *fs, BinOpr op,
885                   expdesc *e1, expdesc *e2, int line) {
886   switch (op) {
887     case OPR_AND: {
888       lua_assert(e1->t == NO_JUMP);  /* list must be closed */
889       luaK_dischargevars(fs, e2);
890       luaK_concat(fs, &e2->f, e1->f);
891       *e1 = *e2;
892       break;
893     }
894     case OPR_OR: {
895       lua_assert(e1->f == NO_JUMP);  /* list must be closed */
896       luaK_dischargevars(fs, e2);
897       luaK_concat(fs, &e2->t, e1->t);
898       *e1 = *e2;
899       break;
900     }
901     case OPR_CONCAT: {
902       luaK_exp2val(fs, e2);
903       if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
904         lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1);
905         freeexp(fs, e1);
906         SETARG_B(getcode(fs, e2), e1->u.info);
907         e1->k = VRELOCABLE; e1->u.info = e2->u.info;
908       }
909       else {
910         luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
911         codeexpval(fs, OP_CONCAT, e1, e2, line);
912       }
913       break;
914     }
915     case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
916     case OPR_IDIV: case OPR_MOD: case OPR_POW:
917     case OPR_BAND: case OPR_BOR: case OPR_BXOR:
918     case OPR_SHL: case OPR_SHR: {
919       codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
920       break;
921     }
922     case OPR_EQ: case OPR_LT: case OPR_LE: {
923       codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2);
924       break;
925     }
926     case OPR_NE: case OPR_GT: case OPR_GE: {
927       codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2);
928       break;
929     }
930     default: lua_assert(0);
931   }
932 }
933 
934 
luaK_fixline(FuncState * fs,int line)935 void luaK_fixline (FuncState *fs, int line) {
936   fs->f->lineinfo[fs->pc - 1] = line;
937 }
938 
939 
luaK_setlist(FuncState * fs,int base,int nelems,int tostore)940 void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
941   int c =  (nelems - 1)/LFIELDS_PER_FLUSH + 1;
942   int b = (tostore == LUA_MULTRET) ? 0 : tostore;
943   lua_assert(tostore != 0);
944   if (c <= MAXARG_C)
945     luaK_codeABC(fs, OP_SETLIST, base, b, c);
946   else if (c <= MAXARG_Ax) {
947     luaK_codeABC(fs, OP_SETLIST, base, b, 0);
948     codeextraarg(fs, c);
949   }
950   else
951     luaX_syntaxerror(fs->ls, "constructor too long");
952   fs->freereg = base + 1;  /* free registers with list values */
953 }
954 
955