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