lcode.c 48 KB

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