Merge branch 'master' into v2.1
[luajit-2.0.git] / src / lj_obj.h
blobdaa62e340f21b91774f4a7d326a161742bb0800e
1 /*
2 ** LuaJIT VM tags, values and objects.
3 ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4 **
5 ** Portions taken verbatim or adapted from the Lua interpreter.
6 ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
7 */
9 #ifndef _LJ_OBJ_H
10 #define _LJ_OBJ_H
12 #include "lua.h"
13 #include "lj_def.h"
14 #include "lj_arch.h"
16 /* -- Memory references (32 bit address space) ---------------------------- */
18 /* Memory size. */
19 typedef uint32_t MSize;
21 /* Memory reference */
22 typedef struct MRef {
23 uint32_t ptr32; /* Pseudo 32 bit pointer. */
24 } MRef;
26 #define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32)
28 #define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p))
29 #define setmrefr(r, v) ((r).ptr32 = (v).ptr32)
31 /* -- GC object references (32 bit address space) ------------------------- */
33 /* GCobj reference */
34 typedef struct GCRef {
35 uint32_t gcptr32; /* Pseudo 32 bit pointer. */
36 } GCRef;
38 /* Common GC header for all collectable objects. */
39 #define GCHeader GCRef nextgc; uint8_t marked; uint8_t gct
40 /* This occupies 6 bytes, so use the next 2 bytes for non-32 bit fields. */
42 #define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32)
43 #define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32)
44 #define gcrefu(r) ((r).gcptr32)
45 #define gcrefi(r) ((int32_t)(r).gcptr32)
46 #define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32)
47 #define gcnext(gc) (gcref((gc)->gch.nextgc))
49 #define setgcref(r, gc) ((r).gcptr32 = (uint32_t)(uintptr_t)&(gc)->gch)
50 #define setgcrefi(r, i) ((r).gcptr32 = (uint32_t)(i))
51 #define setgcrefp(r, p) ((r).gcptr32 = (uint32_t)(uintptr_t)(p))
52 #define setgcrefnull(r) ((r).gcptr32 = 0)
53 #define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32)
55 /* IMPORTANT NOTE:
57 ** All uses of the setgcref* macros MUST be accompanied with a write barrier.
59 ** This is to ensure the integrity of the incremental GC. The invariant
60 ** to preserve is that a black object never points to a white object.
61 ** I.e. never store a white object into a field of a black object.
63 ** It's ok to LEAVE OUT the write barrier ONLY in the following cases:
64 ** - The source is not a GC object (NULL).
65 ** - The target is a GC root. I.e. everything in global_State.
66 ** - The target is a lua_State field (threads are never black).
67 ** - The target is a stack slot, see setgcV et al.
68 ** - The target is an open upvalue, i.e. pointing to a stack slot.
69 ** - The target is a newly created object (i.e. marked white). But make
70 ** sure nothing invokes the GC inbetween.
71 ** - The target and the source are the same object (self-reference).
72 ** - The target already contains the object (e.g. moving elements around).
74 ** The most common case is a store to a stack slot. All other cases where
75 ** a barrier has been omitted are annotated with a NOBARRIER comment.
77 ** The same logic applies for stores to table slots (array part or hash
78 ** part). ALL uses of lj_tab_set* require a barrier for the stored value
79 ** *and* the stored key, based on the above rules. In practice this means
80 ** a barrier is needed if *either* of the key or value are a GC object.
82 ** It's ok to LEAVE OUT the write barrier in the following special cases:
83 ** - The stored value is nil. The key doesn't matter because it's either
84 ** not resurrected or lj_tab_newkey() will take care of the key barrier.
85 ** - The key doesn't matter if the *previously* stored value is guaranteed
86 ** to be non-nil (because the key is kept alive in the table).
87 ** - The key doesn't matter if it's guaranteed not to be part of the table,
88 ** since lj_tab_newkey() takes care of the key barrier. This applies
89 ** trivially to new tables, but watch out for resurrected keys. Storing
90 ** a nil value leaves the key in the table!
92 ** In case of doubt use lj_gc_anybarriert() as it's rather cheap. It's used
93 ** by the interpreter for all table stores.
95 ** Note: In contrast to Lua's GC, LuaJIT's GC does *not* specially mark
96 ** dead keys in tables. The reference is left in, but it's guaranteed to
97 ** be never dereferenced as long as the value is nil. It's ok if the key is
98 ** freed or if any object subsequently gets the same address.
100 ** Not destroying dead keys helps to keep key hash slots stable. This avoids
101 ** specialization back-off for HREFK when a value flips between nil and
102 ** non-nil and the GC gets in the way. It also allows safely hoisting
103 ** HREF/HREFK across GC steps. Dead keys are only removed if a table is
104 ** resized (i.e. by NEWREF) and xREF must not be CSEd across a resize.
106 ** The trade-off is that a write barrier for tables must take the key into
107 ** account, too. Implicitly resurrecting the key by storing a non-nil value
108 ** may invalidate the incremental GC invariant.
111 /* -- Common type definitions --------------------------------------------- */
113 /* Types for handling bytecodes. Need this here, details in lj_bc.h. */
114 typedef uint32_t BCIns; /* Bytecode instruction. */
115 typedef uint32_t BCPos; /* Bytecode position. */
116 typedef uint32_t BCReg; /* Bytecode register. */
117 typedef int32_t BCLine; /* Bytecode line number. */
119 /* Internal assembler functions. Never call these directly from C. */
120 typedef void (*ASMFunction)(void);
122 /* Resizable string buffer. Need this here, details in lj_buf.h. */
123 typedef struct SBuf {
124 MRef p; /* String buffer pointer. */
125 MRef e; /* String buffer end pointer. */
126 MRef b; /* String buffer base. */
127 MRef L; /* lua_State, used for buffer resizing. */
128 } SBuf;
130 /* -- Tags and values ----------------------------------------------------- */
132 /* Frame link. */
133 typedef union {
134 int32_t ftsz; /* Frame type and size of previous frame. */
135 MRef pcr; /* Overlaps PC for Lua frames. */
136 } FrameLink;
138 /* Tagged value. */
139 typedef LJ_ALIGN(8) union TValue {
140 uint64_t u64; /* 64 bit pattern overlaps number. */
141 lua_Number n; /* Number object overlaps split tag/value object. */
142 struct {
143 LJ_ENDIAN_LOHI(
144 union {
145 GCRef gcr; /* GCobj reference (if any). */
146 int32_t i; /* Integer value. */
148 , uint32_t it; /* Internal object tag. Must overlap MSW of number. */
151 struct {
152 LJ_ENDIAN_LOHI(
153 GCRef func; /* Function for next frame (or dummy L). */
154 , FrameLink tp; /* Link to previous frame. */
156 } fr;
157 struct {
158 LJ_ENDIAN_LOHI(
159 uint32_t lo; /* Lower 32 bits of number. */
160 , uint32_t hi; /* Upper 32 bits of number. */
162 } u32;
163 } TValue;
165 typedef const TValue cTValue;
167 #define tvref(r) (mref(r, TValue))
169 /* More external and GCobj tags for internal objects. */
170 #define LAST_TT LUA_TTHREAD
171 #define LUA_TPROTO (LAST_TT+1)
172 #define LUA_TCDATA (LAST_TT+2)
174 /* Internal object tags.
176 ** Internal tags overlap the MSW of a number object (must be a double).
177 ** Interpreted as a double these are special NaNs. The FPU only generates
178 ** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available
179 ** for use as internal tags. Small negative numbers are used to shorten the
180 ** encoding of type comparisons (reg/mem against sign-ext. 8 bit immediate).
182 ** ---MSW---.---LSW---
183 ** primitive types | itype | |
184 ** lightuserdata | itype | void * | (32 bit platforms)
185 ** lightuserdata |ffff| void * | (64 bit platforms, 47 bit pointers)
186 ** GC objects | itype | GCRef |
187 ** int (LJ_DUALNUM)| itype | int |
188 ** number -------double------
190 ** ORDER LJ_T
191 ** Primitive types nil/false/true must be first, lightuserdata next.
192 ** GC objects are at the end, table/userdata must be lowest.
193 ** Also check lj_ir.h for similar ordering constraints.
195 #define LJ_TNIL (~0u)
196 #define LJ_TFALSE (~1u)
197 #define LJ_TTRUE (~2u)
198 #define LJ_TLIGHTUD (~3u)
199 #define LJ_TSTR (~4u)
200 #define LJ_TUPVAL (~5u)
201 #define LJ_TTHREAD (~6u)
202 #define LJ_TPROTO (~7u)
203 #define LJ_TFUNC (~8u)
204 #define LJ_TTRACE (~9u)
205 #define LJ_TCDATA (~10u)
206 #define LJ_TTAB (~11u)
207 #define LJ_TUDATA (~12u)
208 /* This is just the canonical number type used in some places. */
209 #define LJ_TNUMX (~13u)
211 /* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */
212 #if LJ_64
213 #define LJ_TISNUM 0xfffeffffu
214 #else
215 #define LJ_TISNUM LJ_TNUMX
216 #endif
217 #define LJ_TISTRUECOND LJ_TFALSE
218 #define LJ_TISPRI LJ_TTRUE
219 #define LJ_TISGCV (LJ_TSTR+1)
220 #define LJ_TISTABUD LJ_TTAB
222 /* -- String object ------------------------------------------------------- */
224 /* String object header. String payload follows. */
225 typedef struct GCstr {
226 GCHeader;
227 uint8_t reserved; /* Used by lexer for fast lookup of reserved words. */
228 uint8_t unused;
229 MSize hash; /* Hash of string. */
230 MSize len; /* Size of string. */
231 } GCstr;
233 #define strref(r) (&gcref((r))->str)
234 #define strdata(s) ((const char *)((s)+1))
235 #define strdatawr(s) ((char *)((s)+1))
236 #define strVdata(o) strdata(strV(o))
237 #define sizestring(s) (sizeof(struct GCstr)+(s)->len+1)
239 /* -- Userdata object ----------------------------------------------------- */
241 /* Userdata object. Payload follows. */
242 typedef struct GCudata {
243 GCHeader;
244 uint8_t udtype; /* Userdata type. */
245 uint8_t unused2;
246 GCRef env; /* Should be at same offset in GCfunc. */
247 MSize len; /* Size of payload. */
248 GCRef metatable; /* Must be at same offset in GCtab. */
249 uint32_t align1; /* To force 8 byte alignment of the payload. */
250 } GCudata;
252 /* Userdata types. */
253 enum {
254 UDTYPE_USERDATA, /* Regular userdata. */
255 UDTYPE_IO_FILE, /* I/O library FILE. */
256 UDTYPE_FFI_CLIB, /* FFI C library namespace. */
257 UDTYPE__MAX
260 #define uddata(u) ((void *)((u)+1))
261 #define sizeudata(u) (sizeof(struct GCudata)+(u)->len)
263 /* -- C data object ------------------------------------------------------- */
265 /* C data object. Payload follows. */
266 typedef struct GCcdata {
267 GCHeader;
268 uint16_t ctypeid; /* C type ID. */
269 } GCcdata;
271 /* Prepended to variable-sized or realigned C data objects. */
272 typedef struct GCcdataVar {
273 uint16_t offset; /* Offset to allocated memory (relative to GCcdata). */
274 uint16_t extra; /* Extra space allocated (incl. GCcdata + GCcdatav). */
275 MSize len; /* Size of payload. */
276 } GCcdataVar;
278 #define cdataptr(cd) ((void *)((cd)+1))
279 #define cdataisv(cd) ((cd)->marked & 0x80)
280 #define cdatav(cd) ((GCcdataVar *)((char *)(cd) - sizeof(GCcdataVar)))
281 #define cdatavlen(cd) check_exp(cdataisv(cd), cdatav(cd)->len)
282 #define sizecdatav(cd) (cdatavlen(cd) + cdatav(cd)->extra)
283 #define memcdatav(cd) ((void *)((char *)(cd) - cdatav(cd)->offset))
285 /* -- Prototype object ---------------------------------------------------- */
287 #define SCALE_NUM_GCO ((int32_t)sizeof(lua_Number)/sizeof(GCRef))
288 #define round_nkgc(n) (((n) + SCALE_NUM_GCO-1) & ~(SCALE_NUM_GCO-1))
290 typedef struct GCproto {
291 GCHeader;
292 uint8_t numparams; /* Number of parameters. */
293 uint8_t framesize; /* Fixed frame size. */
294 MSize sizebc; /* Number of bytecode instructions. */
295 GCRef gclist;
296 MRef k; /* Split constant array (points to the middle). */
297 MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */
298 MSize sizekgc; /* Number of collectable constants. */
299 MSize sizekn; /* Number of lua_Number constants. */
300 MSize sizept; /* Total size including colocated arrays. */
301 uint8_t sizeuv; /* Number of upvalues. */
302 uint8_t flags; /* Miscellaneous flags (see below). */
303 uint16_t trace; /* Anchor for chain of root traces. */
304 /* ------ The following fields are for debugging/tracebacks only ------ */
305 GCRef chunkname; /* Name of the chunk this function was defined in. */
306 BCLine firstline; /* First line of the function definition. */
307 BCLine numline; /* Number of lines for the function definition. */
308 MRef lineinfo; /* Compressed map from bytecode ins. to source line. */
309 MRef uvinfo; /* Upvalue names. */
310 MRef varinfo; /* Names and compressed extents of local variables. */
311 } GCproto;
313 /* Flags for prototype. */
314 #define PROTO_CHILD 0x01 /* Has child prototypes. */
315 #define PROTO_VARARG 0x02 /* Vararg function. */
316 #define PROTO_FFI 0x04 /* Uses BC_KCDATA for FFI datatypes. */
317 #define PROTO_NOJIT 0x08 /* JIT disabled for this function. */
318 #define PROTO_ILOOP 0x10 /* Patched bytecode with ILOOP etc. */
319 /* Only used during parsing. */
320 #define PROTO_HAS_RETURN 0x20 /* Already emitted a return. */
321 #define PROTO_FIXUP_RETURN 0x40 /* Need to fixup emitted returns. */
322 /* Top bits used for counting created closures. */
323 #define PROTO_CLCOUNT 0x20 /* Base of saturating 3 bit counter. */
324 #define PROTO_CLC_BITS 3
325 #define PROTO_CLC_POLY (3*PROTO_CLCOUNT) /* Polymorphic threshold. */
327 #define PROTO_UV_LOCAL 0x8000 /* Upvalue for local slot. */
328 #define PROTO_UV_IMMUTABLE 0x4000 /* Immutable upvalue. */
330 #define proto_kgc(pt, idx) \
331 check_exp((uintptr_t)(intptr_t)(idx) >= (uintptr_t)-(intptr_t)(pt)->sizekgc, \
332 gcref(mref((pt)->k, GCRef)[(idx)]))
333 #define proto_knumtv(pt, idx) \
334 check_exp((uintptr_t)(idx) < (pt)->sizekn, &mref((pt)->k, TValue)[(idx)])
335 #define proto_bc(pt) ((BCIns *)((char *)(pt) + sizeof(GCproto)))
336 #define proto_bcpos(pt, pc) ((BCPos)((pc) - proto_bc(pt)))
337 #define proto_uv(pt) (mref((pt)->uv, uint16_t))
339 #define proto_chunkname(pt) (strref((pt)->chunkname))
340 #define proto_chunknamestr(pt) (strdata(proto_chunkname((pt))))
341 #define proto_lineinfo(pt) (mref((pt)->lineinfo, const void))
342 #define proto_uvinfo(pt) (mref((pt)->uvinfo, const uint8_t))
343 #define proto_varinfo(pt) (mref((pt)->varinfo, const uint8_t))
345 /* -- Upvalue object ------------------------------------------------------ */
347 typedef struct GCupval {
348 GCHeader;
349 uint8_t closed; /* Set if closed (i.e. uv->v == &uv->u.value). */
350 uint8_t immutable; /* Immutable value. */
351 union {
352 TValue tv; /* If closed: the value itself. */
353 struct { /* If open: double linked list, anchored at thread. */
354 GCRef prev;
355 GCRef next;
358 MRef v; /* Points to stack slot (open) or above (closed). */
359 uint32_t dhash; /* Disambiguation hash: dh1 != dh2 => cannot alias. */
360 } GCupval;
362 #define uvprev(uv_) (&gcref((uv_)->prev)->uv)
363 #define uvnext(uv_) (&gcref((uv_)->next)->uv)
364 #define uvval(uv_) (mref((uv_)->v, TValue))
366 /* -- Function object (closures) ------------------------------------------ */
368 /* Common header for functions. env should be at same offset in GCudata. */
369 #define GCfuncHeader \
370 GCHeader; uint8_t ffid; uint8_t nupvalues; \
371 GCRef env; GCRef gclist; MRef pc
373 typedef struct GCfuncC {
374 GCfuncHeader;
375 lua_CFunction f; /* C function to be called. */
376 TValue upvalue[1]; /* Array of upvalues (TValue). */
377 } GCfuncC;
379 typedef struct GCfuncL {
380 GCfuncHeader;
381 GCRef uvptr[1]; /* Array of _pointers_ to upvalue objects (GCupval). */
382 } GCfuncL;
384 typedef union GCfunc {
385 GCfuncC c;
386 GCfuncL l;
387 } GCfunc;
389 #define FF_LUA 0
390 #define FF_C 1
391 #define isluafunc(fn) ((fn)->c.ffid == FF_LUA)
392 #define iscfunc(fn) ((fn)->c.ffid == FF_C)
393 #define isffunc(fn) ((fn)->c.ffid > FF_C)
394 #define funcproto(fn) \
395 check_exp(isluafunc(fn), (GCproto *)(mref((fn)->l.pc, char)-sizeof(GCproto)))
396 #define sizeCfunc(n) (sizeof(GCfuncC)-sizeof(TValue)+sizeof(TValue)*(n))
397 #define sizeLfunc(n) (sizeof(GCfuncL)-sizeof(GCRef)+sizeof(GCRef)*(n))
399 /* -- Table object -------------------------------------------------------- */
401 /* Hash node. */
402 typedef struct Node {
403 TValue val; /* Value object. Must be first field. */
404 TValue key; /* Key object. */
405 MRef next; /* Hash chain. */
406 MRef freetop; /* Top of free elements (stored in t->node[0]). */
407 } Node;
409 LJ_STATIC_ASSERT(offsetof(Node, val) == 0);
411 typedef struct GCtab {
412 GCHeader;
413 uint8_t nomm; /* Negative cache for fast metamethods. */
414 int8_t colo; /* Array colocation. */
415 MRef array; /* Array part. */
416 GCRef gclist;
417 GCRef metatable; /* Must be at same offset in GCudata. */
418 MRef node; /* Hash part. */
419 uint32_t asize; /* Size of array part (keys [0, asize-1]). */
420 uint32_t hmask; /* Hash part mask (size of hash part - 1). */
421 } GCtab;
423 #define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab))
424 #define tabref(r) (&gcref((r))->tab)
425 #define noderef(r) (mref((r), Node))
426 #define nextnode(n) (mref((n)->next, Node))
428 /* -- State objects ------------------------------------------------------- */
430 /* VM states. */
431 enum {
432 LJ_VMST_INTERP, /* Interpreter. */
433 LJ_VMST_C, /* C function. */
434 LJ_VMST_GC, /* Garbage collector. */
435 LJ_VMST_EXIT, /* Trace exit handler. */
436 LJ_VMST_RECORD, /* Trace recorder. */
437 LJ_VMST_OPT, /* Optimizer. */
438 LJ_VMST_ASM, /* Assembler. */
439 LJ_VMST__MAX
442 #define setvmstate(g, st) ((g)->vmstate = ~LJ_VMST_##st)
444 /* Metamethods. ORDER MM */
445 #ifdef LJ_HASFFI
446 #define MMDEF_FFI(_) _(new)
447 #else
448 #define MMDEF_FFI(_)
449 #endif
451 #if LJ_52 || LJ_HASFFI
452 #define MMDEF_PAIRS(_) _(pairs) _(ipairs)
453 #else
454 #define MMDEF_PAIRS(_)
455 #define MM_pairs 255
456 #define MM_ipairs 255
457 #endif
459 #define MMDEF(_) \
460 _(index) _(newindex) _(gc) _(mode) _(eq) _(len) \
461 /* Only the above (fast) metamethods are negative cached (max. 8). */ \
462 _(lt) _(le) _(concat) _(call) \
463 /* The following must be in ORDER ARITH. */ \
464 _(add) _(sub) _(mul) _(div) _(mod) _(pow) _(unm) \
465 /* The following are used in the standard libraries. */ \
466 _(metatable) _(tostring) MMDEF_FFI(_) MMDEF_PAIRS(_)
468 typedef enum {
469 #define MMENUM(name) MM_##name,
470 MMDEF(MMENUM)
471 #undef MMENUM
472 MM__MAX,
473 MM____ = MM__MAX,
474 MM_FAST = MM_len
475 } MMS;
477 /* GC root IDs. */
478 typedef enum {
479 GCROOT_MMNAME, /* Metamethod names. */
480 GCROOT_MMNAME_LAST = GCROOT_MMNAME + MM__MAX-1,
481 GCROOT_BASEMT, /* Metatables for base types. */
482 GCROOT_BASEMT_NUM = GCROOT_BASEMT + ~LJ_TNUMX,
483 GCROOT_IO_INPUT, /* Userdata for default I/O input file. */
484 GCROOT_IO_OUTPUT, /* Userdata for default I/O output file. */
485 GCROOT_MAX
486 } GCRootID;
488 #define basemt_it(g, it) ((g)->gcroot[GCROOT_BASEMT+~(it)])
489 #define basemt_obj(g, o) ((g)->gcroot[GCROOT_BASEMT+itypemap(o)])
490 #define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)]))
492 typedef struct GCState {
493 MSize total; /* Memory currently allocated. */
494 MSize threshold; /* Memory threshold. */
495 uint8_t currentwhite; /* Current white color. */
496 uint8_t state; /* GC state. */
497 uint8_t nocdatafin; /* No cdata finalizer called. */
498 uint8_t unused2;
499 MSize sweepstr; /* Sweep position in string table. */
500 GCRef root; /* List of all collectable objects. */
501 MRef sweep; /* Sweep position in root list. */
502 GCRef gray; /* List of gray objects. */
503 GCRef grayagain; /* List of objects for atomic traversal. */
504 GCRef weak; /* List of weak tables (to be cleared). */
505 GCRef mmudata; /* List of userdata (to be finalized). */
506 MSize stepmul; /* Incremental GC step granularity. */
507 MSize debt; /* Debt (how much GC is behind schedule). */
508 MSize estimate; /* Estimate of memory actually in use. */
509 MSize pause; /* Pause between successive GC cycles. */
510 } GCState;
512 /* Global state, shared by all threads of a Lua universe. */
513 typedef struct global_State {
514 GCRef *strhash; /* String hash table (hash chain anchors). */
515 MSize strmask; /* String hash mask (size of hash table - 1). */
516 MSize strnum; /* Number of strings in hash table. */
517 lua_Alloc allocf; /* Memory allocator. */
518 void *allocd; /* Memory allocator data. */
519 GCState gc; /* Garbage collector. */
520 volatile int32_t vmstate; /* VM state or current JIT code trace number. */
521 SBuf tmpbuf; /* Temporary string buffer. */
522 GCstr strempty; /* Empty string. */
523 uint8_t stremptyz; /* Zero terminator of empty string. */
524 uint8_t hookmask; /* Hook mask. */
525 uint8_t dispatchmode; /* Dispatch mode. */
526 uint8_t vmevmask; /* VM event mask. */
527 GCRef mainthref; /* Link to main thread. */
528 TValue registrytv; /* Anchor for registry. */
529 TValue tmptv, tmptv2; /* Temporary TValues. */
530 Node nilnode; /* Fallback 1-element hash part (nil key and value). */
531 GCupval uvhead; /* Head of double-linked list of all open upvalues. */
532 int32_t hookcount; /* Instruction hook countdown. */
533 int32_t hookcstart; /* Start count for instruction hook counter. */
534 lua_Hook hookf; /* Hook function. */
535 lua_CFunction wrapf; /* Wrapper for C function calls. */
536 lua_CFunction panic; /* Called as a last resort for errors. */
537 BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */
538 BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */
539 GCRef cur_L; /* Currently executing lua_State. */
540 MRef jit_base; /* Current JIT code L->base or NULL. */
541 MRef ctype_state; /* Pointer to C type state. */
542 GCRef gcroot[GCROOT_MAX]; /* GC roots. */
543 } global_State;
545 #define mainthread(g) (&gcref(g->mainthref)->th)
546 #define niltv(L) \
547 check_exp(tvisnil(&G(L)->nilnode.val), &G(L)->nilnode.val)
548 #define niltvg(g) \
549 check_exp(tvisnil(&(g)->nilnode.val), &(g)->nilnode.val)
551 /* Hook management. Hook event masks are defined in lua.h. */
552 #define HOOK_EVENTMASK 0x0f
553 #define HOOK_ACTIVE 0x10
554 #define HOOK_ACTIVE_SHIFT 4
555 #define HOOK_VMEVENT 0x20
556 #define HOOK_GC 0x40
557 #define HOOK_PROFILE 0x80
558 #define hook_active(g) ((g)->hookmask & HOOK_ACTIVE)
559 #define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE)
560 #define hook_entergc(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_GC))
561 #define hook_vmevent(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_VMEVENT))
562 #define hook_leave(g) ((g)->hookmask &= ~HOOK_ACTIVE)
563 #define hook_save(g) ((g)->hookmask & ~HOOK_EVENTMASK)
564 #define hook_restore(g, h) \
565 ((g)->hookmask = ((g)->hookmask & HOOK_EVENTMASK) | (h))
567 /* Per-thread state object. */
568 struct lua_State {
569 GCHeader;
570 uint8_t dummy_ffid; /* Fake FF_C for curr_funcisL() on dummy frames. */
571 uint8_t status; /* Thread status. */
572 MRef glref; /* Link to global state. */
573 GCRef gclist; /* GC chain. */
574 TValue *base; /* Base of currently executing function. */
575 TValue *top; /* First free slot in the stack. */
576 MRef maxstack; /* Last free slot in the stack. */
577 MRef stack; /* Stack base. */
578 GCRef openupval; /* List of open upvalues in the stack. */
579 GCRef env; /* Thread environment (table of globals). */
580 void *cframe; /* End of C stack frame chain. */
581 MSize stacksize; /* True stack size (incl. LJ_STACK_EXTRA). */
584 #define G(L) (mref(L->glref, global_State))
585 #define registry(L) (&G(L)->registrytv)
587 /* Macros to access the currently executing (Lua) function. */
588 #define curr_func(L) (&gcref((L->base-1)->fr.func)->fn)
589 #define curr_funcisL(L) (isluafunc(curr_func(L)))
590 #define curr_proto(L) (funcproto(curr_func(L)))
591 #define curr_topL(L) (L->base + curr_proto(L)->framesize)
592 #define curr_top(L) (curr_funcisL(L) ? curr_topL(L) : L->top)
594 /* -- GC object definition and conversions -------------------------------- */
596 /* GC header for generic access to common fields of GC objects. */
597 typedef struct GChead {
598 GCHeader;
599 uint8_t unused1;
600 uint8_t unused2;
601 GCRef env;
602 GCRef gclist;
603 GCRef metatable;
604 } GChead;
606 /* The env field SHOULD be at the same offset for all GC objects. */
607 LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCfuncL, env));
608 LJ_STATIC_ASSERT(offsetof(GChead, env) == offsetof(GCudata, env));
610 /* The metatable field MUST be at the same offset for all GC objects. */
611 LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCtab, metatable));
612 LJ_STATIC_ASSERT(offsetof(GChead, metatable) == offsetof(GCudata, metatable));
614 /* The gclist field MUST be at the same offset for all GC objects. */
615 LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(lua_State, gclist));
616 LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCproto, gclist));
617 LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCfuncL, gclist));
618 LJ_STATIC_ASSERT(offsetof(GChead, gclist) == offsetof(GCtab, gclist));
620 typedef union GCobj {
621 GChead gch;
622 GCstr str;
623 GCupval uv;
624 lua_State th;
625 GCproto pt;
626 GCfunc fn;
627 GCcdata cd;
628 GCtab tab;
629 GCudata ud;
630 } GCobj;
632 /* Macros to convert a GCobj pointer into a specific value. */
633 #define gco2str(o) check_exp((o)->gch.gct == ~LJ_TSTR, &(o)->str)
634 #define gco2uv(o) check_exp((o)->gch.gct == ~LJ_TUPVAL, &(o)->uv)
635 #define gco2th(o) check_exp((o)->gch.gct == ~LJ_TTHREAD, &(o)->th)
636 #define gco2pt(o) check_exp((o)->gch.gct == ~LJ_TPROTO, &(o)->pt)
637 #define gco2func(o) check_exp((o)->gch.gct == ~LJ_TFUNC, &(o)->fn)
638 #define gco2cd(o) check_exp((o)->gch.gct == ~LJ_TCDATA, &(o)->cd)
639 #define gco2tab(o) check_exp((o)->gch.gct == ~LJ_TTAB, &(o)->tab)
640 #define gco2ud(o) check_exp((o)->gch.gct == ~LJ_TUDATA, &(o)->ud)
642 /* Macro to convert any collectable object into a GCobj pointer. */
643 #define obj2gco(v) ((GCobj *)(v))
645 /* -- TValue getters/setters ---------------------------------------------- */
647 #ifdef LUA_USE_ASSERT
648 #include "lj_gc.h"
649 #endif
651 /* Macros to test types. */
652 #define itype(o) ((o)->it)
653 #define tvisnil(o) (itype(o) == LJ_TNIL)
654 #define tvisfalse(o) (itype(o) == LJ_TFALSE)
655 #define tvistrue(o) (itype(o) == LJ_TTRUE)
656 #define tvisbool(o) (tvisfalse(o) || tvistrue(o))
657 #if LJ_64
658 #define tvislightud(o) (((int32_t)itype(o) >> 15) == -2)
659 #else
660 #define tvislightud(o) (itype(o) == LJ_TLIGHTUD)
661 #endif
662 #define tvisstr(o) (itype(o) == LJ_TSTR)
663 #define tvisfunc(o) (itype(o) == LJ_TFUNC)
664 #define tvisthread(o) (itype(o) == LJ_TTHREAD)
665 #define tvisproto(o) (itype(o) == LJ_TPROTO)
666 #define tviscdata(o) (itype(o) == LJ_TCDATA)
667 #define tvistab(o) (itype(o) == LJ_TTAB)
668 #define tvisudata(o) (itype(o) == LJ_TUDATA)
669 #define tvisnumber(o) (itype(o) <= LJ_TISNUM)
670 #define tvisint(o) (LJ_DUALNUM && itype(o) == LJ_TISNUM)
671 #define tvisnum(o) (itype(o) < LJ_TISNUM)
673 #define tvistruecond(o) (itype(o) < LJ_TISTRUECOND)
674 #define tvispri(o) (itype(o) >= LJ_TISPRI)
675 #define tvistabud(o) (itype(o) <= LJ_TISTABUD) /* && !tvisnum() */
676 #define tvisgcv(o) ((itype(o) - LJ_TISGCV) > (LJ_TNUMX - LJ_TISGCV))
678 /* Special macros to test numbers for NaN, +0, -0, +1 and raw equality. */
679 #define tvisnan(o) ((o)->n != (o)->n)
680 #if LJ_64
681 #define tviszero(o) (((o)->u64 << 1) == 0)
682 #else
683 #define tviszero(o) (((o)->u32.lo | ((o)->u32.hi << 1)) == 0)
684 #endif
685 #define tvispzero(o) ((o)->u64 == 0)
686 #define tvismzero(o) ((o)->u64 == U64x(80000000,00000000))
687 #define tvispone(o) ((o)->u64 == U64x(3ff00000,00000000))
688 #define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64)
690 /* Macros to convert type ids. */
691 #if LJ_64
692 #define itypemap(o) \
693 (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o))
694 #else
695 #define itypemap(o) (tvisnumber(o) ? ~LJ_TNUMX : ~itype(o))
696 #endif
698 /* Macros to get tagged values. */
699 #define gcval(o) (gcref((o)->gcr))
700 #define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - (o)->it))
701 #if LJ_64
702 #define lightudV(o) \
703 check_exp(tvislightud(o), (void *)((o)->u64 & U64x(00007fff,ffffffff)))
704 #else
705 #define lightudV(o) check_exp(tvislightud(o), gcrefp((o)->gcr, void))
706 #endif
707 #define gcV(o) check_exp(tvisgcv(o), gcval(o))
708 #define strV(o) check_exp(tvisstr(o), &gcval(o)->str)
709 #define funcV(o) check_exp(tvisfunc(o), &gcval(o)->fn)
710 #define threadV(o) check_exp(tvisthread(o), &gcval(o)->th)
711 #define protoV(o) check_exp(tvisproto(o), &gcval(o)->pt)
712 #define cdataV(o) check_exp(tviscdata(o), &gcval(o)->cd)
713 #define tabV(o) check_exp(tvistab(o), &gcval(o)->tab)
714 #define udataV(o) check_exp(tvisudata(o), &gcval(o)->ud)
715 #define numV(o) check_exp(tvisnum(o), (o)->n)
716 #define intV(o) check_exp(tvisint(o), (int32_t)(o)->i)
718 /* Macros to set tagged values. */
719 #define setitype(o, i) ((o)->it = (i))
720 #define setnilV(o) ((o)->it = LJ_TNIL)
721 #define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x))
723 static LJ_AINLINE void setlightudV(TValue *o, void *p)
725 #if LJ_64
726 o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48);
727 #else
728 setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD);
729 #endif
732 #if LJ_64
733 #define checklightudptr(L, p) \
734 (((uint64_t)(p) >> 47) ? (lj_err_msg(L, LJ_ERR_BADLU), NULL) : (p))
735 #define setcont(o, f) \
736 ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin)
737 #else
738 #define checklightudptr(L, p) (p)
739 #define setcont(o, f) setlightudV((o), (void *)(f))
740 #endif
742 #define tvchecklive(L, o) \
743 UNUSED(L), lua_assert(!tvisgcv(o) || \
744 ((~itype(o) == gcval(o)->gch.gct) && !isdead(G(L), gcval(o))))
746 static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t itype)
748 setgcref(o->gcr, v); setitype(o, itype); tvchecklive(L, o);
751 #define define_setV(name, type, tag) \
752 static LJ_AINLINE void name(lua_State *L, TValue *o, type *v) \
754 setgcV(L, o, obj2gco(v), tag); \
756 define_setV(setstrV, GCstr, LJ_TSTR)
757 define_setV(setthreadV, lua_State, LJ_TTHREAD)
758 define_setV(setprotoV, GCproto, LJ_TPROTO)
759 define_setV(setfuncV, GCfunc, LJ_TFUNC)
760 define_setV(setcdataV, GCcdata, LJ_TCDATA)
761 define_setV(settabV, GCtab, LJ_TTAB)
762 define_setV(setudataV, GCudata, LJ_TUDATA)
764 #define setnumV(o, x) ((o)->n = (x))
765 #define setnanV(o) ((o)->u64 = U64x(fff80000,00000000))
766 #define setpinfV(o) ((o)->u64 = U64x(7ff00000,00000000))
767 #define setminfV(o) ((o)->u64 = U64x(fff00000,00000000))
769 static LJ_AINLINE void setintV(TValue *o, int32_t i)
771 #if LJ_DUALNUM
772 o->i = (uint32_t)i; setitype(o, LJ_TISNUM);
773 #else
774 o->n = (lua_Number)i;
775 #endif
778 static LJ_AINLINE void setint64V(TValue *o, int64_t i)
780 if (LJ_DUALNUM && LJ_LIKELY(i == (int64_t)(int32_t)i))
781 setintV(o, (int32_t)i);
782 else
783 setnumV(o, (lua_Number)i);
786 #if LJ_64
787 #define setintptrV(o, i) setint64V((o), (i))
788 #else
789 #define setintptrV(o, i) setintV((o), (i))
790 #endif
792 /* Copy tagged values. */
793 static LJ_AINLINE void copyTV(lua_State *L, TValue *o1, const TValue *o2)
795 *o1 = *o2; tvchecklive(L, o1);
798 /* -- Number to integer conversion ---------------------------------------- */
800 #if LJ_SOFTFP
801 LJ_ASMF int32_t lj_vm_tobit(double x);
802 #endif
804 static LJ_AINLINE int32_t lj_num2bit(lua_Number n)
806 #if LJ_SOFTFP
807 return lj_vm_tobit(n);
808 #else
809 TValue o;
810 o.n = n + 6755399441055744.0; /* 2^52 + 2^51 */
811 return (int32_t)o.u32.lo;
812 #endif
815 #define lj_num2int(n) ((int32_t)(n))
817 static LJ_AINLINE uint64_t lj_num2u64(lua_Number n)
819 #ifdef _MSC_VER
820 if (n >= 9223372036854775808.0) /* They think it's a feature. */
821 return (uint64_t)(int64_t)(n - 18446744073709551616.0);
822 else
823 #endif
824 return (uint64_t)n;
827 static LJ_AINLINE int32_t numberVint(cTValue *o)
829 if (LJ_LIKELY(tvisint(o)))
830 return intV(o);
831 else
832 return lj_num2int(numV(o));
835 static LJ_AINLINE lua_Number numberVnum(cTValue *o)
837 if (LJ_UNLIKELY(tvisint(o)))
838 return (lua_Number)intV(o);
839 else
840 return numV(o);
843 /* -- Miscellaneous object handling --------------------------------------- */
845 /* Names and maps for internal and external object tags. */
846 LJ_DATA const char *const lj_obj_typename[1+LUA_TCDATA+1];
847 LJ_DATA const char *const lj_obj_itypename[~LJ_TNUMX+1];
849 #define lj_typename(o) (lj_obj_itypename[itypemap(o)])
851 /* Compare two objects without calling metamethods. */
852 LJ_FUNC int LJ_FASTCALL lj_obj_equal(cTValue *o1, cTValue *o2);
853 LJ_FUNC const void * LJ_FASTCALL lj_obj_ptr(cTValue *o);
855 #endif