lcode.c 43 KB

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