lj_opt_dce.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. ** DCE: Dead Code Elimination. Pre-LOOP only -- ASM already performs DCE.
  3. ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
  4. */
  5. #define lj_opt_dce_c
  6. #define LUA_CORE
  7. #include "lj_obj.h"
  8. #if LJ_HASJIT
  9. #include "lj_ir.h"
  10. #include "lj_jit.h"
  11. #include "lj_iropt.h"
  12. /* Some local macros to save typing. Undef'd at the end. */
  13. #define IR(ref) (&J->cur.ir[(ref)])
  14. /* Scan through all snapshots and mark all referenced instructions. */
  15. static void dce_marksnap(jit_State *J)
  16. {
  17. SnapNo i, nsnap = J->cur.nsnap;
  18. for (i = 0; i < nsnap; i++) {
  19. SnapShot *snap = &J->cur.snap[i];
  20. SnapEntry *map = &J->cur.snapmap[snap->mapofs];
  21. MSize n, nent = snap->nent;
  22. for (n = 0; n < nent; n++) {
  23. IRRef ref = snap_ref(map[n]);
  24. if (ref >= REF_FIRST)
  25. irt_setmark(IR(ref)->t);
  26. }
  27. }
  28. }
  29. /* Backwards propagate marks. Replace unused instructions with NOPs. */
  30. static void dce_propagate(jit_State *J)
  31. {
  32. IRRef1 *pchain[IR__MAX];
  33. IRRef ins;
  34. uint32_t i;
  35. for (i = 0; i < IR__MAX; i++) pchain[i] = &J->chain[i];
  36. for (ins = J->cur.nins-1; ins >= REF_FIRST; ins--) {
  37. IRIns *ir = IR(ins);
  38. if (irt_ismarked(ir->t)) {
  39. irt_clearmark(ir->t);
  40. } else if (!ir_sideeff(ir)) {
  41. *pchain[ir->o] = ir->prev; /* Reroute original instruction chain. */
  42. lj_ir_nop(ir);
  43. continue;
  44. }
  45. pchain[ir->o] = &ir->prev;
  46. if (ir->op1 >= REF_FIRST) irt_setmark(IR(ir->op1)->t);
  47. if (ir->op2 >= REF_FIRST) irt_setmark(IR(ir->op2)->t);
  48. }
  49. }
  50. /* Dead Code Elimination.
  51. **
  52. ** First backpropagate marks for all used instructions. Then replace
  53. ** the unused ones with a NOP. Note that compressing the IR to eliminate
  54. ** the NOPs does not pay off.
  55. */
  56. void lj_opt_dce(jit_State *J)
  57. {
  58. if ((J->flags & JIT_F_OPT_DCE)) {
  59. dce_marksnap(J);
  60. dce_propagate(J);
  61. memset(J->bpropcache, 0, sizeof(J->bpropcache)); /* Invalidate cache. */
  62. }
  63. }
  64. #undef IR
  65. #endif