lcode.c 46 KB

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