lcode.c 56 KB

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