root/lj_trace.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. lj_trace_err
  2. lj_trace_err_info
  3. trace_findfree
  4. perftools_addtrace
  5. trace_save_alloc
  6. trace_save
  7. lj_trace_free
  8. lj_trace_reenableproto
  9. trace_unpatch
  10. trace_flushroot
  11. lj_trace_flush
  12. lj_trace_flushproto
  13. lj_trace_flushall
  14. lj_trace_initstate
  15. lj_trace_freestate
  16. blacklist_pc
  17. penalty_pc
  18. trace_start
  19. trace_stop
  20. trace_downrec
  21. trace_abort
  22. trace_pendpatch
  23. trace_state
  24. lj_trace_ins
  25. lj_trace_hot
  26. trace_hotside
  27. trace_exit_cp
  28. trace_exit_regs
  29. trace_exit_find
  30. lj_trace_exit

   1 /*
   2 ** Trace management.
   3 ** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
   4 */
   5 
   6 #define lj_trace_c
   7 #define LUA_CORE
   8 
   9 #include "lj_obj.h"
  10 
  11 #if LJ_HASJIT
  12 
  13 #include "lj_gc.h"
  14 #include "lj_err.h"
  15 #include "lj_debug.h"
  16 #include "lj_str.h"
  17 #include "lj_frame.h"
  18 #include "lj_state.h"
  19 #include "lj_bc.h"
  20 #include "lj_ir.h"
  21 #include "lj_jit.h"
  22 #include "lj_iropt.h"
  23 #include "lj_mcode.h"
  24 #include "lj_trace.h"
  25 #include "lj_snap.h"
  26 #include "lj_gdbjit.h"
  27 #include "lj_record.h"
  28 #include "lj_asm.h"
  29 #include "lj_dispatch.h"
  30 #include "lj_vm.h"
  31 #include "lj_vmevent.h"
  32 #include "lj_target.h"
  33 
  34 /* -- Error handling ------------------------------------------------------ */
  35 
  36 /* Synchronous abort with error message. */
  37 void lj_trace_err(jit_State *J, TraceError e)
  38 {
  39   setnilV(&J->errinfo);  /* No error info. */
  40   setintV(J->L->top++, (int32_t)e);
  41   lj_err_throw(J->L, LUA_ERRRUN);
  42 }
  43 
  44 /* Synchronous abort with error message and error info. */
  45 void lj_trace_err_info(jit_State *J, TraceError e)
  46 {
  47   setintV(J->L->top++, (int32_t)e);
  48   lj_err_throw(J->L, LUA_ERRRUN);
  49 }
  50 
  51 /* -- Trace management ---------------------------------------------------- */
  52 
  53 /* The current trace is first assembled in J->cur. The variable length
  54 ** arrays point to shared, growable buffers (J->irbuf etc.). When trace
  55 ** recording ends successfully, the current trace and its data structures
  56 ** are copied to a new (compact) GCtrace object.
  57 */
  58 
  59 /* Find a free trace number. */
  60 static TraceNo trace_findfree(jit_State *J)
  61 {
  62   MSize osz, lim;
  63   if (J->freetrace == 0)
  64     J->freetrace = 1;
  65   for (; J->freetrace < J->sizetrace; J->freetrace++)
  66     if (traceref(J, J->freetrace) == NULL)
  67       return J->freetrace++;
  68   /* Need to grow trace array. */
  69   lim = (MSize)J->param[JIT_P_maxtrace] + 1;
  70   if (lim < 2) lim = 2; else if (lim > 65535) lim = 65535;
  71   osz = J->sizetrace;
  72   if (osz >= lim)
  73     return 0;  /* Too many traces. */
  74   lj_mem_growvec(J->L, J->trace, J->sizetrace, lim, GCRef);
  75   for (; osz < J->sizetrace; osz++)
  76     setgcrefnull(J->trace[osz]);
  77   return J->freetrace;
  78 }
  79 
  80 #define TRACE_APPENDVEC(field, szfield, tp) \
  81   T->field = (tp *)p; \
  82   memcpy(p, J->cur.field, J->cur.szfield*sizeof(tp)); \
  83   p += J->cur.szfield*sizeof(tp);
  84 
  85 #ifdef LUAJIT_USE_PERFTOOLS
  86 /*
  87 ** Create symbol table of JIT-compiled code. For use with Linux perf tools.
  88 ** Example usage:
  89 **   perf record -f -e cycles luajit test.lua
  90 **   perf report -s symbol
  91 **   rm perf.data /tmp/perf-*.map
  92 */
  93 #include <stdio.h>
  94 #include <unistd.h>
  95 
  96 static void perftools_addtrace(GCtrace *T)
  97 {
  98   static FILE *fp;
  99   GCproto *pt = &gcref(T->startpt)->pt;
 100   const BCIns *startpc = mref(T->startpc, const BCIns);
 101   const char *name = proto_chunknamestr(pt);
 102   BCLine lineno;
 103   if (name[0] == '@' || name[0] == '=')
 104     name++;
 105   else
 106     name = "(string)";
 107   lua_assert(startpc >= proto_bc(pt) && startpc < proto_bc(pt) + pt->sizebc);
 108   lineno = lj_debug_line(pt, proto_bcpos(pt, startpc));
 109   if (!fp) {
 110     char fname[40];
 111     sprintf(fname, "/tmp/perf-%d.map", getpid());
 112     if (!(fp = fopen(fname, "w"))) return;
 113     setlinebuf(fp);
 114   }
 115   fprintf(fp, "%lx %x TRACE_%d::%s:%u\n",
 116           (long)T->mcode, T->szmcode, T->traceno, name, lineno);
 117 }
 118 #endif
 119 
 120 /* Allocate space for copy of trace. */
 121 static GCtrace *trace_save_alloc(jit_State *J)
 122 {
 123   size_t sztr = ((sizeof(GCtrace)+7)&~7);
 124   size_t szins = (J->cur.nins-J->cur.nk)*sizeof(IRIns);
 125   size_t sz = sztr + szins +
 126               J->cur.nsnap*sizeof(SnapShot) +
 127               J->cur.nsnapmap*sizeof(SnapEntry);
 128   return lj_mem_newt(J->L, (MSize)sz, GCtrace);
 129 }
 130 
 131 /* Save current trace by copying and compacting it. */
 132 static void trace_save(jit_State *J, GCtrace *T)
 133 {
 134   size_t sztr = ((sizeof(GCtrace)+7)&~7);
 135   size_t szins = (J->cur.nins-J->cur.nk)*sizeof(IRIns);
 136   char *p = (char *)T + sztr;
 137   memcpy(T, &J->cur, sizeof(GCtrace));
 138   setgcrefr(T->nextgc, J2G(J)->gc.root);
 139   setgcrefp(J2G(J)->gc.root, T);
 140   newwhite(J2G(J), T);
 141   T->gct = ~LJ_TTRACE;
 142   T->ir = (IRIns *)p - J->cur.nk;
 143   memcpy(p, J->cur.ir+J->cur.nk, szins);
 144   p += szins;
 145   TRACE_APPENDVEC(snap, nsnap, SnapShot)
 146   TRACE_APPENDVEC(snapmap, nsnapmap, SnapEntry)
 147   J->cur.traceno = 0;
 148   setgcrefp(J->trace[T->traceno], T);
 149   lj_gc_barriertrace(J2G(J), T->traceno);
 150   lj_gdbjit_addtrace(J, T);
 151 #ifdef LUAJIT_USE_PERFTOOLS
 152   perftools_addtrace(T);
 153 #endif
 154 }
 155 
 156 void LJ_FASTCALL lj_trace_free(global_State *g, GCtrace *T)
 157 {
 158   jit_State *J = G2J(g);
 159   if (T->traceno) {
 160     lj_gdbjit_deltrace(J, T);
 161     if (T->traceno < J->freetrace)
 162       J->freetrace = T->traceno;
 163     setgcrefnull(J->trace[T->traceno]);
 164   }
 165   lj_mem_free(g, T,
 166     ((sizeof(GCtrace)+7)&~7) + (T->nins-T->nk)*sizeof(IRIns) +
 167     T->nsnap*sizeof(SnapShot) + T->nsnapmap*sizeof(SnapEntry));
 168 }
 169 
 170 /* Re-enable compiling a prototype by unpatching any modified bytecode. */
 171 void lj_trace_reenableproto(GCproto *pt)
 172 {
 173   if ((pt->flags & PROTO_ILOOP)) {
 174     BCIns *bc = proto_bc(pt);
 175     BCPos i, sizebc = pt->sizebc;;
 176     pt->flags &= ~PROTO_ILOOP;
 177     if (bc_op(bc[0]) == BC_IFUNCF)
 178       setbc_op(&bc[0], BC_FUNCF);
 179     for (i = 1; i < sizebc; i++) {
 180       BCOp op = bc_op(bc[i]);
 181       if (op == BC_IFORL || op == BC_IITERL || op == BC_ILOOP)
 182         setbc_op(&bc[i], (int)op+(int)BC_LOOP-(int)BC_ILOOP);
 183     }
 184   }
 185 }
 186 
 187 /* Unpatch the bytecode modified by a root trace. */
 188 static void trace_unpatch(jit_State *J, GCtrace *T)
 189 {
 190   BCOp op = bc_op(T->startins);
 191   BCIns *pc = mref(T->startpc, BCIns);
 192   UNUSED(J);
 193   if (op == BC_JMP)
 194     return;  /* No need to unpatch branches in parent traces (yet). */
 195   switch (bc_op(*pc)) {
 196   case BC_JFORL:
 197     lua_assert(traceref(J, bc_d(*pc)) == T);
 198     *pc = T->startins;
 199     pc += bc_j(T->startins);
 200     lua_assert(bc_op(*pc) == BC_JFORI);
 201     setbc_op(pc, BC_FORI);
 202     break;
 203   case BC_JITERL:
 204   case BC_JLOOP:
 205     lua_assert(op == BC_ITERL || op == BC_LOOP || bc_isret(op));
 206     *pc = T->startins;
 207     break;
 208   case BC_JMP:
 209     lua_assert(op == BC_ITERL);
 210     pc += bc_j(*pc)+2;
 211     if (bc_op(*pc) == BC_JITERL) {
 212       lua_assert(traceref(J, bc_d(*pc)) == T);
 213       *pc = T->startins;
 214     }
 215     break;
 216   case BC_JFUNCF:
 217     lua_assert(op == BC_FUNCF);
 218     *pc = T->startins;
 219     break;
 220   default:  /* Already unpatched. */
 221     break;
 222   }
 223 }
 224 
 225 /* Flush a root trace. */
 226 static void trace_flushroot(jit_State *J, GCtrace *T)
 227 {
 228   GCproto *pt = &gcref(T->startpt)->pt;
 229   lua_assert(T->root == 0 && pt != NULL);
 230   /* First unpatch any modified bytecode. */
 231   trace_unpatch(J, T);
 232   /* Unlink root trace from chain anchored in prototype. */
 233   if (pt->trace == T->traceno) {  /* Trace is first in chain. Easy. */
 234     pt->trace = T->nextroot;
 235   } else if (pt->trace) {  /* Otherwise search in chain of root traces. */
 236     GCtrace *T2 = traceref(J, pt->trace);
 237     if (T2) {
 238       for (; T2->nextroot; T2 = traceref(J, T2->nextroot))
 239         if (T2->nextroot == T->traceno) {
 240           T2->nextroot = T->nextroot;  /* Unlink from chain. */
 241           break;
 242         }
 243     }
 244   }
 245 }
 246 
 247 /* Flush a trace. Only root traces are considered. */
 248 void lj_trace_flush(jit_State *J, TraceNo traceno)
 249 {
 250   if (traceno > 0 && traceno < J->sizetrace) {
 251     GCtrace *T = traceref(J, traceno);
 252     if (T && T->root == 0)
 253       trace_flushroot(J, T);
 254   }
 255 }
 256 
 257 /* Flush all traces associated with a prototype. */
 258 void lj_trace_flushproto(global_State *g, GCproto *pt)
 259 {
 260   while (pt->trace != 0)
 261     trace_flushroot(G2J(g), traceref(G2J(g), pt->trace));
 262 }
 263 
 264 /* Flush all traces. */
 265 int lj_trace_flushall(lua_State *L)
 266 {
 267   jit_State *J = L2J(L);
 268   ptrdiff_t i;
 269   if ((J2G(J)->hookmask & HOOK_GC))
 270     return 1;
 271   for (i = (ptrdiff_t)J->sizetrace-1; i > 0; i--) {
 272     GCtrace *T = traceref(J, i);
 273     if (T) {
 274       if (T->root == 0)
 275         trace_flushroot(J, T);
 276       lj_gdbjit_deltrace(J, T);
 277       T->traceno = 0;
 278       setgcrefnull(J->trace[i]);
 279     }
 280   }
 281   J->cur.traceno = 0;
 282   J->freetrace = 0;
 283   /* Clear penalty cache. */
 284   memset(J->penalty, 0, sizeof(J->penalty));
 285   /* Free the whole machine code and invalidate all exit stub groups. */
 286   lj_mcode_free(J);
 287   memset(J->exitstubgroup, 0, sizeof(J->exitstubgroup));
 288   lj_vmevent_send(L, TRACE,
 289     setstrV(L, L->top++, lj_str_newlit(L, "flush"));
 290   );
 291   return 0;
 292 }
 293 
 294 /* Initialize JIT compiler state. */
 295 void lj_trace_initstate(global_State *g)
 296 {
 297   jit_State *J = G2J(g);
 298   TValue *tv;
 299   /* Initialize SIMD constants. */
 300   tv = LJ_KSIMD(J, LJ_KSIMD_ABS);
 301   tv[0].u64 = U64x(7fffffff,ffffffff);
 302   tv[1].u64 = U64x(7fffffff,ffffffff);
 303   tv = LJ_KSIMD(J, LJ_KSIMD_NEG);
 304   tv[0].u64 = U64x(80000000,00000000);
 305   tv[1].u64 = U64x(80000000,00000000);
 306 }
 307 
 308 /* Free everything associated with the JIT compiler state. */
 309 void lj_trace_freestate(global_State *g)
 310 {
 311   jit_State *J = G2J(g);
 312 #ifdef LUA_USE_ASSERT
 313   {  /* This assumes all traces have already been freed. */
 314     ptrdiff_t i;
 315     for (i = 1; i < (ptrdiff_t)J->sizetrace; i++)
 316       lua_assert(i == (ptrdiff_t)J->cur.traceno || traceref(J, i) == NULL);
 317   }
 318 #endif
 319   lj_mcode_free(J);
 320   lj_ir_k64_freeall(J);
 321   lj_mem_freevec(g, J->snapmapbuf, J->sizesnapmap, SnapEntry);
 322   lj_mem_freevec(g, J->snapbuf, J->sizesnap, SnapShot);
 323   lj_mem_freevec(g, J->irbuf + J->irbotlim, J->irtoplim - J->irbotlim, IRIns);
 324   lj_mem_freevec(g, J->trace, J->sizetrace, GCRef);
 325 }
 326 
 327 /* -- Penalties and blacklisting ------------------------------------------ */
 328 
 329 /* Blacklist a bytecode instruction. */
 330 static void blacklist_pc(GCproto *pt, BCIns *pc)
 331 {
 332   setbc_op(pc, (int)bc_op(*pc)+(int)BC_ILOOP-(int)BC_LOOP);
 333   pt->flags |= PROTO_ILOOP;
 334 }
 335 
 336 /* Penalize a bytecode instruction. */
 337 static void penalty_pc(jit_State *J, GCproto *pt, BCIns *pc, TraceError e)
 338 {
 339   uint32_t i, val = PENALTY_MIN;
 340   for (i = 0; i < PENALTY_SLOTS; i++)
 341     if (mref(J->penalty[i].pc, const BCIns) == pc) {  /* Cache slot found? */
 342       /* First try to bump its hotcount several times. */
 343       val = ((uint32_t)J->penalty[i].val << 1) +
 344             LJ_PRNG_BITS(J, PENALTY_RNDBITS);
 345       if (val > PENALTY_MAX) {
 346         blacklist_pc(pt, pc);  /* Blacklist it, if that didn't help. */
 347         return;
 348       }
 349       goto setpenalty;
 350     }
 351   /* Assign a new penalty cache slot. */
 352   i = J->penaltyslot;
 353   J->penaltyslot = (J->penaltyslot + 1) & (PENALTY_SLOTS-1);
 354   setmref(J->penalty[i].pc, pc);
 355 setpenalty:
 356   J->penalty[i].val = (uint16_t)val;
 357   J->penalty[i].reason = e;
 358   hotcount_set(J2GG(J), pc+1, val);
 359 }
 360 
 361 /* -- Trace compiler state machine ---------------------------------------- */
 362 
 363 /* Start tracing. */
 364 static void trace_start(jit_State *J)
 365 {
 366   lua_State *L;
 367   TraceNo traceno;
 368 
 369   if ((J->pt->flags & PROTO_NOJIT)) {  /* JIT disabled for this proto? */
 370     if (J->parent == 0) {
 371       /* Lazy bytecode patching to disable hotcount events. */
 372       lua_assert(bc_op(*J->pc) == BC_FORL || bc_op(*J->pc) == BC_ITERL ||
 373                  bc_op(*J->pc) == BC_LOOP || bc_op(*J->pc) == BC_FUNCF);
 374       setbc_op(J->pc, (int)bc_op(*J->pc)+(int)BC_ILOOP-(int)BC_LOOP);
 375       J->pt->flags |= PROTO_ILOOP;
 376     }
 377     J->state = LJ_TRACE_IDLE;  /* Silently ignored. */
 378     return;
 379   }
 380 
 381   /* Get a new trace number. */
 382   traceno = trace_findfree(J);
 383   if (LJ_UNLIKELY(traceno == 0)) {  /* No free trace? */
 384     lua_assert((J2G(J)->hookmask & HOOK_GC) == 0);
 385     lj_trace_flushall(J->L);
 386     J->state = LJ_TRACE_IDLE;  /* Silently ignored. */
 387     return;
 388   }
 389   setgcrefp(J->trace[traceno], &J->cur);
 390 
 391   /* Setup enough of the current trace to be able to send the vmevent. */
 392   memset(&J->cur, 0, sizeof(GCtrace));
 393   J->cur.traceno = traceno;
 394   J->cur.nins = J->cur.nk = REF_BASE;
 395   J->cur.ir = J->irbuf;
 396   J->cur.snap = J->snapbuf;
 397   J->cur.snapmap = J->snapmapbuf;
 398   J->mergesnap = 0;
 399   J->needsnap = 0;
 400   J->bcskip = 0;
 401   J->guardemit.irt = 0;
 402   J->postproc = LJ_POST_NONE;
 403   lj_resetsplit(J);
 404   setgcref(J->cur.startpt, obj2gco(J->pt));
 405 
 406   L = J->L;
 407   lj_vmevent_send(L, TRACE,
 408     setstrV(L, L->top++, lj_str_newlit(L, "start"));
 409     setintV(L->top++, traceno);
 410     setfuncV(L, L->top++, J->fn);
 411     setintV(L->top++, proto_bcpos(J->pt, J->pc));
 412     if (J->parent) {
 413       setintV(L->top++, J->parent);
 414       setintV(L->top++, J->exitno);
 415     }
 416   );
 417   lj_record_setup(J);
 418 }
 419 
 420 /* Stop tracing. */
 421 static void trace_stop(jit_State *J)
 422 {
 423   BCIns *pc = mref(J->cur.startpc, BCIns);
 424   BCOp op = bc_op(J->cur.startins);
 425   GCproto *pt = &gcref(J->cur.startpt)->pt;
 426   TraceNo traceno = J->cur.traceno;
 427   GCtrace *T = trace_save_alloc(J);  /* Do this first. May throw OOM. */
 428   lua_State *L;
 429 
 430   switch (op) {
 431   case BC_FORL:
 432     setbc_op(pc+bc_j(J->cur.startins), BC_JFORI);  /* Patch FORI, too. */
 433     /* fallthrough */
 434   case BC_LOOP:
 435   case BC_ITERL:
 436   case BC_FUNCF:
 437     /* Patch bytecode of starting instruction in root trace. */
 438     setbc_op(pc, (int)op+(int)BC_JLOOP-(int)BC_LOOP);
 439     setbc_d(pc, traceno);
 440   addroot:
 441     /* Add to root trace chain in prototype. */
 442     J->cur.nextroot = pt->trace;
 443     pt->trace = (TraceNo1)traceno;
 444     break;
 445   case BC_RET:
 446   case BC_RET0:
 447   case BC_RET1:
 448     *pc = BCINS_AD(BC_JLOOP, J->cur.snap[0].nslots, traceno);
 449     goto addroot;
 450   case BC_JMP:
 451     /* Patch exit branch in parent to side trace entry. */
 452     lua_assert(J->parent != 0 && J->cur.root != 0);
 453     lj_asm_patchexit(J, traceref(J, J->parent), J->exitno, J->cur.mcode);
 454     /* Avoid compiling a side trace twice (stack resizing uses parent exit). */
 455     traceref(J, J->parent)->snap[J->exitno].count = SNAPCOUNT_DONE;
 456     /* Add to side trace chain in root trace. */
 457     {
 458       GCtrace *root = traceref(J, J->cur.root);
 459       root->nchild++;
 460       J->cur.nextside = root->nextside;
 461       root->nextside = (TraceNo1)traceno;
 462     }
 463     break;
 464   default:
 465     lua_assert(0);
 466     break;
 467   }
 468 
 469   /* Commit new mcode only after all patching is done. */
 470   lj_mcode_commit(J, J->cur.mcode);
 471   J->postproc = LJ_POST_NONE;
 472   trace_save(J, T);
 473 
 474   L = J->L;
 475   lj_vmevent_send(L, TRACE,
 476     setstrV(L, L->top++, lj_str_newlit(L, "stop"));
 477     setintV(L->top++, traceno);
 478   );
 479 }
 480 
 481 /* Start a new root trace for down-recursion. */
 482 static int trace_downrec(jit_State *J)
 483 {
 484   /* Restart recording at the return instruction. */
 485   lua_assert(J->pt != NULL);
 486   lua_assert(bc_isret(bc_op(*J->pc)));
 487   if (bc_op(*J->pc) == BC_RETM)
 488     return 0;  /* NYI: down-recursion with RETM. */
 489   J->parent = 0;
 490   J->exitno = 0;
 491   J->state = LJ_TRACE_RECORD;
 492   trace_start(J);
 493   return 1;
 494 }
 495 
 496 /* Abort tracing. */
 497 static int trace_abort(jit_State *J)
 498 {
 499   lua_State *L = J->L;
 500   TraceError e = LJ_TRERR_RECERR;
 501   TraceNo traceno;
 502 
 503   J->postproc = LJ_POST_NONE;
 504   lj_mcode_abort(J);
 505   if (tvisnumber(L->top-1))
 506     e = (TraceError)numberVint(L->top-1);
 507   if (e == LJ_TRERR_MCODELM) {
 508     L->top--;  /* Remove error object */
 509     J->state = LJ_TRACE_ASM;
 510     return 1;  /* Retry ASM with new MCode area. */
 511   }
 512   /* Penalize or blacklist starting bytecode instruction. */
 513   if (J->parent == 0 && !bc_isret(bc_op(J->cur.startins)))
 514     penalty_pc(J, &gcref(J->cur.startpt)->pt, mref(J->cur.startpc, BCIns), e);
 515 
 516   /* Is there anything to abort? */
 517   traceno = J->cur.traceno;
 518   if (traceno) {
 519     ptrdiff_t errobj = savestack(L, L->top-1);  /* Stack may be resized. */
 520     J->cur.link = 0;
 521     J->cur.linktype = LJ_TRLINK_NONE;
 522     lj_vmevent_send(L, TRACE,
 523       TValue *frame;
 524       const BCIns *pc;
 525       GCfunc *fn;
 526       setstrV(L, L->top++, lj_str_newlit(L, "abort"));
 527       setintV(L->top++, traceno);
 528       /* Find original Lua function call to generate a better error message. */
 529       frame = J->L->base-1;
 530       pc = J->pc;
 531       while (!isluafunc(frame_func(frame))) {
 532         pc = (frame_iscont(frame) ? frame_contpc(frame) : frame_pc(frame)) - 1;
 533         frame = frame_prev(frame);
 534       }
 535       fn = frame_func(frame);
 536       setfuncV(L, L->top++, fn);
 537       setintV(L->top++, proto_bcpos(funcproto(fn), pc));
 538       copyTV(L, L->top++, restorestack(L, errobj));
 539       copyTV(L, L->top++, &J->errinfo);
 540     );
 541     /* Drop aborted trace after the vmevent (which may still access it). */
 542     setgcrefnull(J->trace[traceno]);
 543     if (traceno < J->freetrace)
 544       J->freetrace = traceno;
 545     J->cur.traceno = 0;
 546   }
 547   L->top--;  /* Remove error object */
 548   if (e == LJ_TRERR_DOWNREC)
 549     return trace_downrec(J);
 550   else if (e == LJ_TRERR_MCODEAL)
 551     lj_trace_flushall(L);
 552   return 0;
 553 }
 554 
 555 /* Perform pending re-patch of a bytecode instruction. */
 556 static LJ_AINLINE void trace_pendpatch(jit_State *J, int force)
 557 {
 558   if (LJ_UNLIKELY(J->patchpc)) {
 559     if (force || J->bcskip == 0) {
 560       *J->patchpc = J->patchins;
 561       J->patchpc = NULL;
 562     } else {
 563       J->bcskip = 0;
 564     }
 565   }
 566 }
 567 
 568 /* State machine for the trace compiler. Protected callback. */
 569 static TValue *trace_state(lua_State *L, lua_CFunction dummy, void *ud)
 570 {
 571   jit_State *J = (jit_State *)ud;
 572   UNUSED(dummy);
 573   do {
 574   retry:
 575     switch (J->state) {
 576     case LJ_TRACE_START:
 577       J->state = LJ_TRACE_RECORD;  /* trace_start() may change state. */
 578       trace_start(J);
 579       lj_dispatch_update(J2G(J));
 580       break;
 581 
 582     case LJ_TRACE_RECORD:
 583       trace_pendpatch(J, 0);
 584       setvmstate(J2G(J), RECORD);
 585       lj_vmevent_send_(L, RECORD,
 586         /* Save/restore tmptv state for trace recorder. */
 587         TValue savetv = J2G(J)->tmptv;
 588         TValue savetv2 = J2G(J)->tmptv2;
 589         setintV(L->top++, J->cur.traceno);
 590         setfuncV(L, L->top++, J->fn);
 591         setintV(L->top++, J->pt ? (int32_t)proto_bcpos(J->pt, J->pc) : -1);
 592         setintV(L->top++, J->framedepth);
 593       ,
 594         J2G(J)->tmptv = savetv;
 595         J2G(J)->tmptv2 = savetv2;
 596       );
 597       lj_record_ins(J);
 598       break;
 599 
 600     case LJ_TRACE_END:
 601       trace_pendpatch(J, 1);
 602       J->loopref = 0;
 603       if ((J->flags & JIT_F_OPT_LOOP) &&
 604           J->cur.link == J->cur.traceno && J->framedepth + J->retdepth == 0) {
 605         setvmstate(J2G(J), OPT);
 606         lj_opt_dce(J);
 607         if (lj_opt_loop(J)) {  /* Loop optimization failed? */
 608           J->cur.link = 0;
 609           J->cur.linktype = LJ_TRLINK_NONE;
 610           J->loopref = J->cur.nins;
 611           J->state = LJ_TRACE_RECORD;  /* Try to continue recording. */
 612           break;
 613         }
 614         J->loopref = J->chain[IR_LOOP];  /* Needed by assembler. */
 615       }
 616       lj_opt_split(J);
 617       lj_opt_sink(J);
 618       if (!J->loopref) J->cur.snap[J->cur.nsnap-1].count = SNAPCOUNT_DONE;
 619       J->state = LJ_TRACE_ASM;
 620       break;
 621 
 622     case LJ_TRACE_ASM:
 623       setvmstate(J2G(J), ASM);
 624       lj_asm_trace(J, &J->cur);
 625       trace_stop(J);
 626       setvmstate(J2G(J), INTERP);
 627       J->state = LJ_TRACE_IDLE;
 628       lj_dispatch_update(J2G(J));
 629       return NULL;
 630 
 631     default:  /* Trace aborted asynchronously. */
 632       setintV(L->top++, (int32_t)LJ_TRERR_RECERR);
 633       /* fallthrough */
 634     case LJ_TRACE_ERR:
 635       trace_pendpatch(J, 1);
 636       if (trace_abort(J))
 637         goto retry;
 638       setvmstate(J2G(J), INTERP);
 639       J->state = LJ_TRACE_IDLE;
 640       lj_dispatch_update(J2G(J));
 641       return NULL;
 642     }
 643   } while (J->state > LJ_TRACE_RECORD);
 644   return NULL;
 645 }
 646 
 647 /* -- Event handling ------------------------------------------------------ */
 648 
 649 /* A bytecode instruction is about to be executed. Record it. */
 650 void lj_trace_ins(jit_State *J, const BCIns *pc)
 651 {
 652   /* Note: J->L must already be set. pc is the true bytecode PC here. */
 653   J->pc = pc;
 654   J->fn = curr_func(J->L);
 655   J->pt = isluafunc(J->fn) ? funcproto(J->fn) : NULL;
 656   while (lj_vm_cpcall(J->L, NULL, (void *)J, trace_state) != 0)
 657     J->state = LJ_TRACE_ERR;
 658 }
 659 
 660 /* A hotcount triggered. Start recording a root trace. */
 661 void LJ_FASTCALL lj_trace_hot(jit_State *J, const BCIns *pc)
 662 {
 663   /* Note: pc is the interpreter bytecode PC here. It's offset by 1. */
 664   ERRNO_SAVE
 665   /* Reset hotcount. */
 666   hotcount_set(J2GG(J), pc, J->param[JIT_P_hotloop]*HOTCOUNT_LOOP);
 667   /* Only start a new trace if not recording or inside __gc call or vmevent. */
 668   if (J->state == LJ_TRACE_IDLE &&
 669       !(J2G(J)->hookmask & (HOOK_GC|HOOK_VMEVENT))) {
 670     J->parent = 0;  /* Root trace. */
 671     J->exitno = 0;
 672     J->state = LJ_TRACE_START;
 673     lj_trace_ins(J, pc-1);
 674   }
 675   ERRNO_RESTORE
 676 }
 677 
 678 /* Check for a hot side exit. If yes, start recording a side trace. */
 679 static void trace_hotside(jit_State *J, const BCIns *pc)
 680 {
 681   SnapShot *snap = &traceref(J, J->parent)->snap[J->exitno];
 682   if (!(J2G(J)->hookmask & (HOOK_GC|HOOK_VMEVENT)) &&
 683       snap->count != SNAPCOUNT_DONE &&
 684       ++snap->count >= J->param[JIT_P_hotexit]) {
 685     lua_assert(J->state == LJ_TRACE_IDLE);
 686     /* J->parent is non-zero for a side trace. */
 687     J->state = LJ_TRACE_START;
 688     lj_trace_ins(J, pc);
 689   }
 690 }
 691 
 692 /* Tiny struct to pass data to protected call. */
 693 typedef struct ExitDataCP {
 694   jit_State *J;
 695   void *exptr;          /* Pointer to exit state. */
 696   const BCIns *pc;      /* Restart interpreter at this PC. */
 697 } ExitDataCP;
 698 
 699 /* Need to protect lj_snap_restore because it may throw. */
 700 static TValue *trace_exit_cp(lua_State *L, lua_CFunction dummy, void *ud)
 701 {
 702   ExitDataCP *exd = (ExitDataCP *)ud;
 703   cframe_errfunc(L->cframe) = -1;  /* Inherit error function. */
 704   exd->pc = lj_snap_restore(exd->J, exd->exptr);
 705   UNUSED(dummy);
 706   return NULL;
 707 }
 708 
 709 #ifndef LUAJIT_DISABLE_VMEVENT
 710 /* Push all registers from exit state. */
 711 static void trace_exit_regs(lua_State *L, ExitState *ex)
 712 {
 713   int32_t i;
 714   setintV(L->top++, RID_NUM_GPR);
 715   setintV(L->top++, RID_NUM_FPR);
 716   for (i = 0; i < RID_NUM_GPR; i++) {
 717     if (sizeof(ex->gpr[i]) == sizeof(int32_t))
 718       setintV(L->top++, (int32_t)ex->gpr[i]);
 719     else
 720       setnumV(L->top++, (lua_Number)ex->gpr[i]);
 721   }
 722 #if !LJ_SOFTFP
 723   for (i = 0; i < RID_NUM_FPR; i++) {
 724     setnumV(L->top, ex->fpr[i]);
 725     if (LJ_UNLIKELY(tvisnan(L->top)))
 726       setnanV(L->top);
 727     L->top++;
 728   }
 729 #endif
 730 }
 731 #endif
 732 
 733 #ifdef EXITSTATE_PCREG
 734 /* Determine trace number from pc of exit instruction. */
 735 static TraceNo trace_exit_find(jit_State *J, MCode *pc)
 736 {
 737   TraceNo traceno;
 738   for (traceno = 1; traceno < J->sizetrace; traceno++) {
 739     GCtrace *T = traceref(J, traceno);
 740     if (T && pc >= T->mcode && pc < (MCode *)((char *)T->mcode + T->szmcode))
 741       return traceno;
 742   }
 743   lua_assert(0);
 744   return 0;
 745 }
 746 #endif
 747 
 748 /* A trace exited. Restore interpreter state. */
 749 int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr)
 750 {
 751   ERRNO_SAVE
 752   lua_State *L = J->L;
 753   ExitState *ex = (ExitState *)exptr;
 754   ExitDataCP exd;
 755   int errcode;
 756   const BCIns *pc;
 757   void *cf;
 758   GCtrace *T;
 759 #ifdef EXITSTATE_PCREG
 760   J->parent = trace_exit_find(J, (MCode *)(intptr_t)ex->gpr[EXITSTATE_PCREG]);
 761 #endif
 762   T = traceref(J, J->parent); UNUSED(T);
 763 #ifdef EXITSTATE_CHECKEXIT
 764   if (J->exitno == T->nsnap) {  /* Treat stack check like a parent exit. */
 765     lua_assert(T->root != 0);
 766     J->exitno = T->ir[REF_BASE].op2;
 767     J->parent = T->ir[REF_BASE].op1;
 768     T = traceref(J, J->parent);
 769   }
 770 #endif
 771   lua_assert(T != NULL && J->exitno < T->nsnap);
 772   exd.J = J;
 773   exd.exptr = exptr;
 774   errcode = lj_vm_cpcall(L, NULL, &exd, trace_exit_cp);
 775   if (errcode)
 776     return -errcode;  /* Return negated error code. */
 777 
 778   lj_vmevent_send(L, TEXIT,
 779     lj_state_checkstack(L, 4+RID_NUM_GPR+RID_NUM_FPR+LUA_MINSTACK);
 780     setintV(L->top++, J->parent);
 781     setintV(L->top++, J->exitno);
 782     trace_exit_regs(L, ex);
 783   );
 784 
 785   pc = exd.pc;
 786   cf = cframe_raw(L->cframe);
 787   setcframe_pc(cf, pc);
 788   if (G(L)->gc.state == GCSatomic || G(L)->gc.state == GCSfinalize) {
 789     if (!(G(L)->hookmask & HOOK_GC))
 790       lj_gc_step(L);  /* Exited because of GC: drive GC forward. */
 791   } else {
 792     trace_hotside(J, pc);
 793   }
 794   if (bc_op(*pc) == BC_JLOOP) {
 795     BCIns *retpc = &traceref(J, bc_d(*pc))->startins;
 796     if (bc_isret(bc_op(*retpc))) {
 797       if (J->state == LJ_TRACE_RECORD) {
 798         J->patchins = *pc;
 799         J->patchpc = (BCIns *)pc;
 800         *J->patchpc = *retpc;
 801         J->bcskip = 1;
 802       } else {
 803         pc = retpc;
 804         setcframe_pc(cf, pc);
 805       }
 806     }
 807   }
 808   /* Return MULTRES or 0. */
 809   ERRNO_RESTORE
 810   switch (bc_op(*pc)) {
 811   case BC_CALLM: case BC_CALLMT:
 812     return (int)((BCReg)(L->top - L->base) - bc_a(*pc) - bc_c(*pc));
 813   case BC_RETM:
 814     return (int)((BCReg)(L->top - L->base) + 1 - bc_a(*pc) - bc_d(*pc));
 815   case BC_TSETM:
 816     return (int)((BCReg)(L->top - L->base) + 1 - bc_a(*pc));
 817   default:
 818     if (bc_op(*pc) >= BC_FUNCF)
 819       return (int)((BCReg)(L->top - L->base) + 1);
 820     return 0;
 821   }
 822 }
 823 
 824 #endif

/* [<][>][^][v][top][bottom][index][help] */