lcode.c 45 KB

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