9
3

lcode.c 34 KB

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