lcode.c 52 KB

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