lcode.c 47 KB

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