1/*
2** Common definitions for the JIT compiler.
3** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_JIT_H
7#define _LJ_JIT_H
8
9#include "lj_obj.h"
10#include "lj_ir.h"
11
12/* JIT engine flags. */
13#define JIT_F_ON 0x00000001
14
15/* CPU-specific JIT engine flags. */
16#if LJ_TARGET_X86ORX64
17#define JIT_F_CMOV 0x00000010
18#define JIT_F_SSE2 0x00000020
19#define JIT_F_SSE3 0x00000040
20#define JIT_F_SSE4_1 0x00000080
21#define JIT_F_P4 0x00000100
22#define JIT_F_PREFER_IMUL 0x00000200
23#define JIT_F_SPLIT_XMM 0x00000400
24#define JIT_F_LEA_AGU 0x00000800
25
26/* Names for the CPU-specific flags. Must match the order above. */
27#define JIT_F_CPU_FIRST JIT_F_CMOV
28#define JIT_F_CPUSTRING "\4CMOV\4SSE2\4SSE3\6SSE4.1\2P4\3AMD\2K8\4ATOM"
29#elif LJ_TARGET_ARM
30#define JIT_F_ARMV6_ 0x00000010
31#define JIT_F_ARMV6T2_ 0x00000020
32#define JIT_F_ARMV7 0x00000040
33#define JIT_F_VFPV2 0x00000080
34#define JIT_F_VFPV3 0x00000100
35
36#define JIT_F_ARMV6 (JIT_F_ARMV6_|JIT_F_ARMV6T2_|JIT_F_ARMV7)
37#define JIT_F_ARMV6T2 (JIT_F_ARMV6T2_|JIT_F_ARMV7)
38#define JIT_F_VFP (JIT_F_VFPV2|JIT_F_VFPV3)
39
40/* Names for the CPU-specific flags. Must match the order above. */
41#define JIT_F_CPU_FIRST JIT_F_ARMV6_
42#define JIT_F_CPUSTRING "\5ARMv6\7ARMv6T2\5ARMv7\5VFPv2\5VFPv3"
43#elif LJ_TARGET_PPC
44#define JIT_F_SQRT 0x00000010
45#define JIT_F_ROUND 0x00000020
46
47/* Names for the CPU-specific flags. Must match the order above. */
48#define JIT_F_CPU_FIRST JIT_F_SQRT
49#define JIT_F_CPUSTRING "\4SQRT\5ROUND"
50#elif LJ_TARGET_MIPS
51#define JIT_F_MIPS32R2 0x00000010
52
53/* Names for the CPU-specific flags. Must match the order above. */
54#define JIT_F_CPU_FIRST JIT_F_MIPS32R2
55#define JIT_F_CPUSTRING "\010MIPS32R2"
56#else
57#define JIT_F_CPU_FIRST 0
58#define JIT_F_CPUSTRING ""
59#endif
60
61/* Optimization flags. */
62#define JIT_F_OPT_MASK 0x0fff0000
63
64#define JIT_F_OPT_FOLD 0x00010000
65#define JIT_F_OPT_CSE 0x00020000
66#define JIT_F_OPT_DCE 0x00040000
67#define JIT_F_OPT_FWD 0x00080000
68#define JIT_F_OPT_DSE 0x00100000
69#define JIT_F_OPT_NARROW 0x00200000
70#define JIT_F_OPT_LOOP 0x00400000
71#define JIT_F_OPT_ABC 0x00800000
72#define JIT_F_OPT_SINK 0x01000000
73#define JIT_F_OPT_FUSE 0x02000000
74
75/* Optimizations names for -O. Must match the order above. */
76#define JIT_F_OPT_FIRST JIT_F_OPT_FOLD
77#define JIT_F_OPTSTRING \
78 "\4fold\3cse\3dce\3fwd\3dse\6narrow\4loop\3abc\4sink\4fuse"
79
80/* Optimization levels set a fixed combination of flags. */
81#define JIT_F_OPT_0 0
82#define JIT_F_OPT_1 (JIT_F_OPT_FOLD|JIT_F_OPT_CSE|JIT_F_OPT_DCE)
83#define JIT_F_OPT_2 (JIT_F_OPT_1|JIT_F_OPT_NARROW|JIT_F_OPT_LOOP)
84#define JIT_F_OPT_3 (JIT_F_OPT_2|\
85 JIT_F_OPT_FWD|JIT_F_OPT_DSE|JIT_F_OPT_ABC|JIT_F_OPT_SINK|JIT_F_OPT_FUSE)
86#define JIT_F_OPT_DEFAULT JIT_F_OPT_3
87
88#if LJ_TARGET_WINDOWS || LJ_64
89/* See: http://blogs.msdn.com/oldnewthing/archive/2003/10/08/55239.aspx */
90#define JIT_P_sizemcode_DEFAULT 64
91#else
92/* Could go as low as 4K, but the mmap() overhead would be rather high. */
93#define JIT_P_sizemcode_DEFAULT 32
94#endif
95
96/* Optimization parameters and their defaults. Length is a char in octal! */
97#define JIT_PARAMDEF(_) \
98 _(\010, maxtrace, 1000) /* Max. # of traces in cache. */ \
99 _(\011, maxrecord, 4000) /* Max. # of recorded IR instructions. */ \
100 _(\012, maxirconst, 500) /* Max. # of IR constants of a trace. */ \
101 _(\007, maxside, 100) /* Max. # of side traces of a root trace. */ \
102 _(\007, maxsnap, 500) /* Max. # of snapshots for a trace. */ \
103 \
104 _(\007, hotloop, 56) /* # of iter. to detect a hot loop/call. */ \
105 _(\007, hotexit, 10) /* # of taken exits to start a side trace. */ \
106 _(\007, tryside, 4) /* # of attempts to compile a side trace. */ \
107 \
108 _(\012, instunroll, 4) /* Max. unroll for instable loops. */ \
109 _(\012, loopunroll, 15) /* Max. unroll for loop ops in side traces. */ \
110 _(\012, callunroll, 3) /* Max. unroll for recursive calls. */ \
111 _(\011, recunroll, 2) /* Min. unroll for true recursion. */ \
112 \
113 /* Size of each machine code area (in KBytes). */ \
114 _(\011, sizemcode, JIT_P_sizemcode_DEFAULT) \
115 /* Max. total size of all machine code areas (in KBytes). */ \
116 _(\010, maxmcode, 512) \
117 /* End of list. */
118
119enum {
120#define JIT_PARAMENUM(len, name, value) JIT_P_##name,
121JIT_PARAMDEF(JIT_PARAMENUM)
122#undef JIT_PARAMENUM
123 JIT_P__MAX
124};
125
126#define JIT_PARAMSTR(len, name, value) #len #name
127#define JIT_P_STRING JIT_PARAMDEF(JIT_PARAMSTR)
128
129/* Trace compiler state. */
130typedef enum {
131 LJ_TRACE_IDLE, /* Trace compiler idle. */
132 LJ_TRACE_ACTIVE = 0x10,
133 LJ_TRACE_RECORD, /* Bytecode recording active. */
134 LJ_TRACE_START, /* New trace started. */
135 LJ_TRACE_END, /* End of trace. */
136 LJ_TRACE_ASM, /* Assemble trace. */
137 LJ_TRACE_ERR /* Trace aborted with error. */
138} TraceState;
139
140/* Post-processing action. */
141typedef enum {
142 LJ_POST_NONE, /* No action. */
143 LJ_POST_FIXCOMP, /* Fixup comparison and emit pending guard. */
144 LJ_POST_FIXGUARD, /* Fixup and emit pending guard. */
145 LJ_POST_FIXGUARDSNAP, /* Fixup and emit pending guard and snapshot. */
146 LJ_POST_FIXBOOL, /* Fixup boolean result. */
147 LJ_POST_FIXCONST, /* Fixup constant results. */
148 LJ_POST_FFRETRY /* Suppress recording of retried fast functions. */
149} PostProc;
150
151/* Machine code type. */
152#if LJ_TARGET_X86ORX64
153typedef uint8_t MCode;
154#else
155typedef uint32_t MCode;
156#endif
157
158/* Stack snapshot header. */
159typedef struct SnapShot {
160 uint16_t mapofs; /* Offset into snapshot map. */
161 IRRef1 ref; /* First IR ref for this snapshot. */
162 uint8_t nslots; /* Number of valid slots. */
163 uint8_t topslot; /* Maximum frame extent. */
164 uint8_t nent; /* Number of compressed entries. */
165 uint8_t count; /* Count of taken exits for this snapshot. */
166} SnapShot;
167
168#define SNAPCOUNT_DONE 255 /* Already compiled and linked a side trace. */
169
170/* Compressed snapshot entry. */
171typedef uint32_t SnapEntry;
172
173#define SNAP_FRAME 0x010000 /* Frame slot. */
174#define SNAP_CONT 0x020000 /* Continuation slot. */
175#define SNAP_NORESTORE 0x040000 /* No need to restore slot. */
176#define SNAP_SOFTFPNUM 0x080000 /* Soft-float number. */
177LJ_STATIC_ASSERT(SNAP_FRAME == TREF_FRAME);
178LJ_STATIC_ASSERT(SNAP_CONT == TREF_CONT);
179
180#define SNAP(slot, flags, ref) (((SnapEntry)(slot) << 24) + (flags) + (ref))
181#define SNAP_TR(slot, tr) \
182 (((SnapEntry)(slot) << 24) + ((tr) & (TREF_CONT|TREF_FRAME|TREF_REFMASK)))
183#define SNAP_MKPC(pc) ((SnapEntry)u32ptr(pc))
184#define SNAP_MKFTSZ(ftsz) ((SnapEntry)(ftsz))
185#define snap_ref(sn) ((sn) & 0xffff)
186#define snap_slot(sn) ((BCReg)((sn) >> 24))
187#define snap_isframe(sn) ((sn) & SNAP_FRAME)
188#define snap_pc(sn) ((const BCIns *)(uintptr_t)(sn))
189#define snap_setref(sn, ref) (((sn) & (0xffff0000&~SNAP_NORESTORE)) | (ref))
190
191/* Snapshot and exit numbers. */
192typedef uint32_t SnapNo;
193typedef uint32_t ExitNo;
194
195/* Trace number. */
196typedef uint32_t TraceNo; /* Used to pass around trace numbers. */
197typedef uint16_t TraceNo1; /* Stored trace number. */
198
199/* Type of link. ORDER LJ_TRLINK */
200typedef enum {
201 LJ_TRLINK_NONE, /* Incomplete trace. No link, yet. */
202 LJ_TRLINK_ROOT, /* Link to other root trace. */
203 LJ_TRLINK_LOOP, /* Loop to same trace. */
204 LJ_TRLINK_TAILREC, /* Tail-recursion. */
205 LJ_TRLINK_UPREC, /* Up-recursion. */
206 LJ_TRLINK_DOWNREC, /* Down-recursion. */
207 LJ_TRLINK_INTERP, /* Fallback to interpreter. */
208 LJ_TRLINK_RETURN /* Return to interpreter. */
209} TraceLink;
210
211/* Trace object. */
212typedef struct GCtrace {
213 GCHeader;
214 uint8_t topslot; /* Top stack slot already checked to be allocated. */
215 uint8_t linktype; /* Type of link. */
216 IRRef nins; /* Next IR instruction. Biased with REF_BIAS. */
217 GCRef gclist;
218 IRIns *ir; /* IR instructions/constants. Biased with REF_BIAS. */
219 IRRef nk; /* Lowest IR constant. Biased with REF_BIAS. */
220 uint16_t nsnap; /* Number of snapshots. */
221 uint16_t nsnapmap; /* Number of snapshot map elements. */
222 SnapShot *snap; /* Snapshot array. */
223 SnapEntry *snapmap; /* Snapshot map. */
224 GCRef startpt; /* Starting prototype. */
225 MRef startpc; /* Bytecode PC of starting instruction. */
226 BCIns startins; /* Original bytecode of starting instruction. */
227 MSize szmcode; /* Size of machine code. */
228 MCode *mcode; /* Start of machine code. */
229 MSize mcloop; /* Offset of loop start in machine code. */
230 uint16_t nchild; /* Number of child traces (root trace only). */
231 uint16_t spadjust; /* Stack pointer adjustment (offset in bytes). */
232 TraceNo1 traceno; /* Trace number. */
233 TraceNo1 link; /* Linked trace (or self for loops). */
234 TraceNo1 root; /* Root trace of side trace (or 0 for root traces). */
235 TraceNo1 nextroot; /* Next root trace for same prototype. */
236 TraceNo1 nextside; /* Next side trace of same root trace. */
237 uint8_t sinktags; /* Trace has SINK tags. */
238 uint8_t unused1;
239#ifdef LUAJIT_USE_GDBJIT
240 void *gdbjit_entry; /* GDB JIT entry. */
241#endif
242} GCtrace;
243
244#define gco2trace(o) check_exp((o)->gch.gct == ~LJ_TTRACE, (GCtrace *)(o))
245#define traceref(J, n) \
246 check_exp((n)>0 && (MSize)(n)<J->sizetrace, (GCtrace *)gcref(J->trace[(n)]))
247
248LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtrace, gclist));
249
250static LJ_AINLINE MSize snap_nextofs(GCtrace *T, SnapShot *snap)
251{
252 if (snap+1 == &T->snap[T->nsnap])
253 return T->nsnapmap;
254 else
255 return (snap+1)->mapofs;
256}
257
258/* Round-robin penalty cache for bytecodes leading to aborted traces. */
259typedef struct HotPenalty {
260 MRef pc; /* Starting bytecode PC. */
261 uint16_t val; /* Penalty value, i.e. hotcount start. */
262 uint16_t reason; /* Abort reason (really TraceErr). */
263} HotPenalty;
264
265#define PENALTY_SLOTS 64 /* Penalty cache slot. Must be a power of 2. */
266#define PENALTY_MIN (36*2) /* Minimum penalty value. */
267#define PENALTY_MAX 60000 /* Maximum penalty value. */
268#define PENALTY_RNDBITS 4 /* # of random bits to add to penalty value. */
269
270/* Round-robin backpropagation cache for narrowing conversions. */
271typedef struct BPropEntry {
272 IRRef1 key; /* Key: original reference. */
273 IRRef1 val; /* Value: reference after conversion. */
274 IRRef mode; /* Mode for this entry (currently IRCONV_*). */
275} BPropEntry;
276
277/* Number of slots for the backpropagation cache. Must be a power of 2. */
278#define BPROP_SLOTS 16
279
280/* Scalar evolution analysis cache. */
281typedef struct ScEvEntry {
282 IRRef1 idx; /* Index reference. */
283 IRRef1 start; /* Constant start reference. */
284 IRRef1 stop; /* Constant stop reference. */
285 IRRef1 step; /* Constant step reference. */
286 IRType1 t; /* Scalar type. */
287 uint8_t dir; /* Direction. 1: +, 0: -. */
288} ScEvEntry;
289
290/* 128 bit SIMD constants. */
291enum {
292 LJ_KSIMD_ABS,
293 LJ_KSIMD_NEG,
294 LJ_KSIMD__MAX
295};
296
297/* Get 16 byte aligned pointer to SIMD constant. */
298#define LJ_KSIMD(J, n) \
299 ((TValue *)(((intptr_t)&J->ksimd[2*(n)] + 15) & ~(intptr_t)15))
300
301/* Set/reset flag to activate the SPLIT pass for the current trace. */
302#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
303#define lj_needsplit(J) (J->needsplit = 1)
304#define lj_resetsplit(J) (J->needsplit = 0)
305#else
306#define lj_needsplit(J) UNUSED(J)
307#define lj_resetsplit(J) UNUSED(J)
308#endif
309
310/* Fold state is used to fold instructions on-the-fly. */
311typedef struct FoldState {
312 IRIns ins; /* Currently emitted instruction. */
313 IRIns left; /* Instruction referenced by left operand. */
314 IRIns right; /* Instruction referenced by right operand. */
315} FoldState;
316
317/* JIT compiler state. */
318typedef struct jit_State {
319 GCtrace cur; /* Current trace. */
320
321 lua_State *L; /* Current Lua state. */
322 const BCIns *pc; /* Current PC. */
323 GCfunc *fn; /* Current function. */
324 GCproto *pt; /* Current prototype. */
325 TRef *base; /* Current frame base, points into J->slots. */
326
327 uint32_t flags; /* JIT engine flags. */
328 BCReg maxslot; /* Relative to baseslot. */
329 BCReg baseslot; /* Current frame base, offset into J->slots. */
330
331 uint8_t mergesnap; /* Allowed to merge with next snapshot. */
332 uint8_t needsnap; /* Need snapshot before recording next bytecode. */
333 IRType1 guardemit; /* Accumulated IRT_GUARD for emitted instructions. */
334 uint8_t bcskip; /* Number of bytecode instructions to skip. */
335
336 FoldState fold; /* Fold state. */
337
338 const BCIns *bc_min; /* Start of allowed bytecode range for root trace. */
339 MSize bc_extent; /* Extent of the range. */
340
341 TraceState state; /* Trace compiler state. */
342
343 int32_t instunroll; /* Unroll counter for instable loops. */
344 int32_t loopunroll; /* Unroll counter for loop ops in side traces. */
345 int32_t tailcalled; /* Number of successive tailcalls. */
346 int32_t framedepth; /* Current frame depth. */
347 int32_t retdepth; /* Return frame depth (count of RETF). */
348
349 MRef k64; /* Pointer to chained array of 64 bit constants. */
350 TValue ksimd[LJ_KSIMD__MAX*2+1]; /* 16 byte aligned SIMD constants. */
351
352 IRIns *irbuf; /* Temp. IR instruction buffer. Biased with REF_BIAS. */
353 IRRef irtoplim; /* Upper limit of instuction buffer (biased). */
354 IRRef irbotlim; /* Lower limit of instuction buffer (biased). */
355 IRRef loopref; /* Last loop reference or ref of final LOOP (or 0). */
356
357 MSize sizesnap; /* Size of temp. snapshot buffer. */
358 SnapShot *snapbuf; /* Temp. snapshot buffer. */
359 SnapEntry *snapmapbuf; /* Temp. snapshot map buffer. */
360 MSize sizesnapmap; /* Size of temp. snapshot map buffer. */
361
362 PostProc postproc; /* Required post-processing after execution. */
363#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
364 int needsplit; /* Need SPLIT pass. */
365#endif
366
367 GCRef *trace; /* Array of traces. */
368 TraceNo freetrace; /* Start of scan for next free trace. */
369 MSize sizetrace; /* Size of trace array. */
370
371 IRRef1 chain[IR__MAX]; /* IR instruction skip-list chain anchors. */
372 TRef slot[LJ_MAX_JSLOTS+LJ_STACK_EXTRA]; /* Stack slot map. */
373
374 int32_t param[JIT_P__MAX]; /* JIT engine parameters. */
375
376 MCode *exitstubgroup[LJ_MAX_EXITSTUBGR]; /* Exit stub group addresses. */
377
378 HotPenalty penalty[PENALTY_SLOTS]; /* Penalty slots. */
379 uint32_t penaltyslot; /* Round-robin index into penalty slots. */
380 uint32_t prngstate; /* PRNG state. */
381
382 BPropEntry bpropcache[BPROP_SLOTS]; /* Backpropagation cache slots. */
383 uint32_t bpropslot; /* Round-robin index into bpropcache slots. */
384
385 ScEvEntry scev; /* Scalar evolution analysis cache slots. */
386
387 const BCIns *startpc; /* Bytecode PC of starting instruction. */
388 TraceNo parent; /* Parent of current side trace (0 for root traces). */
389 ExitNo exitno; /* Exit number in parent of current side trace. */
390
391 BCIns *patchpc; /* PC for pending re-patch. */
392 BCIns patchins; /* Instruction for pending re-patch. */
393
394 int mcprot; /* Protection of current mcode area. */
395 MCode *mcarea; /* Base of current mcode area. */
396 MCode *mctop; /* Top of current mcode area. */
397 MCode *mcbot; /* Bottom of current mcode area. */
398 size_t szmcarea; /* Size of current mcode area. */
399 size_t szallmcarea; /* Total size of all allocated mcode areas. */
400
401 TValue errinfo; /* Additional info element for trace errors. */
402}
403#if LJ_TARGET_ARM
404LJ_ALIGN(16) /* For DISPATCH-relative addresses in assembler part. */
405#endif
406jit_State;
407
408/* Trivial PRNG e.g. used for penalty randomization. */
409static LJ_AINLINE uint32_t LJ_PRNG_BITS(jit_State *J, int bits)
410{
411 /* Yes, this LCG is very weak, but that doesn't matter for our use case. */
412 J->prngstate = J->prngstate * 1103515245 + 12345;
413 return J->prngstate >> (32-bits);
414}
415
416#endif
417