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