lcode.c 48 KB

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