lcode.c 49 KB

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