lj_record.c 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  1. /*
  2. ** Trace recorder (bytecode -> SSA IR).
  3. ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
  4. */
  5. #define lj_record_c
  6. #define LUA_CORE
  7. #include "lj_obj.h"
  8. #if LJ_HASJIT
  9. #include "lj_err.h"
  10. #include "lj_str.h"
  11. #include "lj_tab.h"
  12. #include "lj_meta.h"
  13. #include "lj_frame.h"
  14. #if LJ_HASFFI
  15. #include "lj_ctype.h"
  16. #endif
  17. #include "lj_bc.h"
  18. #include "lj_ff.h"
  19. #if LJ_HASPROFILE
  20. #include "lj_debug.h"
  21. #endif
  22. #include "lj_ir.h"
  23. #include "lj_jit.h"
  24. #include "lj_ircall.h"
  25. #include "lj_iropt.h"
  26. #include "lj_trace.h"
  27. #include "lj_record.h"
  28. #include "lj_ffrecord.h"
  29. #include "lj_snap.h"
  30. #include "lj_dispatch.h"
  31. #include "lj_vm.h"
  32. #include "lj_prng.h"
  33. /* Some local macros to save typing. Undef'd at the end. */
  34. #define IR(ref) (&J->cur.ir[(ref)])
  35. /* Pass IR on to next optimization in chain (FOLD). */
  36. #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
  37. /* Emit raw IR without passing through optimizations. */
  38. #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
  39. /* -- Sanity checks ------------------------------------------------------- */
  40. #ifdef LUA_USE_ASSERT
  41. /* Sanity check the whole IR -- sloooow. */
  42. static void rec_check_ir(jit_State *J)
  43. {
  44. IRRef i, nins = J->cur.nins, nk = J->cur.nk;
  45. lj_assertJ(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536,
  46. "inconsistent IR layout");
  47. for (i = nk; i < nins; i++) {
  48. IRIns *ir = IR(i);
  49. uint32_t mode = lj_ir_mode[ir->o];
  50. IRRef op1 = ir->op1;
  51. IRRef op2 = ir->op2;
  52. const char *err = NULL;
  53. switch (irm_op1(mode)) {
  54. case IRMnone:
  55. if (op1 != 0) err = "IRMnone op1 used";
  56. break;
  57. case IRMref:
  58. if (op1 < nk || (i >= REF_BIAS ? op1 >= i : op1 <= i))
  59. err = "IRMref op1 out of range";
  60. break;
  61. case IRMlit: break;
  62. case IRMcst:
  63. if (i >= REF_BIAS) { err = "constant in IR range"; break; }
  64. if (irt_is64(ir->t) && ir->o != IR_KNULL)
  65. i++;
  66. continue;
  67. }
  68. switch (irm_op2(mode)) {
  69. case IRMnone:
  70. if (op2) err = "IRMnone op2 used";
  71. break;
  72. case IRMref:
  73. if (op2 < nk || (i >= REF_BIAS ? op2 >= i : op2 <= i))
  74. err = "IRMref op2 out of range";
  75. break;
  76. case IRMlit: break;
  77. case IRMcst: err = "IRMcst op2"; break;
  78. }
  79. if (!err && ir->prev) {
  80. if (ir->prev < nk || (i >= REF_BIAS ? ir->prev >= i : ir->prev <= i))
  81. err = "chain out of range";
  82. else if (ir->o != IR_NOP && IR(ir->prev)->o != ir->o)
  83. err = "chain to different op";
  84. }
  85. lj_assertJ(!err, "bad IR %04d op %d(%04d,%04d): %s",
  86. i-REF_BIAS,
  87. ir->o,
  88. irm_op1(mode) == IRMref ? op1-REF_BIAS : op1,
  89. irm_op2(mode) == IRMref ? op2-REF_BIAS : op2,
  90. err);
  91. }
  92. }
  93. /* Compare stack slots and frames of the recorder and the VM. */
  94. static void rec_check_slots(jit_State *J)
  95. {
  96. BCReg s, nslots = J->baseslot + J->maxslot;
  97. int32_t depth = 0;
  98. cTValue *base = J->L->base - J->baseslot;
  99. lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot");
  100. lj_assertJ(J->baseslot == 1+LJ_FR2 || (J->slot[J->baseslot-1] & TREF_FRAME),
  101. "baseslot does not point to frame");
  102. lj_assertJ(nslots <= LJ_MAX_JSLOTS, "slot overflow");
  103. for (s = 0; s < nslots; s++) {
  104. TRef tr = J->slot[s];
  105. if (tr) {
  106. cTValue *tv = &base[s];
  107. IRRef ref = tref_ref(tr);
  108. IRIns *ir = NULL; /* Silence compiler. */
  109. lj_assertJ(tv < J->L->top, "slot %d above top of Lua stack", s);
  110. if (!LJ_FR2 || ref || !(tr & (TREF_FRAME | TREF_CONT))) {
  111. lj_assertJ(ref >= J->cur.nk && ref < J->cur.nins,
  112. "slot %d ref %04d out of range", s, ref - REF_BIAS);
  113. ir = IR(ref);
  114. lj_assertJ(irt_t(ir->t) == tref_t(tr), "slot %d IR type mismatch", s);
  115. }
  116. if (s == 0) {
  117. lj_assertJ(tref_isfunc(tr), "frame slot 0 is not a function");
  118. #if LJ_FR2
  119. } else if (s == 1) {
  120. lj_assertJ((tr & ~TREF_FRAME) == 0, "bad frame slot 1");
  121. #endif
  122. } else if ((tr & TREF_FRAME)) {
  123. GCfunc *fn = gco2func(frame_gc(tv));
  124. BCReg delta = (BCReg)(tv - frame_prev(tv));
  125. #if LJ_FR2
  126. lj_assertJ(!ref || ir_knum(ir)->u64 == tv->u64,
  127. "frame slot %d PC mismatch", s);
  128. tr = J->slot[s-1];
  129. ir = IR(tref_ref(tr));
  130. #endif
  131. lj_assertJ(tref_isfunc(tr),
  132. "frame slot %d is not a function", s-LJ_FR2);
  133. lj_assertJ(!tref_isk(tr) || fn == ir_kfunc(ir),
  134. "frame slot %d function mismatch", s-LJ_FR2);
  135. lj_assertJ(s > delta + LJ_FR2 ? (J->slot[s-delta] & TREF_FRAME)
  136. : (s == delta + LJ_FR2),
  137. "frame slot %d broken chain", s-LJ_FR2);
  138. depth++;
  139. } else if ((tr & TREF_CONT)) {
  140. #if LJ_FR2
  141. lj_assertJ(!ref || ir_knum(ir)->u64 == tv->u64,
  142. "cont slot %d continuation mismatch", s);
  143. #else
  144. lj_assertJ(ir_kptr(ir) == gcrefp(tv->gcr, void),
  145. "cont slot %d continuation mismatch", s);
  146. #endif
  147. lj_assertJ((J->slot[s+1+LJ_FR2] & TREF_FRAME),
  148. "cont slot %d not followed by frame", s);
  149. depth++;
  150. } else if ((tr & TREF_KEYINDEX)) {
  151. lj_assertJ(tref_isint(tr), "keyindex slot %d bad type %d",
  152. s, tref_type(tr));
  153. } else {
  154. /* Number repr. may differ, but other types must be the same. */
  155. lj_assertJ(tvisnumber(tv) ? tref_isnumber(tr) :
  156. itype2irt(tv) == tref_type(tr),
  157. "slot %d type mismatch: stack type %d vs IR type %d",
  158. s, itypemap(tv), tref_type(tr));
  159. if (tref_isk(tr)) { /* Compare constants. */
  160. TValue tvk;
  161. lj_ir_kvalue(J->L, &tvk, ir);
  162. lj_assertJ((tvisnum(&tvk) && tvisnan(&tvk)) ?
  163. (tvisnum(tv) && tvisnan(tv)) :
  164. lj_obj_equal(tv, &tvk),
  165. "slot %d const mismatch: stack %016llx vs IR %016llx",
  166. s, tv->u64, tvk.u64);
  167. }
  168. }
  169. }
  170. }
  171. lj_assertJ(J->framedepth == depth,
  172. "frame depth mismatch %d vs %d", J->framedepth, depth);
  173. }
  174. #endif
  175. /* -- Type handling and specialization ------------------------------------ */
  176. /* Note: these functions return tagged references (TRef). */
  177. /* Specialize a slot to a specific type. Note: slot can be negative! */
  178. static TRef sloadt(jit_State *J, int32_t slot, IRType t, int mode)
  179. {
  180. /* Caller may set IRT_GUARD in t. */
  181. TRef ref = emitir_raw(IRT(IR_SLOAD, t), (int32_t)J->baseslot+slot, mode);
  182. J->base[slot] = ref;
  183. return ref;
  184. }
  185. /* Specialize a slot to the runtime type. Note: slot can be negative! */
  186. static TRef sload(jit_State *J, int32_t slot)
  187. {
  188. IRType t = itype2irt(&J->L->base[slot]);
  189. TRef ref = emitir_raw(IRTG(IR_SLOAD, t), (int32_t)J->baseslot+slot,
  190. IRSLOAD_TYPECHECK);
  191. if (irtype_ispri(t)) ref = TREF_PRI(t); /* Canonicalize primitive refs. */
  192. J->base[slot] = ref;
  193. return ref;
  194. }
  195. /* Get TRef from slot. Load slot and specialize if not done already. */
  196. #define getslot(J, s) (J->base[(s)] ? J->base[(s)] : sload(J, (int32_t)(s)))
  197. /* Get TRef for current function. */
  198. static TRef getcurrf(jit_State *J)
  199. {
  200. if (J->base[-1-LJ_FR2])
  201. return J->base[-1-LJ_FR2];
  202. /* Non-base frame functions ought to be loaded already. */
  203. lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot");
  204. return sloadt(J, -1-LJ_FR2, IRT_FUNC, IRSLOAD_READONLY);
  205. }
  206. /* Compare for raw object equality.
  207. ** Returns 0 if the objects are the same.
  208. ** Returns 1 if they are different, but the same type.
  209. ** Returns 2 for two different types.
  210. ** Comparisons between primitives always return 1 -- no caller cares about it.
  211. */
  212. int lj_record_objcmp(jit_State *J, TRef a, TRef b, cTValue *av, cTValue *bv)
  213. {
  214. int diff = !lj_obj_equal(av, bv);
  215. if (!tref_isk2(a, b)) { /* Shortcut, also handles primitives. */
  216. IRType ta = tref_isinteger(a) ? IRT_INT : tref_type(a);
  217. IRType tb = tref_isinteger(b) ? IRT_INT : tref_type(b);
  218. if (ta != tb) {
  219. /* Widen mixed number/int comparisons to number/number comparison. */
  220. if (ta == IRT_INT && tb == IRT_NUM) {
  221. a = emitir(IRTN(IR_CONV), a, IRCONV_NUM_INT);
  222. ta = IRT_NUM;
  223. } else if (ta == IRT_NUM && tb == IRT_INT) {
  224. b = emitir(IRTN(IR_CONV), b, IRCONV_NUM_INT);
  225. } else {
  226. return 2; /* Two different types are never equal. */
  227. }
  228. }
  229. emitir(IRTG(diff ? IR_NE : IR_EQ, ta), a, b);
  230. }
  231. return diff;
  232. }
  233. /* Constify a value. Returns 0 for non-representable object types. */
  234. TRef lj_record_constify(jit_State *J, cTValue *o)
  235. {
  236. if (tvisgcv(o))
  237. return lj_ir_kgc(J, gcV(o), itype2irt(o));
  238. else if (tvisint(o))
  239. return lj_ir_kint(J, intV(o));
  240. else if (tvisnum(o))
  241. return lj_ir_knumint(J, numV(o));
  242. else if (tvisbool(o))
  243. return TREF_PRI(itype2irt(o));
  244. else
  245. return 0; /* Can't represent lightuserdata (pointless). */
  246. }
  247. /* Emit a VLOAD with the correct type. */
  248. TRef lj_record_vload(jit_State *J, TRef ref, MSize idx, IRType t)
  249. {
  250. TRef tr = emitir(IRTG(IR_VLOAD, t), ref, idx);
  251. if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */
  252. return tr;
  253. }
  254. /* -- Record loop ops ----------------------------------------------------- */
  255. /* Loop event. */
  256. typedef enum {
  257. LOOPEV_LEAVE, /* Loop is left or not entered. */
  258. LOOPEV_ENTERLO, /* Loop is entered with a low iteration count left. */
  259. LOOPEV_ENTER /* Loop is entered. */
  260. } LoopEvent;
  261. /* Canonicalize slots: convert integers to numbers. */
  262. static void canonicalize_slots(jit_State *J)
  263. {
  264. BCReg s;
  265. if (LJ_DUALNUM) return;
  266. for (s = J->baseslot+J->maxslot-1; s >= 1; s--) {
  267. TRef tr = J->slot[s];
  268. if (tref_isinteger(tr) && !(tr & TREF_KEYINDEX)) {
  269. IRIns *ir = IR(tref_ref(tr));
  270. if (!(ir->o == IR_SLOAD && (ir->op2 & (IRSLOAD_READONLY))))
  271. J->slot[s] = emitir(IRTN(IR_CONV), tr, IRCONV_NUM_INT);
  272. }
  273. }
  274. }
  275. /* Stop recording. */
  276. void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
  277. {
  278. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  279. if (J->retryrec)
  280. lj_trace_err(J, LJ_TRERR_RETRY);
  281. #endif
  282. lj_trace_end(J);
  283. J->cur.linktype = (uint8_t)linktype;
  284. J->cur.link = (uint16_t)lnk;
  285. /* Looping back at the same stack level? */
  286. if (lnk == J->cur.traceno && J->framedepth + J->retdepth == 0) {
  287. if ((J->flags & JIT_F_OPT_LOOP)) /* Shall we try to create a loop? */
  288. goto nocanon; /* Do not canonicalize or we lose the narrowing. */
  289. if (J->cur.root) /* Otherwise ensure we always link to the root trace. */
  290. J->cur.link = J->cur.root;
  291. }
  292. canonicalize_slots(J);
  293. nocanon:
  294. /* Note: all loop ops must set J->pc to the following instruction! */
  295. lj_snap_add(J); /* Add loop snapshot. */
  296. J->needsnap = 0;
  297. J->mergesnap = 1; /* In case recording continues. */
  298. }
  299. /* Search bytecode backwards for a int/num constant slot initializer. */
  300. static TRef find_kinit(jit_State *J, const BCIns *endpc, BCReg slot, IRType t)
  301. {
  302. /* This algorithm is rather simplistic and assumes quite a bit about
  303. ** how the bytecode is generated. It works fine for FORI initializers,
  304. ** but it won't necessarily work in other cases (e.g. iterator arguments).
  305. ** It doesn't do anything fancy, either (like backpropagating MOVs).
  306. */
  307. const BCIns *pc, *startpc = proto_bc(J->pt);
  308. for (pc = endpc-1; pc > startpc; pc--) {
  309. BCIns ins = *pc;
  310. BCOp op = bc_op(ins);
  311. /* First try to find the last instruction that stores to this slot. */
  312. if (bcmode_a(op) == BCMbase && bc_a(ins) <= slot) {
  313. return 0; /* Multiple results, e.g. from a CALL or KNIL. */
  314. } else if (bcmode_a(op) == BCMdst && bc_a(ins) == slot) {
  315. if (op == BC_KSHORT || op == BC_KNUM) { /* Found const. initializer. */
  316. /* Now try to verify there's no forward jump across it. */
  317. const BCIns *kpc = pc;
  318. for (; pc > startpc; pc--)
  319. if (bc_op(*pc) == BC_JMP) {
  320. const BCIns *target = pc+bc_j(*pc)+1;
  321. if (target > kpc && target <= endpc)
  322. return 0; /* Conditional assignment. */
  323. }
  324. if (op == BC_KSHORT) {
  325. int32_t k = (int32_t)(int16_t)bc_d(ins);
  326. return t == IRT_INT ? lj_ir_kint(J, k) : lj_ir_knum(J, (lua_Number)k);
  327. } else {
  328. cTValue *tv = proto_knumtv(J->pt, bc_d(ins));
  329. if (t == IRT_INT) {
  330. int32_t k = numberVint(tv);
  331. if (tvisint(tv) || numV(tv) == (lua_Number)k) /* -0 is ok here. */
  332. return lj_ir_kint(J, k);
  333. return 0; /* Type mismatch. */
  334. } else {
  335. return lj_ir_knum(J, numberVnum(tv));
  336. }
  337. }
  338. }
  339. return 0; /* Non-constant initializer. */
  340. }
  341. }
  342. return 0; /* No assignment to this slot found? */
  343. }
  344. /* Load and optionally convert a FORI argument from a slot. */
  345. static TRef fori_load(jit_State *J, BCReg slot, IRType t, int mode)
  346. {
  347. int conv = (tvisint(&J->L->base[slot]) != (t==IRT_INT)) ? IRSLOAD_CONVERT : 0;
  348. return sloadt(J, (int32_t)slot,
  349. t + (((mode & IRSLOAD_TYPECHECK) ||
  350. (conv && t == IRT_INT && !(mode >> 16))) ?
  351. IRT_GUARD : 0),
  352. mode + conv);
  353. }
  354. /* Peek before FORI to find a const initializer. Otherwise load from slot. */
  355. static TRef fori_arg(jit_State *J, const BCIns *fori, BCReg slot,
  356. IRType t, int mode)
  357. {
  358. TRef tr = J->base[slot];
  359. if (!tr) {
  360. tr = find_kinit(J, fori, slot, t);
  361. if (!tr)
  362. tr = fori_load(J, slot, t, mode);
  363. }
  364. return tr;
  365. }
  366. /* Return the direction of the FOR loop iterator.
  367. ** It's important to exactly reproduce the semantics of the interpreter.
  368. */
  369. static int rec_for_direction(cTValue *o)
  370. {
  371. return (tvisint(o) ? intV(o) : (int32_t)o->u32.hi) >= 0;
  372. }
  373. /* Simulate the runtime behavior of the FOR loop iterator. */
  374. static LoopEvent rec_for_iter(IROp *op, cTValue *o, int isforl)
  375. {
  376. lua_Number stopv = numberVnum(&o[FORL_STOP]);
  377. lua_Number idxv = numberVnum(&o[FORL_IDX]);
  378. lua_Number stepv = numberVnum(&o[FORL_STEP]);
  379. if (isforl)
  380. idxv += stepv;
  381. if (rec_for_direction(&o[FORL_STEP])) {
  382. if (idxv <= stopv) {
  383. *op = IR_LE;
  384. return idxv + 2*stepv > stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
  385. }
  386. *op = IR_GT; return LOOPEV_LEAVE;
  387. } else {
  388. if (stopv <= idxv) {
  389. *op = IR_GE;
  390. return idxv + 2*stepv < stopv ? LOOPEV_ENTERLO : LOOPEV_ENTER;
  391. }
  392. *op = IR_LT; return LOOPEV_LEAVE;
  393. }
  394. }
  395. /* Record checks for FOR loop overflow and step direction. */
  396. static void rec_for_check(jit_State *J, IRType t, int dir,
  397. TRef stop, TRef step, int init)
  398. {
  399. if (!tref_isk(step)) {
  400. /* Non-constant step: need a guard for the direction. */
  401. TRef zero = (t == IRT_INT) ? lj_ir_kint(J, 0) : lj_ir_knum_zero(J);
  402. emitir(IRTG(dir ? IR_GE : IR_LT, t), step, zero);
  403. /* Add hoistable overflow checks for a narrowed FORL index. */
  404. if (init && t == IRT_INT) {
  405. if (tref_isk(stop)) {
  406. /* Constant stop: optimize check away or to a range check for step. */
  407. int32_t k = IR(tref_ref(stop))->i;
  408. if (dir) {
  409. if (k > 0)
  410. emitir(IRTGI(IR_LE), step, lj_ir_kint(J, (int32_t)0x7fffffff-k));
  411. } else {
  412. if (k < 0)
  413. emitir(IRTGI(IR_GE), step, lj_ir_kint(J, (int32_t)0x80000000-k));
  414. }
  415. } else {
  416. /* Stop+step variable: need full overflow check. */
  417. TRef tr = emitir(IRTGI(IR_ADDOV), step, stop);
  418. emitir(IRTI(IR_USE), tr, 0); /* ADDOV is weak. Avoid dead result. */
  419. }
  420. }
  421. } else if (init && t == IRT_INT && !tref_isk(stop)) {
  422. /* Constant step: optimize overflow check to a range check for stop. */
  423. int32_t k = IR(tref_ref(step))->i;
  424. k = (int32_t)(dir ? 0x7fffffff : 0x80000000) - k;
  425. emitir(IRTGI(dir ? IR_LE : IR_GE), stop, lj_ir_kint(J, k));
  426. }
  427. }
  428. /* Record a FORL instruction. */
  429. static void rec_for_loop(jit_State *J, const BCIns *fori, ScEvEntry *scev,
  430. int init)
  431. {
  432. BCReg ra = bc_a(*fori);
  433. cTValue *tv = &J->L->base[ra];
  434. TRef idx = J->base[ra+FORL_IDX];
  435. IRType t = idx ? tref_type(idx) :
  436. (init || LJ_DUALNUM) ? lj_opt_narrow_forl(J, tv) : IRT_NUM;
  437. int mode = IRSLOAD_INHERIT +
  438. ((!LJ_DUALNUM || tvisint(tv) == (t == IRT_INT)) ? IRSLOAD_READONLY : 0);
  439. TRef stop = fori_arg(J, fori, ra+FORL_STOP, t, mode);
  440. TRef step = fori_arg(J, fori, ra+FORL_STEP, t, mode);
  441. int tc, dir = rec_for_direction(&tv[FORL_STEP]);
  442. lj_assertJ(bc_op(*fori) == BC_FORI || bc_op(*fori) == BC_JFORI,
  443. "bad bytecode %d instead of FORI/JFORI", bc_op(*fori));
  444. scev->t.irt = t;
  445. scev->dir = dir;
  446. scev->stop = tref_ref(stop);
  447. scev->step = tref_ref(step);
  448. rec_for_check(J, t, dir, stop, step, init);
  449. scev->start = tref_ref(find_kinit(J, fori, ra+FORL_IDX, IRT_INT));
  450. tc = (LJ_DUALNUM &&
  451. !(scev->start && irref_isk(scev->stop) && irref_isk(scev->step) &&
  452. tvisint(&tv[FORL_IDX]) == (t == IRT_INT))) ?
  453. IRSLOAD_TYPECHECK : 0;
  454. if (tc) {
  455. J->base[ra+FORL_STOP] = stop;
  456. J->base[ra+FORL_STEP] = step;
  457. }
  458. if (!idx)
  459. idx = fori_load(J, ra+FORL_IDX, t,
  460. IRSLOAD_INHERIT + tc + (J->scev.start << 16));
  461. if (!init)
  462. J->base[ra+FORL_IDX] = idx = emitir(IRT(IR_ADD, t), idx, step);
  463. J->base[ra+FORL_EXT] = idx;
  464. scev->idx = tref_ref(idx);
  465. setmref(scev->pc, fori);
  466. J->maxslot = ra+FORL_EXT+1;
  467. }
  468. /* Record FORL/JFORL or FORI/JFORI. */
  469. static LoopEvent rec_for(jit_State *J, const BCIns *fori, int isforl)
  470. {
  471. BCReg ra = bc_a(*fori);
  472. TValue *tv = &J->L->base[ra];
  473. TRef *tr = &J->base[ra];
  474. IROp op;
  475. LoopEvent ev;
  476. TRef stop;
  477. IRType t;
  478. if (isforl) { /* Handle FORL/JFORL opcodes. */
  479. TRef idx = tr[FORL_IDX];
  480. if (mref(J->scev.pc, const BCIns) == fori && tref_ref(idx) == J->scev.idx) {
  481. t = J->scev.t.irt;
  482. stop = J->scev.stop;
  483. idx = emitir(IRT(IR_ADD, t), idx, J->scev.step);
  484. tr[FORL_EXT] = tr[FORL_IDX] = idx;
  485. } else {
  486. ScEvEntry scev;
  487. rec_for_loop(J, fori, &scev, 0);
  488. t = scev.t.irt;
  489. stop = scev.stop;
  490. }
  491. } else { /* Handle FORI/JFORI opcodes. */
  492. BCReg i;
  493. lj_meta_for(J->L, tv);
  494. t = (LJ_DUALNUM || tref_isint(tr[FORL_IDX])) ? lj_opt_narrow_forl(J, tv) :
  495. IRT_NUM;
  496. for (i = FORL_IDX; i <= FORL_STEP; i++) {
  497. if (!tr[i]) sload(J, ra+i);
  498. lj_assertJ(tref_isnumber_str(tr[i]), "bad FORI argument type");
  499. if (tref_isstr(tr[i]))
  500. tr[i] = emitir(IRTG(IR_STRTO, IRT_NUM), tr[i], 0);
  501. if (t == IRT_INT) {
  502. if (!tref_isinteger(tr[i]))
  503. tr[i] = emitir(IRTGI(IR_CONV), tr[i], IRCONV_INT_NUM|IRCONV_CHECK);
  504. } else {
  505. if (!tref_isnum(tr[i]))
  506. tr[i] = emitir(IRTN(IR_CONV), tr[i], IRCONV_NUM_INT);
  507. }
  508. }
  509. tr[FORL_EXT] = tr[FORL_IDX];
  510. stop = tr[FORL_STOP];
  511. rec_for_check(J, t, rec_for_direction(&tv[FORL_STEP]),
  512. stop, tr[FORL_STEP], 1);
  513. }
  514. ev = rec_for_iter(&op, tv, isforl);
  515. if (ev == LOOPEV_LEAVE) {
  516. J->maxslot = ra+FORL_EXT+1;
  517. J->pc = fori+1;
  518. } else {
  519. J->maxslot = ra;
  520. J->pc = fori+bc_j(*fori)+1;
  521. }
  522. lj_snap_add(J);
  523. emitir(IRTG(op, t), tr[FORL_IDX], stop);
  524. if (ev == LOOPEV_LEAVE) {
  525. J->maxslot = ra;
  526. J->pc = fori+bc_j(*fori)+1;
  527. } else {
  528. J->maxslot = ra+FORL_EXT+1;
  529. J->pc = fori+1;
  530. }
  531. J->needsnap = 1;
  532. return ev;
  533. }
  534. /* Record ITERL/JITERL. */
  535. static LoopEvent rec_iterl(jit_State *J, const BCIns iterins)
  536. {
  537. BCReg ra = bc_a(iterins);
  538. if (!tref_isnil(getslot(J, ra))) { /* Looping back? */
  539. J->base[ra-1] = J->base[ra]; /* Copy result of ITERC to control var. */
  540. J->maxslot = ra-1+bc_b(J->pc[-1]);
  541. J->pc += bc_j(iterins)+1;
  542. return LOOPEV_ENTER;
  543. } else {
  544. J->maxslot = ra-3;
  545. J->pc++;
  546. return LOOPEV_LEAVE;
  547. }
  548. }
  549. /* Record LOOP/JLOOP. Now, that was easy. */
  550. static LoopEvent rec_loop(jit_State *J, BCReg ra, int skip)
  551. {
  552. if (ra < J->maxslot) J->maxslot = ra;
  553. J->pc += skip;
  554. return LOOPEV_ENTER;
  555. }
  556. /* Check if a loop repeatedly failed to trace because it didn't loop back. */
  557. static int innerloopleft(jit_State *J, const BCIns *pc)
  558. {
  559. ptrdiff_t i;
  560. for (i = 0; i < PENALTY_SLOTS; i++)
  561. if (mref(J->penalty[i].pc, const BCIns) == pc) {
  562. if ((J->penalty[i].reason == LJ_TRERR_LLEAVE ||
  563. J->penalty[i].reason == LJ_TRERR_LINNER) &&
  564. J->penalty[i].val >= 2*PENALTY_MIN)
  565. return 1;
  566. break;
  567. }
  568. return 0;
  569. }
  570. /* Handle the case when an interpreted loop op is hit. */
  571. static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
  572. {
  573. if (J->parent == 0 && J->exitno == 0) {
  574. if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
  575. if (bc_op(J->cur.startins) == BC_ITERN) return; /* See rec_itern(). */
  576. /* Same loop? */
  577. if (ev == LOOPEV_LEAVE) /* Must loop back to form a root trace. */
  578. lj_trace_err(J, LJ_TRERR_LLEAVE);
  579. lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping trace. */
  580. } else if (ev != LOOPEV_LEAVE) { /* Entering inner loop? */
  581. /* It's usually better to abort here and wait until the inner loop
  582. ** is traced. But if the inner loop repeatedly didn't loop back,
  583. ** this indicates a low trip count. In this case try unrolling
  584. ** an inner loop even in a root trace. But it's better to be a bit
  585. ** more conservative here and only do it for very short loops.
  586. */
  587. if (bc_j(*pc) != -1 && !innerloopleft(J, pc))
  588. lj_trace_err(J, LJ_TRERR_LINNER); /* Root trace hit an inner loop. */
  589. if ((ev != LOOPEV_ENTERLO &&
  590. J->loopref && J->cur.nins - J->loopref > 24) || --J->loopunroll < 0)
  591. lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
  592. J->loopref = J->cur.nins;
  593. }
  594. } else if (ev != LOOPEV_LEAVE) { /* Side trace enters an inner loop. */
  595. J->loopref = J->cur.nins;
  596. if (--J->loopunroll < 0)
  597. lj_trace_err(J, LJ_TRERR_LUNROLL); /* Limit loop unrolling. */
  598. } /* Side trace continues across a loop that's left or not entered. */
  599. }
  600. /* Handle the case when an already compiled loop op is hit. */
  601. static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev)
  602. {
  603. if (J->parent == 0 && J->exitno == 0) { /* Root trace hit an inner loop. */
  604. /* Better let the inner loop spawn a side trace back here. */
  605. lj_trace_err(J, LJ_TRERR_LINNER);
  606. } else if (ev != LOOPEV_LEAVE) { /* Side trace enters a compiled loop. */
  607. J->instunroll = 0; /* Cannot continue across a compiled loop op. */
  608. if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
  609. lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Form extra loop. */
  610. else
  611. lj_record_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the loop. */
  612. } /* Side trace continues across a loop that's left or not entered. */
  613. }
  614. /* Record ITERN. */
  615. static LoopEvent rec_itern(jit_State *J, BCReg ra, BCReg rb)
  616. {
  617. #if LJ_BE
  618. /* YAGNI: Disabled on big-endian due to issues with lj_vm_next,
  619. ** IR_HIOP, RID_RETLO/RID_RETHI and ra_destpair.
  620. */
  621. UNUSED(ra); UNUSED(rb);
  622. setintV(&J->errinfo, (int32_t)BC_ITERN);
  623. lj_trace_err_info(J, LJ_TRERR_NYIBC);
  624. #else
  625. RecordIndex ix;
  626. /* Since ITERN is recorded at the start, we need our own loop detection. */
  627. if (J->pc == J->startpc &&
  628. J->framedepth + J->retdepth == 0 && J->parent == 0 && J->exitno == 0) {
  629. IRRef ref = REF_FIRST + LJ_HASPROFILE;
  630. #ifdef LUAJIT_ENABLE_CHECKHOOK
  631. ref += 3;
  632. #endif
  633. if (J->cur.nins > ref ||
  634. (LJ_HASPROFILE && J->cur.nins == ref && J->cur.ir[ref-1].o != IR_PROF)) {
  635. J->instunroll = 0; /* Cannot continue unrolling across an ITERN. */
  636. lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping trace. */
  637. return LOOPEV_ENTER;
  638. }
  639. }
  640. J->maxslot = ra;
  641. lj_snap_add(J); /* Required to make JLOOP the first ins in a side-trace. */
  642. ix.tab = getslot(J, ra-2);
  643. ix.key = J->base[ra-1] ? J->base[ra-1] :
  644. sloadt(J, (int32_t)(ra-1), IRT_GUARD|IRT_INT,
  645. IRSLOAD_TYPECHECK|IRSLOAD_KEYINDEX);
  646. copyTV(J->L, &ix.tabv, &J->L->base[ra-2]);
  647. copyTV(J->L, &ix.keyv, &J->L->base[ra-1]);
  648. ix.idxchain = (rb < 3); /* Omit value type check, if unused. */
  649. ix.mobj = 1; /* We need the next index, too. */
  650. J->maxslot = ra + lj_record_next(J, &ix);
  651. J->needsnap = 1;
  652. if (!tref_isnil(ix.key)) { /* Looping back? */
  653. J->base[ra-1] = ix.mobj | TREF_KEYINDEX; /* Control var has next index. */
  654. J->base[ra] = ix.key;
  655. J->base[ra+1] = ix.val;
  656. J->pc += bc_j(J->pc[1])+2;
  657. return LOOPEV_ENTER;
  658. } else {
  659. J->maxslot = ra-3;
  660. J->pc += 2;
  661. return LOOPEV_LEAVE;
  662. }
  663. #endif
  664. }
  665. /* Record ISNEXT. */
  666. static void rec_isnext(jit_State *J, BCReg ra)
  667. {
  668. cTValue *b = &J->L->base[ra-3];
  669. if (tvisfunc(b) && funcV(b)->c.ffid == FF_next &&
  670. tvistab(b+1) && tvisnil(b+2)) {
  671. /* These checks are folded away for a compiled pairs(). */
  672. TRef func = getslot(J, ra-3);
  673. TRef trid = emitir(IRT(IR_FLOAD, IRT_U8), func, IRFL_FUNC_FFID);
  674. emitir(IRTGI(IR_EQ), trid, lj_ir_kint(J, FF_next));
  675. (void)getslot(J, ra-2); /* Type check for table. */
  676. (void)getslot(J, ra-1); /* Type check for nil key. */
  677. J->base[ra-1] = lj_ir_kint(J, 0) | TREF_KEYINDEX;
  678. J->maxslot = ra;
  679. } else { /* Abort trace. Interpreter will despecialize bytecode. */
  680. lj_trace_err(J, LJ_TRERR_RECERR);
  681. }
  682. }
  683. /* -- Record profiler hook checks ----------------------------------------- */
  684. #if LJ_HASPROFILE
  685. /* Need to insert profiler hook check? */
  686. static int rec_profile_need(jit_State *J, GCproto *pt, const BCIns *pc)
  687. {
  688. GCproto *ppt;
  689. lj_assertJ(J->prof_mode == 'f' || J->prof_mode == 'l',
  690. "bad profiler mode %c", J->prof_mode);
  691. if (!pt)
  692. return 0;
  693. ppt = J->prev_pt;
  694. J->prev_pt = pt;
  695. if (pt != ppt && ppt) {
  696. J->prev_line = -1;
  697. return 1;
  698. }
  699. if (J->prof_mode == 'l') {
  700. BCLine line = lj_debug_line(pt, proto_bcpos(pt, pc));
  701. BCLine pline = J->prev_line;
  702. J->prev_line = line;
  703. if (pline != line)
  704. return 1;
  705. }
  706. return 0;
  707. }
  708. static void rec_profile_ins(jit_State *J, const BCIns *pc)
  709. {
  710. if (J->prof_mode && rec_profile_need(J, J->pt, pc)) {
  711. emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
  712. lj_snap_add(J);
  713. }
  714. }
  715. static void rec_profile_ret(jit_State *J)
  716. {
  717. if (J->prof_mode == 'f') {
  718. emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
  719. J->prev_pt = NULL;
  720. lj_snap_add(J);
  721. }
  722. }
  723. #endif
  724. /* -- Record calls and returns -------------------------------------------- */
  725. /* Specialize to the runtime value of the called function or its prototype. */
  726. static TRef rec_call_specialize(jit_State *J, GCfunc *fn, TRef tr)
  727. {
  728. TRef kfunc;
  729. if (isluafunc(fn)) {
  730. GCproto *pt = funcproto(fn);
  731. /* Too many closures created? Probably not a monomorphic function. */
  732. if (pt->flags >= PROTO_CLC_POLY) { /* Specialize to prototype instead. */
  733. TRef trpt = emitir(IRT(IR_FLOAD, IRT_PGC), tr, IRFL_FUNC_PC);
  734. emitir(IRTG(IR_EQ, IRT_PGC), trpt, lj_ir_kptr(J, proto_bc(pt)));
  735. (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); /* Prevent GC of proto. */
  736. return tr;
  737. }
  738. } else {
  739. /* Don't specialize to non-monomorphic builtins. */
  740. switch (fn->c.ffid) {
  741. case FF_coroutine_wrap_aux:
  742. case FF_string_gmatch_aux:
  743. /* NYI: io_file_iter doesn't have an ffid, yet. */
  744. { /* Specialize to the ffid. */
  745. TRef trid = emitir(IRT(IR_FLOAD, IRT_U8), tr, IRFL_FUNC_FFID);
  746. emitir(IRTGI(IR_EQ), trid, lj_ir_kint(J, fn->c.ffid));
  747. }
  748. return tr;
  749. default:
  750. /* NYI: don't specialize to non-monomorphic C functions. */
  751. break;
  752. }
  753. }
  754. /* Otherwise specialize to the function (closure) value itself. */
  755. kfunc = lj_ir_kfunc(J, fn);
  756. emitir(IRTG(IR_EQ, IRT_FUNC), tr, kfunc);
  757. return kfunc;
  758. }
  759. /* Record call setup. */
  760. static void rec_call_setup(jit_State *J, BCReg func, ptrdiff_t nargs)
  761. {
  762. RecordIndex ix;
  763. TValue *functv = &J->L->base[func];
  764. TRef kfunc, *fbase = &J->base[func];
  765. ptrdiff_t i;
  766. (void)getslot(J, func); /* Ensure func has a reference. */
  767. for (i = 1; i <= nargs; i++)
  768. (void)getslot(J, func+LJ_FR2+i); /* Ensure all args have a reference. */
  769. if (!tref_isfunc(fbase[0])) { /* Resolve __call metamethod. */
  770. ix.tab = fbase[0];
  771. copyTV(J->L, &ix.tabv, functv);
  772. if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj))
  773. lj_trace_err(J, LJ_TRERR_NOMM);
  774. for (i = ++nargs; i > LJ_FR2; i--) /* Shift arguments up. */
  775. fbase[i+LJ_FR2] = fbase[i+LJ_FR2-1];
  776. #if LJ_FR2
  777. fbase[2] = fbase[0];
  778. #endif
  779. fbase[0] = ix.mobj; /* Replace function. */
  780. functv = &ix.mobjv;
  781. }
  782. kfunc = rec_call_specialize(J, funcV(functv), fbase[0]);
  783. #if LJ_FR2
  784. fbase[0] = kfunc;
  785. fbase[1] = TREF_FRAME;
  786. #else
  787. fbase[0] = kfunc | TREF_FRAME;
  788. #endif
  789. J->maxslot = (BCReg)nargs;
  790. }
  791. /* Record call. */
  792. void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs)
  793. {
  794. rec_call_setup(J, func, nargs);
  795. /* Bump frame. */
  796. J->framedepth++;
  797. J->base += func+1+LJ_FR2;
  798. J->baseslot += func+1+LJ_FR2;
  799. if (J->baseslot + J->maxslot >= LJ_MAX_JSLOTS)
  800. lj_trace_err(J, LJ_TRERR_STACKOV);
  801. }
  802. /* Record tail call. */
  803. void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
  804. {
  805. rec_call_setup(J, func, nargs);
  806. if (frame_isvarg(J->L->base - 1)) {
  807. BCReg cbase = (BCReg)frame_delta(J->L->base - 1);
  808. if (--J->framedepth < 0)
  809. lj_trace_err(J, LJ_TRERR_NYIRETL);
  810. J->baseslot -= (BCReg)cbase;
  811. J->base -= cbase;
  812. func += cbase;
  813. }
  814. /* Move func + args down. */
  815. if (LJ_FR2 && J->baseslot == 2)
  816. J->base[func+1] = TREF_FRAME;
  817. memmove(&J->base[-1-LJ_FR2], &J->base[func], sizeof(TRef)*(J->maxslot+1+LJ_FR2));
  818. /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
  819. /* Tailcalls can form a loop, so count towards the loop unroll limit. */
  820. if (++J->tailcalled > J->loopunroll)
  821. lj_trace_err(J, LJ_TRERR_LUNROLL);
  822. }
  823. /* Check unroll limits for down-recursion. */
  824. static int check_downrec_unroll(jit_State *J, GCproto *pt)
  825. {
  826. IRRef ptref;
  827. for (ptref = J->chain[IR_KGC]; ptref; ptref = IR(ptref)->prev)
  828. if (ir_kgc(IR(ptref)) == obj2gco(pt)) {
  829. int count = 0;
  830. IRRef ref;
  831. for (ref = J->chain[IR_RETF]; ref; ref = IR(ref)->prev)
  832. if (IR(ref)->op1 == ptref)
  833. count++;
  834. if (count) {
  835. if (J->pc == J->startpc) {
  836. if (count + J->tailcalled > J->param[JIT_P_recunroll])
  837. return 1;
  838. } else {
  839. lj_trace_err(J, LJ_TRERR_DOWNREC);
  840. }
  841. }
  842. }
  843. return 0;
  844. }
  845. static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot);
  846. /* Record return. */
  847. void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
  848. {
  849. TValue *frame = J->L->base - 1;
  850. ptrdiff_t i;
  851. for (i = 0; i < gotresults; i++)
  852. (void)getslot(J, rbase+i); /* Ensure all results have a reference. */
  853. while (frame_ispcall(frame)) { /* Immediately resolve pcall() returns. */
  854. BCReg cbase = (BCReg)frame_delta(frame);
  855. if (--J->framedepth <= 0)
  856. lj_trace_err(J, LJ_TRERR_NYIRETL);
  857. lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
  858. gotresults++;
  859. rbase += cbase;
  860. J->baseslot -= (BCReg)cbase;
  861. J->base -= cbase;
  862. J->base[--rbase] = TREF_TRUE; /* Prepend true to results. */
  863. frame = frame_prevd(frame);
  864. J->needsnap = 1; /* Stop catching on-trace errors. */
  865. }
  866. /* Return to lower frame via interpreter for unhandled cases. */
  867. if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
  868. (!frame_islua(frame) ||
  869. (J->parent == 0 && J->exitno == 0 &&
  870. !bc_isret(bc_op(J->cur.startins))))) {
  871. /* NYI: specialize to frame type and return directly, not via RET*. */
  872. for (i = 0; i < (ptrdiff_t)rbase; i++)
  873. J->base[i] = 0; /* Purge dead slots. */
  874. J->maxslot = rbase + (BCReg)gotresults;
  875. lj_record_stop(J, LJ_TRLINK_RETURN, 0); /* Return to interpreter. */
  876. return;
  877. }
  878. if (frame_isvarg(frame)) {
  879. BCReg cbase = (BCReg)frame_delta(frame);
  880. if (--J->framedepth < 0) /* NYI: return of vararg func to lower frame. */
  881. lj_trace_err(J, LJ_TRERR_NYIRETL);
  882. lj_assertJ(J->baseslot > 1+LJ_FR2, "bad baseslot for return");
  883. rbase += cbase;
  884. J->baseslot -= (BCReg)cbase;
  885. J->base -= cbase;
  886. frame = frame_prevd(frame);
  887. }
  888. if (frame_islua(frame)) { /* Return to Lua frame. */
  889. BCIns callins = *(frame_pc(frame)-1);
  890. ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
  891. BCReg cbase = bc_a(callins);
  892. GCproto *pt = funcproto(frame_func(frame - (cbase+1+LJ_FR2)));
  893. if ((pt->flags & PROTO_NOJIT))
  894. lj_trace_err(J, LJ_TRERR_CJITOFF);
  895. if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
  896. if (check_downrec_unroll(J, pt)) {
  897. J->maxslot = (BCReg)(rbase + gotresults);
  898. lj_snap_purge(J);
  899. lj_record_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno); /* Down-rec. */
  900. return;
  901. }
  902. lj_snap_add(J);
  903. }
  904. for (i = 0; i < nresults; i++) /* Adjust results. */
  905. J->base[i-1-LJ_FR2] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
  906. J->maxslot = cbase+(BCReg)nresults;
  907. if (J->framedepth > 0) { /* Return to a frame that is part of the trace. */
  908. J->framedepth--;
  909. lj_assertJ(J->baseslot > cbase+1+LJ_FR2, "bad baseslot for return");
  910. J->baseslot -= cbase+1+LJ_FR2;
  911. J->base -= cbase+1+LJ_FR2;
  912. } else if (J->parent == 0 && J->exitno == 0 &&
  913. !bc_isret(bc_op(J->cur.startins))) {
  914. /* Return to lower frame would leave the loop in a root trace. */
  915. lj_trace_err(J, LJ_TRERR_LLEAVE);
  916. } else if (J->needsnap) { /* Tailcalled to ff with side-effects. */
  917. lj_trace_err(J, LJ_TRERR_NYIRETL); /* No way to insert snapshot here. */
  918. } else { /* Return to lower frame. Guard for the target we return to. */
  919. TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
  920. TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
  921. emitir(IRTG(IR_RETF, IRT_PGC), trpt, trpc);
  922. J->retdepth++;
  923. J->needsnap = 1;
  924. J->scev.idx = REF_NIL;
  925. lj_assertJ(J->baseslot == 1+LJ_FR2, "bad baseslot for return");
  926. /* Shift result slots up and clear the slots of the new frame below. */
  927. memmove(J->base + cbase, J->base-1-LJ_FR2, sizeof(TRef)*nresults);
  928. memset(J->base-1-LJ_FR2, 0, sizeof(TRef)*(cbase+1+LJ_FR2));
  929. }
  930. } else if (frame_iscont(frame)) { /* Return to continuation frame. */
  931. ASMFunction cont = frame_contf(frame);
  932. BCReg cbase = (BCReg)frame_delta(frame);
  933. if ((J->framedepth -= 2) < 0)
  934. lj_trace_err(J, LJ_TRERR_NYIRETL);
  935. J->baseslot -= (BCReg)cbase;
  936. J->base -= cbase;
  937. J->maxslot = cbase-(2<<LJ_FR2);
  938. if (cont == lj_cont_ra) {
  939. /* Copy result to destination slot. */
  940. BCReg dst = bc_a(*(frame_contpc(frame)-1));
  941. J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
  942. if (dst >= J->maxslot) {
  943. J->maxslot = dst+1;
  944. }
  945. } else if (cont == lj_cont_nop) {
  946. /* Nothing to do here. */
  947. } else if (cont == lj_cont_cat) {
  948. BCReg bslot = bc_b(*(frame_contpc(frame)-1));
  949. TRef tr = gotresults ? J->base[cbase+rbase] : TREF_NIL;
  950. if (bslot != J->maxslot) { /* Concatenate the remainder. */
  951. TValue *b = J->L->base, save; /* Simulate lower frame and result. */
  952. /* Can't handle MM_concat + CALLT + fast func side-effects. */
  953. if (J->postproc != LJ_POST_NONE)
  954. lj_trace_err(J, LJ_TRERR_NYIRETL);
  955. J->base[J->maxslot] = tr;
  956. copyTV(J->L, &save, b-(2<<LJ_FR2));
  957. if (gotresults)
  958. copyTV(J->L, b-(2<<LJ_FR2), b+rbase);
  959. else
  960. setnilV(b-(2<<LJ_FR2));
  961. J->L->base = b - cbase;
  962. tr = rec_cat(J, bslot, cbase-(2<<LJ_FR2));
  963. b = J->L->base + cbase; /* Undo. */
  964. J->L->base = b;
  965. copyTV(J->L, b-(2<<LJ_FR2), &save);
  966. }
  967. if (tr) { /* Store final result. */
  968. BCReg dst = bc_a(*(frame_contpc(frame)-1));
  969. J->base[dst] = tr;
  970. if (dst >= J->maxslot) {
  971. J->maxslot = dst+1;
  972. }
  973. } /* Otherwise continue with another __concat call. */
  974. } else {
  975. /* Result type already specialized. */
  976. lj_assertJ(cont == lj_cont_condf || cont == lj_cont_condt,
  977. "bad continuation type");
  978. }
  979. } else {
  980. lj_trace_err(J, LJ_TRERR_NYIRETL); /* NYI: handle return to C frame. */
  981. }
  982. lj_assertJ(J->baseslot >= 1+LJ_FR2, "bad baseslot for return");
  983. }
  984. /* -- Metamethod handling ------------------------------------------------- */
  985. /* Prepare to record call to metamethod. */
  986. static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
  987. {
  988. BCReg s, top = cont == lj_cont_cat ? J->maxslot : curr_proto(J->L)->framesize;
  989. #if LJ_FR2
  990. J->base[top] = lj_ir_k64(J, IR_KNUM, u64ptr(contptr(cont)));
  991. J->base[top+1] = TREF_CONT;
  992. #else
  993. J->base[top] = lj_ir_kptr(J, contptr(cont)) | TREF_CONT;
  994. #endif
  995. J->framedepth++;
  996. for (s = J->maxslot; s < top; s++)
  997. J->base[s] = 0; /* Clear frame gap to avoid resurrecting previous refs. */
  998. return top+1+LJ_FR2;
  999. }
  1000. /* Record metamethod lookup. */
  1001. int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
  1002. {
  1003. RecordIndex mix;
  1004. GCtab *mt;
  1005. if (tref_istab(ix->tab)) {
  1006. mt = tabref(tabV(&ix->tabv)->metatable);
  1007. mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
  1008. } else if (tref_isudata(ix->tab)) {
  1009. int udtype = udataV(&ix->tabv)->udtype;
  1010. mt = tabref(udataV(&ix->tabv)->metatable);
  1011. /* The metatables of special userdata objects are treated as immutable. */
  1012. if (udtype != UDTYPE_USERDATA) {
  1013. cTValue *mo;
  1014. if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
  1015. /* Specialize to the C library namespace object. */
  1016. emitir(IRTG(IR_EQ, IRT_PGC), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
  1017. } else {
  1018. /* Specialize to the type of userdata. */
  1019. TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
  1020. emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, udtype));
  1021. }
  1022. immutable_mt:
  1023. mo = lj_tab_getstr(mt, mmname_str(J2G(J), mm));
  1024. if (!mo || tvisnil(mo))
  1025. return 0; /* No metamethod. */
  1026. /* Treat metamethod or index table as immutable, too. */
  1027. if (!(tvisfunc(mo) || tvistab(mo)))
  1028. lj_trace_err(J, LJ_TRERR_BADTYPE);
  1029. copyTV(J->L, &ix->mobjv, mo);
  1030. ix->mobj = lj_ir_kgc(J, gcV(mo), tvisfunc(mo) ? IRT_FUNC : IRT_TAB);
  1031. ix->mtv = mt;
  1032. ix->mt = TREF_NIL; /* Dummy value for comparison semantics. */
  1033. return 1; /* Got metamethod or index table. */
  1034. }
  1035. mix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_UDATA_META);
  1036. } else {
  1037. /* Specialize to base metatable. Must flush mcode in lua_setmetatable(). */
  1038. mt = tabref(basemt_obj(J2G(J), &ix->tabv));
  1039. if (mt == NULL) {
  1040. ix->mt = TREF_NIL;
  1041. return 0; /* No metamethod. */
  1042. }
  1043. /* The cdata metatable is treated as immutable. */
  1044. if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
  1045. ix->mt = mix.tab = lj_ir_ggfload(J, IRT_TAB,
  1046. GG_OFS(g.gcroot[GCROOT_BASEMT+itypemap(&ix->tabv)]));
  1047. goto nocheck;
  1048. }
  1049. ix->mt = mt ? mix.tab : TREF_NIL;
  1050. emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mix.tab, lj_ir_knull(J, IRT_TAB));
  1051. nocheck:
  1052. if (mt) {
  1053. GCstr *mmstr = mmname_str(J2G(J), mm);
  1054. cTValue *mo = lj_tab_getstr(mt, mmstr);
  1055. if (mo && !tvisnil(mo))
  1056. copyTV(J->L, &ix->mobjv, mo);
  1057. ix->mtv = mt;
  1058. settabV(J->L, &mix.tabv, mt);
  1059. setstrV(J->L, &mix.keyv, mmstr);
  1060. mix.key = lj_ir_kstr(J, mmstr);
  1061. mix.val = 0;
  1062. mix.idxchain = 0;
  1063. ix->mobj = lj_record_idx(J, &mix);
  1064. return !tref_isnil(ix->mobj); /* 1 if metamethod found, 0 if not. */
  1065. }
  1066. return 0; /* No metamethod. */
  1067. }
  1068. /* Record call to arithmetic metamethod. */
  1069. static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
  1070. {
  1071. /* Set up metamethod call first to save ix->tab and ix->tabv. */
  1072. BCReg func = rec_mm_prep(J, mm == MM_concat ? lj_cont_cat : lj_cont_ra);
  1073. TRef *base = J->base + func;
  1074. TValue *basev = J->L->base + func;
  1075. base[1+LJ_FR2] = ix->tab; base[2+LJ_FR2] = ix->key;
  1076. copyTV(J->L, basev+1+LJ_FR2, &ix->tabv);
  1077. copyTV(J->L, basev+2+LJ_FR2, &ix->keyv);
  1078. if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
  1079. if (mm != MM_unm) {
  1080. ix->tab = ix->key;
  1081. copyTV(J->L, &ix->tabv, &ix->keyv);
  1082. if (lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
  1083. goto ok;
  1084. }
  1085. lj_trace_err(J, LJ_TRERR_NOMM);
  1086. }
  1087. ok:
  1088. base[0] = ix->mobj;
  1089. #if LJ_FR2
  1090. base[1] = 0;
  1091. #endif
  1092. copyTV(J->L, basev+0, &ix->mobjv);
  1093. lj_record_call(J, func, 2);
  1094. return 0; /* No result yet. */
  1095. }
  1096. /* Record call to __len metamethod. */
  1097. static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
  1098. {
  1099. RecordIndex ix;
  1100. ix.tab = tr;
  1101. copyTV(J->L, &ix.tabv, tv);
  1102. if (lj_record_mm_lookup(J, &ix, MM_len)) {
  1103. BCReg func = rec_mm_prep(J, lj_cont_ra);
  1104. TRef *base = J->base + func;
  1105. TValue *basev = J->L->base + func;
  1106. base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv);
  1107. base += LJ_FR2;
  1108. basev += LJ_FR2;
  1109. base[1] = tr; copyTV(J->L, basev+1, tv);
  1110. #if LJ_52
  1111. base[2] = tr; copyTV(J->L, basev+2, tv);
  1112. #else
  1113. base[2] = TREF_NIL; setnilV(basev+2);
  1114. #endif
  1115. lj_record_call(J, func, 2);
  1116. } else {
  1117. if (LJ_52 && tref_istab(tr))
  1118. return emitir(IRTI(IR_ALEN), tr, TREF_NIL);
  1119. lj_trace_err(J, LJ_TRERR_NOMM);
  1120. }
  1121. return 0; /* No result yet. */
  1122. }
  1123. /* Call a comparison metamethod. */
  1124. static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
  1125. {
  1126. BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
  1127. TRef *base = J->base + func + LJ_FR2;
  1128. TValue *tv = J->L->base + func + LJ_FR2;
  1129. base[-LJ_FR2] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
  1130. copyTV(J->L, tv-LJ_FR2, &ix->mobjv);
  1131. copyTV(J->L, tv+1, &ix->valv);
  1132. copyTV(J->L, tv+2, &ix->keyv);
  1133. lj_record_call(J, func, 2);
  1134. }
  1135. /* Record call to equality comparison metamethod (for tab and udata only). */
  1136. static void rec_mm_equal(jit_State *J, RecordIndex *ix, int op)
  1137. {
  1138. ix->tab = ix->val;
  1139. copyTV(J->L, &ix->tabv, &ix->valv);
  1140. if (lj_record_mm_lookup(J, ix, MM_eq)) { /* Lookup mm on 1st operand. */
  1141. cTValue *bv;
  1142. TRef mo1 = ix->mobj;
  1143. TValue mo1v;
  1144. copyTV(J->L, &mo1v, &ix->mobjv);
  1145. /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
  1146. bv = &ix->keyv;
  1147. if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
  1148. TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
  1149. emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
  1150. } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
  1151. TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
  1152. emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
  1153. } else { /* Lookup metamethod on 2nd operand and compare both. */
  1154. ix->tab = ix->key;
  1155. copyTV(J->L, &ix->tabv, bv);
  1156. if (!lj_record_mm_lookup(J, ix, MM_eq) ||
  1157. lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
  1158. return;
  1159. }
  1160. rec_mm_callcomp(J, ix, op);
  1161. }
  1162. }
  1163. /* Record call to ordered comparison metamethods (for arbitrary objects). */
  1164. static void rec_mm_comp(jit_State *J, RecordIndex *ix, int op)
  1165. {
  1166. ix->tab = ix->val;
  1167. copyTV(J->L, &ix->tabv, &ix->valv);
  1168. while (1) {
  1169. MMS mm = (op & 2) ? MM_le : MM_lt; /* Try __le + __lt or only __lt. */
  1170. #if LJ_52
  1171. if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
  1172. ix->tab = ix->key;
  1173. copyTV(J->L, &ix->tabv, &ix->keyv);
  1174. if (!lj_record_mm_lookup(J, ix, mm)) /* Lookup mm on 2nd operand. */
  1175. goto nomatch;
  1176. }
  1177. rec_mm_callcomp(J, ix, op);
  1178. return;
  1179. #else
  1180. if (lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
  1181. cTValue *bv;
  1182. TRef mo1 = ix->mobj;
  1183. TValue mo1v;
  1184. copyTV(J->L, &mo1v, &ix->mobjv);
  1185. /* Avoid the 2nd lookup and the objcmp if the metatables are equal. */
  1186. bv = &ix->keyv;
  1187. if (tvistab(bv) && tabref(tabV(bv)->metatable) == ix->mtv) {
  1188. TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_TAB_META);
  1189. emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
  1190. } else if (tvisudata(bv) && tabref(udataV(bv)->metatable) == ix->mtv) {
  1191. TRef mt2 = emitir(IRT(IR_FLOAD, IRT_TAB), ix->key, IRFL_UDATA_META);
  1192. emitir(IRTG(IR_EQ, IRT_TAB), mt2, ix->mt);
  1193. } else { /* Lookup metamethod on 2nd operand and compare both. */
  1194. ix->tab = ix->key;
  1195. copyTV(J->L, &ix->tabv, bv);
  1196. if (!lj_record_mm_lookup(J, ix, mm) ||
  1197. lj_record_objcmp(J, mo1, ix->mobj, &mo1v, &ix->mobjv))
  1198. goto nomatch;
  1199. }
  1200. rec_mm_callcomp(J, ix, op);
  1201. return;
  1202. }
  1203. #endif
  1204. nomatch:
  1205. /* Lookup failed. Retry with __lt and swapped operands. */
  1206. if (!(op & 2)) break; /* Already at __lt. Interpreter will throw. */
  1207. ix->tab = ix->key; ix->key = ix->val; ix->val = ix->tab;
  1208. copyTV(J->L, &ix->tabv, &ix->keyv);
  1209. copyTV(J->L, &ix->keyv, &ix->valv);
  1210. copyTV(J->L, &ix->valv, &ix->tabv);
  1211. op ^= 3;
  1212. }
  1213. }
  1214. #if LJ_HASFFI
  1215. /* Setup call to cdata comparison metamethod. */
  1216. static void rec_mm_comp_cdata(jit_State *J, RecordIndex *ix, int op, MMS mm)
  1217. {
  1218. lj_snap_add(J);
  1219. if (tref_iscdata(ix->val)) {
  1220. ix->tab = ix->val;
  1221. copyTV(J->L, &ix->tabv, &ix->valv);
  1222. } else {
  1223. lj_assertJ(tref_iscdata(ix->key), "cdata expected");
  1224. ix->tab = ix->key;
  1225. copyTV(J->L, &ix->tabv, &ix->keyv);
  1226. }
  1227. lj_record_mm_lookup(J, ix, mm);
  1228. rec_mm_callcomp(J, ix, op);
  1229. }
  1230. #endif
  1231. /* -- Indexed access ------------------------------------------------------ */
  1232. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  1233. /* Bump table allocations in bytecode when they grow during recording. */
  1234. static void rec_idx_bump(jit_State *J, RecordIndex *ix)
  1235. {
  1236. RBCHashEntry *rbc = &J->rbchash[(ix->tab & (RBCHASH_SLOTS-1))];
  1237. if (tref_ref(ix->tab) == rbc->ref) {
  1238. const BCIns *pc = mref(rbc->pc, const BCIns);
  1239. GCtab *tb = tabV(&ix->tabv);
  1240. uint32_t nhbits;
  1241. IRIns *ir;
  1242. if (!tvisnil(&ix->keyv))
  1243. (void)lj_tab_set(J->L, tb, &ix->keyv); /* Grow table right now. */
  1244. nhbits = tb->hmask > 0 ? lj_fls(tb->hmask)+1 : 0;
  1245. ir = IR(tref_ref(ix->tab));
  1246. if (ir->o == IR_TNEW) {
  1247. uint32_t ah = bc_d(*pc);
  1248. uint32_t asize = ah & 0x7ff, hbits = ah >> 11;
  1249. if (nhbits > hbits) hbits = nhbits;
  1250. if (tb->asize > asize) {
  1251. asize = tb->asize <= 0x7ff ? tb->asize : 0x7ff;
  1252. }
  1253. if ((asize | (hbits<<11)) != ah) { /* Has the size changed? */
  1254. /* Patch bytecode, but continue recording (for more patching). */
  1255. setbc_d(pc, (asize | (hbits<<11)));
  1256. /* Patching TNEW operands is only safe if the trace is aborted. */
  1257. ir->op1 = asize; ir->op2 = hbits;
  1258. J->retryrec = 1; /* Abort the trace at the end of recording. */
  1259. }
  1260. } else if (ir->o == IR_TDUP) {
  1261. GCtab *tpl = gco2tab(proto_kgc(&gcref(rbc->pt)->pt, ~(ptrdiff_t)bc_d(*pc)));
  1262. /* Grow template table, but preserve keys with nil values. */
  1263. if ((tb->asize > tpl->asize && (1u << nhbits)-1 == tpl->hmask) ||
  1264. (tb->asize == tpl->asize && (1u << nhbits)-1 > tpl->hmask)) {
  1265. Node *node = noderef(tpl->node);
  1266. uint32_t i, hmask = tpl->hmask, asize;
  1267. TValue *array;
  1268. for (i = 0; i <= hmask; i++) {
  1269. if (!tvisnil(&node[i].key) && tvisnil(&node[i].val))
  1270. settabV(J->L, &node[i].val, tpl);
  1271. }
  1272. if (!tvisnil(&ix->keyv) && tref_isk(ix->key)) {
  1273. TValue *o = lj_tab_set(J->L, tpl, &ix->keyv);
  1274. if (tvisnil(o)) settabV(J->L, o, tpl);
  1275. }
  1276. lj_tab_resize(J->L, tpl, tb->asize, nhbits);
  1277. node = noderef(tpl->node);
  1278. hmask = tpl->hmask;
  1279. for (i = 0; i <= hmask; i++) {
  1280. /* This is safe, since template tables only hold immutable values. */
  1281. if (tvistab(&node[i].val))
  1282. setnilV(&node[i].val);
  1283. }
  1284. /* The shape of the table may have changed. Clean up array part, too. */
  1285. asize = tpl->asize;
  1286. array = tvref(tpl->array);
  1287. for (i = 0; i < asize; i++) {
  1288. if (tvistab(&array[i]))
  1289. setnilV(&array[i]);
  1290. }
  1291. J->retryrec = 1; /* Abort the trace at the end of recording. */
  1292. }
  1293. }
  1294. }
  1295. }
  1296. #endif
  1297. /* Record bounds-check. */
  1298. static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
  1299. {
  1300. /* Try to emit invariant bounds checks. */
  1301. if ((J->flags & (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) ==
  1302. (JIT_F_OPT_LOOP|JIT_F_OPT_ABC)) {
  1303. IRRef ref = tref_ref(ikey);
  1304. IRIns *ir = IR(ref);
  1305. int32_t ofs = 0;
  1306. IRRef ofsref = 0;
  1307. /* Handle constant offsets. */
  1308. if (ir->o == IR_ADD && irref_isk(ir->op2)) {
  1309. ofsref = ir->op2;
  1310. ofs = IR(ofsref)->i;
  1311. ref = ir->op1;
  1312. ir = IR(ref);
  1313. }
  1314. /* Got scalar evolution analysis results for this reference? */
  1315. if (ref == J->scev.idx) {
  1316. int32_t stop;
  1317. lj_assertJ(irt_isint(J->scev.t) && ir->o == IR_SLOAD,
  1318. "only int SCEV supported");
  1319. stop = numberVint(&(J->L->base - J->baseslot)[ir->op1 + FORL_STOP]);
  1320. /* Runtime value for stop of loop is within bounds? */
  1321. if ((uint64_t)stop + ofs < (uint64_t)asize) {
  1322. /* Emit invariant bounds check for stop. */
  1323. emitir(IRTG(IR_ABC, IRT_P32), asizeref, ofs == 0 ? J->scev.stop :
  1324. emitir(IRTI(IR_ADD), J->scev.stop, ofsref));
  1325. /* Emit invariant bounds check for start, if not const or negative. */
  1326. if (!(J->scev.dir && J->scev.start &&
  1327. (int64_t)IR(J->scev.start)->i + ofs >= 0))
  1328. emitir(IRTG(IR_ABC, IRT_P32), asizeref, ikey);
  1329. return;
  1330. }
  1331. }
  1332. }
  1333. emitir(IRTGI(IR_ABC), asizeref, ikey); /* Emit regular bounds check. */
  1334. }
  1335. /* Record indexed key lookup. */
  1336. static TRef rec_idx_key(jit_State *J, RecordIndex *ix, IRRef *rbref,
  1337. IRType1 *rbguard)
  1338. {
  1339. TRef key;
  1340. GCtab *t = tabV(&ix->tabv);
  1341. ix->oldv = lj_tab_get(J->L, t, &ix->keyv); /* Lookup previous value. */
  1342. *rbref = 0;
  1343. rbguard->irt = 0;
  1344. /* Integer keys are looked up in the array part first. */
  1345. key = ix->key;
  1346. if (tref_isnumber(key)) {
  1347. int32_t k = numberVint(&ix->keyv);
  1348. if (!tvisint(&ix->keyv) && numV(&ix->keyv) != (lua_Number)k)
  1349. k = LJ_MAX_ASIZE;
  1350. if ((MSize)k < LJ_MAX_ASIZE) { /* Potential array key? */
  1351. TRef ikey = lj_opt_narrow_index(J, key);
  1352. TRef asizeref = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
  1353. if ((MSize)k < t->asize) { /* Currently an array key? */
  1354. TRef arrayref;
  1355. rec_idx_abc(J, asizeref, ikey, t->asize);
  1356. arrayref = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_ARRAY);
  1357. return emitir(IRT(IR_AREF, IRT_PGC), arrayref, ikey);
  1358. } else { /* Currently not in array (may be an array extension)? */
  1359. emitir(IRTGI(IR_ULE), asizeref, ikey); /* Inv. bounds check. */
  1360. if (k == 0 && tref_isk(key))
  1361. key = lj_ir_knum_zero(J); /* Canonicalize 0 or +-0.0 to +0.0. */
  1362. /* And continue with the hash lookup. */
  1363. }
  1364. } else if (!tref_isk(key)) {
  1365. /* We can rule out const numbers which failed the integerness test
  1366. ** above. But all other numbers are potential array keys.
  1367. */
  1368. if (t->asize == 0) { /* True sparse tables have an empty array part. */
  1369. /* Guard that the array part stays empty. */
  1370. TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_ASIZE);
  1371. emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
  1372. } else {
  1373. lj_trace_err(J, LJ_TRERR_NYITMIX);
  1374. }
  1375. }
  1376. }
  1377. /* Otherwise the key is located in the hash part. */
  1378. if (t->hmask == 0) { /* Shortcut for empty hash part. */
  1379. /* Guard that the hash part stays empty. */
  1380. TRef tmp = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
  1381. emitir(IRTGI(IR_EQ), tmp, lj_ir_kint(J, 0));
  1382. return lj_ir_kkptr(J, niltvg(J2G(J)));
  1383. }
  1384. if (tref_isinteger(key)) /* Hash keys are based on numbers, not ints. */
  1385. key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
  1386. if (tref_isk(key)) {
  1387. /* Optimize lookup of constant hash keys. */
  1388. GCSize hslot = (GCSize)((char *)ix->oldv-(char *)&noderef(t->node)[0].val);
  1389. if (hslot <= t->hmask*(GCSize)sizeof(Node) &&
  1390. hslot <= 65535*(GCSize)sizeof(Node)) {
  1391. TRef node, kslot, hm;
  1392. *rbref = J->cur.nins; /* Mark possible rollback point. */
  1393. *rbguard = J->guardemit;
  1394. hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
  1395. emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask));
  1396. node = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_NODE);
  1397. kslot = lj_ir_kslot(J, key, (IRRef)(hslot / sizeof(Node)));
  1398. return emitir(IRTG(IR_HREFK, IRT_PGC), node, kslot);
  1399. }
  1400. }
  1401. /* Fall back to a regular hash lookup. */
  1402. return emitir(IRT(IR_HREF, IRT_PGC), ix->tab, key);
  1403. }
  1404. /* Determine whether a key is NOT one of the fast metamethod names. */
  1405. static int nommstr(jit_State *J, TRef key)
  1406. {
  1407. if (tref_isstr(key)) {
  1408. if (tref_isk(key)) {
  1409. GCstr *str = ir_kstr(IR(tref_ref(key)));
  1410. uint32_t mm;
  1411. for (mm = 0; mm <= MM_FAST; mm++)
  1412. if (mmname_str(J2G(J), mm) == str)
  1413. return 0; /* MUST be one the fast metamethod names. */
  1414. } else {
  1415. return 0; /* Variable string key MAY be a metamethod name. */
  1416. }
  1417. }
  1418. return 1; /* CANNOT be a metamethod name. */
  1419. }
  1420. /* Record indexed load/store. */
  1421. TRef lj_record_idx(jit_State *J, RecordIndex *ix)
  1422. {
  1423. TRef xref;
  1424. IROp xrefop, loadop;
  1425. IRRef rbref;
  1426. IRType1 rbguard;
  1427. cTValue *oldv;
  1428. while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */
  1429. /* Never call raw lj_record_idx() on non-table. */
  1430. lj_assertJ(ix->idxchain != 0, "bad usage");
  1431. if (!lj_record_mm_lookup(J, ix, ix->val ? MM_newindex : MM_index))
  1432. lj_trace_err(J, LJ_TRERR_NOMM);
  1433. handlemm:
  1434. if (tref_isfunc(ix->mobj)) { /* Handle metamethod call. */
  1435. BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra);
  1436. TRef *base = J->base + func + LJ_FR2;
  1437. TValue *tv = J->L->base + func + LJ_FR2;
  1438. base[-LJ_FR2] = ix->mobj; base[1] = ix->tab; base[2] = ix->key;
  1439. setfuncV(J->L, tv-LJ_FR2, funcV(&ix->mobjv));
  1440. copyTV(J->L, tv+1, &ix->tabv);
  1441. copyTV(J->L, tv+2, &ix->keyv);
  1442. if (ix->val) {
  1443. base[3] = ix->val;
  1444. copyTV(J->L, tv+3, &ix->valv);
  1445. lj_record_call(J, func, 3); /* mobj(tab, key, val) */
  1446. return 0;
  1447. } else {
  1448. lj_record_call(J, func, 2); /* res = mobj(tab, key) */
  1449. return 0; /* No result yet. */
  1450. }
  1451. }
  1452. #if LJ_HASBUFFER
  1453. /* The index table of buffer objects is treated as immutable. */
  1454. if (ix->mt == TREF_NIL && !ix->val &&
  1455. tref_isudata(ix->tab) && udataV(&ix->tabv)->udtype == UDTYPE_BUFFER &&
  1456. tref_istab(ix->mobj) && tref_isstr(ix->key) && tref_isk(ix->key)) {
  1457. cTValue *val = lj_tab_getstr(tabV(&ix->mobjv), strV(&ix->keyv));
  1458. TRef tr = lj_record_constify(J, val);
  1459. if (tr) return tr; /* Specialize to the value, i.e. a method. */
  1460. }
  1461. #endif
  1462. /* Otherwise retry lookup with metaobject. */
  1463. ix->tab = ix->mobj;
  1464. copyTV(J->L, &ix->tabv, &ix->mobjv);
  1465. if (--ix->idxchain == 0)
  1466. lj_trace_err(J, LJ_TRERR_IDXLOOP);
  1467. }
  1468. /* First catch nil and NaN keys for tables. */
  1469. if (tvisnil(&ix->keyv) || (tvisnum(&ix->keyv) && tvisnan(&ix->keyv))) {
  1470. if (ix->val) /* Better fail early. */
  1471. lj_trace_err(J, LJ_TRERR_STORENN);
  1472. if (tref_isk(ix->key)) {
  1473. if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
  1474. goto handlemm;
  1475. return TREF_NIL;
  1476. }
  1477. }
  1478. /* Record the key lookup. */
  1479. xref = rec_idx_key(J, ix, &rbref, &rbguard);
  1480. xrefop = IR(tref_ref(xref))->o;
  1481. loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD;
  1482. /* The lj_meta_tset() inconsistency is gone, but better play safe. */
  1483. oldv = xrefop == IR_KKPTR ? (cTValue *)ir_kptr(IR(tref_ref(xref))) : ix->oldv;
  1484. if (ix->val == 0) { /* Indexed load */
  1485. IRType t = itype2irt(oldv);
  1486. TRef res;
  1487. if (oldv == niltvg(J2G(J))) {
  1488. emitir(IRTG(IR_EQ, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
  1489. res = TREF_NIL;
  1490. } else {
  1491. res = emitir(IRTG(loadop, t), xref, 0);
  1492. }
  1493. if (tref_ref(res) < rbref) { /* HREFK + load forwarded? */
  1494. lj_ir_rollback(J, rbref); /* Rollback to eliminate hmask guard. */
  1495. J->guardemit = rbguard;
  1496. }
  1497. if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
  1498. goto handlemm;
  1499. if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitives. */
  1500. return res;
  1501. } else { /* Indexed store. */
  1502. GCtab *mt = tabref(tabV(&ix->tabv)->metatable);
  1503. int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val);
  1504. if (tref_ref(xref) < rbref) { /* HREFK forwarded? */
  1505. lj_ir_rollback(J, rbref); /* Rollback to eliminate hmask guard. */
  1506. J->guardemit = rbguard;
  1507. }
  1508. if (tvisnil(oldv)) { /* Previous value was nil? */
  1509. /* Need to duplicate the hasmm check for the early guards. */
  1510. int hasmm = 0;
  1511. if (ix->idxchain && mt) {
  1512. cTValue *mo = lj_tab_getstr(mt, mmname_str(J2G(J), MM_newindex));
  1513. hasmm = mo && !tvisnil(mo);
  1514. }
  1515. if (hasmm)
  1516. emitir(IRTG(loadop, IRT_NIL), xref, 0); /* Guard for nil value. */
  1517. else if (xrefop == IR_HREF)
  1518. emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_PGC),
  1519. xref, lj_ir_kkptr(J, niltvg(J2G(J))));
  1520. if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) {
  1521. lj_assertJ(hasmm, "inconsistent metamethod handling");
  1522. goto handlemm;
  1523. }
  1524. lj_assertJ(!hasmm, "inconsistent metamethod handling");
  1525. if (oldv == niltvg(J2G(J))) { /* Need to insert a new key. */
  1526. TRef key = ix->key;
  1527. if (tref_isinteger(key)) { /* NEWREF needs a TValue as a key. */
  1528. key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
  1529. } else if (tref_isnum(key)) {
  1530. if (tref_isk(key)) {
  1531. if (tvismzero(&ix->keyv))
  1532. key = lj_ir_knum_zero(J); /* Canonicalize -0.0 to +0.0. */
  1533. } else {
  1534. emitir(IRTG(IR_EQ, IRT_NUM), key, key); /* Check for !NaN. */
  1535. }
  1536. }
  1537. xref = emitir(IRT(IR_NEWREF, IRT_PGC), ix->tab, key);
  1538. keybarrier = 0; /* NEWREF already takes care of the key barrier. */
  1539. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  1540. if ((J->flags & JIT_F_OPT_SINK)) /* Avoid a separate flag. */
  1541. rec_idx_bump(J, ix);
  1542. #endif
  1543. }
  1544. } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) {
  1545. /* Cannot derive that the previous value was non-nil, must do checks. */
  1546. if (xrefop == IR_HREF) /* Guard against store to niltv. */
  1547. emitir(IRTG(IR_NE, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
  1548. if (ix->idxchain) { /* Metamethod lookup required? */
  1549. /* A check for NULL metatable is cheaper (hoistable) than a load. */
  1550. if (!mt) {
  1551. TRef mtref = emitir(IRT(IR_FLOAD, IRT_TAB), ix->tab, IRFL_TAB_META);
  1552. emitir(IRTG(IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
  1553. } else {
  1554. IRType t = itype2irt(oldv);
  1555. emitir(IRTG(loadop, t), xref, 0); /* Guard for non-nil value. */
  1556. }
  1557. }
  1558. } else {
  1559. keybarrier = 0; /* Previous non-nil value kept the key alive. */
  1560. }
  1561. /* Convert int to number before storing. */
  1562. if (!LJ_DUALNUM && tref_isinteger(ix->val))
  1563. ix->val = emitir(IRTN(IR_CONV), ix->val, IRCONV_NUM_INT);
  1564. emitir(IRT(loadop+IRDELTA_L2S, tref_type(ix->val)), xref, ix->val);
  1565. if (keybarrier || tref_isgcv(ix->val))
  1566. emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0);
  1567. /* Invalidate neg. metamethod cache for stores with certain string keys. */
  1568. if (!nommstr(J, ix->key)) {
  1569. TRef fref = emitir(IRT(IR_FREF, IRT_PGC), ix->tab, IRFL_TAB_NOMM);
  1570. emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0));
  1571. }
  1572. J->needsnap = 1;
  1573. return 0;
  1574. }
  1575. }
  1576. /* Determine result type of table traversal. */
  1577. static IRType rec_next_types(GCtab *t, uint32_t idx)
  1578. {
  1579. for (; idx < t->asize; idx++) {
  1580. cTValue *a = arrayslot(t, idx);
  1581. if (LJ_LIKELY(!tvisnil(a)))
  1582. return (LJ_DUALNUM ? IRT_INT : IRT_NUM) + (itype2irt(a) << 8);
  1583. }
  1584. idx -= t->asize;
  1585. for (; idx <= t->hmask; idx++) {
  1586. Node *n = &noderef(t->node)[idx];
  1587. if (!tvisnil(&n->val))
  1588. return itype2irt(&n->key) + (itype2irt(&n->val) << 8);
  1589. }
  1590. return IRT_NIL + (IRT_NIL << 8);
  1591. }
  1592. /* Record a table traversal step aka next(). */
  1593. int lj_record_next(jit_State *J, RecordIndex *ix)
  1594. {
  1595. IRType t, tkey, tval;
  1596. TRef trvk;
  1597. t = rec_next_types(tabV(&ix->tabv), ix->keyv.u32.lo);
  1598. tkey = (t & 0xff); tval = (t >> 8);
  1599. trvk = lj_ir_call(J, IRCALL_lj_vm_next, ix->tab, ix->key);
  1600. if (ix->mobj || tkey == IRT_NIL) {
  1601. TRef idx = emitir(IRTI(IR_HIOP), trvk, trvk);
  1602. /* Always check for invalid key from next() for nil result. */
  1603. if (!ix->mobj) emitir(IRTGI(IR_NE), idx, lj_ir_kint(J, -1));
  1604. ix->mobj = idx;
  1605. }
  1606. ix->key = lj_record_vload(J, trvk, 1, tkey);
  1607. if (tkey == IRT_NIL || ix->idxchain) { /* Omit value type check. */
  1608. ix->val = TREF_NIL;
  1609. return 1;
  1610. } else { /* Need value. */
  1611. ix->val = lj_record_vload(J, trvk, 0, tval);
  1612. return 2;
  1613. }
  1614. }
  1615. static void rec_tsetm(jit_State *J, BCReg ra, BCReg rn, int32_t i)
  1616. {
  1617. RecordIndex ix;
  1618. cTValue *basev = J->L->base;
  1619. GCtab *t = tabV(&basev[ra-1]);
  1620. settabV(J->L, &ix.tabv, t);
  1621. ix.tab = getslot(J, ra-1);
  1622. ix.idxchain = 0;
  1623. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  1624. if ((J->flags & JIT_F_OPT_SINK)) {
  1625. if (t->asize < i+rn-ra)
  1626. lj_tab_reasize(J->L, t, i+rn-ra);
  1627. setnilV(&ix.keyv);
  1628. rec_idx_bump(J, &ix);
  1629. }
  1630. #endif
  1631. for (; ra < rn; i++, ra++) {
  1632. setintV(&ix.keyv, i);
  1633. ix.key = lj_ir_kint(J, i);
  1634. copyTV(J->L, &ix.valv, &basev[ra]);
  1635. ix.val = getslot(J, ra);
  1636. lj_record_idx(J, &ix);
  1637. }
  1638. }
  1639. /* -- Upvalue access ------------------------------------------------------ */
  1640. /* Check whether upvalue is immutable and ok to constify. */
  1641. static int rec_upvalue_constify(jit_State *J, GCupval *uvp)
  1642. {
  1643. if (uvp->immutable) {
  1644. cTValue *o = uvval(uvp);
  1645. /* Don't constify objects that may retain large amounts of memory. */
  1646. #if LJ_HASFFI
  1647. if (tviscdata(o)) {
  1648. GCcdata *cd = cdataV(o);
  1649. if (!cdataisv(cd) && !(cd->marked & LJ_GC_CDATA_FIN)) {
  1650. CType *ct = ctype_raw(ctype_ctsG(J2G(J)), cd->ctypeid);
  1651. if (!ctype_hassize(ct->info) || ct->size <= 16)
  1652. return 1;
  1653. }
  1654. return 0;
  1655. }
  1656. #else
  1657. UNUSED(J);
  1658. #endif
  1659. if (!(tvistab(o) || tvisudata(o) || tvisthread(o)))
  1660. return 1;
  1661. }
  1662. return 0;
  1663. }
  1664. /* Record upvalue load/store. */
  1665. static TRef rec_upvalue(jit_State *J, uint32_t uv, TRef val)
  1666. {
  1667. GCupval *uvp = &gcref(J->fn->l.uvptr[uv])->uv;
  1668. TRef fn = getcurrf(J);
  1669. IRRef uref;
  1670. int needbarrier = 0;
  1671. if (rec_upvalue_constify(J, uvp)) { /* Try to constify immutable upvalue. */
  1672. TRef tr, kfunc;
  1673. lj_assertJ(val == 0, "bad usage");
  1674. if (!tref_isk(fn)) { /* Late specialization of current function. */
  1675. if (J->pt->flags >= PROTO_CLC_POLY)
  1676. goto noconstify;
  1677. kfunc = lj_ir_kfunc(J, J->fn);
  1678. emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc);
  1679. #if LJ_FR2
  1680. J->base[-2] = kfunc;
  1681. #else
  1682. J->base[-1] = kfunc | TREF_FRAME;
  1683. #endif
  1684. fn = kfunc;
  1685. }
  1686. tr = lj_record_constify(J, uvval(uvp));
  1687. if (tr)
  1688. return tr;
  1689. }
  1690. noconstify:
  1691. /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
  1692. uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff);
  1693. if (!uvp->closed) {
  1694. /* In current stack? */
  1695. if (uvval(uvp) >= tvref(J->L->stack) &&
  1696. uvval(uvp) < tvref(J->L->maxstack)) {
  1697. int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot));
  1698. if (slot >= 0) { /* Aliases an SSA slot? */
  1699. uref = tref_ref(emitir(IRT(IR_UREFO, IRT_PGC), fn, uv));
  1700. emitir(IRTG(IR_EQ, IRT_PGC),
  1701. REF_BASE,
  1702. emitir(IRT(IR_ADD, IRT_PGC), uref,
  1703. lj_ir_kintpgc(J, (slot - 1 - LJ_FR2) * -8)));
  1704. slot -= (int32_t)J->baseslot; /* Note: slot number may be negative! */
  1705. if (val == 0) {
  1706. return getslot(J, slot);
  1707. } else {
  1708. J->base[slot] = val;
  1709. if (slot >= (int32_t)J->maxslot) J->maxslot = (BCReg)(slot+1);
  1710. return 0;
  1711. }
  1712. }
  1713. }
  1714. /* IR_UREFO+IRT_IGC is not checked for open-ness at runtime.
  1715. ** Always marked as a guard, since it might get promoted to IRT_PGC later.
  1716. */
  1717. uref = emitir(IRTG(IR_UREFO, tref_isgcv(val) ? IRT_PGC : IRT_IGC), fn, uv);
  1718. uref = tref_ref(uref);
  1719. emitir(IRTG(IR_UGT, IRT_PGC),
  1720. emitir(IRT(IR_SUB, IRT_PGC), uref, REF_BASE),
  1721. lj_ir_kintpgc(J, (J->baseslot + J->maxslot) * 8));
  1722. } else {
  1723. /* If fn is constant, then so is the GCupval*, and the upvalue cannot
  1724. ** transition back to open, so no guard is required in this case.
  1725. */
  1726. IRType t = (tref_isk(fn) ? 0 : IRT_GUARD) | IRT_PGC;
  1727. uref = tref_ref(emitir(IRT(IR_UREFC, t), fn, uv));
  1728. needbarrier = 1;
  1729. }
  1730. if (val == 0) { /* Upvalue load */
  1731. IRType t = itype2irt(uvval(uvp));
  1732. TRef res = emitir(IRTG(IR_ULOAD, t), uref, 0);
  1733. if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitive refs. */
  1734. return res;
  1735. } else { /* Upvalue store. */
  1736. /* Convert int to number before storing. */
  1737. if (!LJ_DUALNUM && tref_isinteger(val))
  1738. val = emitir(IRTN(IR_CONV), val, IRCONV_NUM_INT);
  1739. emitir(IRT(IR_USTORE, tref_type(val)), uref, val);
  1740. if (needbarrier && tref_isgcv(val))
  1741. emitir(IRT(IR_OBAR, IRT_NIL), uref, val);
  1742. J->needsnap = 1;
  1743. return 0;
  1744. }
  1745. }
  1746. /* -- Record calls to Lua functions --------------------------------------- */
  1747. /* Check unroll limits for calls. */
  1748. static void check_call_unroll(jit_State *J, TraceNo lnk)
  1749. {
  1750. cTValue *frame = J->L->base - 1;
  1751. void *pc = mref(frame_func(frame)->l.pc, void);
  1752. int32_t depth = J->framedepth;
  1753. int32_t count = 0;
  1754. if ((J->pt->flags & PROTO_VARARG)) depth--; /* Vararg frame still missing. */
  1755. for (; depth > 0; depth--) { /* Count frames with same prototype. */
  1756. if (frame_iscont(frame)) depth--;
  1757. frame = frame_prev(frame);
  1758. if (mref(frame_func(frame)->l.pc, void) == pc)
  1759. count++;
  1760. }
  1761. if (J->pc == J->startpc) {
  1762. if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
  1763. J->pc++;
  1764. if (J->framedepth + J->retdepth == 0)
  1765. lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Tail-rec. */
  1766. else
  1767. lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno); /* Up-recursion. */
  1768. }
  1769. } else {
  1770. if (count > J->param[JIT_P_callunroll]) {
  1771. if (lnk) { /* Possible tail- or up-recursion. */
  1772. lj_trace_flush(J, lnk); /* Flush trace that only returns. */
  1773. /* Set a small, pseudo-random hotcount for a quick retry of JFUNC*. */
  1774. hotcount_set(J2GG(J), J->pc+1, lj_prng_u64(&J2G(J)->prng) & 15u);
  1775. }
  1776. lj_trace_err(J, LJ_TRERR_CUNROLL);
  1777. }
  1778. }
  1779. }
  1780. /* Record Lua function setup. */
  1781. static void rec_func_setup(jit_State *J)
  1782. {
  1783. GCproto *pt = J->pt;
  1784. BCReg s, numparams = pt->numparams;
  1785. if ((pt->flags & PROTO_NOJIT))
  1786. lj_trace_err(J, LJ_TRERR_CJITOFF);
  1787. if (J->baseslot + pt->framesize >= LJ_MAX_JSLOTS)
  1788. lj_trace_err(J, LJ_TRERR_STACKOV);
  1789. /* Fill up missing parameters with nil. */
  1790. for (s = J->maxslot; s < numparams; s++)
  1791. J->base[s] = TREF_NIL;
  1792. /* The remaining slots should never be read before they are written. */
  1793. J->maxslot = numparams;
  1794. }
  1795. /* Record Lua vararg function setup. */
  1796. static void rec_func_vararg(jit_State *J)
  1797. {
  1798. GCproto *pt = J->pt;
  1799. BCReg s, fixargs, vframe = J->maxslot+1+LJ_FR2;
  1800. lj_assertJ((pt->flags & PROTO_VARARG), "FUNCV in non-vararg function");
  1801. if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS)
  1802. lj_trace_err(J, LJ_TRERR_STACKOV);
  1803. J->base[vframe-1-LJ_FR2] = J->base[-1-LJ_FR2]; /* Copy function up. */
  1804. #if LJ_FR2
  1805. J->base[vframe-1] = TREF_FRAME;
  1806. #endif
  1807. /* Copy fixarg slots up and set their original slots to nil. */
  1808. fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot;
  1809. for (s = 0; s < fixargs; s++) {
  1810. J->base[vframe+s] = J->base[s];
  1811. J->base[s] = TREF_NIL;
  1812. }
  1813. J->maxslot = fixargs;
  1814. J->framedepth++;
  1815. J->base += vframe;
  1816. J->baseslot += vframe;
  1817. }
  1818. /* Record entry to a Lua function. */
  1819. static void rec_func_lua(jit_State *J)
  1820. {
  1821. rec_func_setup(J);
  1822. check_call_unroll(J, 0);
  1823. }
  1824. /* Record entry to an already compiled function. */
  1825. static void rec_func_jit(jit_State *J, TraceNo lnk)
  1826. {
  1827. GCtrace *T;
  1828. rec_func_setup(J);
  1829. T = traceref(J, lnk);
  1830. if (T->linktype == LJ_TRLINK_RETURN) { /* Trace returns to interpreter? */
  1831. check_call_unroll(J, lnk);
  1832. /* Temporarily unpatch JFUNC* to continue recording across function. */
  1833. J->patchins = *J->pc;
  1834. J->patchpc = (BCIns *)J->pc;
  1835. *J->patchpc = T->startins;
  1836. return;
  1837. }
  1838. J->instunroll = 0; /* Cannot continue across a compiled function. */
  1839. if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
  1840. lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Extra tail-rec. */
  1841. else
  1842. lj_record_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the function. */
  1843. }
  1844. /* -- Vararg handling ----------------------------------------------------- */
  1845. /* Detect y = select(x, ...) idiom. */
  1846. static int select_detect(jit_State *J)
  1847. {
  1848. BCIns ins = J->pc[1];
  1849. if (bc_op(ins) == BC_CALLM && bc_b(ins) == 2 && bc_c(ins) == 1) {
  1850. cTValue *func = &J->L->base[bc_a(ins)];
  1851. if (tvisfunc(func) && funcV(func)->c.ffid == FF_select) {
  1852. TRef kfunc = lj_ir_kfunc(J, funcV(func));
  1853. emitir(IRTG(IR_EQ, IRT_FUNC), getslot(J, bc_a(ins)), kfunc);
  1854. return 1;
  1855. }
  1856. }
  1857. return 0;
  1858. }
  1859. /* Record vararg instruction. */
  1860. static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
  1861. {
  1862. int32_t numparams = J->pt->numparams;
  1863. ptrdiff_t nvararg = frame_delta(J->L->base-1) - numparams - 1 - LJ_FR2;
  1864. lj_assertJ(frame_isvarg(J->L->base-1), "VARG in non-vararg frame");
  1865. if (LJ_FR2 && dst > J->maxslot)
  1866. J->base[dst-1] = 0; /* Prevent resurrection of unrelated slot. */
  1867. if (J->framedepth > 0) { /* Simple case: varargs defined on-trace. */
  1868. ptrdiff_t i;
  1869. if (nvararg < 0) nvararg = 0;
  1870. if (nresults != 1) {
  1871. if (nresults == -1) nresults = nvararg;
  1872. J->maxslot = dst + (BCReg)nresults;
  1873. } else if (dst >= J->maxslot) {
  1874. J->maxslot = dst + 1;
  1875. }
  1876. if (J->baseslot + J->maxslot >= LJ_MAX_JSLOTS)
  1877. lj_trace_err(J, LJ_TRERR_STACKOV);
  1878. for (i = 0; i < nresults; i++)
  1879. J->base[dst+i] = i < nvararg ? getslot(J, i - nvararg - 1 - LJ_FR2) : TREF_NIL;
  1880. } else { /* Unknown number of varargs passed to trace. */
  1881. TRef fr = emitir(IRTI(IR_SLOAD), LJ_FR2, IRSLOAD_READONLY|IRSLOAD_FRAME);
  1882. int32_t frofs = 8*(1+LJ_FR2+numparams)+FRAME_VARG;
  1883. if (nresults >= 0) { /* Known fixed number of results. */
  1884. ptrdiff_t i;
  1885. if (nvararg > 0) {
  1886. ptrdiff_t nload = nvararg >= nresults ? nresults : nvararg;
  1887. TRef vbase;
  1888. if (nvararg >= nresults)
  1889. emitir(IRTGI(IR_GE), fr, lj_ir_kint(J, frofs+8*(int32_t)nresults));
  1890. else
  1891. emitir(IRTGI(IR_EQ), fr,
  1892. lj_ir_kint(J, (int32_t)frame_ftsz(J->L->base-1)));
  1893. vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
  1894. vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase,
  1895. lj_ir_kintpgc(J, frofs-8*(1+LJ_FR2)));
  1896. for (i = 0; i < nload; i++) {
  1897. IRType t = itype2irt(&J->L->base[i-1-LJ_FR2-nvararg]);
  1898. J->base[dst+i] = lj_record_vload(J, vbase, (MSize)i, t);
  1899. }
  1900. } else {
  1901. emitir(IRTGI(IR_LE), fr, lj_ir_kint(J, frofs));
  1902. nvararg = 0;
  1903. }
  1904. for (i = nvararg; i < nresults; i++)
  1905. J->base[dst+i] = TREF_NIL;
  1906. if (nresults != 1 || dst >= J->maxslot) {
  1907. J->maxslot = dst + (BCReg)nresults;
  1908. }
  1909. } else if (select_detect(J)) { /* y = select(x, ...) */
  1910. TRef tridx = J->base[dst-1];
  1911. TRef tr = TREF_NIL;
  1912. ptrdiff_t idx = lj_ffrecord_select_mode(J, tridx, &J->L->base[dst-1]);
  1913. if (idx < 0) goto nyivarg;
  1914. if (idx != 0 && !tref_isinteger(tridx)) {
  1915. if (tref_isstr(tridx))
  1916. tridx = emitir(IRTG(IR_STRTO, IRT_NUM), tridx, 0);
  1917. tridx = emitir(IRTGI(IR_CONV), tridx, IRCONV_INT_NUM|IRCONV_INDEX);
  1918. }
  1919. if (idx != 0 && tref_isk(tridx)) {
  1920. emitir(IRTGI(idx <= nvararg ? IR_GE : IR_LT),
  1921. fr, lj_ir_kint(J, frofs+8*(int32_t)idx));
  1922. frofs -= 8; /* Bias for 1-based index. */
  1923. } else if (idx <= nvararg) { /* Compute size. */
  1924. TRef tmp = emitir(IRTI(IR_ADD), fr, lj_ir_kint(J, -frofs));
  1925. if (numparams)
  1926. emitir(IRTGI(IR_GE), tmp, lj_ir_kint(J, 0));
  1927. tr = emitir(IRTI(IR_BSHR), tmp, lj_ir_kint(J, 3));
  1928. if (idx != 0) {
  1929. tridx = emitir(IRTI(IR_ADD), tridx, lj_ir_kint(J, -1));
  1930. rec_idx_abc(J, tr, tridx, (uint32_t)nvararg);
  1931. }
  1932. } else {
  1933. TRef tmp = lj_ir_kint(J, frofs);
  1934. if (idx != 0) {
  1935. TRef tmp2 = emitir(IRTI(IR_BSHL), tridx, lj_ir_kint(J, 3));
  1936. tmp = emitir(IRTI(IR_ADD), tmp2, tmp);
  1937. } else {
  1938. tr = lj_ir_kint(J, 0);
  1939. }
  1940. emitir(IRTGI(IR_LT), fr, tmp);
  1941. }
  1942. if (idx != 0 && idx <= nvararg) {
  1943. IRType t;
  1944. TRef aref, vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
  1945. vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase,
  1946. lj_ir_kintpgc(J, frofs-(8<<LJ_FR2)));
  1947. t = itype2irt(&J->L->base[idx-2-LJ_FR2-nvararg]);
  1948. aref = emitir(IRT(IR_AREF, IRT_PGC), vbase, tridx);
  1949. tr = lj_record_vload(J, aref, 0, t);
  1950. }
  1951. J->base[dst-2-LJ_FR2] = tr;
  1952. J->maxslot = dst-1-LJ_FR2;
  1953. J->bcskip = 2; /* Skip CALLM + select. */
  1954. } else {
  1955. nyivarg:
  1956. setintV(&J->errinfo, BC_VARG);
  1957. lj_trace_err_info(J, LJ_TRERR_NYIBC);
  1958. }
  1959. }
  1960. }
  1961. /* -- Record allocations -------------------------------------------------- */
  1962. static TRef rec_tnew(jit_State *J, uint32_t ah)
  1963. {
  1964. uint32_t asize = ah & 0x7ff;
  1965. uint32_t hbits = ah >> 11;
  1966. TRef tr;
  1967. if (asize == 0x7ff) asize = 0x801;
  1968. tr = emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits);
  1969. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  1970. J->rbchash[(tr & (RBCHASH_SLOTS-1))].ref = tref_ref(tr);
  1971. setmref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pc, J->pc);
  1972. setgcref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
  1973. #endif
  1974. return tr;
  1975. }
  1976. /* -- Concatenation ------------------------------------------------------- */
  1977. static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot)
  1978. {
  1979. TRef *top = &J->base[topslot];
  1980. TValue savetv[5+LJ_FR2];
  1981. BCReg s;
  1982. RecordIndex ix;
  1983. lj_assertJ(baseslot < topslot, "bad CAT arg");
  1984. for (s = baseslot; s <= topslot; s++)
  1985. (void)getslot(J, s); /* Ensure all arguments have a reference. */
  1986. if (tref_isnumber_str(top[0]) && tref_isnumber_str(top[-1])) {
  1987. TRef tr, hdr, *trp, *xbase, *base = &J->base[baseslot];
  1988. /* First convert numbers to strings. */
  1989. for (trp = top; trp >= base; trp--) {
  1990. if (tref_isnumber(*trp))
  1991. *trp = emitir(IRT(IR_TOSTR, IRT_STR), *trp,
  1992. tref_isnum(*trp) ? IRTOSTR_NUM : IRTOSTR_INT);
  1993. else if (!tref_isstr(*trp))
  1994. break;
  1995. }
  1996. xbase = ++trp;
  1997. tr = hdr = emitir(IRT(IR_BUFHDR, IRT_PGC),
  1998. lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
  1999. do {
  2000. tr = emitir(IRTG(IR_BUFPUT, IRT_PGC), tr, *trp++);
  2001. } while (trp <= top);
  2002. tr = emitir(IRTG(IR_BUFSTR, IRT_STR), tr, hdr);
  2003. J->maxslot = (BCReg)(xbase - J->base);
  2004. if (xbase == base) return tr; /* Return simple concatenation result. */
  2005. /* Pass partial result. */
  2006. topslot = J->maxslot--;
  2007. *xbase = tr;
  2008. top = xbase;
  2009. setstrV(J->L, &ix.keyv, &J2G(J)->strempty); /* Simulate string result. */
  2010. } else {
  2011. J->maxslot = topslot-1;
  2012. copyTV(J->L, &ix.keyv, &J->L->base[topslot]);
  2013. }
  2014. copyTV(J->L, &ix.tabv, &J->L->base[topslot-1]);
  2015. ix.tab = top[-1];
  2016. ix.key = top[0];
  2017. memcpy(savetv, &J->L->base[topslot-1], sizeof(savetv)); /* Save slots. */
  2018. rec_mm_arith(J, &ix, MM_concat); /* Call __concat metamethod. */
  2019. memcpy(&J->L->base[topslot-1], savetv, sizeof(savetv)); /* Restore slots. */
  2020. return 0; /* No result yet. */
  2021. }
  2022. /* -- Record bytecode ops ------------------------------------------------- */
  2023. /* Prepare for comparison. */
  2024. static void rec_comp_prep(jit_State *J)
  2025. {
  2026. /* Prevent merging with snapshot #0 (GC exit) since we fixup the PC. */
  2027. if (J->cur.nsnap == 1 && J->cur.snap[0].ref == J->cur.nins)
  2028. emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
  2029. lj_snap_add(J);
  2030. }
  2031. /* Fixup comparison. */
  2032. static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
  2033. {
  2034. BCIns jmpins = pc[1];
  2035. const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
  2036. SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
  2037. /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
  2038. #if LJ_FR2
  2039. SnapEntry *flink = &J->cur.snapmap[snap->mapofs + snap->nent];
  2040. uint64_t pcbase;
  2041. memcpy(&pcbase, flink, sizeof(uint64_t));
  2042. pcbase = (pcbase & 0xff) | (u64ptr(npc) << 8);
  2043. memcpy(flink, &pcbase, sizeof(uint64_t));
  2044. #else
  2045. J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
  2046. #endif
  2047. J->needsnap = 1;
  2048. if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
  2049. lj_snap_shrink(J); /* Shrink last snapshot if possible. */
  2050. }
  2051. /* Record the next bytecode instruction (_before_ it's executed). */
  2052. void lj_record_ins(jit_State *J)
  2053. {
  2054. cTValue *lbase;
  2055. RecordIndex ix;
  2056. const BCIns *pc;
  2057. BCIns ins;
  2058. BCOp op;
  2059. TRef ra, rb, rc;
  2060. /* Perform post-processing action before recording the next instruction. */
  2061. if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
  2062. switch (J->postproc) {
  2063. case LJ_POST_FIXCOMP: /* Fixup comparison. */
  2064. pc = (const BCIns *)(uintptr_t)J2G(J)->tmptv.u64;
  2065. rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
  2066. /* fallthrough */
  2067. case LJ_POST_FIXGUARD: /* Fixup and emit pending guard. */
  2068. case LJ_POST_FIXGUARDSNAP: /* Fixup and emit pending guard and snapshot. */
  2069. if (!tvistruecond(&J2G(J)->tmptv2)) {
  2070. J->fold.ins.o ^= 1; /* Flip guard to opposite. */
  2071. if (J->postproc == LJ_POST_FIXGUARDSNAP) {
  2072. SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
  2073. J->cur.snapmap[snap->mapofs+snap->nent-1]--; /* False -> true. */
  2074. }
  2075. }
  2076. lj_opt_fold(J); /* Emit pending guard. */
  2077. /* fallthrough */
  2078. case LJ_POST_FIXBOOL:
  2079. if (!tvistruecond(&J2G(J)->tmptv2)) {
  2080. BCReg s;
  2081. TValue *tv = J->L->base;
  2082. for (s = 0; s < J->maxslot; s++) /* Fixup stack slot (if any). */
  2083. if (J->base[s] == TREF_TRUE && tvisfalse(&tv[s])) {
  2084. J->base[s] = TREF_FALSE;
  2085. break;
  2086. }
  2087. }
  2088. break;
  2089. case LJ_POST_FIXCONST:
  2090. {
  2091. BCReg s;
  2092. TValue *tv = J->L->base;
  2093. for (s = 0; s < J->maxslot; s++) /* Constify stack slots (if any). */
  2094. if (J->base[s] == TREF_NIL && !tvisnil(&tv[s]))
  2095. J->base[s] = lj_record_constify(J, &tv[s]);
  2096. }
  2097. break;
  2098. case LJ_POST_FFRETRY: /* Suppress recording of retried fast function. */
  2099. if (bc_op(*J->pc) >= BC__MAX)
  2100. return;
  2101. break;
  2102. default: lj_assertJ(0, "bad post-processing mode"); break;
  2103. }
  2104. J->postproc = LJ_POST_NONE;
  2105. }
  2106. /* Need snapshot before recording next bytecode (e.g. after a store). */
  2107. if (J->needsnap) {
  2108. J->needsnap = 0;
  2109. if (J->pt) lj_snap_purge(J);
  2110. lj_snap_add(J);
  2111. J->mergesnap = 1;
  2112. }
  2113. /* Skip some bytecodes. */
  2114. if (LJ_UNLIKELY(J->bcskip > 0)) {
  2115. J->bcskip--;
  2116. return;
  2117. }
  2118. /* Record only closed loops for root traces. */
  2119. pc = J->pc;
  2120. if (J->framedepth == 0 &&
  2121. (MSize)((char *)pc - (char *)J->bc_min) >= J->bc_extent)
  2122. lj_trace_err(J, LJ_TRERR_LLEAVE);
  2123. #ifdef LUA_USE_ASSERT
  2124. rec_check_slots(J);
  2125. rec_check_ir(J);
  2126. #endif
  2127. #if LJ_HASPROFILE
  2128. rec_profile_ins(J, pc);
  2129. #endif
  2130. /* Keep a copy of the runtime values of var/num/str operands. */
  2131. #define rav (&ix.valv)
  2132. #define rbv (&ix.tabv)
  2133. #define rcv (&ix.keyv)
  2134. lbase = J->L->base;
  2135. ins = *pc;
  2136. op = bc_op(ins);
  2137. ra = bc_a(ins);
  2138. ix.val = 0;
  2139. switch (bcmode_a(op)) {
  2140. case BCMvar:
  2141. copyTV(J->L, rav, &lbase[ra]); ix.val = ra = getslot(J, ra); break;
  2142. default: break; /* Handled later. */
  2143. }
  2144. rb = bc_b(ins);
  2145. rc = bc_c(ins);
  2146. switch (bcmode_b(op)) {
  2147. case BCMnone: rb = 0; rc = bc_d(ins); break; /* Upgrade rc to 'rd'. */
  2148. case BCMvar:
  2149. copyTV(J->L, rbv, &lbase[rb]); ix.tab = rb = getslot(J, rb); break;
  2150. default: break; /* Handled later. */
  2151. }
  2152. switch (bcmode_c(op)) {
  2153. case BCMvar:
  2154. copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
  2155. case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
  2156. case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
  2157. copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
  2158. tv->u32.hi == LJ_KEYINDEX ? (lj_ir_kint(J, 0) | TREF_KEYINDEX) :
  2159. lj_ir_knumint(J, numV(tv)); } break;
  2160. case BCMstr: { GCstr *s = gco2str(proto_kgc(J->pt, ~(ptrdiff_t)rc));
  2161. setstrV(J->L, rcv, s); ix.key = rc = lj_ir_kstr(J, s); } break;
  2162. default: break; /* Handled later. */
  2163. }
  2164. switch (op) {
  2165. /* -- Comparison ops ---------------------------------------------------- */
  2166. case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
  2167. #if LJ_HASFFI
  2168. if (tref_iscdata(ra) || tref_iscdata(rc)) {
  2169. rec_mm_comp_cdata(J, &ix, op, ((int)op & 2) ? MM_le : MM_lt);
  2170. break;
  2171. }
  2172. #endif
  2173. /* Emit nothing for two numeric or string consts. */
  2174. if (!(tref_isk2(ra,rc) && tref_isnumber_str(ra) && tref_isnumber_str(rc))) {
  2175. IRType ta = tref_isinteger(ra) ? IRT_INT : tref_type(ra);
  2176. IRType tc = tref_isinteger(rc) ? IRT_INT : tref_type(rc);
  2177. int irop;
  2178. if (ta != tc) {
  2179. /* Widen mixed number/int comparisons to number/number comparison. */
  2180. if (ta == IRT_INT && tc == IRT_NUM) {
  2181. ra = emitir(IRTN(IR_CONV), ra, IRCONV_NUM_INT);
  2182. ta = IRT_NUM;
  2183. } else if (ta == IRT_NUM && tc == IRT_INT) {
  2184. rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
  2185. } else if (LJ_52) {
  2186. ta = IRT_NIL; /* Force metamethod for different types. */
  2187. } else if (!((ta == IRT_FALSE || ta == IRT_TRUE) &&
  2188. (tc == IRT_FALSE || tc == IRT_TRUE))) {
  2189. break; /* Interpreter will throw for two different types. */
  2190. }
  2191. }
  2192. rec_comp_prep(J);
  2193. irop = (int)op - (int)BC_ISLT + (int)IR_LT;
  2194. if (ta == IRT_NUM) {
  2195. if ((irop & 1)) irop ^= 4; /* ISGE/ISGT are unordered. */
  2196. if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
  2197. irop ^= 5;
  2198. } else if (ta == IRT_INT) {
  2199. if (!lj_ir_numcmp(numberVnum(rav), numberVnum(rcv), (IROp)irop))
  2200. irop ^= 1;
  2201. } else if (ta == IRT_STR) {
  2202. if (!lj_ir_strcmp(strV(rav), strV(rcv), (IROp)irop)) irop ^= 1;
  2203. ra = lj_ir_call(J, IRCALL_lj_str_cmp, ra, rc);
  2204. rc = lj_ir_kint(J, 0);
  2205. ta = IRT_INT;
  2206. } else {
  2207. rec_mm_comp(J, &ix, (int)op);
  2208. break;
  2209. }
  2210. emitir(IRTG(irop, ta), ra, rc);
  2211. rec_comp_fixup(J, J->pc, ((int)op ^ irop) & 1);
  2212. }
  2213. break;
  2214. case BC_ISEQV: case BC_ISNEV:
  2215. case BC_ISEQS: case BC_ISNES:
  2216. case BC_ISEQN: case BC_ISNEN:
  2217. case BC_ISEQP: case BC_ISNEP:
  2218. #if LJ_HASFFI
  2219. if (tref_iscdata(ra) || tref_iscdata(rc)) {
  2220. rec_mm_comp_cdata(J, &ix, op, MM_eq);
  2221. break;
  2222. }
  2223. #endif
  2224. /* Emit nothing for two non-table, non-udata consts. */
  2225. if (!(tref_isk2(ra, rc) && !(tref_istab(ra) || tref_isudata(ra)))) {
  2226. int diff;
  2227. rec_comp_prep(J);
  2228. diff = lj_record_objcmp(J, ra, rc, rav, rcv);
  2229. if (diff == 2 || !(tref_istab(ra) || tref_isudata(ra)))
  2230. rec_comp_fixup(J, J->pc, ((int)op & 1) == !diff);
  2231. else if (diff == 1) /* Only check __eq if different, but same type. */
  2232. rec_mm_equal(J, &ix, (int)op);
  2233. }
  2234. break;
  2235. /* -- Unary test and copy ops ------------------------------------------- */
  2236. case BC_ISTC: case BC_ISFC:
  2237. if ((op & 1) == tref_istruecond(rc))
  2238. rc = 0; /* Don't store if condition is not true. */
  2239. /* fallthrough */
  2240. case BC_IST: case BC_ISF: /* Type specialization suffices. */
  2241. if (bc_a(pc[1]) < J->maxslot)
  2242. J->maxslot = bc_a(pc[1]); /* Shrink used slots. */
  2243. break;
  2244. case BC_ISTYPE: case BC_ISNUM:
  2245. /* These coercions need to correspond with lj_meta_istype(). */
  2246. if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
  2247. ra = lj_opt_narrow_toint(J, ra);
  2248. else if (rc == ~LJ_TNUMX+2)
  2249. ra = lj_ir_tonum(J, ra);
  2250. else if (rc == ~LJ_TSTR+1)
  2251. ra = lj_ir_tostr(J, ra);
  2252. /* else: type specialization suffices. */
  2253. J->base[bc_a(ins)] = ra;
  2254. break;
  2255. /* -- Unary ops --------------------------------------------------------- */
  2256. case BC_NOT:
  2257. /* Type specialization already forces const result. */
  2258. rc = tref_istruecond(rc) ? TREF_FALSE : TREF_TRUE;
  2259. break;
  2260. case BC_LEN:
  2261. if (tref_isstr(rc))
  2262. rc = emitir(IRTI(IR_FLOAD), rc, IRFL_STR_LEN);
  2263. else if (!LJ_52 && tref_istab(rc))
  2264. rc = emitir(IRTI(IR_ALEN), rc, TREF_NIL);
  2265. else
  2266. rc = rec_mm_len(J, rc, rcv);
  2267. break;
  2268. /* -- Arithmetic ops ---------------------------------------------------- */
  2269. case BC_UNM:
  2270. if (tref_isnumber_str(rc)) {
  2271. rc = lj_opt_narrow_unm(J, rc, rcv);
  2272. } else {
  2273. ix.tab = rc;
  2274. copyTV(J->L, &ix.tabv, rcv);
  2275. rc = rec_mm_arith(J, &ix, MM_unm);
  2276. }
  2277. break;
  2278. case BC_ADDNV: case BC_SUBNV: case BC_MULNV: case BC_DIVNV: case BC_MODNV:
  2279. /* Swap rb/rc and rbv/rcv. rav is temp. */
  2280. ix.tab = rc; ix.key = rc = rb; rb = ix.tab;
  2281. copyTV(J->L, rav, rbv);
  2282. copyTV(J->L, rbv, rcv);
  2283. copyTV(J->L, rcv, rav);
  2284. if (op == BC_MODNV)
  2285. goto recmod;
  2286. /* fallthrough */
  2287. case BC_ADDVN: case BC_SUBVN: case BC_MULVN: case BC_DIVVN:
  2288. case BC_ADDVV: case BC_SUBVV: case BC_MULVV: case BC_DIVVV: {
  2289. MMS mm = bcmode_mm(op);
  2290. if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
  2291. rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv,
  2292. (int)mm - (int)MM_add + (int)IR_ADD);
  2293. else
  2294. rc = rec_mm_arith(J, &ix, mm);
  2295. break;
  2296. }
  2297. case BC_MODVN: case BC_MODVV:
  2298. recmod:
  2299. if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
  2300. rc = lj_opt_narrow_mod(J, rb, rc, rbv, rcv);
  2301. else
  2302. rc = rec_mm_arith(J, &ix, MM_mod);
  2303. break;
  2304. case BC_POW:
  2305. if (tref_isnumber_str(rb) && tref_isnumber_str(rc))
  2306. rc = lj_opt_narrow_arith(J, rb, rc, rbv, rcv, IR_POW);
  2307. else
  2308. rc = rec_mm_arith(J, &ix, MM_pow);
  2309. break;
  2310. /* -- Miscellaneous ops ------------------------------------------------- */
  2311. case BC_CAT:
  2312. rc = rec_cat(J, rb, rc);
  2313. break;
  2314. /* -- Constant and move ops --------------------------------------------- */
  2315. case BC_MOV:
  2316. /* Clear gap of method call to avoid resurrecting previous refs. */
  2317. if (ra > J->maxslot) {
  2318. #if LJ_FR2
  2319. memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
  2320. #else
  2321. J->base[ra-1] = 0;
  2322. #endif
  2323. }
  2324. break;
  2325. case BC_KSTR: case BC_KNUM: case BC_KPRI:
  2326. break;
  2327. case BC_KSHORT:
  2328. rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
  2329. break;
  2330. case BC_KNIL:
  2331. if (LJ_FR2 && ra > J->maxslot)
  2332. J->base[ra-1] = 0;
  2333. while (ra <= rc)
  2334. J->base[ra++] = TREF_NIL;
  2335. if (rc >= J->maxslot) J->maxslot = rc+1;
  2336. break;
  2337. #if LJ_HASFFI
  2338. case BC_KCDATA:
  2339. rc = lj_ir_kgc(J, proto_kgc(J->pt, ~(ptrdiff_t)rc), IRT_CDATA);
  2340. break;
  2341. #endif
  2342. /* -- Upvalue and function ops ------------------------------------------ */
  2343. case BC_UGET:
  2344. rc = rec_upvalue(J, rc, 0);
  2345. break;
  2346. case BC_USETV: case BC_USETS: case BC_USETN: case BC_USETP:
  2347. rec_upvalue(J, ra, rc);
  2348. break;
  2349. /* -- Table ops --------------------------------------------------------- */
  2350. case BC_GGET: case BC_GSET:
  2351. settabV(J->L, &ix.tabv, tabref(J->fn->l.env));
  2352. ix.tab = emitir(IRT(IR_FLOAD, IRT_TAB), getcurrf(J), IRFL_FUNC_ENV);
  2353. ix.idxchain = LJ_MAX_IDXCHAIN;
  2354. rc = lj_record_idx(J, &ix);
  2355. break;
  2356. case BC_TGETB: case BC_TSETB:
  2357. setintV(&ix.keyv, (int32_t)rc);
  2358. ix.key = lj_ir_kint(J, (int32_t)rc);
  2359. /* fallthrough */
  2360. case BC_TGETV: case BC_TGETS: case BC_TSETV: case BC_TSETS:
  2361. ix.idxchain = LJ_MAX_IDXCHAIN;
  2362. rc = lj_record_idx(J, &ix);
  2363. break;
  2364. case BC_TGETR: case BC_TSETR:
  2365. ix.idxchain = 0;
  2366. rc = lj_record_idx(J, &ix);
  2367. break;
  2368. case BC_TSETM:
  2369. rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
  2370. J->maxslot = ra; /* The table slot at ra-1 is the highest used slot. */
  2371. break;
  2372. case BC_TNEW:
  2373. rc = rec_tnew(J, rc);
  2374. break;
  2375. case BC_TDUP:
  2376. rc = emitir(IRTG(IR_TDUP, IRT_TAB),
  2377. lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
  2378. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  2379. J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
  2380. setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
  2381. setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
  2382. #endif
  2383. break;
  2384. /* -- Calls and vararg handling ----------------------------------------- */
  2385. case BC_ITERC:
  2386. J->base[ra] = getslot(J, ra-3);
  2387. J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
  2388. J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
  2389. { /* Do the actual copy now because lj_record_call needs the values. */
  2390. TValue *b = &J->L->base[ra];
  2391. copyTV(J->L, b, b-3);
  2392. copyTV(J->L, b+1+LJ_FR2, b-2);
  2393. copyTV(J->L, b+2+LJ_FR2, b-1);
  2394. }
  2395. lj_record_call(J, ra, (ptrdiff_t)rc-1);
  2396. break;
  2397. /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
  2398. case BC_CALLM:
  2399. rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
  2400. /* fallthrough */
  2401. case BC_CALL:
  2402. lj_record_call(J, ra, (ptrdiff_t)rc-1);
  2403. break;
  2404. case BC_CALLMT:
  2405. rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
  2406. /* fallthrough */
  2407. case BC_CALLT:
  2408. lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
  2409. break;
  2410. case BC_VARG:
  2411. rec_varg(J, ra, (ptrdiff_t)rb-1);
  2412. break;
  2413. /* -- Returns ----------------------------------------------------------- */
  2414. case BC_RETM:
  2415. /* L->top is set to L->base+ra+rc+NRESULTS-1, see lj_dispatch_ins(). */
  2416. rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
  2417. /* fallthrough */
  2418. case BC_RET: case BC_RET0: case BC_RET1:
  2419. #if LJ_HASPROFILE
  2420. rec_profile_ret(J);
  2421. #endif
  2422. lj_record_ret(J, ra, (ptrdiff_t)rc-1);
  2423. break;
  2424. /* -- Loops and branches ------------------------------------------------ */
  2425. case BC_FORI:
  2426. if (rec_for(J, pc, 0) != LOOPEV_LEAVE)
  2427. J->loopref = J->cur.nins;
  2428. break;
  2429. case BC_JFORI:
  2430. lj_assertJ(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL,
  2431. "JFORI does not point to JFORL");
  2432. if (rec_for(J, pc, 0) != LOOPEV_LEAVE) /* Link to existing loop. */
  2433. lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
  2434. /* Continue tracing if the loop is not entered. */
  2435. break;
  2436. case BC_FORL:
  2437. rec_loop_interp(J, pc, rec_for(J, pc+((ptrdiff_t)rc-BCBIAS_J), 1));
  2438. break;
  2439. case BC_ITERL:
  2440. rec_loop_interp(J, pc, rec_iterl(J, *pc));
  2441. break;
  2442. case BC_ITERN:
  2443. rec_loop_interp(J, pc, rec_itern(J, ra, rb));
  2444. break;
  2445. case BC_LOOP:
  2446. rec_loop_interp(J, pc, rec_loop(J, ra, 1));
  2447. break;
  2448. case BC_JFORL:
  2449. rec_loop_jit(J, rc, rec_for(J, pc+bc_j(traceref(J, rc)->startins), 1));
  2450. break;
  2451. case BC_JITERL:
  2452. rec_loop_jit(J, rc, rec_iterl(J, traceref(J, rc)->startins));
  2453. break;
  2454. case BC_JLOOP:
  2455. rec_loop_jit(J, rc, rec_loop(J, ra,
  2456. !bc_isret(bc_op(traceref(J, rc)->startins)) &&
  2457. bc_op(traceref(J, rc)->startins) != BC_ITERN));
  2458. break;
  2459. case BC_IFORL:
  2460. case BC_IITERL:
  2461. case BC_ILOOP:
  2462. case BC_IFUNCF:
  2463. case BC_IFUNCV:
  2464. lj_trace_err(J, LJ_TRERR_BLACKL);
  2465. break;
  2466. case BC_JMP:
  2467. if (ra < J->maxslot)
  2468. J->maxslot = ra; /* Shrink used slots. */
  2469. break;
  2470. case BC_ISNEXT:
  2471. rec_isnext(J, ra);
  2472. break;
  2473. /* -- Function headers -------------------------------------------------- */
  2474. case BC_FUNCF:
  2475. rec_func_lua(J);
  2476. break;
  2477. case BC_JFUNCF:
  2478. rec_func_jit(J, rc);
  2479. break;
  2480. case BC_FUNCV:
  2481. rec_func_vararg(J);
  2482. rec_func_lua(J);
  2483. break;
  2484. case BC_JFUNCV:
  2485. /* Cannot happen. No hotcall counting for varag funcs. */
  2486. lj_assertJ(0, "unsupported vararg hotcall");
  2487. break;
  2488. case BC_FUNCC:
  2489. case BC_FUNCCW:
  2490. lj_ffrecord_func(J);
  2491. break;
  2492. default:
  2493. if (op >= BC__MAX) {
  2494. lj_ffrecord_func(J);
  2495. break;
  2496. }
  2497. /* fallthrough */
  2498. case BC_UCLO:
  2499. case BC_FNEW:
  2500. setintV(&J->errinfo, (int32_t)op);
  2501. lj_trace_err_info(J, LJ_TRERR_NYIBC);
  2502. break;
  2503. }
  2504. /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
  2505. if (bcmode_a(op) == BCMdst && rc) {
  2506. J->base[ra] = rc;
  2507. if (ra >= J->maxslot) {
  2508. #if LJ_FR2
  2509. if (ra > J->maxslot) J->base[ra-1] = 0;
  2510. #endif
  2511. J->maxslot = ra+1;
  2512. }
  2513. }
  2514. #undef rav
  2515. #undef rbv
  2516. #undef rcv
  2517. /* Limit the number of recorded IR instructions and constants. */
  2518. if (J->cur.nins > REF_FIRST+(IRRef)J->param[JIT_P_maxrecord] ||
  2519. J->cur.nk < REF_BIAS-(IRRef)J->param[JIT_P_maxirconst])
  2520. lj_trace_err(J, LJ_TRERR_TRACEOV);
  2521. }
  2522. /* -- Recording setup ----------------------------------------------------- */
  2523. /* Setup recording for a root trace started by a hot loop. */
  2524. static const BCIns *rec_setup_root(jit_State *J)
  2525. {
  2526. /* Determine the next PC and the bytecode range for the loop. */
  2527. const BCIns *pcj, *pc = J->pc;
  2528. BCIns ins = *pc;
  2529. BCReg ra = bc_a(ins);
  2530. switch (bc_op(ins)) {
  2531. case BC_FORL:
  2532. J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
  2533. pc += 1+bc_j(ins);
  2534. J->bc_min = pc;
  2535. break;
  2536. case BC_ITERL:
  2537. if (bc_op(pc[-1]) == BC_JLOOP)
  2538. lj_trace_err(J, LJ_TRERR_LINNER);
  2539. lj_assertJ(bc_op(pc[-1]) == BC_ITERC, "no ITERC before ITERL");
  2540. J->maxslot = ra + bc_b(pc[-1]) - 1;
  2541. J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
  2542. pc += 1+bc_j(ins);
  2543. lj_assertJ(bc_op(pc[-1]) == BC_JMP, "ITERL does not point to JMP+1");
  2544. J->bc_min = pc;
  2545. break;
  2546. case BC_ITERN:
  2547. lj_assertJ(bc_op(pc[1]) == BC_ITERL, "no ITERL after ITERN");
  2548. J->maxslot = ra;
  2549. J->bc_extent = (MSize)(-bc_j(pc[1]))*sizeof(BCIns);
  2550. J->bc_min = pc+2 + bc_j(pc[1]);
  2551. J->state = LJ_TRACE_RECORD_1ST; /* Record the first ITERN, too. */
  2552. break;
  2553. case BC_LOOP:
  2554. /* Only check BC range for real loops, but not for "repeat until true". */
  2555. pcj = pc + bc_j(ins);
  2556. ins = *pcj;
  2557. if (bc_op(ins) == BC_JMP && bc_j(ins) < 0) {
  2558. J->bc_min = pcj+1 + bc_j(ins);
  2559. J->bc_extent = (MSize)(-bc_j(ins))*sizeof(BCIns);
  2560. }
  2561. J->maxslot = ra;
  2562. pc++;
  2563. break;
  2564. case BC_RET:
  2565. case BC_RET0:
  2566. case BC_RET1:
  2567. /* No bytecode range check for down-recursive root traces. */
  2568. J->maxslot = ra + bc_d(ins) - 1;
  2569. break;
  2570. case BC_FUNCF:
  2571. /* No bytecode range check for root traces started by a hot call. */
  2572. J->maxslot = J->pt->numparams;
  2573. pc++;
  2574. break;
  2575. case BC_CALLM:
  2576. case BC_CALL:
  2577. case BC_ITERC:
  2578. /* No bytecode range check for stitched traces. */
  2579. pc++;
  2580. break;
  2581. default:
  2582. lj_assertJ(0, "bad root trace start bytecode %d", bc_op(ins));
  2583. break;
  2584. }
  2585. return pc;
  2586. }
  2587. /* Setup for recording a new trace. */
  2588. void lj_record_setup(jit_State *J)
  2589. {
  2590. uint32_t i;
  2591. /* Initialize state related to current trace. */
  2592. memset(J->slot, 0, sizeof(J->slot));
  2593. memset(J->chain, 0, sizeof(J->chain));
  2594. #ifdef LUAJIT_ENABLE_TABLE_BUMP
  2595. memset(J->rbchash, 0, sizeof(J->rbchash));
  2596. #endif
  2597. memset(J->bpropcache, 0, sizeof(J->bpropcache));
  2598. J->scev.idx = REF_NIL;
  2599. setmref(J->scev.pc, NULL);
  2600. J->baseslot = 1+LJ_FR2; /* Invoking function is at base[-1-LJ_FR2]. */
  2601. J->base = J->slot + J->baseslot;
  2602. J->maxslot = 0;
  2603. J->framedepth = 0;
  2604. J->retdepth = 0;
  2605. J->instunroll = J->param[JIT_P_instunroll];
  2606. J->loopunroll = J->param[JIT_P_loopunroll];
  2607. J->tailcalled = 0;
  2608. J->loopref = 0;
  2609. J->bc_min = NULL; /* Means no limit. */
  2610. J->bc_extent = ~(MSize)0;
  2611. /* Emit instructions for fixed references. Also triggers initial IR alloc. */
  2612. emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
  2613. for (i = 0; i <= 2; i++) {
  2614. IRIns *ir = IR(REF_NIL-i);
  2615. ir->i = 0;
  2616. ir->t.irt = (uint8_t)(IRT_NIL+i);
  2617. ir->o = IR_KPRI;
  2618. ir->prev = 0;
  2619. }
  2620. J->cur.nk = REF_TRUE;
  2621. J->startpc = J->pc;
  2622. setmref(J->cur.startpc, J->pc);
  2623. if (J->parent) { /* Side trace. */
  2624. GCtrace *T = traceref(J, J->parent);
  2625. TraceNo root = T->root ? T->root : J->parent;
  2626. J->cur.root = (uint16_t)root;
  2627. J->cur.startins = BCINS_AD(BC_JMP, 0, 0);
  2628. /* Check whether we could at least potentially form an extra loop. */
  2629. if (J->exitno == 0 && T->snap[0].nent == 0) {
  2630. /* We can narrow a FORL for some side traces, too. */
  2631. if (J->pc > proto_bc(J->pt) && bc_op(J->pc[-1]) == BC_JFORI &&
  2632. bc_d(J->pc[bc_j(J->pc[-1])-1]) == root) {
  2633. lj_snap_add(J);
  2634. rec_for_loop(J, J->pc-1, &J->scev, 1);
  2635. goto sidecheck;
  2636. }
  2637. } else {
  2638. J->startpc = NULL; /* Prevent forming an extra loop. */
  2639. }
  2640. lj_snap_replay(J, T);
  2641. sidecheck:
  2642. if ((traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
  2643. T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
  2644. J->param[JIT_P_tryside])) {
  2645. if (bc_op(*J->pc) == BC_JLOOP) {
  2646. BCIns startins = traceref(J, bc_d(*J->pc))->startins;
  2647. if (bc_op(startins) == BC_ITERN)
  2648. rec_itern(J, bc_a(startins), bc_b(startins));
  2649. }
  2650. lj_record_stop(J, LJ_TRLINK_INTERP, 0);
  2651. }
  2652. } else { /* Root trace. */
  2653. J->cur.root = 0;
  2654. J->cur.startins = *J->pc;
  2655. J->pc = rec_setup_root(J);
  2656. /* Note: the loop instruction itself is recorded at the end and not
  2657. ** at the start! So snapshot #0 needs to point to the *next* instruction.
  2658. ** The one exception is BC_ITERN, which sets LJ_TRACE_RECORD_1ST.
  2659. */
  2660. lj_snap_add(J);
  2661. if (bc_op(J->cur.startins) == BC_FORL)
  2662. rec_for_loop(J, J->pc-1, &J->scev, 1);
  2663. else if (bc_op(J->cur.startins) == BC_ITERC)
  2664. J->startpc = NULL;
  2665. if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
  2666. lj_trace_err(J, LJ_TRERR_STACKOV);
  2667. }
  2668. #if LJ_HASPROFILE
  2669. J->prev_pt = NULL;
  2670. J->prev_line = -1;
  2671. #endif
  2672. #ifdef LUAJIT_ENABLE_CHECKHOOK
  2673. /* Regularly check for instruction/line hooks from compiled code and
  2674. ** exit to the interpreter if the hooks are set.
  2675. **
  2676. ** This is a compile-time option and disabled by default, since the
  2677. ** hook checks may be quite expensive in tight loops.
  2678. **
  2679. ** Note this is only useful if hooks are *not* set most of the time.
  2680. ** Use this only if you want to *asynchronously* interrupt the execution.
  2681. **
  2682. ** You can set the instruction hook via lua_sethook() with a count of 1
  2683. ** from a signal handler or another native thread. Please have a look
  2684. ** at the first few functions in luajit.c for an example (Ctrl-C handler).
  2685. */
  2686. {
  2687. TRef tr = emitir(IRT(IR_XLOAD, IRT_U8),
  2688. lj_ir_kptr(J, &J2G(J)->hookmask), IRXLOAD_VOLATILE);
  2689. tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (LUA_MASKLINE|LUA_MASKCOUNT)));
  2690. emitir(IRTGI(IR_EQ), tr, lj_ir_kint(J, 0));
  2691. }
  2692. #endif
  2693. }
  2694. #undef IR
  2695. #undef emitir_raw
  2696. #undef emitir
  2697. #endif