2
0

lcode.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. /*
  2. ** $Id: lcode.c $
  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 <limits.h>
  10. #include <math.h>
  11. #include <stdlib.h>
  12. #include "lua.h"
  13. #include "lcode.h"
  14. #include "ldebug.h"
  15. #include "ldo.h"
  16. #include "lgc.h"
  17. #include "llex.h"
  18. #include "lmem.h"
  19. #include "lobject.h"
  20. #include "lopcodes.h"
  21. #include "lparser.h"
  22. #include "lstring.h"
  23. #include "ltable.h"
  24. #include "lvm.h"
  25. /* Maximum number of registers in a Lua function (must fit in 8 bits) */
  26. #define MAXREGS 255
  27. #define hasjumps(e) ((e)->t != (e)->f)
  28. static int codesJ (FuncState *fs, OpCode o, int sj, int k);
  29. /* semantic error */
  30. l_noret luaK_semerror (LexState *ls, const char *msg) {
  31. ls->t.token = 0; /* remove "near <token>" from final message */
  32. luaX_syntaxerror(ls, msg);
  33. }
  34. /*
  35. ** If expression is a numeric constant, fills 'v' with its value
  36. ** and returns 1. Otherwise, returns 0.
  37. */
  38. static int tonumeral(const expdesc *e, TValue *v) {
  39. if (hasjumps(e))
  40. return 0; /* not a numeral */
  41. switch (e->k) {
  42. case VKINT:
  43. if (v) setivalue(v, e->u.ival);
  44. return 1;
  45. case VKFLT:
  46. if (v) setfltvalue(v, e->u.nval);
  47. return 1;
  48. default: return 0;
  49. }
  50. }
  51. /*
  52. ** Return the previous instruction of the current code. If there
  53. ** may be a jump target between the current instruction and the
  54. ** previous one, return an invalid instruction (to avoid wrong
  55. ** optimizations).
  56. */
  57. static Instruction *previousinstruction (FuncState *fs) {
  58. static const Instruction invalidinstruction = -1;
  59. if (fs->pc > fs->lasttarget)
  60. return &fs->f->code[fs->pc - 1]; /* previous instruction */
  61. else
  62. return cast(Instruction*, &invalidinstruction);
  63. }
  64. /*
  65. ** Create a OP_LOADNIL instruction, but try to optimize: if the previous
  66. ** instruction is also OP_LOADNIL and ranges are compatible, adjust
  67. ** range of previous instruction instead of emitting a new one. (For
  68. ** instance, 'local a; local b' will generate a single opcode.)
  69. */
  70. void luaK_nil (FuncState *fs, int from, int n) {
  71. int l = from + n - 1; /* last register to set nil */
  72. Instruction *previous = previousinstruction(fs);
  73. if (GET_OPCODE(*previous) == OP_LOADNIL) { /* previous is LOADNIL? */
  74. int pfrom = GETARG_A(*previous); /* get previous range */
  75. int pl = pfrom + GETARG_B(*previous);
  76. if ((pfrom <= from && from <= pl + 1) ||
  77. (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
  78. if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */
  79. if (pl > l) l = pl; /* l = max(l, pl) */
  80. SETARG_A(*previous, from);
  81. SETARG_B(*previous, l - from);
  82. return;
  83. } /* else go through */
  84. }
  85. luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
  86. }
  87. /*
  88. ** Gets the destination address of a jump instruction. Used to traverse
  89. ** a list of jumps.
  90. */
  91. static int getjump (FuncState *fs, int pc) {
  92. int offset = GETARG_sJ(fs->f->code[pc]);
  93. if (offset == NO_JUMP) /* point to itself represents end of list */
  94. return NO_JUMP; /* end of list */
  95. else
  96. return (pc+1)+offset; /* turn offset into absolute position */
  97. }
  98. /*
  99. ** Fix jump instruction at position 'pc' to jump to 'dest'.
  100. ** (Jump addresses are relative in Lua)
  101. */
  102. static void fixjump (FuncState *fs, int pc, int dest) {
  103. Instruction *jmp = &fs->f->code[pc];
  104. int offset = dest - (pc + 1);
  105. lua_assert(dest != NO_JUMP);
  106. if (!(-OFFSET_sJ <= offset && offset <= MAXARG_sJ - OFFSET_sJ))
  107. luaX_syntaxerror(fs->ls, "control structure too long");
  108. lua_assert(GET_OPCODE(*jmp) == OP_JMP);
  109. SETARG_sJ(*jmp, offset);
  110. }
  111. /*
  112. ** Concatenate jump-list 'l2' into jump-list 'l1'
  113. */
  114. void luaK_concat (FuncState *fs, int *l1, int l2) {
  115. if (l2 == NO_JUMP) return; /* nothing to concatenate? */
  116. else if (*l1 == NO_JUMP) /* no original list? */
  117. *l1 = l2; /* 'l1' points to 'l2' */
  118. else {
  119. int list = *l1;
  120. int next;
  121. while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */
  122. list = next;
  123. fixjump(fs, list, l2); /* last element links to 'l2' */
  124. }
  125. }
  126. /*
  127. ** Create a jump instruction and return its position, so its destination
  128. ** can be fixed later (with 'fixjump').
  129. */
  130. int luaK_jump (FuncState *fs) {
  131. return codesJ(fs, OP_JMP, NO_JUMP, 0);
  132. }
  133. /*
  134. ** Code a 'return' instruction
  135. */
  136. void luaK_ret (FuncState *fs, int first, int nret) {
  137. OpCode op;
  138. switch (nret) {
  139. case 0: op = OP_RETURN0; break;
  140. case 1: op = OP_RETURN1; break;
  141. default: op = OP_RETURN; break;
  142. }
  143. luaK_codeABC(fs, op, first, nret + 1, 0);
  144. }
  145. /*
  146. ** Code a "conditional jump", that is, a test or comparison opcode
  147. ** followed by a jump. Return jump position.
  148. */
  149. static int condjump (FuncState *fs, OpCode op, int A, int B, int C, int k) {
  150. luaK_codeABCk(fs, op, A, B, C, k);
  151. return luaK_jump(fs);
  152. }
  153. /*
  154. ** returns current 'pc' and marks it as a jump target (to avoid wrong
  155. ** optimizations with consecutive instructions not in the same basic block).
  156. */
  157. int luaK_getlabel (FuncState *fs) {
  158. fs->lasttarget = fs->pc;
  159. return fs->pc;
  160. }
  161. /*
  162. ** Returns the position of the instruction "controlling" a given
  163. ** jump (that is, its condition), or the jump itself if it is
  164. ** unconditional.
  165. */
  166. static Instruction *getjumpcontrol (FuncState *fs, int pc) {
  167. Instruction *pi = &fs->f->code[pc];
  168. if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
  169. return pi-1;
  170. else
  171. return pi;
  172. }
  173. /*
  174. ** Patch destination register for a TESTSET instruction.
  175. ** If instruction in position 'node' is not a TESTSET, return 0 ("fails").
  176. ** Otherwise, if 'reg' is not 'NO_REG', set it as the destination
  177. ** register. Otherwise, change instruction to a simple 'TEST' (produces
  178. ** no register value)
  179. */
  180. static int patchtestreg (FuncState *fs, int node, int reg) {
  181. Instruction *i = getjumpcontrol(fs, node);
  182. if (GET_OPCODE(*i) != OP_TESTSET)
  183. return 0; /* cannot patch other instructions */
  184. if (reg != NO_REG && reg != GETARG_B(*i))
  185. SETARG_A(*i, reg);
  186. else {
  187. /* no register to put value or register already has the value;
  188. change instruction to simple test */
  189. *i = CREATE_ABCk(OP_TEST, GETARG_B(*i), 0, 0, GETARG_k(*i));
  190. }
  191. return 1;
  192. }
  193. /*
  194. ** Traverse a list of tests ensuring no one produces a value
  195. */
  196. static void removevalues (FuncState *fs, int list) {
  197. for (; list != NO_JUMP; list = getjump(fs, list))
  198. patchtestreg(fs, list, NO_REG);
  199. }
  200. /*
  201. ** Traverse a list of tests, patching their destination address and
  202. ** registers: tests producing values jump to 'vtarget' (and put their
  203. ** values in 'reg'), other tests jump to 'dtarget'.
  204. */
  205. static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
  206. int dtarget) {
  207. while (list != NO_JUMP) {
  208. int next = getjump(fs, list);
  209. if (patchtestreg(fs, list, reg))
  210. fixjump(fs, list, vtarget);
  211. else
  212. fixjump(fs, list, dtarget); /* jump to default target */
  213. list = next;
  214. }
  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. lua_assert(target <= fs->pc);
  223. patchlistaux(fs, list, target, NO_REG, target);
  224. }
  225. void luaK_patchtohere (FuncState *fs, int list) {
  226. int hr = luaK_getlabel(fs); /* mark "here" as a jump target */
  227. luaK_patchlist(fs, list, hr);
  228. }
  229. /*
  230. ** MAXimum number of successive Instructions WiTHout ABSolute line
  231. ** information.
  232. */
  233. #if !defined(MAXIWTHABS)
  234. #define MAXIWTHABS 120
  235. #endif
  236. /* limit for difference between lines in relative line info. */
  237. #define LIMLINEDIFF 0x80
  238. /*
  239. ** Save line info for a new instruction. If difference from last line
  240. ** does not fit in a byte, of after that many instructions, save a new
  241. ** absolute line info; (in that case, the special value 'ABSLINEINFO'
  242. ** in 'lineinfo' signals the existence of this absolute information.)
  243. ** Otherwise, store the difference from last line in 'lineinfo'.
  244. */
  245. static void savelineinfo (FuncState *fs, Proto *f, int line) {
  246. int linedif = line - fs->previousline;
  247. int pc = fs->pc - 1; /* last instruction coded */
  248. if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ > MAXIWTHABS) {
  249. luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,
  250. f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines");
  251. f->abslineinfo[fs->nabslineinfo].pc = pc;
  252. f->abslineinfo[fs->nabslineinfo++].line = line;
  253. linedif = ABSLINEINFO; /* signal that there is absolute information */
  254. fs->iwthabs = 0; /* restart counter */
  255. }
  256. luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,
  257. MAX_INT, "opcodes");
  258. f->lineinfo[pc] = linedif;
  259. fs->previousline = line; /* last line saved */
  260. }
  261. /*
  262. ** Remove line information from the last instruction.
  263. ** If line information for that instruction is absolute, set 'iwthabs'
  264. ** above its max to force the new (replacing) instruction to have
  265. ** absolute line info, too.
  266. */
  267. static void removelastlineinfo (FuncState *fs) {
  268. Proto *f = fs->f;
  269. int pc = fs->pc - 1; /* last instruction coded */
  270. if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */
  271. fs->previousline -= f->lineinfo[pc]; /* last line saved */
  272. fs->iwthabs--;
  273. }
  274. else { /* absolute line information */
  275. fs->nabslineinfo--; /* remove it */
  276. lua_assert(f->abslineinfo[fs->nabslineinfo].pc = pc);
  277. fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */
  278. }
  279. }
  280. /*
  281. ** Remove the last instruction created, correcting line information
  282. ** accordingly.
  283. */
  284. static void removelastinstruction (FuncState *fs) {
  285. removelastlineinfo(fs);
  286. fs->pc--;
  287. }
  288. /*
  289. ** Emit instruction 'i', checking for array sizes and saving also its
  290. ** line information. Return 'i' position.
  291. */
  292. static int luaK_code (FuncState *fs, Instruction i) {
  293. Proto *f = fs->f;
  294. /* put new instruction in code array */
  295. luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
  296. MAX_INT, "opcodes");
  297. f->code[fs->pc++] = i;
  298. savelineinfo(fs, f, fs->ls->lastline);
  299. return fs->pc - 1; /* index of new instruction */
  300. }
  301. /*
  302. ** Format and emit an 'iABC' instruction. (Assertions check consistency
  303. ** of parameters versus opcode.)
  304. */
  305. int luaK_codeABCk (FuncState *fs, OpCode o, int a, int b, int c, int k) {
  306. lua_assert(getOpMode(o) == iABC);
  307. lua_assert(a <= MAXARG_A && b <= MAXARG_B &&
  308. c <= MAXARG_C && (k & ~1) == 0);
  309. return luaK_code(fs, CREATE_ABCk(o, a, b, c, k));
  310. }
  311. /*
  312. ** Format and emit an 'iABx' instruction.
  313. */
  314. int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
  315. lua_assert(getOpMode(o) == iABx);
  316. lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx);
  317. return luaK_code(fs, CREATE_ABx(o, a, bc));
  318. }
  319. /*
  320. ** Format and emit an 'iAsBx' instruction.
  321. */
  322. int luaK_codeAsBx (FuncState *fs, OpCode o, int a, int bc) {
  323. unsigned int b = bc + OFFSET_sBx;
  324. lua_assert(getOpMode(o) == iAsBx);
  325. lua_assert(a <= MAXARG_A && b <= MAXARG_Bx);
  326. return luaK_code(fs, CREATE_ABx(o, a, b));
  327. }
  328. /*
  329. ** Format and emit an 'isJ' instruction.
  330. */
  331. static int codesJ (FuncState *fs, OpCode o, int sj, int k) {
  332. unsigned int j = sj + OFFSET_sJ;
  333. lua_assert(getOpMode(o) == isJ);
  334. lua_assert(j <= MAXARG_sJ && (k & ~1) == 0);
  335. return luaK_code(fs, CREATE_sJ(o, j, k));
  336. }
  337. /*
  338. ** Emit an "extra argument" instruction (format 'iAx')
  339. */
  340. static int codeextraarg (FuncState *fs, int a) {
  341. lua_assert(a <= MAXARG_Ax);
  342. return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a));
  343. }
  344. /*
  345. ** Emit a "load constant" instruction, using either 'OP_LOADK'
  346. ** (if constant index 'k' fits in 18 bits) or an 'OP_LOADKX'
  347. ** instruction with "extra argument".
  348. */
  349. static int luaK_codek (FuncState *fs, int reg, int k) {
  350. if (k <= MAXARG_Bx)
  351. return luaK_codeABx(fs, OP_LOADK, reg, k);
  352. else {
  353. int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
  354. codeextraarg(fs, k);
  355. return p;
  356. }
  357. }
  358. /*
  359. ** Check register-stack level, keeping track of its maximum size
  360. ** in field 'maxstacksize'
  361. */
  362. void luaK_checkstack (FuncState *fs, int n) {
  363. int newstack = fs->freereg + n;
  364. if (newstack > fs->f->maxstacksize) {
  365. if (newstack >= MAXREGS)
  366. luaX_syntaxerror(fs->ls,
  367. "function or expression needs too many registers");
  368. fs->f->maxstacksize = cast_byte(newstack);
  369. }
  370. }
  371. /*
  372. ** Reserve 'n' registers in register stack
  373. */
  374. void luaK_reserveregs (FuncState *fs, int n) {
  375. luaK_checkstack(fs, n);
  376. fs->freereg += n;
  377. }
  378. /*
  379. ** Free register 'reg', if it is neither a constant index nor
  380. ** a local variable.
  381. )
  382. */
  383. static void freereg (FuncState *fs, int reg) {
  384. if (reg >= fs->nactvar) {
  385. fs->freereg--;
  386. lua_assert(reg == fs->freereg);
  387. }
  388. }
  389. /*
  390. ** Free two registers in proper order
  391. */
  392. static void freeregs (FuncState *fs, int r1, int r2) {
  393. if (r1 > r2) {
  394. freereg(fs, r1);
  395. freereg(fs, r2);
  396. }
  397. else {
  398. freereg(fs, r2);
  399. freereg(fs, r1);
  400. }
  401. }
  402. /*
  403. ** Free register used by expression 'e' (if any)
  404. */
  405. static void freeexp (FuncState *fs, expdesc *e) {
  406. if (e->k == VNONRELOC)
  407. freereg(fs, e->u.info);
  408. }
  409. /*
  410. ** Free registers used by expressions 'e1' and 'e2' (if any) in proper
  411. ** order.
  412. */
  413. static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {
  414. int r1 = (e1->k == VNONRELOC) ? e1->u.info : -1;
  415. int r2 = (e2->k == VNONRELOC) ? e2->u.info : -1;
  416. freeregs(fs, r1, r2);
  417. }
  418. /*
  419. ** Add constant 'v' to prototype's list of constants (field 'k').
  420. ** Use scanner's table to cache position of constants in constant list
  421. ** and try to reuse constants. Because some values should not be used
  422. ** as keys (nil cannot be a key, integer keys can collapse with float
  423. ** keys), the caller must provide a useful 'key' for indexing the cache.
  424. */
  425. static int addk (FuncState *fs, TValue *key, TValue *v) {
  426. lua_State *L = fs->ls->L;
  427. Proto *f = fs->f;
  428. TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */
  429. int k, oldsize;
  430. if (ttisinteger(idx)) { /* is there an index there? */
  431. k = cast_int(ivalue(idx));
  432. /* correct value? (warning: must distinguish floats from integers!) */
  433. if (k < fs->nk && ttypetag(&f->k[k]) == ttypetag(v) &&
  434. luaV_rawequalobj(&f->k[k], v))
  435. return k; /* reuse index */
  436. }
  437. /* constant not found; create a new entry */
  438. oldsize = f->sizek;
  439. k = fs->nk;
  440. /* numerical value does not need GC barrier;
  441. table has no metatable, so it does not need to invalidate cache */
  442. setivalue(idx, k);
  443. luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
  444. while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
  445. setobj(L, &f->k[k], v);
  446. fs->nk++;
  447. luaC_barrier(L, f, v);
  448. return k;
  449. }
  450. /*
  451. ** Add a string to list of constants and return its index.
  452. */
  453. int luaK_stringK (FuncState *fs, TString *s) {
  454. TValue o;
  455. setsvalue(fs->ls->L, &o, s);
  456. return addk(fs, &o, &o); /* use string itself as key */
  457. }
  458. /*
  459. ** Add an integer to list of constants and return its index.
  460. ** Integers use userdata as keys to avoid collision with floats with
  461. ** same value; conversion to 'void*' is used only for hashing, so there
  462. ** are no "precision" problems.
  463. */
  464. static int luaK_intK (FuncState *fs, lua_Integer n) {
  465. TValue k, o;
  466. setpvalue(&k, cast_voidp(cast_sizet(n)));
  467. setivalue(&o, n);
  468. return addk(fs, &k, &o);
  469. }
  470. /*
  471. ** Add a float to list of constants and return its index.
  472. */
  473. static int luaK_numberK (FuncState *fs, lua_Number r) {
  474. TValue o;
  475. setfltvalue(&o, r);
  476. return addk(fs, &o, &o); /* use number itself as key */
  477. }
  478. /*
  479. ** Add a boolean to list of constants and return its index.
  480. */
  481. static int boolK (FuncState *fs, int b) {
  482. TValue o;
  483. setbvalue(&o, b);
  484. return addk(fs, &o, &o); /* use boolean itself as key */
  485. }
  486. /*
  487. ** Add nil to list of constants and return its index.
  488. */
  489. static int nilK (FuncState *fs) {
  490. TValue k, v;
  491. setnilvalue(&v);
  492. /* cannot use nil as key; instead use table itself to represent nil */
  493. sethvalue(fs->ls->L, &k, fs->ls->h);
  494. return addk(fs, &k, &v);
  495. }
  496. /*
  497. ** Check whether 'i' can be stored in an 'sC' operand.
  498. ** Equivalent to (0 <= i + OFFSET_sC && i + OFFSET_sC <= MAXARG_C)
  499. ** but without risk of overflows in the addition.
  500. */
  501. static int fitsC (lua_Integer i) {
  502. return (-OFFSET_sC <= i && i <= MAXARG_C - OFFSET_sC);
  503. }
  504. /*
  505. ** Check whether 'i' can be stored in an 'sBx' operand.
  506. */
  507. static int fitsBx (lua_Integer i) {
  508. return (-OFFSET_sBx <= i && i <= MAXARG_Bx - OFFSET_sBx);
  509. }
  510. void luaK_int (FuncState *fs, int reg, lua_Integer i) {
  511. if (fitsBx(i))
  512. luaK_codeAsBx(fs, OP_LOADI, reg, cast_int(i));
  513. else
  514. luaK_codek(fs, reg, luaK_intK(fs, i));
  515. }
  516. static int floatI (lua_Number f, lua_Integer *fi) {
  517. return (luaV_flttointeger(f, fi, 0) && fitsBx(*fi));
  518. }
  519. static void luaK_float (FuncState *fs, int reg, lua_Number f) {
  520. lua_Integer fi;
  521. if (floatI(f, &fi))
  522. luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
  523. else
  524. luaK_codek(fs, reg, luaK_numberK(fs, f));
  525. }
  526. /*
  527. ** Fix an expression to return the number of results 'nresults'.
  528. ** Either 'e' is a multi-ret expression (function call or vararg)
  529. ** or 'nresults' is LUA_MULTRET (as any expression can satisfy that).
  530. */
  531. void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
  532. Instruction *pc = &getinstruction(fs, e);
  533. if (e->k == VCALL) /* expression is an open function call? */
  534. SETARG_C(*pc, nresults + 1);
  535. else if (e->k == VVARARG) {
  536. SETARG_C(*pc, nresults + 1);
  537. SETARG_A(*pc, fs->freereg);
  538. luaK_reserveregs(fs, 1);
  539. }
  540. else lua_assert(nresults == LUA_MULTRET);
  541. }
  542. /*
  543. ** Fix an expression to return one result.
  544. ** If expression is not a multi-ret expression (function call or
  545. ** vararg), it already returns one result, so nothing needs to be done.
  546. ** Function calls become VNONRELOC expressions (as its result comes
  547. ** fixed in the base register of the call), while vararg expressions
  548. ** become VRELOC (as OP_VARARG puts its results where it wants).
  549. ** (Calls are created returning one result, so that does not need
  550. ** to be fixed.)
  551. */
  552. void luaK_setoneret (FuncState *fs, expdesc *e) {
  553. if (e->k == VCALL) { /* expression is an open function call? */
  554. /* already returns 1 value */
  555. lua_assert(GETARG_C(getinstruction(fs, e)) == 2);
  556. e->k = VNONRELOC; /* result has fixed position */
  557. e->u.info = GETARG_A(getinstruction(fs, e));
  558. }
  559. else if (e->k == VVARARG) {
  560. SETARG_C(getinstruction(fs, e), 2);
  561. e->k = VRELOC; /* can relocate its simple result */
  562. }
  563. }
  564. /*
  565. ** Ensure that expression 'e' is not a variable.
  566. ** (Expression still may have jump lists.)
  567. */
  568. void luaK_dischargevars (FuncState *fs, expdesc *e) {
  569. switch (e->k) {
  570. case VLOCAL: { /* already in a register */
  571. e->u.info = e->u.var.idx;
  572. e->k = VNONRELOC; /* becomes a non-relocatable value */
  573. break;
  574. }
  575. case VUPVAL: { /* move value to some (pending) register */
  576. e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.var.idx, 0);
  577. e->k = VRELOC;
  578. break;
  579. }
  580. case VINDEXUP: {
  581. e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);
  582. e->k = VRELOC;
  583. break;
  584. }
  585. case VINDEXI: {
  586. freereg(fs, e->u.ind.t);
  587. e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);
  588. e->k = VRELOC;
  589. break;
  590. }
  591. case VINDEXSTR: {
  592. freereg(fs, e->u.ind.t);
  593. e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);
  594. e->k = VRELOC;
  595. break;
  596. }
  597. case VINDEXED: {
  598. freeregs(fs, e->u.ind.t, e->u.ind.idx);
  599. e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);
  600. e->k = VRELOC;
  601. break;
  602. }
  603. case VVARARG: case VCALL: {
  604. luaK_setoneret(fs, e);
  605. break;
  606. }
  607. default: break; /* there is one value available (somewhere) */
  608. }
  609. }
  610. /*
  611. ** Ensures expression value is in register 'reg' (and therefore
  612. ** 'e' will become a non-relocatable expression).
  613. ** (Expression still may have jump lists.)
  614. */
  615. static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
  616. luaK_dischargevars(fs, e);
  617. switch (e->k) {
  618. case VNIL: {
  619. luaK_nil(fs, reg, 1);
  620. break;
  621. }
  622. case VFALSE: case VTRUE: {
  623. luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
  624. break;
  625. }
  626. case VK: {
  627. luaK_codek(fs, reg, e->u.info);
  628. break;
  629. }
  630. case VKFLT: {
  631. luaK_float(fs, reg, e->u.nval);
  632. break;
  633. }
  634. case VKINT: {
  635. luaK_int(fs, reg, e->u.ival);
  636. break;
  637. }
  638. case VRELOC: {
  639. Instruction *pc = &getinstruction(fs, e);
  640. SETARG_A(*pc, reg); /* instruction will put result in 'reg' */
  641. break;
  642. }
  643. case VNONRELOC: {
  644. if (reg != e->u.info)
  645. luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
  646. break;
  647. }
  648. default: {
  649. lua_assert(e->k == VJMP);
  650. return; /* nothing to do... */
  651. }
  652. }
  653. e->u.info = reg;
  654. e->k = VNONRELOC;
  655. }
  656. /*
  657. ** Ensures expression value is in any register.
  658. ** (Expression still may have jump lists.)
  659. */
  660. static void discharge2anyreg (FuncState *fs, expdesc *e) {
  661. if (e->k != VNONRELOC) { /* no fixed register yet? */
  662. luaK_reserveregs(fs, 1); /* get a register */
  663. discharge2reg(fs, e, fs->freereg-1); /* put value there */
  664. }
  665. }
  666. static int code_loadbool (FuncState *fs, int A, int b, int jump) {
  667. luaK_getlabel(fs); /* those instructions may be jump targets */
  668. return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
  669. }
  670. /*
  671. ** check whether list has any jump that do not produce a value
  672. ** or produce an inverted value
  673. */
  674. static int need_value (FuncState *fs, int list) {
  675. for (; list != NO_JUMP; list = getjump(fs, list)) {
  676. Instruction i = *getjumpcontrol(fs, list);
  677. if (GET_OPCODE(i) != OP_TESTSET) return 1;
  678. }
  679. return 0; /* not found */
  680. }
  681. /*
  682. ** Ensures final expression result (which includes results from its
  683. ** jump lists) is in register 'reg'.
  684. ** If expression has jumps, need to patch these jumps either to
  685. ** its final position or to "load" instructions (for those tests
  686. ** that do not produce values).
  687. */
  688. static void exp2reg (FuncState *fs, expdesc *e, int reg) {
  689. discharge2reg(fs, e, reg);
  690. if (e->k == VJMP) /* expression itself is a test? */
  691. luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
  692. if (hasjumps(e)) {
  693. int final; /* position after whole expression */
  694. int p_f = NO_JUMP; /* position of an eventual LOAD false */
  695. int p_t = NO_JUMP; /* position of an eventual LOAD true */
  696. if (need_value(fs, e->t) || need_value(fs, e->f)) {
  697. int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
  698. p_f = code_loadbool(fs, reg, 0, 1); /* load false and skip next i. */
  699. p_t = code_loadbool(fs, reg, 1, 0); /* load true */
  700. /* jump around these booleans if 'e' is not a test */
  701. luaK_patchtohere(fs, fj);
  702. }
  703. final = luaK_getlabel(fs);
  704. patchlistaux(fs, e->f, final, reg, p_f);
  705. patchlistaux(fs, e->t, final, reg, p_t);
  706. }
  707. e->f = e->t = NO_JUMP;
  708. e->u.info = reg;
  709. e->k = VNONRELOC;
  710. }
  711. /*
  712. ** Ensures final expression result is in next available register.
  713. */
  714. void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
  715. luaK_dischargevars(fs, e);
  716. freeexp(fs, e);
  717. luaK_reserveregs(fs, 1);
  718. exp2reg(fs, e, fs->freereg - 1);
  719. }
  720. /*
  721. ** Ensures final expression result is in some (any) register
  722. ** and return that register.
  723. */
  724. int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
  725. luaK_dischargevars(fs, e);
  726. if (e->k == VNONRELOC) { /* expression already has a register? */
  727. if (!hasjumps(e)) /* no jumps? */
  728. return e->u.info; /* result is already in a register */
  729. if (e->u.info >= fs->nactvar) { /* reg. is not a local? */
  730. exp2reg(fs, e, e->u.info); /* put final result in it */
  731. return e->u.info;
  732. }
  733. }
  734. luaK_exp2nextreg(fs, e); /* otherwise, use next available register */
  735. return e->u.info;
  736. }
  737. /*
  738. ** Ensures final expression result is either in a register
  739. ** or in an upvalue.
  740. */
  741. void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
  742. if (e->k != VUPVAL || hasjumps(e))
  743. luaK_exp2anyreg(fs, e);
  744. }
  745. /*
  746. ** Ensures final expression result is either in a register
  747. ** or it is a constant.
  748. */
  749. void luaK_exp2val (FuncState *fs, expdesc *e) {
  750. if (hasjumps(e))
  751. luaK_exp2anyreg(fs, e);
  752. else
  753. luaK_dischargevars(fs, e);
  754. }
  755. /*
  756. ** Try to make 'e' a K expression with an index in the range of R/K
  757. ** indices. Return true iff succeeded.
  758. */
  759. static int luaK_exp2K (FuncState *fs, expdesc *e) {
  760. if (!hasjumps(e)) {
  761. int info;
  762. switch (e->k) { /* move constants to 'k' */
  763. case VTRUE: info = boolK(fs, 1); break;
  764. case VFALSE: info = boolK(fs, 0); break;
  765. case VNIL: info = nilK(fs); break;
  766. case VKINT: info = luaK_intK(fs, e->u.ival); break;
  767. case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
  768. case VK: info = e->u.info; break;
  769. default: return 0; /* not a constant */
  770. }
  771. if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
  772. e->k = VK; /* make expression a 'K' expression */
  773. e->u.info = info;
  774. return 1;
  775. }
  776. }
  777. /* else, expression doesn't fit; leave it unchanged */
  778. return 0;
  779. }
  780. /*
  781. ** Ensures final expression result is in a valid R/K index
  782. ** (that is, it is either in a register or in 'k' with an index
  783. ** in the range of R/K indices).
  784. ** Returns 1 iff expression is K.
  785. */
  786. int luaK_exp2RK (FuncState *fs, expdesc *e) {
  787. if (luaK_exp2K(fs, e))
  788. return 1;
  789. else { /* not a constant in the right range: put it in a register */
  790. luaK_exp2anyreg(fs, e);
  791. return 0;
  792. }
  793. }
  794. static void codeABRK (FuncState *fs, OpCode o, int a, int b,
  795. expdesc *ec) {
  796. int k = luaK_exp2RK(fs, ec);
  797. luaK_codeABCk(fs, o, a, b, ec->u.info, k);
  798. }
  799. /*
  800. ** Generate code to store result of expression 'ex' into variable 'var'.
  801. */
  802. void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
  803. switch (var->k) {
  804. case VLOCAL: {
  805. freeexp(fs, ex);
  806. exp2reg(fs, ex, var->u.var.idx); /* compute 'ex' into proper place */
  807. return;
  808. }
  809. case VUPVAL: {
  810. int e = luaK_exp2anyreg(fs, ex);
  811. luaK_codeABC(fs, OP_SETUPVAL, e, var->u.var.idx, 0);
  812. break;
  813. }
  814. case VINDEXUP: {
  815. codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);
  816. break;
  817. }
  818. case VINDEXI: {
  819. codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);
  820. break;
  821. }
  822. case VINDEXSTR: {
  823. codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);
  824. break;
  825. }
  826. case VINDEXED: {
  827. codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);
  828. break;
  829. }
  830. default: lua_assert(0); /* invalid var kind to store */
  831. }
  832. freeexp(fs, ex);
  833. }
  834. /*
  835. ** Emit SELF instruction (convert expression 'e' into 'e:key(e,').
  836. */
  837. void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
  838. int ereg;
  839. luaK_exp2anyreg(fs, e);
  840. ereg = e->u.info; /* register where 'e' was placed */
  841. freeexp(fs, e);
  842. e->u.info = fs->freereg; /* base register for op_self */
  843. e->k = VNONRELOC; /* self expression has a fixed register */
  844. luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
  845. codeABRK(fs, OP_SELF, e->u.info, ereg, key);
  846. freeexp(fs, key);
  847. }
  848. /*
  849. ** Negate condition 'e' (where 'e' is a comparison).
  850. */
  851. static void negatecondition (FuncState *fs, expdesc *e) {
  852. Instruction *pc = getjumpcontrol(fs, e->u.info);
  853. lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
  854. GET_OPCODE(*pc) != OP_TEST);
  855. SETARG_k(*pc, (GETARG_k(*pc) ^ 1));
  856. }
  857. /*
  858. ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
  859. ** is true, code will jump if 'e' is true.) Return jump position.
  860. ** Optimize when 'e' is 'not' something, inverting the condition
  861. ** and removing the 'not'.
  862. */
  863. static int jumponcond (FuncState *fs, expdesc *e, int cond) {
  864. if (e->k == VRELOC) {
  865. Instruction ie = getinstruction(fs, e);
  866. if (GET_OPCODE(ie) == OP_NOT) {
  867. removelastinstruction(fs); /* remove previous OP_NOT */
  868. return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);
  869. }
  870. /* else go through */
  871. }
  872. discharge2anyreg(fs, e);
  873. freeexp(fs, e);
  874. return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);
  875. }
  876. /*
  877. ** Emit code to go through if 'e' is true, jump otherwise.
  878. */
  879. void luaK_goiftrue (FuncState *fs, expdesc *e) {
  880. int pc; /* pc of new jump */
  881. luaK_dischargevars(fs, e);
  882. switch (e->k) {
  883. case VJMP: { /* condition? */
  884. negatecondition(fs, e); /* jump when it is false */
  885. pc = e->u.info; /* save jump position */
  886. break;
  887. }
  888. case VK: case VKFLT: case VKINT: case VTRUE: {
  889. pc = NO_JUMP; /* always true; do nothing */
  890. break;
  891. }
  892. default: {
  893. pc = jumponcond(fs, e, 0); /* jump when false */
  894. break;
  895. }
  896. }
  897. luaK_concat(fs, &e->f, pc); /* insert new jump in false list */
  898. luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */
  899. e->t = NO_JUMP;
  900. }
  901. /*
  902. ** Emit code to go through if 'e' is false, jump otherwise.
  903. */
  904. void luaK_goiffalse (FuncState *fs, expdesc *e) {
  905. int pc; /* pc of new jump */
  906. luaK_dischargevars(fs, e);
  907. switch (e->k) {
  908. case VJMP: {
  909. pc = e->u.info; /* already jump if true */
  910. break;
  911. }
  912. case VNIL: case VFALSE: {
  913. pc = NO_JUMP; /* always false; do nothing */
  914. break;
  915. }
  916. default: {
  917. pc = jumponcond(fs, e, 1); /* jump if true */
  918. break;
  919. }
  920. }
  921. luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */
  922. luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */
  923. e->f = NO_JUMP;
  924. }
  925. /*
  926. ** Code 'not e', doing constant folding.
  927. */
  928. static void codenot (FuncState *fs, expdesc *e) {
  929. luaK_dischargevars(fs, e);
  930. switch (e->k) {
  931. case VNIL: case VFALSE: {
  932. e->k = VTRUE; /* true == not nil == not false */
  933. break;
  934. }
  935. case VK: case VKFLT: case VKINT: case VTRUE: {
  936. e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
  937. break;
  938. }
  939. case VJMP: {
  940. negatecondition(fs, e);
  941. break;
  942. }
  943. case VRELOC:
  944. case VNONRELOC: {
  945. discharge2anyreg(fs, e);
  946. freeexp(fs, e);
  947. e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
  948. e->k = VRELOC;
  949. break;
  950. }
  951. default: lua_assert(0); /* cannot happen */
  952. }
  953. /* interchange true and false lists */
  954. { int temp = e->f; e->f = e->t; e->t = temp; }
  955. removevalues(fs, e->f); /* values are useless when negated */
  956. removevalues(fs, e->t);
  957. }
  958. /*
  959. ** Check whether expression 'e' is a small literal string
  960. */
  961. static int isKstr (FuncState *fs, expdesc *e) {
  962. return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B &&
  963. ttisshrstring(&fs->f->k[e->u.info]));
  964. }
  965. /*
  966. ** Check whether expression 'e' is a literal integer.
  967. */
  968. int luaK_isKint (expdesc *e) {
  969. return (e->k == VKINT && !hasjumps(e));
  970. }
  971. /*
  972. ** Check whether expression 'e' is a literal integer in
  973. ** proper range to fit in register C
  974. */
  975. static int isCint (expdesc *e) {
  976. return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));
  977. }
  978. /*
  979. ** Check whether expression 'e' is a literal integer in
  980. ** proper range to fit in register sC
  981. */
  982. static int isSCint (expdesc *e) {
  983. return luaK_isKint(e) && fitsC(e->u.ival);
  984. }
  985. /*
  986. ** Check whether expression 'e' is a literal integer or float in
  987. ** proper range to fit in a register (sB or sC).
  988. */
  989. static int isSCnumber (expdesc *e, lua_Integer *i, int *isfloat) {
  990. if (e->k == VKINT)
  991. *i = e->u.ival;
  992. else if (!(e->k == VKFLT && floatI(e->u.nval, i)))
  993. return 0; /* not a number */
  994. else
  995. *isfloat = 1;
  996. if (!hasjumps(e) && fitsC(*i)) {
  997. *i += OFFSET_sC;
  998. return 1;
  999. }
  1000. else
  1001. return 0;
  1002. }
  1003. /*
  1004. ** Create expression 't[k]'. 't' must have its final result already in a
  1005. ** register or upvalue. Upvalues can only be indexed by literal strings.
  1006. ** Keys can be literal strings in the constant table or arbitrary
  1007. ** values in registers.
  1008. */
  1009. void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
  1010. lua_assert(!hasjumps(t) &&
  1011. (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL));
  1012. if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non string? */
  1013. luaK_exp2anyreg(fs, t); /* put it in a register */
  1014. if (t->k == VUPVAL) {
  1015. t->u.ind.t = t->u.var.idx; /* upvalue index */
  1016. t->u.ind.idx = k->u.info; /* literal string */
  1017. t->k = VINDEXUP;
  1018. }
  1019. else {
  1020. /* register index of the table */
  1021. t->u.ind.t = (t->k == VLOCAL) ? t->u.var.idx: t->u.info;
  1022. if (isKstr(fs, k)) {
  1023. t->u.ind.idx = k->u.info; /* literal string */
  1024. t->k = VINDEXSTR;
  1025. }
  1026. else if (isCint(k)) {
  1027. t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */
  1028. t->k = VINDEXI;
  1029. }
  1030. else {
  1031. t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */
  1032. t->k = VINDEXED;
  1033. }
  1034. }
  1035. }
  1036. /*
  1037. ** Return false if folding can raise an error.
  1038. ** Bitwise operations need operands convertible to integers; division
  1039. ** operations cannot have 0 as divisor.
  1040. */
  1041. static int validop (int op, TValue *v1, TValue *v2) {
  1042. switch (op) {
  1043. case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
  1044. case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
  1045. lua_Integer i;
  1046. return (tointegerns(v1, &i) && tointegerns(v2, &i));
  1047. }
  1048. case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
  1049. return (nvalue(v2) != 0);
  1050. default: return 1; /* everything else is valid */
  1051. }
  1052. }
  1053. /*
  1054. ** Try to "constant-fold" an operation; return 1 iff successful.
  1055. ** (In this case, 'e1' has the final result.)
  1056. */
  1057. static int constfolding (FuncState *fs, int op, expdesc *e1,
  1058. const expdesc *e2) {
  1059. TValue v1, v2, res;
  1060. if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
  1061. return 0; /* non-numeric operands or not safe to fold */
  1062. luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
  1063. if (ttisinteger(&res)) {
  1064. e1->k = VKINT;
  1065. e1->u.ival = ivalue(&res);
  1066. }
  1067. else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
  1068. lua_Number n = fltvalue(&res);
  1069. if (luai_numisnan(n) || n == 0)
  1070. return 0;
  1071. e1->k = VKFLT;
  1072. e1->u.nval = n;
  1073. }
  1074. return 1;
  1075. }
  1076. /*
  1077. ** Emit code for unary expressions that "produce values"
  1078. ** (everything but 'not').
  1079. ** Expression to produce final result will be encoded in 'e'.
  1080. */
  1081. static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
  1082. int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */
  1083. freeexp(fs, e);
  1084. e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */
  1085. e->k = VRELOC; /* all those operations are relocatable */
  1086. luaK_fixline(fs, line);
  1087. }
  1088. /*
  1089. ** Emit code for binary expressions that "produce values"
  1090. ** (everything but logical operators 'and'/'or' and comparison
  1091. ** operators).
  1092. ** Expression to produce final result will be encoded in 'e1'.
  1093. ** Because 'luaK_exp2anyreg' can free registers, its calls must be
  1094. ** in "stack order" (that is, first on 'e2', which may have more
  1095. ** recent registers to be released).
  1096. */
  1097. static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
  1098. OpCode op, int v2, int k, int line) {
  1099. int v1 = luaK_exp2anyreg(fs, e1);
  1100. int pc = luaK_codeABCk(fs, op, 0, v1, v2, k);
  1101. freeexps(fs, e1, e2);
  1102. e1->u.info = pc;
  1103. e1->k = VRELOC; /* all those operations are relocatable */
  1104. luaK_fixline(fs, line);
  1105. }
  1106. /*
  1107. ** Emit code for binary expressions that "produce values" over
  1108. ** two registers.
  1109. */
  1110. static void codebinexpval (FuncState *fs, OpCode op,
  1111. expdesc *e1, expdesc *e2, int line) {
  1112. int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */
  1113. finishbinexpval(fs, e1, e2, op, v2, 0, line);
  1114. }
  1115. /*
  1116. ** Code binary operators ('+', '-', ...) with immediate operands.
  1117. */
  1118. static void codebini (FuncState *fs, OpCode op,
  1119. expdesc *e1, expdesc *e2, int k, int line) {
  1120. int v2 = cast_int(e2->u.ival) + OFFSET_sC; /* immediate operand */
  1121. finishbinexpval(fs, e1, e2, op, v2, k, line);
  1122. }
  1123. static void swapexps (expdesc *e1, expdesc *e2) {
  1124. expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
  1125. }
  1126. /*
  1127. ** Code arithmetic operators ('+', '-', ...). If second operand is a
  1128. ** constant in the proper range, use variant opcodes with immediate
  1129. ** operands or K operands.
  1130. */
  1131. static void codearith (FuncState *fs, OpCode op,
  1132. expdesc *e1, expdesc *e2, int flip, int line) {
  1133. if (isSCint(e2)) /* immediate operand? */
  1134. codebini(fs, cast(OpCode, op - OP_ADD + OP_ADDI), e1, e2, flip, line);
  1135. else if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */
  1136. int v2 = e2->u.info; /* K index */
  1137. op = cast(OpCode, op - OP_ADD + OP_ADDK);
  1138. finishbinexpval(fs, e1, e2, op, v2, flip, line);
  1139. }
  1140. else { /* 'e2' is neither an immediate nor a K operand */
  1141. if (flip)
  1142. swapexps(e1, e2); /* back to original order */
  1143. codebinexpval(fs, op, e1, e2, line); /* use standard operators */
  1144. }
  1145. }
  1146. /*
  1147. ** Code commutative operators ('+', '*'). If first operand is a
  1148. ** numeric constant, change order of operands to try to use an
  1149. ** immediate or K operator.
  1150. */
  1151. static void codecommutative (FuncState *fs, OpCode op,
  1152. expdesc *e1, expdesc *e2, int line) {
  1153. int flip = 0;
  1154. if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
  1155. swapexps(e1, e2); /* change order */
  1156. flip = 1;
  1157. }
  1158. codearith(fs, op, e1, e2, flip, line);
  1159. }
  1160. /*
  1161. ** Code bitwise operations; they are all associative, so the function
  1162. ** tries to put an integer constant as the 2nd operand (a K operand).
  1163. */
  1164. static void codebitwise (FuncState *fs, BinOpr opr,
  1165. expdesc *e1, expdesc *e2, int line) {
  1166. int inv = 0;
  1167. int v2;
  1168. OpCode op;
  1169. if (e1->k == VKINT && luaK_exp2RK(fs, e1)) {
  1170. swapexps(e1, e2); /* 'e2' will be the constant operand */
  1171. inv = 1;
  1172. }
  1173. else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */
  1174. op = cast(OpCode, opr - OPR_BAND + OP_BAND);
  1175. codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */
  1176. return;
  1177. }
  1178. v2 = e2->u.info; /* index in K array */
  1179. op = cast(OpCode, opr - OPR_BAND + OP_BANDK);
  1180. lua_assert(ttisinteger(&fs->f->k[v2]));
  1181. finishbinexpval(fs, e1, e2, op, v2, inv, line);
  1182. }
  1183. /*
  1184. ** Code shift operators. If second operand is constant, use immediate
  1185. ** operand (negating it if shift is in the other direction).
  1186. */
  1187. static void codeshift (FuncState *fs, OpCode op,
  1188. expdesc *e1, expdesc *e2, int line) {
  1189. if (isSCint(e2)) {
  1190. int changedir = 0;
  1191. if (op == OP_SHL) {
  1192. changedir = 1;
  1193. e2->u.ival = -(e2->u.ival);
  1194. }
  1195. codebini(fs, OP_SHRI, e1, e2, changedir, line);
  1196. }
  1197. else
  1198. codebinexpval(fs, op, e1, e2, line);
  1199. }
  1200. /*
  1201. ** Emit code for order comparisons. When using an immediate operand,
  1202. ** 'isfloat' tells whether the original value was a float.
  1203. */
  1204. static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
  1205. int r1, r2;
  1206. lua_Integer im;
  1207. int isfloat = 0;
  1208. if (isSCnumber(e2, &im, &isfloat)) {
  1209. /* use immediate operand */
  1210. r1 = luaK_exp2anyreg(fs, e1);
  1211. r2 = cast_int(im);
  1212. op = cast(OpCode, (op - OP_LT) + OP_LTI);
  1213. }
  1214. else if (isSCnumber(e1, &im, &isfloat)) {
  1215. /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
  1216. r1 = luaK_exp2anyreg(fs, e2);
  1217. r2 = cast_int(im);
  1218. op = (op == OP_LT) ? OP_GTI : OP_GEI;
  1219. }
  1220. else { /* regular case, compare two registers */
  1221. r1 = luaK_exp2anyreg(fs, e1);
  1222. r2 = luaK_exp2anyreg(fs, e2);
  1223. }
  1224. freeexps(fs, e1, e2);
  1225. e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);
  1226. e1->k = VJMP;
  1227. }
  1228. /*
  1229. ** Emit code for equality comparisons ('==', '~=').
  1230. ** 'e1' was already put as RK by 'luaK_infix'.
  1231. */
  1232. static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
  1233. int r1, r2;
  1234. lua_Integer im;
  1235. int isfloat = 0; /* not needed here, but kept for symmetry */
  1236. OpCode op;
  1237. if (e1->k != VNONRELOC) {
  1238. lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
  1239. swapexps(e1, e2);
  1240. }
  1241. r1 = luaK_exp2anyreg(fs, e1); /* 1nd expression must be in register */
  1242. if (isSCnumber(e2, &im, &isfloat)) {
  1243. op = OP_EQI;
  1244. r2 = cast_int(im); /* immediate operand */
  1245. }
  1246. else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */
  1247. op = OP_EQK;
  1248. r2 = e2->u.info; /* constant index */
  1249. }
  1250. else {
  1251. op = OP_EQ; /* will compare two registers */
  1252. r2 = luaK_exp2anyreg(fs, e2);
  1253. }
  1254. freeexps(fs, e1, e2);
  1255. e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));
  1256. e1->k = VJMP;
  1257. }
  1258. /*
  1259. ** Apply prefix operation 'op' to expression 'e'.
  1260. */
  1261. void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
  1262. static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
  1263. switch (op) {
  1264. case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
  1265. if (constfolding(fs, op + LUA_OPUNM, e, &ef))
  1266. break;
  1267. /* FALLTHROUGH */
  1268. case OPR_LEN:
  1269. codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line);
  1270. break;
  1271. case OPR_NOT: codenot(fs, e); break;
  1272. default: lua_assert(0);
  1273. }
  1274. }
  1275. /*
  1276. ** Process 1st operand 'v' of binary operation 'op' before reading
  1277. ** 2nd operand.
  1278. */
  1279. void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
  1280. switch (op) {
  1281. case OPR_AND: {
  1282. luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
  1283. break;
  1284. }
  1285. case OPR_OR: {
  1286. luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */
  1287. break;
  1288. }
  1289. case OPR_CONCAT: {
  1290. luaK_exp2nextreg(fs, v); /* operand must be on the stack */
  1291. break;
  1292. }
  1293. case OPR_ADD: case OPR_SUB:
  1294. case OPR_MUL: case OPR_DIV: case OPR_IDIV:
  1295. case OPR_MOD: case OPR_POW:
  1296. case OPR_BAND: case OPR_BOR: case OPR_BXOR:
  1297. case OPR_SHL: case OPR_SHR: {
  1298. if (!tonumeral(v, NULL))
  1299. luaK_exp2anyreg(fs, v);
  1300. /* else keep numeral, which may be folded with 2nd operand */
  1301. break;
  1302. }
  1303. case OPR_EQ: case OPR_NE: {
  1304. if (!tonumeral(v, NULL))
  1305. luaK_exp2RK(fs, v);
  1306. /* else keep numeral, which may be an immediate operand */
  1307. break;
  1308. }
  1309. case OPR_LT: case OPR_LE:
  1310. case OPR_GT: case OPR_GE: {
  1311. lua_Integer dummy;
  1312. int dummy2;
  1313. if (!isSCnumber(v, &dummy, &dummy2))
  1314. luaK_exp2anyreg(fs, v);
  1315. /* else keep numeral, which may be an immediate operand */
  1316. break;
  1317. }
  1318. default: lua_assert(0);
  1319. }
  1320. }
  1321. /*
  1322. ** Create code for '(e1 .. e2)'.
  1323. ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',
  1324. ** because concatenation is right associative), merge both CONCATs.
  1325. */
  1326. static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
  1327. Instruction *ie2 = previousinstruction(fs);
  1328. if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */
  1329. int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */
  1330. lua_assert(e1->u.info + 1 == GETARG_A(*ie2));
  1331. freeexp(fs, e2);
  1332. SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */
  1333. SETARG_B(*ie2, n + 1); /* will concatenate one more element */
  1334. }
  1335. else { /* 'e2' is not a concatenation */
  1336. luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */
  1337. freeexp(fs, e2);
  1338. luaK_fixline(fs, line);
  1339. }
  1340. }
  1341. /*
  1342. ** Finalize code for binary operation, after reading 2nd operand.
  1343. */
  1344. void luaK_posfix (FuncState *fs, BinOpr opr,
  1345. expdesc *e1, expdesc *e2, int line) {
  1346. switch (opr) {
  1347. case OPR_AND: {
  1348. lua_assert(e1->t == NO_JUMP); /* list closed by 'luK_infix' */
  1349. luaK_dischargevars(fs, e2);
  1350. luaK_concat(fs, &e2->f, e1->f);
  1351. *e1 = *e2;
  1352. break;
  1353. }
  1354. case OPR_OR: {
  1355. lua_assert(e1->f == NO_JUMP); /* list closed by 'luK_infix' */
  1356. luaK_dischargevars(fs, e2);
  1357. luaK_concat(fs, &e2->t, e1->t);
  1358. *e1 = *e2;
  1359. break;
  1360. }
  1361. case OPR_CONCAT: { /* e1 .. e2 */
  1362. luaK_exp2nextreg(fs, e2);
  1363. codeconcat(fs, e1, e2, line);
  1364. break;
  1365. }
  1366. case OPR_ADD: case OPR_MUL: {
  1367. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1368. codecommutative(fs, cast(OpCode, opr + OP_ADD), e1, e2, line);
  1369. break;
  1370. }
  1371. case OPR_SUB: case OPR_DIV:
  1372. case OPR_IDIV: case OPR_MOD: case OPR_POW: {
  1373. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1374. codearith(fs, cast(OpCode, opr + OP_ADD), e1, e2, 0, line);
  1375. break;
  1376. }
  1377. case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
  1378. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1379. codebitwise(fs, opr, e1, e2, line);
  1380. break;
  1381. }
  1382. case OPR_SHL: {
  1383. if (!constfolding(fs, LUA_OPSHL, e1, e2)) {
  1384. if (isSCint(e1)) {
  1385. swapexps(e1, e2);
  1386. codebini(fs, OP_SHLI, e1, e2, 1, line);
  1387. }
  1388. else
  1389. codeshift(fs, OP_SHL, e1, e2, line);
  1390. }
  1391. break;
  1392. }
  1393. case OPR_SHR: {
  1394. if (!constfolding(fs, LUA_OPSHR, e1, e2))
  1395. codeshift(fs, OP_SHR, e1, e2, line);
  1396. break;
  1397. }
  1398. case OPR_EQ: case OPR_NE: {
  1399. codeeq(fs, opr, e1, e2);
  1400. break;
  1401. }
  1402. case OPR_LT: case OPR_LE: {
  1403. OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ);
  1404. codeorder(fs, op, e1, e2);
  1405. break;
  1406. }
  1407. case OPR_GT: case OPR_GE: {
  1408. /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */
  1409. OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ);
  1410. swapexps(e1, e2);
  1411. codeorder(fs, op, e1, e2);
  1412. break;
  1413. }
  1414. default: lua_assert(0);
  1415. }
  1416. }
  1417. /*
  1418. ** Change line information associated with current position, by removing
  1419. ** previous info and adding it again with new line.
  1420. */
  1421. void luaK_fixline (FuncState *fs, int line) {
  1422. removelastlineinfo(fs);
  1423. savelineinfo(fs, fs->f, line);
  1424. }
  1425. /*
  1426. ** Emit a SETLIST instruction.
  1427. ** 'base' is register that keeps table;
  1428. ** 'nelems' is #table plus those to be stored now;
  1429. ** 'tostore' is number of values (in registers 'base + 1',...) to add to
  1430. ** table (or LUA_MULTRET to add up to stack top).
  1431. */
  1432. void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
  1433. int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1;
  1434. int b = (tostore == LUA_MULTRET) ? 0 : tostore;
  1435. lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);
  1436. if (c <= MAXARG_C)
  1437. luaK_codeABC(fs, OP_SETLIST, base, b, c);
  1438. else if (c <= MAXARG_Ax) {
  1439. luaK_codeABC(fs, OP_SETLIST, base, b, 0);
  1440. codeextraarg(fs, c);
  1441. }
  1442. else
  1443. luaX_syntaxerror(fs->ls, "constructor too long");
  1444. fs->freereg = base + 1; /* free registers with list values */
  1445. }
  1446. /*
  1447. ** return the final target of a jump (skipping jumps to jumps)
  1448. */
  1449. static int finaltarget (Instruction *code, int i) {
  1450. int count;
  1451. for (count = 0; count < 100; count++) { /* avoid infinite loops */
  1452. Instruction pc = code[i];
  1453. if (GET_OPCODE(pc) != OP_JMP)
  1454. break;
  1455. else
  1456. i += GETARG_sJ(pc) + 1;
  1457. }
  1458. return i;
  1459. }
  1460. /*
  1461. ** Do a final pass over the code of a function, doing small peephole
  1462. ** optimizations and adjustments.
  1463. */
  1464. void luaK_finish (FuncState *fs) {
  1465. int i;
  1466. Proto *p = fs->f;
  1467. for (i = 0; i < fs->pc; i++) {
  1468. Instruction *pc = &p->code[i];
  1469. lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc));
  1470. switch (GET_OPCODE(*pc)) {
  1471. case OP_RETURN0: case OP_RETURN1: {
  1472. if (!(fs->needclose || p->is_vararg))
  1473. break; /* no extra work */
  1474. /* else use OP_RETURN to do the extra work */
  1475. SET_OPCODE(*pc, OP_RETURN);
  1476. } /* FALLTHROUGH */
  1477. case OP_RETURN: case OP_TAILCALL: {
  1478. if (fs->needclose || p->is_vararg) {
  1479. SETARG_C(*pc, p->is_vararg ? p->numparams + 1 : 0);
  1480. SETARG_k(*pc, 1); /* signal that there is extra work */
  1481. }
  1482. break;
  1483. }
  1484. case OP_JMP: {
  1485. int target = finaltarget(p->code, i);
  1486. fixjump(fs, i, target);
  1487. break;
  1488. }
  1489. default: break;
  1490. }
  1491. }
  1492. }