lj_asm.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631
  1. /*
  2. ** IR assembler (SSA IR -> machine code).
  3. ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
  4. */
  5. #define lj_asm_c
  6. #define LUA_CORE
  7. #include "lj_obj.h"
  8. #if LJ_HASJIT
  9. #include "lj_gc.h"
  10. #include "lj_buf.h"
  11. #include "lj_str.h"
  12. #include "lj_tab.h"
  13. #include "lj_frame.h"
  14. #if LJ_HASFFI
  15. #include "lj_ctype.h"
  16. #endif
  17. #include "lj_ir.h"
  18. #include "lj_jit.h"
  19. #include "lj_ircall.h"
  20. #include "lj_iropt.h"
  21. #include "lj_mcode.h"
  22. #include "lj_trace.h"
  23. #include "lj_snap.h"
  24. #include "lj_asm.h"
  25. #include "lj_dispatch.h"
  26. #include "lj_vm.h"
  27. #include "lj_target.h"
  28. #include "lj_prng.h"
  29. #ifdef LUA_USE_ASSERT
  30. #include <stdio.h>
  31. #endif
  32. /* -- Assembler state and common macros ----------------------------------- */
  33. /* Assembler state. */
  34. typedef struct ASMState {
  35. RegCost cost[RID_MAX]; /* Reference and blended allocation cost for regs. */
  36. MCode *mcp; /* Current MCode pointer (grows down). */
  37. MCode *mclim; /* Lower limit for MCode memory + red zone. */
  38. #ifdef LUA_USE_ASSERT
  39. MCode *mcp_prev; /* Red zone overflow check. */
  40. #endif
  41. IRIns *ir; /* Copy of pointer to IR instructions/constants. */
  42. jit_State *J; /* JIT compiler state. */
  43. #if LJ_TARGET_X86ORX64
  44. x86ModRM mrm; /* Fused x86 address operand. */
  45. #endif
  46. RegSet freeset; /* Set of free registers. */
  47. RegSet modset; /* Set of registers modified inside the loop. */
  48. RegSet weakset; /* Set of weakly referenced registers. */
  49. RegSet phiset; /* Set of PHI registers. */
  50. uint32_t flags; /* Copy of JIT compiler flags. */
  51. int loopinv; /* Loop branch inversion (0:no, 1:yes, 2:yes+CC_P). */
  52. int32_t evenspill; /* Next even spill slot. */
  53. int32_t oddspill; /* Next odd spill slot (or 0). */
  54. IRRef curins; /* Reference of current instruction. */
  55. IRRef stopins; /* Stop assembly before hitting this instruction. */
  56. IRRef orignins; /* Original T->nins. */
  57. IRRef snapref; /* Current snapshot is active after this reference. */
  58. IRRef snaprename; /* Rename highwater mark for snapshot check. */
  59. SnapNo snapno; /* Current snapshot number. */
  60. SnapNo loopsnapno; /* Loop snapshot number. */
  61. int snapalloc; /* Current snapshot needs allocation. */
  62. BloomFilter snapfilt1, snapfilt2; /* Filled with snapshot refs. */
  63. IRRef fuseref; /* Fusion limit (loopref, 0 or FUSE_DISABLED). */
  64. IRRef sectref; /* Section base reference (loopref or 0). */
  65. IRRef loopref; /* Reference of LOOP instruction (or 0). */
  66. BCReg topslot; /* Number of slots for stack check (unless 0). */
  67. int32_t gcsteps; /* Accumulated number of GC steps (per section). */
  68. GCtrace *T; /* Trace to assemble. */
  69. GCtrace *parent; /* Parent trace (or NULL). */
  70. MCode *mcbot; /* Bottom of reserved MCode. */
  71. MCode *mctop; /* Top of generated MCode. */
  72. MCode *mctoporig; /* Original top of generated MCode. */
  73. MCode *mcloop; /* Pointer to loop MCode (or NULL). */
  74. MCode *invmcp; /* Points to invertible loop branch (or NULL). */
  75. MCode *flagmcp; /* Pending opportunity to merge flag setting ins. */
  76. MCode *realign; /* Realign loop if not NULL. */
  77. #ifdef LUAJIT_RANDOM_RA
  78. /* Randomize register allocation. OK for fuzz testing, not for production. */
  79. uint64_t prngbits;
  80. PRNGState prngstate;
  81. #endif
  82. #ifdef RID_NUM_KREF
  83. intptr_t krefk[RID_NUM_KREF];
  84. #endif
  85. IRRef1 phireg[RID_MAX]; /* PHI register references. */
  86. uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */
  87. } ASMState;
  88. #ifdef LUA_USE_ASSERT
  89. #define lj_assertA(c, ...) lj_assertG_(J2G(as->J), (c), __VA_ARGS__)
  90. #else
  91. #define lj_assertA(c, ...) ((void)as)
  92. #endif
  93. #define IR(ref) (&as->ir[(ref)])
  94. #define ASMREF_TMP1 REF_TRUE /* Temp. register. */
  95. #define ASMREF_TMP2 REF_FALSE /* Temp. register. */
  96. #define ASMREF_L REF_NIL /* Stores register for L. */
  97. /* Check for variant to invariant references. */
  98. #define iscrossref(as, ref) ((ref) < as->sectref)
  99. /* Inhibit memory op fusion from variant to invariant references. */
  100. #define FUSE_DISABLED (~(IRRef)0)
  101. #define mayfuse(as, ref) ((ref) > as->fuseref)
  102. #define neverfuse(as) (as->fuseref == FUSE_DISABLED)
  103. #define canfuse(as, ir) (!neverfuse(as) && !irt_isphi((ir)->t))
  104. #define opisfusableload(o) \
  105. ((o) == IR_ALOAD || (o) == IR_HLOAD || (o) == IR_ULOAD || \
  106. (o) == IR_FLOAD || (o) == IR_XLOAD || (o) == IR_SLOAD || (o) == IR_VLOAD)
  107. /* Sparse limit checks using a red zone before the actual limit. */
  108. #define MCLIM_REDZONE 64
  109. static LJ_NORET LJ_NOINLINE void asm_mclimit(ASMState *as)
  110. {
  111. lj_mcode_limiterr(as->J, (size_t)(as->mctop - as->mcp + 4*MCLIM_REDZONE));
  112. }
  113. static LJ_AINLINE void checkmclim(ASMState *as)
  114. {
  115. #ifdef LUA_USE_ASSERT
  116. if (as->mcp + MCLIM_REDZONE < as->mcp_prev) {
  117. IRIns *ir = IR(as->curins+1);
  118. lj_assertA(0, "red zone overflow: %p IR %04d %02d %04d %04d\n", as->mcp,
  119. as->curins+1-REF_BIAS, ir->o, ir->op1-REF_BIAS, ir->op2-REF_BIAS);
  120. }
  121. #endif
  122. if (LJ_UNLIKELY(as->mcp < as->mclim)) asm_mclimit(as);
  123. #ifdef LUA_USE_ASSERT
  124. as->mcp_prev = as->mcp;
  125. #endif
  126. }
  127. #ifdef RID_NUM_KREF
  128. #define ra_iskref(ref) ((ref) < RID_NUM_KREF)
  129. #define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
  130. #define ra_krefk(as, ref) (as->krefk[(ref)])
  131. static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, intptr_t k)
  132. {
  133. IRRef ref = (IRRef)(r - RID_MIN_KREF);
  134. as->krefk[ref] = k;
  135. as->cost[r] = REGCOST(ref, ref);
  136. }
  137. #else
  138. #define ra_iskref(ref) 0
  139. #define ra_krefreg(ref) RID_MIN_GPR
  140. #define ra_krefk(as, ref) 0
  141. #endif
  142. /* Arch-specific field offsets. */
  143. static const uint8_t field_ofs[IRFL__MAX+1] = {
  144. #define FLOFS(name, ofs) (uint8_t)(ofs),
  145. IRFLDEF(FLOFS)
  146. #undef FLOFS
  147. 0
  148. };
  149. #ifdef LUAJIT_RANDOM_RA
  150. /* Return a fixed number of random bits from the local PRNG state. */
  151. static uint32_t ra_random_bits(ASMState *as, uint32_t nbits) {
  152. uint64_t b = as->prngbits;
  153. uint32_t res = (1u << nbits) - 1u;
  154. if (b <= res) b = lj_prng_u64(&as->prngstate) | (1ull << 63);
  155. res &= (uint32_t)b;
  156. as->prngbits = b >> nbits;
  157. return res;
  158. }
  159. /* Pick a random register from a register set. */
  160. static Reg rset_pickrandom(ASMState *as, RegSet rs)
  161. {
  162. Reg r = rset_pickbot_(rs);
  163. rs >>= r;
  164. if (rs > 1) { /* More than one bit set? */
  165. while (1) {
  166. /* We need to sample max. the GPR or FPR half of the set. */
  167. uint32_t d = ra_random_bits(as, RSET_BITS-1);
  168. if ((rs >> d) & 1) {
  169. r += d;
  170. break;
  171. }
  172. }
  173. }
  174. return r;
  175. }
  176. #define rset_picktop(rs) rset_pickrandom(as, rs)
  177. #define rset_pickbot(rs) rset_pickrandom(as, rs)
  178. #else
  179. #define rset_picktop(rs) rset_picktop_(rs)
  180. #define rset_pickbot(rs) rset_pickbot_(rs)
  181. #endif
  182. /* -- Target-specific instruction emitter --------------------------------- */
  183. #if LJ_TARGET_X86ORX64
  184. #include "lj_emit_x86.h"
  185. #elif LJ_TARGET_ARM
  186. #include "lj_emit_arm.h"
  187. #elif LJ_TARGET_ARM64
  188. #include "lj_emit_arm64.h"
  189. #elif LJ_TARGET_PPC
  190. #include "lj_emit_ppc.h"
  191. #elif LJ_TARGET_MIPS
  192. #include "lj_emit_mips.h"
  193. #else
  194. #error "Missing instruction emitter for target CPU"
  195. #endif
  196. /* Generic load/store of register from/to stack slot. */
  197. #define emit_spload(as, ir, r, ofs) \
  198. emit_loadofs(as, ir, (r), RID_SP, (ofs))
  199. #define emit_spstore(as, ir, r, ofs) \
  200. emit_storeofs(as, ir, (r), RID_SP, (ofs))
  201. /* -- Register allocator debugging ---------------------------------------- */
  202. /* #define LUAJIT_DEBUG_RA */
  203. #ifdef LUAJIT_DEBUG_RA
  204. #include <stdio.h>
  205. #include <stdarg.h>
  206. #define RIDNAME(name) #name,
  207. static const char *const ra_regname[] = {
  208. GPRDEF(RIDNAME)
  209. FPRDEF(RIDNAME)
  210. VRIDDEF(RIDNAME)
  211. NULL
  212. };
  213. #undef RIDNAME
  214. static char ra_dbg_buf[65536];
  215. static char *ra_dbg_p;
  216. static char *ra_dbg_merge;
  217. static MCode *ra_dbg_mcp;
  218. static void ra_dstart(void)
  219. {
  220. ra_dbg_p = ra_dbg_buf;
  221. ra_dbg_merge = NULL;
  222. ra_dbg_mcp = NULL;
  223. }
  224. static void ra_dflush(void)
  225. {
  226. fwrite(ra_dbg_buf, 1, (size_t)(ra_dbg_p-ra_dbg_buf), stdout);
  227. ra_dstart();
  228. }
  229. static void ra_dprintf(ASMState *as, const char *fmt, ...)
  230. {
  231. char *p;
  232. va_list argp;
  233. va_start(argp, fmt);
  234. p = ra_dbg_mcp == as->mcp ? ra_dbg_merge : ra_dbg_p;
  235. ra_dbg_mcp = NULL;
  236. p += sprintf(p, "%08x \e[36m%04d ", (uintptr_t)as->mcp, as->curins-REF_BIAS);
  237. for (;;) {
  238. const char *e = strchr(fmt, '$');
  239. if (e == NULL) break;
  240. memcpy(p, fmt, (size_t)(e-fmt));
  241. p += e-fmt;
  242. if (e[1] == 'r') {
  243. Reg r = va_arg(argp, Reg) & RID_MASK;
  244. if (r <= RID_MAX) {
  245. const char *q;
  246. for (q = ra_regname[r]; *q; q++)
  247. *p++ = *q >= 'A' && *q <= 'Z' ? *q + 0x20 : *q;
  248. } else {
  249. *p++ = '?';
  250. lj_assertA(0, "bad register %d for debug format \"%s\"", r, fmt);
  251. }
  252. } else if (e[1] == 'f' || e[1] == 'i') {
  253. IRRef ref;
  254. if (e[1] == 'f')
  255. ref = va_arg(argp, IRRef);
  256. else
  257. ref = va_arg(argp, IRIns *) - as->ir;
  258. if (ref >= REF_BIAS)
  259. p += sprintf(p, "%04d", ref - REF_BIAS);
  260. else
  261. p += sprintf(p, "K%03d", REF_BIAS - ref);
  262. } else if (e[1] == 's') {
  263. uint32_t slot = va_arg(argp, uint32_t);
  264. p += sprintf(p, "[sp+0x%x]", sps_scale(slot));
  265. } else if (e[1] == 'x') {
  266. p += sprintf(p, "%08x", va_arg(argp, int32_t));
  267. } else {
  268. lj_assertA(0, "bad debug format code");
  269. }
  270. fmt = e+2;
  271. }
  272. va_end(argp);
  273. while (*fmt)
  274. *p++ = *fmt++;
  275. *p++ = '\e'; *p++ = '['; *p++ = 'm'; *p++ = '\n';
  276. if (p > ra_dbg_buf+sizeof(ra_dbg_buf)-256) {
  277. fwrite(ra_dbg_buf, 1, (size_t)(p-ra_dbg_buf), stdout);
  278. p = ra_dbg_buf;
  279. }
  280. ra_dbg_p = p;
  281. }
  282. #define RA_DBG_START() ra_dstart()
  283. #define RA_DBG_FLUSH() ra_dflush()
  284. #define RA_DBG_REF() \
  285. do { char *_p = ra_dbg_p; ra_dprintf(as, ""); \
  286. ra_dbg_merge = _p; ra_dbg_mcp = as->mcp; } while (0)
  287. #define RA_DBGX(x) ra_dprintf x
  288. #else
  289. #define RA_DBG_START() ((void)0)
  290. #define RA_DBG_FLUSH() ((void)0)
  291. #define RA_DBG_REF() ((void)0)
  292. #define RA_DBGX(x) ((void)0)
  293. #endif
  294. /* -- Register allocator -------------------------------------------------- */
  295. #define ra_free(as, r) rset_set(as->freeset, (r))
  296. #define ra_modified(as, r) rset_set(as->modset, (r))
  297. #define ra_weak(as, r) rset_set(as->weakset, (r))
  298. #define ra_noweak(as, r) rset_clear(as->weakset, (r))
  299. #define ra_used(ir) (ra_hasreg((ir)->r) || ra_hasspill((ir)->s))
  300. /* Setup register allocator. */
  301. static void ra_setup(ASMState *as)
  302. {
  303. Reg r;
  304. /* Initially all regs (except the stack pointer) are free for use. */
  305. as->freeset = RSET_INIT;
  306. as->modset = RSET_EMPTY;
  307. as->weakset = RSET_EMPTY;
  308. as->phiset = RSET_EMPTY;
  309. memset(as->phireg, 0, sizeof(as->phireg));
  310. for (r = RID_MIN_GPR; r < RID_MAX; r++)
  311. as->cost[r] = REGCOST(~0u, 0u);
  312. }
  313. /* Rematerialize constants. */
  314. static Reg ra_rematk(ASMState *as, IRRef ref)
  315. {
  316. IRIns *ir;
  317. Reg r;
  318. if (ra_iskref(ref)) {
  319. r = ra_krefreg(ref);
  320. lj_assertA(!rset_test(as->freeset, r), "rematk of free reg %d", r);
  321. ra_free(as, r);
  322. ra_modified(as, r);
  323. #if LJ_64
  324. emit_loadu64(as, r, ra_krefk(as, ref));
  325. #else
  326. emit_loadi(as, r, ra_krefk(as, ref));
  327. #endif
  328. return r;
  329. }
  330. ir = IR(ref);
  331. r = ir->r;
  332. lj_assertA(ra_hasreg(r), "rematk of K%03d has no reg", REF_BIAS - ref);
  333. lj_assertA(!ra_hasspill(ir->s),
  334. "rematk of K%03d has spill slot [%x]", REF_BIAS - ref, ir->s);
  335. ra_free(as, r);
  336. ra_modified(as, r);
  337. ir->r = RID_INIT; /* Do not keep any hint. */
  338. RA_DBGX((as, "remat $i $r", ir, r));
  339. #if !LJ_SOFTFP32
  340. if (ir->o == IR_KNUM) {
  341. emit_loadk64(as, r, ir);
  342. } else
  343. #endif
  344. if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
  345. ra_sethint(ir->r, RID_BASE); /* Restore BASE register hint. */
  346. emit_getgl(as, r, jit_base);
  347. } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
  348. /* REF_NIL stores ASMREF_L register. */
  349. lj_assertA(irt_isnil(ir->t), "rematk of bad ASMREF_L");
  350. emit_getgl(as, r, cur_L);
  351. #if LJ_64
  352. } else if (ir->o == IR_KINT64) {
  353. emit_loadu64(as, r, ir_kint64(ir)->u64);
  354. #if LJ_GC64
  355. } else if (ir->o == IR_KGC) {
  356. emit_loadu64(as, r, (uintptr_t)ir_kgc(ir));
  357. } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
  358. emit_loadu64(as, r, (uintptr_t)ir_kptr(ir));
  359. #endif
  360. #endif
  361. } else {
  362. lj_assertA(ir->o == IR_KINT || ir->o == IR_KGC ||
  363. ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL,
  364. "rematk of bad IR op %d", ir->o);
  365. emit_loadi(as, r, ir->i);
  366. }
  367. return r;
  368. }
  369. /* Force a spill. Allocate a new spill slot if needed. */
  370. static int32_t ra_spill(ASMState *as, IRIns *ir)
  371. {
  372. int32_t slot = ir->s;
  373. lj_assertA(ir >= as->ir + REF_TRUE,
  374. "spill of K%03d", REF_BIAS - (int)(ir - as->ir));
  375. if (!ra_hasspill(slot)) {
  376. if (irt_is64(ir->t)) {
  377. slot = as->evenspill;
  378. as->evenspill += 2;
  379. } else if (as->oddspill) {
  380. slot = as->oddspill;
  381. as->oddspill = 0;
  382. } else {
  383. slot = as->evenspill;
  384. as->oddspill = slot+1;
  385. as->evenspill += 2;
  386. }
  387. if (as->evenspill > 256)
  388. lj_trace_err(as->J, LJ_TRERR_SPILLOV);
  389. ir->s = (uint8_t)slot;
  390. }
  391. return sps_scale(slot);
  392. }
  393. /* Release the temporarily allocated register in ASMREF_TMP1/ASMREF_TMP2. */
  394. static Reg ra_releasetmp(ASMState *as, IRRef ref)
  395. {
  396. IRIns *ir = IR(ref);
  397. Reg r = ir->r;
  398. lj_assertA(ra_hasreg(r), "release of TMP%d has no reg", ref-ASMREF_TMP1+1);
  399. lj_assertA(!ra_hasspill(ir->s),
  400. "release of TMP%d has spill slot [%x]", ref-ASMREF_TMP1+1, ir->s);
  401. ra_free(as, r);
  402. ra_modified(as, r);
  403. ir->r = RID_INIT;
  404. return r;
  405. }
  406. /* Restore a register (marked as free). Rematerialize or force a spill. */
  407. static Reg ra_restore(ASMState *as, IRRef ref)
  408. {
  409. if (emit_canremat(ref)) {
  410. return ra_rematk(as, ref);
  411. } else {
  412. IRIns *ir = IR(ref);
  413. int32_t ofs = ra_spill(as, ir); /* Force a spill slot. */
  414. Reg r = ir->r;
  415. lj_assertA(ra_hasreg(r), "restore of IR %04d has no reg", ref - REF_BIAS);
  416. ra_sethint(ir->r, r); /* Keep hint. */
  417. ra_free(as, r);
  418. if (!rset_test(as->weakset, r)) { /* Only restore non-weak references. */
  419. ra_modified(as, r);
  420. RA_DBGX((as, "restore $i $r", ir, r));
  421. emit_spload(as, ir, r, ofs);
  422. }
  423. return r;
  424. }
  425. }
  426. /* Save a register to a spill slot. */
  427. static void ra_save(ASMState *as, IRIns *ir, Reg r)
  428. {
  429. RA_DBGX((as, "save $i $r", ir, r));
  430. emit_spstore(as, ir, r, sps_scale(ir->s));
  431. }
  432. #define MINCOST(name) \
  433. if (rset_test(RSET_ALL, RID_##name) && \
  434. LJ_LIKELY(allow&RID2RSET(RID_##name)) && as->cost[RID_##name] < cost) \
  435. cost = as->cost[RID_##name];
  436. /* Evict the register with the lowest cost, forcing a restore. */
  437. static Reg ra_evict(ASMState *as, RegSet allow)
  438. {
  439. IRRef ref;
  440. RegCost cost = ~(RegCost)0;
  441. lj_assertA(allow != RSET_EMPTY, "evict from empty set");
  442. if (RID_NUM_FPR == 0 || allow < RID2RSET(RID_MAX_GPR)) {
  443. GPRDEF(MINCOST)
  444. } else {
  445. FPRDEF(MINCOST)
  446. }
  447. ref = regcost_ref(cost);
  448. lj_assertA(ra_iskref(ref) || (ref >= as->T->nk && ref < as->T->nins),
  449. "evict of out-of-range IR %04d", ref - REF_BIAS);
  450. /* Preferably pick any weak ref instead of a non-weak, non-const ref. */
  451. if (!irref_isk(ref) && (as->weakset & allow)) {
  452. IRIns *ir = IR(ref);
  453. if (!rset_test(as->weakset, ir->r))
  454. ref = regcost_ref(as->cost[rset_pickbot((as->weakset & allow))]);
  455. }
  456. return ra_restore(as, ref);
  457. }
  458. /* Pick any register (marked as free). Evict on-demand. */
  459. static Reg ra_pick(ASMState *as, RegSet allow)
  460. {
  461. RegSet pick = as->freeset & allow;
  462. if (!pick)
  463. return ra_evict(as, allow);
  464. else
  465. return rset_picktop(pick);
  466. }
  467. /* Get a scratch register (marked as free). */
  468. static Reg ra_scratch(ASMState *as, RegSet allow)
  469. {
  470. Reg r = ra_pick(as, allow);
  471. ra_modified(as, r);
  472. RA_DBGX((as, "scratch $r", r));
  473. return r;
  474. }
  475. /* Evict all registers from a set (if not free). */
  476. static void ra_evictset(ASMState *as, RegSet drop)
  477. {
  478. RegSet work;
  479. as->modset |= drop;
  480. #if !LJ_SOFTFP
  481. work = (drop & ~as->freeset) & RSET_FPR;
  482. while (work) {
  483. Reg r = rset_pickbot(work);
  484. ra_restore(as, regcost_ref(as->cost[r]));
  485. rset_clear(work, r);
  486. checkmclim(as);
  487. }
  488. #endif
  489. work = (drop & ~as->freeset);
  490. while (work) {
  491. Reg r = rset_pickbot(work);
  492. ra_restore(as, regcost_ref(as->cost[r]));
  493. rset_clear(work, r);
  494. checkmclim(as);
  495. }
  496. }
  497. /* Evict (rematerialize) all registers allocated to constants. */
  498. static void ra_evictk(ASMState *as)
  499. {
  500. RegSet work;
  501. #if !LJ_SOFTFP
  502. work = ~as->freeset & RSET_FPR;
  503. while (work) {
  504. Reg r = rset_pickbot(work);
  505. IRRef ref = regcost_ref(as->cost[r]);
  506. if (emit_canremat(ref) && irref_isk(ref)) {
  507. ra_rematk(as, ref);
  508. checkmclim(as);
  509. }
  510. rset_clear(work, r);
  511. }
  512. #endif
  513. work = ~as->freeset & RSET_GPR;
  514. while (work) {
  515. Reg r = rset_pickbot(work);
  516. IRRef ref = regcost_ref(as->cost[r]);
  517. if (emit_canremat(ref) && irref_isk(ref)) {
  518. ra_rematk(as, ref);
  519. checkmclim(as);
  520. }
  521. rset_clear(work, r);
  522. }
  523. }
  524. #ifdef RID_NUM_KREF
  525. /* Allocate a register for a constant. */
  526. static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow)
  527. {
  528. /* First try to find a register which already holds the same constant. */
  529. RegSet pick, work = ~as->freeset & RSET_GPR;
  530. Reg r;
  531. while (work) {
  532. IRRef ref;
  533. r = rset_pickbot(work);
  534. ref = regcost_ref(as->cost[r]);
  535. #if LJ_64
  536. if (ref < ASMREF_L) {
  537. if (ra_iskref(ref)) {
  538. if (k == ra_krefk(as, ref))
  539. return r;
  540. } else {
  541. IRIns *ir = IR(ref);
  542. if ((ir->o == IR_KINT64 && k == (int64_t)ir_kint64(ir)->u64) ||
  543. #if LJ_GC64
  544. #if LJ_TARGET_ARM64
  545. (ir->o == IR_KINT && (uint64_t)k == (uint32_t)ir->i) ||
  546. #else
  547. (ir->o == IR_KINT && k == ir->i) ||
  548. #endif
  549. (ir->o == IR_KGC && k == (intptr_t)ir_kgc(ir)) ||
  550. ((ir->o == IR_KPTR || ir->o == IR_KKPTR) &&
  551. k == (intptr_t)ir_kptr(ir))
  552. #else
  553. (ir->o != IR_KINT64 && k == ir->i)
  554. #endif
  555. )
  556. return r;
  557. }
  558. }
  559. #else
  560. if (ref < ASMREF_L &&
  561. k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
  562. return r;
  563. #endif
  564. rset_clear(work, r);
  565. }
  566. pick = as->freeset & allow;
  567. if (pick) {
  568. /* Constants should preferably get unmodified registers. */
  569. if ((pick & ~as->modset))
  570. pick &= ~as->modset;
  571. r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
  572. } else {
  573. r = ra_evict(as, allow);
  574. }
  575. RA_DBGX((as, "allock $x $r", k, r));
  576. ra_setkref(as, r, k);
  577. rset_clear(as->freeset, r);
  578. ra_noweak(as, r);
  579. return r;
  580. }
  581. /* Allocate a specific register for a constant. */
  582. static void ra_allockreg(ASMState *as, intptr_t k, Reg r)
  583. {
  584. Reg kr = ra_allock(as, k, RID2RSET(r));
  585. if (kr != r) {
  586. IRIns irdummy;
  587. irdummy.t.irt = IRT_INT;
  588. ra_scratch(as, RID2RSET(r));
  589. emit_movrr(as, &irdummy, r, kr);
  590. }
  591. }
  592. #else
  593. #define ra_allockreg(as, k, r) emit_loadi(as, (r), (k))
  594. #endif
  595. /* Allocate a register for ref from the allowed set of registers.
  596. ** Note: this function assumes the ref does NOT have a register yet!
  597. ** Picks an optimal register, sets the cost and marks the register as non-free.
  598. */
  599. static Reg ra_allocref(ASMState *as, IRRef ref, RegSet allow)
  600. {
  601. IRIns *ir = IR(ref);
  602. RegSet pick = as->freeset & allow;
  603. Reg r;
  604. lj_assertA(ra_noreg(ir->r),
  605. "IR %04d already has reg %d", ref - REF_BIAS, ir->r);
  606. if (pick) {
  607. /* First check register hint from propagation or PHI. */
  608. if (ra_hashint(ir->r)) {
  609. r = ra_gethint(ir->r);
  610. if (rset_test(pick, r)) /* Use hint register if possible. */
  611. goto found;
  612. /* Rematerialization is cheaper than missing a hint. */
  613. if (rset_test(allow, r) && emit_canremat(regcost_ref(as->cost[r]))) {
  614. ra_rematk(as, regcost_ref(as->cost[r]));
  615. goto found;
  616. }
  617. RA_DBGX((as, "hintmiss $f $r", ref, r));
  618. }
  619. /* Invariants should preferably get unmodified registers. */
  620. if (ref < as->loopref && !irt_isphi(ir->t)) {
  621. if ((pick & ~as->modset))
  622. pick &= ~as->modset;
  623. r = rset_pickbot(pick); /* Reduce conflicts with inverse allocation. */
  624. } else {
  625. /* We've got plenty of regs, so get callee-save regs if possible. */
  626. if (RID_NUM_GPR > 8 && (pick & ~RSET_SCRATCH))
  627. pick &= ~RSET_SCRATCH;
  628. r = rset_picktop(pick);
  629. }
  630. } else {
  631. r = ra_evict(as, allow);
  632. }
  633. found:
  634. RA_DBGX((as, "alloc $f $r", ref, r));
  635. ir->r = (uint8_t)r;
  636. rset_clear(as->freeset, r);
  637. ra_noweak(as, r);
  638. as->cost[r] = REGCOST_REF_T(ref, irt_t(ir->t));
  639. return r;
  640. }
  641. /* Allocate a register on-demand. */
  642. static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
  643. {
  644. Reg r = IR(ref)->r;
  645. /* Note: allow is ignored if the register is already allocated. */
  646. if (ra_noreg(r)) r = ra_allocref(as, ref, allow);
  647. ra_noweak(as, r);
  648. return r;
  649. }
  650. /* Add a register rename to the IR. */
  651. static void ra_addrename(ASMState *as, Reg down, IRRef ref, SnapNo snapno)
  652. {
  653. IRRef ren;
  654. lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, snapno);
  655. ren = tref_ref(lj_ir_emit(as->J));
  656. as->J->cur.ir[ren].r = (uint8_t)down;
  657. as->J->cur.ir[ren].s = SPS_NONE;
  658. }
  659. /* Rename register allocation and emit move. */
  660. static void ra_rename(ASMState *as, Reg down, Reg up)
  661. {
  662. IRRef ref = regcost_ref(as->cost[up] = as->cost[down]);
  663. IRIns *ir = IR(ref);
  664. ir->r = (uint8_t)up;
  665. as->cost[down] = 0;
  666. lj_assertA((down < RID_MAX_GPR) == (up < RID_MAX_GPR),
  667. "rename between GPR/FPR %d and %d", down, up);
  668. lj_assertA(!rset_test(as->freeset, down), "rename from free reg %d", down);
  669. lj_assertA(rset_test(as->freeset, up), "rename to non-free reg %d", up);
  670. ra_free(as, down); /* 'down' is free ... */
  671. ra_modified(as, down);
  672. rset_clear(as->freeset, up); /* ... and 'up' is now allocated. */
  673. ra_noweak(as, up);
  674. RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
  675. emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
  676. if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
  677. /*
  678. ** The rename is effective at the subsequent (already emitted) exit
  679. ** branch. This is for the current snapshot (as->snapno). Except if we
  680. ** haven't yet allocated any refs for the snapshot (as->snapalloc == 1),
  681. ** then it belongs to the next snapshot.
  682. ** See also the discussion at asm_snap_checkrename().
  683. */
  684. ra_addrename(as, down, ref, as->snapno + as->snapalloc);
  685. }
  686. }
  687. /* Pick a destination register (marked as free).
  688. ** Caveat: allow is ignored if there's already a destination register.
  689. ** Use ra_destreg() to get a specific register.
  690. */
  691. static Reg ra_dest(ASMState *as, IRIns *ir, RegSet allow)
  692. {
  693. Reg dest = ir->r;
  694. if (ra_hasreg(dest)) {
  695. ra_free(as, dest);
  696. ra_modified(as, dest);
  697. } else {
  698. if (ra_hashint(dest) && rset_test((as->freeset&allow), ra_gethint(dest))) {
  699. dest = ra_gethint(dest);
  700. ra_modified(as, dest);
  701. RA_DBGX((as, "dest $r", dest));
  702. } else {
  703. dest = ra_scratch(as, allow);
  704. }
  705. ir->r = dest;
  706. }
  707. if (LJ_UNLIKELY(ra_hasspill(ir->s))) ra_save(as, ir, dest);
  708. return dest;
  709. }
  710. /* Force a specific destination register (marked as free). */
  711. static void ra_destreg(ASMState *as, IRIns *ir, Reg r)
  712. {
  713. Reg dest = ra_dest(as, ir, RID2RSET(r));
  714. if (dest != r) {
  715. lj_assertA(rset_test(as->freeset, r), "dest reg %d is not free", r);
  716. ra_modified(as, r);
  717. emit_movrr(as, ir, dest, r);
  718. }
  719. }
  720. #if LJ_TARGET_X86ORX64
  721. /* Propagate dest register to left reference. Emit moves as needed.
  722. ** This is a required fixup step for all 2-operand machine instructions.
  723. */
  724. static void ra_left(ASMState *as, Reg dest, IRRef lref)
  725. {
  726. IRIns *ir = IR(lref);
  727. Reg left = ir->r;
  728. if (ra_noreg(left)) {
  729. if (irref_isk(lref)) {
  730. if (ir->o == IR_KNUM) {
  731. /* FP remat needs a load except for +0. Still better than eviction. */
  732. if (tvispzero(ir_knum(ir)) || !(as->freeset & RSET_FPR)) {
  733. emit_loadk64(as, dest, ir);
  734. return;
  735. }
  736. #if LJ_64
  737. } else if (ir->o == IR_KINT64) {
  738. emit_loadk64(as, dest, ir);
  739. return;
  740. #if LJ_GC64
  741. } else if (ir->o == IR_KGC || ir->o == IR_KPTR || ir->o == IR_KKPTR) {
  742. emit_loadk64(as, dest, ir);
  743. return;
  744. #endif
  745. #endif
  746. } else if (ir->o != IR_KPRI) {
  747. lj_assertA(ir->o == IR_KINT || ir->o == IR_KGC ||
  748. ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL,
  749. "K%03d has bad IR op %d", REF_BIAS - lref, ir->o);
  750. emit_loadi(as, dest, ir->i);
  751. return;
  752. }
  753. }
  754. if (!ra_hashint(left) && !iscrossref(as, lref))
  755. ra_sethint(ir->r, dest); /* Propagate register hint. */
  756. left = ra_allocref(as, lref, dest < RID_MAX_GPR ? RSET_GPR : RSET_FPR);
  757. }
  758. ra_noweak(as, left);
  759. /* Move needed for true 3-operand instruction: y=a+b ==> y=a; y+=b. */
  760. if (dest != left) {
  761. /* Use register renaming if dest is the PHI reg. */
  762. if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
  763. ra_modified(as, left);
  764. ra_rename(as, left, dest);
  765. } else {
  766. emit_movrr(as, ir, dest, left);
  767. }
  768. }
  769. }
  770. #else
  771. /* Similar to ra_left, except we override any hints. */
  772. static void ra_leftov(ASMState *as, Reg dest, IRRef lref)
  773. {
  774. IRIns *ir = IR(lref);
  775. Reg left = ir->r;
  776. if (ra_noreg(left)) {
  777. ra_sethint(ir->r, dest); /* Propagate register hint. */
  778. left = ra_allocref(as, lref,
  779. (LJ_SOFTFP || dest < RID_MAX_GPR) ? RSET_GPR : RSET_FPR);
  780. }
  781. ra_noweak(as, left);
  782. if (dest != left) {
  783. /* Use register renaming if dest is the PHI reg. */
  784. if (irt_isphi(ir->t) && as->phireg[dest] == lref) {
  785. ra_modified(as, left);
  786. ra_rename(as, left, dest);
  787. } else {
  788. emit_movrr(as, ir, dest, left);
  789. }
  790. }
  791. }
  792. #endif
  793. /* Force a RID_RETLO/RID_RETHI destination register pair (marked as free). */
  794. static void ra_destpair(ASMState *as, IRIns *ir)
  795. {
  796. Reg destlo = ir->r, desthi = (ir+1)->r;
  797. IRIns *irx = (LJ_64 && !irt_is64(ir->t)) ? ir+1 : ir;
  798. /* First spill unrelated refs blocking the destination registers. */
  799. if (!rset_test(as->freeset, RID_RETLO) &&
  800. destlo != RID_RETLO && desthi != RID_RETLO)
  801. ra_restore(as, regcost_ref(as->cost[RID_RETLO]));
  802. if (!rset_test(as->freeset, RID_RETHI) &&
  803. destlo != RID_RETHI && desthi != RID_RETHI)
  804. ra_restore(as, regcost_ref(as->cost[RID_RETHI]));
  805. /* Next free the destination registers (if any). */
  806. if (ra_hasreg(destlo)) {
  807. ra_free(as, destlo);
  808. ra_modified(as, destlo);
  809. } else {
  810. destlo = RID_RETLO;
  811. }
  812. if (ra_hasreg(desthi)) {
  813. ra_free(as, desthi);
  814. ra_modified(as, desthi);
  815. } else {
  816. desthi = RID_RETHI;
  817. }
  818. /* Check for conflicts and shuffle the registers as needed. */
  819. if (destlo == RID_RETHI) {
  820. if (desthi == RID_RETLO) {
  821. #if LJ_TARGET_X86ORX64
  822. *--as->mcp = XI_XCHGa + RID_RETHI;
  823. if (LJ_64 && irt_is64(irx->t)) *--as->mcp = 0x48;
  824. #else
  825. emit_movrr(as, irx, RID_RETHI, RID_TMP);
  826. emit_movrr(as, irx, RID_RETLO, RID_RETHI);
  827. emit_movrr(as, irx, RID_TMP, RID_RETLO);
  828. #endif
  829. } else {
  830. emit_movrr(as, irx, RID_RETHI, RID_RETLO);
  831. if (desthi != RID_RETHI) emit_movrr(as, irx, desthi, RID_RETHI);
  832. }
  833. } else if (desthi == RID_RETLO) {
  834. emit_movrr(as, irx, RID_RETLO, RID_RETHI);
  835. if (destlo != RID_RETLO) emit_movrr(as, irx, destlo, RID_RETLO);
  836. } else {
  837. if (desthi != RID_RETHI) emit_movrr(as, irx, desthi, RID_RETHI);
  838. if (destlo != RID_RETLO) emit_movrr(as, irx, destlo, RID_RETLO);
  839. }
  840. /* Restore spill slots (if any). */
  841. if (ra_hasspill((ir+1)->s)) ra_save(as, ir+1, RID_RETHI);
  842. if (ra_hasspill(ir->s)) ra_save(as, ir, RID_RETLO);
  843. }
  844. /* -- Snapshot handling --------- ----------------------------------------- */
  845. /* Can we rematerialize a KNUM instead of forcing a spill? */
  846. static int asm_snap_canremat(ASMState *as)
  847. {
  848. Reg r;
  849. for (r = RID_MIN_FPR; r < RID_MAX_FPR; r++)
  850. if (irref_isk(regcost_ref(as->cost[r])))
  851. return 1;
  852. return 0;
  853. }
  854. /* Check whether a sunk store corresponds to an allocation. */
  855. static int asm_sunk_store(ASMState *as, IRIns *ira, IRIns *irs)
  856. {
  857. if (irs->s == 255) {
  858. if (irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
  859. irs->o == IR_FSTORE || irs->o == IR_XSTORE) {
  860. IRIns *irk = IR(irs->op1);
  861. if (irk->o == IR_AREF || irk->o == IR_HREFK)
  862. irk = IR(irk->op1);
  863. return (IR(irk->op1) == ira);
  864. }
  865. return 0;
  866. } else {
  867. return (ira + irs->s == irs); /* Quick check. */
  868. }
  869. }
  870. /* Allocate register or spill slot for a ref that escapes to a snapshot. */
  871. static void asm_snap_alloc1(ASMState *as, IRRef ref)
  872. {
  873. IRIns *ir = IR(ref);
  874. if (!irref_isk(ref) && ir->r != RID_SUNK) {
  875. bloomset(as->snapfilt1, ref);
  876. bloomset(as->snapfilt2, hashrot(ref, ref + HASH_BIAS));
  877. if (ra_used(ir)) return;
  878. if (ir->r == RID_SINK) {
  879. ir->r = RID_SUNK;
  880. #if LJ_HASFFI
  881. if (ir->o == IR_CNEWI) { /* Allocate CNEWI value. */
  882. asm_snap_alloc1(as, ir->op2);
  883. if (LJ_32 && (ir+1)->o == IR_HIOP)
  884. asm_snap_alloc1(as, (ir+1)->op2);
  885. } else
  886. #endif
  887. { /* Allocate stored values for TNEW, TDUP and CNEW. */
  888. IRIns *irs;
  889. lj_assertA(ir->o == IR_TNEW || ir->o == IR_TDUP || ir->o == IR_CNEW,
  890. "sink of IR %04d has bad op %d", ref - REF_BIAS, ir->o);
  891. for (irs = IR(as->snapref-1); irs > ir; irs--)
  892. if (irs->r == RID_SINK && asm_sunk_store(as, ir, irs)) {
  893. lj_assertA(irs->o == IR_ASTORE || irs->o == IR_HSTORE ||
  894. irs->o == IR_FSTORE || irs->o == IR_XSTORE,
  895. "sunk store IR %04d has bad op %d",
  896. (int)(irs - as->ir) - REF_BIAS, irs->o);
  897. asm_snap_alloc1(as, irs->op2);
  898. if (LJ_32 && (irs+1)->o == IR_HIOP)
  899. asm_snap_alloc1(as, (irs+1)->op2);
  900. }
  901. }
  902. } else {
  903. RegSet allow;
  904. if (ir->o == IR_CONV && ir->op2 == IRCONV_NUM_INT) {
  905. IRIns *irc;
  906. for (irc = IR(as->curins); irc > ir; irc--)
  907. if ((irc->op1 == ref || irc->op2 == ref) &&
  908. !(irc->r == RID_SINK || irc->r == RID_SUNK))
  909. goto nosink; /* Don't sink conversion if result is used. */
  910. asm_snap_alloc1(as, ir->op1);
  911. return;
  912. }
  913. nosink:
  914. allow = (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR;
  915. if ((as->freeset & allow) ||
  916. (allow == RSET_FPR && asm_snap_canremat(as))) {
  917. /* Get a weak register if we have a free one or can rematerialize. */
  918. Reg r = ra_allocref(as, ref, allow); /* Allocate a register. */
  919. if (!irt_isphi(ir->t))
  920. ra_weak(as, r); /* But mark it as weakly referenced. */
  921. checkmclim(as);
  922. RA_DBGX((as, "snapreg $f $r", ref, ir->r));
  923. } else {
  924. ra_spill(as, ir); /* Otherwise force a spill slot. */
  925. RA_DBGX((as, "snapspill $f $s", ref, ir->s));
  926. }
  927. }
  928. }
  929. }
  930. /* Allocate refs escaping to a snapshot. */
  931. static void asm_snap_alloc(ASMState *as, int snapno)
  932. {
  933. SnapShot *snap = &as->T->snap[snapno];
  934. SnapEntry *map = &as->T->snapmap[snap->mapofs];
  935. MSize n, nent = snap->nent;
  936. as->snapfilt1 = as->snapfilt2 = 0;
  937. for (n = 0; n < nent; n++) {
  938. SnapEntry sn = map[n];
  939. IRRef ref = snap_ref(sn);
  940. if (!irref_isk(ref)) {
  941. asm_snap_alloc1(as, ref);
  942. if (LJ_SOFTFP && (sn & SNAP_SOFTFPNUM)) {
  943. lj_assertA(irt_type(IR(ref+1)->t) == IRT_SOFTFP,
  944. "snap %d[%d] points to bad SOFTFP IR %04d",
  945. snapno, n, ref - REF_BIAS);
  946. asm_snap_alloc1(as, ref+1);
  947. }
  948. }
  949. }
  950. }
  951. /* All guards for a snapshot use the same exitno. This is currently the
  952. ** same as the snapshot number. Since the exact origin of the exit cannot
  953. ** be determined, all guards for the same snapshot must exit with the same
  954. ** RegSP mapping.
  955. ** A renamed ref which has been used in a prior guard for the same snapshot
  956. ** would cause an inconsistency. The easy way out is to force a spill slot.
  957. */
  958. static int asm_snap_checkrename(ASMState *as, IRRef ren)
  959. {
  960. if (bloomtest(as->snapfilt1, ren) &&
  961. bloomtest(as->snapfilt2, hashrot(ren, ren + HASH_BIAS))) {
  962. IRIns *ir = IR(ren);
  963. ra_spill(as, ir); /* Register renamed, so force a spill slot. */
  964. RA_DBGX((as, "snaprensp $f $s", ren, ir->s));
  965. return 1; /* Found. */
  966. }
  967. return 0; /* Not found. */
  968. }
  969. /* Prepare snapshot for next guard or throwing instruction. */
  970. static void asm_snap_prep(ASMState *as)
  971. {
  972. if (as->snapalloc) {
  973. /* Alloc on first invocation for each snapshot. */
  974. as->snapalloc = 0;
  975. asm_snap_alloc(as, as->snapno);
  976. as->snaprename = as->T->nins;
  977. } else {
  978. /* Check any renames above the highwater mark. */
  979. for (; as->snaprename < as->T->nins; as->snaprename++) {
  980. IRIns *ir = &as->T->ir[as->snaprename];
  981. if (asm_snap_checkrename(as, ir->op1))
  982. ir->op2 = REF_BIAS-1; /* Kill rename. */
  983. }
  984. }
  985. }
  986. /* Move to previous snapshot when we cross the current snapshot ref. */
  987. static void asm_snap_prev(ASMState *as)
  988. {
  989. if (as->curins < as->snapref) {
  990. uintptr_t ofs = (uintptr_t)(as->mctoporig - as->mcp);
  991. if (ofs >= 0x10000) lj_trace_err(as->J, LJ_TRERR_MCODEOV);
  992. do {
  993. if (as->snapno == 0) return;
  994. as->snapno--;
  995. as->snapref = as->T->snap[as->snapno].ref;
  996. as->T->snap[as->snapno].mcofs = (uint16_t)ofs; /* Remember mcode ofs. */
  997. } while (as->curins < as->snapref); /* May have no ins inbetween. */
  998. as->snapalloc = 1;
  999. }
  1000. }
  1001. /* Fixup snapshot mcode offsetst. */
  1002. static void asm_snap_fixup_mcofs(ASMState *as)
  1003. {
  1004. uint32_t sz = (uint32_t)(as->mctoporig - as->mcp);
  1005. SnapShot *snap = as->T->snap;
  1006. SnapNo i;
  1007. for (i = as->T->nsnap-1; i > 0; i--) {
  1008. /* Compute offset from mcode start and store in correct snapshot. */
  1009. snap[i].mcofs = (uint16_t)(sz - snap[i-1].mcofs);
  1010. }
  1011. snap[0].mcofs = 0;
  1012. }
  1013. /* -- Miscellaneous helpers ----------------------------------------------- */
  1014. /* Calculate stack adjustment. */
  1015. static int32_t asm_stack_adjust(ASMState *as)
  1016. {
  1017. if (as->evenspill <= SPS_FIXED)
  1018. return 0;
  1019. return sps_scale(sps_align(as->evenspill));
  1020. }
  1021. /* Must match with hash*() in lj_tab.c. */
  1022. static uint32_t ir_khash(ASMState *as, IRIns *ir)
  1023. {
  1024. uint32_t lo, hi;
  1025. UNUSED(as);
  1026. if (irt_isstr(ir->t)) {
  1027. return ir_kstr(ir)->sid;
  1028. } else if (irt_isnum(ir->t)) {
  1029. lo = ir_knum(ir)->u32.lo;
  1030. hi = ir_knum(ir)->u32.hi << 1;
  1031. } else if (irt_ispri(ir->t)) {
  1032. lj_assertA(!irt_isnil(ir->t), "hash of nil key");
  1033. return irt_type(ir->t)-IRT_FALSE;
  1034. } else {
  1035. lj_assertA(irt_isgcv(ir->t), "hash of bad IR type %d", irt_type(ir->t));
  1036. lo = u32ptr(ir_kgc(ir));
  1037. #if LJ_GC64
  1038. hi = (uint32_t)(u64ptr(ir_kgc(ir)) >> 32) | (irt_toitype(ir->t) << 15);
  1039. #else
  1040. hi = lo + HASH_BIAS;
  1041. #endif
  1042. }
  1043. return hashrot(lo, hi);
  1044. }
  1045. /* -- Allocations --------------------------------------------------------- */
  1046. static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args);
  1047. static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci);
  1048. static void asm_snew(ASMState *as, IRIns *ir)
  1049. {
  1050. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_new];
  1051. IRRef args[3];
  1052. asm_snap_prep(as);
  1053. args[0] = ASMREF_L; /* lua_State *L */
  1054. args[1] = ir->op1; /* const char *str */
  1055. args[2] = ir->op2; /* size_t len */
  1056. as->gcsteps++;
  1057. asm_setupresult(as, ir, ci); /* GCstr * */
  1058. asm_gencall(as, ci, args);
  1059. }
  1060. static void asm_tnew(ASMState *as, IRIns *ir)
  1061. {
  1062. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_new1];
  1063. IRRef args[2];
  1064. asm_snap_prep(as);
  1065. args[0] = ASMREF_L; /* lua_State *L */
  1066. args[1] = ASMREF_TMP1; /* uint32_t ahsize */
  1067. as->gcsteps++;
  1068. asm_setupresult(as, ir, ci); /* GCtab * */
  1069. asm_gencall(as, ci, args);
  1070. ra_allockreg(as, ir->op1 | (ir->op2 << 24), ra_releasetmp(as, ASMREF_TMP1));
  1071. }
  1072. static void asm_tdup(ASMState *as, IRIns *ir)
  1073. {
  1074. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_dup];
  1075. IRRef args[2];
  1076. asm_snap_prep(as);
  1077. args[0] = ASMREF_L; /* lua_State *L */
  1078. args[1] = ir->op1; /* const GCtab *kt */
  1079. as->gcsteps++;
  1080. asm_setupresult(as, ir, ci); /* GCtab * */
  1081. asm_gencall(as, ci, args);
  1082. }
  1083. static void asm_gc_check(ASMState *as);
  1084. /* Explicit GC step. */
  1085. static void asm_gcstep(ASMState *as, IRIns *ir)
  1086. {
  1087. IRIns *ira;
  1088. for (ira = IR(as->stopins+1); ira < ir; ira++)
  1089. if ((ira->o == IR_TNEW || ira->o == IR_TDUP ||
  1090. (LJ_HASFFI && (ira->o == IR_CNEW || ira->o == IR_CNEWI))) &&
  1091. ra_used(ira))
  1092. as->gcsteps++;
  1093. if (as->gcsteps)
  1094. asm_gc_check(as);
  1095. as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */
  1096. }
  1097. /* -- Buffer operations --------------------------------------------------- */
  1098. static void asm_tvptr(ASMState *as, Reg dest, IRRef ref, MSize mode);
  1099. #if LJ_HASBUFFER
  1100. static void asm_bufhdr_write(ASMState *as, Reg sb);
  1101. #endif
  1102. static void asm_bufhdr(ASMState *as, IRIns *ir)
  1103. {
  1104. Reg sb = ra_dest(as, ir, RSET_GPR);
  1105. switch (ir->op2) {
  1106. case IRBUFHDR_RESET: {
  1107. Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb));
  1108. IRIns irbp;
  1109. irbp.ot = IRT(0, IRT_PTR); /* Buffer data pointer type. */
  1110. emit_storeofs(as, &irbp, tmp, sb, offsetof(SBuf, w));
  1111. emit_loadofs(as, &irbp, tmp, sb, offsetof(SBuf, b));
  1112. break;
  1113. }
  1114. case IRBUFHDR_APPEND: {
  1115. /* Rematerialize const buffer pointer instead of likely spill. */
  1116. IRIns *irp = IR(ir->op1);
  1117. if (!(ra_hasreg(irp->r) || irp == ir-1 ||
  1118. (irp == ir-2 && !ra_used(ir-1)))) {
  1119. while (!(irp->o == IR_BUFHDR && irp->op2 == IRBUFHDR_RESET))
  1120. irp = IR(irp->op1);
  1121. if (irref_isk(irp->op1)) {
  1122. ra_weak(as, ra_allocref(as, ir->op1, RSET_GPR));
  1123. ir = irp;
  1124. }
  1125. }
  1126. break;
  1127. }
  1128. #if LJ_HASBUFFER
  1129. case IRBUFHDR_WRITE:
  1130. asm_bufhdr_write(as, sb);
  1131. break;
  1132. #endif
  1133. default: lj_assertA(0, "bad BUFHDR op2 %d", ir->op2); break;
  1134. }
  1135. #if LJ_TARGET_X86ORX64
  1136. ra_left(as, sb, ir->op1);
  1137. #else
  1138. ra_leftov(as, sb, ir->op1);
  1139. #endif
  1140. }
  1141. static void asm_bufput(ASMState *as, IRIns *ir)
  1142. {
  1143. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_putstr];
  1144. IRRef args[3];
  1145. IRIns *irs;
  1146. int kchar = -129;
  1147. args[0] = ir->op1; /* SBuf * */
  1148. args[1] = ir->op2; /* GCstr * */
  1149. irs = IR(ir->op2);
  1150. lj_assertA(irt_isstr(irs->t),
  1151. "BUFPUT of non-string IR %04d", ir->op2 - REF_BIAS);
  1152. if (irs->o == IR_KGC) {
  1153. GCstr *s = ir_kstr(irs);
  1154. if (s->len == 1) { /* Optimize put of single-char string constant. */
  1155. kchar = (int8_t)strdata(s)[0]; /* Signed! */
  1156. args[1] = ASMREF_TMP1; /* int, truncated to char */
  1157. ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
  1158. }
  1159. } else if (mayfuse(as, ir->op2) && ra_noreg(irs->r)) {
  1160. if (irs->o == IR_TOSTR) { /* Fuse number to string conversions. */
  1161. if (irs->op2 == IRTOSTR_NUM) {
  1162. args[1] = ASMREF_TMP1; /* TValue * */
  1163. ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putnum];
  1164. } else {
  1165. lj_assertA(irt_isinteger(IR(irs->op1)->t),
  1166. "TOSTR of non-numeric IR %04d", irs->op1);
  1167. args[1] = irs->op1; /* int */
  1168. if (irs->op2 == IRTOSTR_INT)
  1169. ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putint];
  1170. else
  1171. ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
  1172. }
  1173. } else if (irs->o == IR_SNEW) { /* Fuse string allocation. */
  1174. args[1] = irs->op1; /* const void * */
  1175. args[2] = irs->op2; /* MSize */
  1176. ci = &lj_ir_callinfo[IRCALL_lj_buf_putmem];
  1177. }
  1178. }
  1179. asm_setupresult(as, ir, ci); /* SBuf * */
  1180. asm_gencall(as, ci, args);
  1181. if (args[1] == ASMREF_TMP1) {
  1182. Reg tmp = ra_releasetmp(as, ASMREF_TMP1);
  1183. if (kchar == -129)
  1184. asm_tvptr(as, tmp, irs->op1, IRTMPREF_IN1);
  1185. else
  1186. ra_allockreg(as, kchar, tmp);
  1187. }
  1188. }
  1189. static void asm_bufstr(ASMState *as, IRIns *ir)
  1190. {
  1191. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_tostr];
  1192. IRRef args[1];
  1193. args[0] = ir->op1; /* SBuf *sb */
  1194. as->gcsteps++;
  1195. asm_setupresult(as, ir, ci); /* GCstr * */
  1196. asm_gencall(as, ci, args);
  1197. }
  1198. /* -- Type conversions ---------------------------------------------------- */
  1199. static void asm_tostr(ASMState *as, IRIns *ir)
  1200. {
  1201. const CCallInfo *ci;
  1202. IRRef args[2];
  1203. asm_snap_prep(as);
  1204. args[0] = ASMREF_L;
  1205. as->gcsteps++;
  1206. if (ir->op2 == IRTOSTR_NUM) {
  1207. args[1] = ASMREF_TMP1; /* cTValue * */
  1208. ci = &lj_ir_callinfo[IRCALL_lj_strfmt_num];
  1209. } else {
  1210. args[1] = ir->op1; /* int32_t k */
  1211. if (ir->op2 == IRTOSTR_INT)
  1212. ci = &lj_ir_callinfo[IRCALL_lj_strfmt_int];
  1213. else
  1214. ci = &lj_ir_callinfo[IRCALL_lj_strfmt_char];
  1215. }
  1216. asm_setupresult(as, ir, ci); /* GCstr * */
  1217. asm_gencall(as, ci, args);
  1218. if (ir->op2 == IRTOSTR_NUM)
  1219. asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1, IRTMPREF_IN1);
  1220. }
  1221. #if LJ_32 && LJ_HASFFI && !LJ_SOFTFP && !LJ_TARGET_X86
  1222. static void asm_conv64(ASMState *as, IRIns *ir)
  1223. {
  1224. IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
  1225. IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
  1226. IRCallID id;
  1227. IRRef args[2];
  1228. lj_assertA((ir-1)->o == IR_CONV && ir->o == IR_HIOP,
  1229. "not a CONV/HIOP pair at IR %04d", (int)(ir - as->ir) - REF_BIAS);
  1230. args[LJ_BE] = (ir-1)->op1;
  1231. args[LJ_LE] = ir->op1;
  1232. if (st == IRT_NUM || st == IRT_FLOAT) {
  1233. id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
  1234. ir--;
  1235. } else {
  1236. id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
  1237. }
  1238. {
  1239. #if LJ_TARGET_ARM && !LJ_ABI_SOFTFP
  1240. CCallInfo cim = lj_ir_callinfo[id], *ci = &cim;
  1241. cim.flags |= CCI_VARARG; /* These calls don't use the hard-float ABI! */
  1242. #else
  1243. const CCallInfo *ci = &lj_ir_callinfo[id];
  1244. #endif
  1245. asm_setupresult(as, ir, ci);
  1246. asm_gencall(as, ci, args);
  1247. }
  1248. }
  1249. #endif
  1250. /* -- Memory references --------------------------------------------------- */
  1251. static void asm_newref(ASMState *as, IRIns *ir)
  1252. {
  1253. const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
  1254. IRRef args[3];
  1255. if (ir->r == RID_SINK)
  1256. return;
  1257. asm_snap_prep(as);
  1258. args[0] = ASMREF_L; /* lua_State *L */
  1259. args[1] = ir->op1; /* GCtab *t */
  1260. args[2] = ASMREF_TMP1; /* cTValue *key */
  1261. asm_setupresult(as, ir, ci); /* TValue * */
  1262. asm_gencall(as, ci, args);
  1263. asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2, IRTMPREF_IN1);
  1264. }
  1265. static void asm_tmpref(ASMState *as, IRIns *ir)
  1266. {
  1267. Reg r = ra_dest(as, ir, RSET_GPR);
  1268. asm_tvptr(as, r, ir->op1, ir->op2);
  1269. }
  1270. static void asm_lref(ASMState *as, IRIns *ir)
  1271. {
  1272. Reg r = ra_dest(as, ir, RSET_GPR);
  1273. #if LJ_TARGET_X86ORX64
  1274. ra_left(as, r, ASMREF_L);
  1275. #else
  1276. ra_leftov(as, r, ASMREF_L);
  1277. #endif
  1278. }
  1279. /* -- Calls --------------------------------------------------------------- */
  1280. /* Collect arguments from CALL* and CARG instructions. */
  1281. static void asm_collectargs(ASMState *as, IRIns *ir,
  1282. const CCallInfo *ci, IRRef *args)
  1283. {
  1284. uint32_t n = CCI_XNARGS(ci);
  1285. /* Account for split args. */
  1286. lj_assertA(n <= CCI_NARGS_MAX*2, "too many args %d to collect", n);
  1287. if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
  1288. while (n-- > 1) {
  1289. ir = IR(ir->op1);
  1290. lj_assertA(ir->o == IR_CARG, "malformed CALL arg tree");
  1291. args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
  1292. }
  1293. args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
  1294. lj_assertA(IR(ir->op1)->o != IR_CARG, "malformed CALL arg tree");
  1295. }
  1296. /* Reconstruct CCallInfo flags for CALLX*. */
  1297. static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
  1298. {
  1299. uint32_t nargs = 0;
  1300. if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
  1301. IRIns *ira = IR(ir->op1);
  1302. nargs++;
  1303. while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
  1304. }
  1305. #if LJ_HASFFI
  1306. if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
  1307. CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
  1308. CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
  1309. nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
  1310. #if LJ_TARGET_X86
  1311. nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
  1312. #endif
  1313. }
  1314. #endif
  1315. return (nargs | (ir->t.irt << CCI_OTSHIFT));
  1316. }
  1317. static void asm_callid(ASMState *as, IRIns *ir, IRCallID id)
  1318. {
  1319. const CCallInfo *ci = &lj_ir_callinfo[id];
  1320. IRRef args[2];
  1321. args[0] = ir->op1;
  1322. args[1] = ir->op2;
  1323. asm_setupresult(as, ir, ci);
  1324. asm_gencall(as, ci, args);
  1325. }
  1326. static void asm_call(ASMState *as, IRIns *ir)
  1327. {
  1328. IRRef args[CCI_NARGS_MAX];
  1329. const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
  1330. asm_collectargs(as, ir, ci, args);
  1331. asm_setupresult(as, ir, ci);
  1332. asm_gencall(as, ci, args);
  1333. }
  1334. /* -- PHI and loop handling ----------------------------------------------- */
  1335. /* Break a PHI cycle by renaming to a free register (evict if needed). */
  1336. static void asm_phi_break(ASMState *as, RegSet blocked, RegSet blockedby,
  1337. RegSet allow)
  1338. {
  1339. RegSet candidates = blocked & allow;
  1340. if (candidates) { /* If this register file has candidates. */
  1341. /* Note: the set for ra_pick cannot be empty, since each register file
  1342. ** has some registers never allocated to PHIs.
  1343. */
  1344. Reg down, up = ra_pick(as, ~blocked & allow); /* Get a free register. */
  1345. if (candidates & ~blockedby) /* Optimize shifts, else it's a cycle. */
  1346. candidates = candidates & ~blockedby;
  1347. down = rset_picktop(candidates); /* Pick candidate PHI register. */
  1348. ra_rename(as, down, up); /* And rename it to the free register. */
  1349. }
  1350. }
  1351. /* PHI register shuffling.
  1352. **
  1353. ** The allocator tries hard to preserve PHI register assignments across
  1354. ** the loop body. Most of the time this loop does nothing, since there
  1355. ** are no register mismatches.
  1356. **
  1357. ** If a register mismatch is detected and ...
  1358. ** - the register is currently free: rename it.
  1359. ** - the register is blocked by an invariant: restore/remat and rename it.
  1360. ** - Otherwise the register is used by another PHI, so mark it as blocked.
  1361. **
  1362. ** The renames are order-sensitive, so just retry the loop if a register
  1363. ** is marked as blocked, but has been freed in the meantime. A cycle is
  1364. ** detected if all of the blocked registers are allocated. To break the
  1365. ** cycle rename one of them to a free register and retry.
  1366. **
  1367. ** Note that PHI spill slots are kept in sync and don't need to be shuffled.
  1368. */
  1369. static void asm_phi_shuffle(ASMState *as)
  1370. {
  1371. RegSet work;
  1372. /* Find and resolve PHI register mismatches. */
  1373. for (;;) {
  1374. RegSet blocked = RSET_EMPTY;
  1375. RegSet blockedby = RSET_EMPTY;
  1376. RegSet phiset = as->phiset;
  1377. while (phiset) { /* Check all left PHI operand registers. */
  1378. Reg r = rset_pickbot(phiset);
  1379. IRIns *irl = IR(as->phireg[r]);
  1380. Reg left = irl->r;
  1381. if (r != left) { /* Mismatch? */
  1382. if (!rset_test(as->freeset, r)) { /* PHI register blocked? */
  1383. IRRef ref = regcost_ref(as->cost[r]);
  1384. /* Blocked by other PHI (w/reg)? */
  1385. if (!ra_iskref(ref) && irt_ismarked(IR(ref)->t)) {
  1386. rset_set(blocked, r);
  1387. if (ra_hasreg(left))
  1388. rset_set(blockedby, left);
  1389. left = RID_NONE;
  1390. } else { /* Otherwise grab register from invariant. */
  1391. ra_restore(as, ref);
  1392. checkmclim(as);
  1393. }
  1394. }
  1395. if (ra_hasreg(left)) {
  1396. ra_rename(as, left, r);
  1397. checkmclim(as);
  1398. }
  1399. }
  1400. rset_clear(phiset, r);
  1401. }
  1402. if (!blocked) break; /* Finished. */
  1403. if (!(as->freeset & blocked)) { /* Break cycles if none are free. */
  1404. asm_phi_break(as, blocked, blockedby, RSET_GPR);
  1405. if (!LJ_SOFTFP) asm_phi_break(as, blocked, blockedby, RSET_FPR);
  1406. checkmclim(as);
  1407. } /* Else retry some more renames. */
  1408. }
  1409. /* Restore/remat invariants whose registers are modified inside the loop. */
  1410. #if !LJ_SOFTFP
  1411. work = as->modset & ~(as->freeset | as->phiset) & RSET_FPR;
  1412. while (work) {
  1413. Reg r = rset_pickbot(work);
  1414. ra_restore(as, regcost_ref(as->cost[r]));
  1415. rset_clear(work, r);
  1416. checkmclim(as);
  1417. }
  1418. #endif
  1419. work = as->modset & ~(as->freeset | as->phiset);
  1420. while (work) {
  1421. Reg r = rset_pickbot(work);
  1422. ra_restore(as, regcost_ref(as->cost[r]));
  1423. rset_clear(work, r);
  1424. checkmclim(as);
  1425. }
  1426. /* Allocate and save all unsaved PHI regs and clear marks. */
  1427. work = as->phiset;
  1428. while (work) {
  1429. Reg r = rset_picktop(work);
  1430. IRRef lref = as->phireg[r];
  1431. IRIns *ir = IR(lref);
  1432. if (ra_hasspill(ir->s)) { /* Left PHI gained a spill slot? */
  1433. irt_clearmark(ir->t); /* Handled here, so clear marker now. */
  1434. ra_alloc1(as, lref, RID2RSET(r));
  1435. ra_save(as, ir, r); /* Save to spill slot inside the loop. */
  1436. checkmclim(as);
  1437. }
  1438. rset_clear(work, r);
  1439. }
  1440. }
  1441. /* Copy unsynced left/right PHI spill slots. Rarely needed. */
  1442. static void asm_phi_copyspill(ASMState *as)
  1443. {
  1444. int need = 0;
  1445. IRIns *ir;
  1446. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--)
  1447. if (ra_hasspill(ir->s) && ra_hasspill(IR(ir->op1)->s))
  1448. need |= irt_isfp(ir->t) ? 2 : 1; /* Unsynced spill slot? */
  1449. if ((need & 1)) { /* Copy integer spill slots. */
  1450. #if !LJ_TARGET_X86ORX64
  1451. Reg r = RID_TMP;
  1452. #else
  1453. Reg r = RID_RET;
  1454. if ((as->freeset & RSET_GPR))
  1455. r = rset_pickbot((as->freeset & RSET_GPR));
  1456. else
  1457. emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1458. #endif
  1459. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
  1460. if (ra_hasspill(ir->s)) {
  1461. IRIns *irl = IR(ir->op1);
  1462. if (ra_hasspill(irl->s) && !irt_isfp(ir->t)) {
  1463. emit_spstore(as, irl, r, sps_scale(irl->s));
  1464. emit_spload(as, ir, r, sps_scale(ir->s));
  1465. checkmclim(as);
  1466. }
  1467. }
  1468. }
  1469. #if LJ_TARGET_X86ORX64
  1470. if (!rset_test(as->freeset, r))
  1471. emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1472. #endif
  1473. }
  1474. #if !LJ_SOFTFP
  1475. if ((need & 2)) { /* Copy FP spill slots. */
  1476. #if LJ_TARGET_X86
  1477. Reg r = RID_XMM0;
  1478. #else
  1479. Reg r = RID_FPRET;
  1480. #endif
  1481. if ((as->freeset & RSET_FPR))
  1482. r = rset_pickbot((as->freeset & RSET_FPR));
  1483. if (!rset_test(as->freeset, r))
  1484. emit_spload(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1485. for (ir = IR(as->orignins-1); ir->o == IR_PHI; ir--) {
  1486. if (ra_hasspill(ir->s)) {
  1487. IRIns *irl = IR(ir->op1);
  1488. if (ra_hasspill(irl->s) && irt_isfp(ir->t)) {
  1489. emit_spstore(as, irl, r, sps_scale(irl->s));
  1490. emit_spload(as, ir, r, sps_scale(ir->s));
  1491. checkmclim(as);
  1492. }
  1493. }
  1494. }
  1495. if (!rset_test(as->freeset, r))
  1496. emit_spstore(as, IR(regcost_ref(as->cost[r])), r, SPOFS_TMP);
  1497. }
  1498. #endif
  1499. }
  1500. /* Emit renames for left PHIs which are only spilled outside the loop. */
  1501. static void asm_phi_fixup(ASMState *as)
  1502. {
  1503. RegSet work = as->phiset;
  1504. while (work) {
  1505. Reg r = rset_picktop(work);
  1506. IRRef lref = as->phireg[r];
  1507. IRIns *ir = IR(lref);
  1508. if (irt_ismarked(ir->t)) {
  1509. irt_clearmark(ir->t);
  1510. /* Left PHI gained a spill slot before the loop? */
  1511. if (ra_hasspill(ir->s)) {
  1512. ra_addrename(as, r, lref, as->loopsnapno);
  1513. }
  1514. }
  1515. rset_clear(work, r);
  1516. }
  1517. }
  1518. /* Setup right PHI reference. */
  1519. static void asm_phi(ASMState *as, IRIns *ir)
  1520. {
  1521. RegSet allow = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) &
  1522. ~as->phiset;
  1523. RegSet afree = (as->freeset & allow);
  1524. IRIns *irl = IR(ir->op1);
  1525. IRIns *irr = IR(ir->op2);
  1526. if (ir->r == RID_SINK) /* Sink PHI. */
  1527. return;
  1528. /* Spill slot shuffling is not implemented yet (but rarely needed). */
  1529. if (ra_hasspill(irl->s) || ra_hasspill(irr->s))
  1530. lj_trace_err(as->J, LJ_TRERR_NYIPHI);
  1531. /* Leave at least one register free for non-PHIs (and PHI cycle breaking). */
  1532. if ((afree & (afree-1))) { /* Two or more free registers? */
  1533. Reg r;
  1534. if (ra_noreg(irr->r)) { /* Get a register for the right PHI. */
  1535. r = ra_allocref(as, ir->op2, allow);
  1536. } else { /* Duplicate right PHI, need a copy (rare). */
  1537. r = ra_scratch(as, allow);
  1538. emit_movrr(as, irr, r, irr->r);
  1539. }
  1540. ir->r = (uint8_t)r;
  1541. rset_set(as->phiset, r);
  1542. as->phireg[r] = (IRRef1)ir->op1;
  1543. irt_setmark(irl->t); /* Marks left PHIs _with_ register. */
  1544. if (ra_noreg(irl->r))
  1545. ra_sethint(irl->r, r); /* Set register hint for left PHI. */
  1546. } else { /* Otherwise allocate a spill slot. */
  1547. /* This is overly restrictive, but it triggers only on synthetic code. */
  1548. if (ra_hasreg(irl->r) || ra_hasreg(irr->r))
  1549. lj_trace_err(as->J, LJ_TRERR_NYIPHI);
  1550. ra_spill(as, ir);
  1551. irr->s = ir->s; /* Set right PHI spill slot. Sync left slot later. */
  1552. }
  1553. }
  1554. static void asm_loop_fixup(ASMState *as);
  1555. /* Middle part of a loop. */
  1556. static void asm_loop(ASMState *as)
  1557. {
  1558. MCode *mcspill;
  1559. /* LOOP is a guard, so the snapno is up to date. */
  1560. as->loopsnapno = as->snapno;
  1561. if (as->gcsteps)
  1562. asm_gc_check(as);
  1563. /* LOOP marks the transition from the variant to the invariant part. */
  1564. as->flagmcp = as->invmcp = NULL;
  1565. as->sectref = 0;
  1566. if (!neverfuse(as)) as->fuseref = 0;
  1567. asm_phi_shuffle(as);
  1568. mcspill = as->mcp;
  1569. asm_phi_copyspill(as);
  1570. asm_loop_fixup(as);
  1571. as->mcloop = as->mcp;
  1572. RA_DBGX((as, "===== LOOP ====="));
  1573. if (!as->realign) RA_DBG_FLUSH();
  1574. if (as->mcp != mcspill)
  1575. emit_jmp(as, mcspill);
  1576. }
  1577. /* -- Target-specific assembler ------------------------------------------- */
  1578. #if LJ_TARGET_X86ORX64
  1579. #include "lj_asm_x86.h"
  1580. #elif LJ_TARGET_ARM
  1581. #include "lj_asm_arm.h"
  1582. #elif LJ_TARGET_ARM64
  1583. #include "lj_asm_arm64.h"
  1584. #elif LJ_TARGET_PPC
  1585. #include "lj_asm_ppc.h"
  1586. #elif LJ_TARGET_MIPS
  1587. #include "lj_asm_mips.h"
  1588. #else
  1589. #error "Missing assembler for target CPU"
  1590. #endif
  1591. /* -- Common instruction helpers ------------------------------------------ */
  1592. #if !LJ_SOFTFP32
  1593. #if !LJ_TARGET_X86ORX64
  1594. #define asm_ldexp(as, ir) asm_callid(as, ir, IRCALL_ldexp)
  1595. #endif
  1596. static void asm_pow(ASMState *as, IRIns *ir)
  1597. {
  1598. #if LJ_64 && LJ_HASFFI
  1599. if (!irt_isnum(ir->t))
  1600. asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
  1601. IRCALL_lj_carith_powu64);
  1602. else
  1603. #endif
  1604. asm_callid(as, ir, IRCALL_pow);
  1605. }
  1606. static void asm_div(ASMState *as, IRIns *ir)
  1607. {
  1608. #if LJ_64 && LJ_HASFFI
  1609. if (!irt_isnum(ir->t))
  1610. asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
  1611. IRCALL_lj_carith_divu64);
  1612. else
  1613. #endif
  1614. asm_fpdiv(as, ir);
  1615. }
  1616. #endif
  1617. static void asm_mod(ASMState *as, IRIns *ir)
  1618. {
  1619. #if LJ_64 && LJ_HASFFI
  1620. if (!irt_isint(ir->t))
  1621. asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
  1622. IRCALL_lj_carith_modu64);
  1623. else
  1624. #endif
  1625. asm_callid(as, ir, IRCALL_lj_vm_modi);
  1626. }
  1627. static void asm_fuseequal(ASMState *as, IRIns *ir)
  1628. {
  1629. /* Fuse HREF + EQ/NE. */
  1630. if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) {
  1631. as->curins--;
  1632. asm_href(as, ir-1, (IROp)ir->o);
  1633. } else {
  1634. asm_equal(as, ir);
  1635. }
  1636. }
  1637. static void asm_alen(ASMState *as, IRIns *ir)
  1638. {
  1639. asm_callid(as, ir, ir->op2 == REF_NIL ? IRCALL_lj_tab_len :
  1640. IRCALL_lj_tab_len_hint);
  1641. }
  1642. /* -- Instruction dispatch ------------------------------------------------ */
  1643. /* Assemble a single instruction. */
  1644. static void asm_ir(ASMState *as, IRIns *ir)
  1645. {
  1646. switch ((IROp)ir->o) {
  1647. /* Miscellaneous ops. */
  1648. case IR_LOOP: asm_loop(as); break;
  1649. case IR_NOP: case IR_XBAR:
  1650. lj_assertA(!ra_used(ir),
  1651. "IR %04d not unused", (int)(ir - as->ir) - REF_BIAS);
  1652. break;
  1653. case IR_USE:
  1654. ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
  1655. case IR_PHI: asm_phi(as, ir); break;
  1656. case IR_HIOP: asm_hiop(as, ir); break;
  1657. case IR_GCSTEP: asm_gcstep(as, ir); break;
  1658. case IR_PROF: asm_prof(as, ir); break;
  1659. /* Guarded assertions. */
  1660. case IR_LT: case IR_GE: case IR_LE: case IR_GT:
  1661. case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
  1662. case IR_ABC:
  1663. asm_comp(as, ir);
  1664. break;
  1665. case IR_EQ: case IR_NE: asm_fuseequal(as, ir); break;
  1666. case IR_RETF: asm_retf(as, ir); break;
  1667. /* Bit ops. */
  1668. case IR_BNOT: asm_bnot(as, ir); break;
  1669. case IR_BSWAP: asm_bswap(as, ir); break;
  1670. case IR_BAND: asm_band(as, ir); break;
  1671. case IR_BOR: asm_bor(as, ir); break;
  1672. case IR_BXOR: asm_bxor(as, ir); break;
  1673. case IR_BSHL: asm_bshl(as, ir); break;
  1674. case IR_BSHR: asm_bshr(as, ir); break;
  1675. case IR_BSAR: asm_bsar(as, ir); break;
  1676. case IR_BROL: asm_brol(as, ir); break;
  1677. case IR_BROR: asm_bror(as, ir); break;
  1678. /* Arithmetic ops. */
  1679. case IR_ADD: asm_add(as, ir); break;
  1680. case IR_SUB: asm_sub(as, ir); break;
  1681. case IR_MUL: asm_mul(as, ir); break;
  1682. case IR_MOD: asm_mod(as, ir); break;
  1683. case IR_NEG: asm_neg(as, ir); break;
  1684. #if LJ_SOFTFP32
  1685. case IR_DIV: case IR_POW: case IR_ABS:
  1686. case IR_LDEXP: case IR_FPMATH: case IR_TOBIT:
  1687. /* Unused for LJ_SOFTFP32. */
  1688. lj_assertA(0, "IR %04d with unused op %d",
  1689. (int)(ir - as->ir) - REF_BIAS, ir->o);
  1690. break;
  1691. #else
  1692. case IR_DIV: asm_div(as, ir); break;
  1693. case IR_POW: asm_pow(as, ir); break;
  1694. case IR_ABS: asm_abs(as, ir); break;
  1695. case IR_LDEXP: asm_ldexp(as, ir); break;
  1696. case IR_FPMATH: asm_fpmath(as, ir); break;
  1697. case IR_TOBIT: asm_tobit(as, ir); break;
  1698. #endif
  1699. case IR_MIN: asm_min(as, ir); break;
  1700. case IR_MAX: asm_max(as, ir); break;
  1701. /* Overflow-checking arithmetic ops. */
  1702. case IR_ADDOV: asm_addov(as, ir); break;
  1703. case IR_SUBOV: asm_subov(as, ir); break;
  1704. case IR_MULOV: asm_mulov(as, ir); break;
  1705. /* Memory references. */
  1706. case IR_AREF: asm_aref(as, ir); break;
  1707. case IR_HREF: asm_href(as, ir, 0); break;
  1708. case IR_HREFK: asm_hrefk(as, ir); break;
  1709. case IR_NEWREF: asm_newref(as, ir); break;
  1710. case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
  1711. case IR_FREF: asm_fref(as, ir); break;
  1712. case IR_TMPREF: asm_tmpref(as, ir); break;
  1713. case IR_STRREF: asm_strref(as, ir); break;
  1714. case IR_LREF: asm_lref(as, ir); break;
  1715. /* Loads and stores. */
  1716. case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  1717. asm_ahuvload(as, ir);
  1718. break;
  1719. case IR_FLOAD: asm_fload(as, ir); break;
  1720. case IR_XLOAD: asm_xload(as, ir); break;
  1721. case IR_SLOAD: asm_sload(as, ir); break;
  1722. case IR_ALEN: asm_alen(as, ir); break;
  1723. case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
  1724. case IR_FSTORE: asm_fstore(as, ir); break;
  1725. case IR_XSTORE: asm_xstore(as, ir); break;
  1726. /* Allocations. */
  1727. case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
  1728. case IR_TNEW: asm_tnew(as, ir); break;
  1729. case IR_TDUP: asm_tdup(as, ir); break;
  1730. case IR_CNEW: case IR_CNEWI:
  1731. #if LJ_HASFFI
  1732. asm_cnew(as, ir);
  1733. #else
  1734. lj_assertA(0, "IR %04d with unused op %d",
  1735. (int)(ir - as->ir) - REF_BIAS, ir->o);
  1736. #endif
  1737. break;
  1738. /* Buffer operations. */
  1739. case IR_BUFHDR: asm_bufhdr(as, ir); break;
  1740. case IR_BUFPUT: asm_bufput(as, ir); break;
  1741. case IR_BUFSTR: asm_bufstr(as, ir); break;
  1742. /* Write barriers. */
  1743. case IR_TBAR: asm_tbar(as, ir); break;
  1744. case IR_OBAR: asm_obar(as, ir); break;
  1745. /* Type conversions. */
  1746. case IR_CONV: asm_conv(as, ir); break;
  1747. case IR_TOSTR: asm_tostr(as, ir); break;
  1748. case IR_STRTO: asm_strto(as, ir); break;
  1749. /* Calls. */
  1750. case IR_CALLA:
  1751. as->gcsteps++;
  1752. /* fallthrough */
  1753. case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
  1754. case IR_CALLXS: asm_callx(as, ir); break;
  1755. case IR_CARG: break;
  1756. default:
  1757. setintV(&as->J->errinfo, ir->o);
  1758. lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
  1759. break;
  1760. }
  1761. }
  1762. /* -- Head of trace ------------------------------------------------------- */
  1763. /* Head of a root trace. */
  1764. static void asm_head_root(ASMState *as)
  1765. {
  1766. int32_t spadj;
  1767. asm_head_root_base(as);
  1768. emit_setvmstate(as, (int32_t)as->T->traceno);
  1769. spadj = asm_stack_adjust(as);
  1770. as->T->spadjust = (uint16_t)spadj;
  1771. emit_spsub(as, spadj);
  1772. /* Root traces assume a checked stack for the starting proto. */
  1773. as->T->topslot = gcref(as->T->startpt)->pt.framesize;
  1774. }
  1775. /* Head of a side trace.
  1776. **
  1777. ** The current simplistic algorithm requires that all slots inherited
  1778. ** from the parent are live in a register between pass 2 and pass 3. This
  1779. ** avoids the complexity of stack slot shuffling. But of course this may
  1780. ** overflow the register set in some cases and cause the dreaded error:
  1781. ** "NYI: register coalescing too complex". A refined algorithm is needed.
  1782. */
  1783. static void asm_head_side(ASMState *as)
  1784. {
  1785. IRRef1 sloadins[RID_MAX];
  1786. RegSet allow = RSET_ALL; /* Inverse of all coalesced registers. */
  1787. RegSet live = RSET_EMPTY; /* Live parent registers. */
  1788. RegSet pallow = RSET_GPR; /* Registers needed by the parent stack check. */
  1789. Reg pbase;
  1790. IRIns *irp = &as->parent->ir[REF_BASE]; /* Parent base. */
  1791. int32_t spadj, spdelta;
  1792. int pass2 = 0;
  1793. int pass3 = 0;
  1794. IRRef i;
  1795. if (as->snapno && as->topslot > as->parent->topslot) {
  1796. /* Force snap #0 alloc to prevent register overwrite in stack check. */
  1797. asm_snap_alloc(as, 0);
  1798. }
  1799. pbase = asm_head_side_base(as, irp);
  1800. if (pbase != RID_NONE) {
  1801. rset_clear(allow, pbase);
  1802. rset_clear(pallow, pbase);
  1803. }
  1804. /* Scan all parent SLOADs and collect register dependencies. */
  1805. for (i = as->stopins; i > REF_BASE; i--) {
  1806. IRIns *ir = IR(i);
  1807. RegSP rs;
  1808. lj_assertA((ir->o == IR_SLOAD && (ir->op2 & IRSLOAD_PARENT)) ||
  1809. (LJ_SOFTFP && ir->o == IR_HIOP) || ir->o == IR_PVAL,
  1810. "IR %04d has bad parent op %d",
  1811. (int)(ir - as->ir) - REF_BIAS, ir->o);
  1812. rs = as->parentmap[i - REF_FIRST];
  1813. if (ra_hasreg(ir->r)) {
  1814. rset_clear(allow, ir->r);
  1815. if (ra_hasspill(ir->s)) {
  1816. ra_save(as, ir, ir->r);
  1817. checkmclim(as);
  1818. }
  1819. } else if (ra_hasspill(ir->s)) {
  1820. irt_setmark(ir->t);
  1821. pass2 = 1;
  1822. }
  1823. if (ir->r == rs) { /* Coalesce matching registers right now. */
  1824. ra_free(as, ir->r);
  1825. } else if (ra_hasspill(regsp_spill(rs))) {
  1826. if (ra_hasreg(ir->r))
  1827. pass3 = 1;
  1828. } else if (ra_used(ir)) {
  1829. sloadins[rs] = (IRRef1)i;
  1830. rset_set(live, rs); /* Block live parent register. */
  1831. }
  1832. if (!ra_hasspill(regsp_spill(rs))) rset_clear(pallow, regsp_reg(rs));
  1833. }
  1834. /* Calculate stack frame adjustment. */
  1835. spadj = asm_stack_adjust(as);
  1836. spdelta = spadj - (int32_t)as->parent->spadjust;
  1837. if (spdelta < 0) { /* Don't shrink the stack frame. */
  1838. spadj = (int32_t)as->parent->spadjust;
  1839. spdelta = 0;
  1840. }
  1841. as->T->spadjust = (uint16_t)spadj;
  1842. /* Reload spilled target registers. */
  1843. if (pass2) {
  1844. for (i = as->stopins; i > REF_BASE; i--) {
  1845. IRIns *ir = IR(i);
  1846. if (irt_ismarked(ir->t)) {
  1847. RegSet mask;
  1848. Reg r;
  1849. RegSP rs;
  1850. irt_clearmark(ir->t);
  1851. rs = as->parentmap[i - REF_FIRST];
  1852. if (!ra_hasspill(regsp_spill(rs)))
  1853. ra_sethint(ir->r, rs); /* Hint may be gone, set it again. */
  1854. else if (sps_scale(regsp_spill(rs))+spdelta == sps_scale(ir->s))
  1855. continue; /* Same spill slot, do nothing. */
  1856. mask = ((!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR) & allow;
  1857. if (mask == RSET_EMPTY)
  1858. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1859. r = ra_allocref(as, i, mask);
  1860. ra_save(as, ir, r);
  1861. rset_clear(allow, r);
  1862. if (r == rs) { /* Coalesce matching registers right now. */
  1863. ra_free(as, r);
  1864. rset_clear(live, r);
  1865. } else if (ra_hasspill(regsp_spill(rs))) {
  1866. pass3 = 1;
  1867. }
  1868. checkmclim(as);
  1869. }
  1870. }
  1871. }
  1872. /* Store trace number and adjust stack frame relative to the parent. */
  1873. emit_setvmstate(as, (int32_t)as->T->traceno);
  1874. emit_spsub(as, spdelta);
  1875. #if !LJ_TARGET_X86ORX64
  1876. /* Restore BASE register from parent spill slot. */
  1877. if (ra_hasspill(irp->s))
  1878. emit_spload(as, IR(REF_BASE), IR(REF_BASE)->r, sps_scale(irp->s));
  1879. #endif
  1880. /* Restore target registers from parent spill slots. */
  1881. if (pass3) {
  1882. RegSet work = ~as->freeset & RSET_ALL;
  1883. while (work) {
  1884. Reg r = rset_pickbot(work);
  1885. IRRef ref = regcost_ref(as->cost[r]);
  1886. RegSP rs = as->parentmap[ref - REF_FIRST];
  1887. rset_clear(work, r);
  1888. if (ra_hasspill(regsp_spill(rs))) {
  1889. int32_t ofs = sps_scale(regsp_spill(rs));
  1890. ra_free(as, r);
  1891. emit_spload(as, IR(ref), r, ofs);
  1892. checkmclim(as);
  1893. }
  1894. }
  1895. }
  1896. /* Shuffle registers to match up target regs with parent regs. */
  1897. for (;;) {
  1898. RegSet work;
  1899. /* Repeatedly coalesce free live registers by moving to their target. */
  1900. while ((work = as->freeset & live) != RSET_EMPTY) {
  1901. Reg rp = rset_pickbot(work);
  1902. IRIns *ir = IR(sloadins[rp]);
  1903. rset_clear(live, rp);
  1904. rset_clear(allow, rp);
  1905. ra_free(as, ir->r);
  1906. emit_movrr(as, ir, ir->r, rp);
  1907. checkmclim(as);
  1908. }
  1909. /* We're done if no live registers remain. */
  1910. if (live == RSET_EMPTY)
  1911. break;
  1912. /* Break cycles by renaming one target to a temp. register. */
  1913. if (live & RSET_GPR) {
  1914. RegSet tmpset = as->freeset & ~live & allow & RSET_GPR;
  1915. if (tmpset == RSET_EMPTY)
  1916. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1917. ra_rename(as, rset_pickbot(live & RSET_GPR), rset_pickbot(tmpset));
  1918. }
  1919. if (!LJ_SOFTFP && (live & RSET_FPR)) {
  1920. RegSet tmpset = as->freeset & ~live & allow & RSET_FPR;
  1921. if (tmpset == RSET_EMPTY)
  1922. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  1923. ra_rename(as, rset_pickbot(live & RSET_FPR), rset_pickbot(tmpset));
  1924. }
  1925. checkmclim(as);
  1926. /* Continue with coalescing to fix up the broken cycle(s). */
  1927. }
  1928. /* Inherit top stack slot already checked by parent trace. */
  1929. as->T->topslot = as->parent->topslot;
  1930. if (as->topslot > as->T->topslot) { /* Need to check for higher slot? */
  1931. #ifdef EXITSTATE_CHECKEXIT
  1932. /* Highest exit + 1 indicates stack check. */
  1933. ExitNo exitno = as->T->nsnap;
  1934. #else
  1935. /* Reuse the parent exit in the context of the parent trace. */
  1936. ExitNo exitno = as->J->exitno;
  1937. #endif
  1938. as->T->topslot = (uint8_t)as->topslot; /* Remember for child traces. */
  1939. asm_stack_check(as, as->topslot, irp, pallow, exitno);
  1940. }
  1941. }
  1942. /* -- Tail of trace ------------------------------------------------------- */
  1943. /* Get base slot for a snapshot. */
  1944. static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
  1945. {
  1946. SnapEntry *map = &as->T->snapmap[snap->mapofs];
  1947. MSize n;
  1948. for (n = snap->nent; n > 0; n--) {
  1949. SnapEntry sn = map[n-1];
  1950. if ((sn & SNAP_FRAME)) {
  1951. *gotframe = 1;
  1952. return snap_slot(sn) - LJ_FR2;
  1953. }
  1954. }
  1955. return 0;
  1956. }
  1957. /* Link to another trace. */
  1958. static void asm_tail_link(ASMState *as)
  1959. {
  1960. SnapNo snapno = as->T->nsnap-1; /* Last snapshot. */
  1961. SnapShot *snap = &as->T->snap[snapno];
  1962. int gotframe = 0;
  1963. BCReg baseslot = asm_baseslot(as, snap, &gotframe);
  1964. as->topslot = snap->topslot;
  1965. checkmclim(as);
  1966. ra_allocref(as, REF_BASE, RID2RSET(RID_BASE));
  1967. if (as->T->link == 0) {
  1968. /* Setup fixed registers for exit to interpreter. */
  1969. const BCIns *pc = snap_pc(&as->T->snapmap[snap->mapofs + snap->nent]);
  1970. int32_t mres;
  1971. if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
  1972. BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
  1973. if (bc_isret(bc_op(*retpc)))
  1974. pc = retpc;
  1975. }
  1976. #if LJ_GC64
  1977. emit_loadu64(as, RID_LPC, u64ptr(pc));
  1978. #else
  1979. ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
  1980. ra_allockreg(as, i32ptr(pc), RID_LPC);
  1981. #endif
  1982. mres = (int32_t)(snap->nslots - baseslot - LJ_FR2);
  1983. switch (bc_op(*pc)) {
  1984. case BC_CALLM: case BC_CALLMT:
  1985. mres -= (int32_t)(1 + LJ_FR2 + bc_a(*pc) + bc_c(*pc)); break;
  1986. case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
  1987. case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
  1988. default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
  1989. }
  1990. ra_allockreg(as, mres, RID_RET); /* Return MULTRES or 0. */
  1991. } else if (baseslot) {
  1992. /* Save modified BASE for linking to trace with higher start frame. */
  1993. emit_setgl(as, RID_BASE, jit_base);
  1994. }
  1995. emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
  1996. if (as->J->ktrace) { /* Patch ktrace slot with the final GCtrace pointer. */
  1997. setgcref(IR(as->J->ktrace)[LJ_GC64].gcr, obj2gco(as->J->curfinal));
  1998. IR(as->J->ktrace)->o = IR_KGC;
  1999. }
  2000. /* Sync the interpreter state with the on-trace state. */
  2001. asm_stack_restore(as, snap);
  2002. /* Root traces that add frames need to check the stack at the end. */
  2003. if (!as->parent && gotframe)
  2004. asm_stack_check(as, as->topslot, NULL, as->freeset & RSET_GPR, snapno);
  2005. }
  2006. /* -- Trace setup --------------------------------------------------------- */
  2007. /* Clear reg/sp for all instructions and add register hints. */
  2008. static void asm_setup_regsp(ASMState *as)
  2009. {
  2010. GCtrace *T = as->T;
  2011. int sink = T->sinktags;
  2012. IRRef nins = T->nins;
  2013. IRIns *ir, *lastir;
  2014. int inloop;
  2015. #if LJ_TARGET_ARM
  2016. uint32_t rload = 0xa6402a64;
  2017. #endif
  2018. ra_setup(as);
  2019. #if LJ_TARGET_ARM64
  2020. ra_setkref(as, RID_GL, (intptr_t)J2G(as->J));
  2021. #endif
  2022. /* Clear reg/sp for constants. */
  2023. for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++) {
  2024. ir->prev = REGSP_INIT;
  2025. if (irt_is64(ir->t) && ir->o != IR_KNULL) {
  2026. #if LJ_GC64
  2027. /* The false-positive of irt_is64() for ASMREF_L (REF_NIL) is OK here. */
  2028. ir->i = 0; /* Will become non-zero only for RIP-relative addresses. */
  2029. #else
  2030. /* Make life easier for backends by putting address of constant in i. */
  2031. ir->i = (int32_t)(intptr_t)(ir+1);
  2032. #endif
  2033. ir++;
  2034. }
  2035. }
  2036. /* REF_BASE is used for implicit references to the BASE register. */
  2037. lastir->prev = REGSP_HINT(RID_BASE);
  2038. as->snaprename = nins;
  2039. as->snapref = nins;
  2040. as->snapno = T->nsnap;
  2041. as->snapalloc = 0;
  2042. as->stopins = REF_BASE;
  2043. as->orignins = nins;
  2044. as->curins = nins;
  2045. /* Setup register hints for parent link instructions. */
  2046. ir = IR(REF_FIRST);
  2047. if (as->parent) {
  2048. uint16_t *p;
  2049. lastir = lj_snap_regspmap(as->J, as->parent, as->J->exitno, ir);
  2050. if (lastir - ir > LJ_MAX_JSLOTS)
  2051. lj_trace_err(as->J, LJ_TRERR_NYICOAL);
  2052. as->stopins = (IRRef)((lastir-1) - as->ir);
  2053. for (p = as->parentmap; ir < lastir; ir++) {
  2054. RegSP rs = ir->prev;
  2055. *p++ = (uint16_t)rs; /* Copy original parent RegSP to parentmap. */
  2056. if (!ra_hasspill(regsp_spill(rs)))
  2057. ir->prev = (uint16_t)REGSP_HINT(regsp_reg(rs));
  2058. else
  2059. ir->prev = REGSP_INIT;
  2060. }
  2061. }
  2062. inloop = 0;
  2063. as->evenspill = SPS_FIRST;
  2064. for (lastir = IR(nins); ir < lastir; ir++) {
  2065. if (sink) {
  2066. if (ir->r == RID_SINK)
  2067. continue;
  2068. if (ir->r == RID_SUNK) { /* Revert after ASM restart. */
  2069. ir->r = RID_SINK;
  2070. continue;
  2071. }
  2072. }
  2073. switch (ir->o) {
  2074. case IR_LOOP:
  2075. inloop = 1;
  2076. break;
  2077. #if LJ_TARGET_ARM
  2078. case IR_SLOAD:
  2079. if (!((ir->op2 & IRSLOAD_TYPECHECK) || (ir+1)->o == IR_HIOP))
  2080. break;
  2081. /* fallthrough */
  2082. case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  2083. if (!LJ_SOFTFP && irt_isnum(ir->t)) break;
  2084. ir->prev = (uint16_t)REGSP_HINT((rload & 15));
  2085. rload = lj_ror(rload, 4);
  2086. continue;
  2087. case IR_TMPREF:
  2088. if ((ir->op2 & IRTMPREF_OUT2) && as->evenspill < 4)
  2089. as->evenspill = 4; /* TMPREF OUT2 needs two TValues on the stack. */
  2090. break;
  2091. #endif
  2092. case IR_CALLXS: {
  2093. CCallInfo ci;
  2094. ci.flags = asm_callx_flags(as, ir);
  2095. ir->prev = asm_setup_call_slots(as, ir, &ci);
  2096. if (inloop)
  2097. as->modset |= RSET_SCRATCH;
  2098. continue;
  2099. }
  2100. case IR_CALLL:
  2101. /* lj_vm_next needs two TValues on the stack. */
  2102. #if LJ_TARGET_X64 && LJ_ABI_WIN
  2103. if (ir->op2 == IRCALL_lj_vm_next && as->evenspill < SPS_FIRST + 4)
  2104. as->evenspill = SPS_FIRST + 4;
  2105. #else
  2106. if (SPS_FIRST < 4 && ir->op2 == IRCALL_lj_vm_next && as->evenspill < 4)
  2107. as->evenspill = 4;
  2108. #endif
  2109. /* fallthrough */
  2110. case IR_CALLN: case IR_CALLA: case IR_CALLS: {
  2111. const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
  2112. ir->prev = asm_setup_call_slots(as, ir, ci);
  2113. if (inloop)
  2114. as->modset |= (ci->flags & CCI_NOFPRCLOBBER) ?
  2115. (RSET_SCRATCH & ~RSET_FPR) : RSET_SCRATCH;
  2116. continue;
  2117. }
  2118. case IR_HIOP:
  2119. switch ((ir-1)->o) {
  2120. #if LJ_SOFTFP && LJ_TARGET_ARM
  2121. case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  2122. if (ra_hashint((ir-1)->r)) {
  2123. ir->prev = (ir-1)->prev + 1;
  2124. continue;
  2125. }
  2126. break;
  2127. #endif
  2128. #if !LJ_SOFTFP && LJ_NEED_FP64 && LJ_32 && LJ_HASFFI
  2129. case IR_CONV:
  2130. if (irt_isfp((ir-1)->t)) {
  2131. ir->prev = REGSP_HINT(RID_FPRET);
  2132. continue;
  2133. }
  2134. #endif
  2135. /* fallthrough */
  2136. case IR_CALLN: case IR_CALLL: case IR_CALLS: case IR_CALLXS:
  2137. #if LJ_SOFTFP
  2138. case IR_MIN: case IR_MAX:
  2139. #endif
  2140. (ir-1)->prev = REGSP_HINT(RID_RETLO);
  2141. ir->prev = REGSP_HINT(RID_RETHI);
  2142. continue;
  2143. default:
  2144. break;
  2145. }
  2146. break;
  2147. #if LJ_SOFTFP
  2148. case IR_MIN: case IR_MAX:
  2149. if ((ir+1)->o != IR_HIOP) break;
  2150. #endif
  2151. /* fallthrough */
  2152. /* C calls evict all scratch regs and return results in RID_RET. */
  2153. case IR_SNEW: case IR_XSNEW: case IR_NEWREF: case IR_BUFPUT:
  2154. if (REGARG_NUMGPR < 3 && as->evenspill < 3)
  2155. as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
  2156. #if LJ_TARGET_X86 && LJ_HASFFI
  2157. if (0) {
  2158. case IR_CNEW:
  2159. if (ir->op2 != REF_NIL && as->evenspill < 4)
  2160. as->evenspill = 4; /* lj_cdata_newv needs 4 args. */
  2161. }
  2162. /* fallthrough */
  2163. #else
  2164. /* fallthrough */
  2165. case IR_CNEW:
  2166. #endif
  2167. /* fallthrough */
  2168. case IR_TNEW: case IR_TDUP: case IR_CNEWI: case IR_TOSTR:
  2169. case IR_BUFSTR:
  2170. ir->prev = REGSP_HINT(RID_RET);
  2171. if (inloop)
  2172. as->modset = RSET_SCRATCH;
  2173. continue;
  2174. case IR_STRTO: case IR_OBAR:
  2175. if (inloop)
  2176. as->modset = RSET_SCRATCH;
  2177. break;
  2178. #if !LJ_SOFTFP
  2179. #if !LJ_TARGET_X86ORX64
  2180. case IR_LDEXP:
  2181. #endif
  2182. #endif
  2183. /* fallthrough */
  2184. case IR_POW:
  2185. if (!LJ_SOFTFP && irt_isnum(ir->t)) {
  2186. if (inloop)
  2187. as->modset |= RSET_SCRATCH;
  2188. #if LJ_TARGET_X86
  2189. if (irt_isnum(IR(ir->op2)->t)) {
  2190. if (as->evenspill < 4) /* Leave room to call pow(). */
  2191. as->evenspill = 4;
  2192. }
  2193. break;
  2194. #else
  2195. ir->prev = REGSP_HINT(RID_FPRET);
  2196. continue;
  2197. #endif
  2198. }
  2199. /* fallthrough */ /* for integer POW */
  2200. case IR_DIV: case IR_MOD:
  2201. if ((LJ_64 && LJ_SOFTFP) || !irt_isnum(ir->t)) {
  2202. ir->prev = REGSP_HINT(RID_RET);
  2203. if (inloop)
  2204. as->modset |= (RSET_SCRATCH & RSET_GPR);
  2205. continue;
  2206. }
  2207. break;
  2208. #if LJ_64 && LJ_SOFTFP
  2209. case IR_ADD: case IR_SUB: case IR_MUL:
  2210. if (irt_isnum(ir->t)) {
  2211. ir->prev = REGSP_HINT(RID_RET);
  2212. if (inloop)
  2213. as->modset |= (RSET_SCRATCH & RSET_GPR);
  2214. continue;
  2215. }
  2216. break;
  2217. #endif
  2218. case IR_FPMATH:
  2219. #if LJ_TARGET_X86ORX64
  2220. if (ir->op2 <= IRFPM_TRUNC) {
  2221. if (!(as->flags & JIT_F_SSE4_1)) {
  2222. ir->prev = REGSP_HINT(RID_XMM0);
  2223. if (inloop)
  2224. as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
  2225. continue;
  2226. }
  2227. break;
  2228. }
  2229. #endif
  2230. if (inloop)
  2231. as->modset |= RSET_SCRATCH;
  2232. #if LJ_TARGET_X86
  2233. break;
  2234. #else
  2235. ir->prev = REGSP_HINT(RID_FPRET);
  2236. continue;
  2237. #endif
  2238. #if LJ_TARGET_X86ORX64
  2239. /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
  2240. case IR_BSHL: case IR_BSHR: case IR_BSAR:
  2241. if ((as->flags & JIT_F_BMI2)) /* Except if BMI2 is available. */
  2242. break;
  2243. /* fallthrough */
  2244. case IR_BROL: case IR_BROR:
  2245. if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
  2246. IR(ir->op2)->r = REGSP_HINT(RID_ECX);
  2247. if (inloop)
  2248. rset_set(as->modset, RID_ECX);
  2249. }
  2250. break;
  2251. #endif
  2252. /* Do not propagate hints across type conversions or loads. */
  2253. case IR_TOBIT:
  2254. case IR_XLOAD:
  2255. #if !LJ_TARGET_ARM
  2256. case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
  2257. #endif
  2258. break;
  2259. case IR_CONV:
  2260. if (irt_isfp(ir->t) || (ir->op2 & IRCONV_SRCMASK) == IRT_NUM ||
  2261. (ir->op2 & IRCONV_SRCMASK) == IRT_FLOAT)
  2262. break;
  2263. /* fallthrough */
  2264. default:
  2265. /* Propagate hints across likely 'op reg, imm' or 'op reg'. */
  2266. if (irref_isk(ir->op2) && !irref_isk(ir->op1) &&
  2267. ra_hashint(regsp_reg(IR(ir->op1)->prev))) {
  2268. ir->prev = IR(ir->op1)->prev;
  2269. continue;
  2270. }
  2271. break;
  2272. }
  2273. ir->prev = REGSP_INIT;
  2274. }
  2275. if ((as->evenspill & 1))
  2276. as->oddspill = as->evenspill++;
  2277. else
  2278. as->oddspill = 0;
  2279. }
  2280. /* -- Assembler core ------------------------------------------------------ */
  2281. /* Assemble a trace. */
  2282. void lj_asm_trace(jit_State *J, GCtrace *T)
  2283. {
  2284. ASMState as_;
  2285. ASMState *as = &as_;
  2286. /* Remove nops/renames left over from ASM restart due to LJ_TRERR_MCODELM. */
  2287. {
  2288. IRRef nins = T->nins;
  2289. IRIns *ir = &T->ir[nins-1];
  2290. if (ir->o == IR_NOP || ir->o == IR_RENAME) {
  2291. do { ir--; nins--; } while (ir->o == IR_NOP || ir->o == IR_RENAME);
  2292. T->nins = nins;
  2293. }
  2294. }
  2295. /* Ensure an initialized instruction beyond the last one for HIOP checks. */
  2296. /* This also allows one RENAME to be added without reallocating curfinal. */
  2297. as->orignins = lj_ir_nextins(J);
  2298. lj_ir_nop(&J->cur.ir[as->orignins]);
  2299. /* Setup initial state. Copy some fields to reduce indirections. */
  2300. as->J = J;
  2301. as->T = T;
  2302. J->curfinal = lj_trace_alloc(J->L, T); /* This copies the IR, too. */
  2303. as->flags = J->flags;
  2304. as->loopref = J->loopref;
  2305. as->realign = NULL;
  2306. as->loopinv = 0;
  2307. as->parent = J->parent ? traceref(J, J->parent) : NULL;
  2308. #ifdef LUAJIT_RANDOM_RA
  2309. (void)lj_prng_u64(&J2G(J)->prng); /* Ensure PRNG step between traces. */
  2310. #endif
  2311. /* Reserve MCode memory. */
  2312. as->mctop = as->mctoporig = lj_mcode_reserve(J, &as->mcbot);
  2313. as->mcp = as->mctop;
  2314. as->mclim = as->mcbot + MCLIM_REDZONE;
  2315. asm_setup_target(as);
  2316. /*
  2317. ** This is a loop, because the MCode may have to be (re-)assembled
  2318. ** multiple times:
  2319. **
  2320. ** 1. as->realign is set (and the assembly aborted), if the arch-specific
  2321. ** backend wants the MCode to be aligned differently.
  2322. **
  2323. ** This is currently only the case on x86/x64, where small loops get
  2324. ** an aligned loop body plus a short branch. Not much effort is wasted,
  2325. ** because the abort happens very quickly and only once.
  2326. **
  2327. ** 2. The IR is immovable, since the MCode embeds pointers to various
  2328. ** constants inside the IR. But RENAMEs may need to be added to the IR
  2329. ** during assembly, which might grow and reallocate the IR. We check
  2330. ** at the end if the IR (in J->cur.ir) has actually grown, resize the
  2331. ** copy (in J->curfinal.ir) and try again.
  2332. **
  2333. ** 95% of all traces have zero RENAMEs, 3% have one RENAME, 1.5% have
  2334. ** 2 RENAMEs and only 0.5% have more than that. That's why we opt to
  2335. ** always have one spare slot in the IR (see above), which means we
  2336. ** have to redo the assembly for only ~2% of all traces.
  2337. **
  2338. ** Very, very rarely, this needs to be done repeatedly, since the
  2339. ** location of constants inside the IR (actually, reachability from
  2340. ** a global pointer) may affect register allocation and thus the
  2341. ** number of RENAMEs.
  2342. */
  2343. for (;;) {
  2344. as->mcp = as->mctop;
  2345. #ifdef LUA_USE_ASSERT
  2346. as->mcp_prev = as->mcp;
  2347. #endif
  2348. as->ir = J->curfinal->ir; /* Use the copied IR. */
  2349. as->curins = J->cur.nins = as->orignins;
  2350. #ifdef LUAJIT_RANDOM_RA
  2351. as->prngstate = J2G(J)->prng; /* Must (re)start from identical state. */
  2352. as->prngbits = 0;
  2353. #endif
  2354. RA_DBG_START();
  2355. RA_DBGX((as, "===== STOP ====="));
  2356. /* General trace setup. Emit tail of trace. */
  2357. asm_tail_prep(as);
  2358. as->mcloop = NULL;
  2359. as->flagmcp = NULL;
  2360. as->topslot = 0;
  2361. as->gcsteps = 0;
  2362. as->sectref = as->loopref;
  2363. as->fuseref = (as->flags & JIT_F_OPT_FUSE) ? as->loopref : FUSE_DISABLED;
  2364. asm_setup_regsp(as);
  2365. if (!as->loopref)
  2366. asm_tail_link(as);
  2367. /* Assemble a trace in linear backwards order. */
  2368. for (as->curins--; as->curins > as->stopins; as->curins--) {
  2369. IRIns *ir = IR(as->curins);
  2370. /* 64 bit types handled by SPLIT for 32 bit archs. */
  2371. lj_assertA(!(LJ_32 && irt_isint64(ir->t)),
  2372. "IR %04d has unsplit 64 bit type",
  2373. (int)(ir - as->ir) - REF_BIAS);
  2374. asm_snap_prev(as);
  2375. if (!ra_used(ir) && !ir_sideeff(ir) && (as->flags & JIT_F_OPT_DCE))
  2376. continue; /* Dead-code elimination can be soooo easy. */
  2377. if (irt_isguard(ir->t))
  2378. asm_snap_prep(as);
  2379. RA_DBG_REF();
  2380. checkmclim(as);
  2381. asm_ir(as, ir);
  2382. }
  2383. if (as->realign && J->curfinal->nins >= T->nins)
  2384. continue; /* Retry in case only the MCode needs to be realigned. */
  2385. /* Emit head of trace. */
  2386. RA_DBG_REF();
  2387. checkmclim(as);
  2388. if (as->gcsteps > 0) {
  2389. as->curins = as->T->snap[0].ref;
  2390. asm_snap_prep(as); /* The GC check is a guard. */
  2391. asm_gc_check(as);
  2392. as->curins = as->stopins;
  2393. }
  2394. ra_evictk(as);
  2395. if (as->parent)
  2396. asm_head_side(as);
  2397. else
  2398. asm_head_root(as);
  2399. asm_phi_fixup(as);
  2400. if (J->curfinal->nins >= T->nins) { /* IR didn't grow? */
  2401. lj_assertA(J->curfinal->nk == T->nk, "unexpected IR constant growth");
  2402. memcpy(J->curfinal->ir + as->orignins, T->ir + as->orignins,
  2403. (T->nins - as->orignins) * sizeof(IRIns)); /* Copy RENAMEs. */
  2404. T->nins = J->curfinal->nins;
  2405. /* Fill mcofs of any unprocessed snapshots. */
  2406. as->curins = REF_FIRST;
  2407. asm_snap_prev(as);
  2408. break; /* Done. */
  2409. }
  2410. /* Otherwise try again with a bigger IR. */
  2411. lj_trace_free(J2G(J), J->curfinal);
  2412. J->curfinal = NULL; /* In case lj_trace_alloc() OOMs. */
  2413. J->curfinal = lj_trace_alloc(J->L, T);
  2414. as->realign = NULL;
  2415. }
  2416. RA_DBGX((as, "===== START ===="));
  2417. RA_DBG_FLUSH();
  2418. if (as->freeset != RSET_ALL)
  2419. lj_trace_err(as->J, LJ_TRERR_BADRA); /* Ouch! Should never happen. */
  2420. /* Set trace entry point before fixing up tail to allow link to self. */
  2421. T->mcode = as->mcp;
  2422. T->mcloop = as->mcloop ? (MSize)((char *)as->mcloop - (char *)as->mcp) : 0;
  2423. if (as->loopref)
  2424. asm_loop_tail_fixup(as);
  2425. else
  2426. asm_tail_fixup(as, T->link); /* Note: this may change as->mctop! */
  2427. T->szmcode = (MSize)((char *)as->mctop - (char *)as->mcp);
  2428. asm_snap_fixup_mcofs(as);
  2429. #if LJ_TARGET_MCODE_FIXUP
  2430. asm_mcode_fixup(T->mcode, T->szmcode);
  2431. #endif
  2432. lj_mcode_sync(T->mcode, as->mctoporig);
  2433. }
  2434. #undef IR
  2435. #endif