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 <= i + OFFSET_sC && i + OFFSET_sC <= 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 int floatI (lua_Number f, lua_Integer *fi) {
  549. return (luaV_flttointeger(f, fi, 0) && fitsBx(*fi));
  550. }
  551. static void luaK_float (FuncState *fs, int reg, lua_Number f) {
  552. lua_Integer fi;
  553. if (floatI(f, &fi))
  554. luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
  555. else
  556. luaK_codek(fs, reg, luaK_numberK(fs, f));
  557. }
  558. /*
  559. ** Convert a constant in 'v' into an expression description 'e'
  560. */
  561. static void const2exp (TValue *v, expdesc *e) {
  562. switch (ttypetag(v)) {
  563. case LUA_TNUMINT:
  564. e->k = VKINT; e->u.ival = ivalue(v);
  565. break;
  566. case LUA_TNUMFLT:
  567. e->k = VKFLT; e->u.nval = fltvalue(v);
  568. break;
  569. case LUA_TBOOLEAN:
  570. e->k = bvalue(v) ? VTRUE : VFALSE;
  571. break;
  572. case LUA_TNIL:
  573. e->k = VNIL;
  574. break;
  575. case LUA_TSHRSTR: case LUA_TLNGSTR:
  576. e->k = VKSTR; e->u.strval = tsvalue(v);
  577. break;
  578. default: lua_assert(0);
  579. }
  580. }
  581. /*
  582. ** Fix an expression to return the number of results 'nresults'.
  583. ** Either 'e' is a multi-ret expression (function call or vararg)
  584. ** or 'nresults' is LUA_MULTRET (as any expression can satisfy that).
  585. */
  586. void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
  587. Instruction *pc = &getinstruction(fs, e);
  588. if (e->k == VCALL) /* expression is an open function call? */
  589. SETARG_C(*pc, nresults + 1);
  590. else if (e->k == VVARARG) {
  591. SETARG_C(*pc, nresults + 1);
  592. SETARG_A(*pc, fs->freereg);
  593. luaK_reserveregs(fs, 1);
  594. }
  595. else lua_assert(nresults == LUA_MULTRET);
  596. }
  597. /*
  598. ** Convert a VKSTR to a VK
  599. */
  600. static void str2K (FuncState *fs, expdesc *e) {
  601. lua_assert(e->k == VKSTR);
  602. e->u.info = stringK(fs, e->u.strval);
  603. e->k = VK;
  604. }
  605. /*
  606. ** Fix an expression to return one result.
  607. ** If expression is not a multi-ret expression (function call or
  608. ** vararg), it already returns one result, so nothing needs to be done.
  609. ** Function calls become VNONRELOC expressions (as its result comes
  610. ** fixed in the base register of the call), while vararg expressions
  611. ** become VRELOC (as OP_VARARG puts its results where it wants).
  612. ** (Calls are created returning one result, so that does not need
  613. ** to be fixed.)
  614. */
  615. void luaK_setoneret (FuncState *fs, expdesc *e) {
  616. if (e->k == VCALL) { /* expression is an open function call? */
  617. /* already returns 1 value */
  618. lua_assert(GETARG_C(getinstruction(fs, e)) == 2);
  619. e->k = VNONRELOC; /* result has fixed position */
  620. e->u.info = GETARG_A(getinstruction(fs, e));
  621. }
  622. else if (e->k == VVARARG) {
  623. SETARG_C(getinstruction(fs, e), 2);
  624. e->k = VRELOC; /* can relocate its simple result */
  625. }
  626. }
  627. /*
  628. ** Ensure that expression 'e' is not a variable (nor a constant).
  629. ** (Expression still may have jump lists.)
  630. */
  631. void luaK_dischargevars (FuncState *fs, expdesc *e) {
  632. switch (e->k) {
  633. case VCONST: {
  634. const2exp(const2val(fs, e), e);
  635. break;
  636. }
  637. case VLOCAL: { /* already in a register */
  638. e->u.info = e->u.var.sidx;
  639. e->k = VNONRELOC; /* becomes a non-relocatable value */
  640. break;
  641. }
  642. case VUPVAL: { /* move value to some (pending) register */
  643. e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
  644. e->k = VRELOC;
  645. break;
  646. }
  647. case VINDEXUP: {
  648. e->u.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.ind.t, e->u.ind.idx);
  649. e->k = VRELOC;
  650. break;
  651. }
  652. case VINDEXI: {
  653. freereg(fs, e->u.ind.t);
  654. e->u.info = luaK_codeABC(fs, OP_GETI, 0, e->u.ind.t, e->u.ind.idx);
  655. e->k = VRELOC;
  656. break;
  657. }
  658. case VINDEXSTR: {
  659. freereg(fs, e->u.ind.t);
  660. e->u.info = luaK_codeABC(fs, OP_GETFIELD, 0, e->u.ind.t, e->u.ind.idx);
  661. e->k = VRELOC;
  662. break;
  663. }
  664. case VINDEXED: {
  665. freeregs(fs, e->u.ind.t, e->u.ind.idx);
  666. e->u.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.ind.t, e->u.ind.idx);
  667. e->k = VRELOC;
  668. break;
  669. }
  670. case VVARARG: case VCALL: {
  671. luaK_setoneret(fs, e);
  672. break;
  673. }
  674. default: break; /* there is one value available (somewhere) */
  675. }
  676. }
  677. /*
  678. ** Ensures expression value is in register 'reg' (and therefore
  679. ** 'e' will become a non-relocatable expression).
  680. ** (Expression still may have jump lists.)
  681. */
  682. static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
  683. luaK_dischargevars(fs, e);
  684. switch (e->k) {
  685. case VNIL: {
  686. luaK_nil(fs, reg, 1);
  687. break;
  688. }
  689. case VFALSE: case VTRUE: {
  690. luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
  691. break;
  692. }
  693. case VKSTR: {
  694. str2K(fs, e);
  695. } /* FALLTHROUGH */
  696. case VK: {
  697. luaK_codek(fs, reg, e->u.info);
  698. break;
  699. }
  700. case VKFLT: {
  701. luaK_float(fs, reg, e->u.nval);
  702. break;
  703. }
  704. case VKINT: {
  705. luaK_int(fs, reg, e->u.ival);
  706. break;
  707. }
  708. case VRELOC: {
  709. Instruction *pc = &getinstruction(fs, e);
  710. SETARG_A(*pc, reg); /* instruction will put result in 'reg' */
  711. break;
  712. }
  713. case VNONRELOC: {
  714. if (reg != e->u.info)
  715. luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0);
  716. break;
  717. }
  718. default: {
  719. lua_assert(e->k == VJMP);
  720. return; /* nothing to do... */
  721. }
  722. }
  723. e->u.info = reg;
  724. e->k = VNONRELOC;
  725. }
  726. /*
  727. ** Ensures expression value is in any register.
  728. ** (Expression still may have jump lists.)
  729. */
  730. static void discharge2anyreg (FuncState *fs, expdesc *e) {
  731. if (e->k != VNONRELOC) { /* no fixed register yet? */
  732. luaK_reserveregs(fs, 1); /* get a register */
  733. discharge2reg(fs, e, fs->freereg-1); /* put value there */
  734. }
  735. }
  736. static int code_loadbool (FuncState *fs, int A, int b, int jump) {
  737. luaK_getlabel(fs); /* those instructions may be jump targets */
  738. return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
  739. }
  740. /*
  741. ** check whether list has any jump that do not produce a value
  742. ** or produce an inverted value
  743. */
  744. static int need_value (FuncState *fs, int list) {
  745. for (; list != NO_JUMP; list = getjump(fs, list)) {
  746. Instruction i = *getjumpcontrol(fs, list);
  747. if (GET_OPCODE(i) != OP_TESTSET) return 1;
  748. }
  749. return 0; /* not found */
  750. }
  751. /*
  752. ** Ensures final expression result (which includes results from its
  753. ** jump lists) is in register 'reg'.
  754. ** If expression has jumps, need to patch these jumps either to
  755. ** its final position or to "load" instructions (for those tests
  756. ** that do not produce values).
  757. */
  758. static void exp2reg (FuncState *fs, expdesc *e, int reg) {
  759. discharge2reg(fs, e, reg);
  760. if (e->k == VJMP) /* expression itself is a test? */
  761. luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */
  762. if (hasjumps(e)) {
  763. int final; /* position after whole expression */
  764. int p_f = NO_JUMP; /* position of an eventual LOAD false */
  765. int p_t = NO_JUMP; /* position of an eventual LOAD true */
  766. if (need_value(fs, e->t) || need_value(fs, e->f)) {
  767. int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
  768. p_f = code_loadbool(fs, reg, 0, 1); /* load false and skip next i. */
  769. p_t = code_loadbool(fs, reg, 1, 0); /* load true */
  770. /* jump around these booleans if 'e' is not a test */
  771. luaK_patchtohere(fs, fj);
  772. }
  773. final = luaK_getlabel(fs);
  774. patchlistaux(fs, e->f, final, reg, p_f);
  775. patchlistaux(fs, e->t, final, reg, p_t);
  776. }
  777. e->f = e->t = NO_JUMP;
  778. e->u.info = reg;
  779. e->k = VNONRELOC;
  780. }
  781. /*
  782. ** Ensures final expression result is in next available register.
  783. */
  784. void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
  785. luaK_dischargevars(fs, e);
  786. freeexp(fs, e);
  787. luaK_reserveregs(fs, 1);
  788. exp2reg(fs, e, fs->freereg - 1);
  789. }
  790. /*
  791. ** Ensures final expression result is in some (any) register
  792. ** and return that register.
  793. */
  794. int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
  795. luaK_dischargevars(fs, e);
  796. if (e->k == VNONRELOC) { /* expression already has a register? */
  797. if (!hasjumps(e)) /* no jumps? */
  798. return e->u.info; /* result is already in a register */
  799. if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */
  800. exp2reg(fs, e, e->u.info); /* put final result in it */
  801. return e->u.info;
  802. }
  803. }
  804. luaK_exp2nextreg(fs, e); /* otherwise, use next available register */
  805. return e->u.info;
  806. }
  807. /*
  808. ** Ensures final expression result is either in a register
  809. ** or in an upvalue.
  810. */
  811. void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
  812. if (e->k != VUPVAL || hasjumps(e))
  813. luaK_exp2anyreg(fs, e);
  814. }
  815. /*
  816. ** Ensures final expression result is either in a register
  817. ** or it is a constant.
  818. */
  819. void luaK_exp2val (FuncState *fs, expdesc *e) {
  820. if (hasjumps(e))
  821. luaK_exp2anyreg(fs, e);
  822. else
  823. luaK_dischargevars(fs, e);
  824. }
  825. /*
  826. ** Try to make 'e' a K expression with an index in the range of R/K
  827. ** indices. Return true iff succeeded.
  828. */
  829. static int luaK_exp2K (FuncState *fs, expdesc *e) {
  830. if (!hasjumps(e)) {
  831. int info;
  832. switch (e->k) { /* move constants to 'k' */
  833. case VTRUE: info = boolK(fs, 1); break;
  834. case VFALSE: info = boolK(fs, 0); break;
  835. case VNIL: info = nilK(fs); break;
  836. case VKINT: info = luaK_intK(fs, e->u.ival); break;
  837. case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
  838. case VKSTR: info = stringK(fs, e->u.strval); break;
  839. case VK: info = e->u.info; break;
  840. default: return 0; /* not a constant */
  841. }
  842. if (info <= MAXINDEXRK) { /* does constant fit in 'argC'? */
  843. e->k = VK; /* make expression a 'K' expression */
  844. e->u.info = info;
  845. return 1;
  846. }
  847. }
  848. /* else, expression doesn't fit; leave it unchanged */
  849. return 0;
  850. }
  851. /*
  852. ** Ensures final expression result is in a valid R/K index
  853. ** (that is, it is either in a register or in 'k' with an index
  854. ** in the range of R/K indices).
  855. ** Returns 1 iff expression is K.
  856. */
  857. int luaK_exp2RK (FuncState *fs, expdesc *e) {
  858. if (luaK_exp2K(fs, e))
  859. return 1;
  860. else { /* not a constant in the right range: put it in a register */
  861. luaK_exp2anyreg(fs, e);
  862. return 0;
  863. }
  864. }
  865. static void codeABRK (FuncState *fs, OpCode o, int a, int b,
  866. expdesc *ec) {
  867. int k = luaK_exp2RK(fs, ec);
  868. luaK_codeABCk(fs, o, a, b, ec->u.info, k);
  869. }
  870. /*
  871. ** Generate code to store result of expression 'ex' into variable 'var'.
  872. */
  873. void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
  874. switch (var->k) {
  875. case VLOCAL: {
  876. freeexp(fs, ex);
  877. exp2reg(fs, ex, var->u.var.sidx); /* compute 'ex' into proper place */
  878. return;
  879. }
  880. case VUPVAL: {
  881. int e = luaK_exp2anyreg(fs, ex);
  882. luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
  883. break;
  884. }
  885. case VINDEXUP: {
  886. codeABRK(fs, OP_SETTABUP, var->u.ind.t, var->u.ind.idx, ex);
  887. break;
  888. }
  889. case VINDEXI: {
  890. codeABRK(fs, OP_SETI, var->u.ind.t, var->u.ind.idx, ex);
  891. break;
  892. }
  893. case VINDEXSTR: {
  894. codeABRK(fs, OP_SETFIELD, var->u.ind.t, var->u.ind.idx, ex);
  895. break;
  896. }
  897. case VINDEXED: {
  898. codeABRK(fs, OP_SETTABLE, var->u.ind.t, var->u.ind.idx, ex);
  899. break;
  900. }
  901. default: lua_assert(0); /* invalid var kind to store */
  902. }
  903. freeexp(fs, ex);
  904. }
  905. /*
  906. ** Emit SELF instruction (convert expression 'e' into 'e:key(e,').
  907. */
  908. void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
  909. int ereg;
  910. luaK_exp2anyreg(fs, e);
  911. ereg = e->u.info; /* register where 'e' was placed */
  912. freeexp(fs, e);
  913. e->u.info = fs->freereg; /* base register for op_self */
  914. e->k = VNONRELOC; /* self expression has a fixed register */
  915. luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
  916. codeABRK(fs, OP_SELF, e->u.info, ereg, key);
  917. freeexp(fs, key);
  918. }
  919. /*
  920. ** Negate condition 'e' (where 'e' is a comparison).
  921. */
  922. static void negatecondition (FuncState *fs, expdesc *e) {
  923. Instruction *pc = getjumpcontrol(fs, e->u.info);
  924. lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
  925. GET_OPCODE(*pc) != OP_TEST);
  926. SETARG_k(*pc, (GETARG_k(*pc) ^ 1));
  927. }
  928. /*
  929. ** Emit instruction to jump if 'e' is 'cond' (that is, if 'cond'
  930. ** is true, code will jump if 'e' is true.) Return jump position.
  931. ** Optimize when 'e' is 'not' something, inverting the condition
  932. ** and removing the 'not'.
  933. */
  934. static int jumponcond (FuncState *fs, expdesc *e, int cond) {
  935. if (e->k == VRELOC) {
  936. Instruction ie = getinstruction(fs, e);
  937. if (GET_OPCODE(ie) == OP_NOT) {
  938. removelastinstruction(fs); /* remove previous OP_NOT */
  939. return condjump(fs, OP_TEST, GETARG_B(ie), 0, 0, !cond);
  940. }
  941. /* else go through */
  942. }
  943. discharge2anyreg(fs, e);
  944. freeexp(fs, e);
  945. return condjump(fs, OP_TESTSET, NO_REG, e->u.info, 0, cond);
  946. }
  947. /*
  948. ** Emit code to go through if 'e' is true, jump otherwise.
  949. */
  950. void luaK_goiftrue (FuncState *fs, expdesc *e) {
  951. int pc; /* pc of new jump */
  952. luaK_dischargevars(fs, e);
  953. switch (e->k) {
  954. case VJMP: { /* condition? */
  955. negatecondition(fs, e); /* jump when it is false */
  956. pc = e->u.info; /* save jump position */
  957. break;
  958. }
  959. case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
  960. pc = NO_JUMP; /* always true; do nothing */
  961. break;
  962. }
  963. default: {
  964. pc = jumponcond(fs, e, 0); /* jump when false */
  965. break;
  966. }
  967. }
  968. luaK_concat(fs, &e->f, pc); /* insert new jump in false list */
  969. luaK_patchtohere(fs, e->t); /* true list jumps to here (to go through) */
  970. e->t = NO_JUMP;
  971. }
  972. /*
  973. ** Emit code to go through if 'e' is false, jump otherwise.
  974. */
  975. void luaK_goiffalse (FuncState *fs, expdesc *e) {
  976. int pc; /* pc of new jump */
  977. luaK_dischargevars(fs, e);
  978. switch (e->k) {
  979. case VJMP: {
  980. pc = e->u.info; /* already jump if true */
  981. break;
  982. }
  983. case VNIL: case VFALSE: {
  984. pc = NO_JUMP; /* always false; do nothing */
  985. break;
  986. }
  987. default: {
  988. pc = jumponcond(fs, e, 1); /* jump if true */
  989. break;
  990. }
  991. }
  992. luaK_concat(fs, &e->t, pc); /* insert new jump in 't' list */
  993. luaK_patchtohere(fs, e->f); /* false list jumps to here (to go through) */
  994. e->f = NO_JUMP;
  995. }
  996. /*
  997. ** Code 'not e', doing constant folding.
  998. */
  999. static void codenot (FuncState *fs, expdesc *e) {
  1000. switch (e->k) {
  1001. case VNIL: case VFALSE: {
  1002. e->k = VTRUE; /* true == not nil == not false */
  1003. break;
  1004. }
  1005. case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
  1006. e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
  1007. break;
  1008. }
  1009. case VJMP: {
  1010. negatecondition(fs, e);
  1011. break;
  1012. }
  1013. case VRELOC:
  1014. case VNONRELOC: {
  1015. discharge2anyreg(fs, e);
  1016. freeexp(fs, e);
  1017. e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0);
  1018. e->k = VRELOC;
  1019. break;
  1020. }
  1021. default: lua_assert(0); /* cannot happen */
  1022. }
  1023. /* interchange true and false lists */
  1024. { int temp = e->f; e->f = e->t; e->t = temp; }
  1025. removevalues(fs, e->f); /* values are useless when negated */
  1026. removevalues(fs, e->t);
  1027. }
  1028. /*
  1029. ** Check whether expression 'e' is a small literal string
  1030. */
  1031. static int isKstr (FuncState *fs, expdesc *e) {
  1032. return (e->k == VK && !hasjumps(e) && e->u.info <= MAXARG_B &&
  1033. ttisshrstring(&fs->f->k[e->u.info]));
  1034. }
  1035. /*
  1036. ** Check whether expression 'e' is a literal integer.
  1037. */
  1038. int luaK_isKint (expdesc *e) {
  1039. return (e->k == VKINT && !hasjumps(e));
  1040. }
  1041. /*
  1042. ** Check whether expression 'e' is a literal integer in
  1043. ** proper range to fit in register C
  1044. */
  1045. static int isCint (expdesc *e) {
  1046. return luaK_isKint(e) && (l_castS2U(e->u.ival) <= l_castS2U(MAXARG_C));
  1047. }
  1048. /*
  1049. ** Check whether expression 'e' is a literal integer in
  1050. ** proper range to fit in register sC
  1051. */
  1052. static int isSCint (expdesc *e) {
  1053. return luaK_isKint(e) && fitsC(e->u.ival);
  1054. }
  1055. /*
  1056. ** Check whether expression 'e' is a literal integer or float in
  1057. ** proper range to fit in a register (sB or sC).
  1058. */
  1059. static int isSCnumber (expdesc *e, lua_Integer *i, int *isfloat) {
  1060. if (e->k == VKINT)
  1061. *i = e->u.ival;
  1062. else if (!(e->k == VKFLT && floatI(e->u.nval, i)))
  1063. return 0; /* not a number */
  1064. else
  1065. *isfloat = 1;
  1066. if (!hasjumps(e) && fitsC(*i)) {
  1067. *i += OFFSET_sC;
  1068. return 1;
  1069. }
  1070. else
  1071. return 0;
  1072. }
  1073. /*
  1074. ** Create expression 't[k]'. 't' must have its final result already in a
  1075. ** register or upvalue. Upvalues can only be indexed by literal strings.
  1076. ** Keys can be literal strings in the constant table or arbitrary
  1077. ** values in registers.
  1078. */
  1079. void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
  1080. if (k->k == VKSTR)
  1081. str2K(fs, k);
  1082. lua_assert(!hasjumps(t) &&
  1083. (t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL));
  1084. if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */
  1085. luaK_exp2anyreg(fs, t); /* put it in a register */
  1086. if (t->k == VUPVAL) {
  1087. t->u.ind.t = t->u.info; /* upvalue index */
  1088. t->u.ind.idx = k->u.info; /* literal string */
  1089. t->k = VINDEXUP;
  1090. }
  1091. else {
  1092. /* register index of the table */
  1093. t->u.ind.t = (t->k == VLOCAL) ? t->u.var.sidx: t->u.info;
  1094. if (isKstr(fs, k)) {
  1095. t->u.ind.idx = k->u.info; /* literal string */
  1096. t->k = VINDEXSTR;
  1097. }
  1098. else if (isCint(k)) {
  1099. t->u.ind.idx = cast_int(k->u.ival); /* int. constant in proper range */
  1100. t->k = VINDEXI;
  1101. }
  1102. else {
  1103. t->u.ind.idx = luaK_exp2anyreg(fs, k); /* register */
  1104. t->k = VINDEXED;
  1105. }
  1106. }
  1107. }
  1108. /*
  1109. ** Return false if folding can raise an error.
  1110. ** Bitwise operations need operands convertible to integers; division
  1111. ** operations cannot have 0 as divisor.
  1112. */
  1113. static int validop (int op, TValue *v1, TValue *v2) {
  1114. switch (op) {
  1115. case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
  1116. case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
  1117. lua_Integer i;
  1118. return (tointegerns(v1, &i) && tointegerns(v2, &i));
  1119. }
  1120. case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
  1121. return (nvalue(v2) != 0);
  1122. default: return 1; /* everything else is valid */
  1123. }
  1124. }
  1125. /*
  1126. ** Try to "constant-fold" an operation; return 1 iff successful.
  1127. ** (In this case, 'e1' has the final result.)
  1128. */
  1129. static int constfolding (FuncState *fs, int op, expdesc *e1,
  1130. const expdesc *e2) {
  1131. TValue v1, v2, res;
  1132. if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
  1133. return 0; /* non-numeric operands or not safe to fold */
  1134. luaO_rawarith(fs->ls->L, op, &v1, &v2, &res); /* does operation */
  1135. if (ttisinteger(&res)) {
  1136. e1->k = VKINT;
  1137. e1->u.ival = ivalue(&res);
  1138. }
  1139. else { /* folds neither NaN nor 0.0 (to avoid problems with -0.0) */
  1140. lua_Number n = fltvalue(&res);
  1141. if (luai_numisnan(n) || n == 0)
  1142. return 0;
  1143. e1->k = VKFLT;
  1144. e1->u.nval = n;
  1145. }
  1146. return 1;
  1147. }
  1148. /*
  1149. ** Emit code for unary expressions that "produce values"
  1150. ** (everything but 'not').
  1151. ** Expression to produce final result will be encoded in 'e'.
  1152. */
  1153. static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
  1154. int r = luaK_exp2anyreg(fs, e); /* opcodes operate only on registers */
  1155. freeexp(fs, e);
  1156. e->u.info = luaK_codeABC(fs, op, 0, r, 0); /* generate opcode */
  1157. e->k = VRELOC; /* all those operations are relocatable */
  1158. luaK_fixline(fs, line);
  1159. }
  1160. /*
  1161. ** Emit code for binary expressions that "produce values"
  1162. ** (everything but logical operators 'and'/'or' and comparison
  1163. ** operators).
  1164. ** Expression to produce final result will be encoded in 'e1'.
  1165. ** Because 'luaK_exp2anyreg' can free registers, its calls must be
  1166. ** in "stack order" (that is, first on 'e2', which may have more
  1167. ** recent registers to be released).
  1168. */
  1169. static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
  1170. OpCode op, int v2, int k, int line) {
  1171. int v1 = luaK_exp2anyreg(fs, e1);
  1172. int pc = luaK_codeABCk(fs, op, 0, v1, v2, k);
  1173. freeexps(fs, e1, e2);
  1174. e1->u.info = pc;
  1175. e1->k = VRELOC; /* all those operations are relocatable */
  1176. luaK_fixline(fs, line);
  1177. }
  1178. /*
  1179. ** Emit code for binary expressions that "produce values" over
  1180. ** two registers.
  1181. */
  1182. static void codebinexpval (FuncState *fs, OpCode op,
  1183. expdesc *e1, expdesc *e2, int line) {
  1184. int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */
  1185. finishbinexpval(fs, e1, e2, op, v2, 0, line);
  1186. }
  1187. /*
  1188. ** Code binary operators ('+', '-', ...) with immediate operands.
  1189. */
  1190. static void codebini (FuncState *fs, OpCode op,
  1191. expdesc *e1, expdesc *e2, int k, int line) {
  1192. int v2 = cast_int(e2->u.ival) + OFFSET_sC; /* immediate operand */
  1193. finishbinexpval(fs, e1, e2, op, v2, k, line);
  1194. }
  1195. static void swapexps (expdesc *e1, expdesc *e2) {
  1196. expdesc temp = *e1; *e1 = *e2; *e2 = temp; /* swap 'e1' and 'e2' */
  1197. }
  1198. /*
  1199. ** Code arithmetic operators ('+', '-', ...). If second operand is a
  1200. ** constant in the proper range, use variant opcodes with immediate
  1201. ** operands or K operands.
  1202. */
  1203. static void codearith (FuncState *fs, OpCode op,
  1204. expdesc *e1, expdesc *e2, int flip, int line) {
  1205. if (isSCint(e2)) /* immediate operand? */
  1206. codebini(fs, cast(OpCode, op - OP_ADD + OP_ADDI), e1, e2, flip, line);
  1207. else if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */
  1208. int v2 = e2->u.info; /* K index */
  1209. op = cast(OpCode, op - OP_ADD + OP_ADDK);
  1210. finishbinexpval(fs, e1, e2, op, v2, flip, line);
  1211. }
  1212. else { /* 'e2' is neither an immediate nor a K operand */
  1213. if (flip)
  1214. swapexps(e1, e2); /* back to original order */
  1215. codebinexpval(fs, op, e1, e2, line); /* use standard operators */
  1216. }
  1217. }
  1218. /*
  1219. ** Code commutative operators ('+', '*'). If first operand is a
  1220. ** numeric constant, change order of operands to try to use an
  1221. ** immediate or K operator.
  1222. */
  1223. static void codecommutative (FuncState *fs, OpCode op,
  1224. expdesc *e1, expdesc *e2, int line) {
  1225. int flip = 0;
  1226. if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
  1227. swapexps(e1, e2); /* change order */
  1228. flip = 1;
  1229. }
  1230. codearith(fs, op, e1, e2, flip, line);
  1231. }
  1232. /*
  1233. ** Code bitwise operations; they are all associative, so the function
  1234. ** tries to put an integer constant as the 2nd operand (a K operand).
  1235. */
  1236. static void codebitwise (FuncState *fs, BinOpr opr,
  1237. expdesc *e1, expdesc *e2, int line) {
  1238. int inv = 0;
  1239. int v2;
  1240. OpCode op;
  1241. if (e1->k == VKINT && luaK_exp2RK(fs, e1)) {
  1242. swapexps(e1, e2); /* 'e2' will be the constant operand */
  1243. inv = 1;
  1244. }
  1245. else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */
  1246. op = cast(OpCode, opr - OPR_BAND + OP_BAND);
  1247. codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */
  1248. return;
  1249. }
  1250. v2 = e2->u.info; /* index in K array */
  1251. op = cast(OpCode, opr - OPR_BAND + OP_BANDK);
  1252. lua_assert(ttisinteger(&fs->f->k[v2]));
  1253. finishbinexpval(fs, e1, e2, op, v2, inv, line);
  1254. }
  1255. /*
  1256. ** Code shift operators. If second operand is constant, use immediate
  1257. ** operand (negating it if shift is in the other direction).
  1258. */
  1259. static void codeshift (FuncState *fs, OpCode op,
  1260. expdesc *e1, expdesc *e2, int line) {
  1261. if (isSCint(e2)) {
  1262. int changedir = 0;
  1263. if (op == OP_SHL) {
  1264. changedir = 1;
  1265. e2->u.ival = -(e2->u.ival);
  1266. }
  1267. codebini(fs, OP_SHRI, e1, e2, changedir, line);
  1268. }
  1269. else
  1270. codebinexpval(fs, op, e1, e2, line);
  1271. }
  1272. /*
  1273. ** Emit code for order comparisons. When using an immediate operand,
  1274. ** 'isfloat' tells whether the original value was a float.
  1275. */
  1276. static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
  1277. int r1, r2;
  1278. lua_Integer im;
  1279. int isfloat = 0;
  1280. if (isSCnumber(e2, &im, &isfloat)) {
  1281. /* use immediate operand */
  1282. r1 = luaK_exp2anyreg(fs, e1);
  1283. r2 = cast_int(im);
  1284. op = cast(OpCode, (op - OP_LT) + OP_LTI);
  1285. }
  1286. else if (isSCnumber(e1, &im, &isfloat)) {
  1287. /* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
  1288. r1 = luaK_exp2anyreg(fs, e2);
  1289. r2 = cast_int(im);
  1290. op = (op == OP_LT) ? OP_GTI : OP_GEI;
  1291. }
  1292. else { /* regular case, compare two registers */
  1293. r1 = luaK_exp2anyreg(fs, e1);
  1294. r2 = luaK_exp2anyreg(fs, e2);
  1295. }
  1296. freeexps(fs, e1, e2);
  1297. e1->u.info = condjump(fs, op, r1, r2, isfloat, 1);
  1298. e1->k = VJMP;
  1299. }
  1300. /*
  1301. ** Emit code for equality comparisons ('==', '~=').
  1302. ** 'e1' was already put as RK by 'luaK_infix'.
  1303. */
  1304. static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
  1305. int r1, r2;
  1306. lua_Integer im;
  1307. int isfloat = 0; /* not needed here, but kept for symmetry */
  1308. OpCode op;
  1309. if (e1->k != VNONRELOC) {
  1310. lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
  1311. swapexps(e1, e2);
  1312. }
  1313. r1 = luaK_exp2anyreg(fs, e1); /* 1nd expression must be in register */
  1314. if (isSCnumber(e2, &im, &isfloat)) {
  1315. op = OP_EQI;
  1316. r2 = cast_int(im); /* immediate operand */
  1317. }
  1318. else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */
  1319. op = OP_EQK;
  1320. r2 = e2->u.info; /* constant index */
  1321. }
  1322. else {
  1323. op = OP_EQ; /* will compare two registers */
  1324. r2 = luaK_exp2anyreg(fs, e2);
  1325. }
  1326. freeexps(fs, e1, e2);
  1327. e1->u.info = condjump(fs, op, r1, r2, isfloat, (opr == OPR_EQ));
  1328. e1->k = VJMP;
  1329. }
  1330. /*
  1331. ** Apply prefix operation 'op' to expression 'e'.
  1332. */
  1333. void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
  1334. static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
  1335. luaK_dischargevars(fs, e);
  1336. switch (op) {
  1337. case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
  1338. if (constfolding(fs, op + LUA_OPUNM, e, &ef))
  1339. break;
  1340. /* else */ /* FALLTHROUGH */
  1341. case OPR_LEN:
  1342. codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line);
  1343. break;
  1344. case OPR_NOT: codenot(fs, e); break;
  1345. default: lua_assert(0);
  1346. }
  1347. }
  1348. /*
  1349. ** Process 1st operand 'v' of binary operation 'op' before reading
  1350. ** 2nd operand.
  1351. */
  1352. void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
  1353. luaK_dischargevars(fs, v);
  1354. switch (op) {
  1355. case OPR_AND: {
  1356. luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
  1357. break;
  1358. }
  1359. case OPR_OR: {
  1360. luaK_goiffalse(fs, v); /* go ahead only if 'v' is false */
  1361. break;
  1362. }
  1363. case OPR_CONCAT: {
  1364. luaK_exp2nextreg(fs, v); /* operand must be on the stack */
  1365. break;
  1366. }
  1367. case OPR_ADD: case OPR_SUB:
  1368. case OPR_MUL: case OPR_DIV: case OPR_IDIV:
  1369. case OPR_MOD: case OPR_POW:
  1370. case OPR_BAND: case OPR_BOR: case OPR_BXOR:
  1371. case OPR_SHL: case OPR_SHR: {
  1372. if (!tonumeral(v, NULL))
  1373. luaK_exp2anyreg(fs, v);
  1374. /* else keep numeral, which may be folded with 2nd operand */
  1375. break;
  1376. }
  1377. case OPR_EQ: case OPR_NE: {
  1378. if (!tonumeral(v, NULL))
  1379. luaK_exp2RK(fs, v);
  1380. /* else keep numeral, which may be an immediate operand */
  1381. break;
  1382. }
  1383. case OPR_LT: case OPR_LE:
  1384. case OPR_GT: case OPR_GE: {
  1385. lua_Integer dummy;
  1386. int dummy2;
  1387. if (!isSCnumber(v, &dummy, &dummy2))
  1388. luaK_exp2anyreg(fs, v);
  1389. /* else keep numeral, which may be an immediate operand */
  1390. break;
  1391. }
  1392. default: lua_assert(0);
  1393. }
  1394. }
  1395. /*
  1396. ** Create code for '(e1 .. e2)'.
  1397. ** For '(e1 .. e2.1 .. e2.2)' (which is '(e1 .. (e2.1 .. e2.2))',
  1398. ** because concatenation is right associative), merge both CONCATs.
  1399. */
  1400. static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
  1401. Instruction *ie2 = previousinstruction(fs);
  1402. if (GET_OPCODE(*ie2) == OP_CONCAT) { /* is 'e2' a concatenation? */
  1403. int n = GETARG_B(*ie2); /* # of elements concatenated in 'e2' */
  1404. lua_assert(e1->u.info + 1 == GETARG_A(*ie2));
  1405. freeexp(fs, e2);
  1406. SETARG_A(*ie2, e1->u.info); /* correct first element ('e1') */
  1407. SETARG_B(*ie2, n + 1); /* will concatenate one more element */
  1408. }
  1409. else { /* 'e2' is not a concatenation */
  1410. luaK_codeABC(fs, OP_CONCAT, e1->u.info, 2, 0); /* new concat opcode */
  1411. freeexp(fs, e2);
  1412. luaK_fixline(fs, line);
  1413. }
  1414. }
  1415. /*
  1416. ** Finalize code for binary operation, after reading 2nd operand.
  1417. */
  1418. void luaK_posfix (FuncState *fs, BinOpr opr,
  1419. expdesc *e1, expdesc *e2, int line) {
  1420. luaK_dischargevars(fs, e2);
  1421. switch (opr) {
  1422. case OPR_AND: {
  1423. lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */
  1424. luaK_concat(fs, &e2->f, e1->f);
  1425. *e1 = *e2;
  1426. break;
  1427. }
  1428. case OPR_OR: {
  1429. lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */
  1430. luaK_concat(fs, &e2->t, e1->t);
  1431. *e1 = *e2;
  1432. break;
  1433. }
  1434. case OPR_CONCAT: { /* e1 .. e2 */
  1435. luaK_exp2nextreg(fs, e2);
  1436. codeconcat(fs, e1, e2, line);
  1437. break;
  1438. }
  1439. case OPR_ADD: case OPR_MUL: {
  1440. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1441. codecommutative(fs, cast(OpCode, opr + OP_ADD), e1, e2, line);
  1442. break;
  1443. }
  1444. case OPR_SUB: case OPR_DIV:
  1445. case OPR_IDIV: case OPR_MOD: case OPR_POW: {
  1446. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1447. codearith(fs, cast(OpCode, opr + OP_ADD), e1, e2, 0, line);
  1448. break;
  1449. }
  1450. case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
  1451. if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
  1452. codebitwise(fs, opr, e1, e2, line);
  1453. break;
  1454. }
  1455. case OPR_SHL: {
  1456. if (!constfolding(fs, LUA_OPSHL, e1, e2)) {
  1457. if (isSCint(e1)) {
  1458. swapexps(e1, e2);
  1459. codebini(fs, OP_SHLI, e1, e2, 1, line);
  1460. }
  1461. else
  1462. codeshift(fs, OP_SHL, e1, e2, line);
  1463. }
  1464. break;
  1465. }
  1466. case OPR_SHR: {
  1467. if (!constfolding(fs, LUA_OPSHR, e1, e2))
  1468. codeshift(fs, OP_SHR, e1, e2, line);
  1469. break;
  1470. }
  1471. case OPR_EQ: case OPR_NE: {
  1472. codeeq(fs, opr, e1, e2);
  1473. break;
  1474. }
  1475. case OPR_LT: case OPR_LE: {
  1476. OpCode op = cast(OpCode, (opr - OPR_EQ) + OP_EQ);
  1477. codeorder(fs, op, e1, e2);
  1478. break;
  1479. }
  1480. case OPR_GT: case OPR_GE: {
  1481. /* '(a > b)' <=> '(b < a)'; '(a >= b)' <=> '(b <= a)' */
  1482. OpCode op = cast(OpCode, (opr - OPR_NE) + OP_EQ);
  1483. swapexps(e1, e2);
  1484. codeorder(fs, op, e1, e2);
  1485. break;
  1486. }
  1487. default: lua_assert(0);
  1488. }
  1489. }
  1490. /*
  1491. ** Change line information associated with current position, by removing
  1492. ** previous info and adding it again with new line.
  1493. */
  1494. void luaK_fixline (FuncState *fs, int line) {
  1495. removelastlineinfo(fs);
  1496. savelineinfo(fs, fs->f, line);
  1497. }
  1498. void luaK_settablesize (FuncState *fs, int pc, int ra, int rc, int rb) {
  1499. Instruction *inst = &fs->f->code[pc];
  1500. int extra = 0;
  1501. int k = 0;
  1502. if (rb != 0)
  1503. rb = luaO_ceillog2(rb) + 1; /* hash size */
  1504. if (rc > MAXARG_C) { /* does it need the extra argument? */
  1505. extra = rc / (MAXARG_C + 1);
  1506. rc %= (MAXARG_C + 1);
  1507. k = 1;
  1508. }
  1509. *inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k);
  1510. *(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);
  1511. }
  1512. /*
  1513. ** Emit a SETLIST instruction.
  1514. ** 'base' is register that keeps table;
  1515. ** 'nelems' is #table plus those to be stored now;
  1516. ** 'tostore' is number of values (in registers 'base + 1',...) to add to
  1517. ** table (or LUA_MULTRET to add up to stack top).
  1518. */
  1519. void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
  1520. lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);
  1521. if (tostore == LUA_MULTRET)
  1522. tostore = 0;
  1523. if (nelems <= MAXARG_C)
  1524. luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems);
  1525. else {
  1526. int extra = nelems / (MAXARG_C + 1);
  1527. nelems %= (MAXARG_C + 1);
  1528. luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1);
  1529. codeextraarg(fs, extra);
  1530. }
  1531. fs->freereg = base + 1; /* free registers with list values */
  1532. }
  1533. /*
  1534. ** return the final target of a jump (skipping jumps to jumps)
  1535. */
  1536. static int finaltarget (Instruction *code, int i) {
  1537. int count;
  1538. for (count = 0; count < 100; count++) { /* avoid infinite loops */
  1539. Instruction pc = code[i];
  1540. if (GET_OPCODE(pc) != OP_JMP)
  1541. break;
  1542. else
  1543. i += GETARG_sJ(pc) + 1;
  1544. }
  1545. return i;
  1546. }
  1547. /*
  1548. ** Do a final pass over the code of a function, doing small peephole
  1549. ** optimizations and adjustments.
  1550. */
  1551. void luaK_finish (FuncState *fs) {
  1552. int i;
  1553. Proto *p = fs->f;
  1554. for (i = 0; i < fs->pc; i++) {
  1555. Instruction *pc = &p->code[i];
  1556. lua_assert(i == 0 || isOT(*(pc - 1)) == isIT(*pc));
  1557. switch (GET_OPCODE(*pc)) {
  1558. case OP_RETURN0: case OP_RETURN1: {
  1559. if (!(fs->needclose || p->is_vararg))
  1560. break; /* no extra work */
  1561. /* else use OP_RETURN to do the extra work */
  1562. SET_OPCODE(*pc, OP_RETURN);
  1563. } /* FALLTHROUGH */
  1564. case OP_RETURN: case OP_TAILCALL: {
  1565. if (fs->needclose)
  1566. SETARG_k(*pc, 1); /* signal that it needs to close */
  1567. if (p->is_vararg)
  1568. SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */
  1569. break;
  1570. }
  1571. case OP_JMP: {
  1572. int target = finaltarget(p->code, i);
  1573. fixjump(fs, i, target);
  1574. break;
  1575. }
  1576. default: break;
  1577. }
  1578. }
  1579. }