1 /* $NetBSD: lcode.c,v 1.11 2018/08/04 17:30:01 alnsn Exp $ */ 2 3 /* 4 ** Id: lcode.c,v 2.112.1.1 2017/04/19 17:20:42 roberto Exp 5 ** Code generator for Lua 6 ** See Copyright Notice in lua.h 7 */ 8 9 #define lcode_c 10 #define LUA_CORE 11 12 #include "lprefix.h" 13 14 15 #ifndef _KERNEL 16 #include <math.h> 17 #include <stdlib.h> 18 #endif /* _KERNEL */ 19 20 #include "lua.h" 21 22 #include "lcode.h" 23 #include "ldebug.h" 24 #include "ldo.h" 25 #include "lgc.h" 26 #include "llex.h" 27 #include "lmem.h" 28 #include "lobject.h" 29 #include "lopcodes.h" 30 #include "lparser.h" 31 #include "lstring.h" 32 #include "ltable.h" 33 #include "lvm.h" 34 35 36 /* Maximum number of registers in a Lua function (must fit in 8 bits) */ 37 #define MAXREGS 255 38 39 40 #define hasjumps(e) ((e)->t != (e)->f) 41 42 43 /* 44 ** If expression is a numeric constant, fills 'v' with its value 45 ** and returns 1. Otherwise, returns 0. 46 */ 47 static int tonumeral(const expdesc *e, TValue *v) { 48 if (hasjumps(e)) 49 return 0; /* not a numeral */ 50 switch (e->k) { 51 case VKINT: 52 if (v) setivalue(v, e->u.ival); 53 return 1; 54 #ifndef _KERNEL 55 case VKFLT: 56 if (v) setfltvalue(v, e->u.nval); 57 return 1; 58 #endif /* _KERNEL */ 59 default: return 0; 60 } 61 } 62 63 64 /* 65 ** Create a OP_LOADNIL instruction, but try to optimize: if the previous 66 ** instruction is also OP_LOADNIL and ranges are compatible, adjust 67 ** range of previous instruction instead of emitting a new one. (For 68 ** instance, 'local a; local b' will generate a single opcode.) 69 */ 70 void luaK_nil (FuncState *fs, int from, int n) { 71 Instruction *previous; 72 int l = from + n - 1; /* last register to set nil */ 73 if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ 74 previous = &fs->f->code[fs->pc-1]; 75 if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */ 76 int pfrom = GETARG_A(*previous); /* get previous range */ 77 int pl = pfrom + GETARG_B(*previous); 78 if ((pfrom <= from && from <= pl + 1) || 79 (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ 80 if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ 81 if (pl > l) l = pl; /* l = max(l, pl) */ 82 SETARG_A(*previous, from); 83 SETARG_B(*previous, l - from); 84 return; 85 } 86 } /* else go through */ 87 } 88 luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ 89 } 90 91 92 /* 93 ** Gets the destination address of a jump instruction. Used to traverse 94 ** a list of jumps. 95 */ 96 static int getjump (FuncState *fs, int pc) { 97 int offset = GETARG_sBx(fs->f->code[pc]); 98 if (offset == NO_JUMP) /* point to itself represents end of list */ 99 return NO_JUMP; /* end of list */ 100 else 101 return (pc+1)+offset; /* turn offset into absolute position */ 102 } 103 104 105 /* 106 ** Fix jump instruction at position 'pc' to jump to 'dest'. 107 ** (Jump addresses are relative in Lua) 108 */ 109 static void fixjump (FuncState *fs, int pc, int dest) { 110 Instruction *jmp = &fs->f->code[pc]; 111 int offset = dest - (pc + 1); 112 lua_assert(dest != NO_JUMP); 113 if (abs(offset) > MAXARG_sBx) 114 luaX_syntaxerror(fs->ls, "control structure too long"); 115 SETARG_sBx(*jmp, offset); 116 } 117 118 119 /* 120 ** Concatenate jump-list 'l2' into jump-list 'l1' 121 */ 122 void luaK_concat (FuncState *fs, int *l1, int l2) { 123 if (l2 == NO_JUMP) return; /* nothing to concatenate? */ 124 else if (*l1 == NO_JUMP) /* no original list? */ 125 *l1 = l2; /* 'l1' points to 'l2' */ 126 else { 127 int list = *l1; 128 int next; 129 while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ 130 list = next; 131 fixjump(fs, list, l2); /* last element links to 'l2' */ 132 } 133 } 134 135 136 /* 137 ** Create a jump instruction and return its position, so its destination 138 ** can be fixed later (with 'fixjump'). If there are jumps to 139 ** this position (kept in 'jpc'), link them all together so that 140 ** 'patchlistaux' will fix all them directly to the final destination. 141 */ 142 int luaK_jump (FuncState *fs) { 143 int jpc = fs->jpc; /* save list of jumps to here */ 144 int j; 145 fs->jpc = NO_JUMP; /* no more jumps to here */ 146 j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); 147 luaK_concat(fs, &j, jpc); /* keep them on hold */ 148 return j; 149 } 150 151 152 /* 153 ** Code a 'return' instruction 154 */ 155 void luaK_ret (FuncState *fs, int first, int nret) { 156 luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); 157 } 158 159 160 /* 161 ** Code a "conditional jump", that is, a test or comparison opcode 162 ** followed by a jump. Return jump position. 163 */ 164 static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { 165 luaK_codeABC(fs, op, A, B, C); 166 return luaK_jump(fs); 167 } 168 169 170 /* 171 ** returns current 'pc' and marks it as a jump target (to avoid wrong 172 ** optimizations with consecutive instructions not in the same basic block). 173 */ 174 int luaK_getlabel (FuncState *fs) { 175 fs->lasttarget = fs->pc; 176 return fs->pc; 177 } 178 179 180 /* 181 ** Returns the position of the instruction "controlling" a given 182 ** jump (that is, its condition), or the jump itself if it is 183 ** unconditional. 184 */ 185 static Instruction *getjumpcontrol (FuncState *fs, int pc) { 186 Instruction *pi = &fs->f->code[pc]; 187 if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) 188 return pi-1; 189 else 190 return pi; 191 } 192 193 194 /* 195 ** Patch destination register for a TESTSET instruction. 196 ** If instruction in position 'node' is not a TESTSET, return 0 ("fails"). 197 ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination 198 ** register. Otherwise, change instruction to a simple 'TEST' (produces 199 ** no register value) 200 */ 201 static int patchtestreg (FuncState *fs, int node, int reg) { 202 Instruction *i = getjumpcontrol(fs, node); 203 if (GET_OPCODE(*i) != OP_TESTSET) 204 return 0; /* cannot patch other instructions */ 205 if (reg != NO_REG && reg != GETARG_B(*i)) 206 SETARG_A(*i, reg); 207 else { 208 /* no register to put value or register already has the value; 209 change instruction to simple test */ 210 *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); 211 } 212 return 1; 213 } 214 215 216 /* 217 ** Traverse a list of tests ensuring no one produces a value 218 */ 219 static void removevalues (FuncState *fs, int list) { 220 for (; list != NO_JUMP; list = getjump(fs, list)) 221 patchtestreg(fs, list, NO_REG); 222 } 223 224 225 /* 226 ** Traverse a list of tests, patching their destination address and 227 ** registers: tests producing values jump to 'vtarget' (and put their 228 ** values in 'reg'), other tests jump to 'dtarget'. 229 */ 230 static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, 231 int dtarget) { 232 while (list != NO_JUMP) { 233 int next = getjump(fs, list); 234 if (patchtestreg(fs, list, reg)) 235 fixjump(fs, list, vtarget); 236 else 237 fixjump(fs, list, dtarget); /* jump to default target */ 238 list = next; 239 } 240 } 241 242 243 /* 244 ** Ensure all pending jumps to current position are fixed (jumping 245 ** to current position with no values) and reset list of pending 246 ** jumps 247 */ 248 static void dischargejpc (FuncState *fs) { 249 patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); 250 fs->jpc = NO_JUMP; 251 } 252 253 254 /* 255 ** Add elements in 'list' to list of pending jumps to "here" 256 ** (current position) 257 */ 258 void luaK_patchtohere (FuncState *fs, int list) { 259 luaK_getlabel(fs); /* mark "here" as a jump target */ 260 luaK_concat(fs, &fs->jpc, list); 261 } 262 263 264 /* 265 ** Path all jumps in 'list' to jump to 'target'. 266 ** (The assert means that we cannot fix a jump to a forward address 267 ** because we only know addresses once code is generated.) 268 */ 269 void luaK_patchlist (FuncState *fs, int list, int target) { 270 if (target == fs->pc) /* 'target' is current position? */ 271 luaK_patchtohere(fs, list); /* add list to pending jumps */ 272 else { 273 lua_assert(target < fs->pc); 274 patchlistaux(fs, list, target, NO_REG, target); 275 } 276 } 277 278 279 /* 280 ** Path all jumps in 'list' to close upvalues up to given 'level' 281 ** (The assertion checks that jumps either were closing nothing 282 ** or were closing higher levels, from inner blocks.) 283 */ 284 void luaK_patchclose (FuncState *fs, int list, int level) { 285 level++; /* argument is +1 to reserve 0 as non-op */ 286 for (; list != NO_JUMP; list = getjump(fs, list)) { 287 lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && 288 (GETARG_A(fs->f->code[list]) == 0 || 289 GETARG_A(fs->f->code[list]) >= level)); 290 SETARG_A(fs->f->code[list], level); 291 } 292 } 293 294 295 /* 296 ** Emit instruction 'i', checking for array sizes and saving also its 297 ** line information. Return 'i' position. 298 */ 299 static int luaK_code (FuncState *fs, Instruction i) { 300 Proto *f = fs->f; 301 dischargejpc(fs); /* 'pc' will change */ 302 /* put new instruction in code array */ 303 luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, 304 MAX_INT, "opcodes"); 305 f->code[fs->pc] = i; 306 /* save corresponding line information */ 307 luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int, 308 MAX_INT, "opcodes"); 309 f->lineinfo[fs->pc] = fs->ls->lastline; 310 return fs->pc++; 311 } 312 313 314 /* 315 ** Format and emit an 'iABC' instruction. (Assertions check consistency 316 ** of parameters versus opcode.) 317 */ 318 int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { 319 lua_assert(getOpMode(o) == iABC); 320 lua_assert(getBMode(o) != OpArgN || b == 0); 321 lua_assert(getCMode(o) != OpArgN || c == 0); 322 lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); 323 return luaK_code(fs, CREATE_ABC(o, a, b, c)); 324 } 325 326 327 /* 328 ** Format and emit an 'iABx' instruction. 329 */ 330 int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { 331 lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); 332 lua_assert(getCMode(o) == OpArgN); 333 lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); 334 return luaK_code(fs, CREATE_ABx(o, a, bc)); 335 } 336 337 338 /* 339 ** Emit an "extra argument" instruction (format 'iAx') 340 */ 341 static int codeextraarg (FuncState *fs, int a) { 342 lua_assert(a <= MAXARG_Ax); 343 return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); 344 } 345 346 347 /* 348 ** Emit a "load constant" instruction, using either 'OP_LOADK' 349 ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX' 350 ** instruction with "extra argument". 351 */ 352 int luaK_codek (FuncState *fs, int reg, int k) { 353 if (k <= MAXARG_Bx) 354 return luaK_codeABx(fs, OP_LOADK, reg, k); 355 else { 356 int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); 357 codeextraarg(fs, k); 358 return p; 359 } 360 } 361 362 363 /* 364 ** Check register-stack level, keeping track of its maximum size 365 ** in field 'maxstacksize' 366 */ 367 void luaK_checkstack (FuncState *fs, int n) { 368 int newstack = fs->freereg + n; 369 if (newstack > fs->f->maxstacksize) { 370 if (newstack >= MAXREGS) 371 luaX_syntaxerror(fs->ls, 372 "function or expression needs too many registers"); 373 fs->f->maxstacksize = cast_byte(newstack); 374 } 375 } 376 377 378 /* 379 ** Reserve 'n' registers in register stack 380 */ 381 void luaK_reserveregs (FuncState *fs, int n) { 382 luaK_checkstack(fs, n); 383 fs->freereg += n; 384 } 385 386 387 /* 388 ** Free register 'reg', if it is neither a constant index nor 389 ** a local variable. 390 ) 391 */ 392 static void freereg (FuncState *fs, int reg) { 393 if (!ISK(reg) && reg >= fs->nactvar) { 394 fs->freereg--; 395 lua_assert(reg == fs->freereg); 396 } 397 } 398 399 400 /* 401 ** Free register used by expression 'e' (if any) 402 */ 403 static void freeexp (FuncState *fs, expdesc *e) { 404 if (e->k == VNONRELOC) 405 freereg(fs, e->u.info); 406 } 407 408 409 /* 410 ** Free registers used by expressions 'e1' and 'e2' (if any) in proper 411 ** order. 412 */ 413 static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) { 414 int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1; 415 int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1; 416 if (r1 > r2) { 417 freereg(fs, r1); 418 freereg(fs, r2); 419 } 420 else { 421 freereg(fs, r2); 422 freereg(fs, r1); 423 } 424 } 425 426 427 /* 428 ** Add constant 'v' to prototype's list of constants (field 'k'). 429 ** Use scanner's table to cache position of constants in constant list 430 ** and try to reuse constants. Because some values should not be used 431 ** as keys (nil cannot be a key, integer keys can collapse with float 432 ** keys), the caller must provide a useful 'key' for indexing the cache. 433 */ 434 static int addk (FuncState *fs, TValue *key, TValue *v) { 435 lua_State *L = fs->ls->L; 436 Proto *f = fs->f; 437 TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */ 438 int k, oldsize; 439 if (ttisinteger(idx)) { /* is there an index there? */ 440 k = cast_int(ivalue(idx)); 441 /* correct value? (warning: must distinguish floats from integers!) */ 442 if (k < fs->nk && ttype(&f->k[k]) == ttype(v) && 443 luaV_rawequalobj(&f->k[k], v)) 444 return k; /* reuse index */ 445 } 446 /* constant not found; create a new entry */ 447 oldsize = f->sizek; 448 k = fs->nk; 449 /* numerical value does not need GC barrier; 450 table has no metatable, so it does not need to invalidate cache */ 451 setivalue(idx, k); 452 luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); 453 while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); 454 setobj(L, &f->k[k], v); 455 fs->nk++; 456 luaC_barrier(L, f, v); 457 return k; 458 } 459 460 461 /* 462 ** Add a string to list of constants and return its index. 463 */ 464 int luaK_stringK (FuncState *fs, TString *s) { 465 TValue o; 466 setsvalue(fs->ls->L, &o, s); 467 return addk(fs, &o, &o); /* use string itself as key */ 468 } 469 470 471 /* 472 ** Add an integer to list of constants and return its index. 473 ** Integers use userdata as keys to avoid collision with floats with 474 ** same value; conversion to 'void*' is used only for hashing, so there 475 ** are no "precision" problems. 476 */ 477 int luaK_intK (FuncState *fs, lua_Integer n) { 478 TValue k, o; 479 setpvalue(&k, cast(void*, cast(size_t, n))); 480 setivalue(&o, n); 481 return addk(fs, &k, &o); 482 } 483 484 485 #ifndef _KERNEL 486 /* 487 ** Add a float to list of constants and return its index. 488 */ 489 static int luaK_numberK (FuncState *fs, lua_Number r) { 490 TValue o; 491 setfltvalue(&o, r); 492 return addk(fs, &o, &o); /* use number itself as key */ 493 } 494 #endif /* _KERNEL */ 495 496 497 /* 498 ** Add a boolean to list of constants and return its index. 499 */ 500 static int boolK (FuncState *fs, int b) { 501 TValue o; 502 setbvalue(&o, b); 503 return addk(fs, &o, &o); /* use boolean itself as key */ 504 } 505 506 507 /* 508 ** Add nil to list of constants and return its index. 509 */ 510 static int nilK (FuncState *fs) { 511 TValue k, v; 512 setnilvalue(&v); 513 /* cannot use nil as key; instead use table itself to represent nil */ 514 sethvalue(fs->ls->L, &k, fs->ls->h); 515 return addk(fs, &k, &v); 516 } 517 518 519 /* 520 ** Fix an expression to return the number of results 'nresults'. 521 ** Either 'e' is a multi-ret expression (function call or vararg) 522 ** or 'nresults' is LUA_MULTRET (as any expression can satisfy that). 523 */ 524 void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { 525 if (e->k == VCALL) { /* expression is an open function call? */ 526 SETARG_C(getinstruction(fs, e), nresults + 1); 527 } 528 else if (e->k == VVARARG) { 529 Instruction *pc = &getinstruction(fs, e); 530 SETARG_B(*pc, nresults + 1); 531 SETARG_A(*pc, fs->freereg); 532 luaK_reserveregs(fs, 1); 533 } 534 else lua_assert(nresults == LUA_MULTRET); 535 } 536 537 538 /* 539 ** Fix an expression to return one result. 540 ** If expression is not a multi-ret expression (function call or 541 ** vararg), it already returns one result, so nothing needs to be done. 542 ** Function calls become VNONRELOC expressions (as its result comes 543 ** fixed in the base register of the call), while vararg expressions 544 ** become VRELOCABLE (as OP_VARARG puts its results where it wants). 545 ** (Calls are created returning one result, so that does not need 546 ** to be fixed.) 547 */ 548 void luaK_setoneret (FuncState *fs, expdesc *e) { 549 if (e->k == VCALL) { /* expression is an open function call? */ 550 /* already returns 1 value */ 551 lua_assert(GETARG_C(getinstruction(fs, e)) == 2); 552 e->k = VNONRELOC; /* result has fixed position */ 553 e->u.info = GETARG_A(getinstruction(fs, e)); 554 } 555 else if (e->k == VVARARG) { 556 SETARG_B(getinstruction(fs, e), 2); 557 e->k = VRELOCABLE; /* can relocate its simple result */ 558 } 559 } 560 561 562 /* 563 ** Ensure that expression 'e' is not a variable. 564 */ 565 void luaK_dischargevars (FuncState *fs, expdesc *e) { 566 switch (e->k) { 567 case VLOCAL: { /* already in a register */ 568 e->k = VNONRELOC; /* becomes a non-relocatable value */ 569 break; 570 } 571 case VUPVAL: { /* move value to some (pending) register */ 572 e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); 573 e->k = VRELOCABLE; 574 break; 575 } 576 case VINDEXED: { 577 OpCode op; 578 freereg(fs, e->u.ind.idx); 579 if (e->u.ind.vt == VLOCAL) { /* is 't' in a register? */ 580 freereg(fs, e->u.ind.t); 581 op = OP_GETTABLE; 582 } 583 else { 584 lua_assert(e->u.ind.vt == VUPVAL); 585 op = OP_GETTABUP; /* 't' is in an upvalue */ 586 } 587 e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); 588 e->k = VRELOCABLE; 589 break; 590 } 591 case VVARARG: case VCALL: { 592 luaK_setoneret(fs, e); 593 break; 594 } 595 default: break; /* there is one value available (somewhere) */ 596 } 597 } 598 599 600 /* 601 ** Ensures expression value is in register 'reg' (and therefore 602 ** 'e' will become a non-relocatable expression). 603 */ 604 static void discharge2reg (FuncState *fs, expdesc *e, int reg) { 605 luaK_dischargevars(fs, e); 606 switch (e->k) { 607 case VNIL: { 608 luaK_nil(fs, reg, 1); 609 break; 610 } 611 case VFALSE: case VTRUE: { 612 luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); 613 break; 614 } 615 case VK: { 616 luaK_codek(fs, reg, e->u.info); 617 break; 618 } 619 #ifndef _KERNEL 620 case VKFLT: { 621 luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); 622 break; 623 } 624 #endif /* _KERNEL */ 625 case VKINT: { 626 luaK_codek(fs, reg, luaK_intK(fs, e->u.ival)); 627 break; 628 } 629 case VRELOCABLE: { 630 Instruction *pc = &getinstruction(fs, e); 631 SETARG_A(*pc, reg); /* instruction will put result in 'reg' */ 632 break; 633 } 634 case VNONRELOC: { 635 if (reg != e->u.info) 636 luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); 637 break; 638 } 639 default: { 640 lua_assert(e->k == VJMP); 641 return; /* nothing to do... */ 642 } 643 } 644 e->u.info = reg; 645 e->k = VNONRELOC; 646 } 647 648 649 /* 650 ** Ensures expression value is in any register. 651 */ 652 static void discharge2anyreg (FuncState *fs, expdesc *e) { 653 if (e->k != VNONRELOC) { /* no fixed register yet? */ 654 luaK_reserveregs(fs, 1); /* get a register */ 655 discharge2reg(fs, e, fs->freereg-1); /* put value there */ 656 } 657 } 658 659 660 static int code_loadbool (FuncState *fs, int A, int b, int jump) { 661 luaK_getlabel(fs); /* those instructions may be jump targets */ 662 return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); 663 } 664 665 666 /* 667 ** check whether list has any jump that do not produce a value 668 ** or produce an inverted value 669 */ 670 static int need_value (FuncState *fs, int list) { 671 for (; list != NO_JUMP; list = getjump(fs, list)) { 672 Instruction i = *getjumpcontrol(fs, list); 673 if (GET_OPCODE(i) != OP_TESTSET) return 1; 674 } 675 return 0; /* not found */ 676 } 677 678 679 /* 680 ** Ensures final expression result (including results from its jump 681 ** lists) is in register 'reg'. 682 ** If expression has jumps, need to patch these jumps either to 683 ** its final position or to "load" instructions (for those tests 684 ** that do not produce values). 685 */ 686 static void exp2reg (FuncState *fs, expdesc *e, int reg) { 687 discharge2reg(fs, e, reg); 688 if (e->k == VJMP) /* expression itself is a test? */ 689 luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ 690 if (hasjumps(e)) { 691 int final; /* position after whole expression */ 692 int p_f = NO_JUMP; /* position of an eventual LOAD false */ 693 int p_t = NO_JUMP; /* position of an eventual LOAD true */ 694 if (need_value(fs, e->t) || need_value(fs, e->f)) { 695 int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); 696 p_f = code_loadbool(fs, reg, 0, 1); 697 p_t = code_loadbool(fs, reg, 1, 0); 698 luaK_patchtohere(fs, fj); 699 } 700 final = luaK_getlabel(fs); 701 patchlistaux(fs, e->f, final, reg, p_f); 702 patchlistaux(fs, e->t, final, reg, p_t); 703 } 704 e->f = e->t = NO_JUMP; 705 e->u.info = reg; 706 e->k = VNONRELOC; 707 } 708 709 710 /* 711 ** Ensures final expression result (including results from its jump 712 ** lists) is in next available register. 713 */ 714 void luaK_exp2nextreg (FuncState *fs, expdesc *e) { 715 luaK_dischargevars(fs, e); 716 freeexp(fs, e); 717 luaK_reserveregs(fs, 1); 718 exp2reg(fs, e, fs->freereg - 1); 719 } 720 721 722 /* 723 ** Ensures final expression result (including results from its jump 724 ** lists) is in some (any) register and return that register. 725 */ 726 int luaK_exp2anyreg (FuncState *fs, expdesc *e) { 727 luaK_dischargevars(fs, e); 728 if (e->k == VNONRELOC) { /* expression already has a register? */ 729 if (!hasjumps(e)) /* no jumps? */ 730 return e->u.info; /* result is already in a register */ 731 if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ 732 exp2reg(fs, e, e->u.info); /* put final result in it */ 733 return e->u.info; 734 } 735 } 736 luaK_exp2nextreg(fs, e); /* otherwise, use next available register */ 737 return e->u.info; 738 } 739 740 741 /* 742 ** Ensures final expression result is either in a register or in an 743 ** upvalue. 744 */ 745 void luaK_exp2anyregup (FuncState *fs, expdesc *e) { 746 if (e->k != VUPVAL || hasjumps(e)) 747 luaK_exp2anyreg(fs, e); 748 } 749 750 751 /* 752 ** Ensures final expression result is either in a register or it is 753 ** a constant. 754 */ 755 void luaK_exp2val (FuncState *fs, expdesc *e) { 756 if (hasjumps(e)) 757 luaK_exp2anyreg(fs, e); 758 else 759 luaK_dischargevars(fs, e); 760 } 761 762 763 /* 764 ** Ensures final expression result is in a valid R/K index 765 ** (that is, it is either in a register or in 'k' with an index 766 ** in the range of R/K indices). 767 ** Returns R/K index. 768 */ 769 int luaK_exp2RK (FuncState *fs, expdesc *e) { 770 luaK_exp2val(fs, e); 771 switch (e->k) { /* move constants to 'k' */ 772 case VTRUE: e->u.info = boolK(fs, 1); goto vk; 773 case VFALSE: e->u.info = boolK(fs, 0); goto vk; 774 case VNIL: e->u.info = nilK(fs); goto vk; 775 case VKINT: e->u.info = luaK_intK(fs, e->u.ival); goto vk; 776 #ifndef _KERNEL 777 case VKFLT: e->u.info = luaK_numberK(fs, e->u.nval); goto vk; 778 #endif /* _KERNEL */ 779 case VK: 780 vk: 781 e->k = VK; 782 if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */ 783 return RKASK(e->u.info); 784 else break; 785 default: break; 786 } 787 /* not a constant in the right range: put it in a register */ 788 return luaK_exp2anyreg(fs, e); 789 } 790 791 792 /* 793 ** Generate code to store result of expression 'ex' into variable 'var'. 794 */ 795 void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { 796 switch (var->k) { 797 case VLOCAL: { 798 freeexp(fs, ex); 799 exp2reg(fs, ex, var->u.info); /* compute 'ex' into proper place */ 800 return; 801 } 802 case VUPVAL: { 803 int e = luaK_exp2anyreg(fs, ex); 804 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); 805 break; 806 } 807 case VINDEXED: { 808 OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; 809 int e = luaK_exp2RK(fs, ex); 810 luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); 811 break; 812 } 813 default: lua_assert(0); /* invalid var kind to store */ 814 } 815 freeexp(fs, ex); 816 } 817 818 819 /* 820 ** Emit SELF instruction (convert expression 'e' into 'e:key(e,'). 821 */ 822 void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { 823 int ereg; 824 luaK_exp2anyreg(fs, e); 825 ereg = e->u.info; /* register where 'e' was placed */ 826 freeexp(fs, e); 827 e->u.info = fs->freereg; /* base register for op_self */ 828 e->k = VNONRELOC; /* self expression has a fixed register */ 829 luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ 830 luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); 831 freeexp(fs, key); 832 } 833 834 835 /* 836 ** Negate condition 'e' (where 'e' is a comparison). 837 */ 838 static void negatecondition (FuncState *fs, expdesc *e) { 839 Instruction *pc = getjumpcontrol(fs, e->u.info); 840 lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && 841 GET_OPCODE(*pc) != OP_TEST); 842 SETARG_A(*pc, !(GETARG_A(*pc))); 843 } 844 845 846 /* 847 ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond' 848 ** is true, code will jump if 'e' is true.) Return jump position. 849 ** Optimize when 'e' is 'not' something, inverting the condition 850 ** and removing the 'not'. 851 */ 852 static int jumponcond (FuncState *fs, expdesc *e, int cond) { 853 if (e->k == VRELOCABLE) { 854 Instruction ie = getinstruction(fs, e); 855 if (GET_OPCODE(ie) == OP_NOT) { 856 fs->pc--; /* remove previous OP_NOT */ 857 return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); 858 } 859 /* else go through */ 860 } 861 discharge2anyreg(fs, e); 862 freeexp(fs, e); 863 return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); 864 } 865 866 867 /* 868 ** Emit code to go through if 'e' is true, jump otherwise. 869 */ 870 void luaK_goiftrue (FuncState *fs, expdesc *e) { 871 int pc; /* pc of new jump */ 872 luaK_dischargevars(fs, e); 873 switch (e->k) { 874 case VJMP: { /* condition? */ 875 negatecondition(fs, e); /* jump when it is false */ 876 pc = e->u.info; /* save jump position */ 877 break; 878 } 879 #ifndef _KERNEL 880 case VK: case VKFLT: case VKINT: case VTRUE: { 881 #else /* _KERNEL */ 882 case VK: case VKINT: case VTRUE: { 883 #endif /* _KERNEL */ 884 pc = NO_JUMP; /* always true; do nothing */ 885 break; 886 } 887 default: { 888 pc = jumponcond(fs, e, 0); /* jump when false */ 889 break; 890 } 891 } 892 luaK_concat(fs, &e->f, pc); /* insert new jump in false list */ 893 luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */ 894 e->t = NO_JUMP; 895 } 896 897 898 /* 899 ** Emit code to go through if 'e' is false, jump otherwise. 900 */ 901 void luaK_goiffalse (FuncState *fs, expdesc *e) { 902 int pc; /* pc of new jump */ 903 luaK_dischargevars(fs, e); 904 switch (e->k) { 905 case VJMP: { 906 pc = e->u.info; /* already jump if true */ 907 break; 908 } 909 case VNIL: case VFALSE: { 910 pc = NO_JUMP; /* always false; do nothing */ 911 break; 912 } 913 default: { 914 pc = jumponcond(fs, e, 1); /* jump if true */ 915 break; 916 } 917 } 918 luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */ 919 luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */ 920 e->f = NO_JUMP; 921 } 922 923 924 /* 925 ** Code 'not e', doing constant folding. 926 */ 927 static void codenot (FuncState *fs, expdesc *e) { 928 luaK_dischargevars(fs, e); 929 switch (e->k) { 930 case VNIL: case VFALSE: { 931 e->k = VTRUE; /* true == not nil == not false */ 932 break; 933 } 934 #ifndef _KERNEL 935 case VK: case VKFLT: case VKINT: case VTRUE: { 936 #else /* _KERNEL */ 937 case VK: case VKINT: case VTRUE: { 938 #endif /* _KERNEL */ 939 e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */ 940 break; 941 } 942 case VJMP: { 943 negatecondition(fs, e); 944 break; 945 } 946 case VRELOCABLE: 947 case VNONRELOC: { 948 discharge2anyreg(fs, e); 949 freeexp(fs, e); 950 e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); 951 e->k = VRELOCABLE; 952 break; 953 } 954 default: lua_assert(0); /* cannot happen */ 955 } 956 /* interchange true and false lists */ 957 { int temp = e->f; e->f = e->t; e->t = temp; } 958 removevalues(fs, e->f); /* values are useless when negated */ 959 removevalues(fs, e->t); 960 } 961 962 963 /* 964 ** Create expression 't[k]'. 't' must have its final result already in a 965 ** register or upvalue. 966 */ 967 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { 968 lua_assert(!hasjumps(t) && (vkisinreg(t->k) || t->k == VUPVAL)); 969 t->u.ind.t = t->u.info; /* register or upvalue index */ 970 t->u.ind.idx = luaK_exp2RK(fs, k); /* R/K index for key */ 971 t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL : VLOCAL; 972 t->k = VINDEXED; 973 } 974 975 976 /* 977 ** Return false if folding can raise an error. 978 ** Bitwise operations need operands convertible to integers; division 979 ** operations cannot have 0 as divisor. 980 */ 981 static int validop (int op, TValue *v1, TValue *v2) { 982 switch (op) { 983 case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: 984 case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */ 985 lua_Integer i; 986 return (tointeger(v1, &i) && tointeger(v2, &i)); 987 } 988 #ifndef _KERNEL 989 case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ 990 #else /* _KERNEL */ 991 case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */ 992 #endif /* _KERNEL */ 993 return (nvalue(v2) != 0); 994 default: return 1; /* everything else is valid */ 995 } 996 } 997 998 999 /* 1000 ** Try to "constant-fold" an operation; return 1 iff successful. 1001 ** (In this case, 'e1' has the final result.) 1002 */ 1003 static int constfolding (FuncState *fs, int op, expdesc *e1, 1004 const expdesc *e2) { 1005 TValue v1, v2, res; 1006 if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2)) 1007 return 0; /* non-numeric operands or not safe to fold */ 1008 luaO_arith(fs->ls->L, op, &v1, &v2, &res); /* does operation */ 1009 if (ttisinteger(&res)) { 1010 e1->k = VKINT; 1011 e1->u.ival = ivalue(&res); 1012 } 1013 else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */ 1014 #ifndef _KERNEL 1015 lua_Number n = fltvalue(&res); 1016 if (luai_numisnan(n) || n == 0) 1017 return 0; 1018 e1->k = VKFLT; 1019 e1->u.nval = n; 1020 #else /* _KERNEL */ 1021 return 0; /* if it is not integer, we must fail */ 1022 #endif /* _KERNEL */ 1023 } 1024 return 1; 1025 } 1026 1027 1028 /* 1029 ** Emit code for unary expressions that "produce values" 1030 ** (everything but 'not'). 1031 ** Expression to produce final result will be encoded in 'e'. 1032 */ 1033 static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) { 1034 int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */ 1035 freeexp(fs, e); 1036 e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */ 1037 e->k = VRELOCABLE; /* all those operations are relocatable */ 1038 luaK_fixline(fs, line); 1039 } 1040 1041 1042 /* 1043 ** Emit code for binary expressions that "produce values" 1044 ** (everything but logical operators 'and'/'or' and comparison 1045 ** operators). 1046 ** Expression to produce final result will be encoded in 'e1'. 1047 ** Because 'luaK_exp2RK' can free registers, its calls must be 1048 ** in "stack order" (that is, first on 'e2', which may have more 1049 ** recent registers to be released). 1050 */ 1051 static void codebinexpval (FuncState *fs, OpCode op, 1052 expdesc *e1, expdesc *e2, int line) { 1053 int rk2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */ 1054 int rk1 = luaK_exp2RK(fs, e1); 1055 freeexps(fs, e1, e2); 1056 e1->u.info = luaK_codeABC(fs, op, 0, rk1, rk2); /* generate opcode */ 1057 e1->k = VRELOCABLE; /* all those operations are relocatable */ 1058 luaK_fixline(fs, line); 1059 } 1060 1061 1062 /* 1063 ** Emit code for comparisons. 1064 ** 'e1' was already put in R/K form by 'luaK_infix'. 1065 */ 1066 static void codecomp (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) { 1067 int rk1 = (e1->k == VK) ? RKASK(e1->u.info) 1068 : check_exp(e1->k == VNONRELOC, e1->u.info); 1069 int rk2 = luaK_exp2RK(fs, e2); 1070 freeexps(fs, e1, e2); 1071 switch (opr) { 1072 case OPR_NE: { /* '(a ~= b)' ==> 'not (a == b)' */ 1073 e1->u.info = condjump(fs, OP_EQ, 0, rk1, rk2); 1074 break; 1075 } 1076 case OPR_GT: case OPR_GE: { 1077 /* '(a > b)' ==> '(b < a)'; '(a >= b)' ==> '(b <= a)' */ 1078 OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ); 1079 e1->u.info = condjump(fs, op, 1, rk2, rk1); /* invert operands */ 1080 break; 1081 } 1082 default: { /* '==', '<', '<=' use their own opcodes */ 1083 OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ); 1084 e1->u.info = condjump(fs, op, 1, rk1, rk2); 1085 break; 1086 } 1087 } 1088 e1->k = VJMP; 1089 } 1090 1091 1092 /* 1093 ** Aplly prefix operation 'op' to expression 'e'. 1094 */ 1095 void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { 1096 static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP}; 1097 switch (op) { 1098 case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */ 1099 if (constfolding(fs, op + LUA_OPUNM, e, &ef)) 1100 break; 1101 /* FALLTHROUGH */ 1102 case OPR_LEN: 1103 codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line); 1104 break; 1105 case OPR_NOT: codenot(fs, e); break; 1106 default: lua_assert(0); 1107 } 1108 } 1109 1110 1111 /* 1112 ** Process 1st operand 'v' of binary operation 'op' before reading 1113 ** 2nd operand. 1114 */ 1115 void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { 1116 switch (op) { 1117 case OPR_AND: { 1118 luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */ 1119 break; 1120 } 1121 case OPR_OR: { 1122 luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */ 1123 break; 1124 } 1125 case OPR_CONCAT: { 1126 luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */ 1127 break; 1128 } 1129 case OPR_ADD: case OPR_SUB: 1130 #ifndef _KERNEL 1131 case OPR_MUL: case OPR_DIV: case OPR_IDIV: 1132 case OPR_MOD: case OPR_POW: 1133 #else /* _KERNEL */ 1134 case OPR_MUL: case OPR_IDIV: 1135 case OPR_MOD: 1136 #endif /* _KERNEL */ 1137 case OPR_BAND: case OPR_BOR: case OPR_BXOR: 1138 case OPR_SHL: case OPR_SHR: { 1139 if (!tonumeral(v, NULL)) 1140 luaK_exp2RK(fs, v); 1141 /* else keep numeral, which may be folded with 2nd operand */ 1142 break; 1143 } 1144 default: { 1145 luaK_exp2RK(fs, v); 1146 break; 1147 } 1148 } 1149 } 1150 1151 1152 /* 1153 ** Finalize code for binary operation, after reading 2nd operand. 1154 ** For '(a .. b .. c)' (which is '(a .. (b .. c))', because 1155 ** concatenation is right associative), merge second CONCAT into first 1156 ** one. 1157 */ 1158 void luaK_posfix (FuncState *fs, BinOpr op, 1159 expdesc *e1, expdesc *e2, int line) { 1160 switch (op) { 1161 case OPR_AND: { 1162 lua_assert(e1->t == NO_JUMP); /* list closed by 'luK_infix' */ 1163 luaK_dischargevars(fs, e2); 1164 luaK_concat(fs, &e2->f, e1->f); 1165 *e1 = *e2; 1166 break; 1167 } 1168 case OPR_OR: { 1169 lua_assert(e1->f == NO_JUMP); /* list closed by 'luK_infix' */ 1170 luaK_dischargevars(fs, e2); 1171 luaK_concat(fs, &e2->t, e1->t); 1172 *e1 = *e2; 1173 break; 1174 } 1175 case OPR_CONCAT: { 1176 luaK_exp2val(fs, e2); 1177 if (e2->k == VRELOCABLE && 1178 GET_OPCODE(getinstruction(fs, e2)) == OP_CONCAT) { 1179 lua_assert(e1->u.info == GETARG_B(getinstruction(fs, e2))-1); 1180 freeexp(fs, e1); 1181 SETARG_B(getinstruction(fs, e2), e1->u.info); 1182 e1->k = VRELOCABLE; e1->u.info = e2->u.info; 1183 } 1184 else { 1185 luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ 1186 codebinexpval(fs, OP_CONCAT, e1, e2, line); 1187 } 1188 break; 1189 } 1190 #ifndef _KERNEL 1191 case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: 1192 case OPR_IDIV: case OPR_MOD: case OPR_POW: 1193 #else /* _KERNEL */ 1194 case OPR_ADD: case OPR_SUB: case OPR_MUL: 1195 case OPR_IDIV: case OPR_MOD: 1196 #endif /* _KERNEL */ 1197 case OPR_BAND: case OPR_BOR: case OPR_BXOR: 1198 case OPR_SHL: case OPR_SHR: { 1199 if (!constfolding(fs, op + LUA_OPADD, e1, e2)) 1200 codebinexpval(fs, cast(OpCode, op + OP_ADD), e1, e2, line); 1201 break; 1202 } 1203 case OPR_EQ: case OPR_LT: case OPR_LE: 1204 case OPR_NE: case OPR_GT: case OPR_GE: { 1205 codecomp(fs, op, e1, e2); 1206 break; 1207 } 1208 default: lua_assert(0); 1209 } 1210 } 1211 1212 1213 /* 1214 ** Change line information associated with current position. 1215 */ 1216 void luaK_fixline (FuncState *fs, int line) { 1217 fs->f->lineinfo[fs->pc - 1] = line; 1218 } 1219 1220 1221 /* 1222 ** Emit a SETLIST instruction. 1223 ** 'base' is register that keeps table; 1224 ** 'nelems' is #table plus those to be stored now; 1225 ** 'tostore' is number of values (in registers 'base + 1',...) to add to 1226 ** table (or LUA_MULTRET to add up to stack top). 1227 */ 1228 void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { 1229 int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; 1230 int b = (tostore == LUA_MULTRET) ? 0 : tostore; 1231 lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH); 1232 if (c <= MAXARG_C) 1233 luaK_codeABC(fs, OP_SETLIST, base, b, c); 1234 else if (c <= MAXARG_Ax) { 1235 luaK_codeABC(fs, OP_SETLIST, base, b, 0); 1236 codeextraarg(fs, c); 1237 } 1238 else 1239 luaX_syntaxerror(fs->ls, "constructor too long"); 1240 fs->freereg = base + 1; /* free registers with list values */ 1241 } 1242 1243