lj_opt_narrow.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /*
  2. ** NARROW: Narrowing of numbers to integers (double to int32_t).
  3. ** STRIPOV: Stripping of overflow checks.
  4. ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
  5. */
  6. #define lj_opt_narrow_c
  7. #define LUA_CORE
  8. #include "lj_obj.h"
  9. #if LJ_HASJIT
  10. #include "lj_bc.h"
  11. #include "lj_ir.h"
  12. #include "lj_jit.h"
  13. #include "lj_iropt.h"
  14. #include "lj_trace.h"
  15. #include "lj_vm.h"
  16. #include "lj_strscan.h"
  17. /* Rationale for narrowing optimizations:
  18. **
  19. ** Lua has only a single number type and this is a FP double by default.
  20. ** Narrowing doubles to integers does not pay off for the interpreter on a
  21. ** current-generation x86/x64 machine. Most FP operations need the same
  22. ** amount of execution resources as their integer counterparts, except
  23. ** with slightly longer latencies. Longer latencies are a non-issue for
  24. ** the interpreter, since they are usually hidden by other overhead.
  25. **
  26. ** The total CPU execution bandwidth is the sum of the bandwidth of the FP
  27. ** and the integer units, because they execute in parallel. The FP units
  28. ** have an equal or higher bandwidth than the integer units. Not using
  29. ** them means losing execution bandwidth. Moving work away from them to
  30. ** the already quite busy integer units is a losing proposition.
  31. **
  32. ** The situation for JIT-compiled code is a bit different: the higher code
  33. ** density makes the extra latencies much more visible. Tight loops expose
  34. ** the latencies for updating the induction variables. Array indexing
  35. ** requires narrowing conversions with high latencies and additional
  36. ** guards (to check that the index is really an integer). And many common
  37. ** optimizations only work on integers.
  38. **
  39. ** One solution would be speculative, eager narrowing of all number loads.
  40. ** This causes many problems, like losing -0 or the need to resolve type
  41. ** mismatches between traces. It also effectively forces the integer type
  42. ** to have overflow-checking semantics. This impedes many basic
  43. ** optimizations and requires adding overflow checks to all integer
  44. ** arithmetic operations (whereas FP arithmetics can do without).
  45. **
  46. ** Always replacing an FP op with an integer op plus an overflow check is
  47. ** counter-productive on a current-generation super-scalar CPU. Although
  48. ** the overflow check branches are highly predictable, they will clog the
  49. ** execution port for the branch unit and tie up reorder buffers. This is
  50. ** turning a pure data-flow dependency into a different data-flow
  51. ** dependency (with slightly lower latency) *plus* a control dependency.
  52. ** In general, you don't want to do this since latencies due to data-flow
  53. ** dependencies can be well hidden by out-of-order execution.
  54. **
  55. ** A better solution is to keep all numbers as FP values and only narrow
  56. ** when it's beneficial to do so. LuaJIT uses predictive narrowing for
  57. ** induction variables and demand-driven narrowing for index expressions,
  58. ** integer arguments and bit operations. Additionally it can eliminate or
  59. ** hoist most of the resulting overflow checks. Regular arithmetic
  60. ** computations are never narrowed to integers.
  61. **
  62. ** The integer type in the IR has convenient wrap-around semantics and
  63. ** ignores overflow. Extra operations have been added for
  64. ** overflow-checking arithmetic (ADDOV/SUBOV) instead of an extra type.
  65. ** Apart from reducing overall complexity of the compiler, this also
  66. ** nicely solves the problem where you want to apply algebraic
  67. ** simplifications to ADD, but not to ADDOV. And the x86/x64 assembler can
  68. ** use lea instead of an add for integer ADD, but not for ADDOV (lea does
  69. ** not affect the flags, but it helps to avoid register moves).
  70. **
  71. **
  72. ** All of the above has to be reconsidered for architectures with slow FP
  73. ** operations or without a hardware FPU. The dual-number mode of LuaJIT
  74. ** addresses this issue. Arithmetic operations are performed on integers
  75. ** as far as possible and overflow checks are added as needed.
  76. **
  77. ** This implies that narrowing for integer arguments and bit operations
  78. ** should also strip overflow checks, e.g. replace ADDOV with ADD. The
  79. ** original overflow guards are weak and can be eliminated by DCE, if
  80. ** there's no other use.
  81. **
  82. ** A slight twist is that it's usually beneficial to use overflow-checked
  83. ** integer arithmetics if all inputs are already integers. This is the only
  84. ** change that affects the single-number mode, too.
  85. */
  86. /* Some local macros to save typing. Undef'd at the end. */
  87. #define IR(ref) (&J->cur.ir[(ref)])
  88. #define fins (&J->fold.ins)
  89. /* Pass IR on to next optimization in chain (FOLD). */
  90. #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J))
  91. #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J))
  92. /* -- Elimination of narrowing type conversions --------------------------- */
  93. /* Narrowing of index expressions and bit operations is demand-driven. The
  94. ** trace recorder emits a narrowing type conversion (CONV.int.num or TOBIT)
  95. ** in all of these cases (e.g. array indexing or string indexing). FOLD
  96. ** already takes care of eliminating simple redundant conversions like
  97. ** CONV.int.num(CONV.num.int(x)) ==> x.
  98. **
  99. ** But the surrounding code is FP-heavy and arithmetic operations are
  100. ** performed on FP numbers (for the single-number mode). Consider a common
  101. ** example such as 'x=t[i+1]', with 'i' already an integer (due to induction
  102. ** variable narrowing). The index expression would be recorded as
  103. ** CONV.int.num(ADD(CONV.num.int(i), 1))
  104. ** which is clearly suboptimal.
  105. **
  106. ** One can do better by recursively backpropagating the narrowing type
  107. ** conversion across FP arithmetic operations. This turns FP ops into
  108. ** their corresponding integer counterparts. Depending on the semantics of
  109. ** the conversion they also need to check for overflow. Currently only ADD
  110. ** and SUB are supported.
  111. **
  112. ** The above example can be rewritten as
  113. ** ADDOV(CONV.int.num(CONV.num.int(i)), 1)
  114. ** and then into ADDOV(i, 1) after folding of the conversions. The original
  115. ** FP ops remain in the IR and are eliminated by DCE since all references to
  116. ** them are gone.
  117. **
  118. ** [In dual-number mode the trace recorder already emits ADDOV etc., but
  119. ** this can be further reduced. See below.]
  120. **
  121. ** Special care has to be taken to avoid narrowing across an operation
  122. ** which is potentially operating on non-integral operands. One obvious
  123. ** case is when an expression contains a non-integral constant, but ends
  124. ** up as an integer index at runtime (like t[x+1.5] with x=0.5).
  125. **
  126. ** Operations with two non-constant operands illustrate a similar problem
  127. ** (like t[a+b] with a=1.5 and b=2.5). Backpropagation has to stop there,
  128. ** unless it can be proven that either operand is integral (e.g. by CSEing
  129. ** a previous conversion). As a not-so-obvious corollary this logic also
  130. ** applies for a whole expression tree (e.g. t[(a+1)+(b+1)]).
  131. **
  132. ** Correctness of the transformation is guaranteed by avoiding to expand
  133. ** the tree by adding more conversions than the one we would need to emit
  134. ** if not backpropagating. TOBIT employs a more optimistic rule, because
  135. ** the conversion has special semantics, designed to make the life of the
  136. ** compiler writer easier. ;-)
  137. **
  138. ** Using on-the-fly backpropagation of an expression tree doesn't work
  139. ** because it's unknown whether the transform is correct until the end.
  140. ** This either requires IR rollback and cache invalidation for every
  141. ** subtree or a two-pass algorithm. The former didn't work out too well,
  142. ** so the code now combines a recursive collector with a stack-based
  143. ** emitter.
  144. **
  145. ** [A recursive backpropagation algorithm with backtracking, employing
  146. ** skip-list lookup and round-robin caching, emitting stack operations
  147. ** on-the-fly for a stack-based interpreter -- and all of that in a meager
  148. ** kilobyte? Yep, compilers are a great treasure chest. Throw away your
  149. ** textbooks and read the codebase of a compiler today!]
  150. **
  151. ** There's another optimization opportunity for array indexing: it's
  152. ** always accompanied by an array bounds-check. The outermost overflow
  153. ** check may be delegated to the ABC operation. This works because ABC is
  154. ** an unsigned comparison and wrap-around due to overflow creates negative
  155. ** numbers.
  156. **
  157. ** But this optimization is only valid for constants that cannot overflow
  158. ** an int32_t into the range of valid array indexes [0..2^27+1). A check
  159. ** for +-2^30 is safe since -2^31 - 2^30 wraps to 2^30 and 2^31-1 + 2^30
  160. ** wraps to -2^30-1.
  161. **
  162. ** It's also good enough in practice, since e.g. t[i+1] or t[i-10] are
  163. ** quite common. So the above example finally ends up as ADD(i, 1)!
  164. **
  165. ** Later on, the assembler is able to fuse the whole array reference and
  166. ** the ADD into the memory operands of loads and other instructions. This
  167. ** is why LuaJIT is able to generate very pretty (and fast) machine code
  168. ** for array indexing. And that, my dear, concludes another story about
  169. ** one of the hidden secrets of LuaJIT ...
  170. */
  171. /* Maximum backpropagation depth and maximum stack size. */
  172. #define NARROW_MAX_BACKPROP 100
  173. #define NARROW_MAX_STACK 256
  174. /* The stack machine has a 32 bit instruction format: [IROpT | IRRef1]
  175. ** The lower 16 bits hold a reference (or 0). The upper 16 bits hold
  176. ** the IR opcode + type or one of the following special opcodes:
  177. */
  178. enum {
  179. NARROW_REF, /* Push ref. */
  180. NARROW_CONV, /* Push conversion of ref. */
  181. NARROW_SEXT, /* Push sign-extension of ref. */
  182. NARROW_INT /* Push KINT ref. The next code holds an int32_t. */
  183. };
  184. typedef uint32_t NarrowIns;
  185. #define NARROWINS(op, ref) (((op) << 16) + (ref))
  186. #define narrow_op(ins) ((IROpT)((ins) >> 16))
  187. #define narrow_ref(ins) ((IRRef1)(ins))
  188. /* Context used for narrowing of type conversions. */
  189. typedef struct NarrowConv {
  190. jit_State *J; /* JIT compiler state. */
  191. NarrowIns *sp; /* Current stack pointer. */
  192. NarrowIns *maxsp; /* Maximum stack pointer minus redzone. */
  193. IRRef mode; /* Conversion mode (IRCONV_*). */
  194. IRType t; /* Destination type: IRT_INT or IRT_I64. */
  195. NarrowIns stack[NARROW_MAX_STACK]; /* Stack holding stack-machine code. */
  196. } NarrowConv;
  197. /* Lookup a reference in the backpropagation cache. */
  198. static BPropEntry *narrow_bpc_get(jit_State *J, IRRef1 key, IRRef mode)
  199. {
  200. ptrdiff_t i;
  201. for (i = 0; i < BPROP_SLOTS; i++) {
  202. BPropEntry *bp = &J->bpropcache[i];
  203. /* Stronger checks are ok, too. */
  204. if (bp->key == key && bp->mode >= mode &&
  205. ((bp->mode ^ mode) & IRCONV_MODEMASK) == 0)
  206. return bp;
  207. }
  208. return NULL;
  209. }
  210. /* Add an entry to the backpropagation cache. */
  211. static void narrow_bpc_set(jit_State *J, IRRef1 key, IRRef1 val, IRRef mode)
  212. {
  213. uint32_t slot = J->bpropslot;
  214. BPropEntry *bp = &J->bpropcache[slot];
  215. J->bpropslot = (slot + 1) & (BPROP_SLOTS-1);
  216. bp->key = key;
  217. bp->val = val;
  218. bp->mode = mode;
  219. }
  220. /* Backpropagate overflow stripping. */
  221. static void narrow_stripov_backprop(NarrowConv *nc, IRRef ref, int depth)
  222. {
  223. jit_State *J = nc->J;
  224. IRIns *ir = IR(ref);
  225. if (ir->o == IR_ADDOV || ir->o == IR_SUBOV ||
  226. (ir->o == IR_MULOV && (nc->mode & IRCONV_CONVMASK) == IRCONV_ANY)) {
  227. BPropEntry *bp = narrow_bpc_get(nc->J, ref, IRCONV_TOBIT);
  228. if (bp) {
  229. ref = bp->val;
  230. } else if (++depth < NARROW_MAX_BACKPROP && nc->sp < nc->maxsp) {
  231. NarrowIns *savesp = nc->sp;
  232. narrow_stripov_backprop(nc, ir->op1, depth);
  233. if (nc->sp < nc->maxsp) {
  234. narrow_stripov_backprop(nc, ir->op2, depth);
  235. if (nc->sp < nc->maxsp) {
  236. *nc->sp++ = NARROWINS(IRT(ir->o - IR_ADDOV + IR_ADD, IRT_INT), ref);
  237. return;
  238. }
  239. }
  240. nc->sp = savesp; /* Path too deep, need to backtrack. */
  241. }
  242. }
  243. *nc->sp++ = NARROWINS(NARROW_REF, ref);
  244. }
  245. /* Backpropagate narrowing conversion. Return number of needed conversions. */
  246. static int narrow_conv_backprop(NarrowConv *nc, IRRef ref, int depth)
  247. {
  248. jit_State *J = nc->J;
  249. IRIns *ir = IR(ref);
  250. IRRef cref;
  251. if (nc->sp >= nc->maxsp) return 10; /* Path too deep. */
  252. /* Check the easy cases first. */
  253. if (ir->o == IR_CONV && (ir->op2 & IRCONV_SRCMASK) == IRT_INT) {
  254. if ((nc->mode & IRCONV_CONVMASK) <= IRCONV_ANY)
  255. narrow_stripov_backprop(nc, ir->op1, depth+1);
  256. else
  257. *nc->sp++ = NARROWINS(NARROW_REF, ir->op1); /* Undo conversion. */
  258. if (nc->t == IRT_I64)
  259. *nc->sp++ = NARROWINS(NARROW_SEXT, 0); /* Sign-extend integer. */
  260. return 0;
  261. } else if (ir->o == IR_KNUM) { /* Narrow FP constant. */
  262. lua_Number n = ir_knum(ir)->n;
  263. if ((nc->mode & IRCONV_CONVMASK) == IRCONV_TOBIT) {
  264. /* Allows a wider range of constants. */
  265. int64_t k64 = (int64_t)n;
  266. if (n == (lua_Number)k64) { /* Only if const doesn't lose precision. */
  267. *nc->sp++ = NARROWINS(NARROW_INT, 0);
  268. *nc->sp++ = (NarrowIns)k64; /* But always truncate to 32 bits. */
  269. return 0;
  270. }
  271. } else {
  272. int32_t k = lj_num2int(n);
  273. /* Only if constant is a small integer. */
  274. if (checki16(k) && n == (lua_Number)k) {
  275. *nc->sp++ = NARROWINS(NARROW_INT, 0);
  276. *nc->sp++ = (NarrowIns)k;
  277. return 0;
  278. }
  279. }
  280. return 10; /* Never narrow other FP constants (this is rare). */
  281. }
  282. /* Try to CSE the conversion. Stronger checks are ok, too. */
  283. cref = J->chain[fins->o];
  284. while (cref > ref) {
  285. IRIns *cr = IR(cref);
  286. if (cr->op1 == ref &&
  287. (fins->o == IR_TOBIT ||
  288. ((cr->op2 & IRCONV_MODEMASK) == (nc->mode & IRCONV_MODEMASK) &&
  289. irt_isguard(cr->t) >= irt_isguard(fins->t)))) {
  290. *nc->sp++ = NARROWINS(NARROW_REF, cref);
  291. return 0; /* Already there, no additional conversion needed. */
  292. }
  293. cref = cr->prev;
  294. }
  295. /* Backpropagate across ADD/SUB. */
  296. if (ir->o == IR_ADD || ir->o == IR_SUB) {
  297. /* Try cache lookup first. */
  298. IRRef mode = nc->mode;
  299. BPropEntry *bp;
  300. /* Inner conversions need a stronger check. */
  301. if ((mode & IRCONV_CONVMASK) == IRCONV_INDEX && depth > 0)
  302. mode += IRCONV_CHECK-IRCONV_INDEX;
  303. bp = narrow_bpc_get(nc->J, (IRRef1)ref, mode);
  304. if (bp) {
  305. *nc->sp++ = NARROWINS(NARROW_REF, bp->val);
  306. return 0;
  307. } else if (nc->t == IRT_I64) {
  308. /* Try sign-extending from an existing (checked) conversion to int. */
  309. mode = (IRT_INT<<5)|IRT_NUM|IRCONV_INDEX;
  310. bp = narrow_bpc_get(nc->J, (IRRef1)ref, mode);
  311. if (bp) {
  312. *nc->sp++ = NARROWINS(NARROW_REF, bp->val);
  313. *nc->sp++ = NARROWINS(NARROW_SEXT, 0);
  314. return 0;
  315. }
  316. }
  317. if (++depth < NARROW_MAX_BACKPROP && nc->sp < nc->maxsp) {
  318. NarrowIns *savesp = nc->sp;
  319. int count = narrow_conv_backprop(nc, ir->op1, depth);
  320. count += narrow_conv_backprop(nc, ir->op2, depth);
  321. if (count <= 1) { /* Limit total number of conversions. */
  322. *nc->sp++ = NARROWINS(IRT(ir->o, nc->t), ref);
  323. return count;
  324. }
  325. nc->sp = savesp; /* Too many conversions, need to backtrack. */
  326. }
  327. }
  328. /* Otherwise add a conversion. */
  329. *nc->sp++ = NARROWINS(NARROW_CONV, ref);
  330. return 1;
  331. }
  332. /* Emit the conversions collected during backpropagation. */
  333. static IRRef narrow_conv_emit(jit_State *J, NarrowConv *nc)
  334. {
  335. /* The fins fields must be saved now -- emitir() overwrites them. */
  336. IROpT guardot = irt_isguard(fins->t) ? IRTG(IR_ADDOV-IR_ADD, 0) : 0;
  337. IROpT convot = fins->ot;
  338. IRRef1 convop2 = fins->op2;
  339. NarrowIns *next = nc->stack; /* List of instructions from backpropagation. */
  340. NarrowIns *last = nc->sp;
  341. NarrowIns *sp = nc->stack; /* Recycle the stack to store operands. */
  342. while (next < last) { /* Simple stack machine to process the ins. list. */
  343. NarrowIns ref = *next++;
  344. IROpT op = narrow_op(ref);
  345. if (op == NARROW_REF) {
  346. *sp++ = ref;
  347. } else if (op == NARROW_CONV) {
  348. *sp++ = emitir_raw(convot, ref, convop2); /* Raw emit avoids a loop. */
  349. } else if (op == NARROW_SEXT) {
  350. lj_assertJ(sp >= nc->stack+1, "stack underflow");
  351. sp[-1] = emitir(IRT(IR_CONV, IRT_I64), sp[-1],
  352. (IRT_I64<<5)|IRT_INT|IRCONV_SEXT);
  353. } else if (op == NARROW_INT) {
  354. lj_assertJ(next < last, "missing arg to NARROW_INT");
  355. *sp++ = nc->t == IRT_I64 ?
  356. lj_ir_kint64(J, (int64_t)(int32_t)*next++) :
  357. lj_ir_kint(J, *next++);
  358. } else { /* Regular IROpT. Pops two operands and pushes one result. */
  359. IRRef mode = nc->mode;
  360. lj_assertJ(sp >= nc->stack+2, "stack underflow");
  361. sp--;
  362. /* Omit some overflow checks for array indexing. See comments above. */
  363. if ((mode & IRCONV_CONVMASK) == IRCONV_INDEX) {
  364. if (next == last && irref_isk(narrow_ref(sp[0])) &&
  365. (uint32_t)IR(narrow_ref(sp[0]))->i + 0x40000000u < 0x80000000u)
  366. guardot = 0;
  367. else /* Otherwise cache a stronger check. */
  368. mode += IRCONV_CHECK-IRCONV_INDEX;
  369. }
  370. sp[-1] = emitir(op+guardot, sp[-1], sp[0]);
  371. /* Add to cache. */
  372. if (narrow_ref(ref))
  373. narrow_bpc_set(J, narrow_ref(ref), narrow_ref(sp[-1]), mode);
  374. }
  375. }
  376. lj_assertJ(sp == nc->stack+1, "stack misalignment");
  377. return nc->stack[0];
  378. }
  379. /* Narrow a type conversion of an arithmetic operation. */
  380. TRef LJ_FASTCALL lj_opt_narrow_convert(jit_State *J)
  381. {
  382. if ((J->flags & JIT_F_OPT_NARROW)) {
  383. NarrowConv nc;
  384. nc.J = J;
  385. nc.sp = nc.stack;
  386. nc.maxsp = &nc.stack[NARROW_MAX_STACK-4];
  387. nc.t = irt_type(fins->t);
  388. if (fins->o == IR_TOBIT) {
  389. nc.mode = IRCONV_TOBIT; /* Used only in the backpropagation cache. */
  390. } else {
  391. nc.mode = fins->op2;
  392. }
  393. if (narrow_conv_backprop(&nc, fins->op1, 0) <= 1)
  394. return narrow_conv_emit(J, &nc);
  395. }
  396. return NEXTFOLD;
  397. }
  398. /* -- Narrowing of implicit conversions ----------------------------------- */
  399. /* Recursively strip overflow checks. */
  400. static TRef narrow_stripov(jit_State *J, TRef tr, int lastop, IRRef mode)
  401. {
  402. IRRef ref = tref_ref(tr);
  403. IRIns *ir = IR(ref);
  404. int op = ir->o;
  405. if (op >= IR_ADDOV && op <= lastop) {
  406. BPropEntry *bp = narrow_bpc_get(J, ref, mode);
  407. if (bp) {
  408. return TREF(bp->val, irt_t(IR(bp->val)->t));
  409. } else {
  410. IRRef op1 = ir->op1, op2 = ir->op2; /* The IR may be reallocated. */
  411. op1 = narrow_stripov(J, op1, lastop, mode);
  412. op2 = narrow_stripov(J, op2, lastop, mode);
  413. tr = emitir(IRT(op - IR_ADDOV + IR_ADD,
  414. ((mode & IRCONV_DSTMASK) >> IRCONV_DSH)), op1, op2);
  415. narrow_bpc_set(J, ref, tref_ref(tr), mode);
  416. }
  417. } else if (LJ_64 && (mode & IRCONV_SEXT) && !irt_is64(ir->t)) {
  418. tr = emitir(IRT(IR_CONV, IRT_INTP), tr, mode);
  419. }
  420. return tr;
  421. }
  422. /* Narrow array index. */
  423. TRef LJ_FASTCALL lj_opt_narrow_index(jit_State *J, TRef tr)
  424. {
  425. IRIns *ir;
  426. lj_assertJ(tref_isnumber(tr), "expected number type");
  427. if (tref_isnum(tr)) /* Conversion may be narrowed, too. See above. */
  428. return emitir(IRTGI(IR_CONV), tr, IRCONV_INT_NUM|IRCONV_INDEX);
  429. /* Omit some overflow checks for array indexing. See comments above. */
  430. ir = IR(tref_ref(tr));
  431. if ((ir->o == IR_ADDOV || ir->o == IR_SUBOV) && irref_isk(ir->op2) &&
  432. (uint32_t)IR(ir->op2)->i + 0x40000000u < 0x80000000u)
  433. return emitir(IRTI(ir->o - IR_ADDOV + IR_ADD), ir->op1, ir->op2);
  434. return tr;
  435. }
  436. /* Narrow conversion to integer operand (overflow undefined). */
  437. TRef LJ_FASTCALL lj_opt_narrow_toint(jit_State *J, TRef tr)
  438. {
  439. if (tref_isstr(tr))
  440. tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
  441. if (tref_isnum(tr)) /* Conversion may be narrowed, too. See above. */
  442. return emitir(IRTI(IR_CONV), tr, IRCONV_INT_NUM|IRCONV_ANY);
  443. if (!tref_isinteger(tr))
  444. lj_trace_err(J, LJ_TRERR_BADTYPE);
  445. /*
  446. ** Undefined overflow semantics allow stripping of ADDOV, SUBOV and MULOV.
  447. ** Use IRCONV_TOBIT for the cache entries, since the semantics are the same.
  448. */
  449. return narrow_stripov(J, tr, IR_MULOV, (IRT_INT<<5)|IRT_INT|IRCONV_TOBIT);
  450. }
  451. /* Narrow conversion to bitop operand (overflow wrapped). */
  452. TRef LJ_FASTCALL lj_opt_narrow_tobit(jit_State *J, TRef tr)
  453. {
  454. if (tref_isstr(tr))
  455. tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
  456. if (tref_isnum(tr)) /* Conversion may be narrowed, too. See above. */
  457. return emitir(IRTI(IR_TOBIT), tr, lj_ir_knum_tobit(J));
  458. if (!tref_isinteger(tr))
  459. lj_trace_err(J, LJ_TRERR_BADTYPE);
  460. /*
  461. ** Wrapped overflow semantics allow stripping of ADDOV and SUBOV.
  462. ** MULOV cannot be stripped due to precision widening.
  463. */
  464. return narrow_stripov(J, tr, IR_SUBOV, (IRT_INT<<5)|IRT_INT|IRCONV_TOBIT);
  465. }
  466. #if LJ_HASFFI
  467. /* Narrow C array index (overflow undefined). */
  468. TRef LJ_FASTCALL lj_opt_narrow_cindex(jit_State *J, TRef tr)
  469. {
  470. lj_assertJ(tref_isnumber(tr), "expected number type");
  471. if (tref_isnum(tr))
  472. return emitir(IRT(IR_CONV, IRT_INTP), tr, (IRT_INTP<<5)|IRT_NUM|IRCONV_ANY);
  473. /* Undefined overflow semantics allow stripping of ADDOV, SUBOV and MULOV. */
  474. return narrow_stripov(J, tr, IR_MULOV,
  475. LJ_64 ? ((IRT_INTP<<5)|IRT_INT|IRCONV_SEXT) :
  476. ((IRT_INTP<<5)|IRT_INT|IRCONV_TOBIT));
  477. }
  478. #endif
  479. /* -- Narrowing of arithmetic operators ----------------------------------- */
  480. /* Check whether a number fits into an int32_t (-0 is ok, too). */
  481. static int numisint(lua_Number n)
  482. {
  483. return (n == (lua_Number)lj_num2int(n));
  484. }
  485. /* Convert string to number. Error out for non-numeric string values. */
  486. static TRef conv_str_tonum(jit_State *J, TRef tr, TValue *o)
  487. {
  488. if (tref_isstr(tr)) {
  489. tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
  490. /* Would need an inverted STRTO for this rare and useless case. */
  491. if (!lj_strscan_num(strV(o), o)) /* Convert in-place. Value used below. */
  492. lj_trace_err(J, LJ_TRERR_BADTYPE); /* Punt if non-numeric. */
  493. }
  494. return tr;
  495. }
  496. /* Narrowing of arithmetic operations. */
  497. TRef lj_opt_narrow_arith(jit_State *J, TRef rb, TRef rc,
  498. TValue *vb, TValue *vc, IROp op)
  499. {
  500. rb = conv_str_tonum(J, rb, vb);
  501. rc = conv_str_tonum(J, rc, vc);
  502. /* Must not narrow MUL in non-DUALNUM variant, because it loses -0. */
  503. if ((op >= IR_ADD && op <= (LJ_DUALNUM ? IR_MUL : IR_SUB)) &&
  504. tref_isinteger(rb) && tref_isinteger(rc) &&
  505. numisint(lj_vm_foldarith(numberVnum(vb), numberVnum(vc),
  506. (int)op - (int)IR_ADD)))
  507. return emitir(IRTGI((int)op - (int)IR_ADD + (int)IR_ADDOV), rb, rc);
  508. if (!tref_isnum(rb)) rb = emitir(IRTN(IR_CONV), rb, IRCONV_NUM_INT);
  509. if (!tref_isnum(rc)) rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
  510. return emitir(IRTN(op), rb, rc);
  511. }
  512. /* Narrowing of unary minus operator. */
  513. TRef lj_opt_narrow_unm(jit_State *J, TRef rc, TValue *vc)
  514. {
  515. rc = conv_str_tonum(J, rc, vc);
  516. if (tref_isinteger(rc)) {
  517. uint32_t k = (uint32_t)numberVint(vc);
  518. if ((LJ_DUALNUM || k != 0) && k != 0x80000000u) {
  519. TRef zero = lj_ir_kint(J, 0);
  520. if (!LJ_DUALNUM)
  521. emitir(IRTGI(IR_NE), rc, zero);
  522. return emitir(IRTGI(IR_SUBOV), zero, rc);
  523. }
  524. rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
  525. }
  526. return emitir(IRTN(IR_NEG), rc, lj_ir_ksimd(J, LJ_KSIMD_NEG));
  527. }
  528. /* Narrowing of modulo operator. */
  529. TRef lj_opt_narrow_mod(jit_State *J, TRef rb, TRef rc, TValue *vb, TValue *vc)
  530. {
  531. TRef tmp;
  532. rb = conv_str_tonum(J, rb, vb);
  533. rc = conv_str_tonum(J, rc, vc);
  534. if ((LJ_DUALNUM || (J->flags & JIT_F_OPT_NARROW)) &&
  535. tref_isinteger(rb) && tref_isinteger(rc) &&
  536. (tvisint(vc) ? intV(vc) != 0 : !tviszero(vc))) {
  537. emitir(IRTGI(IR_NE), rc, lj_ir_kint(J, 0));
  538. return emitir(IRTI(IR_MOD), rb, rc);
  539. }
  540. /* b % c ==> b - floor(b/c)*c */
  541. rb = lj_ir_tonum(J, rb);
  542. rc = lj_ir_tonum(J, rc);
  543. tmp = emitir(IRTN(IR_DIV), rb, rc);
  544. tmp = emitir(IRTN(IR_FPMATH), tmp, IRFPM_FLOOR);
  545. tmp = emitir(IRTN(IR_MUL), tmp, rc);
  546. return emitir(IRTN(IR_SUB), rb, tmp);
  547. }
  548. /* -- Predictive narrowing of induction variables ------------------------- */
  549. /* Narrow a single runtime value. */
  550. static int narrow_forl(jit_State *J, cTValue *o)
  551. {
  552. if (tvisint(o)) return 1;
  553. if (LJ_DUALNUM || (J->flags & JIT_F_OPT_NARROW)) return numisint(numV(o));
  554. return 0;
  555. }
  556. /* Narrow the FORL index type by looking at the runtime values. */
  557. IRType lj_opt_narrow_forl(jit_State *J, cTValue *tv)
  558. {
  559. lj_assertJ(tvisnumber(&tv[FORL_IDX]) &&
  560. tvisnumber(&tv[FORL_STOP]) &&
  561. tvisnumber(&tv[FORL_STEP]),
  562. "expected number types");
  563. /* Narrow only if the runtime values of start/stop/step are all integers. */
  564. if (narrow_forl(J, &tv[FORL_IDX]) &&
  565. narrow_forl(J, &tv[FORL_STOP]) &&
  566. narrow_forl(J, &tv[FORL_STEP])) {
  567. /* And if the loop index can't possibly overflow. */
  568. lua_Number step = numberVnum(&tv[FORL_STEP]);
  569. lua_Number sum = numberVnum(&tv[FORL_STOP]) + step;
  570. if (0 <= step ? (sum <= 2147483647.0) : (sum >= -2147483648.0))
  571. return IRT_INT;
  572. }
  573. return IRT_NUM;
  574. }
  575. #undef IR
  576. #undef fins
  577. #undef emitir
  578. #undef emitir_raw
  579. #endif