src/lj_opt_mem.c - luajit-2.0-src

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** Memory access optimizations.
  3. ** AA: Alias Analysis using high-level semantic disambiguation.
  4. ** FWD: Load Forwarding (L2L) + Store Forwarding (S2L).
  5. ** DSE: Dead-Store Elimination.
  6. ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
  7. */

  8. #define lj_opt_mem_c
  9. #define LUA_CORE

  10. #include "lj_obj.h"

  11. #if LJ_HASJIT

  12. #include "lj_tab.h"
  13. #include "lj_ir.h"
  14. #include "lj_jit.h"
  15. #include "lj_iropt.h"
  16. #include "lj_ircall.h"

  17. /* Some local macros to save typing. Undef'd at the end. */
  18. #define IR(ref)                (&J->cur.ir[(ref)])
  19. #define fins                (&J->fold.ins)
  20. #define fleft                (&J->fold.left)
  21. #define fright                (&J->fold.right)

  22. /*
  23. ** Caveat #1: return value is not always a TRef -- only use with tref_ref().
  24. ** Caveat #2: FWD relies on active CSE for xREF operands -- see lj_opt_fold().
  25. */

  26. /* Return values from alias analysis. */
  27. typedef enum {
  28.   ALIAS_NO,        /* The two refs CANNOT alias (exact). */
  29.   ALIAS_MAY,        /* The two refs MAY alias (inexact). */
  30.   ALIAS_MUST        /* The two refs MUST alias (exact). */
  31. } AliasRet;

  32. /* -- ALOAD/HLOAD forwarding and ASTORE/HSTORE elimination ---------------- */

  33. /* Simplified escape analysis: check for intervening stores. */
  34. static AliasRet aa_escape(jit_State *J, IRIns *ir, IRIns *stop)
  35. {
  36.   IRRef ref = (IRRef)(ir - J->cur.ir);  /* The ref that might be stored. */
  37.   for (ir++; ir < stop; ir++)
  38.     if (ir->op2 == ref &&
  39.         (ir->o == IR_ASTORE || ir->o == IR_HSTORE ||
  40.          ir->o == IR_USTORE || ir->o == IR_FSTORE))
  41.       return ALIAS_MAY;  /* Reference was stored and might alias. */
  42.   return ALIAS_NO;  /* Reference was not stored. */
  43. }

  44. /* Alias analysis for two different table references. */
  45. static AliasRet aa_table(jit_State *J, IRRef ta, IRRef tb)
  46. {
  47.   IRIns *taba = IR(ta), *tabb = IR(tb);
  48.   int newa, newb;
  49.   lua_assert(ta != tb);
  50.   lua_assert(irt_istab(taba->t) && irt_istab(tabb->t));
  51.   /* Disambiguate new allocations. */
  52.   newa = (taba->o == IR_TNEW || taba->o == IR_TDUP);
  53.   newb = (tabb->o == IR_TNEW || tabb->o == IR_TDUP);
  54.   if (newa && newb)
  55.     return ALIAS_NO;  /* Two different allocations never alias. */
  56.   if (newb) {  /* At least one allocation? */
  57.     IRIns *tmp = taba; taba = tabb; tabb = tmp;
  58.   } else if (!newa) {
  59.     return ALIAS_MAY;  /* Anything else: we just don't know. */
  60.   }
  61.   return aa_escape(J, taba, tabb);
  62. }

  63. /* Alias analysis for array and hash access using key-based disambiguation. */
  64. static AliasRet aa_ahref(jit_State *J, IRIns *refa, IRIns *refb)
  65. {
  66.   IRRef ka = refa->op2;
  67.   IRRef kb = refb->op2;
  68.   IRIns *keya, *keyb;
  69.   IRRef ta, tb;
  70.   if (refa == refb)
  71.     return ALIAS_MUST;  /* Shortcut for same refs. */
  72.   keya = IR(ka);
  73.   if (keya->o == IR_KSLOT) { ka = keya->op1; keya = IR(ka); }
  74.   keyb = IR(kb);
  75.   if (keyb->o == IR_KSLOT) { kb = keyb->op1; keyb = IR(kb); }
  76.   ta = (refa->o==IR_HREFK || refa->o==IR_AREF) ? IR(refa->op1)->op1 : refa->op1;
  77.   tb = (refb->o==IR_HREFK || refb->o==IR_AREF) ? IR(refb->op1)->op1 : refb->op1;
  78.   if (ka == kb) {
  79.     /* Same key. Check for same table with different ref (NEWREF vs. HREF). */
  80.     if (ta == tb)
  81.       return ALIAS_MUST;  /* Same key, same table. */
  82.     else
  83.       return aa_table(J, ta, tb);  /* Same key, possibly different table. */
  84.   }
  85.   if (irref_isk(ka) && irref_isk(kb))
  86.     return ALIAS_NO;  /* Different constant keys. */
  87.   if (refa->o == IR_AREF) {
  88.     /* Disambiguate array references based on index arithmetic. */
  89.     int32_t ofsa = 0, ofsb = 0;
  90.     IRRef basea = ka, baseb = kb;
  91.     lua_assert(refb->o == IR_AREF);
  92.     /* Gather base and offset from t[base] or t[base+-ofs]. */
  93.     if (keya->o == IR_ADD && irref_isk(keya->op2)) {
  94.       basea = keya->op1;
  95.       ofsa = IR(keya->op2)->i;
  96.       if (basea == kb && ofsa != 0)
  97.         return ALIAS_NO;  /* t[base+-ofs] vs. t[base]. */
  98.     }
  99.     if (keyb->o == IR_ADD && irref_isk(keyb->op2)) {
  100.       baseb = keyb->op1;
  101.       ofsb = IR(keyb->op2)->i;
  102.       if (ka == baseb && ofsb != 0)
  103.         return ALIAS_NO;  /* t[base] vs. t[base+-ofs]. */
  104.     }
  105.     if (basea == baseb && ofsa != ofsb)
  106.       return ALIAS_NO;  /* t[base+-o1] vs. t[base+-o2] and o1 != o2. */
  107.   } else {
  108.     /* Disambiguate hash references based on the type of their keys. */
  109.     lua_assert((refa->o==IR_HREF || refa->o==IR_HREFK || refa->o==IR_NEWREF) &&
  110.                (refb->o==IR_HREF || refb->o==IR_HREFK || refb->o==IR_NEWREF));
  111.     if (!irt_sametype(keya->t, keyb->t))
  112.       return ALIAS_NO;  /* Different key types. */
  113.   }
  114.   if (ta == tb)
  115.     return ALIAS_MAY;  /* Same table, cannot disambiguate keys. */
  116.   else
  117.     return aa_table(J, ta, tb);  /* Try to disambiguate tables. */
  118. }

  119. /* Array and hash load forwarding. */
  120. static TRef fwd_ahload(jit_State *J, IRRef xref)
  121. {
  122.   IRIns *xr = IR(xref);
  123.   IRRef lim = xref;  /* Search limit. */
  124.   IRRef ref;

  125.   /* Search for conflicting stores. */
  126.   ref = J->chain[fins->o+IRDELTA_L2S];
  127.   while (ref > xref) {
  128.     IRIns *store = IR(ref);
  129.     switch (aa_ahref(J, xr, IR(store->op1))) {
  130.     case ALIAS_NO:   break/* Continue searching. */
  131.     case ALIAS_MAY:  lim = ref; goto cselim;  /* Limit search for load. */
  132.     case ALIAS_MUST: return store->op2;  /* Store forwarding. */
  133.     }
  134.     ref = store->prev;
  135.   }

  136.   /* No conflicting store (yet): const-fold loads from allocations. */
  137.   {
  138.     IRIns *ir = (xr->o == IR_HREFK || xr->o == IR_AREF) ? IR(xr->op1) : xr;
  139.     IRRef tab = ir->op1;
  140.     ir = IR(tab);
  141.     if (ir->o == IR_TNEW || (ir->o == IR_TDUP && irref_isk(xr->op2))) {
  142.       /* A NEWREF with a number key may end up pointing to the array part.
  143.       ** But it's referenced from HSTORE and not found in the ASTORE chain.
  144.       ** For now simply consider this a conflict without forwarding anything.
  145.       */
  146.       if (xr->o == IR_AREF) {
  147.         IRRef ref2 = J->chain[IR_NEWREF];
  148.         while (ref2 > tab) {
  149.           IRIns *newref = IR(ref2);
  150.           if (irt_isnum(IR(newref->op2)->t))
  151.             goto cselim;
  152.           ref2 = newref->prev;
  153.         }
  154.       }
  155.       /* NEWREF inhibits CSE for HREF, and dependent FLOADs from HREFK/AREF.
  156.       ** But the above search for conflicting stores was limited by xref.
  157.       ** So continue searching, limited by the TNEW/TDUP. Store forwarding
  158.       ** is ok, too. A conflict does NOT limit the search for a matching load.
  159.       */
  160.       while (ref > tab) {
  161.         IRIns *store = IR(ref);
  162.         switch (aa_ahref(J, xr, IR(store->op1))) {
  163.         case ALIAS_NO:   break/* Continue searching. */
  164.         case ALIAS_MAY:  goto cselim;  /* Conflicting store. */
  165.         case ALIAS_MUST: return store->op2;  /* Store forwarding. */
  166.         }
  167.         ref = store->prev;
  168.       }
  169.       lua_assert(ir->o != IR_TNEW || irt_isnil(fins->t));
  170.       if (irt_ispri(fins->t)) {
  171.         return TREF_PRI(irt_type(fins->t));
  172.       } else if (irt_isnum(fins->t) || (LJ_DUALNUM && irt_isint(fins->t)) ||
  173.                  irt_isstr(fins->t)) {
  174.         TValue keyv;
  175.         cTValue *tv;
  176.         IRIns *key = IR(xr->op2);
  177.         if (key->o == IR_KSLOT) key = IR(key->op1);
  178.         lj_ir_kvalue(J->L, &keyv, key);
  179.         tv = lj_tab_get(J->L, ir_ktab(IR(ir->op1)), &keyv);
  180.         lua_assert(itype2irt(tv) == irt_type(fins->t));
  181.         if (irt_isnum(fins->t))
  182.           return lj_ir_knum_u64(J, tv->u64);
  183.         else if (LJ_DUALNUM && irt_isint(fins->t))
  184.           return lj_ir_kint(J, intV(tv));
  185.         else
  186.           return lj_ir_kstr(J, strV(tv));
  187.       }
  188.       /* Othwerwise: don't intern as a constant. */
  189.     }
  190.   }

  191. cselim:
  192.   /* Try to find a matching load. Below the conflicting store, if any. */
  193.   ref = J->chain[fins->o];
  194.   while (ref > lim) {
  195.     IRIns *load = IR(ref);
  196.     if (load->op1 == xref)
  197.       return ref;  /* Load forwarding. */
  198.     ref = load->prev;
  199.   }
  200.   return 0/* Conflict or no match. */
  201. }

  202. /* Reassociate ALOAD across PHIs to handle t[i-1] forwarding case. */
  203. static TRef fwd_aload_reassoc(jit_State *J)
  204. {
  205.   IRIns *irx = IR(fins->op1);
  206.   IRIns *key = IR(irx->op2);
  207.   if (key->o == IR_ADD && irref_isk(key->op2)) {
  208.     IRIns *add2 = IR(key->op1);
  209.     if (add2->o == IR_ADD && irref_isk(add2->op2) &&
  210.         IR(key->op2)->i == -IR(add2->op2)->i) {
  211.       IRRef ref = J->chain[IR_AREF];
  212.       IRRef lim = add2->op1;
  213.       if (irx->op1 > lim) lim = irx->op1;
  214.       while (ref > lim) {
  215.         IRIns *ir = IR(ref);
  216.         if (ir->op1 == irx->op1 && ir->op2 == add2->op1)
  217.           return fwd_ahload(J, ref);
  218.         ref = ir->prev;
  219.       }
  220.     }
  221.   }
  222.   return 0;
  223. }

  224. /* ALOAD forwarding. */
  225. TRef LJ_FASTCALL lj_opt_fwd_aload(jit_State *J)
  226. {
  227.   IRRef ref;
  228.   if ((ref = fwd_ahload(J, fins->op1)) ||
  229.       (ref = fwd_aload_reassoc(J)))
  230.     return ref;
  231.   return EMITFOLD;
  232. }

  233. /* HLOAD forwarding. */
  234. TRef LJ_FASTCALL lj_opt_fwd_hload(jit_State *J)
  235. {
  236.   IRRef ref = fwd_ahload(J, fins->op1);
  237.   if (ref)
  238.     return ref;
  239.   return EMITFOLD;
  240. }

  241. /* HREFK forwarding. */
  242. TRef LJ_FASTCALL lj_opt_fwd_hrefk(jit_State *J)
  243. {
  244.   IRRef tab = fleft->op1;
  245.   IRRef ref = J->chain[IR_NEWREF];
  246.   while (ref > tab) {
  247.     IRIns *newref = IR(ref);
  248.     if (tab == newref->op1) {
  249.       if (fright->op1 == newref->op2)
  250.         return ref;  /* Forward from NEWREF. */
  251.       else
  252.         goto docse;
  253.     } else if (aa_table(J, tab, newref->op1) != ALIAS_NO) {
  254.       goto docse;
  255.     }
  256.     ref = newref->prev;
  257.   }
  258.   /* No conflicting NEWREF: key location unchanged for HREFK of TDUP. */
  259.   if (IR(tab)->o == IR_TDUP)
  260.     fins->t.irt &= ~IRT_GUARD;  /* Drop HREFK guard. */
  261. docse:
  262.   return CSEFOLD;
  263. }

  264. /* Check whether HREF of TNEW/TDUP can be folded to niltv. */
  265. int LJ_FASTCALL lj_opt_fwd_href_nokey(jit_State *J)
  266. {
  267.   IRRef lim = fins->op1;  /* Search limit. */
  268.   IRRef ref;

  269.   /* The key for an ASTORE may end up in the hash part after a NEWREF. */
  270.   if (irt_isnum(fright->t) && J->chain[IR_NEWREF] > lim) {
  271.     ref = J->chain[IR_ASTORE];
  272.     while (ref > lim) {
  273.       if (ref < J->chain[IR_NEWREF])
  274.         return 0/* Conflict. */
  275.       ref = IR(ref)->prev;
  276.     }
  277.   }

  278.   /* Search for conflicting stores. */
  279.   ref = J->chain[IR_HSTORE];
  280.   while (ref > lim) {
  281.     IRIns *store = IR(ref);
  282.     if (aa_ahref(J, fins, IR(store->op1)) != ALIAS_NO)
  283.       return 0/* Conflict. */
  284.     ref = store->prev;
  285.   }

  286.   return 1/* No conflict. Can fold to niltv. */
  287. }

  288. /* Check whether there's no aliasing table.clear. */
  289. static int fwd_aa_tab_clear(jit_State *J, IRRef lim, IRRef ta)
  290. {
  291.   IRRef ref = J->chain[IR_CALLS];
  292.   while (ref > lim) {
  293.     IRIns *calls = IR(ref);
  294.     if (calls->op2 == IRCALL_lj_tab_clear &&
  295.         (ta == calls->op1 || aa_table(J, ta, calls->op1) != ALIAS_NO))
  296.       return 0/* Conflict. */
  297.     ref = calls->prev;
  298.   }
  299.   return 1/* No conflict. Can safely FOLD/CSE. */
  300. }

  301. /* Check whether there's no aliasing NEWREF/table.clear for the left operand. */
  302. int LJ_FASTCALL lj_opt_fwd_tptr(jit_State *J, IRRef lim)
  303. {
  304.   IRRef ta = fins->op1;
  305.   IRRef ref = J->chain[IR_NEWREF];
  306.   while (ref > lim) {
  307.     IRIns *newref = IR(ref);
  308.     if (ta == newref->op1 || aa_table(J, ta, newref->op1) != ALIAS_NO)
  309.       return 0/* Conflict. */
  310.     ref = newref->prev;
  311.   }
  312.   return fwd_aa_tab_clear(J, lim, ta);
  313. }

  314. /* ASTORE/HSTORE elimination. */
  315. TRef LJ_FASTCALL lj_opt_dse_ahstore(jit_State *J)
  316. {
  317.   IRRef xref = fins->op1;  /* xREF reference. */
  318.   IRRef val = fins->op2;  /* Stored value reference. */
  319.   IRIns *xr = IR(xref);
  320.   IRRef1 *refp = &J->chain[fins->o];
  321.   IRRef ref = *refp;
  322.   while (ref > xref) {  /* Search for redundant or conflicting stores. */
  323.     IRIns *store = IR(ref);
  324.     switch (aa_ahref(J, xr, IR(store->op1))) {
  325.     case ALIAS_NO:
  326.       break/* Continue searching. */
  327.     case ALIAS_MAY:        /* Store to MAYBE the same location. */
  328.       if (store->op2 != val)  /* Conflict if the value is different. */
  329.         goto doemit;
  330.       break/* Otherwise continue searching. */
  331.     case ALIAS_MUST:        /* Store to the same location. */
  332.       if (store->op2 == val)  /* Same value: drop the new store. */
  333.         return DROPFOLD;
  334.       /* Different value: try to eliminate the redundant store. */
  335.       if (ref > J->chain[IR_LOOP]) {  /* Quick check to avoid crossing LOOP. */
  336.         IRIns *ir;
  337.         /* Check for any intervening guards (includes conflicting loads). */
  338.         for (ir = IR(J->cur.nins-1); ir > store; ir--)
  339.           if (irt_isguard(ir->t) || ir->o == IR_CALLL)
  340.             goto doemit;  /* No elimination possible. */
  341.         /* Remove redundant store from chain and replace with NOP. */
  342.         *refp = store->prev;
  343.         store->o = IR_NOP;
  344.         store->t.irt = IRT_NIL;
  345.         store->op1 = store->op2 = 0;
  346.         store->prev = 0;
  347.         /* Now emit the new store instead. */
  348.       }
  349.       goto doemit;
  350.     }
  351.     ref = *(refp = &store->prev);
  352.   }
  353. doemit:
  354.   return EMITFOLD/* Otherwise we have a conflict or simply no match. */
  355. }

  356. /* -- ULOAD forwarding ---------------------------------------------------- */

  357. /* The current alias analysis for upvalues is very simplistic. It only
  358. ** disambiguates between the unique upvalues of the same function.
  359. ** This is good enough for now, since most upvalues are read-only.
  360. **
  361. ** A more precise analysis would be feasible with the help of the parser:
  362. ** generate a unique key for every upvalue, even across all prototypes.
  363. ** Lacking a realistic use-case, it's unclear whether this is beneficial.
  364. */
  365. static AliasRet aa_uref(IRIns *refa, IRIns *refb)
  366. {
  367.   if (refa->o != refb->o)
  368.     return ALIAS_NO;  /* Different UREFx type. */
  369.   if (refa->op1 == refb->op1) {  /* Same function. */
  370.     if (refa->op2 == refb->op2)
  371.       return ALIAS_MUST;  /* Same function, same upvalue idx. */
  372.     else
  373.       return ALIAS_NO;  /* Same function, different upvalue idx. */
  374.   } else/* Different functions, check disambiguation hash values. */
  375.     if (((refa->op2 ^ refb->op2) & 0xff))
  376.       return ALIAS_NO;  /* Upvalues with different hash values cannot alias. */
  377.     else
  378.       return ALIAS_MAY;  /* No conclusion can be drawn for same hash value. */
  379.   }
  380. }

  381. /* ULOAD forwarding. */
  382. TRef LJ_FASTCALL lj_opt_fwd_uload(jit_State *J)
  383. {
  384.   IRRef uref = fins->op1;
  385.   IRRef lim = REF_BASE;  /* Search limit. */
  386.   IRIns *xr = IR(uref);
  387.   IRRef ref;

  388.   /* Search for conflicting stores. */
  389.   ref = J->chain[IR_USTORE];
  390.   while (ref > lim) {
  391.     IRIns *store = IR(ref);
  392.     switch (aa_uref(xr, IR(store->op1))) {
  393.     case ALIAS_NO:   break/* Continue searching. */
  394.     case ALIAS_MAY:  lim = ref; goto cselim;  /* Limit search for load. */
  395.     case ALIAS_MUST: return store->op2;  /* Store forwarding. */
  396.     }
  397.     ref = store->prev;
  398.   }

  399. cselim:
  400.   /* Try to find a matching load. Below the conflicting store, if any. */

  401.   ref = J->chain[IR_ULOAD];
  402.   while (ref > lim) {
  403.     IRIns *ir = IR(ref);
  404.     if (ir->op1 == uref ||
  405.         (IR(ir->op1)->op12 == IR(uref)->op12 && IR(ir->op1)->o == IR(uref)->o))
  406.       return ref;  /* Match for identical or equal UREFx (non-CSEable UREFO). */
  407.     ref = ir->prev;
  408.   }
  409.   return lj_ir_emit(J);
  410. }

  411. /* USTORE elimination. */
  412. TRef LJ_FASTCALL lj_opt_dse_ustore(jit_State *J)
  413. {
  414.   IRRef xref = fins->op1;  /* xREF reference. */
  415.   IRRef val = fins->op2;  /* Stored value reference. */
  416.   IRIns *xr = IR(xref);
  417.   IRRef1 *refp = &J->chain[IR_USTORE];
  418.   IRRef ref = *refp;
  419.   while (ref > xref) {  /* Search for redundant or conflicting stores. */
  420.     IRIns *store = IR(ref);
  421.     switch (aa_uref(xr, IR(store->op1))) {
  422.     case ALIAS_NO:
  423.       break/* Continue searching. */
  424.     case ALIAS_MAY:        /* Store to MAYBE the same location. */
  425.       if (store->op2 != val)  /* Conflict if the value is different. */
  426.         goto doemit;
  427.       break/* Otherwise continue searching. */
  428.     case ALIAS_MUST:        /* Store to the same location. */
  429.       if (store->op2 == val)  /* Same value: drop the new store. */
  430.         return DROPFOLD;
  431.       /* Different value: try to eliminate the redundant store. */
  432.       if (ref > J->chain[IR_LOOP]) {  /* Quick check to avoid crossing LOOP. */
  433.         IRIns *ir;
  434.         /* Check for any intervening guards (includes conflicting loads). */
  435.         for (ir = IR(J->cur.nins-1); ir > store; ir--)
  436.           if (irt_isguard(ir->t))
  437.             goto doemit;  /* No elimination possible. */
  438.         /* Remove redundant store from chain and replace with NOP. */
  439.         *refp = store->prev;
  440.         store->o = IR_NOP;
  441.         store->t.irt = IRT_NIL;
  442.         store->op1 = store->op2 = 0;
  443.         store->prev = 0;
  444.         if (ref+1 < J->cur.nins &&
  445.             store[1].o == IR_OBAR && store[1].op1 == xref) {
  446.           IRRef1 *bp = &J->chain[IR_OBAR];
  447.           IRIns *obar;
  448.           for (obar = IR(*bp); *bp > ref+1; obar = IR(*bp))
  449.             bp = &obar->prev;
  450.           /* Remove OBAR, too. */
  451.           *bp = obar->prev;
  452.           obar->o = IR_NOP;
  453.           obar->t.irt = IRT_NIL;
  454.           obar->op1 = obar->op2 = 0;
  455.           obar->prev = 0;
  456.         }
  457.         /* Now emit the new store instead. */
  458.       }
  459.       goto doemit;
  460.     }
  461.     ref = *(refp = &store->prev);
  462.   }
  463. doemit:
  464.   return EMITFOLD/* Otherwise we have a conflict or simply no match. */
  465. }

  466. /* -- FLOAD forwarding and FSTORE elimination ----------------------------- */

  467. /* Alias analysis for field access.
  468. ** Field loads are cheap and field stores are rare.
  469. ** Simple disambiguation based on field types is good enough.
  470. */
  471. static AliasRet aa_fref(jit_State *J, IRIns *refa, IRIns *refb)
  472. {
  473.   if (refa->op2 != refb->op2)
  474.     return ALIAS_NO;  /* Different fields. */
  475.   if (refa->op1 == refb->op1)
  476.     return ALIAS_MUST;  /* Same field, same object. */
  477.   else if (refa->op2 >= IRFL_TAB_META && refa->op2 <= IRFL_TAB_NOMM)
  478.     return aa_table(J, refa->op1, refb->op1);  /* Disambiguate tables. */
  479.   else
  480.     return ALIAS_MAY;  /* Same field, possibly different object. */
  481. }

  482. /* Only the loads for mutable fields end up here (see FOLD). */
  483. TRef LJ_FASTCALL lj_opt_fwd_fload(jit_State *J)
  484. {
  485.   IRRef oref = fins->op1;  /* Object reference. */
  486.   IRRef fid = fins->op2;  /* Field ID. */
  487.   IRRef lim = oref;  /* Search limit. */
  488.   IRRef ref;

  489.   /* Search for conflicting stores. */
  490.   ref = J->chain[IR_FSTORE];
  491.   while (ref > oref) {
  492.     IRIns *store = IR(ref);
  493.     switch (aa_fref(J, fins, IR(store->op1))) {
  494.     case ALIAS_NO:   break/* Continue searching. */
  495.     case ALIAS_MAY:  lim = ref; goto cselim;  /* Limit search for load. */
  496.     case ALIAS_MUST: return store->op2;  /* Store forwarding. */
  497.     }
  498.     ref = store->prev;
  499.   }

  500.   /* No conflicting store: const-fold field loads from allocations. */
  501.   if (fid == IRFL_TAB_META) {
  502.     IRIns *ir = IR(oref);
  503.     if (ir->o == IR_TNEW || ir->o == IR_TDUP)
  504.       return lj_ir_knull(J, IRT_TAB);
  505.   }

  506. cselim:
  507.   /* Try to find a matching load. Below the conflicting store, if any. */
  508.   return lj_opt_cselim(J, lim);
  509. }

  510. /* FSTORE elimination. */
  511. TRef LJ_FASTCALL lj_opt_dse_fstore(jit_State *J)
  512. {
  513.   IRRef fref = fins->op1;  /* FREF reference. */
  514.   IRRef val = fins->op2;  /* Stored value reference. */
  515.   IRIns *xr = IR(fref);
  516.   IRRef1 *refp = &J->chain[IR_FSTORE];
  517.   IRRef ref = *refp;
  518.   while (ref > fref) {  /* Search for redundant or conflicting stores. */
  519.     IRIns *store = IR(ref);
  520.     switch (aa_fref(J, xr, IR(store->op1))) {
  521.     case ALIAS_NO:
  522.       break/* Continue searching. */
  523.     case ALIAS_MAY:
  524.       if (store->op2 != val)  /* Conflict if the value is different. */
  525.         goto doemit;
  526.       break/* Otherwise continue searching. */
  527.     case ALIAS_MUST:
  528.       if (store->op2 == val)  /* Same value: drop the new store. */
  529.         return DROPFOLD;
  530.       /* Different value: try to eliminate the redundant store. */
  531.       if (ref > J->chain[IR_LOOP]) {  /* Quick check to avoid crossing LOOP. */
  532.         IRIns *ir;
  533.         /* Check for any intervening guards or conflicting loads. */
  534.         for (ir = IR(J->cur.nins-1); ir > store; ir--)
  535.           if (irt_isguard(ir->t) || (ir->o == IR_FLOAD && ir->op2 == xr->op2))
  536.             goto doemit;  /* No elimination possible. */
  537.         /* Remove redundant store from chain and replace with NOP. */
  538.         *refp = store->prev;
  539.         store->o = IR_NOP;
  540.         store->t.irt = IRT_NIL;
  541.         store->op1 = store->op2 = 0;
  542.         store->prev = 0;
  543.         /* Now emit the new store instead. */
  544.       }
  545.       goto doemit;
  546.     }
  547.     ref = *(refp = &store->prev);
  548.   }
  549. doemit:
  550.   return EMITFOLD/* Otherwise we have a conflict or simply no match. */
  551. }

  552. /* -- XLOAD forwarding and XSTORE elimination ----------------------------- */

  553. /* Find cdata allocation for a reference (if any). */
  554. static IRIns *aa_findcnew(jit_State *J, IRIns *ir)
  555. {
  556.   while (ir->o == IR_ADD) {
  557.     if (!irref_isk(ir->op1)) {
  558.       IRIns *ir1 = aa_findcnew(J, IR(ir->op1));  /* Left-recursion. */
  559.       if (ir1) return ir1;
  560.     }
  561.     if (irref_isk(ir->op2)) return NULL;
  562.     ir = IR(ir->op2);  /* Flatten right-recursion. */
  563.   }
  564.   return ir->o == IR_CNEW ? ir : NULL;
  565. }

  566. /* Alias analysis for two cdata allocations. */
  567. static AliasRet aa_cnew(jit_State *J, IRIns *refa, IRIns *refb)
  568. {
  569.   IRIns *cnewa = aa_findcnew(J, refa);
  570.   IRIns *cnewb = aa_findcnew(J, refb);
  571.   if (cnewa == cnewb)
  572.     return ALIAS_MAY;  /* Same allocation or neither is an allocation. */
  573.   if (cnewa && cnewb)
  574.     return ALIAS_NO;  /* Two different allocations never alias. */
  575.   if (cnewb) { cnewa = cnewb; refb = refa; }
  576.   return aa_escape(J, cnewa, refb);
  577. }

  578. /* Alias analysis for XLOAD/XSTORE. */
  579. static AliasRet aa_xref(jit_State *J, IRIns *refa, IRIns *xa, IRIns *xb)
  580. {
  581.   ptrdiff_t ofsa = 0, ofsb = 0;
  582.   IRIns *refb = IR(xb->op1);
  583.   IRIns *basea = refa, *baseb = refb;
  584.   if (refa == refb && irt_sametype(xa->t, xb->t))
  585.     return ALIAS_MUST;  /* Shortcut for same refs with identical type. */
  586.   /* Offset-based disambiguation. */
  587.   if (refa->o == IR_ADD && irref_isk(refa->op2)) {
  588.     IRIns *irk = IR(refa->op2);
  589.     basea = IR(refa->op1);
  590.     ofsa = (LJ_64 && irk->o == IR_KINT64) ? (ptrdiff_t)ir_k64(irk)->u64 :
  591.                                             (ptrdiff_t)irk->i;
  592.   }
  593.   if (refb->o == IR_ADD && irref_isk(refb->op2)) {
  594.     IRIns *irk = IR(refb->op2);
  595.     baseb = IR(refb->op1);
  596.     ofsb = (LJ_64 && irk->o == IR_KINT64) ? (ptrdiff_t)ir_k64(irk)->u64 :
  597.                                             (ptrdiff_t)irk->i;
  598.   }
  599.   /* Treat constified pointers like base vs. base+offset. */
  600.   if (basea->o == IR_KPTR && baseb->o == IR_KPTR) {
  601.     ofsb += (char *)ir_kptr(baseb) - (char *)ir_kptr(basea);
  602.     baseb = basea;
  603.   }
  604.   /* This implements (very) strict aliasing rules.
  605.   ** Different types do NOT alias, except for differences in signedness.
  606.   ** Type punning through unions is allowed (but forces a reload).
  607.   */
  608.   if (basea == baseb) {
  609.     ptrdiff_t sza = irt_size(xa->t), szb = irt_size(xb->t);
  610.     if (ofsa == ofsb) {
  611.       if (sza == szb && irt_isfp(xa->t) == irt_isfp(xb->t))
  612.         return ALIAS_MUST;  /* Same-sized, same-kind. May need to convert. */
  613.     } else if (ofsa + sza <= ofsb || ofsb + szb <= ofsa) {
  614.       return ALIAS_NO;  /* Non-overlapping base+-o1 vs. base+-o2. */
  615.     }
  616.     /* NYI: extract, extend or reinterpret bits (int <-> fp). */
  617.     return ALIAS_MAY;  /* Overlapping or type punning: force reload. */
  618.   }
  619.   if (!irt_sametype(xa->t, xb->t) &&
  620.       !(irt_typerange(xa->t, IRT_I8, IRT_U64) &&
  621.         ((xa->t.irt - IRT_I8) ^ (xb->t.irt - IRT_I8)) == 1))
  622.     return ALIAS_NO;
  623.   /* NYI: structural disambiguation. */
  624.   return aa_cnew(J, basea, baseb);  /* Try to disambiguate allocations. */
  625. }

  626. /* Return CSEd reference or 0. Caveat: swaps lower ref to the right! */
  627. static IRRef reassoc_trycse(jit_State *J, IROp op, IRRef op1, IRRef op2)
  628. {
  629.   IRRef ref = J->chain[op];
  630.   IRRef lim = op1;
  631.   if (op2 > lim) { lim = op2; op2 = op1; op1 = lim; }
  632.   while (ref > lim) {
  633.     IRIns *ir = IR(ref);
  634.     if (ir->op1 == op1 && ir->op2 == op2)
  635.       return ref;
  636.     ref = ir->prev;
  637.   }
  638.   return 0;
  639. }

  640. /* Reassociate index references. */
  641. static IRRef reassoc_xref(jit_State *J, IRIns *ir)
  642. {
  643.   ptrdiff_t ofs = 0;
  644.   if (ir->o == IR_ADD && irref_isk(ir->op2)) {  /* Get constant offset. */
  645.     IRIns *irk = IR(ir->op2);
  646.     ofs = (LJ_64 && irk->o == IR_KINT64) ? (ptrdiff_t)ir_k64(irk)->u64 :
  647.                                            (ptrdiff_t)irk->i;
  648.     ir = IR(ir->op1);
  649.   }
  650.   if (ir->o == IR_ADD) {  /* Add of base + index. */
  651.     /* Index ref > base ref for loop-carried dependences. Only check op1. */
  652.     IRIns *ir2, *ir1 = IR(ir->op1);
  653.     int32_t shift = 0;
  654.     IRRef idxref;
  655.     /* Determine index shifts. Don't bother with IR_MUL here. */
  656.     if (ir1->o == IR_BSHL && irref_isk(ir1->op2))
  657.       shift = IR(ir1->op2)->i;
  658.     else if (ir1->o == IR_ADD && ir1->op1 == ir1->op2)
  659.       shift = 1;
  660.     else
  661.       ir1 = ir;
  662.     ir2 = IR(ir1->op1);
  663.     /* A non-reassociated add. Must be a loop-carried dependence. */
  664.     if (ir2->o == IR_ADD && irt_isint(ir2->t) && irref_isk(ir2->op2))
  665.       ofs += (ptrdiff_t)IR(ir2->op2)->i << shift;
  666.     else
  667.       return 0;
  668.     idxref = ir2->op1;
  669.     /* Try to CSE the reassociated chain. Give up if not found. */
  670.     if (ir1 != ir &&
  671.         !(idxref = reassoc_trycse(J, ir1->o, idxref,
  672.                                   ir1->o == IR_BSHL ? ir1->op2 : idxref)))
  673.       return 0;
  674.     if (!(idxref = reassoc_trycse(J, IR_ADD, idxref, ir->op2)))
  675.       return 0;
  676.     if (ofs != 0) {
  677.       IRRef refk = tref_ref(lj_ir_kintp(J, ofs));
  678.       if (!(idxref = reassoc_trycse(J, IR_ADD, idxref, refk)))
  679.         return 0;
  680.     }
  681.     return idxref;  /* Success, found a reassociated index reference. Phew. */
  682.   }
  683.   return 0/* Failure. */
  684. }

  685. /* XLOAD forwarding. */
  686. TRef LJ_FASTCALL lj_opt_fwd_xload(jit_State *J)
  687. {
  688.   IRRef xref = fins->op1;
  689.   IRIns *xr = IR(xref);
  690.   IRRef lim = xref;  /* Search limit. */
  691.   IRRef ref;

  692.   if ((fins->op2 & IRXLOAD_READONLY))
  693.     goto cselim;
  694.   if ((fins->op2 & IRXLOAD_VOLATILE))
  695.     goto doemit;

  696.   /* Search for conflicting stores. */
  697.   ref = J->chain[IR_XSTORE];
  698. retry:
  699.   if (J->chain[IR_CALLXS] > lim) lim = J->chain[IR_CALLXS];
  700.   if (J->chain[IR_XBAR] > lim) lim = J->chain[IR_XBAR];
  701.   while (ref > lim) {
  702.     IRIns *store = IR(ref);
  703.     switch (aa_xref(J, xr, fins, store)) {
  704.     case ALIAS_NO:   break/* Continue searching. */
  705.     case ALIAS_MAY:  lim = ref; goto cselim;  /* Limit search for load. */
  706.     case ALIAS_MUST:
  707.       /* Emit conversion if the loaded type doesn't match the forwarded type. */
  708.       if (!irt_sametype(fins->t, IR(store->op2)->t)) {
  709.         IRType dt = irt_type(fins->t), st = irt_type(IR(store->op2)->t);
  710.         if (dt == IRT_I8 || dt == IRT_I16) {  /* Trunc + sign-extend. */
  711.           st = dt | IRCONV_SEXT;
  712.           dt = IRT_INT;
  713.         } else if (dt == IRT_U8 || dt == IRT_U16) {  /* Trunc + zero-extend. */
  714.           st = dt;
  715.           dt = IRT_INT;
  716.         }
  717.         fins->ot = IRT(IR_CONV, dt);
  718.         fins->op1 = store->op2;
  719.         fins->op2 = (dt<<5)|st;
  720.         return RETRYFOLD;
  721.       }
  722.       return store->op2;  /* Store forwarding. */
  723.     }
  724.     ref = store->prev;
  725.   }

  726. cselim:
  727.   /* Try to find a matching load. Below the conflicting store, if any. */
  728.   ref = J->chain[IR_XLOAD];
  729.   while (ref > lim) {
  730.     /* CSE for XLOAD depends on the type, but not on the IRXLOAD_* flags. */
  731.     if (IR(ref)->op1 == xref && irt_sametype(IR(ref)->t, fins->t))
  732.       return ref;
  733.     ref = IR(ref)->prev;
  734.   }

  735.   /* Reassociate XLOAD across PHIs to handle a[i-1] forwarding case. */
  736.   if (!(fins->op2 & IRXLOAD_READONLY) && J->chain[IR_LOOP] &&
  737.       xref == fins->op1 && (xref = reassoc_xref(J, xr)) != 0) {
  738.     ref = J->chain[IR_XSTORE];
  739.     while (ref > lim)  /* Skip stores that have already been checked. */
  740.       ref = IR(ref)->prev;
  741.     lim = xref;
  742.     xr = IR(xref);
  743.     goto retry;  /* Retry with the reassociated reference. */
  744.   }
  745. doemit:
  746.   return EMITFOLD;
  747. }

  748. /* XSTORE elimination. */
  749. TRef LJ_FASTCALL lj_opt_dse_xstore(jit_State *J)
  750. {
  751.   IRRef xref = fins->op1;
  752.   IRIns *xr = IR(xref);
  753.   IRRef lim = xref;  /* Search limit. */
  754.   IRRef val = fins->op2;  /* Stored value reference. */
  755.   IRRef1 *refp = &J->chain[IR_XSTORE];
  756.   IRRef ref = *refp;
  757.   if (J->chain[IR_CALLXS] > lim) lim = J->chain[IR_CALLXS];
  758.   if (J->chain[IR_XBAR] > lim) lim = J->chain[IR_XBAR];
  759.   if (J->chain[IR_XSNEW] > lim) lim = J->chain[IR_XSNEW];
  760.   while (ref > lim) {  /* Search for redundant or conflicting stores. */
  761.     IRIns *store = IR(ref);
  762.     switch (aa_xref(J, xr, fins, store)) {
  763.     case ALIAS_NO:
  764.       break/* Continue searching. */
  765.     case ALIAS_MAY:
  766.       if (store->op2 != val)  /* Conflict if the value is different. */
  767.         goto doemit;
  768.       break/* Otherwise continue searching. */
  769.     case ALIAS_MUST:
  770.       if (store->op2 == val)  /* Same value: drop the new store. */
  771.         return DROPFOLD;
  772.       /* Different value: try to eliminate the redundant store. */
  773.       if (ref > J->chain[IR_LOOP]) {  /* Quick check to avoid crossing LOOP. */
  774.         IRIns *ir;
  775.         /* Check for any intervening guards or any XLOADs (no AA performed). */
  776.         for (ir = IR(J->cur.nins-1); ir > store; ir--)
  777.           if (irt_isguard(ir->t) || ir->o == IR_XLOAD)
  778.             goto doemit;  /* No elimination possible. */
  779.         /* Remove redundant store from chain and replace with NOP. */
  780.         *refp = store->prev;
  781.         store->o = IR_NOP;
  782.         store->t.irt = IRT_NIL;
  783.         store->op1 = store->op2 = 0;
  784.         store->prev = 0;
  785.         /* Now emit the new store instead. */
  786.       }
  787.       goto doemit;
  788.     }
  789.     ref = *(refp = &store->prev);
  790.   }
  791. doemit:
  792.   return EMITFOLD/* Otherwise we have a conflict or simply no match. */
  793. }

  794. /* -- Forwarding of lj_tab_len -------------------------------------------- */

  795. /* This is rather simplistic right now, but better than nothing. */
  796. TRef LJ_FASTCALL lj_opt_fwd_tab_len(jit_State *J)
  797. {
  798.   IRRef tab = fins->op1;  /* Table reference. */
  799.   IRRef lim = tab;  /* Search limit. */
  800.   IRRef ref;

  801.   /* Any ASTORE is a conflict and limits the search. */
  802.   if (J->chain[IR_ASTORE] > lim) lim = J->chain[IR_ASTORE];

  803.   /* Search for conflicting HSTORE with numeric key. */
  804.   ref = J->chain[IR_HSTORE];
  805.   while (ref > lim) {
  806.     IRIns *store = IR(ref);
  807.     IRIns *href = IR(store->op1);
  808.     IRIns *key = IR(href->op2);
  809.     if (irt_isnum(key->o == IR_KSLOT ? IR(key->op1)->t : key->t)) {
  810.       lim = ref;  /* Conflicting store found, limits search for TLEN. */
  811.       break;
  812.     }
  813.     ref = store->prev;
  814.   }

  815.   /* Search for aliasing table.clear. */
  816.   if (!fwd_aa_tab_clear(J, lim, tab))
  817.     return lj_ir_emit(J);

  818.   /* Try to find a matching load. Below the conflicting store, if any. */
  819.   return lj_opt_cselim(J, lim);
  820. }

  821. /* -- ASTORE/HSTORE previous type analysis -------------------------------- */

  822. /* Check whether the previous value for a table store is non-nil.
  823. ** This can be derived either from a previous store or from a previous
  824. ** load (because all loads from tables perform a type check).
  825. **
  826. ** The result of the analysis can be used to avoid the metatable check
  827. ** and the guard against HREF returning niltv. Both of these are cheap,
  828. ** so let's not spend too much effort on the analysis.
  829. **
  830. ** A result of 1 is exact: previous value CANNOT be nil.
  831. ** A result of 0 is inexact: previous value MAY be nil.
  832. */
  833. int lj_opt_fwd_wasnonnil(jit_State *J, IROpT loadop, IRRef xref)
  834. {
  835.   /* First check stores. */
  836.   IRRef ref = J->chain[loadop+IRDELTA_L2S];
  837.   while (ref > xref) {
  838.     IRIns *store = IR(ref);
  839.     if (store->op1 == xref) {  /* Same xREF. */
  840.       /* A nil store MAY alias, but a non-nil store MUST alias. */
  841.       return !irt_isnil(store->t);
  842.     } else if (irt_isnil(store->t)) {  /* Must check any nil store. */
  843.       IRRef skref = IR(store->op1)->op2;
  844.       IRRef xkref = IR(xref)->op2;
  845.       /* Same key type MAY alias. Need ALOAD check due to multiple int types. */
  846.       if (loadop == IR_ALOAD || irt_sametype(IR(skref)->t, IR(xkref)->t)) {
  847.         if (skref == xkref || !irref_isk(skref) || !irref_isk(xkref))
  848.           return 0/* A nil store with same const key or var key MAY alias. */
  849.         /* Different const keys CANNOT alias. */
  850.       }  /* Different key types CANNOT alias. */
  851.     }  /* Other non-nil stores MAY alias. */
  852.     ref = store->prev;
  853.   }

  854.   /* Check loads since nothing could be derived from stores. */
  855.   ref = J->chain[loadop];
  856.   while (ref > xref) {
  857.     IRIns *load = IR(ref);
  858.     if (load->op1 == xref) {  /* Same xREF. */
  859.       /* A nil load MAY alias, but a non-nil load MUST alias. */
  860.       return !irt_isnil(load->t);
  861.     }  /* Other non-nil loads MAY alias. */
  862.     ref = load->prev;
  863.   }
  864.   return 0/* Nothing derived at all, previous value MAY be nil. */
  865. }

  866. /* ------------------------------------------------------------------------ */

  867. #undef IR
  868. #undef fins
  869. #undef fleft
  870. #undef fright

  871. #endif