aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/.gitignore2
-rw-r--r--src/Makefile84
-rw-r--r--src/Makefile.dep216
-rw-r--r--src/host/buildvm.c26
-rw-r--r--src/host/buildvm.h1
-rw-r--r--src/host/buildvm_asm.c59
-rw-r--r--src/host/buildvm_lib.c61
-rw-r--r--src/host/buildvm_libbc.h56
-rw-r--r--src/host/buildvm_peobj.c28
-rw-r--r--src/host/genlibbc.lua197
-rw-r--r--src/jit/bc.lua19
-rw-r--r--src/jit/bcsave.lua30
-rw-r--r--src/jit/dis_arm.lua18
-rw-r--r--src/jit/dis_arm64.lua1216
-rw-r--r--src/jit/dis_mips.lua79
-rw-r--r--src/jit/dis_mips64.lua17
-rw-r--r--src/jit/dis_mips64el.lua17
-rw-r--r--src/jit/dis_mipsel.lua15
-rw-r--r--src/jit/dis_ppc.lua18
-rw-r--r--src/jit/dis_x64.lua15
-rw-r--r--src/jit/dis_x86.lua275
-rw-r--r--src/jit/dump.lua45
-rw-r--r--src/jit/p.lua311
-rw-r--r--src/jit/v.lua17
-rw-r--r--src/jit/zone.lua45
-rw-r--r--src/lib_aux.c6
-rw-r--r--src/lib_base.c91
-rw-r--r--src/lib_bit.c134
-rw-r--r--src/lib_debug.c10
-rw-r--r--src/lib_ffi.c48
-rw-r--r--src/lib_io.c41
-rw-r--r--src/lib_jit.c169
-rw-r--r--src/lib_math.c11
-rw-r--r--src/lib_os.c37
-rw-r--r--src/lib_package.c21
-rw-r--r--src/lib_string.c448
-rw-r--r--src/lib_table.c187
-rw-r--r--src/lj_alloc.c257
-rw-r--r--src/lj_api.c135
-rw-r--r--src/lj_arch.h215
-rw-r--r--src/lj_asm.c717
-rw-r--r--src/lj_asm_arm.h464
-rw-r--r--src/lj_asm_arm64.h2008
-rw-r--r--src/lj_asm_mips.h1329
-rw-r--r--src/lj_asm_ppc.h408
-rw-r--r--src/lj_asm_x86.h1115
-rw-r--r--src/lj_bc.h4
-rw-r--r--src/lj_bcdump.h6
-rw-r--r--src/lj_bcread.c143
-rw-r--r--src/lj_bcwrite.c229
-rw-r--r--src/lj_buf.c232
-rw-r--r--src/lj_buf.h103
-rw-r--r--src/lj_carith.c76
-rw-r--r--src/lj_carith.h10
-rw-r--r--src/lj_ccall.c356
-rw-r--r--src/lj_ccall.h45
-rw-r--r--src/lj_ccallback.c201
-rw-r--r--src/lj_cdata.c40
-rw-r--r--src/lj_cdata.h7
-rw-r--r--src/lj_clib.c29
-rw-r--r--src/lj_cparse.c83
-rw-r--r--src/lj_crecord.c269
-rw-r--r--src/lj_crecord.h7
-rw-r--r--src/lj_ctype.c17
-rw-r--r--src/lj_ctype.h2
-rw-r--r--src/lj_debug.c186
-rw-r--r--src/lj_debug.h8
-rw-r--r--src/lj_def.h19
-rw-r--r--src/lj_dispatch.c85
-rw-r--r--src/lj_dispatch.h43
-rw-r--r--src/lj_emit_arm.h21
-rw-r--r--src/lj_emit_arm64.h419
-rw-r--r--src/lj_emit_mips.h138
-rw-r--r--src/lj_emit_ppc.h22
-rw-r--r--src/lj_emit_x86.h160
-rw-r--r--src/lj_err.c203
-rw-r--r--src/lj_errmsg.h5
-rw-r--r--src/lj_ffrecord.c587
-rw-r--r--src/lj_frame.h158
-rw-r--r--src/lj_gc.c70
-rw-r--r--src/lj_gc.h10
-rw-r--r--src/lj_gdbjit.c48
-rw-r--r--src/lj_ir.c153
-rw-r--r--src/lj_ir.h75
-rw-r--r--src/lj_ircall.h172
-rw-r--r--src/lj_iropt.h11
-rw-r--r--src/lj_jit.h118
-rw-r--r--src/lj_lex.c371
-rw-r--r--src/lj_lex.h17
-rw-r--r--src/lj_lib.c75
-rw-r--r--src/lj_lib.h29
-rw-r--r--src/lj_load.c4
-rw-r--r--src/lj_mcode.c4
-rw-r--r--src/lj_meta.c125
-rw-r--r--src/lj_meta.h1
-rw-r--r--src/lj_obj.c17
-rw-r--r--src/lj_obj.h188
-rw-r--r--src/lj_opt_fold.c328
-rw-r--r--src/lj_opt_loop.c29
-rw-r--r--src/lj_opt_mem.c27
-rw-r--r--src/lj_opt_narrow.c2
-rw-r--r--src/lj_opt_sink.c10
-rw-r--r--src/lj_opt_split.c152
-rw-r--r--src/lj_parse.c189
-rw-r--r--src/lj_profile.c368
-rw-r--r--src/lj_profile.h21
-rw-r--r--src/lj_record.c651
-rw-r--r--src/lj_record.h1
-rw-r--r--src/lj_snap.c123
-rw-r--r--src/lj_state.c35
-rw-r--r--src/lj_state.h2
-rw-r--r--src/lj_str.c212
-rw-r--r--src/lj_str.h35
-rw-r--r--src/lj_strfmt.c472
-rw-r--r--src/lj_strfmt.h125
-rw-r--r--src/lj_strfmt_num.c592
-rw-r--r--src/lj_strscan.c57
-rw-r--r--src/lj_tab.c54
-rw-r--r--src/lj_tab.h5
-rw-r--r--src/lj_target.h6
-rw-r--r--src/lj_target_arm.h4
-rw-r--r--src/lj_target_arm64.h322
-rw-r--r--src/lj_target_mips.h155
-rw-r--r--src/lj_target_ppc.h2
-rw-r--r--src/lj_target_x86.h30
-rw-r--r--src/lj_trace.c131
-rw-r--r--src/lj_trace.h2
-rw-r--r--src/lj_traceerr.h4
-rw-r--r--src/lj_vm.h26
-rw-r--r--src/lj_vmevent.c1
-rw-r--r--src/lj_vmmath.c56
-rw-r--r--src/ljamalg.c4
-rw-r--r--src/lua.h1
-rw-r--r--src/luaconf.h2
-rw-r--r--src/luajit.c118
-rw-r--r--src/luajit.h15
-rw-r--r--src/msvcbuild.bat11
-rw-r--r--src/ps4build.bat32
-rw-r--r--src/vm_arm.dasc339
-rw-r--r--src/vm_arm64.dasc3964
-rw-r--r--src/vm_mips.dasc2492
-rw-r--r--src/vm_mips64.dasc5062
-rw-r--r--src/vm_ppc.dasc372
-rw-r--r--src/vm_ppcspe.dasc3691
-rw-r--r--src/vm_x64.dasc4909
-rw-r--r--src/vm_x86.dasc1563
-rw-r--r--src/xb1build.bat101
147 files changed, 32484 insertions, 10540 deletions
diff --git a/src/.gitignore b/src/.gitignore
index fc94e82c..1a30573c 100644
--- a/src/.gitignore
+++ b/src/.gitignore
@@ -4,4 +4,4 @@ lj_ffdef.h
4lj_libdef.h 4lj_libdef.h
5lj_recdef.h 5lj_recdef.h
6lj_folddef.h 6lj_folddef.h
7lj_vm.s 7lj_vm.[sS]
diff --git a/src/Makefile b/src/Makefile
index bd172dbe..7cb4c14a 100644
--- a/src/Makefile
+++ b/src/Makefile
@@ -11,8 +11,8 @@
11############################################################################## 11##############################################################################
12 12
13MAJVER= 2 13MAJVER= 2
14MINVER= 0 14MINVER= 1
15RELVER= 4 15RELVER= 0
16ABIVER= 5.1 16ABIVER= 5.1
17NODOTABIVER= 51 17NODOTABIVER= 51
18 18
@@ -44,17 +44,14 @@ CCOPT= -O2 -fomit-frame-pointer
44# 44#
45# Target-specific compiler options: 45# Target-specific compiler options:
46# 46#
47# x86 only: it's recommended to compile at least for i686. Better yet,
48# compile for an architecture that has SSE2, too (-msse -msse2).
49#
50# x86/x64 only: For GCC 4.2 or higher and if you don't intend to distribute 47# x86/x64 only: For GCC 4.2 or higher and if you don't intend to distribute
51# the binaries to a different machine you could also use: -march=native 48# the binaries to a different machine you could also use: -march=native
52# 49#
53CCOPT_x86= -march=i686 50CCOPT_x86= -march=i686 -msse -msse2 -mfpmath=sse
54CCOPT_x64= 51CCOPT_x64=
55CCOPT_arm= 52CCOPT_arm=
53CCOPT_arm64=
56CCOPT_ppc= 54CCOPT_ppc=
57CCOPT_ppcspe=
58CCOPT_mips= 55CCOPT_mips=
59# 56#
60CCDEBUG= 57CCDEBUG=
@@ -113,6 +110,9 @@ XCFLAGS=
113#XCFLAGS+= -DLUAJIT_NUMMODE=1 110#XCFLAGS+= -DLUAJIT_NUMMODE=1
114#XCFLAGS+= -DLUAJIT_NUMMODE=2 111#XCFLAGS+= -DLUAJIT_NUMMODE=2
115# 112#
113# Enable GC64 mode for x64.
114#XCFLAGS+= -DLUAJIT_ENABLE_GC64
115#
116############################################################################## 116##############################################################################
117 117
118############################################################################## 118##############################################################################
@@ -124,8 +124,8 @@ XCFLAGS=
124# 124#
125# Use the system provided memory allocator (realloc) instead of the 125# Use the system provided memory allocator (realloc) instead of the
126# bundled memory allocator. This is slower, but sometimes helpful for 126# bundled memory allocator. This is slower, but sometimes helpful for
127# debugging. This option cannot be enabled on x64, since realloc usually 127# debugging. This option cannot be enabled on x64 without GC64, since
128# doesn't return addresses in the right address range. 128# realloc usually doesn't return addresses in the right address range.
129# OTOH this option is mandatory for Valgrind's memcheck tool on x64 and 129# OTOH this option is mandatory for Valgrind's memcheck tool on x64 and
130# the only way to get useful results from it for all other architectures. 130# the only way to get useful results from it for all other architectures.
131#XCFLAGS+= -DLUAJIT_USE_SYSMALLOC 131#XCFLAGS+= -DLUAJIT_USE_SYSMALLOC
@@ -186,7 +186,8 @@ endif
186# make HOST_CC="gcc -m32" CROSS=i586-mingw32msvc- TARGET_SYS=Windows 186# make HOST_CC="gcc -m32" CROSS=i586-mingw32msvc- TARGET_SYS=Windows
187# make HOST_CC="gcc -m32" CROSS=powerpc-linux-gnu- 187# make HOST_CC="gcc -m32" CROSS=powerpc-linux-gnu-
188 188
189CCOPTIONS= $(CCDEBUG) $(CCOPT) $(CCWARN) $(XCFLAGS) $(CFLAGS) 189ASOPTIONS= $(CCOPT) $(CCWARN) $(XCFLAGS) $(CFLAGS)
190CCOPTIONS= $(CCDEBUG) $(ASOPTIONS)
190LDOPTIONS= $(CCDEBUG) $(LDFLAGS) 191LDOPTIONS= $(CCDEBUG) $(LDFLAGS)
191 192
192HOST_CC= $(CC) 193HOST_CC= $(CC)
@@ -225,6 +226,7 @@ TARGET_XLDFLAGS=
225TARGET_XLIBS= -lm 226TARGET_XLIBS= -lm
226TARGET_TCFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS) 227TARGET_TCFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS)
227TARGET_ACFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS) 228TARGET_ACFLAGS= $(CCOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS)
229TARGET_ASFLAGS= $(ASOPTIONS) $(TARGET_XCFLAGS) $(TARGET_FLAGS) $(TARGET_CFLAGS)
228TARGET_ALDFLAGS= $(LDOPTIONS) $(TARGET_XLDFLAGS) $(TARGET_FLAGS) $(TARGET_LDFLAGS) 230TARGET_ALDFLAGS= $(LDOPTIONS) $(TARGET_XLDFLAGS) $(TARGET_FLAGS) $(TARGET_LDFLAGS)
229TARGET_ASHLDFLAGS= $(LDOPTIONS) $(TARGET_XSHLDFLAGS) $(TARGET_FLAGS) $(TARGET_SHLDFLAGS) 231TARGET_ASHLDFLAGS= $(LDOPTIONS) $(TARGET_XSHLDFLAGS) $(TARGET_FLAGS) $(TARGET_SHLDFLAGS)
230TARGET_ALIBS= $(TARGET_XLIBS) $(LIBS) $(TARGET_LIBS) 232TARGET_ALIBS= $(TARGET_XLIBS) $(LIBS) $(TARGET_LIBS)
@@ -239,17 +241,26 @@ else
239ifneq (,$(findstring LJ_TARGET_ARM ,$(TARGET_TESTARCH))) 241ifneq (,$(findstring LJ_TARGET_ARM ,$(TARGET_TESTARCH)))
240 TARGET_LJARCH= arm 242 TARGET_LJARCH= arm
241else 243else
244ifneq (,$(findstring LJ_TARGET_ARM64 ,$(TARGET_TESTARCH)))
245 TARGET_LJARCH= arm64
246else
242ifneq (,$(findstring LJ_TARGET_PPC ,$(TARGET_TESTARCH))) 247ifneq (,$(findstring LJ_TARGET_PPC ,$(TARGET_TESTARCH)))
248 ifneq (,$(findstring LJ_LE 1,$(TARGET_TESTARCH)))
249 TARGET_ARCH= -DLJ_ARCH_ENDIAN=LUAJIT_LE
250 else
251 TARGET_ARCH= -DLJ_ARCH_ENDIAN=LUAJIT_BE
252 endif
243 TARGET_LJARCH= ppc 253 TARGET_LJARCH= ppc
244else 254else
245ifneq (,$(findstring LJ_TARGET_PPCSPE ,$(TARGET_TESTARCH)))
246 TARGET_LJARCH= ppcspe
247else
248ifneq (,$(findstring LJ_TARGET_MIPS ,$(TARGET_TESTARCH))) 255ifneq (,$(findstring LJ_TARGET_MIPS ,$(TARGET_TESTARCH)))
249 ifneq (,$(findstring MIPSEL ,$(TARGET_TESTARCH))) 256 ifneq (,$(findstring MIPSEL ,$(TARGET_TESTARCH)))
250 TARGET_ARCH= -D__MIPSEL__=1 257 TARGET_ARCH= -D__MIPSEL__=1
251 endif 258 endif
252 TARGET_LJARCH= mips 259 ifneq (,$(findstring LJ_TARGET_MIPS64 ,$(TARGET_TESTARCH)))
260 TARGET_LJARCH= mips64
261 else
262 TARGET_LJARCH= mips
263 endif
253else 264else
254 $(error Unsupported target architecture) 265 $(error Unsupported target architecture)
255endif 266endif
@@ -263,6 +274,7 @@ ifneq (,$(findstring LJ_TARGET_PS3 1,$(TARGET_TESTARCH)))
263 TARGET_SYS= PS3 274 TARGET_SYS= PS3
264 TARGET_ARCH+= -D__CELLOS_LV2__ 275 TARGET_ARCH+= -D__CELLOS_LV2__
265 TARGET_XCFLAGS+= -DLUAJIT_USE_SYSMALLOC 276 TARGET_XCFLAGS+= -DLUAJIT_USE_SYSMALLOC
277 TARGET_XLIBS+= -lpthread
266endif 278endif
267 279
268TARGET_XCFLAGS+= $(CCOPT_$(TARGET_LJARCH)) 280TARGET_XCFLAGS+= $(CCOPT_$(TARGET_LJARCH))
@@ -314,6 +326,9 @@ ifeq (iOS,$(TARGET_SYS))
314 TARGET_XSHLDFLAGS= -dynamiclib -single_module -undefined dynamic_lookup -fPIC 326 TARGET_XSHLDFLAGS= -dynamiclib -single_module -undefined dynamic_lookup -fPIC
315 TARGET_DYNXLDOPTS= 327 TARGET_DYNXLDOPTS=
316 TARGET_XSHLDFLAGS+= -install_name $(TARGET_DYLIBPATH) -compatibility_version $(MAJVER).$(MINVER) -current_version $(MAJVER).$(MINVER).$(RELVER) 328 TARGET_XSHLDFLAGS+= -install_name $(TARGET_DYLIBPATH) -compatibility_version $(MAJVER).$(MINVER) -current_version $(MAJVER).$(MINVER).$(RELVER)
329 ifeq (arm64,$(TARGET_LJARCH))
330 TARGET_XCFLAGS+= -fno-omit-frame-pointer
331 endif
317else 332else
318 ifneq (SunOS,$(TARGET_SYS)) 333 ifneq (SunOS,$(TARGET_SYS))
319 ifneq (PS3,$(TARGET_SYS)) 334 ifneq (PS3,$(TARGET_SYS))
@@ -374,6 +389,11 @@ DASM_XFLAGS=
374DASM_AFLAGS= 389DASM_AFLAGS=
375DASM_ARCH= $(TARGET_LJARCH) 390DASM_ARCH= $(TARGET_LJARCH)
376 391
392ifneq (,$(findstring LJ_LE 1,$(TARGET_TESTARCH)))
393 DASM_AFLAGS+= -D ENDIAN_LE
394else
395 DASM_AFLAGS+= -D ENDIAN_BE
396endif
377ifneq (,$(findstring LJ_ARCH_BITS 64,$(TARGET_TESTARCH))) 397ifneq (,$(findstring LJ_ARCH_BITS 64,$(TARGET_TESTARCH)))
378 DASM_AFLAGS+= -D P64 398 DASM_AFLAGS+= -D P64
379endif 399endif
@@ -406,13 +426,10 @@ DASM_AFLAGS+= -D VER=$(subst LJ_ARCH_VERSION_,,$(filter LJ_ARCH_VERSION_%,$(subs
406ifeq (Windows,$(TARGET_SYS)) 426ifeq (Windows,$(TARGET_SYS))
407 DASM_AFLAGS+= -D WIN 427 DASM_AFLAGS+= -D WIN
408endif 428endif
409ifeq (x86,$(TARGET_LJARCH))
410 ifneq (,$(findstring __SSE2__ 1,$(TARGET_TESTARCH)))
411 DASM_AFLAGS+= -D SSE
412 endif
413else
414ifeq (x64,$(TARGET_LJARCH)) 429ifeq (x64,$(TARGET_LJARCH))
415 DASM_ARCH= x86 430 ifeq (,$(findstring LJ_FR2 1,$(TARGET_TESTARCH)))
431 DASM_ARCH= x86
432 endif
416else 433else
417ifeq (arm,$(TARGET_LJARCH)) 434ifeq (arm,$(TARGET_LJARCH))
418 ifeq (iOS,$(TARGET_SYS)) 435 ifeq (iOS,$(TARGET_SYS))
@@ -426,13 +443,15 @@ ifeq (ppc,$(TARGET_LJARCH))
426 ifneq (,$(findstring LJ_ARCH_ROUND 1,$(TARGET_TESTARCH))) 443 ifneq (,$(findstring LJ_ARCH_ROUND 1,$(TARGET_TESTARCH)))
427 DASM_AFLAGS+= -D ROUND 444 DASM_AFLAGS+= -D ROUND
428 endif 445 endif
429 ifneq (,$(findstring LJ_ARCH_PPC64 1,$(TARGET_TESTARCH))) 446 ifneq (,$(findstring LJ_ARCH_PPC32ON64 1,$(TARGET_TESTARCH)))
430 DASM_AFLAGS+= -D GPR64 447 DASM_AFLAGS+= -D GPR64
431 endif 448 endif
432 ifeq (PS3,$(TARGET_SYS)) 449 ifeq (PS3,$(TARGET_SYS))
433 DASM_AFLAGS+= -D PPE -D TOC 450 DASM_AFLAGS+= -D PPE -D TOC
434 endif 451 endif
435endif 452 ifneq (,$(findstring LJ_ARCH_PPC64 ,$(TARGET_TESTARCH)))
453 DASM_ARCH= ppc64
454 endif
436endif 455endif
437endif 456endif
438endif 457endif
@@ -448,7 +467,7 @@ BUILDVM_X= $(BUILDVM_T)
448HOST_O= $(MINILUA_O) $(BUILDVM_O) 467HOST_O= $(MINILUA_O) $(BUILDVM_O)
449HOST_T= $(MINILUA_T) $(BUILDVM_T) 468HOST_T= $(MINILUA_T) $(BUILDVM_T)
450 469
451LJVM_S= lj_vm.s 470LJVM_S= lj_vm.S
452LJVM_O= lj_vm.o 471LJVM_O= lj_vm.o
453LJVM_BOUT= $(LJVM_S) 472LJVM_BOUT= $(LJVM_S)
454LJVM_MODE= elfasm 473LJVM_MODE= elfasm
@@ -457,10 +476,11 @@ LJLIB_O= lib_base.o lib_math.o lib_bit.o lib_string.o lib_table.o \
457 lib_io.o lib_os.o lib_package.o lib_debug.o lib_jit.o lib_ffi.o 476 lib_io.o lib_os.o lib_package.o lib_debug.o lib_jit.o lib_ffi.o
458LJLIB_C= $(LJLIB_O:.o=.c) 477LJLIB_C= $(LJLIB_O:.o=.c)
459 478
460LJCORE_O= lj_gc.o lj_err.o lj_char.o lj_bc.o lj_obj.o \ 479LJCORE_O= lj_gc.o lj_err.o lj_char.o lj_bc.o lj_obj.o lj_buf.o \
461 lj_str.o lj_tab.o lj_func.o lj_udata.o lj_meta.o lj_debug.o \ 480 lj_str.o lj_tab.o lj_func.o lj_udata.o lj_meta.o lj_debug.o \
462 lj_state.o lj_dispatch.o lj_vmevent.o lj_vmmath.o lj_strscan.o \ 481 lj_state.o lj_dispatch.o lj_vmevent.o lj_vmmath.o lj_strscan.o \
463 lj_api.o lj_lex.o lj_parse.o lj_bcread.o lj_bcwrite.o lj_load.o \ 482 lj_strfmt.o lj_strfmt_num.o lj_api.o lj_profile.o \
483 lj_lex.o lj_parse.o lj_bcread.o lj_bcwrite.o lj_load.o \
464 lj_ir.o lj_opt_mem.o lj_opt_fold.o lj_opt_narrow.o \ 484 lj_ir.o lj_opt_mem.o lj_opt_fold.o lj_opt_narrow.o \
465 lj_opt_dce.o lj_opt_loop.o lj_opt_split.o lj_opt_sink.o \ 485 lj_opt_dce.o lj_opt_loop.o lj_opt_split.o lj_opt_sink.o \
466 lj_mcode.o lj_snap.o lj_record.o lj_crecord.o lj_ffrecord.o \ 486 lj_mcode.o lj_snap.o lj_record.o lj_crecord.o lj_ffrecord.o \
@@ -580,6 +600,10 @@ amalg:
580clean: 600clean:
581 $(HOST_RM) $(ALL_RM) 601 $(HOST_RM) $(ALL_RM)
582 602
603libbc:
604 ./$(LUAJIT_T) host/genlibbc.lua -o host/buildvm_libbc.h $(LJLIB_C)
605 $(MAKE) all
606
583depend: 607depend:
584 @for file in $(ALL_HDRGEN); do \ 608 @for file in $(ALL_HDRGEN); do \
585 test -f $$file || touch $$file; \ 609 test -f $$file || touch $$file; \
@@ -594,7 +618,7 @@ depend:
594 test -s $$file || $(HOST_RM) $$file; \ 618 test -s $$file || $(HOST_RM) $$file; \
595 done 619 done
596 620
597.PHONY: default all amalg clean depend 621.PHONY: default all amalg clean libbc depend
598 622
599############################################################################## 623##############################################################################
600# Rules for generated files. 624# Rules for generated files.
@@ -604,7 +628,7 @@ $(MINILUA_T): $(MINILUA_O)
604 $(E) "HOSTLINK $@" 628 $(E) "HOSTLINK $@"
605 $(Q)$(HOST_CC) $(HOST_ALDFLAGS) -o $@ $(MINILUA_O) $(MINILUA_LIBS) $(HOST_ALIBS) 629 $(Q)$(HOST_CC) $(HOST_ALDFLAGS) -o $@ $(MINILUA_O) $(MINILUA_LIBS) $(HOST_ALIBS)
606 630
607host/buildvm_arch.h: $(DASM_DASC) $(DASM_DEP) 631host/buildvm_arch.h: $(DASM_DASC) $(DASM_DEP) $(DASM_DIR)/*.lua
608 $(E) "DYNASM $@" 632 $(E) "DYNASM $@"
609 $(Q)$(DASM) $(DASM_FLAGS) -o $@ $(DASM_DASC) 633 $(Q)$(DASM) $(DASM_FLAGS) -o $@ $(DASM_DASC)
610 634
@@ -651,10 +675,10 @@ lj_folddef.h: $(BUILDVM_T) lj_opt_fold.c
651 $(Q)$(TARGET_DYNCC) $(TARGET_ACFLAGS) -c -o $(@:.o=_dyn.o) $< 675 $(Q)$(TARGET_DYNCC) $(TARGET_ACFLAGS) -c -o $(@:.o=_dyn.o) $<
652 $(Q)$(TARGET_CC) $(TARGET_ACFLAGS) -c -o $@ $< 676 $(Q)$(TARGET_CC) $(TARGET_ACFLAGS) -c -o $@ $<
653 677
654%.o: %.s 678%.o: %.S
655 $(E) "ASM $@" 679 $(E) "ASM $@"
656 $(Q)$(TARGET_DYNCC) $(TARGET_ACFLAGS) -c -o $(@:.o=_dyn.o) $< 680 $(Q)$(TARGET_DYNCC) $(TARGET_ASFLAGS) -c -o $(@:.o=_dyn.o) $<
657 $(Q)$(TARGET_CC) $(TARGET_ACFLAGS) -c -o $@ $< 681 $(Q)$(TARGET_CC) $(TARGET_ASFLAGS) -c -o $@ $<
658 682
659$(LUAJIT_O): 683$(LUAJIT_O):
660 $(E) "CC $@" 684 $(E) "CC $@"
diff --git a/src/Makefile.dep b/src/Makefile.dep
index 9e14d617..2b1cb5ef 100644
--- a/src/Makefile.dep
+++ b/src/Makefile.dep
@@ -3,45 +3,49 @@ lib_aux.o: lib_aux.c lua.h luaconf.h lauxlib.h lj_obj.h lj_def.h \
3 lj_dispatch.h lj_bc.h lj_traceerr.h lj_lib.h lj_alloc.h 3 lj_dispatch.h lj_bc.h lj_traceerr.h lj_lib.h lj_alloc.h
4lib_base.o: lib_base.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 4lib_base.o: lib_base.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
5 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h \ 5 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h \
6 lj_tab.h lj_meta.h lj_state.h lj_ctype.h lj_cconv.h lj_bc.h lj_ff.h \ 6 lj_tab.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_cconv.h \
7 lj_ffdef.h lj_dispatch.h lj_jit.h lj_ir.h lj_char.h lj_strscan.h \ 7 lj_ff.h lj_ffdef.h lj_dispatch.h lj_jit.h lj_ir.h lj_char.h lj_strscan.h \
8 lj_lib.h lj_libdef.h 8 lj_strfmt.h lj_lib.h lj_libdef.h
9lib_bit.o: lib_bit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ 9lib_bit.o: lib_bit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
10 lj_arch.h lj_err.h lj_errmsg.h lj_str.h lj_lib.h lj_libdef.h 10 lj_arch.h lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_strscan.h \
11 lj_strfmt.h lj_ctype.h lj_cdata.h lj_cconv.h lj_carith.h lj_ff.h \
12 lj_ffdef.h lj_lib.h lj_libdef.h
11lib_debug.o: lib_debug.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 13lib_debug.o: lib_debug.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
12 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_lib.h \ 14 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_lib.h \
13 lj_libdef.h 15 lj_libdef.h
14lib_ffi.o: lib_ffi.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ 16lib_ffi.o: lib_ffi.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
15 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h \ 17 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h \
16 lj_ctype.h lj_cparse.h lj_cdata.h lj_cconv.h lj_carith.h lj_ccall.h \ 18 lj_ctype.h lj_cparse.h lj_cdata.h lj_cconv.h lj_carith.h lj_ccall.h \
17 lj_ccallback.h lj_clib.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h 19 lj_ccallback.h lj_clib.h lj_strfmt.h lj_ff.h lj_ffdef.h lj_lib.h \
20 lj_libdef.h
18lib_init.o: lib_init.c lua.h luaconf.h lauxlib.h lualib.h lj_arch.h 21lib_init.o: lib_init.c lua.h luaconf.h lauxlib.h lualib.h lj_arch.h
19lib_io.o: lib_io.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ 22lib_io.o: lib_io.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
20 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_state.h lj_ff.h \ 23 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_state.h \
21 lj_ffdef.h lj_lib.h lj_libdef.h 24 lj_strfmt.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h
22lib_jit.o: lib_jit.c lua.h luaconf.h lauxlib.h lualib.h lj_arch.h \ 25lib_jit.o: lib_jit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
23 lj_obj.h lj_def.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h \ 26 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h \
24 lj_bc.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_target.h \ 27 lj_state.h lj_bc.h lj_ctype.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h \
25 lj_target_*.h lj_dispatch.h lj_vm.h lj_vmevent.h lj_lib.h luajit.h \ 28 lj_target.h lj_target_*.h lj_trace.h lj_dispatch.h lj_traceerr.h \
26 lj_libdef.h 29 lj_vm.h lj_vmevent.h lj_lib.h luajit.h lj_libdef.h
27lib_math.o: lib_math.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 30lib_math.o: lib_math.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
28 lj_def.h lj_arch.h lj_lib.h lj_vm.h lj_libdef.h 31 lj_def.h lj_arch.h lj_lib.h lj_vm.h lj_libdef.h
29lib_os.o: lib_os.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ 32lib_os.o: lib_os.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \
30 lj_arch.h lj_err.h lj_errmsg.h lj_lib.h lj_libdef.h 33 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_lib.h \
34 lj_libdef.h
31lib_package.o: lib_package.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 35lib_package.o: lib_package.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
32 lj_def.h lj_arch.h lj_err.h lj_errmsg.h lj_lib.h 36 lj_def.h lj_arch.h lj_err.h lj_errmsg.h lj_lib.h
33lib_string.o: lib_string.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 37lib_string.o: lib_string.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
34 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h \ 38 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h \
35 lj_meta.h lj_state.h lj_ff.h lj_ffdef.h lj_bcdump.h lj_lex.h lj_char.h \ 39 lj_tab.h lj_meta.h lj_state.h lj_ff.h lj_ffdef.h lj_bcdump.h lj_lex.h \
36 lj_lib.h lj_libdef.h 40 lj_char.h lj_strfmt.h lj_lib.h lj_libdef.h
37lib_table.o: lib_table.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ 41lib_table.o: lib_table.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \
38 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_lib.h \ 42 lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h \
39 lj_libdef.h 43 lj_tab.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h
40lj_alloc.o: lj_alloc.c lj_def.h lua.h luaconf.h lj_arch.h lj_alloc.h 44lj_alloc.o: lj_alloc.c lj_def.h lua.h luaconf.h lj_arch.h lj_alloc.h
41lj_api.o: lj_api.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 45lj_api.o: lj_api.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
42 lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_func.h lj_udata.h \ 46 lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_func.h lj_udata.h \
43 lj_meta.h lj_state.h lj_bc.h lj_frame.h lj_trace.h lj_jit.h lj_ir.h \ 47 lj_meta.h lj_state.h lj_bc.h lj_frame.h lj_trace.h lj_jit.h lj_ir.h \
44 lj_dispatch.h lj_traceerr.h lj_vm.h lj_strscan.h 48 lj_dispatch.h lj_traceerr.h lj_vm.h lj_strscan.h lj_strfmt.h
45lj_asm.o: lj_asm.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 49lj_asm.o: lj_asm.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
46 lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h lj_ir.h lj_jit.h \ 50 lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h lj_ir.h lj_jit.h \
47 lj_ircall.h lj_iropt.h lj_mcode.h lj_trace.h lj_dispatch.h lj_traceerr.h \ 51 lj_ircall.h lj_iropt.h lj_mcode.h lj_trace.h lj_dispatch.h lj_traceerr.h \
@@ -50,17 +54,20 @@ lj_asm.o: lj_asm.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
50lj_bc.o: lj_bc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.h \ 54lj_bc.o: lj_bc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.h \
51 lj_bcdef.h 55 lj_bcdef.h
52lj_bcread.o: lj_bcread.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 56lj_bcread.o: lj_bcread.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
53 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_bc.h lj_ctype.h \ 57 lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_bc.h \
54 lj_cdata.h lualib.h lj_lex.h lj_bcdump.h lj_state.h 58 lj_ctype.h lj_cdata.h lualib.h lj_lex.h lj_bcdump.h lj_state.h \
59 lj_strfmt.h
55lj_bcwrite.o: lj_bcwrite.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 60lj_bcwrite.o: lj_bcwrite.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
56 lj_gc.h lj_str.h lj_bc.h lj_ctype.h lj_dispatch.h lj_jit.h lj_ir.h \ 61 lj_gc.h lj_buf.h lj_str.h lj_bc.h lj_ctype.h lj_dispatch.h lj_jit.h \
57 lj_bcdump.h lj_lex.h lj_err.h lj_errmsg.h lj_vm.h 62 lj_ir.h lj_strfmt.h lj_bcdump.h lj_lex.h lj_err.h lj_errmsg.h lj_vm.h
63lj_buf.o: lj_buf.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
64 lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_strfmt.h
58lj_carith.o: lj_carith.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 65lj_carith.o: lj_carith.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
59 lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_meta.h lj_ctype.h lj_cconv.h \ 66 lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_meta.h lj_ir.h lj_ctype.h \
60 lj_cdata.h lj_carith.h 67 lj_cconv.h lj_cdata.h lj_carith.h lj_strscan.h
61lj_ccall.o: lj_ccall.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 68lj_ccall.o: lj_ccall.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
62 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h lj_cconv.h \ 69 lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_cconv.h lj_cdata.h \
63 lj_cdata.h lj_ccall.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \ 70 lj_ccall.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \
64 lj_traceerr.h 71 lj_traceerr.h
65lj_ccallback.o: lj_ccallback.c lj_obj.h lua.h luaconf.h lj_def.h \ 72lj_ccallback.o: lj_ccallback.c lj_obj.h lua.h luaconf.h lj_def.h \
66 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_state.h lj_frame.h \ 73 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_state.h lj_frame.h \
@@ -71,107 +78,118 @@ lj_cconv.o: lj_cconv.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
71 lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_gc.h lj_cdata.h lj_cconv.h \ 78 lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_gc.h lj_cdata.h lj_cconv.h \
72 lj_ccallback.h 79 lj_ccallback.h
73lj_cdata.o: lj_cdata.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 80lj_cdata.o: lj_cdata.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
74 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h lj_cconv.h \ 81 lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_cconv.h lj_cdata.h
75 lj_cdata.h
76lj_char.o: lj_char.c lj_char.h lj_def.h lua.h luaconf.h 82lj_char.o: lj_char.c lj_char.h lj_def.h lua.h luaconf.h
77lj_clib.o: lj_clib.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 83lj_clib.o: lj_clib.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
78 lj_err.h lj_errmsg.h lj_tab.h lj_str.h lj_udata.h lj_ctype.h lj_cconv.h \ 84 lj_err.h lj_errmsg.h lj_tab.h lj_str.h lj_udata.h lj_ctype.h lj_cconv.h \
79 lj_cdata.h lj_clib.h 85 lj_cdata.h lj_clib.h lj_strfmt.h
80lj_cparse.o: lj_cparse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 86lj_cparse.o: lj_cparse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
81 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_ctype.h lj_cparse.h lj_frame.h \ 87 lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_ctype.h lj_cparse.h \
82 lj_bc.h lj_vm.h lj_char.h lj_strscan.h 88 lj_frame.h lj_bc.h lj_vm.h lj_char.h lj_strscan.h lj_strfmt.h
83lj_crecord.o: lj_crecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 89lj_crecord.o: lj_crecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
84 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h \ 90 lj_err.h lj_errmsg.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h lj_gc.h \
85 lj_gc.h lj_cdata.h lj_cparse.h lj_cconv.h lj_clib.h lj_ccall.h lj_ff.h \ 91 lj_cdata.h lj_cparse.h lj_cconv.h lj_carith.h lj_clib.h lj_ccall.h \
86 lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \ 92 lj_ff.h lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \
87 lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h lj_snap.h \ 93 lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h lj_snap.h \
88 lj_crecord.h 94 lj_crecord.h lj_strfmt.h
89lj_ctype.o: lj_ctype.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 95lj_ctype.o: lj_ctype.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
90 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h lj_ccallback.h 96 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_strfmt.h lj_ctype.h \
97 lj_ccallback.h lj_buf.h
91lj_debug.o: lj_debug.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 98lj_debug.o: lj_debug.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
92 lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_state.h lj_frame.h \ 99 lj_err.h lj_errmsg.h lj_debug.h lj_buf.h lj_gc.h lj_str.h lj_tab.h \
93 lj_bc.h lj_vm.h lj_jit.h lj_ir.h 100 lj_state.h lj_frame.h lj_bc.h lj_strfmt.h lj_jit.h lj_ir.h
94lj_dispatch.o: lj_dispatch.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 101lj_dispatch.o: lj_dispatch.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
95 lj_err.h lj_errmsg.h lj_func.h lj_str.h lj_tab.h lj_meta.h lj_debug.h \ 102 lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_func.h lj_tab.h \
96 lj_state.h lj_frame.h lj_bc.h lj_ff.h lj_ffdef.h lj_jit.h lj_ir.h \ 103 lj_meta.h lj_debug.h lj_state.h lj_frame.h lj_bc.h lj_ff.h lj_ffdef.h \
97 lj_ccallback.h lj_ctype.h lj_gc.h lj_trace.h lj_dispatch.h lj_traceerr.h \ 104 lj_strfmt.h lj_jit.h lj_ir.h lj_ccallback.h lj_ctype.h lj_trace.h \
98 lj_vm.h luajit.h 105 lj_dispatch.h lj_traceerr.h lj_profile.h lj_vm.h luajit.h
99lj_err.o: lj_err.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_err.h \ 106lj_err.o: lj_err.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_err.h \
100 lj_errmsg.h lj_debug.h lj_str.h lj_func.h lj_state.h lj_frame.h lj_bc.h \ 107 lj_errmsg.h lj_debug.h lj_str.h lj_func.h lj_state.h lj_frame.h lj_bc.h \
101 lj_ff.h lj_ffdef.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h \ 108 lj_ff.h lj_ffdef.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h \
102 lj_traceerr.h lj_vm.h 109 lj_traceerr.h lj_vm.h lj_strfmt.h
103lj_ffrecord.o: lj_ffrecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 110lj_ffrecord.o: lj_ffrecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
104 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ff.h \ 111 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ff.h \
105 lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \ 112 lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \
106 lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h lj_crecord.h \ 113 lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h lj_crecord.h \
107 lj_vm.h lj_strscan.h lj_recdef.h 114 lj_vm.h lj_strscan.h lj_strfmt.h lj_recdef.h
108lj_func.o: lj_func.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 115lj_func.o: lj_func.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
109 lj_func.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \ 116 lj_func.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \
110 lj_traceerr.h lj_vm.h 117 lj_traceerr.h lj_vm.h
111lj_gc.o: lj_gc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 118lj_gc.o: lj_gc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
112 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_udata.h lj_meta.h \ 119 lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_func.h lj_udata.h \
113 lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_cdata.h lj_trace.h lj_jit.h \ 120 lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_cdata.h lj_trace.h \
114 lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h 121 lj_jit.h lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h
115lj_gdbjit.o: lj_gdbjit.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 122lj_gdbjit.o: lj_gdbjit.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
116 lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_frame.h lj_bc.h lj_jit.h \ 123 lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_frame.h lj_bc.h lj_buf.h \
117 lj_ir.h lj_dispatch.h 124 lj_str.h lj_strfmt.h lj_jit.h lj_ir.h lj_dispatch.h
118lj_ir.o: lj_ir.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 125lj_ir.o: lj_ir.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
119 lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \ 126 lj_buf.h lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h \
120 lj_dispatch.h lj_bc.h lj_traceerr.h lj_ctype.h lj_cdata.h lj_carith.h \ 127 lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_ctype.h lj_cdata.h \
121 lj_vm.h lj_strscan.h lj_lib.h 128 lj_carith.h lj_vm.h lj_strscan.h lj_strfmt.h lj_lib.h
122lj_lex.o: lj_lex.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 129lj_lex.o: lj_lex.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
123 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_ctype.h lj_cdata.h lualib.h \ 130 lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_ctype.h lj_cdata.h \
124 lj_state.h lj_lex.h lj_parse.h lj_char.h lj_strscan.h 131 lualib.h lj_state.h lj_lex.h lj_parse.h lj_char.h lj_strscan.h \
132 lj_strfmt.h
125lj_lib.o: lj_lib.c lauxlib.h lua.h luaconf.h lj_obj.h lj_def.h lj_arch.h \ 133lj_lib.o: lj_lib.c lauxlib.h lua.h luaconf.h lj_obj.h lj_def.h lj_arch.h \
126 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_bc.h \ 134 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_bc.h \
127 lj_dispatch.h lj_jit.h lj_ir.h lj_vm.h lj_strscan.h lj_lib.h 135 lj_dispatch.h lj_jit.h lj_ir.h lj_vm.h lj_strscan.h lj_strfmt.h lj_lex.h \
136 lj_bcdump.h lj_lib.h
128lj_load.o: lj_load.c lua.h luaconf.h lauxlib.h lj_obj.h lj_def.h \ 137lj_load.o: lj_load.c lua.h luaconf.h lauxlib.h lj_obj.h lj_def.h \
129 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_func.h lj_frame.h \ 138 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_func.h \
130 lj_bc.h lj_vm.h lj_lex.h lj_bcdump.h lj_parse.h 139 lj_frame.h lj_bc.h lj_vm.h lj_lex.h lj_bcdump.h lj_parse.h
131lj_mcode.o: lj_mcode.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 140lj_mcode.o: lj_mcode.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
132 lj_gc.h lj_err.h lj_errmsg.h lj_jit.h lj_ir.h lj_mcode.h lj_trace.h \ 141 lj_gc.h lj_err.h lj_errmsg.h lj_jit.h lj_ir.h lj_mcode.h lj_trace.h \
133 lj_dispatch.h lj_bc.h lj_traceerr.h lj_vm.h 142 lj_dispatch.h lj_bc.h lj_traceerr.h lj_vm.h
134lj_meta.o: lj_meta.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 143lj_meta.o: lj_meta.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
135 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h lj_frame.h lj_bc.h \ 144 lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_meta.h lj_frame.h \
136 lj_vm.h lj_strscan.h 145 lj_bc.h lj_vm.h lj_strscan.h lj_strfmt.h lj_lib.h
137lj_obj.o: lj_obj.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h 146lj_obj.o: lj_obj.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h
138lj_opt_dce.o: lj_opt_dce.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 147lj_opt_dce.o: lj_opt_dce.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
139 lj_ir.h lj_jit.h lj_iropt.h 148 lj_ir.h lj_jit.h lj_iropt.h
140lj_opt_fold.o: lj_opt_fold.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 149lj_opt_fold.o: lj_opt_fold.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
141 lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_iropt.h lj_trace.h lj_dispatch.h \ 150 lj_buf.h lj_gc.h lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_ircall.h \
142 lj_bc.h lj_traceerr.h lj_ctype.h lj_gc.h lj_carith.h lj_vm.h \ 151 lj_iropt.h lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_ctype.h \
143 lj_strscan.h lj_folddef.h 152 lj_carith.h lj_vm.h lj_strscan.h lj_strfmt.h lj_folddef.h
144lj_opt_loop.o: lj_opt_loop.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 153lj_opt_loop.o: lj_opt_loop.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
145 lj_err.h lj_errmsg.h lj_str.h lj_ir.h lj_jit.h lj_iropt.h lj_trace.h \ 154 lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_ir.h lj_jit.h \
146 lj_dispatch.h lj_bc.h lj_traceerr.h lj_snap.h lj_vm.h 155 lj_iropt.h lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_snap.h \
156 lj_vm.h
147lj_opt_mem.o: lj_opt_mem.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 157lj_opt_mem.o: lj_opt_mem.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
148 lj_tab.h lj_ir.h lj_jit.h lj_iropt.h 158 lj_tab.h lj_ir.h lj_jit.h lj_iropt.h lj_ircall.h
149lj_opt_narrow.o: lj_opt_narrow.c lj_obj.h lua.h luaconf.h lj_def.h \ 159lj_opt_narrow.o: lj_opt_narrow.c lj_obj.h lua.h luaconf.h lj_def.h \
150 lj_arch.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h lj_trace.h lj_dispatch.h \ 160 lj_arch.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h lj_trace.h lj_dispatch.h \
151 lj_traceerr.h lj_vm.h lj_strscan.h 161 lj_traceerr.h lj_vm.h lj_strscan.h
152lj_opt_sink.o: lj_opt_sink.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 162lj_opt_sink.o: lj_opt_sink.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
153 lj_ir.h lj_jit.h lj_iropt.h lj_target.h lj_target_*.h 163 lj_ir.h lj_jit.h lj_iropt.h lj_target.h lj_target_*.h
154lj_opt_split.o: lj_opt_split.c lj_obj.h lua.h luaconf.h lj_def.h \ 164lj_opt_split.o: lj_opt_split.c lj_obj.h lua.h luaconf.h lj_def.h \
155 lj_arch.h lj_err.h lj_errmsg.h lj_str.h lj_ir.h lj_jit.h lj_ircall.h \ 165 lj_arch.h lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_ir.h \
156 lj_iropt.h lj_vm.h 166 lj_jit.h lj_ircall.h lj_iropt.h lj_dispatch.h lj_bc.h lj_vm.h
157lj_parse.o: lj_parse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 167lj_parse.o: lj_parse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
158 lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_func.h \ 168 lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_buf.h lj_str.h lj_tab.h \
159 lj_state.h lj_bc.h lj_ctype.h lj_lex.h lj_parse.h lj_vm.h lj_vmevent.h 169 lj_func.h lj_state.h lj_bc.h lj_ctype.h lj_strfmt.h lj_lex.h lj_parse.h \
170 lj_vm.h lj_vmevent.h
171lj_profile.o: lj_profile.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
172 lj_buf.h lj_gc.h lj_str.h lj_frame.h lj_bc.h lj_debug.h lj_dispatch.h \
173 lj_jit.h lj_ir.h lj_trace.h lj_traceerr.h lj_profile.h luajit.h
160lj_record.o: lj_record.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 174lj_record.o: lj_record.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
161 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h lj_frame.h lj_bc.h \ 175 lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h lj_frame.h lj_bc.h \
162 lj_ctype.h lj_gc.h lj_ff.h lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h \ 176 lj_ctype.h lj_gc.h lj_ff.h lj_ffdef.h lj_debug.h lj_ir.h lj_jit.h \
163 lj_iropt.h lj_trace.h lj_dispatch.h lj_traceerr.h lj_record.h \ 177 lj_ircall.h lj_iropt.h lj_trace.h lj_dispatch.h lj_traceerr.h \
164 lj_ffrecord.h lj_snap.h lj_vm.h 178 lj_record.h lj_ffrecord.h lj_snap.h lj_vm.h
165lj_snap.o: lj_snap.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 179lj_snap.o: lj_snap.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
166 lj_tab.h lj_state.h lj_frame.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h \ 180 lj_tab.h lj_state.h lj_frame.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h \
167 lj_trace.h lj_dispatch.h lj_traceerr.h lj_snap.h lj_target.h \ 181 lj_trace.h lj_dispatch.h lj_traceerr.h lj_snap.h lj_target.h \
168 lj_target_*.h lj_ctype.h lj_cdata.h 182 lj_target_*.h lj_ctype.h lj_cdata.h
169lj_state.o: lj_state.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 183lj_state.o: lj_state.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
170 lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_meta.h \ 184 lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_func.h \
171 lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_trace.h lj_jit.h lj_ir.h \ 185 lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_trace.h lj_jit.h \
172 lj_dispatch.h lj_traceerr.h lj_vm.h lj_lex.h lj_alloc.h 186 lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_lex.h lj_alloc.h luajit.h
173lj_str.o: lj_str.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 187lj_str.o: lj_str.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
174 lj_err.h lj_errmsg.h lj_str.h lj_state.h lj_char.h 188 lj_err.h lj_errmsg.h lj_str.h lj_char.h
189lj_strfmt.o: lj_strfmt.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
190 lj_buf.h lj_gc.h lj_str.h lj_state.h lj_char.h lj_strfmt.h
191lj_strfmt_num.o: lj_strfmt_num.c lj_obj.h lua.h luaconf.h lj_def.h \
192 lj_arch.h lj_buf.h lj_gc.h lj_str.h lj_strfmt.h
175lj_strscan.o: lj_strscan.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 193lj_strscan.o: lj_strscan.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
176 lj_char.h lj_strscan.h 194 lj_char.h lj_strscan.h
177lj_tab.o: lj_tab.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ 195lj_tab.o: lj_tab.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \
@@ -189,26 +207,27 @@ lj_vmevent.o: lj_vmevent.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
189lj_vmmath.o: lj_vmmath.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ 207lj_vmmath.o: lj_vmmath.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \
190 lj_ir.h lj_vm.h 208 lj_ir.h lj_vm.h
191ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_gc.c lj_obj.h lj_def.h \ 209ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_gc.c lj_obj.h lj_def.h \
192 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h \ 210 lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h \
193 lj_udata.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_cdata.h \ 211 lj_func.h lj_udata.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h \
194 lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_err.c \ 212 lj_cdata.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_traceerr.h \
195 lj_debug.h lj_ff.h lj_ffdef.h lj_char.c lj_char.h lj_bc.c lj_bcdef.h \ 213 lj_vm.h lj_err.c lj_debug.h lj_ff.h lj_ffdef.h lj_strfmt.h lj_char.c \
196 lj_obj.c lj_str.c lj_tab.c lj_func.c lj_udata.c lj_meta.c lj_strscan.h \ 214 lj_char.h lj_bc.c lj_bcdef.h lj_obj.c lj_buf.c lj_str.c lj_tab.c \
197 lj_debug.c lj_state.c lj_lex.h lj_alloc.h lj_dispatch.c lj_ccallback.h \ 215 lj_func.c lj_udata.c lj_meta.c lj_strscan.h lj_lib.h lj_debug.c \
198 luajit.h lj_vmevent.c lj_vmevent.h lj_vmmath.c lj_strscan.c lj_api.c \ 216 lj_state.c lj_lex.h lj_alloc.h luajit.h lj_dispatch.c lj_ccallback.h \
199 lj_lex.c lualib.h lj_parse.h lj_parse.c lj_bcread.c lj_bcdump.h \ 217 lj_profile.h lj_vmevent.c lj_vmevent.h lj_vmmath.c lj_strscan.c \
200 lj_bcwrite.c lj_load.c lj_ctype.c lj_cdata.c lj_cconv.h lj_cconv.c \ 218 lj_strfmt.c lj_strfmt_num.c lj_api.c lj_profile.c lj_lex.c lualib.h \
201 lj_ccall.c lj_ccall.h lj_ccallback.c lj_target.h lj_target_*.h \ 219 lj_parse.h lj_parse.c lj_bcread.c lj_bcdump.h lj_bcwrite.c lj_load.c \
202 lj_mcode.h lj_carith.c lj_carith.h lj_clib.c lj_clib.h lj_cparse.c \ 220 lj_ctype.c lj_cdata.c lj_cconv.h lj_cconv.c lj_ccall.c lj_ccall.h \
203 lj_cparse.h lj_lib.c lj_lib.h lj_ir.c lj_ircall.h lj_iropt.h \ 221 lj_ccallback.c lj_target.h lj_target_*.h lj_mcode.h lj_carith.c \
204 lj_opt_mem.c lj_opt_fold.c lj_folddef.h lj_opt_narrow.c lj_opt_dce.c \ 222 lj_carith.h lj_clib.c lj_clib.h lj_cparse.c lj_cparse.h lj_lib.c lj_ir.c \
205 lj_opt_loop.c lj_snap.h lj_opt_split.c lj_opt_sink.c lj_mcode.c \ 223 lj_ircall.h lj_iropt.h lj_opt_mem.c lj_opt_fold.c lj_folddef.h \
206 lj_snap.c lj_record.c lj_record.h lj_ffrecord.h lj_crecord.c \ 224 lj_opt_narrow.c lj_opt_dce.c lj_opt_loop.c lj_snap.h lj_opt_split.c \
207 lj_crecord.h lj_ffrecord.c lj_recdef.h lj_asm.c lj_asm.h lj_emit_*.h \ 225 lj_opt_sink.c lj_mcode.c lj_snap.c lj_record.c lj_record.h lj_ffrecord.h \
208 lj_asm_*.h lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c lib_aux.c \ 226 lj_crecord.c lj_crecord.h lj_ffrecord.c lj_recdef.h lj_asm.c lj_asm.h \
209 lib_base.c lj_libdef.h lib_math.c lib_string.c lib_table.c lib_io.c \ 227 lj_emit_*.h lj_asm_*.h lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c \
210 lib_os.c lib_package.c lib_debug.c lib_bit.c lib_jit.c lib_ffi.c \ 228 lib_aux.c lib_base.c lj_libdef.h lib_math.c lib_string.c lib_table.c \
211 lib_init.c 229 lib_io.c lib_os.c lib_package.c lib_debug.c lib_bit.c lib_jit.c \
230 lib_ffi.c lib_init.c
212luajit.o: luajit.c lua.h luaconf.h lauxlib.h lualib.h luajit.h lj_arch.h 231luajit.o: luajit.c lua.h luaconf.h lauxlib.h lualib.h luajit.h lj_arch.h
213host/buildvm.o: host/buildvm.c host/buildvm.h lj_def.h lua.h luaconf.h \ 232host/buildvm.o: host/buildvm.c host/buildvm.h lj_def.h lua.h luaconf.h \
214 lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_gc.h lj_obj.h lj_bc.h lj_ir.h \ 233 lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_gc.h lj_obj.h lj_bc.h lj_ir.h \
@@ -220,7 +239,8 @@ host/buildvm_asm.o: host/buildvm_asm.c host/buildvm.h lj_def.h lua.h luaconf.h \
220host/buildvm_fold.o: host/buildvm_fold.c host/buildvm.h lj_def.h lua.h \ 239host/buildvm_fold.o: host/buildvm_fold.c host/buildvm.h lj_def.h lua.h \
221 luaconf.h lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_ir.h lj_obj.h 240 luaconf.h lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_ir.h lj_obj.h
222host/buildvm_lib.o: host/buildvm_lib.c host/buildvm.h lj_def.h lua.h luaconf.h \ 241host/buildvm_lib.o: host/buildvm_lib.c host/buildvm.h lj_def.h lua.h luaconf.h \
223 lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_lib.h lj_obj.h 242 lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_bc.h lj_lib.h lj_obj.h \
243 host/buildvm_libbc.h
224host/buildvm_peobj.o: host/buildvm_peobj.c host/buildvm.h lj_def.h lua.h \ 244host/buildvm_peobj.o: host/buildvm_peobj.c host/buildvm.h lj_def.h lua.h \
225 luaconf.h lj_arch.h lj_bc.h lj_def.h lj_arch.h 245 luaconf.h lj_arch.h lj_bc.h lj_def.h lj_arch.h
226host/minilua.o: host/minilua.c 246host/minilua.o: host/minilua.c
diff --git a/src/host/buildvm.c b/src/host/buildvm.c
index b9560f31..de23fabd 100644
--- a/src/host/buildvm.c
+++ b/src/host/buildvm.c
@@ -59,10 +59,10 @@ static int collect_reloc(BuildCtx *ctx, uint8_t *addr, int idx, int type);
59#include "../dynasm/dasm_x86.h" 59#include "../dynasm/dasm_x86.h"
60#elif LJ_TARGET_ARM 60#elif LJ_TARGET_ARM
61#include "../dynasm/dasm_arm.h" 61#include "../dynasm/dasm_arm.h"
62#elif LJ_TARGET_ARM64
63#include "../dynasm/dasm_arm64.h"
62#elif LJ_TARGET_PPC 64#elif LJ_TARGET_PPC
63#include "../dynasm/dasm_ppc.h" 65#include "../dynasm/dasm_ppc.h"
64#elif LJ_TARGET_PPCSPE
65#include "../dynasm/dasm_ppc.h"
66#elif LJ_TARGET_MIPS 66#elif LJ_TARGET_MIPS
67#include "../dynasm/dasm_mips.h" 67#include "../dynasm/dasm_mips.h"
68#else 68#else
@@ -110,11 +110,11 @@ static const char *sym_decorate(BuildCtx *ctx,
110 if (p) { 110 if (p) {
111#if LJ_TARGET_X86ORX64 111#if LJ_TARGET_X86ORX64
112 if (!LJ_64 && (ctx->mode == BUILD_coffasm || ctx->mode == BUILD_peobj)) 112 if (!LJ_64 && (ctx->mode == BUILD_coffasm || ctx->mode == BUILD_peobj))
113 name[0] = '@'; 113 name[0] = name[1] == 'R' ? '_' : '@'; /* Just for _RtlUnwind@16. */
114 else 114 else
115 *p = '\0'; 115 *p = '\0';
116#elif (LJ_TARGET_PPC || LJ_TARGET_PPCSPE) && !LJ_TARGET_CONSOLE 116#elif LJ_TARGET_PPC && !LJ_TARGET_CONSOLE
117 /* Keep @plt. */ 117 /* Keep @plt etc. */
118#else 118#else
119 *p = '\0'; 119 *p = '\0';
120#endif 120#endif
@@ -179,6 +179,7 @@ static int build_code(BuildCtx *ctx)
179 ctx->nreloc = 0; 179 ctx->nreloc = 0;
180 180
181 ctx->globnames = globnames; 181 ctx->globnames = globnames;
182 ctx->extnames = extnames;
182 ctx->relocsym = (const char **)malloc(NRELOCSYM*sizeof(const char *)); 183 ctx->relocsym = (const char **)malloc(NRELOCSYM*sizeof(const char *));
183 ctx->nrelocsym = 0; 184 ctx->nrelocsym = 0;
184 for (i = 0; i < (int)NRELOCSYM; i++) relocmap[i] = -1; 185 for (i = 0; i < (int)NRELOCSYM; i++) relocmap[i] = -1;
@@ -320,20 +321,20 @@ static void emit_vmdef(BuildCtx *ctx)
320 char buf[80]; 321 char buf[80];
321 int i; 322 int i;
322 fprintf(ctx->fp, "-- This is a generated file. DO NOT EDIT!\n\n"); 323 fprintf(ctx->fp, "-- This is a generated file. DO NOT EDIT!\n\n");
323 fprintf(ctx->fp, "module(...)\n\n"); 324 fprintf(ctx->fp, "return {\n\n");
324 325
325 fprintf(ctx->fp, "bcnames = \""); 326 fprintf(ctx->fp, "bcnames = \"");
326 for (i = 0; bc_names[i]; i++) fprintf(ctx->fp, "%-6s", bc_names[i]); 327 for (i = 0; bc_names[i]; i++) fprintf(ctx->fp, "%-6s", bc_names[i]);
327 fprintf(ctx->fp, "\"\n\n"); 328 fprintf(ctx->fp, "\",\n\n");
328 329
329 fprintf(ctx->fp, "irnames = \""); 330 fprintf(ctx->fp, "irnames = \"");
330 for (i = 0; ir_names[i]; i++) fprintf(ctx->fp, "%-6s", ir_names[i]); 331 for (i = 0; ir_names[i]; i++) fprintf(ctx->fp, "%-6s", ir_names[i]);
331 fprintf(ctx->fp, "\"\n\n"); 332 fprintf(ctx->fp, "\",\n\n");
332 333
333 fprintf(ctx->fp, "irfpm = { [0]="); 334 fprintf(ctx->fp, "irfpm = { [0]=");
334 for (i = 0; irfpm_names[i]; i++) 335 for (i = 0; irfpm_names[i]; i++)
335 fprintf(ctx->fp, "\"%s\", ", lower(buf, irfpm_names[i])); 336 fprintf(ctx->fp, "\"%s\", ", lower(buf, irfpm_names[i]));
336 fprintf(ctx->fp, "}\n\n"); 337 fprintf(ctx->fp, "},\n\n");
337 338
338 fprintf(ctx->fp, "irfield = { [0]="); 339 fprintf(ctx->fp, "irfield = { [0]=");
339 for (i = 0; irfield_names[i]; i++) { 340 for (i = 0; irfield_names[i]; i++) {
@@ -343,17 +344,17 @@ static void emit_vmdef(BuildCtx *ctx)
343 if (p) *p = '.'; 344 if (p) *p = '.';
344 fprintf(ctx->fp, "\"%s\", ", buf); 345 fprintf(ctx->fp, "\"%s\", ", buf);
345 } 346 }
346 fprintf(ctx->fp, "}\n\n"); 347 fprintf(ctx->fp, "},\n\n");
347 348
348 fprintf(ctx->fp, "ircall = {\n[0]="); 349 fprintf(ctx->fp, "ircall = {\n[0]=");
349 for (i = 0; ircall_names[i]; i++) 350 for (i = 0; ircall_names[i]; i++)
350 fprintf(ctx->fp, "\"%s\",\n", ircall_names[i]); 351 fprintf(ctx->fp, "\"%s\",\n", ircall_names[i]);
351 fprintf(ctx->fp, "}\n\n"); 352 fprintf(ctx->fp, "},\n\n");
352 353
353 fprintf(ctx->fp, "traceerr = {\n[0]="); 354 fprintf(ctx->fp, "traceerr = {\n[0]=");
354 for (i = 0; trace_errors[i]; i++) 355 for (i = 0; trace_errors[i]; i++)
355 fprintf(ctx->fp, "\"%s\",\n", trace_errors[i]); 356 fprintf(ctx->fp, "\"%s\",\n", trace_errors[i]);
356 fprintf(ctx->fp, "}\n\n"); 357 fprintf(ctx->fp, "},\n\n");
357} 358}
358 359
359/* -- Argument parsing ---------------------------------------------------- */ 360/* -- Argument parsing ---------------------------------------------------- */
@@ -490,6 +491,7 @@ int main(int argc, char **argv)
490 case BUILD_vmdef: 491 case BUILD_vmdef:
491 emit_vmdef(ctx); 492 emit_vmdef(ctx);
492 emit_lib(ctx); 493 emit_lib(ctx);
494 fprintf(ctx->fp, "}\n\n");
493 break; 495 break;
494 case BUILD_ffdef: 496 case BUILD_ffdef:
495 case BUILD_libdef: 497 case BUILD_libdef:
diff --git a/src/host/buildvm.h b/src/host/buildvm.h
index e6dd3dcb..b90428dc 100644
--- a/src/host/buildvm.h
+++ b/src/host/buildvm.h
@@ -82,6 +82,7 @@ typedef struct BuildCtx {
82 const char *beginsym; 82 const char *beginsym;
83 /* Strings generated by DynASM. */ 83 /* Strings generated by DynASM. */
84 const char *const *globnames; 84 const char *const *globnames;
85 const char *const *extnames;
85 const char *dasm_ident; 86 const char *dasm_ident;
86 const char *dasm_arch; 87 const char *dasm_arch;
87 /* Relocations. */ 88 /* Relocations. */
diff --git a/src/host/buildvm_asm.c b/src/host/buildvm_asm.c
index 368f9394..addf281f 100644
--- a/src/host/buildvm_asm.c
+++ b/src/host/buildvm_asm.c
@@ -51,8 +51,8 @@ static const char *const jccnames[] = {
51 "js", "jns", "jpe", "jpo", "jl", "jge", "jle", "jg" 51 "js", "jns", "jpe", "jpo", "jl", "jge", "jle", "jg"
52}; 52};
53 53
54/* Emit relocation for the incredibly stupid OSX assembler. */ 54/* Emit x86/x64 text relocations. */
55static void emit_asm_reloc_mach(BuildCtx *ctx, uint8_t *cp, int n, 55static void emit_asm_reloc_text(BuildCtx *ctx, uint8_t *cp, int n,
56 const char *sym) 56 const char *sym)
57{ 57{
58 const char *opname = NULL; 58 const char *opname = NULL;
@@ -71,6 +71,20 @@ err:
71 exit(1); 71 exit(1);
72 } 72 }
73 emit_asm_bytes(ctx, cp, n); 73 emit_asm_bytes(ctx, cp, n);
74 if (strncmp(sym+(*sym == '_'), LABEL_PREFIX, sizeof(LABEL_PREFIX)-1)) {
75 /* Various fixups for external symbols outside of our binary. */
76 if (ctx->mode == BUILD_elfasm) {
77 if (LJ_32)
78 fprintf(ctx->fp, "#if __PIC__\n\t%s lj_wrap_%s\n#else\n", opname, sym);
79 fprintf(ctx->fp, "\t%s %s@PLT\n", opname, sym);
80 if (LJ_32)
81 fprintf(ctx->fp, "#endif\n");
82 return;
83 } else if (LJ_32 && ctx->mode == BUILD_machasm) {
84 fprintf(ctx->fp, "\t%s L%s$stub\n", opname, sym);
85 return;
86 }
87 }
74 fprintf(ctx->fp, "\t%s %s\n", opname, sym); 88 fprintf(ctx->fp, "\t%s %s\n", opname, sym);
75} 89}
76#else 90#else
@@ -107,7 +121,16 @@ static void emit_asm_wordreloc(BuildCtx *ctx, uint8_t *p, int n,
107 ins, sym); 121 ins, sym);
108 exit(1); 122 exit(1);
109 } 123 }
110#elif LJ_TARGET_PPC || LJ_TARGET_PPCSPE 124#elif LJ_TARGET_ARM64
125 if ((ins >> 26) == 0x25u) {
126 fprintf(ctx->fp, "\tbl %s\n", sym);
127 } else {
128 fprintf(stderr,
129 "Error: unsupported opcode %08x for %s symbol relocation.\n",
130 ins, sym);
131 exit(1);
132 }
133#elif LJ_TARGET_PPC
111#if LJ_TARGET_PS3 134#if LJ_TARGET_PS3
112#define TOCPREFIX "." 135#define TOCPREFIX "."
113#else 136#else
@@ -117,6 +140,14 @@ static void emit_asm_wordreloc(BuildCtx *ctx, uint8_t *p, int n,
117 fprintf(ctx->fp, "\t%s %d, %d, " TOCPREFIX "%s\n", 140 fprintf(ctx->fp, "\t%s %d, %d, " TOCPREFIX "%s\n",
118 (ins & 1) ? "bcl" : "bc", (ins >> 21) & 31, (ins >> 16) & 31, sym); 141 (ins & 1) ? "bcl" : "bc", (ins >> 21) & 31, (ins >> 16) & 31, sym);
119 } else if ((ins >> 26) == 18) { 142 } else if ((ins >> 26) == 18) {
143#if LJ_ARCH_PPC64
144 const char *suffix = strchr(sym, '@');
145 if (suffix && suffix[1] == 'h') {
146 fprintf(ctx->fp, "\taddis 11, 2, %s\n", sym);
147 } else if (suffix && suffix[1] == 'l') {
148 fprintf(ctx->fp, "\tld 12, %s\n", sym);
149 } else
150#endif
120 fprintf(ctx->fp, "\t%s " TOCPREFIX "%s\n", (ins & 1) ? "bl" : "b", sym); 151 fprintf(ctx->fp, "\t%s " TOCPREFIX "%s\n", (ins & 1) ? "bl" : "b", sym);
121 } else { 152 } else {
122 fprintf(stderr, 153 fprintf(stderr,
@@ -214,6 +245,9 @@ void emit_asm(BuildCtx *ctx)
214 int i, rel; 245 int i, rel;
215 246
216 fprintf(ctx->fp, "\t.file \"buildvm_%s.dasc\"\n", ctx->dasm_arch); 247 fprintf(ctx->fp, "\t.file \"buildvm_%s.dasc\"\n", ctx->dasm_arch);
248#if LJ_ARCH_PPC64
249 fprintf(ctx->fp, "\t.abiversion 2\n");
250#endif
217 fprintf(ctx->fp, "\t.text\n"); 251 fprintf(ctx->fp, "\t.text\n");
218 emit_asm_align(ctx, 4); 252 emit_asm_align(ctx, 4);
219 253
@@ -227,11 +261,20 @@ void emit_asm(BuildCtx *ctx)
227 261
228#if LJ_TARGET_ARM && defined(__GNUC__) && !LJ_NO_UNWIND 262#if LJ_TARGET_ARM && defined(__GNUC__) && !LJ_NO_UNWIND
229 /* This should really be moved into buildvm_arm.dasc. */ 263 /* This should really be moved into buildvm_arm.dasc. */
264#if LJ_ARCH_HASFPU
265 fprintf(ctx->fp,
266 ".fnstart\n"
267 ".save {r5, r6, r7, r8, r9, r10, r11, lr}\n"
268 ".vsave {d8-d15}\n"
269 ".save {r4}\n"
270 ".pad #28\n");
271#else
230 fprintf(ctx->fp, 272 fprintf(ctx->fp,
231 ".fnstart\n" 273 ".fnstart\n"
232 ".save {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n" 274 ".save {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n"
233 ".pad #28\n"); 275 ".pad #28\n");
234#endif 276#endif
277#endif
235#if LJ_TARGET_MIPS 278#if LJ_TARGET_MIPS
236 fprintf(ctx->fp, ".set nomips16\n.abicalls\n.set noreorder\n.set nomacro\n"); 279 fprintf(ctx->fp, ".set nomips16\n.abicalls\n.set noreorder\n.set nomacro\n");
237#endif 280#endif
@@ -254,8 +297,9 @@ void emit_asm(BuildCtx *ctx)
254 BuildReloc *r = &ctx->reloc[rel]; 297 BuildReloc *r = &ctx->reloc[rel];
255 int n = r->ofs - ofs; 298 int n = r->ofs - ofs;
256#if LJ_TARGET_X86ORX64 299#if LJ_TARGET_X86ORX64
257 if (ctx->mode == BUILD_machasm && r->type != 0) { 300 if (r->type != 0 &&
258 emit_asm_reloc_mach(ctx, ctx->code+ofs, n, ctx->relocsym[r->sym]); 301 (ctx->mode == BUILD_elfasm || ctx->mode == BUILD_machasm)) {
302 emit_asm_reloc_text(ctx, ctx->code+ofs, n, ctx->relocsym[r->sym]);
259 } else { 303 } else {
260 emit_asm_bytes(ctx, ctx->code+ofs, n); 304 emit_asm_bytes(ctx, ctx->code+ofs, n);
261 emit_asm_reloc(ctx, r->type, ctx->relocsym[r->sym]); 305 emit_asm_reloc(ctx, r->type, ctx->relocsym[r->sym]);
@@ -289,10 +333,7 @@ void emit_asm(BuildCtx *ctx)
289#if !(LJ_TARGET_PS3 || LJ_TARGET_PSVITA) 333#if !(LJ_TARGET_PS3 || LJ_TARGET_PSVITA)
290 fprintf(ctx->fp, "\t.section .note.GNU-stack,\"\"," ELFASM_PX "progbits\n"); 334 fprintf(ctx->fp, "\t.section .note.GNU-stack,\"\"," ELFASM_PX "progbits\n");
291#endif 335#endif
292#if LJ_TARGET_PPCSPE 336#if LJ_TARGET_PPC && !LJ_TARGET_PS3
293 /* Soft-float ABI + SPE. */
294 fprintf(ctx->fp, "\t.gnu_attribute 4, 2\n\t.gnu_attribute 8, 3\n");
295#elif LJ_TARGET_PPC && !LJ_TARGET_PS3
296 /* Hard-float ABI. */ 337 /* Hard-float ABI. */
297 fprintf(ctx->fp, "\t.gnu_attribute 4, 1\n"); 338 fprintf(ctx->fp, "\t.gnu_attribute 4, 1\n");
298#endif 339#endif
diff --git a/src/host/buildvm_lib.c b/src/host/buildvm_lib.c
index 569e2caf..2956fdb6 100644
--- a/src/host/buildvm_lib.c
+++ b/src/host/buildvm_lib.c
@@ -5,7 +5,9 @@
5 5
6#include "buildvm.h" 6#include "buildvm.h"
7#include "lj_obj.h" 7#include "lj_obj.h"
8#include "lj_bc.h"
8#include "lj_lib.h" 9#include "lj_lib.h"
10#include "buildvm_libbc.h"
9 11
10/* Context for library definitions. */ 12/* Context for library definitions. */
11static uint8_t obuf[8192]; 13static uint8_t obuf[8192];
@@ -151,6 +153,62 @@ static void libdef_func(BuildCtx *ctx, char *p, int arg)
151 regfunc = REGFUNC_OK; 153 regfunc = REGFUNC_OK;
152} 154}
153 155
156static uint8_t *libdef_uleb128(uint8_t *p, uint32_t *vv)
157{
158 uint32_t v = *p++;
159 if (v >= 0x80) {
160 int sh = 0; v &= 0x7f;
161 do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80);
162 }
163 *vv = v;
164 return p;
165}
166
167static void libdef_fixupbc(uint8_t *p)
168{
169 uint32_t i, sizebc;
170 p += 4;
171 p = libdef_uleb128(p, &sizebc);
172 p = libdef_uleb128(p, &sizebc);
173 p = libdef_uleb128(p, &sizebc);
174 for (i = 0; i < sizebc; i++, p += 4) {
175 uint8_t op = p[libbc_endian ? 3 : 0];
176 uint8_t ra = p[libbc_endian ? 2 : 1];
177 uint8_t rc = p[libbc_endian ? 1 : 2];
178 uint8_t rb = p[libbc_endian ? 0 : 3];
179 if (!LJ_DUALNUM && op == BC_ISTYPE && rc == ~LJ_TNUMX+1) {
180 op = BC_ISNUM; rc++;
181 }
182 p[LJ_ENDIAN_SELECT(0, 3)] = op;
183 p[LJ_ENDIAN_SELECT(1, 2)] = ra;
184 p[LJ_ENDIAN_SELECT(2, 1)] = rc;
185 p[LJ_ENDIAN_SELECT(3, 0)] = rb;
186 }
187}
188
189static void libdef_lua(BuildCtx *ctx, char *p, int arg)
190{
191 UNUSED(arg);
192 if (ctx->mode == BUILD_libdef) {
193 int i;
194 for (i = 0; libbc_map[i].name != NULL; i++) {
195 if (!strcmp(libbc_map[i].name, p)) {
196 int ofs = libbc_map[i].ofs;
197 int len = libbc_map[i+1].ofs - ofs;
198 obuf[2]++; /* Bump hash table size. */
199 *optr++ = LIBINIT_LUA;
200 libdef_name(p, 0);
201 memcpy(optr, libbc_code + ofs, len);
202 libdef_fixupbc(optr);
203 optr += len;
204 return;
205 }
206 }
207 fprintf(stderr, "Error: missing libbc definition for %s\n", p);
208 exit(1);
209 }
210}
211
154static uint32_t find_rec(char *name) 212static uint32_t find_rec(char *name)
155{ 213{
156 char *p = (char *)obuf; 214 char *p = (char *)obuf;
@@ -277,6 +335,7 @@ static const LibDefHandler libdef_handlers[] = {
277 { "CF(", ")", libdef_func, LIBINIT_CF }, 335 { "CF(", ")", libdef_func, LIBINIT_CF },
278 { "ASM(", ")", libdef_func, LIBINIT_ASM }, 336 { "ASM(", ")", libdef_func, LIBINIT_ASM },
279 { "ASM_(", ")", libdef_func, LIBINIT_ASM_ }, 337 { "ASM_(", ")", libdef_func, LIBINIT_ASM_ },
338 { "LUA(", ")", libdef_lua, 0 },
280 { "REC(", ")", libdef_rec, 0 }, 339 { "REC(", ")", libdef_rec, 0 },
281 { "PUSH(", ")", libdef_push, 0 }, 340 { "PUSH(", ")", libdef_push, 0 },
282 { "SET(", ")", libdef_set, 0 }, 341 { "SET(", ")", libdef_set, 0 },
@@ -373,7 +432,7 @@ void emit_lib(BuildCtx *ctx)
373 "#ifndef FF_NUM_ASMFUNC\n#define FF_NUM_ASMFUNC %d\n#endif\n\n", 432 "#ifndef FF_NUM_ASMFUNC\n#define FF_NUM_ASMFUNC %d\n#endif\n\n",
374 ffasmfunc); 433 ffasmfunc);
375 } else if (ctx->mode == BUILD_vmdef) { 434 } else if (ctx->mode == BUILD_vmdef) {
376 fprintf(ctx->fp, "}\n\n"); 435 fprintf(ctx->fp, "},\n\n");
377 } else if (ctx->mode == BUILD_bcdef) { 436 } else if (ctx->mode == BUILD_bcdef) {
378 int i; 437 int i;
379 fprintf(ctx->fp, "\n};\n\n"); 438 fprintf(ctx->fp, "\n};\n\n");
diff --git a/src/host/buildvm_libbc.h b/src/host/buildvm_libbc.h
new file mode 100644
index 00000000..b2600bd5
--- /dev/null
+++ b/src/host/buildvm_libbc.h
@@ -0,0 +1,56 @@
1/* This is a generated file. DO NOT EDIT! */
2
3static const int libbc_endian = 0;
4
5static const uint8_t libbc_code[] = {
6#if LJ_FR2
70,1,2,0,0,1,2,24,1,0,0,76,1,2,0,241,135,158,166,3,220,203,178,130,4,0,1,2,0,
80,1,2,24,1,0,0,76,1,2,0,243,244,148,165,20,198,190,199,252,3,0,1,2,0,0,0,3,
916,0,5,0,21,1,0,0,76,1,2,0,0,2,10,0,0,0,15,16,0,12,0,16,1,9,0,41,2,1,0,21,3,
100,0,41,4,1,0,77,2,8,128,18,6,1,0,18,8,5,0,59,9,5,0,66,6,3,2,10,6,0,0,88,7,1,
11128,76,6,2,0,79,2,248,127,75,0,1,0,0,2,11,0,0,0,16,16,0,12,0,16,1,9,0,43,2,
120,0,18,3,0,0,41,4,0,0,88,5,7,128,18,7,1,0,18,9,5,0,18,10,6,0,66,7,3,2,10,7,
130,0,88,8,1,128,76,7,2,0,70,5,3,3,82,5,247,127,75,0,1,0,0,1,2,0,0,0,3,16,0,12,
140,21,1,0,0,76,1,2,0,0,2,10,0,0,2,30,16,0,12,0,21,2,0,0,11,1,0,0,88,3,7,128,
158,2,0,0,88,3,23,128,59,3,2,0,43,4,0,0,64,4,2,0,76,3,2,0,88,3,18,128,16,1,14,
160,41,3,1,0,3,3,1,0,88,3,14,128,3,1,2,0,88,3,12,128,59,3,1,0,22,4,1,1,18,5,2,
170,41,6,1,0,77,4,4,128,23,8,1,7,59,9,7,0,64,9,8,0,79,4,252,127,43,4,0,0,64,4,
182,0,76,3,2,0,75,0,1,0,0,2,0,5,12,0,0,0,35,16,0,12,0,16,1,14,0,16,2,14,0,16,
193,14,0,11,4,0,0,88,5,1,128,18,4,0,0,16,4,12,0,3,1,2,0,88,5,24,128,33,5,1,3,
200,2,3,0,88,6,4,128,2,3,1,0,88,6,2,128,4,4,0,0,88,6,9,128,18,6,1,0,18,7,2,0,
2141,8,1,0,77,6,4,128,32,10,5,9,59,11,9,0,64,11,10,4,79,6,252,127,88,6,8,128,
2218,6,2,0,18,7,1,0,41,8,255,255,77,6,4,128,32,10,5,9,59,11,9,0,64,11,10,4,79,
236,252,127,76,4,2,0,0
24#else
250,1,2,0,0,1,2,24,1,0,0,76,1,2,0,241,135,158,166,3,220,203,178,130,4,0,1,2,0,
260,1,2,24,1,0,0,76,1,2,0,243,244,148,165,20,198,190,199,252,3,0,1,2,0,0,0,3,
2716,0,5,0,21,1,0,0,76,1,2,0,0,2,9,0,0,0,15,16,0,12,0,16,1,9,0,41,2,1,0,21,3,
280,0,41,4,1,0,77,2,8,128,18,6,1,0,18,7,5,0,59,8,5,0,66,6,3,2,10,6,0,0,88,7,1,
29128,76,6,2,0,79,2,248,127,75,0,1,0,0,2,10,0,0,0,16,16,0,12,0,16,1,9,0,43,2,
300,0,18,3,0,0,41,4,0,0,88,5,7,128,18,7,1,0,18,8,5,0,18,9,6,0,66,7,3,2,10,7,0,
310,88,8,1,128,76,7,2,0,70,5,3,3,82,5,247,127,75,0,1,0,0,1,2,0,0,0,3,16,0,12,
320,21,1,0,0,76,1,2,0,0,2,10,0,0,2,30,16,0,12,0,21,2,0,0,11,1,0,0,88,3,7,128,
338,2,0,0,88,3,23,128,59,3,2,0,43,4,0,0,64,4,2,0,76,3,2,0,88,3,18,128,16,1,14,
340,41,3,1,0,3,3,1,0,88,3,14,128,3,1,2,0,88,3,12,128,59,3,1,0,22,4,1,1,18,5,2,
350,41,6,1,0,77,4,4,128,23,8,1,7,59,9,7,0,64,9,8,0,79,4,252,127,43,4,0,0,64,4,
362,0,76,3,2,0,75,0,1,0,0,2,0,5,12,0,0,0,35,16,0,12,0,16,1,14,0,16,2,14,0,16,
373,14,0,11,4,0,0,88,5,1,128,18,4,0,0,16,4,12,0,3,1,2,0,88,5,24,128,33,5,1,3,
380,2,3,0,88,6,4,128,2,3,1,0,88,6,2,128,4,4,0,0,88,6,9,128,18,6,1,0,18,7,2,0,
3941,8,1,0,77,6,4,128,32,10,5,9,59,11,9,0,64,11,10,4,79,6,252,127,88,6,8,128,
4018,6,2,0,18,7,1,0,41,8,255,255,77,6,4,128,32,10,5,9,59,11,9,0,64,11,10,4,79,
416,252,127,76,4,2,0,0
42#endif
43};
44
45static const struct { const char *name; int ofs; } libbc_map[] = {
46{"math_deg",0},
47{"math_rad",25},
48{"string_len",50},
49{"table_foreachi",69},
50{"table_foreach",136},
51{"table_getn",207},
52{"table_remove",226},
53{"table_move",355},
54{NULL,502}
55};
56
diff --git a/src/host/buildvm_peobj.c b/src/host/buildvm_peobj.c
index aab00d68..2eb2bb7b 100644
--- a/src/host/buildvm_peobj.c
+++ b/src/host/buildvm_peobj.c
@@ -109,6 +109,8 @@ enum {
109#if LJ_TARGET_X64 109#if LJ_TARGET_X64
110 PEOBJ_SECT_PDATA, 110 PEOBJ_SECT_PDATA,
111 PEOBJ_SECT_XDATA, 111 PEOBJ_SECT_XDATA,
112#elif LJ_TARGET_X86
113 PEOBJ_SECT_SXDATA,
112#endif 114#endif
113 PEOBJ_SECT_RDATA_Z, 115 PEOBJ_SECT_RDATA_Z,
114 PEOBJ_NSECTIONS 116 PEOBJ_NSECTIONS
@@ -208,6 +210,13 @@ void emit_peobj(BuildCtx *ctx)
208 sofs += (pesect[PEOBJ_SECT_XDATA].nreloc = 1) * PEOBJ_RELOC_SIZE; 210 sofs += (pesect[PEOBJ_SECT_XDATA].nreloc = 1) * PEOBJ_RELOC_SIZE;
209 /* Flags: 40 = read, 30 = align4, 40 = initialized data. */ 211 /* Flags: 40 = read, 30 = align4, 40 = initialized data. */
210 pesect[PEOBJ_SECT_XDATA].flags = 0x40300040; 212 pesect[PEOBJ_SECT_XDATA].flags = 0x40300040;
213#elif LJ_TARGET_X86
214 memcpy(pesect[PEOBJ_SECT_SXDATA].name, ".sxdata", sizeof(".sxdata")-1);
215 pesect[PEOBJ_SECT_SXDATA].ofs = sofs;
216 sofs += (pesect[PEOBJ_SECT_SXDATA].size = 4);
217 pesect[PEOBJ_SECT_SXDATA].relocofs = sofs;
218 /* Flags: 40 = read, 30 = align4, 02 = lnk_info, 40 = initialized data. */
219 pesect[PEOBJ_SECT_SXDATA].flags = 0x40300240;
211#endif 220#endif
212 221
213 memcpy(pesect[PEOBJ_SECT_RDATA_Z].name, ".rdata$Z", sizeof(".rdata$Z")-1); 222 memcpy(pesect[PEOBJ_SECT_RDATA_Z].name, ".rdata$Z", sizeof(".rdata$Z")-1);
@@ -232,7 +241,7 @@ void emit_peobj(BuildCtx *ctx)
232 nrsym = ctx->nrelocsym; 241 nrsym = ctx->nrelocsym;
233 pehdr.nsyms = 1+PEOBJ_NSECTIONS*2 + 1+ctx->nsym + nrsym; 242 pehdr.nsyms = 1+PEOBJ_NSECTIONS*2 + 1+ctx->nsym + nrsym;
234#if LJ_TARGET_X64 243#if LJ_TARGET_X64
235 pehdr.nsyms += 1; /* Symbol for lj_err_unwind_win64. */ 244 pehdr.nsyms += 1; /* Symbol for lj_err_unwind_win. */
236#endif 245#endif
237 246
238 /* Write PE object header and all sections. */ 247 /* Write PE object header and all sections. */
@@ -312,6 +321,19 @@ void emit_peobj(BuildCtx *ctx)
312 reloc.type = PEOBJ_RELOC_ADDR32NB; 321 reloc.type = PEOBJ_RELOC_ADDR32NB;
313 owrite(ctx, &reloc, PEOBJ_RELOC_SIZE); 322 owrite(ctx, &reloc, PEOBJ_RELOC_SIZE);
314 } 323 }
324#elif LJ_TARGET_X86
325 /* Write .sxdata section. */
326 for (i = 0; i < nrsym; i++) {
327 if (!strcmp(ctx->relocsym[i], "_lj_err_unwind_win")) {
328 uint32_t symidx = 1+2+i;
329 owrite(ctx, &symidx, 4);
330 break;
331 }
332 }
333 if (i == nrsym) {
334 fprintf(stderr, "Error: extern lj_err_unwind_win not used\n");
335 exit(1);
336 }
315#endif 337#endif
316 338
317 /* Write .rdata$Z section. */ 339 /* Write .rdata$Z section. */
@@ -333,8 +355,10 @@ void emit_peobj(BuildCtx *ctx)
333#if LJ_TARGET_X64 355#if LJ_TARGET_X64
334 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_PDATA); 356 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_PDATA);
335 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_XDATA); 357 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_XDATA);
336 emit_peobj_sym(ctx, "lj_err_unwind_win64", 0, 358 emit_peobj_sym(ctx, "lj_err_unwind_win", 0,
337 PEOBJ_SECT_UNDEF, PEOBJ_TYPE_FUNC, PEOBJ_SCL_EXTERN); 359 PEOBJ_SECT_UNDEF, PEOBJ_TYPE_FUNC, PEOBJ_SCL_EXTERN);
360#elif LJ_TARGET_X86
361 emit_peobj_sym_sect(ctx, pesect, PEOBJ_SECT_SXDATA);
338#endif 362#endif
339 363
340 emit_peobj_sym(ctx, ctx->beginsym, 0, 364 emit_peobj_sym(ctx, ctx->beginsym, 0,
diff --git a/src/host/genlibbc.lua b/src/host/genlibbc.lua
new file mode 100644
index 00000000..6f5a05cc
--- /dev/null
+++ b/src/host/genlibbc.lua
@@ -0,0 +1,197 @@
1----------------------------------------------------------------------------
2-- Lua script to dump the bytecode of the library functions written in Lua.
3-- The resulting 'buildvm_libbc.h' is used for the build process of LuaJIT.
4----------------------------------------------------------------------------
5-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
6-- Released under the MIT license. See Copyright Notice in luajit.h
7----------------------------------------------------------------------------
8
9local ffi = require("ffi")
10local bit = require("bit")
11local vmdef = require("jit.vmdef")
12local bcnames = vmdef.bcnames
13
14local format = string.format
15
16local isbe = (string.byte(string.dump(function() end), 5) % 2 == 1)
17
18local function usage(arg)
19 io.stderr:write("Usage: ", arg and arg[0] or "genlibbc",
20 " [-o buildvm_libbc.h] lib_*.c\n")
21 os.exit(1)
22end
23
24local function parse_arg(arg)
25 local outfile = "-"
26 if not (arg and arg[1]) then
27 usage(arg)
28 end
29 if arg[1] == "-o" then
30 outfile = arg[2]
31 if not outfile then usage(arg) end
32 table.remove(arg, 1)
33 table.remove(arg, 1)
34 end
35 return outfile
36end
37
38local function read_files(names)
39 local src = ""
40 for _,name in ipairs(names) do
41 local fp = assert(io.open(name))
42 src = src .. fp:read("*a")
43 fp:close()
44 end
45 return src
46end
47
48local function transform_lua(code)
49 local fixup = {}
50 local n = -30000
51 code = string.gsub(code, "CHECK_(%w*)%((.-)%)", function(tp, var)
52 n = n + 1
53 fixup[n] = { "CHECK", tp }
54 return format("%s=%d", var, n)
55 end)
56 code = string.gsub(code, "PAIRS%((.-)%)", function(var)
57 fixup.PAIRS = true
58 return format("nil, %s, 0", var)
59 end)
60 return "return "..code, fixup
61end
62
63local function read_uleb128(p)
64 local v = p[0]; p = p + 1
65 if v >= 128 then
66 local sh = 7; v = v - 128
67 repeat
68 local r = p[0]
69 v = v + bit.lshift(bit.band(r, 127), sh)
70 sh = sh + 7
71 p = p + 1
72 until r < 128
73 end
74 return p, v
75end
76
77-- ORDER LJ_T
78local name2itype = {
79 str = 5, func = 9, tab = 12, int = 14, num = 15
80}
81
82local BC = {}
83for i=0,#bcnames/6-1 do
84 BC[string.gsub(string.sub(bcnames, i*6+1, i*6+6), " ", "")] = i
85end
86local xop, xra = isbe and 3 or 0, isbe and 2 or 1
87local xrc, xrb = isbe and 1 or 2, isbe and 0 or 3
88
89local function fixup_dump(dump, fixup)
90 local buf = ffi.new("uint8_t[?]", #dump+1, dump)
91 local p = buf+5
92 local n, sizebc
93 p, n = read_uleb128(p)
94 local start = p
95 p = p + 4
96 p = read_uleb128(p)
97 p = read_uleb128(p)
98 p, sizebc = read_uleb128(p)
99 local rawtab = {}
100 for i=0,sizebc-1 do
101 local op = p[xop]
102 if op == BC.KSHORT then
103 local rd = p[xrc] + 256*p[xrb]
104 rd = bit.arshift(bit.lshift(rd, 16), 16)
105 local f = fixup[rd]
106 if f then
107 if f[1] == "CHECK" then
108 local tp = f[2]
109 if tp == "tab" then rawtab[p[xra]] = true end
110 p[xop] = tp == "num" and BC.ISNUM or BC.ISTYPE
111 p[xrb] = 0
112 p[xrc] = name2itype[tp]
113 else
114 error("unhandled fixup type: "..f[1])
115 end
116 end
117 elseif op == BC.TGETV then
118 if rawtab[p[xrb]] then
119 p[xop] = BC.TGETR
120 end
121 elseif op == BC.TSETV then
122 if rawtab[p[xrb]] then
123 p[xop] = BC.TSETR
124 end
125 elseif op == BC.ITERC then
126 if fixup.PAIRS then
127 p[xop] = BC.ITERN
128 end
129 end
130 p = p + 4
131 end
132 return ffi.string(start, n)
133end
134
135local function find_defs(src)
136 local defs = {}
137 for name, code in string.gmatch(src, "LJLIB_LUA%(([^)]*)%)%s*/%*(.-)%*/") do
138 local env = {}
139 local tcode, fixup = transform_lua(code)
140 local func = assert(load(tcode, "", nil, env))()
141 defs[name] = fixup_dump(string.dump(func, true), fixup)
142 defs[#defs+1] = name
143 end
144 return defs
145end
146
147local function gen_header(defs)
148 local t = {}
149 local function w(x) t[#t+1] = x end
150 w("/* This is a generated file. DO NOT EDIT! */\n\n")
151 w("static const int libbc_endian = ") w(isbe and 1 or 0) w(";\n\n")
152 local s = ""
153 for _,name in ipairs(defs) do
154 s = s .. defs[name]
155 end
156 w("static const uint8_t libbc_code[] = {\n")
157 local n = 0
158 for i=1,#s do
159 local x = string.byte(s, i)
160 w(x); w(",")
161 n = n + (x < 10 and 2 or (x < 100 and 3 or 4))
162 if n >= 75 then n = 0; w("\n") end
163 end
164 w("0\n};\n\n")
165 w("static const struct { const char *name; int ofs; } libbc_map[] = {\n")
166 local m = 0
167 for _,name in ipairs(defs) do
168 w('{"'); w(name); w('",'); w(m) w('},\n')
169 m = m + #defs[name]
170 end
171 w("{NULL,"); w(m); w("}\n};\n\n")
172 return table.concat(t)
173end
174
175local function write_file(name, data)
176 if name == "-" then
177 assert(io.write(data))
178 assert(io.flush())
179 else
180 local fp = io.open(name)
181 if fp then
182 local old = fp:read("*a")
183 fp:close()
184 if data == old then return end
185 end
186 fp = assert(io.open(name, "w"))
187 assert(fp:write(data))
188 assert(fp:close())
189 end
190end
191
192local outfile = parse_arg(arg)
193local src = read_files(arg)
194local defs = find_defs(src)
195local hdr = gen_header(defs)
196write_file(outfile, hdr)
197
diff --git a/src/jit/bc.lua b/src/jit/bc.lua
index a4cd5f20..193cf01f 100644
--- a/src/jit/bc.lua
+++ b/src/jit/bc.lua
@@ -41,7 +41,7 @@
41 41
42-- Cache some library functions and objects. 42-- Cache some library functions and objects.
43local jit = require("jit") 43local jit = require("jit")
44assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") 44assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
45local jutil = require("jit.util") 45local jutil = require("jit.util")
46local vmdef = require("jit.vmdef") 46local vmdef = require("jit.vmdef")
47local bit = require("bit") 47local bit = require("bit")
@@ -179,13 +179,12 @@ local function bcliston(outfile)
179end 179end
180 180
181-- Public module functions. 181-- Public module functions.
182module(...) 182return {
183 183 line = bcline,
184line = bcline 184 dump = bcdump,
185dump = bcdump 185 targets = bctargets,
186targets = bctargets 186 on = bcliston,
187 187 off = bclistoff,
188on = bcliston 188 start = bcliston -- For -j command line option.
189off = bclistoff 189}
190start = bcliston -- For -j command line option.
191 190
diff --git a/src/jit/bcsave.lua b/src/jit/bcsave.lua
index d548b1a7..9ee22a01 100644
--- a/src/jit/bcsave.lua
+++ b/src/jit/bcsave.lua
@@ -11,7 +11,7 @@
11------------------------------------------------------------------------------ 11------------------------------------------------------------------------------
12 12
13local jit = require("jit") 13local jit = require("jit")
14assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") 14assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
15local bit = require("bit") 15local bit = require("bit")
16 16
17-- Symbol name prefix for LuaJIT bytecode. 17-- Symbol name prefix for LuaJIT bytecode.
@@ -63,7 +63,7 @@ local map_type = {
63} 63}
64 64
65local map_arch = { 65local map_arch = {
66 x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true, 66 x86 = true, x64 = true, arm = true, arm64 = true, ppc = true,
67 mips = true, mipsel = true, 67 mips = true, mipsel = true,
68} 68}
69 69
@@ -125,12 +125,12 @@ extern "C"
125#ifdef _WIN32 125#ifdef _WIN32
126__declspec(dllexport) 126__declspec(dllexport)
127#endif 127#endif
128const char %s%s[] = { 128const unsigned char %s%s[] = {
129]], LJBC_PREFIX, ctx.modname)) 129]], LJBC_PREFIX, ctx.modname))
130 else 130 else
131 fp:write(string.format([[ 131 fp:write(string.format([[
132#define %s%s_SIZE %d 132#define %s%s_SIZE %d
133static const char %s%s[] = { 133static const unsigned char %s%s[] = {
134]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) 134]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname))
135 end 135 end
136 local t, n, m = {}, 0, 0 136 local t, n, m = {}, 0, 0
@@ -200,9 +200,9 @@ typedef struct {
200]] 200]]
201 local symname = LJBC_PREFIX..ctx.modname 201 local symname = LJBC_PREFIX..ctx.modname
202 local is64, isbe = false, false 202 local is64, isbe = false, false
203 if ctx.arch == "x64" then 203 if ctx.arch == "x64" or ctx.arch == "arm64" then
204 is64 = true 204 is64 = true
205 elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then 205 elseif ctx.arch == "ppc" or ctx.arch == "mips" then
206 isbe = true 206 isbe = true
207 end 207 end
208 208
@@ -237,7 +237,7 @@ typedef struct {
237 hdr.eendian = isbe and 2 or 1 237 hdr.eendian = isbe and 2 or 1
238 hdr.eversion = 1 238 hdr.eversion = 1
239 hdr.type = f16(1) 239 hdr.type = f16(1)
240 hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch]) 240 hdr.machine = f16(({ x86=3, x64=62, arm=40, arm64=183, ppc=20, mips=8, mipsel=8 })[ctx.arch])
241 if ctx.arch == "mips" or ctx.arch == "mipsel" then 241 if ctx.arch == "mips" or ctx.arch == "mipsel" then
242 hdr.flags = f32(0x50001006) 242 hdr.flags = f32(0x50001006)
243 end 243 end
@@ -477,13 +477,13 @@ typedef struct {
477} mach_obj_64; 477} mach_obj_64;
478typedef struct { 478typedef struct {
479 mach_fat_header fat; 479 mach_fat_header fat;
480 mach_fat_arch fat_arch[4]; 480 mach_fat_arch fat_arch[2];
481 struct { 481 struct {
482 mach_header hdr; 482 mach_header hdr;
483 mach_segment_command seg; 483 mach_segment_command seg;
484 mach_section sec; 484 mach_section sec;
485 mach_symtab_command sym; 485 mach_symtab_command sym;
486 } arch[4]; 486 } arch[2];
487 mach_nlist sym_entry; 487 mach_nlist sym_entry;
488 uint8_t space[4096]; 488 uint8_t space[4096];
489} mach_fat_obj; 489} mach_fat_obj;
@@ -494,6 +494,8 @@ typedef struct {
494 is64, align, mobj = true, 8, "mach_obj_64" 494 is64, align, mobj = true, 8, "mach_obj_64"
495 elseif ctx.arch == "arm" then 495 elseif ctx.arch == "arm" then
496 isfat, mobj = true, "mach_fat_obj" 496 isfat, mobj = true, "mach_fat_obj"
497 elseif ctx.arch == "arm64" then
498 is64, align, isfat, mobj = true, 8, true, "mach_fat_obj"
497 else 499 else
498 check(ctx.arch == "x86", "unsupported architecture for OSX") 500 check(ctx.arch == "x86", "unsupported architecture for OSX")
499 end 501 end
@@ -503,8 +505,8 @@ typedef struct {
503 -- Create Mach-O object and fill in header. 505 -- Create Mach-O object and fill in header.
504 local o = ffi.new(mobj) 506 local o = ffi.new(mobj)
505 local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) 507 local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align)
506 local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch] 508 local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12}, arm64={0x01000007,0x0100000c} })[ctx.arch]
507 local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch] 509 local cpusubtype = ({ x86={3}, x64={3}, arm={3,9}, arm64={3,0} })[ctx.arch]
508 if isfat then 510 if isfat then
509 o.fat.magic = be32(0xcafebabe) 511 o.fat.magic = be32(0xcafebabe)
510 o.fat.nfat_arch = be32(#cpusubtype) 512 o.fat.nfat_arch = be32(#cpusubtype)
@@ -653,7 +655,7 @@ end
653------------------------------------------------------------------------------ 655------------------------------------------------------------------------------
654 656
655-- Public module functions. 657-- Public module functions.
656module(...) 658return {
657 659 start = docmd -- Process -b command line option.
658start = docmd -- Process -b command line option. 660}
659 661
diff --git a/src/jit/dis_arm.lua b/src/jit/dis_arm.lua
index 91ebb7d5..c2dd7769 100644
--- a/src/jit/dis_arm.lua
+++ b/src/jit/dis_arm.lua
@@ -658,7 +658,7 @@ local function disass_block(ctx, ofs, len)
658end 658end
659 659
660-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). 660-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
661local function create_(code, addr, out) 661local function create(code, addr, out)
662 local ctx = {} 662 local ctx = {}
663 ctx.code = code 663 ctx.code = code
664 ctx.addr = addr or 0 664 ctx.addr = addr or 0
@@ -670,20 +670,20 @@ local function create_(code, addr, out)
670end 670end
671 671
672-- Simple API: disassemble code (a string) at address and output via out. 672-- Simple API: disassemble code (a string) at address and output via out.
673local function disass_(code, addr, out) 673local function disass(code, addr, out)
674 create_(code, addr, out):disass() 674 create(code, addr, out):disass()
675end 675end
676 676
677-- Return register name for RID. 677-- Return register name for RID.
678local function regname_(r) 678local function regname(r)
679 if r < 16 then return map_gpr[r] end 679 if r < 16 then return map_gpr[r] end
680 return "d"..(r-16) 680 return "d"..(r-16)
681end 681end
682 682
683-- Public module functions. 683-- Public module functions.
684module(...) 684return {
685 685 create = create,
686create = create_ 686 disass = disass,
687disass = disass_ 687 regname = regname
688regname = regname_ 688}
689 689
diff --git a/src/jit/dis_arm64.lua b/src/jit/dis_arm64.lua
new file mode 100644
index 00000000..a7173326
--- /dev/null
+++ b/src/jit/dis_arm64.lua
@@ -0,0 +1,1216 @@
1----------------------------------------------------------------------------
2-- LuaJIT ARM64 disassembler module.
3--
4-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
5-- Released under the MIT license. See Copyright Notice in luajit.h
6--
7-- Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
8-- Sponsored by Cisco Systems, Inc.
9----------------------------------------------------------------------------
10-- This is a helper module used by the LuaJIT machine code dumper module.
11--
12-- It disassembles most user-mode AArch64 instructions.
13-- NYI: Advanced SIMD and VFP instructions.
14------------------------------------------------------------------------------
15
16local type = type
17local sub, byte, format = string.sub, string.byte, string.format
18local match, gmatch, gsub = string.match, string.gmatch, string.gsub
19local concat = table.concat
20local bit = require("bit")
21local band, bor, bxor, tohex = bit.band, bit.bor, bit.bxor, bit.tohex
22local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
23local ror = bit.ror
24
25------------------------------------------------------------------------------
26-- Opcode maps
27------------------------------------------------------------------------------
28
29local map_adr = { -- PC-relative addressing.
30 shift = 31, mask = 1,
31 [0] = "adrDBx", "adrpDBx"
32}
33
34local map_addsubi = { -- Add/subtract immediate.
35 shift = 29, mask = 3,
36 [0] = "add|movDNIg", "adds|cmnD0NIg", "subDNIg", "subs|cmpD0NIg",
37}
38
39local map_logi = { -- Logical immediate.
40 shift = 31, mask = 1,
41 [0] = {
42 shift = 22, mask = 1,
43 [0] = {
44 shift = 29, mask = 3,
45 [0] = "andDNig", "orr|movDN0ig", "eorDNig", "ands|tstD0Nig"
46 },
47 false -- unallocated
48 },
49 {
50 shift = 29, mask = 3,
51 [0] = "andDNig", "orr|movDN0ig", "eorDNig", "ands|tstD0Nig"
52 }
53}
54
55local map_movwi = { -- Move wide immediate.
56 shift = 31, mask = 1,
57 [0] = {
58 shift = 22, mask = 1,
59 [0] = {
60 shift = 29, mask = 3,
61 [0] = "movnDWRg", false, "movz|movDYRg", "movkDWRg"
62 }, false -- unallocated
63 },
64 {
65 shift = 29, mask = 3,
66 [0] = "movnDWRg", false, "movz|movDYRg", "movkDWRg"
67 },
68}
69
70local map_bitf = { -- Bitfield.
71 shift = 31, mask = 1,
72 [0] = {
73 shift = 22, mask = 1,
74 [0] = {
75 shift = 29, mask = 3,
76 [0] = "sbfm|sbfiz|sbfx|asr|sxtw|sxth|sxtbDN12w",
77 "bfm|bfi|bfxilDN13w",
78 "ubfm|ubfiz|ubfx|lsr|lsl|uxth|uxtbDN12w"
79 }
80 },
81 {
82 shift = 22, mask = 1,
83 {
84 shift = 29, mask = 3,
85 [0] = "sbfm|sbfiz|sbfx|asr|sxtw|sxth|sxtbDN12x",
86 "bfm|bfi|bfxilDN13x",
87 "ubfm|ubfiz|ubfx|lsr|lsl|uxth|uxtbDN12x"
88 }
89 }
90}
91
92local map_datai = { -- Data processing - immediate.
93 shift = 23, mask = 7,
94 [0] = map_adr, map_adr, map_addsubi, false,
95 map_logi, map_movwi, map_bitf,
96 {
97 shift = 15, mask = 0x1c0c1,
98 [0] = "extr|rorDNM4w", [0x10080] = "extr|rorDNM4x",
99 [0x10081] = "extr|rorDNM4x"
100 }
101}
102
103local map_logsr = { -- Logical, shifted register.
104 shift = 31, mask = 1,
105 [0] = {
106 shift = 15, mask = 1,
107 [0] = {
108 shift = 29, mask = 3,
109 [0] = {
110 shift = 21, mask = 7,
111 [0] = "andDNMSg", "bicDNMSg", "andDNMSg", "bicDNMSg",
112 "andDNMSg", "bicDNMSg", "andDNMg", "bicDNMg"
113 },
114 {
115 shift = 21, mask = 7,
116 [0] ="orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0MSg", "orn|mvnDN0MSg",
117 "orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0Mg", "orn|mvnDN0Mg"
118 },
119 {
120 shift = 21, mask = 7,
121 [0] = "eorDNMSg", "eonDNMSg", "eorDNMSg", "eonDNMSg",
122 "eorDNMSg", "eonDNMSg", "eorDNMg", "eonDNMg"
123 },
124 {
125 shift = 21, mask = 7,
126 [0] = "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMSg", "bicsDNMSg",
127 "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMg", "bicsDNMg"
128 }
129 },
130 false -- unallocated
131 },
132 {
133 shift = 29, mask = 3,
134 [0] = {
135 shift = 21, mask = 7,
136 [0] = "andDNMSg", "bicDNMSg", "andDNMSg", "bicDNMSg",
137 "andDNMSg", "bicDNMSg", "andDNMg", "bicDNMg"
138 },
139 {
140 shift = 21, mask = 7,
141 [0] = "orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0MSg", "orn|mvnDN0MSg",
142 "orr|movDN0MSg", "orn|mvnDN0MSg", "orr|movDN0Mg", "orn|mvnDN0Mg"
143 },
144 {
145 shift = 21, mask = 7,
146 [0] = "eorDNMSg", "eonDNMSg", "eorDNMSg", "eonDNMSg",
147 "eorDNMSg", "eonDNMSg", "eorDNMg", "eonDNMg"
148 },
149 {
150 shift = 21, mask = 7,
151 [0] = "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMSg", "bicsDNMSg",
152 "ands|tstD0NMSg", "bicsDNMSg", "ands|tstD0NMg", "bicsDNMg"
153 }
154 }
155}
156
157local map_assh = {
158 shift = 31, mask = 1,
159 [0] = {
160 shift = 15, mask = 1,
161 [0] = {
162 shift = 29, mask = 3,
163 [0] = {
164 shift = 22, mask = 3,
165 [0] = "addDNMSg", "addDNMSg", "addDNMSg", "addDNMg"
166 },
167 {
168 shift = 22, mask = 3,
169 [0] = "adds|cmnD0NMSg", "adds|cmnD0NMSg",
170 "adds|cmnD0NMSg", "adds|cmnD0NMg"
171 },
172 {
173 shift = 22, mask = 3,
174 [0] = "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0Mg"
175 },
176 {
177 shift = 22, mask = 3,
178 [0] = "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0MzSg",
179 "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0Mzg"
180 },
181 },
182 false -- unallocated
183 },
184 {
185 shift = 29, mask = 3,
186 [0] = {
187 shift = 22, mask = 3,
188 [0] = "addDNMSg", "addDNMSg", "addDNMSg", "addDNMg"
189 },
190 {
191 shift = 22, mask = 3,
192 [0] = "adds|cmnD0NMSg", "adds|cmnD0NMSg", "adds|cmnD0NMSg",
193 "adds|cmnD0NMg"
194 },
195 {
196 shift = 22, mask = 3,
197 [0] = "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0MSg", "sub|negDN0Mg"
198 },
199 {
200 shift = 22, mask = 3,
201 [0] = "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0MzSg",
202 "subs|cmp|negsD0N0MzSg", "subs|cmp|negsD0N0Mzg"
203 }
204 }
205}
206
207local map_addsubsh = { -- Add/subtract, shifted register.
208 shift = 22, mask = 3,
209 [0] = map_assh, map_assh, map_assh
210}
211
212local map_addsubex = { -- Add/subtract, extended register.
213 shift = 22, mask = 3,
214 [0] = {
215 shift = 29, mask = 3,
216 [0] = "addDNMXg", "adds|cmnD0NMXg", "subDNMXg", "subs|cmpD0NMzXg",
217 }
218}
219
220local map_addsubc = { -- Add/subtract, with carry.
221 shift = 10, mask = 63,
222 [0] = {
223 shift = 29, mask = 3,
224 [0] = "adcDNMg", "adcsDNMg", "sbc|ngcDN0Mg", "sbcs|ngcsDN0Mg",
225 }
226}
227
228local map_ccomp = {
229 shift = 4, mask = 1,
230 [0] = {
231 shift = 10, mask = 3,
232 [0] = { -- Conditional compare register.
233 shift = 29, mask = 3,
234 "ccmnNMVCg", false, "ccmpNMVCg",
235 },
236 [2] = { -- Conditional compare immediate.
237 shift = 29, mask = 3,
238 "ccmnN5VCg", false, "ccmpN5VCg",
239 }
240 }
241}
242
243local map_csel = { -- Conditional select.
244 shift = 11, mask = 1,
245 [0] = {
246 shift = 10, mask = 1,
247 [0] = {
248 shift = 29, mask = 3,
249 [0] = "cselDNMzCg", false, "csinv|cinv|csetmDNMcg", false,
250 },
251 {
252 shift = 29, mask = 3,
253 [0] = "csinc|cinc|csetDNMcg", false, "csneg|cnegDNMcg", false,
254 }
255 }
256}
257
258local map_data1s = { -- Data processing, 1 source.
259 shift = 29, mask = 1,
260 [0] = {
261 shift = 31, mask = 1,
262 [0] = {
263 shift = 10, mask = 0x7ff,
264 [0] = "rbitDNg", "rev16DNg", "revDNw", false, "clzDNg", "clsDNg"
265 },
266 {
267 shift = 10, mask = 0x7ff,
268 [0] = "rbitDNg", "rev16DNg", "rev32DNx", "revDNx", "clzDNg", "clsDNg"
269 }
270 }
271}
272
273local map_data2s = { -- Data processing, 2 sources.
274 shift = 29, mask = 1,
275 [0] = {
276 shift = 10, mask = 63,
277 false, "udivDNMg", "sdivDNMg", false, false, false, false, "lslDNMg",
278 "lsrDNMg", "asrDNMg", "rorDNMg"
279 }
280}
281
282local map_data3s = { -- Data processing, 3 sources.
283 shift = 29, mask = 7,
284 [0] = {
285 shift = 21, mask = 7,
286 [0] = {
287 shift = 15, mask = 1,
288 [0] = "madd|mulDNMA0g", "msub|mnegDNMA0g"
289 }
290 }, false, false, false,
291 {
292 shift = 15, mask = 1,
293 [0] = {
294 shift = 21, mask = 7,
295 [0] = "madd|mulDNMA0g", "smaddl|smullDxNMwA0x", "smulhDNMx", false,
296 false, "umaddl|umullDxNMwA0x", "umulhDNMx"
297 },
298 {
299 shift = 21, mask = 7,
300 [0] = "msub|mnegDNMA0g", "smsubl|smneglDxNMwA0x", false, false,
301 false, "umsubl|umneglDxNMwA0x"
302 }
303 }
304}
305
306local map_datar = { -- Data processing, register.
307 shift = 28, mask = 1,
308 [0] = {
309 shift = 24, mask = 1,
310 [0] = map_logsr,
311 {
312 shift = 21, mask = 1,
313 [0] = map_addsubsh, map_addsubex
314 }
315 },
316 {
317 shift = 21, mask = 15,
318 [0] = map_addsubc, false, map_ccomp, false, map_csel, false,
319 {
320 shift = 30, mask = 1,
321 [0] = map_data2s, map_data1s
322 },
323 false, map_data3s, map_data3s, map_data3s, map_data3s, map_data3s,
324 map_data3s, map_data3s, map_data3s
325 }
326}
327
328local map_lrl = { -- Load register, literal.
329 shift = 26, mask = 1,
330 [0] = {
331 shift = 30, mask = 3,
332 [0] = "ldrDwB", "ldrDxB", "ldrswDxB"
333 },
334 {
335 shift = 30, mask = 3,
336 [0] = "ldrDsB", "ldrDdB"
337 }
338}
339
340local map_lsriind = { -- Load/store register, immediate pre/post-indexed.
341 shift = 30, mask = 3,
342 [0] = {
343 shift = 26, mask = 1,
344 [0] = {
345 shift = 22, mask = 3,
346 [0] = "strbDwzL", "ldrbDwzL", "ldrsbDxzL", "ldrsbDwzL"
347 }
348 },
349 {
350 shift = 26, mask = 1,
351 [0] = {
352 shift = 22, mask = 3,
353 [0] = "strhDwzL", "ldrhDwzL", "ldrshDxzL", "ldrshDwzL"
354 }
355 },
356 {
357 shift = 26, mask = 1,
358 [0] = {
359 shift = 22, mask = 3,
360 [0] = "strDwzL", "ldrDwzL", "ldrswDxzL"
361 },
362 {
363 shift = 22, mask = 3,
364 [0] = "strDszL", "ldrDszL"
365 }
366 },
367 {
368 shift = 26, mask = 1,
369 [0] = {
370 shift = 22, mask = 3,
371 [0] = "strDxzL", "ldrDxzL"
372 },
373 {
374 shift = 22, mask = 3,
375 [0] = "strDdzL", "ldrDdzL"
376 }
377 }
378}
379
380local map_lsriro = {
381 shift = 21, mask = 1,
382 [0] = { -- Load/store register immediate.
383 shift = 10, mask = 3,
384 [0] = { -- Unscaled immediate.
385 shift = 26, mask = 1,
386 [0] = {
387 shift = 30, mask = 3,
388 [0] = {
389 shift = 22, mask = 3,
390 [0] = "sturbDwK", "ldurbDwK"
391 },
392 {
393 shift = 22, mask = 3,
394 [0] = "sturhDwK", "ldurhDwK"
395 },
396 {
397 shift = 22, mask = 3,
398 [0] = "sturDwK", "ldurDwK"
399 },
400 {
401 shift = 22, mask = 3,
402 [0] = "sturDxK", "ldurDxK"
403 }
404 }
405 }, map_lsriind, false, map_lsriind
406 },
407 { -- Load/store register, register offset.
408 shift = 10, mask = 3,
409 [2] = {
410 shift = 26, mask = 1,
411 [0] = {
412 shift = 30, mask = 3,
413 [0] = {
414 shift = 22, mask = 3,
415 [0] = "strbDwO", "ldrbDwO", "ldrsbDxO", "ldrsbDwO"
416 },
417 {
418 shift = 22, mask = 3,
419 [0] = "strhDwO", "ldrhDwO", "ldrshDxO", "ldrshDwO"
420 },
421 {
422 shift = 22, mask = 3,
423 [0] = "strDwO", "ldrDwO", "ldrswDxO"
424 },
425 {
426 shift = 22, mask = 3,
427 [0] = "strDxO", "ldrDxO"
428 }
429 },
430 {
431 shift = 30, mask = 3,
432 [2] = {
433 shift = 22, mask = 3,
434 [0] = "strDsO", "ldrDsO"
435 },
436 [3] = {
437 shift = 22, mask = 3,
438 [0] = "strDdO", "ldrDdO"
439 }
440 }
441 }
442 }
443}
444
445local map_lsp = { -- Load/store register pair, offset.
446 shift = 22, mask = 1,
447 [0] = {
448 shift = 30, mask = 3,
449 [0] = {
450 shift = 26, mask = 1,
451 [0] = "stpDzAzwP", "stpDzAzsP",
452 },
453 {
454 shift = 26, mask = 1,
455 "stpDzAzdP"
456 },
457 {
458 shift = 26, mask = 1,
459 [0] = "stpDzAzxP"
460 }
461 },
462 {
463 shift = 30, mask = 3,
464 [0] = {
465 shift = 26, mask = 1,
466 [0] = "ldpDzAzwP", "ldpDzAzsP",
467 },
468 {
469 shift = 26, mask = 1,
470 [0] = "ldpswDAxP", "ldpDzAzdP"
471 },
472 {
473 shift = 26, mask = 1,
474 [0] = "ldpDzAzxP"
475 }
476 }
477}
478
479local map_ls = { -- Loads and stores.
480 shift = 24, mask = 0x31,
481 [0x10] = map_lrl, [0x30] = map_lsriro,
482 [0x20] = {
483 shift = 23, mask = 3,
484 map_lsp, map_lsp, map_lsp
485 },
486 [0x21] = {
487 shift = 23, mask = 3,
488 map_lsp, map_lsp, map_lsp
489 },
490 [0x31] = {
491 shift = 26, mask = 1,
492 [0] = {
493 shift = 30, mask = 3,
494 [0] = {
495 shift = 22, mask = 3,
496 [0] = "strbDwzU", "ldrbDwzU"
497 },
498 {
499 shift = 22, mask = 3,
500 [0] = "strhDwzU", "ldrhDwzU"
501 },
502 {
503 shift = 22, mask = 3,
504 [0] = "strDwzU", "ldrDwzU"
505 },
506 {
507 shift = 22, mask = 3,
508 [0] = "strDxzU", "ldrDxzU"
509 }
510 },
511 {
512 shift = 30, mask = 3,
513 [2] = {
514 shift = 22, mask = 3,
515 [0] = "strDszU", "ldrDszU"
516 },
517 [3] = {
518 shift = 22, mask = 3,
519 [0] = "strDdzU", "ldrDdzU"
520 }
521 }
522 },
523}
524
525local map_datafp = { -- Data processing, SIMD and FP.
526 shift = 28, mask = 7,
527 { -- 001
528 shift = 24, mask = 1,
529 [0] = {
530 shift = 21, mask = 1,
531 {
532 shift = 10, mask = 3,
533 [0] = {
534 shift = 12, mask = 1,
535 [0] = {
536 shift = 13, mask = 1,
537 [0] = {
538 shift = 14, mask = 1,
539 [0] = {
540 shift = 15, mask = 1,
541 [0] = { -- FP/int conversion.
542 shift = 31, mask = 1,
543 [0] = {
544 shift = 16, mask = 0xff,
545 [0x20] = "fcvtnsDwNs", [0x21] = "fcvtnuDwNs",
546 [0x22] = "scvtfDsNw", [0x23] = "ucvtfDsNw",
547 [0x24] = "fcvtasDwNs", [0x25] = "fcvtauDwNs",
548 [0x26] = "fmovDwNs", [0x27] = "fmovDsNw",
549 [0x28] = "fcvtpsDwNs", [0x29] = "fcvtpuDwNs",
550 [0x30] = "fcvtmsDwNs", [0x31] = "fcvtmuDwNs",
551 [0x38] = "fcvtzsDwNs", [0x39] = "fcvtzuDwNs",
552 [0x60] = "fcvtnsDwNd", [0x61] = "fcvtnuDwNd",
553 [0x62] = "scvtfDdNw", [0x63] = "ucvtfDdNw",
554 [0x64] = "fcvtasDwNd", [0x65] = "fcvtauDwNd",
555 [0x68] = "fcvtpsDwNd", [0x69] = "fcvtpuDwNd",
556 [0x70] = "fcvtmsDwNd", [0x71] = "fcvtmuDwNd",
557 [0x78] = "fcvtzsDwNd", [0x79] = "fcvtzuDwNd"
558 },
559 {
560 shift = 16, mask = 0xff,
561 [0x20] = "fcvtnsDxNs", [0x21] = "fcvtnuDxNs",
562 [0x22] = "scvtfDsNx", [0x23] = "ucvtfDsNx",
563 [0x24] = "fcvtasDxNs", [0x25] = "fcvtauDxNs",
564 [0x28] = "fcvtpsDxNs", [0x29] = "fcvtpuDxNs",
565 [0x30] = "fcvtmsDxNs", [0x31] = "fcvtmuDxNs",
566 [0x38] = "fcvtzsDxNs", [0x39] = "fcvtzuDxNs",
567 [0x60] = "fcvtnsDxNd", [0x61] = "fcvtnuDxNd",
568 [0x62] = "scvtfDdNx", [0x63] = "ucvtfDdNx",
569 [0x64] = "fcvtasDxNd", [0x65] = "fcvtauDxNd",
570 [0x66] = "fmovDxNd", [0x67] = "fmovDdNx",
571 [0x68] = "fcvtpsDxNd", [0x69] = "fcvtpuDxNd",
572 [0x70] = "fcvtmsDxNd", [0x71] = "fcvtmuDxNd",
573 [0x78] = "fcvtzsDxNd", [0x79] = "fcvtzuDxNd"
574 }
575 }
576 },
577 { -- FP data-processing, 1 source.
578 shift = 31, mask = 1,
579 [0] = {
580 shift = 22, mask = 3,
581 [0] = {
582 shift = 15, mask = 63,
583 [0] = "fmovDNf", "fabsDNf", "fnegDNf",
584 "fsqrtDNf", false, "fcvtDdNs", false, false,
585 "frintnDNf", "frintpDNf", "frintmDNf", "frintzDNf",
586 "frintaDNf", false, "frintxDNf", "frintiDNf",
587 },
588 {
589 shift = 15, mask = 63,
590 [0] = "fmovDNf", "fabsDNf", "fnegDNf",
591 "fsqrtDNf", "fcvtDsNd", false, false, false,
592 "frintnDNf", "frintpDNf", "frintmDNf", "frintzDNf",
593 "frintaDNf", false, "frintxDNf", "frintiDNf",
594 }
595 }
596 }
597 },
598 { -- FP compare.
599 shift = 31, mask = 1,
600 [0] = {
601 shift = 14, mask = 3,
602 [0] = {
603 shift = 23, mask = 1,
604 [0] = {
605 shift = 0, mask = 31,
606 [0] = "fcmpNMf", [8] = "fcmpNZf",
607 [16] = "fcmpeNMf", [24] = "fcmpeNZf",
608 }
609 }
610 }
611 }
612 },
613 { -- FP immediate.
614 shift = 31, mask = 1,
615 [0] = {
616 shift = 5, mask = 31,
617 [0] = {
618 shift = 23, mask = 1,
619 [0] = "fmovDFf"
620 }
621 }
622 }
623 },
624 { -- FP conditional compare.
625 shift = 31, mask = 1,
626 [0] = {
627 shift = 23, mask = 1,
628 [0] = {
629 shift = 4, mask = 1,
630 [0] = "fccmpNMVCf", "fccmpeNMVCf"
631 }
632 }
633 },
634 { -- FP data-processing, 2 sources.
635 shift = 31, mask = 1,
636 [0] = {
637 shift = 23, mask = 1,
638 [0] = {
639 shift = 12, mask = 15,
640 [0] = "fmulDNMf", "fdivDNMf", "faddDNMf", "fsubDNMf",
641 "fmaxDNMf", "fminDNMf", "fmaxnmDNMf", "fminnmDNMf",
642 "fnmulDNMf"
643 }
644 }
645 },
646 { -- FP conditional select.
647 shift = 31, mask = 1,
648 [0] = {
649 shift = 23, mask = 1,
650 [0] = "fcselDNMCf"
651 }
652 }
653 }
654 },
655 { -- FP data-processing, 3 sources.
656 shift = 31, mask = 1,
657 [0] = {
658 shift = 15, mask = 1,
659 [0] = {
660 shift = 21, mask = 5,
661 [0] = "fmaddDNMAf", "fnmaddDNMAf"
662 },
663 {
664 shift = 21, mask = 5,
665 [0] = "fmsubDNMAf", "fnmsubDNMAf"
666 }
667 }
668 }
669 }
670}
671
672local map_br = { -- Branches, exception generating and system instructions.
673 shift = 29, mask = 7,
674 [0] = "bB",
675 { -- Compare & branch, immediate.
676 shift = 24, mask = 3,
677 [0] = "cbzDBg", "cbnzDBg", "tbzDTBw", "tbnzDTBw"
678 },
679 { -- Conditional branch, immediate.
680 shift = 24, mask = 3,
681 [0] = {
682 shift = 4, mask = 1,
683 [0] = {
684 shift = 0, mask = 15,
685 [0] = "beqB", "bneB", "bhsB", "bloB", "bmiB", "bplB", "bvsB", "bvcB",
686 "bhiB", "blsB", "bgeB", "bltB", "bgtB", "bleB", "balB"
687 }
688 }
689 }, false, "blB",
690 { -- Compare & branch, immediate.
691 shift = 24, mask = 3,
692 [0] = "cbzDBg", "cbnzDBg", "tbzDTBx", "tbnzDTBx"
693 },
694 {
695 shift = 24, mask = 3,
696 [0] = { -- Exception generation.
697 shift = 0, mask = 0xe0001f,
698 [0x200000] = "brkW"
699 },
700 { -- System instructions.
701 shift = 0, mask = 0x3fffff,
702 [0x03201f] = "nop"
703 },
704 { -- Unconditional branch, register.
705 shift = 0, mask = 0xfffc1f,
706 [0x1f0000] = "brNx", [0x3f0000] = "blrNx",
707 [0x5f0000] = "retNx"
708 },
709 }
710}
711
712local map_init = {
713 shift = 25, mask = 15,
714 [0] = false, false, false, false, map_ls, map_datar, map_ls, map_datafp,
715 map_datai, map_datai, map_br, map_br, map_ls, map_datar, map_ls, map_datafp
716}
717
718------------------------------------------------------------------------------
719
720local map_regs = { x = {}, w = {}, d = {}, s = {} }
721
722for i=0,30 do
723 map_regs.x[i] = "x"..i
724 map_regs.w[i] = "w"..i
725 map_regs.d[i] = "d"..i
726 map_regs.s[i] = "s"..i
727end
728map_regs.x[31] = "sp"
729map_regs.w[31] = "wsp"
730map_regs.d[31] = "d31"
731map_regs.s[31] = "s31"
732
733local map_cond = {
734 [0] = "eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc",
735 "hi", "ls", "ge", "lt", "gt", "le", "al",
736}
737
738local map_shift = { [0] = "lsl", "lsr", "asr", }
739
740local map_extend = {
741 [0] = "uxtb", "uxth", "uxtw", "uxtx", "sxtb", "sxth", "sxtw", "sxtx",
742}
743
744------------------------------------------------------------------------------
745
746-- Output a nicely formatted line with an opcode and operands.
747local function putop(ctx, text, operands)
748 local pos = ctx.pos
749 local extra = ""
750 if ctx.rel then
751 local sym = ctx.symtab[ctx.rel]
752 if sym then
753 extra = "\t->"..sym
754 end
755 end
756 if ctx.hexdump > 0 then
757 ctx.out(format("%08x %s %-5s %s%s\n",
758 ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
759 else
760 ctx.out(format("%08x %-5s %s%s\n",
761 ctx.addr+pos, text, concat(operands, ", "), extra))
762 end
763 ctx.pos = pos + 4
764end
765
766-- Fallback for unknown opcodes.
767local function unknown(ctx)
768 return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
769end
770
771local function match_reg(p, pat, regnum)
772 return map_regs[match(pat, p.."%w-([xwds])")][regnum]
773end
774
775local function fmt_hex32(x)
776 if x < 0 then
777 return tohex(x)
778 else
779 return format("%x", x)
780 end
781end
782
783local imm13_rep = { 0x55555555, 0x11111111, 0x01010101, 0x00010001, 0x00000001 }
784
785local function decode_imm13(op)
786 local imms = band(rshift(op, 10), 63)
787 local immr = band(rshift(op, 16), 63)
788 if band(op, 0x00400000) == 0 then
789 local len = 5
790 if imms >= 56 then
791 if imms >= 60 then len = 1 else len = 2 end
792 elseif imms >= 48 then len = 3 elseif imms >= 32 then len = 4 end
793 local l = lshift(1, len)-1
794 local s = band(imms, l)
795 local r = band(immr, l)
796 local imm = ror(rshift(-1, 31-s), r)
797 if len ~= 5 then imm = band(imm, lshift(1, l)-1) + rshift(imm, 31-l) end
798 imm = imm * imm13_rep[len]
799 local ix = fmt_hex32(imm)
800 if rshift(op, 31) ~= 0 then
801 return ix..tohex(imm)
802 else
803 return ix
804 end
805 else
806 local lo, hi = -1, 0
807 if imms < 32 then lo = rshift(-1, 31-imms) else hi = rshift(-1, 63-imms) end
808 if immr ~= 0 then
809 lo, hi = ror(lo, immr), ror(hi, immr)
810 local x = immr == 32 and 0 or band(bxor(lo, hi), lshift(-1, 32-immr))
811 lo, hi = bxor(lo, x), bxor(hi, x)
812 if immr >= 32 then lo, hi = hi, lo end
813 end
814 if hi ~= 0 then
815 return fmt_hex32(hi)..tohex(lo)
816 else
817 return fmt_hex32(lo)
818 end
819 end
820end
821
822local function parse_immpc(op, name)
823 if name == "b" or name == "bl" then
824 return arshift(lshift(op, 6), 4)
825 elseif name == "adr" or name == "adrp" then
826 local immlo = band(rshift(op, 29), 3)
827 local immhi = lshift(arshift(lshift(op, 8), 13), 2)
828 return bor(immhi, immlo)
829 elseif name == "tbz" or name == "tbnz" then
830 return lshift(arshift(lshift(op, 13), 18), 2)
831 else
832 return lshift(arshift(lshift(op, 8), 13), 2)
833 end
834end
835
836local function parse_fpimm8(op)
837 local sign = band(op, 0x100000) == 0 and 1 or -1
838 local exp = bxor(rshift(arshift(lshift(op, 12), 5), 24), 0x80) - 131
839 local frac = 16+band(rshift(op, 13), 15)
840 return sign * frac * 2^exp
841end
842
843local function prefer_bfx(sf, uns, imms, immr)
844 if imms < immr or imms == 31 or imms == 63 then
845 return false
846 end
847 if immr == 0 then
848 if sf == 0 and (imms == 7 or imms == 15) then
849 return false
850 end
851 if sf ~= 0 and uns == 0 and (imms == 7 or imms == 15 or imms == 31) then
852 return false
853 end
854 end
855 return true
856end
857
858-- Disassemble a single instruction.
859local function disass_ins(ctx)
860 local pos = ctx.pos
861 local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
862 local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0)
863 local operands = {}
864 local suffix = ""
865 local last, name, pat
866 local map_reg
867 ctx.op = op
868 ctx.rel = nil
869 last = nil
870 local opat
871 opat = map_init[band(rshift(op, 25), 15)]
872 while type(opat) ~= "string" do
873 if not opat then return unknown(ctx) end
874 opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._
875 end
876 name, pat = match(opat, "^([a-z0-9]*)(.*)")
877 local altname, pat2 = match(pat, "|([a-z0-9_.|]*)(.*)")
878 if altname then pat = pat2 end
879 if sub(pat, 1, 1) == "." then
880 local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)")
881 suffix = suffix..s2
882 pat = p2
883 end
884
885 local rt = match(pat, "[gf]")
886 if rt then
887 if rt == "g" then
888 map_reg = band(op, 0x80000000) ~= 0 and map_regs.x or map_regs.w
889 else
890 map_reg = band(op, 0x400000) ~= 0 and map_regs.d or map_regs.s
891 end
892 end
893
894 local second0, immr
895
896 for p in gmatch(pat, ".") do
897 local x = nil
898 if p == "D" then
899 local regnum = band(op, 31)
900 x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
901 elseif p == "N" then
902 local regnum = band(rshift(op, 5), 31)
903 x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
904 elseif p == "M" then
905 local regnum = band(rshift(op, 16), 31)
906 x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
907 elseif p == "A" then
908 local regnum = band(rshift(op, 10), 31)
909 x = rt and map_reg[regnum] or match_reg(p, pat, regnum)
910 elseif p == "B" then
911 local addr = ctx.addr + pos + parse_immpc(op, name)
912 ctx.rel = addr
913 x = "0x"..tohex(addr)
914 elseif p == "T" then
915 x = bor(band(rshift(op, 26), 32), band(rshift(op, 19), 31))
916 elseif p == "V" then
917 x = band(op, 15)
918 elseif p == "C" then
919 x = map_cond[band(rshift(op, 12), 15)]
920 elseif p == "c" then
921 local rn = band(rshift(op, 5), 31)
922 local rm = band(rshift(op, 16), 31)
923 local cond = band(rshift(op, 12), 15)
924 local invc = bxor(cond, 1)
925 x = map_cond[cond]
926 if altname and cond ~= 14 and cond ~= 15 then
927 local a1, a2 = match(altname, "([^|]*)|(.*)")
928 if rn == rm then
929 local n = #operands
930 operands[n] = nil
931 x = map_cond[invc]
932 if rn ~= 31 then
933 if a1 then name = a1 else name = altname end
934 else
935 operands[n-1] = nil
936 name = a2
937 end
938 end
939 end
940 elseif p == "W" then
941 x = band(rshift(op, 5), 0xffff)
942 elseif p == "Y" then
943 x = band(rshift(op, 5), 0xffff)
944 local hw = band(rshift(op, 21), 3)
945 if altname and (hw == 0 or x ~= 0) then
946 name = altname
947 end
948 elseif p == "L" then
949 local rn = map_regs.x[band(rshift(op, 5), 31)]
950 local imm9 = arshift(lshift(op, 11), 23)
951 if band(op, 0x800) ~= 0 then
952 x = "["..rn..", #"..imm9.."]!"
953 else
954 x = "["..rn.."], #"..imm9
955 end
956 elseif p == "U" then
957 local rn = map_regs.x[band(rshift(op, 5), 31)]
958 local sz = band(rshift(op, 30), 3)
959 local imm12 = lshift(arshift(lshift(op, 10), 20), sz)
960 if imm12 ~= 0 then
961 x = "["..rn..", #"..imm12.."]"
962 else
963 x = "["..rn.."]"
964 end
965 elseif p == "K" then
966 local rn = map_regs.x[band(rshift(op, 5), 31)]
967 local imm9 = arshift(lshift(op, 11), 23)
968 if imm9 ~= 0 then
969 x = "["..rn..", #"..imm9.."]"
970 else
971 x = "["..rn.."]"
972 end
973 elseif p == "O" then
974 local rn, rm = map_regs.x[band(rshift(op, 5), 31)]
975 local m = band(rshift(op, 13), 1)
976 if m == 0 then
977 rm = map_regs.w[band(rshift(op, 16), 31)]
978 else
979 rm = map_regs.x[band(rshift(op, 16), 31)]
980 end
981 x = "["..rn..", "..rm
982 local opt = band(rshift(op, 13), 7)
983 local s = band(rshift(op, 12), 1)
984 local sz = band(rshift(op, 30), 3)
985 -- extension to be applied
986 if opt == 3 then
987 if s == 0 then x = x.."]"
988 else x = x..", lsl #"..sz.."]" end
989 elseif opt == 2 or opt == 6 or opt == 7 then
990 if s == 0 then x = x..", "..map_extend[opt].."]"
991 else x = x..", "..map_extend[opt].." #"..sz.."]" end
992 else
993 x = x.."]"
994 end
995 elseif p == "P" then
996 local opcv, sh = rshift(op, 26), 2
997 if opcv >= 0x2a then sh = 4 elseif opcv >= 0x1b then sh = 3 end
998 local imm7 = lshift(arshift(lshift(op, 10), 25), sh)
999 local rn = map_regs.x[band(rshift(op, 5), 31)]
1000 local ind = band(rshift(op, 23), 3)
1001 if ind == 1 then
1002 x = "["..rn.."], #"..imm7
1003 elseif ind == 2 then
1004 if imm7 == 0 then
1005 x = "["..rn.."]"
1006 else
1007 x = "["..rn..", #"..imm7.."]"
1008 end
1009 elseif ind == 3 then
1010 x = "["..rn..", #"..imm7.."]!"
1011 end
1012 elseif p == "I" then
1013 local shf = band(rshift(op, 22), 3)
1014 local imm12 = band(rshift(op, 10), 0x0fff)
1015 local rn, rd = band(rshift(op, 5), 31), band(op, 31)
1016 if altname == "mov" and shf == 0 and imm12 == 0 and (rn == 31 or rd == 31) then
1017 name = altname
1018 x = nil
1019 elseif shf == 0 then
1020 x = imm12
1021 elseif shf == 1 then
1022 x = imm12..", lsl #12"
1023 end
1024 elseif p == "i" then
1025 x = "#0x"..decode_imm13(op)
1026 elseif p == "1" then
1027 immr = band(rshift(op, 16), 63)
1028 x = immr
1029 elseif p == "2" then
1030 x = band(rshift(op, 10), 63)
1031 if altname then
1032 local a1, a2, a3, a4, a5, a6 =
1033 match(altname, "([^|]*)|([^|]*)|([^|]*)|([^|]*)|([^|]*)|(.*)")
1034 local sf = band(rshift(op, 26), 32)
1035 local uns = band(rshift(op, 30), 1)
1036 if prefer_bfx(sf, uns, x, immr) then
1037 name = a2
1038 x = x - immr + 1
1039 elseif immr == 0 and x == 7 then
1040 local n = #operands
1041 operands[n] = nil
1042 if sf ~= 0 then
1043 operands[n-1] = gsub(operands[n-1], "x", "w")
1044 end
1045 last = operands[n-1]
1046 name = a6
1047 x = nil
1048 elseif immr == 0 and x == 15 then
1049 local n = #operands
1050 operands[n] = nil
1051 if sf ~= 0 then
1052 operands[n-1] = gsub(operands[n-1], "x", "w")
1053 end
1054 last = operands[n-1]
1055 name = a5
1056 x = nil
1057 elseif x == 31 or x == 63 then
1058 if x == 31 and immr == 0 and name == "sbfm" then
1059 name = a4
1060 local n = #operands
1061 operands[n] = nil
1062 if sf ~= 0 then
1063 operands[n-1] = gsub(operands[n-1], "x", "w")
1064 end
1065 last = operands[n-1]
1066 else
1067 name = a3
1068 end
1069 x = nil
1070 elseif band(x, 31) ~= 31 and immr == x+1 and name == "ubfm" then
1071 name = a4
1072 last = "#"..(sf+32 - immr)
1073 operands[#operands] = last
1074 x = nil
1075 elseif x < immr then
1076 name = a1
1077 last = "#"..(sf+32 - immr)
1078 operands[#operands] = last
1079 x = x + 1
1080 end
1081 end
1082 elseif p == "3" then
1083 x = band(rshift(op, 10), 63)
1084 if altname then
1085 local a1, a2 = match(altname, "([^|]*)|(.*)")
1086 if x < immr then
1087 name = a1
1088 local sf = band(rshift(op, 26), 32)
1089 last = "#"..(sf+32 - immr)
1090 operands[#operands] = last
1091 x = x + 1
1092 elseif x >= immr then
1093 name = a2
1094 x = x - immr + 1
1095 end
1096 end
1097 elseif p == "4" then
1098 x = band(rshift(op, 10), 63)
1099 local rn = band(rshift(op, 5), 31)
1100 local rm = band(rshift(op, 16), 31)
1101 if altname and rn == rm then
1102 local n = #operands
1103 operands[n] = nil
1104 last = operands[n-1]
1105 name = altname
1106 end
1107 elseif p == "5" then
1108 x = band(rshift(op, 16), 31)
1109 elseif p == "S" then
1110 x = band(rshift(op, 10), 63)
1111 if x == 0 then x = nil
1112 else x = map_shift[band(rshift(op, 22), 3)].." #"..x end
1113 elseif p == "X" then
1114 local opt = band(rshift(op, 13), 7)
1115 -- Width specifier <R>.
1116 if opt ~= 3 and opt ~= 7 then
1117 last = map_regs.w[band(rshift(op, 16), 31)]
1118 operands[#operands] = last
1119 end
1120 x = band(rshift(op, 10), 7)
1121 -- Extension.
1122 if opt == 2 + band(rshift(op, 31), 1) and
1123 band(rshift(op, second0 and 5 or 0), 31) == 31 then
1124 if x == 0 then x = nil
1125 else x = "lsl #"..x end
1126 else
1127 if x == 0 then x = map_extend[band(rshift(op, 13), 7)]
1128 else x = map_extend[band(rshift(op, 13), 7)].." #"..x end
1129 end
1130 elseif p == "R" then
1131 x = band(rshift(op,21), 3)
1132 if x == 0 then x = nil
1133 else x = "lsl #"..x*16 end
1134 elseif p == "z" then
1135 local n = #operands
1136 if operands[n] == "sp" then operands[n] = "xzr"
1137 elseif operands[n] == "wsp" then operands[n] = "wzr"
1138 end
1139 elseif p == "Z" then
1140 x = 0
1141 elseif p == "F" then
1142 x = parse_fpimm8(op)
1143 elseif p == "g" or p == "f" or p == "x" or p == "w" or
1144 p == "d" or p == "s" then
1145 -- These are handled in D/N/M/A.
1146 elseif p == "0" then
1147 if last == "sp" or last == "wsp" then
1148 local n = #operands
1149 operands[n] = nil
1150 last = operands[n-1]
1151 if altname then
1152 local a1, a2 = match(altname, "([^|]*)|(.*)")
1153 if not a1 then
1154 name = altname
1155 elseif second0 then
1156 name, altname = a2, a1
1157 else
1158 name, altname = a1, a2
1159 end
1160 end
1161 end
1162 second0 = true
1163 else
1164 assert(false)
1165 end
1166 if x then
1167 last = x
1168 if type(x) == "number" then x = "#"..x end
1169 operands[#operands+1] = x
1170 end
1171 end
1172
1173 return putop(ctx, name..suffix, operands)
1174end
1175
1176------------------------------------------------------------------------------
1177
1178-- Disassemble a block of code.
1179local function disass_block(ctx, ofs, len)
1180 if not ofs then ofs = 0 end
1181 local stop = len and ofs+len or #ctx.code
1182 ctx.pos = ofs
1183 ctx.rel = nil
1184 while ctx.pos < stop do disass_ins(ctx) end
1185end
1186
1187-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
1188local function create(code, addr, out)
1189 local ctx = {}
1190 ctx.code = code
1191 ctx.addr = addr or 0
1192 ctx.out = out or io.write
1193 ctx.symtab = {}
1194 ctx.disass = disass_block
1195 ctx.hexdump = 8
1196 return ctx
1197end
1198
1199-- Simple API: disassemble code (a string) at address and output via out.
1200local function disass(code, addr, out)
1201 create(code, addr, out):disass()
1202end
1203
1204-- Return register name for RID.
1205local function regname(r)
1206 if r < 32 then return map_regs.x[r] end
1207 return map_regs.d[r-32]
1208end
1209
1210-- Public module functions.
1211return {
1212 create = create,
1213 disass = disass,
1214 regname = regname
1215}
1216
diff --git a/src/jit/dis_mips.lua b/src/jit/dis_mips.lua
index 02dfc172..a12b8e62 100644
--- a/src/jit/dis_mips.lua
+++ b/src/jit/dis_mips.lua
@@ -34,15 +34,17 @@ local map_special = {
34 "jrS", "jalrD1S", "movzDST", "movnDST", 34 "jrS", "jalrD1S", "movzDST", "movnDST",
35 "syscallY", "breakY", false, "sync", 35 "syscallY", "breakY", false, "sync",
36 "mfhiD", "mthiS", "mfloD", "mtloS", 36 "mfhiD", "mthiS", "mfloD", "mtloS",
37 false, false, false, false, 37 "dsllvDST", false, "dsrlvDST", "dsravDST",
38 "multST", "multuST", "divST", "divuST", 38 "multST", "multuST", "divST", "divuST",
39 false, false, false, false, 39 "dmultST", "dmultuST", "ddivST", "ddivuST",
40 "addDST", "addu|moveDST0", "subDST", "subu|neguDS0T", 40 "addDST", "addu|moveDST0", "subDST", "subu|neguDS0T",
41 "andDST", "orDST", "xorDST", "nor|notDST0", 41 "andDST", "or|moveDST0", "xorDST", "nor|notDST0",
42 false, false, "sltDST", "sltuDST", 42 false, false, "sltDST", "sltuDST",
43 false, false, false, false, 43 "daddDST", "dadduDST", "dsubDST", "dsubuDST",
44 "tgeSTZ", "tgeuSTZ", "tltSTZ", "tltuSTZ", 44 "tgeSTZ", "tgeuSTZ", "tltSTZ", "tltuSTZ",
45 "teqSTZ", false, "tneSTZ", 45 "teqSTZ", false, "tneSTZ", false,
46 "dsllDTA", false, "dsrlDTA", "dsraDTA",
47 "dsll32DTA", false, "dsrl32DTA", "dsra32DTA",
46} 48}
47 49
48local map_special2 = { 50local map_special2 = {
@@ -60,11 +62,17 @@ local map_bshfl = {
60 [24] = "sehDT", 62 [24] = "sehDT",
61} 63}
62 64
65local map_dbshfl = {
66 shift = 6, mask = 31,
67 [2] = "dsbhDT",
68 [5] = "dshdDT",
69}
70
63local map_special3 = { 71local map_special3 = {
64 shift = 0, mask = 63, 72 shift = 0, mask = 63,
65 [0] = "extTSAK", [4] = "insTSAL", 73 [0] = "extTSAK", [1] = "dextmTSAP", [3] = "dextTSAK",
66 [32] = map_bshfl, 74 [4] = "insTSAL", [6] = "dinsuTSEQ", [7] = "dinsTSAL",
67 [59] = "rdhwrTD", 75 [32] = map_bshfl, [36] = map_dbshfl, [59] = "rdhwrTD",
68} 76}
69 77
70local map_regimm = { 78local map_regimm = {
@@ -178,8 +186,8 @@ local map_cop1bc = {
178 186
179local map_cop1 = { 187local map_cop1 = {
180 shift = 21, mask = 31, 188 shift = 21, mask = 31,
181 [0] = "mfc1TG", false, "cfc1TG", "mfhc1TG", 189 [0] = "mfc1TG", "dmfc1TG", "cfc1TG", "mfhc1TG",
182 "mtc1TG", false, "ctc1TG", "mthc1TG", 190 "mtc1TG", "dmtc1TG", "ctc1TG", "mthc1TG",
183 map_cop1bc, false, false, false, 191 map_cop1bc, false, false, false,
184 false, false, false, false, 192 false, false, false, false,
185 map_cop1s, map_cop1d, false, false, 193 map_cop1s, map_cop1d, false, false,
@@ -213,16 +221,16 @@ local map_pri = {
213 "andiTSU", "ori|liTS0U", "xoriTSU", "luiTU", 221 "andiTSU", "ori|liTS0U", "xoriTSU", "luiTU",
214 map_cop0, map_cop1, false, map_cop1x, 222 map_cop0, map_cop1, false, map_cop1x,
215 "beql|beqzlST0B", "bnel|bnezlST0B", "blezlSB", "bgtzlSB", 223 "beql|beqzlST0B", "bnel|bnezlST0B", "blezlSB", "bgtzlSB",
216 false, false, false, false, 224 "daddiTSI", "daddiuTSI", false, false,
217 map_special2, false, false, map_special3, 225 map_special2, "jalxJ", false, map_special3,
218 "lbTSO", "lhTSO", "lwlTSO", "lwTSO", 226 "lbTSO", "lhTSO", "lwlTSO", "lwTSO",
219 "lbuTSO", "lhuTSO", "lwrTSO", false, 227 "lbuTSO", "lhuTSO", "lwrTSO", false,
220 "sbTSO", "shTSO", "swlTSO", "swTSO", 228 "sbTSO", "shTSO", "swlTSO", "swTSO",
221 false, false, "swrTSO", "cacheNSO", 229 false, false, "swrTSO", "cacheNSO",
222 "llTSO", "lwc1HSO", "lwc2TSO", "prefNSO", 230 "llTSO", "lwc1HSO", "lwc2TSO", "prefNSO",
223 false, "ldc1HSO", "ldc2TSO", false, 231 false, "ldc1HSO", "ldc2TSO", "ldTSO",
224 "scTSO", "swc1HSO", "swc2TSO", false, 232 "scTSO", "swc1HSO", "swc2TSO", false,
225 false, "sdc1HSO", "sdc2TSO", false, 233 false, "sdc1HSO", "sdc2TSO", "sdTSO",
226} 234}
227 235
228------------------------------------------------------------------------------ 236------------------------------------------------------------------------------
@@ -306,6 +314,8 @@ local function disass_ins(ctx)
306 x = "f"..band(rshift(op, 21), 31) 314 x = "f"..band(rshift(op, 21), 31)
307 elseif p == "A" then 315 elseif p == "A" then
308 x = band(rshift(op, 6), 31) 316 x = band(rshift(op, 6), 31)
317 elseif p == "E" then
318 x = band(rshift(op, 6), 31) + 32
309 elseif p == "M" then 319 elseif p == "M" then
310 x = band(rshift(op, 11), 31) 320 x = band(rshift(op, 11), 31)
311 elseif p == "N" then 321 elseif p == "N" then
@@ -315,8 +325,12 @@ local function disass_ins(ctx)
315 if x == 0 then x = nil end 325 if x == 0 then x = nil end
316 elseif p == "K" then 326 elseif p == "K" then
317 x = band(rshift(op, 11), 31) + 1 327 x = band(rshift(op, 11), 31) + 1
328 elseif p == "P" then
329 x = band(rshift(op, 11), 31) + 33
318 elseif p == "L" then 330 elseif p == "L" then
319 x = band(rshift(op, 11), 31) - last + 1 331 x = band(rshift(op, 11), 31) - last + 1
332 elseif p == "Q" then
333 x = band(rshift(op, 11), 31) - last + 33
320 elseif p == "I" then 334 elseif p == "I" then
321 x = arshift(lshift(op, 16), 16) 335 x = arshift(lshift(op, 16), 16)
322 elseif p == "U" then 336 elseif p == "U" then
@@ -330,11 +344,12 @@ local function disass_ins(ctx)
330 elseif p == "B" then 344 elseif p == "B" then
331 x = ctx.addr + ctx.pos + arshift(lshift(op, 16), 16)*4 + 4 345 x = ctx.addr + ctx.pos + arshift(lshift(op, 16), 16)*4 + 4
332 ctx.rel = x 346 ctx.rel = x
333 x = "0x"..tohex(x) 347 x = format("0x%08x", x)
334 elseif p == "J" then 348 elseif p == "J" then
335 x = band(ctx.addr + ctx.pos, 0xf0000000) + band(op, 0x03ffffff)*4 349 local a = ctx.addr + ctx.pos
350 x = a - band(a, 0x0fffffff) + band(op, 0x03ffffff)*4
336 ctx.rel = x 351 ctx.rel = x
337 x = "0x"..tohex(x) 352 x = format("0x%08x", x)
338 elseif p == "V" then 353 elseif p == "V" then
339 x = band(rshift(op, 8), 7) 354 x = band(rshift(op, 8), 7)
340 if x == 0 then x = nil end 355 if x == 0 then x = nil end
@@ -384,7 +399,7 @@ local function disass_block(ctx, ofs, len)
384end 399end
385 400
386-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). 401-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
387local function create_(code, addr, out) 402local function create(code, addr, out)
388 local ctx = {} 403 local ctx = {}
389 ctx.code = code 404 ctx.code = code
390 ctx.addr = addr or 0 405 ctx.addr = addr or 0
@@ -396,33 +411,33 @@ local function create_(code, addr, out)
396 return ctx 411 return ctx
397end 412end
398 413
399local function create_el_(code, addr, out) 414local function create_el(code, addr, out)
400 local ctx = create_(code, addr, out) 415 local ctx = create(code, addr, out)
401 ctx.get = get_le 416 ctx.get = get_le
402 return ctx 417 return ctx
403end 418end
404 419
405-- Simple API: disassemble code (a string) at address and output via out. 420-- Simple API: disassemble code (a string) at address and output via out.
406local function disass_(code, addr, out) 421local function disass(code, addr, out)
407 create_(code, addr, out):disass() 422 create(code, addr, out):disass()
408end 423end
409 424
410local function disass_el_(code, addr, out) 425local function disass_el(code, addr, out)
411 create_el_(code, addr, out):disass() 426 create_el(code, addr, out):disass()
412end 427end
413 428
414-- Return register name for RID. 429-- Return register name for RID.
415local function regname_(r) 430local function regname(r)
416 if r < 32 then return map_gpr[r] end 431 if r < 32 then return map_gpr[r] end
417 return "f"..(r-32) 432 return "f"..(r-32)
418end 433end
419 434
420-- Public module functions. 435-- Public module functions.
421module(...) 436return {
422 437 create = create,
423create = create_ 438 create_el = create_el,
424create_el = create_el_ 439 disass = disass,
425disass = disass_ 440 disass_el = disass_el,
426disass_el = disass_el_ 441 regname = regname
427regname = regname_ 442}
428 443
diff --git a/src/jit/dis_mips64.lua b/src/jit/dis_mips64.lua
new file mode 100644
index 00000000..c4374928
--- /dev/null
+++ b/src/jit/dis_mips64.lua
@@ -0,0 +1,17 @@
1----------------------------------------------------------------------------
2-- LuaJIT MIPS64 disassembler wrapper module.
3--
4-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
5-- Released under the MIT license. See Copyright Notice in luajit.h
6----------------------------------------------------------------------------
7-- This module just exports the big-endian functions from the
8-- MIPS disassembler module. All the interesting stuff is there.
9------------------------------------------------------------------------------
10
11local dis_mips = require((string.match(..., ".*%.") or "").."dis_mips")
12return {
13 create = dis_mips.create,
14 disass = dis_mips.disass,
15 regname = dis_mips.regname
16}
17
diff --git a/src/jit/dis_mips64el.lua b/src/jit/dis_mips64el.lua
new file mode 100644
index 00000000..2b1470af
--- /dev/null
+++ b/src/jit/dis_mips64el.lua
@@ -0,0 +1,17 @@
1----------------------------------------------------------------------------
2-- LuaJIT MIPS64EL disassembler wrapper module.
3--
4-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
5-- Released under the MIT license. See Copyright Notice in luajit.h
6----------------------------------------------------------------------------
7-- This module just exports the little-endian functions from the
8-- MIPS disassembler module. All the interesting stuff is there.
9------------------------------------------------------------------------------
10
11local dis_mips = require((string.match(..., ".*%.") or "").."dis_mips")
12return {
13 create = dis_mips.create_el,
14 disass = dis_mips.disass_el,
15 regname = dis_mips.regname
16}
17
diff --git a/src/jit/dis_mipsel.lua b/src/jit/dis_mipsel.lua
index c9c2e245..f69b11f0 100644
--- a/src/jit/dis_mipsel.lua
+++ b/src/jit/dis_mipsel.lua
@@ -8,13 +8,10 @@
8-- MIPS disassembler module. All the interesting stuff is there. 8-- MIPS disassembler module. All the interesting stuff is there.
9------------------------------------------------------------------------------ 9------------------------------------------------------------------------------
10 10
11local require = require 11local dis_mips = require((string.match(..., ".*%.") or "").."dis_mips")
12 12return {
13module(...) 13 create = dis_mips.create_el,
14 14 disass = dis_mips.disass_el,
15local dis_mips = require(_PACKAGE.."dis_mips") 15 regname = dis_mips.regname
16 16}
17create = dis_mips.create_el
18disass = dis_mips.disass_el
19regname = dis_mips.regname
20 17
diff --git a/src/jit/dis_ppc.lua b/src/jit/dis_ppc.lua
index 4043aeb8..2aeb1b29 100644
--- a/src/jit/dis_ppc.lua
+++ b/src/jit/dis_ppc.lua
@@ -560,7 +560,7 @@ local function disass_block(ctx, ofs, len)
560end 560end
561 561
562-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). 562-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
563local function create_(code, addr, out) 563local function create(code, addr, out)
564 local ctx = {} 564 local ctx = {}
565 ctx.code = code 565 ctx.code = code
566 ctx.addr = addr or 0 566 ctx.addr = addr or 0
@@ -572,20 +572,20 @@ local function create_(code, addr, out)
572end 572end
573 573
574-- Simple API: disassemble code (a string) at address and output via out. 574-- Simple API: disassemble code (a string) at address and output via out.
575local function disass_(code, addr, out) 575local function disass(code, addr, out)
576 create_(code, addr, out):disass() 576 create(code, addr, out):disass()
577end 577end
578 578
579-- Return register name for RID. 579-- Return register name for RID.
580local function regname_(r) 580local function regname(r)
581 if r < 32 then return map_gpr[r] end 581 if r < 32 then return map_gpr[r] end
582 return "f"..(r-32) 582 return "f"..(r-32)
583end 583end
584 584
585-- Public module functions. 585-- Public module functions.
586module(...) 586return {
587 587 create = create,
588create = create_ 588 disass = disass,
589disass = disass_ 589 regname = regname
590regname = regname_ 590}
591 591
diff --git a/src/jit/dis_x64.lua b/src/jit/dis_x64.lua
index 08918035..d5714ee1 100644
--- a/src/jit/dis_x64.lua
+++ b/src/jit/dis_x64.lua
@@ -8,13 +8,10 @@
8-- x86/x64 disassembler module. All the interesting stuff is there. 8-- x86/x64 disassembler module. All the interesting stuff is there.
9------------------------------------------------------------------------------ 9------------------------------------------------------------------------------
10 10
11local require = require 11local dis_x86 = require((string.match(..., ".*%.") or "").."dis_x86")
12 12return {
13module(...) 13 create = dis_x86.create64,
14 14 disass = dis_x86.disass64,
15local dis_x86 = require(_PACKAGE.."dis_x86") 15 regname = dis_x86.regname64
16 16}
17create = dis_x86.create64
18disass = dis_x86.disass64
19regname = dis_x86.regname64
20 17
diff --git a/src/jit/dis_x86.lua b/src/jit/dis_x86.lua
index 74d0f529..4371233d 100644
--- a/src/jit/dis_x86.lua
+++ b/src/jit/dis_x86.lua
@@ -15,19 +15,20 @@
15-- Intel and AMD manuals. The supported instruction set is quite extensive 15-- Intel and AMD manuals. The supported instruction set is quite extensive
16-- and reflects what a current generation Intel or AMD CPU implements in 16-- and reflects what a current generation Intel or AMD CPU implements in
17-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, 17-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
18-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) 18-- SSE4.1, SSE4.2, SSE4a, AVX, AVX2 and even privileged and hypervisor
19-- instructions. 19-- (VMX/SVM) instructions.
20-- 20--
21-- Notes: 21-- Notes:
22-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. 22-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
23-- * No attempt at optimization has been made -- it's fast enough for my needs. 23-- * No attempt at optimization has been made -- it's fast enough for my needs.
24-- * The public API may change when more architectures are added.
25------------------------------------------------------------------------------ 24------------------------------------------------------------------------------
26 25
27local type = type 26local type = type
28local sub, byte, format = string.sub, string.byte, string.format 27local sub, byte, format = string.sub, string.byte, string.format
29local match, gmatch, gsub = string.match, string.gmatch, string.gsub 28local match, gmatch, gsub = string.match, string.gmatch, string.gsub
30local lower, rep = string.lower, string.rep 29local lower, rep = string.lower, string.rep
30local bit = require("bit")
31local tohex = bit.tohex
31 32
32-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. 33-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
33local map_opc1_32 = { 34local map_opc1_32 = {
@@ -76,7 +77,7 @@ local map_opc1_32 = {
76"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", 77"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
77"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", 78"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
78--Cx 79--Cx
79"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", 80"shift!Bmu","shift!Vmu","retBw","ret","vex*3$lesVrm","vex*2$ldsVrm","movBmi","movVmi",
80"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", 81"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
81--Dx 82--Dx
82"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", 83"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
@@ -101,7 +102,7 @@ local map_opc1_64 = setmetatable({
101 [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", 102 [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
102 [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", 103 [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
103 [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", 104 [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
104 [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, 105 [0x82]=false, [0x9a]=false, [0xc4]="vex*3", [0xc5]="vex*2", [0xce]=false,
105 [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, 106 [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
106}, { __index = map_opc1_32 }) 107}, { __index = map_opc1_32 })
107 108
@@ -112,12 +113,12 @@ local map_opc2 = {
112[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", 113[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
113"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", 114"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
114--1x 115--1x
115"movupsXrm|movssXrm|movupdXrm|movsdXrm", 116"movupsXrm|movssXrvm|movupdXrm|movsdXrvm",
116"movupsXmr|movssXmr|movupdXmr|movsdXmr", 117"movupsXmr|movssXmvr|movupdXmr|movsdXmvr",
117"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", 118"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
118"movlpsXmr||movlpdXmr", 119"movlpsXmr||movlpdXmr",
119"unpcklpsXrm||unpcklpdXrm", 120"unpcklpsXrvm||unpcklpdXrvm",
120"unpckhpsXrm||unpckhpdXrm", 121"unpckhpsXrvm||unpckhpdXrvm",
121"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", 122"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
122"movhpsXmr||movhpdXmr", 123"movhpsXmr||movhpdXmr",
123"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", 124"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
@@ -126,7 +127,7 @@ local map_opc2 = {
126"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, 127"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
127"movapsXrm||movapdXrm", 128"movapsXrm||movapdXrm",
128"movapsXmr||movapdXmr", 129"movapsXmr||movapdXmr",
129"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", 130"cvtpi2psXrMm|cvtsi2ssXrvVmt|cvtpi2pdXrMm|cvtsi2sdXrvVmt",
130"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", 131"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
131"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", 132"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
132"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", 133"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
@@ -142,27 +143,27 @@ local map_opc2 = {
142"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", 143"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
143--5x 144--5x
144"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", 145"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
145"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", 146"rsqrtpsXrm|rsqrtssXrvm","rcppsXrm|rcpssXrvm",
146"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", 147"andpsXrvm||andpdXrvm","andnpsXrvm||andnpdXrvm",
147"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", 148"orpsXrvm||orpdXrvm","xorpsXrvm||xorpdXrvm",
148"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", 149"addpsXrvm|addssXrvm|addpdXrvm|addsdXrvm","mulpsXrvm|mulssXrvm|mulpdXrvm|mulsdXrvm",
149"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", 150"cvtps2pdXrm|cvtss2sdXrvm|cvtpd2psXrm|cvtsd2ssXrvm",
150"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", 151"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
151"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", 152"subpsXrvm|subssXrvm|subpdXrvm|subsdXrvm","minpsXrvm|minssXrvm|minpdXrvm|minsdXrvm",
152"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", 153"divpsXrvm|divssXrvm|divpdXrvm|divsdXrvm","maxpsXrvm|maxssXrvm|maxpdXrvm|maxsdXrvm",
153--6x 154--6x
154"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", 155"punpcklbwPrvm","punpcklwdPrvm","punpckldqPrvm","packsswbPrvm",
155"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", 156"pcmpgtbPrvm","pcmpgtwPrvm","pcmpgtdPrvm","packuswbPrvm",
156"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", 157"punpckhbwPrvm","punpckhwdPrvm","punpckhdqPrvm","packssdwPrvm",
157"||punpcklqdqXrm","||punpckhqdqXrm", 158"||punpcklqdqXrvm","||punpckhqdqXrvm",
158"movPrVSm","movqMrm|movdquXrm|movdqaXrm", 159"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
159--7x 160--7x
160"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", 161"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pvmu",
161"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", 162"pshiftd!Pvmu","pshiftq!Mvmu||pshiftdq!Xvmu",
162"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", 163"pcmpeqbPrvm","pcmpeqwPrvm","pcmpeqdPrvm","emms*|",
163"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", 164"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
164nil,nil, 165nil,nil,
165"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", 166"||haddpdXrvm|haddpsXrvm","||hsubpdXrvm|hsubpsXrvm",
166"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", 167"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
167--8x 168--8x
168"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", 169"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
@@ -180,27 +181,27 @@ nil,nil,
180"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", 181"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
181--Cx 182--Cx
182"xaddBmr","xaddVmr", 183"xaddBmr","xaddVmr",
183"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", 184"cmppsXrvmu|cmpssXrvmu|cmppdXrvmu|cmpsdXrvmu","$movntiVmr|",
184"pinsrwPrWmu","pextrwDrPmu", 185"pinsrwPrvWmu","pextrwDrPmu",
185"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", 186"shufpsXrvmu||shufpdXrvmu","$cmpxchg!Qmp",
186"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", 187"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
187--Dx 188--Dx
188"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", 189"||addsubpdXrvm|addsubpsXrvm","psrlwPrvm","psrldPrvm","psrlqPrvm",
189"paddqPrm","pmullwPrm", 190"paddqPrvm","pmullwPrvm",
190"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", 191"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
191"psubusbPrm","psubuswPrm","pminubPrm","pandPrm", 192"psubusbPrvm","psubuswPrvm","pminubPrvm","pandPrvm",
192"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", 193"paddusbPrvm","padduswPrvm","pmaxubPrvm","pandnPrvm",
193--Ex 194--Ex
194"pavgbPrm","psrawPrm","psradPrm","pavgwPrm", 195"pavgbPrvm","psrawPrvm","psradPrvm","pavgwPrvm",
195"pmulhuwPrm","pmulhwPrm", 196"pmulhuwPrvm","pmulhwPrvm",
196"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", 197"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
197"psubsbPrm","psubswPrm","pminswPrm","porPrm", 198"psubsbPrvm","psubswPrvm","pminswPrvm","porPrvm",
198"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", 199"paddsbPrvm","paddswPrvm","pmaxswPrvm","pxorPrvm",
199--Fx 200--Fx
200"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", 201"|||lddquXrm","psllwPrvm","pslldPrvm","psllqPrvm",
201"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", 202"pmuludqPrvm","pmaddwdPrvm","psadbwPrvm","maskmovqMrm||maskmovdquXrm$",
202"psubbPrm","psubwPrm","psubdPrm","psubqPrm", 203"psubbPrvm","psubwPrvm","psubdPrvm","psubqPrvm",
203"paddbPrm","paddwPrm","padddPrm","ud", 204"paddbPrvm","paddwPrvm","padddPrvm","ud",
204} 205}
205assert(map_opc2[255] == "ud") 206assert(map_opc2[255] == "ud")
206 207
@@ -208,49 +209,73 @@ assert(map_opc2[255] == "ud")
208local map_opc3 = { 209local map_opc3 = {
209["38"] = { -- [66] 0f 38 xx 210["38"] = { -- [66] 0f 38 xx
210--0x 211--0x
211[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", 212[0]="pshufbPrvm","phaddwPrvm","phadddPrvm","phaddswPrvm",
212"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", 213"pmaddubswPrvm","phsubwPrvm","phsubdPrvm","phsubswPrvm",
213"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", 214"psignbPrvm","psignwPrvm","psigndPrvm","pmulhrswPrvm",
214nil,nil,nil,nil, 215"||permilpsXrvm","||permilpdXrvm",nil,nil,
215--1x 216--1x
216"||pblendvbXrma",nil,nil,nil, 217"||pblendvbXrma",nil,nil,nil,
217"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", 218"||blendvpsXrma","||blendvpdXrma","||permpsXrvm","||ptestXrm",
218nil,nil,nil,nil, 219"||broadcastssXrm","||broadcastsdXrm","||broadcastf128XrlXm",nil,
219"pabsbPrm","pabswPrm","pabsdPrm",nil, 220"pabsbPrm","pabswPrm","pabsdPrm",nil,
220--2x 221--2x
221"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", 222"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
222"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, 223"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
223"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", 224"||pmuldqXrvm","||pcmpeqqXrvm","||$movntdqaXrm","||packusdwXrvm",
224nil,nil,nil,nil, 225"||maskmovpsXrvm","||maskmovpdXrvm","||maskmovpsXmvr","||maskmovpdXmvr",
225--3x 226--3x
226"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", 227"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
227"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", 228"||pmovzxwqXrm","||pmovzxdqXrm","||permdXrvm","||pcmpgtqXrvm",
228"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", 229"||pminsbXrvm","||pminsdXrvm","||pminuwXrvm","||pminudXrvm",
229"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", 230"||pmaxsbXrvm","||pmaxsdXrvm","||pmaxuwXrvm","||pmaxudXrvm",
230--4x 231--4x
231"||pmulddXrm","||phminposuwXrm", 232"||pmulddXrvm","||phminposuwXrm",nil,nil,
233nil,"||psrlvVSXrvm","||psravdXrvm","||psllvVSXrvm",
234--5x
235[0x58] = "||pbroadcastdXrlXm",[0x59] = "||pbroadcastqXrlXm",
236[0x5a] = "||broadcasti128XrlXm",
237--7x
238[0x78] = "||pbroadcastbXrlXm",[0x79] = "||pbroadcastwXrlXm",
239--8x
240[0x8c] = "||pmaskmovXrvVSm",
241[0x8e] = "||pmaskmovVSmXvr",
242--Dx
243[0xdc] = "||aesencXrvm", [0xdd] = "||aesenclastXrvm",
244[0xde] = "||aesdecXrvm", [0xdf] = "||aesdeclastXrvm",
232--Fx 245--Fx
233[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", 246[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
247[0xf7] = "| sarxVrmv| shlxVrmv| shrxVrmv",
234}, 248},
235 249
236["3a"] = { -- [66] 0f 3a xx 250["3a"] = { -- [66] 0f 3a xx
237--0x 251--0x
238[0x00]=nil,nil,nil,nil,nil,nil,nil,nil, 252[0x00]="||permqXrmu","||permpdXrmu","||pblenddXrvmu",nil,
239"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", 253"||permilpsXrmu","||permilpdXrmu","||perm2f128Xrvmu",nil,
240"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", 254"||roundpsXrmu","||roundpdXrmu","||roundssXrvmu","||roundsdXrvmu",
255"||blendpsXrvmu","||blendpdXrvmu","||pblendwXrvmu","palignrPrvmu",
241--1x 256--1x
242nil,nil,nil,nil, 257nil,nil,nil,nil,
243"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", 258"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
244nil,nil,nil,nil,nil,nil,nil,nil, 259"||insertf128XrvlXmu","||extractf128XlXmYru",nil,nil,
260nil,nil,nil,nil,
245--2x 261--2x
246"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, 262"||pinsrbXrvVmu","||insertpsXrvmu","||pinsrXrvVmuS",nil,
263--3x
264[0x38] = "||inserti128Xrvmu",[0x39] = "||extracti128XlXmYru",
247--4x 265--4x
248[0x40] = "||dppsXrmu", 266[0x40] = "||dppsXrvmu",
249[0x41] = "||dppdXrmu", 267[0x41] = "||dppdXrvmu",
250[0x42] = "||mpsadbwXrmu", 268[0x42] = "||mpsadbwXrvmu",
269[0x44] = "||pclmulqdqXrvmu",
270[0x46] = "||perm2i128Xrvmu",
271[0x4a] = "||blendvpsXrvmb",[0x4b] = "||blendvpdXrvmb",
272[0x4c] = "||pblendvbXrvmb",
251--6x 273--6x
252[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", 274[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
253[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", 275[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
276[0xdf] = "||aeskeygenassistXrmu",
277--Fx
278[0xf0] = "||| rorxVrmu",
254}, 279},
255} 280}
256 281
@@ -354,17 +379,19 @@ local map_regs = {
354 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! 379 "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
355 X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", 380 X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
356 "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, 381 "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
382 Y = { "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7",
383 "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15" },
357} 384}
358local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } 385local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
359 386
360-- Maps for size names. 387-- Maps for size names.
361local map_sz2n = { 388local map_sz2n = {
362 B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, 389 B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, Y = 32,
363} 390}
364local map_sz2prefix = { 391local map_sz2prefix = {
365 B = "byte", W = "word", D = "dword", 392 B = "byte", W = "word", D = "dword",
366 Q = "qword", 393 Q = "qword",
367 M = "qword", X = "xword", 394 M = "qword", X = "xword", Y = "yword",
368 F = "dword", G = "qword", -- No need for sizes/register names for these two. 395 F = "dword", G = "qword", -- No need for sizes/register names for these two.
369} 396}
370 397
@@ -387,10 +414,13 @@ local function putop(ctx, text, operands)
387 if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end 414 if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
388 if ctx.rex then 415 if ctx.rex then
389 local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. 416 local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
390 (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") 417 (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")..
391 if t ~= "" then text = "rex."..t.." "..text end 418 (ctx.vexl and "l" or "")
419 if ctx.vexv and ctx.vexv ~= 0 then t = t.."v"..ctx.vexv end
420 if t ~= "" then text = ctx.rex.."."..t.." "..gsub(text, "^ ", "")
421 elseif ctx.rex == "vex" then text = gsub("v"..text, "^v ", "") end
392 ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false 422 ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
393 ctx.rex = false 423 ctx.rex = false; ctx.vexl = false; ctx.vexv = false
394 end 424 end
395 if ctx.seg then 425 if ctx.seg then
396 local text2, n = gsub(text, "%[", "["..ctx.seg..":") 426 local text2, n = gsub(text, "%[", "["..ctx.seg..":")
@@ -405,6 +435,7 @@ local function putop(ctx, text, operands)
405 end 435 end
406 ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) 436 ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
407 ctx.mrm = false 437 ctx.mrm = false
438 ctx.vexv = false
408 ctx.start = pos 439 ctx.start = pos
409 ctx.imm = nil 440 ctx.imm = nil
410end 441end
@@ -413,7 +444,7 @@ end
413local function clearprefixes(ctx) 444local function clearprefixes(ctx)
414 ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false 445 ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
415 ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false 446 ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
416 ctx.rex = false; ctx.a32 = false 447 ctx.rex = false; ctx.a32 = false; ctx.vexl = false
417end 448end
418 449
419-- Fallback for incomplete opcodes at the end. 450-- Fallback for incomplete opcodes at the end.
@@ -450,9 +481,9 @@ end
450-- Process pattern string and generate the operands. 481-- Process pattern string and generate the operands.
451local function putpat(ctx, name, pat) 482local function putpat(ctx, name, pat)
452 local operands, regs, sz, mode, sp, rm, sc, rx, sdisp 483 local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
453 local code, pos, stop = ctx.code, ctx.pos, ctx.stop 484 local code, pos, stop, vexl = ctx.code, ctx.pos, ctx.stop, ctx.vexl
454 485
455 -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz 486 -- Chars used: 1DFGIMPQRSTUVWXYabcdfgijlmoprstuvwxyz
456 for p in gmatch(pat, ".") do 487 for p in gmatch(pat, ".") do
457 local x = nil 488 local x = nil
458 if p == "V" or p == "U" then 489 if p == "V" or p == "U" then
@@ -467,11 +498,13 @@ local function putpat(ctx, name, pat)
467 elseif p == "B" then 498 elseif p == "B" then
468 sz = "B" 499 sz = "B"
469 regs = ctx.rex and map_regs.B64 or map_regs.B 500 regs = ctx.rex and map_regs.B64 or map_regs.B
470 elseif match(p, "[WDQMXFG]") then 501 elseif match(p, "[WDQMXYFG]") then
471 sz = p 502 sz = p
503 if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end
472 regs = map_regs[sz] 504 regs = map_regs[sz]
473 elseif p == "P" then 505 elseif p == "P" then
474 sz = ctx.o16 and "X" or "M"; ctx.o16 = false 506 sz = ctx.o16 and "X" or "M"; ctx.o16 = false
507 if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end
475 regs = map_regs[sz] 508 regs = map_regs[sz]
476 elseif p == "S" then 509 elseif p == "S" then
477 name = name..lower(sz) 510 name = name..lower(sz)
@@ -484,6 +517,10 @@ local function putpat(ctx, name, pat)
484 local imm = getimm(ctx, pos, 1); if not imm then return end 517 local imm = getimm(ctx, pos, 1); if not imm then return end
485 x = format("0x%02x", imm) 518 x = format("0x%02x", imm)
486 pos = pos+1 519 pos = pos+1
520 elseif p == "b" then
521 local imm = getimm(ctx, pos, 1); if not imm then return end
522 x = regs[imm/16+1]
523 pos = pos+1
487 elseif p == "w" then 524 elseif p == "w" then
488 local imm = getimm(ctx, pos, 2); if not imm then return end 525 local imm = getimm(ctx, pos, 2); if not imm then return end
489 x = format("0x%x", imm) 526 x = format("0x%x", imm)
@@ -532,7 +569,7 @@ local function putpat(ctx, name, pat)
532 local lo = imm % 0x1000000 569 local lo = imm % 0x1000000
533 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) 570 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
534 else 571 else
535 x = format("0x%08x", imm) 572 x = "0x"..tohex(imm)
536 end 573 end
537 elseif p == "R" then 574 elseif p == "R" then
538 local r = byte(code, pos-1, pos-1)%8 575 local r = byte(code, pos-1, pos-1)%8
@@ -616,8 +653,13 @@ local function putpat(ctx, name, pat)
616 else 653 else
617 x = "CR"..sp 654 x = "CR"..sp
618 end 655 end
656 elseif p == "v" then
657 if ctx.vexv then
658 x = regs[ctx.vexv+1]; ctx.vexv = false
659 end
619 elseif p == "y" then x = "DR"..sp 660 elseif p == "y" then x = "DR"..sp
620 elseif p == "z" then x = "TR"..sp 661 elseif p == "z" then x = "TR"..sp
662 elseif p == "l" then vexl = false
621 elseif p == "t" then 663 elseif p == "t" then
622 else 664 else
623 error("bad pattern `"..pat.."'") 665 error("bad pattern `"..pat.."'")
@@ -692,7 +734,7 @@ map_act = {
692 B = putpat, W = putpat, D = putpat, Q = putpat, 734 B = putpat, W = putpat, D = putpat, Q = putpat,
693 V = putpat, U = putpat, T = putpat, 735 V = putpat, U = putpat, T = putpat,
694 M = putpat, X = putpat, P = putpat, 736 M = putpat, X = putpat, P = putpat,
695 F = putpat, G = putpat, 737 F = putpat, G = putpat, Y = putpat,
696 738
697 -- Collect prefixes. 739 -- Collect prefixes.
698 [":"] = function(ctx, name, pat) 740 [":"] = function(ctx, name, pat)
@@ -753,15 +795,68 @@ map_act = {
753 795
754 -- REX prefix. 796 -- REX prefix.
755 rex = function(ctx, name, pat) 797 rex = function(ctx, name, pat)
756 if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. 798 if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed.
757 for p in gmatch(pat, ".") do ctx["rex"..p] = true end 799 for p in gmatch(pat, ".") do ctx["rex"..p] = true end
758 ctx.rex = true 800 ctx.rex = "rex"
801 end,
802
803 -- VEX prefix.
804 vex = function(ctx, name, pat)
805 if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed.
806 ctx.rex = "vex"
807 local pos = ctx.pos
808 if ctx.mrm then
809 ctx.mrm = nil
810 pos = pos-1
811 end
812 local b = byte(ctx.code, pos, pos)
813 if not b then return incomplete(ctx) end
814 pos = pos+1
815 if b < 128 then ctx.rexr = true end
816 local m = 1
817 if pat == "3" then
818 m = b%32; b = (b-m)/32
819 local nb = b%2; b = (b-nb)/2
820 if nb == 0 then ctx.rexb = true end
821 local nx = b%2
822 if nx == 0 then ctx.rexx = true end
823 b = byte(ctx.code, pos, pos)
824 if not b then return incomplete(ctx) end
825 pos = pos+1
826 if b >= 128 then ctx.rexw = true end
827 end
828 ctx.pos = pos
829 local map
830 if m == 1 then map = map_opc2
831 elseif m == 2 then map = map_opc3["38"]
832 elseif m == 3 then map = map_opc3["3a"]
833 else return unknown(ctx) end
834 local p = b%4; b = (b-p)/4
835 if p == 1 then ctx.o16 = "o16"
836 elseif p == 2 then ctx.rep = "rep"
837 elseif p == 3 then ctx.rep = "repne" end
838 local l = b%2; b = (b-l)/2
839 if l ~= 0 then ctx.vexl = true end
840 ctx.vexv = (-1-b)%16
841 return dispatchmap(ctx, map)
759 end, 842 end,
760 843
761 -- Special case for nop with REX prefix. 844 -- Special case for nop with REX prefix.
762 nop = function(ctx, name, pat) 845 nop = function(ctx, name, pat)
763 return dispatch(ctx, ctx.rex and pat or "nop") 846 return dispatch(ctx, ctx.rex and pat or "nop")
764 end, 847 end,
848
849 -- Special case for 0F 77.
850 emms = function(ctx, name, pat)
851 if ctx.rex ~= "vex" then
852 return putop(ctx, "emms")
853 elseif ctx.vexl then
854 ctx.vexl = false
855 return putop(ctx, "zeroall")
856 else
857 return putop(ctx, "zeroupper")
858 end
859 end,
765} 860}
766 861
767------------------------------------------------------------------------------ 862------------------------------------------------------------------------------
@@ -782,7 +877,7 @@ local function disass_block(ctx, ofs, len)
782end 877end
783 878
784-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). 879-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
785local function create_(code, addr, out) 880local function create(code, addr, out)
786 local ctx = {} 881 local ctx = {}
787 ctx.code = code 882 ctx.code = code
788 ctx.addr = (addr or 0) - 1 883 ctx.addr = (addr or 0) - 1
@@ -796,8 +891,8 @@ local function create_(code, addr, out)
796 return ctx 891 return ctx
797end 892end
798 893
799local function create64_(code, addr, out) 894local function create64(code, addr, out)
800 local ctx = create_(code, addr, out) 895 local ctx = create(code, addr, out)
801 ctx.x64 = true 896 ctx.x64 = true
802 ctx.map1 = map_opc1_64 897 ctx.map1 = map_opc1_64
803 ctx.aregs = map_regs.Q 898 ctx.aregs = map_regs.Q
@@ -805,32 +900,32 @@ local function create64_(code, addr, out)
805end 900end
806 901
807-- Simple API: disassemble code (a string) at address and output via out. 902-- Simple API: disassemble code (a string) at address and output via out.
808local function disass_(code, addr, out) 903local function disass(code, addr, out)
809 create_(code, addr, out):disass() 904 create(code, addr, out):disass()
810end 905end
811 906
812local function disass64_(code, addr, out) 907local function disass64(code, addr, out)
813 create64_(code, addr, out):disass() 908 create64(code, addr, out):disass()
814end 909end
815 910
816-- Return register name for RID. 911-- Return register name for RID.
817local function regname_(r) 912local function regname(r)
818 if r < 8 then return map_regs.D[r+1] end 913 if r < 8 then return map_regs.D[r+1] end
819 return map_regs.X[r-7] 914 return map_regs.X[r-7]
820end 915end
821 916
822local function regname64_(r) 917local function regname64(r)
823 if r < 16 then return map_regs.Q[r+1] end 918 if r < 16 then return map_regs.Q[r+1] end
824 return map_regs.X[r-15] 919 return map_regs.X[r-15]
825end 920end
826 921
827-- Public module functions. 922-- Public module functions.
828module(...) 923return {
829 924 create = create,
830create = create_ 925 create64 = create64,
831create64 = create64_ 926 disass = disass,
832disass = disass_ 927 disass64 = disass64,
833disass64 = disass64_ 928 regname = regname,
834regname = regname_ 929 regname64 = regname64
835regname64 = regname64_ 930}
836 931
diff --git a/src/jit/dump.lua b/src/jit/dump.lua
index 6c6abb66..2bea652b 100644
--- a/src/jit/dump.lua
+++ b/src/jit/dump.lua
@@ -55,7 +55,7 @@
55 55
56-- Cache some library functions and objects. 56-- Cache some library functions and objects.
57local jit = require("jit") 57local jit = require("jit")
58assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") 58assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
59local jutil = require("jit.util") 59local jutil = require("jit.util")
60local vmdef = require("jit.vmdef") 60local vmdef = require("jit.vmdef")
61local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc 61local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc
@@ -63,7 +63,7 @@ local traceinfo, traceir, tracek = jutil.traceinfo, jutil.traceir, jutil.tracek
63local tracemc, tracesnap = jutil.tracemc, jutil.tracesnap 63local tracemc, tracesnap = jutil.tracemc, jutil.tracesnap
64local traceexitstub, ircalladdr = jutil.traceexitstub, jutil.ircalladdr 64local traceexitstub, ircalladdr = jutil.traceexitstub, jutil.ircalladdr
65local bit = require("bit") 65local bit = require("bit")
66local band, shr = bit.band, bit.rshift 66local band, shr, tohex = bit.band, bit.rshift, bit.tohex
67local sub, gsub, format = string.sub, string.gsub, string.format 67local sub, gsub, format = string.sub, string.gsub, string.format
68local byte, rep = string.byte, string.rep 68local byte, rep = string.byte, string.rep
69local type, tostring = type, tostring 69local type, tostring = type, tostring
@@ -85,12 +85,13 @@ local nexitsym = 0
85local function fillsymtab_tr(tr, nexit) 85local function fillsymtab_tr(tr, nexit)
86 local t = {} 86 local t = {}
87 symtabmt.__index = t 87 symtabmt.__index = t
88 if jit.arch == "mips" or jit.arch == "mipsel" then 88 if jit.arch:sub(1, 4) == "mips" then
89 t[traceexitstub(tr, 0)] = "exit" 89 t[traceexitstub(tr, 0)] = "exit"
90 return 90 return
91 end 91 end
92 for i=0,nexit-1 do 92 for i=0,nexit-1 do
93 local addr = traceexitstub(tr, i) 93 local addr = traceexitstub(tr, i)
94 if addr < 0 then addr = addr + 2^32 end
94 t[addr] = tostring(i) 95 t[addr] = tostring(i)
95 end 96 end
96 local addr = traceexitstub(tr, nexit) 97 local addr = traceexitstub(tr, nexit)
@@ -104,7 +105,10 @@ local function fillsymtab(tr, nexit)
104 local ircall = vmdef.ircall 105 local ircall = vmdef.ircall
105 for i=0,#ircall do 106 for i=0,#ircall do
106 local addr = ircalladdr(i) 107 local addr = ircalladdr(i)
107 if addr ~= 0 then t[addr] = ircall[i] end 108 if addr ~= 0 then
109 if addr < 0 then addr = addr + 2^32 end
110 t[addr] = ircall[i]
111 end
108 end 112 end
109 end 113 end
110 if nexitsym == 1000000 then -- Per-trace exit stubs. 114 if nexitsym == 1000000 then -- Per-trace exit stubs.
@@ -118,6 +122,7 @@ local function fillsymtab(tr, nexit)
118 nexit = 1000000 122 nexit = 1000000
119 break 123 break
120 end 124 end
125 if addr < 0 then addr = addr + 2^32 end
121 t[addr] = tostring(i) 126 t[addr] = tostring(i)
122 end 127 end
123 nexitsym = nexit 128 nexitsym = nexit
@@ -136,6 +141,7 @@ local function dump_mcode(tr)
136 local mcode, addr, loop = tracemc(tr) 141 local mcode, addr, loop = tracemc(tr)
137 if not mcode then return end 142 if not mcode then return end
138 if not disass then disass = require("jit.dis_"..jit.arch) end 143 if not disass then disass = require("jit.dis_"..jit.arch) end
144 if addr < 0 then addr = addr + 2^32 end
139 out:write("---- TRACE ", tr, " mcode ", #mcode, "\n") 145 out:write("---- TRACE ", tr, " mcode ", #mcode, "\n")
140 local ctx = disass.create(mcode, addr, dumpwrite) 146 local ctx = disass.create(mcode, addr, dumpwrite)
141 ctx.hexdump = 0 147 ctx.hexdump = 0
@@ -270,8 +276,7 @@ local litname = {
270 ["CONV "] = setmetatable({}, { __index = function(t, mode) 276 ["CONV "] = setmetatable({}, { __index = function(t, mode)
271 local s = irtype[band(mode, 31)] 277 local s = irtype[band(mode, 31)]
272 s = irtype[band(shr(mode, 5), 31)].."."..s 278 s = irtype[band(shr(mode, 5), 31)].."."..s
273 if band(mode, 0x400) ~= 0 then s = s.." trunc" 279 if band(mode, 0x800) ~= 0 then s = s.." sext" end
274 elseif band(mode, 0x800) ~= 0 then s = s.." sext" end
275 local c = shr(mode, 14) 280 local c = shr(mode, 14)
276 if c == 2 then s = s.." index" elseif c == 3 then s = s.." check" end 281 if c == 2 then s = s.." index" elseif c == 3 then s = s.." check" end
277 t[mode] = s 282 t[mode] = s
@@ -280,6 +285,8 @@ local litname = {
280 ["FLOAD "] = vmdef.irfield, 285 ["FLOAD "] = vmdef.irfield,
281 ["FREF "] = vmdef.irfield, 286 ["FREF "] = vmdef.irfield,
282 ["FPMATH"] = vmdef.irfpm, 287 ["FPMATH"] = vmdef.irfpm,
288 ["BUFHDR"] = { [0] = "RESET", "APPEND" },
289 ["TOSTR "] = { [0] = "INT", "NUM", "CHAR" },
283} 290}
284 291
285local function ctlsub(c) 292local function ctlsub(c)
@@ -303,15 +310,17 @@ local function fmtfunc(func, pc)
303 end 310 end
304end 311end
305 312
306local function formatk(tr, idx) 313local function formatk(tr, idx, sn)
307 local k, t, slot = tracek(tr, idx) 314 local k, t, slot = tracek(tr, idx)
308 local tn = type(k) 315 local tn = type(k)
309 local s 316 local s
310 if tn == "number" then 317 if tn == "number" then
311 if k == 2^52+2^51 then 318 if band(sn or 0, 0x30000) ~= 0 then
319 s = band(sn, 0x20000) ~= 0 and "contpc" or "ftsz"
320 elseif k == 2^52+2^51 then
312 s = "bias" 321 s = "bias"
313 else 322 else
314 s = format("%+.14g", k) 323 s = format(0 < k and k < 0x1p-1026 and "%+a" or "%+.14g", k)
315 end 324 end
316 elseif tn == "string" then 325 elseif tn == "string" then
317 s = format(#k > 20 and '"%.20s"~' or '"%s"', gsub(k, "%c", ctlsub)) 326 s = format(#k > 20 and '"%.20s"~' or '"%s"', gsub(k, "%c", ctlsub))
@@ -329,6 +338,8 @@ local function formatk(tr, idx)
329 elseif t == 21 then -- int64_t 338 elseif t == 21 then -- int64_t
330 s = sub(tostring(k), 1, -3) 339 s = sub(tostring(k), 1, -3)
331 if sub(s, 1, 1) ~= "-" then s = "+"..s end 340 if sub(s, 1, 1) ~= "-" then s = "+"..s end
341 elseif sn == 0x1057fff then -- SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL)
342 return "----" -- Special case for LJ_FR2 slot 1.
332 else 343 else
333 s = tostring(k) -- For primitives. 344 s = tostring(k) -- For primitives.
334 end 345 end
@@ -347,7 +358,7 @@ local function printsnap(tr, snap)
347 n = n + 1 358 n = n + 1
348 local ref = band(sn, 0xffff) - 0x8000 -- REF_BIAS 359 local ref = band(sn, 0xffff) - 0x8000 -- REF_BIAS
349 if ref < 0 then 360 if ref < 0 then
350 out:write(formatk(tr, ref)) 361 out:write(formatk(tr, ref, sn))
351 elseif band(sn, 0x80000) ~= 0 then -- SNAP_SOFTFPNUM 362 elseif band(sn, 0x80000) ~= 0 then -- SNAP_SOFTFPNUM
352 out:write(colorize(format("%04d/%04d", ref, ref+1), 14)) 363 out:write(colorize(format("%04d/%04d", ref, ref+1), 14))
353 else 364 else
@@ -545,7 +556,7 @@ local function dump_trace(what, tr, func, pc, otr, oex)
545 if what == "start" then 556 if what == "start" then
546 if dumpmode.H then out:write('<pre class="ljdump">\n') end 557 if dumpmode.H then out:write('<pre class="ljdump">\n') end
547 out:write("---- TRACE ", tr, " ", what) 558 out:write("---- TRACE ", tr, " ", what)
548 if otr then out:write(" ", otr, "/", oex) end 559 if otr then out:write(" ", otr, "/", oex == -1 and "stitch" or oex) end
549 out:write(" ", fmtfunc(func, pc), "\n") 560 out:write(" ", fmtfunc(func, pc), "\n")
550 elseif what == "stop" or what == "abort" then 561 elseif what == "stop" or what == "abort" then
551 out:write("---- TRACE ", tr, " ", what) 562 out:write("---- TRACE ", tr, " ", what)
@@ -608,7 +619,7 @@ local function dump_texit(tr, ex, ngpr, nfpr, ...)
608 end 619 end
609 else 620 else
610 for i=1,ngpr do 621 for i=1,ngpr do
611 out:write(format(" %08x", regs[i])) 622 out:write(" ", tohex(regs[i]))
612 if i % 8 == 0 then out:write("\n") end 623 if i % 8 == 0 then out:write("\n") end
613 end 624 end
614 end 625 end
@@ -693,9 +704,9 @@ local function dumpon(opt, outfile)
693end 704end
694 705
695-- Public module functions. 706-- Public module functions.
696module(...) 707return {
697 708 on = dumpon,
698on = dumpon 709 off = dumpoff,
699off = dumpoff 710 start = dumpon -- For -j command line option.
700start = dumpon -- For -j command line option. 711}
701 712
diff --git a/src/jit/p.lua b/src/jit/p.lua
new file mode 100644
index 00000000..7be10586
--- /dev/null
+++ b/src/jit/p.lua
@@ -0,0 +1,311 @@
1----------------------------------------------------------------------------
2-- LuaJIT profiler.
3--
4-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
5-- Released under the MIT license. See Copyright Notice in luajit.h
6----------------------------------------------------------------------------
7--
8-- This module is a simple command line interface to the built-in
9-- low-overhead profiler of LuaJIT.
10--
11-- The lower-level API of the profiler is accessible via the "jit.profile"
12-- module or the luaJIT_profile_* C API.
13--
14-- Example usage:
15--
16-- luajit -jp myapp.lua
17-- luajit -jp=s myapp.lua
18-- luajit -jp=-s myapp.lua
19-- luajit -jp=vl myapp.lua
20-- luajit -jp=G,profile.txt myapp.lua
21--
22-- The following dump features are available:
23--
24-- f Stack dump: function name, otherwise module:line. Default mode.
25-- F Stack dump: ditto, but always prepend module.
26-- l Stack dump: module:line.
27-- <number> stack dump depth (callee < caller). Default: 1.
28-- -<number> Inverse stack dump depth (caller > callee).
29-- s Split stack dump after first stack level. Implies abs(depth) >= 2.
30-- p Show full path for module names.
31-- v Show VM states. Can be combined with stack dumps, e.g. vf or fv.
32-- z Show zones. Can be combined with stack dumps, e.g. zf or fz.
33-- r Show raw sample counts. Default: show percentages.
34-- a Annotate excerpts from source code files.
35-- A Annotate complete source code files.
36-- G Produce raw output suitable for graphical tools (e.g. flame graphs).
37-- m<number> Minimum sample percentage to be shown. Default: 3.
38-- i<number> Sampling interval in milliseconds. Default: 10.
39--
40----------------------------------------------------------------------------
41
42-- Cache some library functions and objects.
43local jit = require("jit")
44assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
45local profile = require("jit.profile")
46local vmdef = require("jit.vmdef")
47local math = math
48local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor
49local sort, format = table.sort, string.format
50local stdout = io.stdout
51local zone -- Load jit.zone module on demand.
52
53-- Output file handle.
54local out
55
56------------------------------------------------------------------------------
57
58local prof_ud
59local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth
60local prof_ann, prof_count1, prof_count2, prof_samples
61
62local map_vmmode = {
63 N = "Compiled",
64 I = "Interpreted",
65 C = "C code",
66 G = "Garbage Collector",
67 J = "JIT Compiler",
68}
69
70-- Profiler callback.
71local function prof_cb(th, samples, vmmode)
72 prof_samples = prof_samples + samples
73 local key_stack, key_stack2, key_state
74 -- Collect keys for sample.
75 if prof_states then
76 if prof_states == "v" then
77 key_state = map_vmmode[vmmode] or vmmode
78 else
79 key_state = zone:get() or "(none)"
80 end
81 end
82 if prof_fmt then
83 key_stack = profile.dumpstack(th, prof_fmt, prof_depth)
84 key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x)
85 return vmdef.ffnames[tonumber(x)]
86 end)
87 if prof_split == 2 then
88 local k1, k2 = key_stack:match("(.-) [<>] (.*)")
89 if k2 then key_stack, key_stack2 = k1, k2 end
90 elseif prof_split == 3 then
91 key_stack2 = profile.dumpstack(th, "l", 1)
92 end
93 end
94 -- Order keys.
95 local k1, k2
96 if prof_split == 1 then
97 if key_state then
98 k1 = key_state
99 if key_stack then k2 = key_stack end
100 end
101 elseif key_stack then
102 k1 = key_stack
103 if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end
104 end
105 -- Coalesce samples in one or two levels.
106 if k1 then
107 local t1 = prof_count1
108 t1[k1] = (t1[k1] or 0) + samples
109 if k2 then
110 local t2 = prof_count2
111 local t3 = t2[k1]
112 if not t3 then t3 = {}; t2[k1] = t3 end
113 t3[k2] = (t3[k2] or 0) + samples
114 end
115 end
116end
117
118------------------------------------------------------------------------------
119
120-- Show top N list.
121local function prof_top(count1, count2, samples, indent)
122 local t, n = {}, 0
123 for k in pairs(count1) do
124 n = n + 1
125 t[n] = k
126 end
127 sort(t, function(a, b) return count1[a] > count1[b] end)
128 for i=1,n do
129 local k = t[i]
130 local v = count1[k]
131 local pct = floor(v*100/samples + 0.5)
132 if pct < prof_min then break end
133 if not prof_raw then
134 out:write(format("%s%2d%% %s\n", indent, pct, k))
135 elseif prof_raw == "r" then
136 out:write(format("%s%5d %s\n", indent, v, k))
137 else
138 out:write(format("%s %d\n", k, v))
139 end
140 if count2 then
141 local r = count2[k]
142 if r then
143 prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or
144 (prof_depth < 0 and " -> " or " <- "))
145 end
146 end
147 end
148end
149
150-- Annotate source code
151local function prof_annotate(count1, samples)
152 local files = {}
153 local ms = 0
154 for k, v in pairs(count1) do
155 local pct = floor(v*100/samples + 0.5)
156 ms = math.max(ms, v)
157 if pct >= prof_min then
158 local file, line = k:match("^(.*):(%d+)$")
159 if not file then file = k; line = 0 end
160 local fl = files[file]
161 if not fl then fl = {}; files[file] = fl; files[#files+1] = file end
162 line = tonumber(line)
163 fl[line] = prof_raw and v or pct
164 end
165 end
166 sort(files)
167 local fmtv, fmtn = " %3d%% | %s\n", " | %s\n"
168 if prof_raw then
169 local n = math.max(5, math.ceil(math.log10(ms)))
170 fmtv = "%"..n.."d | %s\n"
171 fmtn = (" "):rep(n).." | %s\n"
172 end
173 local ann = prof_ann
174 for _, file in ipairs(files) do
175 local f0 = file:byte()
176 if f0 == 40 or f0 == 91 then
177 out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file))
178 break
179 end
180 local fp, err = io.open(file)
181 if not fp then
182 out:write(format("====== ERROR: %s: %s\n", file, err))
183 break
184 end
185 out:write(format("\n====== %s ======\n", file))
186 local fl = files[file]
187 local n, show = 1, false
188 if ann ~= 0 then
189 for i=1,ann do
190 if fl[i] then show = true; out:write("@@ 1 @@\n"); break end
191 end
192 end
193 for line in fp:lines() do
194 if line:byte() == 27 then
195 out:write("[Cannot annotate bytecode file]\n")
196 break
197 end
198 local v = fl[n]
199 if ann ~= 0 then
200 local v2 = fl[n+ann]
201 if show then
202 if v2 then show = n+ann elseif v then show = n
203 elseif show+ann < n then show = false end
204 elseif v2 then
205 show = n+ann
206 out:write(format("@@ %d @@\n", n))
207 end
208 if not show then goto next end
209 end
210 if v then
211 out:write(format(fmtv, v, line))
212 else
213 out:write(format(fmtn, line))
214 end
215 ::next::
216 n = n + 1
217 end
218 fp:close()
219 end
220end
221
222------------------------------------------------------------------------------
223
224-- Finish profiling and dump result.
225local function prof_finish()
226 if prof_ud then
227 profile.stop()
228 local samples = prof_samples
229 if samples == 0 then
230 if prof_raw ~= true then out:write("[No samples collected]\n") end
231 return
232 end
233 if prof_ann then
234 prof_annotate(prof_count1, samples)
235 else
236 prof_top(prof_count1, prof_count2, samples, "")
237 end
238 prof_count1 = nil
239 prof_count2 = nil
240 prof_ud = nil
241 end
242end
243
244-- Start profiling.
245local function prof_start(mode)
246 local interval = ""
247 mode = mode:gsub("i%d*", function(s) interval = s; return "" end)
248 prof_min = 3
249 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end)
250 prof_depth = 1
251 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end)
252 local m = {}
253 for c in mode:gmatch(".") do m[c] = c end
254 prof_states = m.z or m.v
255 if prof_states == "z" then zone = require("jit.zone") end
256 local scope = m.l or m.f or m.F or (prof_states and "" or "f")
257 local flags = (m.p or "")
258 prof_raw = m.r
259 if m.s then
260 prof_split = 2
261 if prof_depth == -1 or m["-"] then prof_depth = -2
262 elseif prof_depth == 1 then prof_depth = 2 end
263 elseif mode:find("[fF].*l") then
264 scope = "l"
265 prof_split = 3
266 else
267 prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0
268 end
269 prof_ann = m.A and 0 or (m.a and 3)
270 if prof_ann then
271 scope = "l"
272 prof_fmt = "pl"
273 prof_split = 0
274 prof_depth = 1
275 elseif m.G and scope ~= "" then
276 prof_fmt = flags..scope.."Z;"
277 prof_depth = -100
278 prof_raw = true
279 prof_min = 0
280 elseif scope == "" then
281 prof_fmt = false
282 else
283 local sc = prof_split == 3 and m.f or m.F or scope
284 prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ")
285 end
286 prof_count1 = {}
287 prof_count2 = {}
288 prof_samples = 0
289 profile.start(scope:lower()..interval, prof_cb)
290 prof_ud = newproxy(true)
291 getmetatable(prof_ud).__gc = prof_finish
292end
293
294------------------------------------------------------------------------------
295
296local function start(mode, outfile)
297 if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end
298 if outfile then
299 out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
300 else
301 out = stdout
302 end
303 prof_start(mode or "f")
304end
305
306-- Public module functions.
307return {
308 start = start, -- For -j command line option.
309 stop = prof_finish
310}
311
diff --git a/src/jit/v.lua b/src/jit/v.lua
index 0f5407a1..934de985 100644
--- a/src/jit/v.lua
+++ b/src/jit/v.lua
@@ -59,7 +59,7 @@
59 59
60-- Cache some library functions and objects. 60-- Cache some library functions and objects.
61local jit = require("jit") 61local jit = require("jit")
62assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") 62assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
63local jutil = require("jit.util") 63local jutil = require("jit.util")
64local vmdef = require("jit.vmdef") 64local vmdef = require("jit.vmdef")
65local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo 65local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
@@ -99,7 +99,7 @@ end
99local function dump_trace(what, tr, func, pc, otr, oex) 99local function dump_trace(what, tr, func, pc, otr, oex)
100 if what == "start" then 100 if what == "start" then
101 startloc = fmtfunc(func, pc) 101 startloc = fmtfunc(func, pc)
102 startex = otr and "("..otr.."/"..oex..") " or "" 102 startex = otr and "("..otr.."/"..(oex == -1 and "stitch" or oex)..") " or ""
103 else 103 else
104 if what == "abort" then 104 if what == "abort" then
105 local loc = fmtfunc(func, pc) 105 local loc = fmtfunc(func, pc)
@@ -116,6 +116,9 @@ local function dump_trace(what, tr, func, pc, otr, oex)
116 if ltype == "interpreter" then 116 if ltype == "interpreter" then
117 out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", 117 out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
118 tr, startex, startloc)) 118 tr, startex, startloc))
119 elseif ltype == "stitch" then
120 out:write(format("[TRACE %3s %s%s %s %s]\n",
121 tr, startex, startloc, ltype, fmtfunc(func, pc)))
119 elseif link == tr or link == 0 then 122 elseif link == tr or link == 0 then
120 out:write(format("[TRACE %3s %s%s %s]\n", 123 out:write(format("[TRACE %3s %s%s %s]\n",
121 tr, startex, startloc, ltype)) 124 tr, startex, startloc, ltype))
@@ -159,9 +162,9 @@ local function dumpon(outfile)
159end 162end
160 163
161-- Public module functions. 164-- Public module functions.
162module(...) 165return {
163 166 on = dumpon,
164on = dumpon 167 off = dumpoff,
165off = dumpoff 168 start = dumpon -- For -j command line option.
166start = dumpon -- For -j command line option. 169}
167 170
diff --git a/src/jit/zone.lua b/src/jit/zone.lua
new file mode 100644
index 00000000..fa702c4e
--- /dev/null
+++ b/src/jit/zone.lua
@@ -0,0 +1,45 @@
1----------------------------------------------------------------------------
2-- LuaJIT profiler zones.
3--
4-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
5-- Released under the MIT license. See Copyright Notice in luajit.h
6----------------------------------------------------------------------------
7--
8-- This module implements a simple hierarchical zone model.
9--
10-- Example usage:
11--
12-- local zone = require("jit.zone")
13-- zone("AI")
14-- ...
15-- zone("A*")
16-- ...
17-- print(zone:get()) --> "A*"
18-- ...
19-- zone()
20-- ...
21-- print(zone:get()) --> "AI"
22-- ...
23-- zone()
24--
25----------------------------------------------------------------------------
26
27local remove = table.remove
28
29return setmetatable({
30 flush = function(t)
31 for i=#t,1,-1 do t[i] = nil end
32 end,
33 get = function(t)
34 return t[#t]
35 end
36}, {
37 __call = function(t, zone)
38 if zone then
39 t[#t+1] = zone
40 else
41 return (assert(remove(t), "empty zone stack"))
42 end
43 end
44})
45
diff --git a/src/lib_aux.c b/src/lib_aux.c
index 7af1cd43..4e137949 100644
--- a/src/lib_aux.c
+++ b/src/lib_aux.c
@@ -302,7 +302,7 @@ static int panic(lua_State *L)
302 302
303#ifdef LUAJIT_USE_SYSMALLOC 303#ifdef LUAJIT_USE_SYSMALLOC
304 304
305#if LJ_64 && !defined(LUAJIT_USE_VALGRIND) 305#if LJ_64 && !LJ_GC64 && !defined(LUAJIT_USE_VALGRIND)
306#error "Must use builtin allocator for 64 bit target" 306#error "Must use builtin allocator for 64 bit target"
307#endif 307#endif
308 308
@@ -334,7 +334,7 @@ LUALIB_API lua_State *luaL_newstate(void)
334 lua_State *L; 334 lua_State *L;
335 void *ud = lj_alloc_create(); 335 void *ud = lj_alloc_create();
336 if (ud == NULL) return NULL; 336 if (ud == NULL) return NULL;
337#if LJ_64 337#if LJ_64 && !LJ_GC64
338 L = lj_state_newstate(lj_alloc_f, ud); 338 L = lj_state_newstate(lj_alloc_f, ud);
339#else 339#else
340 L = lua_newstate(lj_alloc_f, ud); 340 L = lua_newstate(lj_alloc_f, ud);
@@ -343,7 +343,7 @@ LUALIB_API lua_State *luaL_newstate(void)
343 return L; 343 return L;
344} 344}
345 345
346#if LJ_64 346#if LJ_64 && !LJ_GC64
347LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud) 347LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud)
348{ 348{
349 UNUSED(f); UNUSED(ud); 349 UNUSED(f); UNUSED(ud);
diff --git a/src/lib_base.c b/src/lib_base.c
index 162bbbb2..44014f9b 100644
--- a/src/lib_base.c
+++ b/src/lib_base.c
@@ -23,6 +23,7 @@
23#include "lj_tab.h" 23#include "lj_tab.h"
24#include "lj_meta.h" 24#include "lj_meta.h"
25#include "lj_state.h" 25#include "lj_state.h"
26#include "lj_frame.h"
26#if LJ_HASFFI 27#if LJ_HASFFI
27#include "lj_ctype.h" 28#include "lj_ctype.h"
28#include "lj_cconv.h" 29#include "lj_cconv.h"
@@ -32,6 +33,7 @@
32#include "lj_dispatch.h" 33#include "lj_dispatch.h"
33#include "lj_char.h" 34#include "lj_char.h"
34#include "lj_strscan.h" 35#include "lj_strscan.h"
36#include "lj_strfmt.h"
35#include "lj_lib.h" 37#include "lj_lib.h"
36 38
37/* -- Base library: checks ------------------------------------------------ */ 39/* -- Base library: checks ------------------------------------------------ */
@@ -86,10 +88,11 @@ static int ffh_pairs(lua_State *L, MMS mm)
86 cTValue *mo = lj_meta_lookup(L, o, mm); 88 cTValue *mo = lj_meta_lookup(L, o, mm);
87 if ((LJ_52 || tviscdata(o)) && !tvisnil(mo)) { 89 if ((LJ_52 || tviscdata(o)) && !tvisnil(mo)) {
88 L->top = o+1; /* Only keep one argument. */ 90 L->top = o+1; /* Only keep one argument. */
89 copyTV(L, L->base-1, mo); /* Replace callable. */ 91 copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
90 return FFH_TAILCALL; 92 return FFH_TAILCALL;
91 } else { 93 } else {
92 if (!tvistab(o)) lj_err_argt(L, 1, LUA_TTABLE); 94 if (!tvistab(o)) lj_err_argt(L, 1, LUA_TTABLE);
95 if (LJ_FR2) { copyTV(L, o-1, o); o--; }
93 setfuncV(L, o-1, funcV(lj_lib_upvalue(L, 1))); 96 setfuncV(L, o-1, funcV(lj_lib_upvalue(L, 1)));
94 if (mm == MM_pairs) setnilV(o+1); else setintV(o+1, 0); 97 if (mm == MM_pairs) setnilV(o+1); else setintV(o+1, 0);
95 return FFH_RES(3); 98 return FFH_RES(3);
@@ -100,7 +103,7 @@ static int ffh_pairs(lua_State *L, MMS mm)
100#endif 103#endif
101 104
102LJLIB_PUSH(lastcl) 105LJLIB_PUSH(lastcl)
103LJLIB_ASM(pairs) 106LJLIB_ASM(pairs) LJLIB_REC(xpairs 0)
104{ 107{
105 return ffh_pairs(L, MM_pairs); 108 return ffh_pairs(L, MM_pairs);
106} 109}
@@ -113,7 +116,7 @@ LJLIB_NOREGUV LJLIB_ASM(ipairs_aux) LJLIB_REC(.)
113} 116}
114 117
115LJLIB_PUSH(lastcl) 118LJLIB_PUSH(lastcl)
116LJLIB_ASM(ipairs) LJLIB_REC(.) 119LJLIB_ASM(ipairs) LJLIB_REC(xpairs 1)
117{ 120{
118 return ffh_pairs(L, MM_ipairs); 121 return ffh_pairs(L, MM_ipairs);
119} 122}
@@ -131,11 +134,11 @@ LJLIB_ASM(setmetatable) LJLIB_REC(.)
131 lj_err_caller(L, LJ_ERR_PROTMT); 134 lj_err_caller(L, LJ_ERR_PROTMT);
132 setgcref(t->metatable, obj2gco(mt)); 135 setgcref(t->metatable, obj2gco(mt));
133 if (mt) { lj_gc_objbarriert(L, t, mt); } 136 if (mt) { lj_gc_objbarriert(L, t, mt); }
134 settabV(L, L->base-1, t); 137 settabV(L, L->base-1-LJ_FR2, t);
135 return FFH_RES(1); 138 return FFH_RES(1);
136} 139}
137 140
138LJLIB_CF(getfenv) 141LJLIB_CF(getfenv) LJLIB_REC(.)
139{ 142{
140 GCfunc *fn; 143 GCfunc *fn;
141 cTValue *o = L->base; 144 cTValue *o = L->base;
@@ -144,6 +147,7 @@ LJLIB_CF(getfenv)
144 o = lj_debug_frame(L, level, &level); 147 o = lj_debug_frame(L, level, &level);
145 if (o == NULL) 148 if (o == NULL)
146 lj_err_arg(L, 1, LJ_ERR_INVLVL); 149 lj_err_arg(L, 1, LJ_ERR_INVLVL);
150 if (LJ_FR2) o--;
147 } 151 }
148 fn = &gcval(o)->fn; 152 fn = &gcval(o)->fn;
149 settabV(L, L->top++, isluafunc(fn) ? tabref(fn->l.env) : tabref(L->env)); 153 settabV(L, L->top++, isluafunc(fn) ? tabref(fn->l.env) : tabref(L->env));
@@ -165,6 +169,7 @@ LJLIB_CF(setfenv)
165 o = lj_debug_frame(L, level, &level); 169 o = lj_debug_frame(L, level, &level);
166 if (o == NULL) 170 if (o == NULL)
167 lj_err_arg(L, 1, LJ_ERR_INVLVL); 171 lj_err_arg(L, 1, LJ_ERR_INVLVL);
172 if (LJ_FR2) o--;
168 } 173 }
169 fn = &gcval(o)->fn; 174 fn = &gcval(o)->fn;
170 if (!isluafunc(fn)) 175 if (!isluafunc(fn))
@@ -257,7 +262,7 @@ LJLIB_ASM(tonumber) LJLIB_REC(.)
257 if (base == 10) { 262 if (base == 10) {
258 TValue *o = lj_lib_checkany(L, 1); 263 TValue *o = lj_lib_checkany(L, 1);
259 if (lj_strscan_numberobj(o)) { 264 if (lj_strscan_numberobj(o)) {
260 copyTV(L, L->base-1, o); 265 copyTV(L, L->base-1-LJ_FR2, o);
261 return FFH_RES(1); 266 return FFH_RES(1);
262 } 267 }
263#if LJ_HASFFI 268#if LJ_HASFFI
@@ -270,11 +275,11 @@ LJLIB_ASM(tonumber) LJLIB_REC(.)
270 ct->size <= 4 && !(ct->size == 4 && (ct->info & CTF_UNSIGNED))) { 275 ct->size <= 4 && !(ct->size == 4 && (ct->info & CTF_UNSIGNED))) {
271 int32_t i; 276 int32_t i;
272 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o, 0); 277 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_INT32), (uint8_t *)&i, o, 0);
273 setintV(L->base-1, i); 278 setintV(L->base-1-LJ_FR2, i);
274 return FFH_RES(1); 279 return FFH_RES(1);
275 } 280 }
276 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_DOUBLE), 281 lj_cconv_ct_tv(cts, ctype_get(cts, CTID_DOUBLE),
277 (uint8_t *)&(L->base-1)->n, o, 0); 282 (uint8_t *)&(L->base-1-LJ_FR2)->n, o, 0);
278 return FFH_RES(1); 283 return FFH_RES(1);
279 } 284 }
280 } 285 }
@@ -290,45 +295,29 @@ LJLIB_ASM(tonumber) LJLIB_REC(.)
290 while (lj_char_isspace((unsigned char)(*ep))) ep++; 295 while (lj_char_isspace((unsigned char)(*ep))) ep++;
291 if (*ep == '\0') { 296 if (*ep == '\0') {
292 if (LJ_DUALNUM && LJ_LIKELY(ul < 0x80000000u)) 297 if (LJ_DUALNUM && LJ_LIKELY(ul < 0x80000000u))
293 setintV(L->base-1, (int32_t)ul); 298 setintV(L->base-1-LJ_FR2, (int32_t)ul);
294 else 299 else
295 setnumV(L->base-1, (lua_Number)ul); 300 setnumV(L->base-1-LJ_FR2, (lua_Number)ul);
296 return FFH_RES(1); 301 return FFH_RES(1);
297 } 302 }
298 } 303 }
299 } 304 }
300 setnilV(L->base-1); 305 setnilV(L->base-1-LJ_FR2);
301 return FFH_RES(1); 306 return FFH_RES(1);
302} 307}
303 308
304LJLIB_PUSH("nil")
305LJLIB_PUSH("false")
306LJLIB_PUSH("true")
307LJLIB_ASM(tostring) LJLIB_REC(.) 309LJLIB_ASM(tostring) LJLIB_REC(.)
308{ 310{
309 TValue *o = lj_lib_checkany(L, 1); 311 TValue *o = lj_lib_checkany(L, 1);
310 cTValue *mo; 312 cTValue *mo;
311 L->top = o+1; /* Only keep one argument. */ 313 L->top = o+1; /* Only keep one argument. */
312 if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) { 314 if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {
313 copyTV(L, L->base-1, mo); /* Replace callable. */ 315 copyTV(L, L->base-1-LJ_FR2, mo); /* Replace callable. */
314 return FFH_TAILCALL; 316 return FFH_TAILCALL;
315 } else {
316 GCstr *s;
317 if (tvisnumber(o)) {
318 s = lj_str_fromnumber(L, o);
319 } else if (tvispri(o)) {
320 s = strV(lj_lib_upvalue(L, -(int32_t)itype(o)));
321 } else {
322 if (tvisfunc(o) && isffunc(funcV(o)))
323 lua_pushfstring(L, "function: builtin#%d", funcV(o)->c.ffid);
324 else
325 lua_pushfstring(L, "%s: %p", lj_typename(o), lua_topointer(L, 1));
326 /* Note: lua_pushfstring calls the GC which may invalidate o. */
327 s = strV(L->top-1);
328 }
329 setstrV(L, L->base-1, s);
330 return FFH_RES(1);
331 } 317 }
318 lj_gc_check(L);
319 setstrV(L, L->base-1-LJ_FR2, lj_strfmt_obj(L, L->base));
320 return FFH_RES(1);
332} 321}
333 322
334/* -- Base library: throw and catch errors -------------------------------- */ 323/* -- Base library: throw and catch errors -------------------------------- */
@@ -440,20 +429,20 @@ LJLIB_CF(dofile)
440 429
441LJLIB_CF(gcinfo) 430LJLIB_CF(gcinfo)
442{ 431{
443 setintV(L->top++, (G(L)->gc.total >> 10)); 432 setintV(L->top++, (int32_t)(G(L)->gc.total >> 10));
444 return 1; 433 return 1;
445} 434}
446 435
447LJLIB_CF(collectgarbage) 436LJLIB_CF(collectgarbage)
448{ 437{
449 int opt = lj_lib_checkopt(L, 1, LUA_GCCOLLECT, /* ORDER LUA_GC* */ 438 int opt = lj_lib_checkopt(L, 1, LUA_GCCOLLECT, /* ORDER LUA_GC* */
450 "\4stop\7restart\7collect\5count\1\377\4step\10setpause\12setstepmul"); 439 "\4stop\7restart\7collect\5count\1\377\4step\10setpause\12setstepmul\1\377\11isrunning");
451 int32_t data = lj_lib_optint(L, 2, 0); 440 int32_t data = lj_lib_optint(L, 2, 0);
452 if (opt == LUA_GCCOUNT) { 441 if (opt == LUA_GCCOUNT) {
453 setnumV(L->top, (lua_Number)G(L)->gc.total/1024.0); 442 setnumV(L->top, (lua_Number)G(L)->gc.total/1024.0);
454 } else { 443 } else {
455 int res = lua_gc(L, opt, data); 444 int res = lua_gc(L, opt, data);
456 if (opt == LUA_GCSTEP) 445 if (opt == LUA_GCSTEP || opt == LUA_GCISRUNNING)
457 setboolV(L->top, res); 446 setboolV(L->top, res);
458 else 447 else
459 setintV(L->top, res); 448 setintV(L->top, res);
@@ -506,21 +495,12 @@ LJLIB_CF(print)
506 } 495 }
507 shortcut = (tvisfunc(tv) && funcV(tv)->c.ffid == FF_tostring); 496 shortcut = (tvisfunc(tv) && funcV(tv)->c.ffid == FF_tostring);
508 for (i = 0; i < nargs; i++) { 497 for (i = 0; i < nargs; i++) {
498 cTValue *o = &L->base[i];
509 const char *str; 499 const char *str;
510 size_t size; 500 size_t size;
511 cTValue *o = &L->base[i]; 501 MSize len;
512 if (shortcut && tvisstr(o)) { 502 if (shortcut && (str = lj_strfmt_wstrnum(L, o, &len)) != NULL) {
513 str = strVdata(o); 503 size = len;
514 size = strV(o)->len;
515 } else if (shortcut && tvisint(o)) {
516 char buf[LJ_STR_INTBUF];
517 char *p = lj_str_bufint(buf, intV(o));
518 size = (size_t)(buf+LJ_STR_INTBUF-p);
519 str = p;
520 } else if (shortcut && tvisnum(o)) {
521 char buf[LJ_STR_NUMBUF];
522 size = lj_str_bufnum(buf, o);
523 str = buf;
524 } else { 504 } else {
525 copyTV(L, L->top+1, o); 505 copyTV(L, L->top+1, o);
526 copyTV(L, L->top, L->top-1); 506 copyTV(L, L->top, L->top-1);
@@ -558,7 +538,7 @@ LJLIB_CF(coroutine_status)
558 if (co == L) s = "running"; 538 if (co == L) s = "running";
559 else if (co->status == LUA_YIELD) s = "suspended"; 539 else if (co->status == LUA_YIELD) s = "suspended";
560 else if (co->status != 0) s = "dead"; 540 else if (co->status != 0) s = "dead";
561 else if (co->base > tvref(co->stack)+1) s = "normal"; 541 else if (co->base > tvref(co->stack)+1+LJ_FR2) s = "normal";
562 else if (co->top == co->base) s = "dead"; 542 else if (co->top == co->base) s = "dead";
563 else s = "suspended"; 543 else s = "suspended";
564 lua_pushstring(L, s); 544 lua_pushstring(L, s);
@@ -578,6 +558,12 @@ LJLIB_CF(coroutine_running)
578#endif 558#endif
579} 559}
580 560
561LJLIB_CF(coroutine_isyieldable)
562{
563 setboolV(L->top++, cframe_canyield(L->cframe));
564 return 1;
565}
566
581LJLIB_CF(coroutine_create) 567LJLIB_CF(coroutine_create)
582{ 568{
583 lua_State *L1; 569 lua_State *L1;
@@ -600,8 +586,8 @@ static int ffh_resume(lua_State *L, lua_State *co, int wrap)
600 (co->status == 0 && co->top == co->base)) { 586 (co->status == 0 && co->top == co->base)) {
601 ErrMsg em = co->cframe ? LJ_ERR_CORUN : LJ_ERR_CODEAD; 587 ErrMsg em = co->cframe ? LJ_ERR_CORUN : LJ_ERR_CODEAD;
602 if (wrap) lj_err_caller(L, em); 588 if (wrap) lj_err_caller(L, em);
603 setboolV(L->base-1, 0); 589 setboolV(L->base-1-LJ_FR2, 0);
604 setstrV(L, L->base, lj_err_str(L, em)); 590 setstrV(L, L->base-LJ_FR2, lj_err_str(L, em));
605 return FFH_RES(2); 591 return FFH_RES(2);
606 } 592 }
607 lj_state_growstack(co, (MSize)(L->top - L->base)); 593 lj_state_growstack(co, (MSize)(L->top - L->base));
@@ -642,9 +628,10 @@ static void setpc_wrap_aux(lua_State *L, GCfunc *fn);
642 628
643LJLIB_CF(coroutine_wrap) 629LJLIB_CF(coroutine_wrap)
644{ 630{
631 GCfunc *fn;
645 lj_cf_coroutine_create(L); 632 lj_cf_coroutine_create(L);
646 lj_lib_pushcc(L, lj_ffh_coroutine_wrap_aux, FF_coroutine_wrap_aux, 1); 633 fn = lj_lib_pushcc(L, lj_ffh_coroutine_wrap_aux, FF_coroutine_wrap_aux, 1);
647 setpc_wrap_aux(L, funcV(L->top-1)); 634 setpc_wrap_aux(L, fn);
648 return 1; 635 return 1;
649} 636}
650 637
diff --git a/src/lib_bit.c b/src/lib_bit.c
index 6dffdfac..c979a448 100644
--- a/src/lib_bit.c
+++ b/src/lib_bit.c
@@ -12,26 +12,99 @@
12 12
13#include "lj_obj.h" 13#include "lj_obj.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_str.h" 15#include "lj_buf.h"
16#include "lj_strscan.h"
17#include "lj_strfmt.h"
18#if LJ_HASFFI
19#include "lj_ctype.h"
20#include "lj_cdata.h"
21#include "lj_cconv.h"
22#include "lj_carith.h"
23#endif
24#include "lj_ff.h"
16#include "lj_lib.h" 25#include "lj_lib.h"
17 26
18/* ------------------------------------------------------------------------ */ 27/* ------------------------------------------------------------------------ */
19 28
20#define LJLIB_MODULE_bit 29#define LJLIB_MODULE_bit
21 30
22LJLIB_ASM(bit_tobit) LJLIB_REC(bit_unary IR_TOBIT) 31#if LJ_HASFFI
32static int bit_result64(lua_State *L, CTypeID id, uint64_t x)
23{ 33{
34 GCcdata *cd = lj_cdata_new_(L, id, 8);
35 *(uint64_t *)cdataptr(cd) = x;
36 setcdataV(L, L->base-1-LJ_FR2, cd);
37 return FFH_RES(1);
38}
39#else
40static int32_t bit_checkbit(lua_State *L, int narg)
41{
42 TValue *o = L->base + narg-1;
43 if (!(o < L->top && lj_strscan_numberobj(o)))
44 lj_err_argt(L, narg, LUA_TNUMBER);
45 if (LJ_LIKELY(tvisint(o))) {
46 return intV(o);
47 } else {
48 int32_t i = lj_num2bit(numV(o));
49 if (LJ_DUALNUM) setintV(o, i);
50 return i;
51 }
52}
53#endif
54
55LJLIB_ASM(bit_tobit) LJLIB_REC(bit_tobit)
56{
57#if LJ_HASFFI
58 CTypeID id = 0;
59 setintV(L->base-1-LJ_FR2, (int32_t)lj_carith_check64(L, 1, &id));
60 return FFH_RES(1);
61#else
62 lj_lib_checknumber(L, 1);
63 return FFH_RETRY;
64#endif
65}
66
67LJLIB_ASM(bit_bnot) LJLIB_REC(bit_unary IR_BNOT)
68{
69#if LJ_HASFFI
70 CTypeID id = 0;
71 uint64_t x = lj_carith_check64(L, 1, &id);
72 return id ? bit_result64(L, id, ~x) : FFH_RETRY;
73#else
24 lj_lib_checknumber(L, 1); 74 lj_lib_checknumber(L, 1);
25 return FFH_RETRY; 75 return FFH_RETRY;
76#endif
77}
78
79LJLIB_ASM(bit_bswap) LJLIB_REC(bit_unary IR_BSWAP)
80{
81#if LJ_HASFFI
82 CTypeID id = 0;
83 uint64_t x = lj_carith_check64(L, 1, &id);
84 return id ? bit_result64(L, id, lj_bswap64(x)) : FFH_RETRY;
85#else
86 lj_lib_checknumber(L, 1);
87 return FFH_RETRY;
88#endif
26} 89}
27LJLIB_ASM_(bit_bnot) LJLIB_REC(bit_unary IR_BNOT)
28LJLIB_ASM_(bit_bswap) LJLIB_REC(bit_unary IR_BSWAP)
29 90
30LJLIB_ASM(bit_lshift) LJLIB_REC(bit_shift IR_BSHL) 91LJLIB_ASM(bit_lshift) LJLIB_REC(bit_shift IR_BSHL)
31{ 92{
93#if LJ_HASFFI
94 CTypeID id = 0, id2 = 0;
95 uint64_t x = lj_carith_check64(L, 1, &id);
96 int32_t sh = (int32_t)lj_carith_check64(L, 2, &id2);
97 if (id) {
98 x = lj_carith_shift64(x, sh, curr_func(L)->c.ffid - (int)FF_bit_lshift);
99 return bit_result64(L, id, x);
100 }
101 if (id2) setintV(L->base+1, sh);
102 return FFH_RETRY;
103#else
32 lj_lib_checknumber(L, 1); 104 lj_lib_checknumber(L, 1);
33 lj_lib_checkbit(L, 2); 105 bit_checkbit(L, 2);
34 return FFH_RETRY; 106 return FFH_RETRY;
107#endif
35} 108}
36LJLIB_ASM_(bit_rshift) LJLIB_REC(bit_shift IR_BSHR) 109LJLIB_ASM_(bit_rshift) LJLIB_REC(bit_shift IR_BSHR)
37LJLIB_ASM_(bit_arshift) LJLIB_REC(bit_shift IR_BSAR) 110LJLIB_ASM_(bit_arshift) LJLIB_REC(bit_shift IR_BSAR)
@@ -40,25 +113,58 @@ LJLIB_ASM_(bit_ror) LJLIB_REC(bit_shift IR_BROR)
40 113
41LJLIB_ASM(bit_band) LJLIB_REC(bit_nary IR_BAND) 114LJLIB_ASM(bit_band) LJLIB_REC(bit_nary IR_BAND)
42{ 115{
116#if LJ_HASFFI
117 CTypeID id = 0;
118 TValue *o = L->base, *top = L->top;
119 int i = 0;
120 do { lj_carith_check64(L, ++i, &id); } while (++o < top);
121 if (id) {
122 CTState *cts = ctype_cts(L);
123 CType *ct = ctype_get(cts, id);
124 int op = curr_func(L)->c.ffid - (int)FF_bit_bor;
125 uint64_t x, y = op >= 0 ? 0 : ~(uint64_t)0;
126 o = L->base;
127 do {
128 lj_cconv_ct_tv(cts, ct, (uint8_t *)&x, o, 0);
129 if (op < 0) y &= x; else if (op == 0) y |= x; else y ^= x;
130 } while (++o < top);
131 return bit_result64(L, id, y);
132 }
133 return FFH_RETRY;
134#else
43 int i = 0; 135 int i = 0;
44 do { lj_lib_checknumber(L, ++i); } while (L->base+i < L->top); 136 do { lj_lib_checknumber(L, ++i); } while (L->base+i < L->top);
45 return FFH_RETRY; 137 return FFH_RETRY;
138#endif
46} 139}
47LJLIB_ASM_(bit_bor) LJLIB_REC(bit_nary IR_BOR) 140LJLIB_ASM_(bit_bor) LJLIB_REC(bit_nary IR_BOR)
48LJLIB_ASM_(bit_bxor) LJLIB_REC(bit_nary IR_BXOR) 141LJLIB_ASM_(bit_bxor) LJLIB_REC(bit_nary IR_BXOR)
49 142
50/* ------------------------------------------------------------------------ */ 143/* ------------------------------------------------------------------------ */
51 144
52LJLIB_CF(bit_tohex) 145LJLIB_CF(bit_tohex) LJLIB_REC(.)
53{ 146{
54 uint32_t b = (uint32_t)lj_lib_checkbit(L, 1); 147#if LJ_HASFFI
55 int32_t i, n = L->base+1 >= L->top ? 8 : lj_lib_checkbit(L, 2); 148 CTypeID id = 0, id2 = 0;
56 const char *hexdigits = "0123456789abcdef"; 149 uint64_t b = lj_carith_check64(L, 1, &id);
57 char buf[8]; 150 int32_t n = L->base+1>=L->top ? (id ? 16 : 8) :
58 if (n < 0) { n = -n; hexdigits = "0123456789ABCDEF"; } 151 (int32_t)lj_carith_check64(L, 2, &id2);
59 if (n > 8) n = 8; 152#else
60 for (i = n; --i >= 0; ) { buf[i] = hexdigits[b & 15]; b >>= 4; } 153 uint32_t b = (uint32_t)bit_checkbit(L, 1);
61 lua_pushlstring(L, buf, (size_t)n); 154 int32_t n = L->base+1>=L->top ? 8 : bit_checkbit(L, 2);
155#endif
156 SBuf *sb = lj_buf_tmp_(L);
157 SFormat sf = (STRFMT_UINT|STRFMT_T_HEX);
158 if (n < 0) { n = -n; sf |= STRFMT_F_UPPER; }
159 sf |= ((SFormat)((n+1)&255) << STRFMT_SH_PREC);
160#if LJ_HASFFI
161 if (n < 16) b &= ((uint64_t)1 << 4*n)-1;
162#else
163 if (n < 8) b &= (1u << 4*n)-1;
164#endif
165 sb = lj_strfmt_putfxint(sb, sf, b);
166 setstrV(L, L->top-1, lj_buf_str(L, sb));
167 lj_gc_check(L);
62 return 1; 168 return 1;
63} 169}
64 170
diff --git a/src/lib_debug.c b/src/lib_debug.c
index 54c3b7e2..f112b5bc 100644
--- a/src/lib_debug.c
+++ b/src/lib_debug.c
@@ -29,7 +29,7 @@ LJLIB_CF(debug_getregistry)
29 return 1; 29 return 1;
30} 30}
31 31
32LJLIB_CF(debug_getmetatable) 32LJLIB_CF(debug_getmetatable) LJLIB_REC(.)
33{ 33{
34 lj_lib_checkany(L, 1); 34 lj_lib_checkany(L, 1);
35 if (!lua_getmetatable(L, 1)) { 35 if (!lua_getmetatable(L, 1)) {
@@ -283,13 +283,13 @@ LJLIB_CF(debug_setuservalue)
283 283
284/* ------------------------------------------------------------------------ */ 284/* ------------------------------------------------------------------------ */
285 285
286static const char KEY_HOOK = 'h'; 286#define KEY_HOOK ((void *)0x3004)
287 287
288static void hookf(lua_State *L, lua_Debug *ar) 288static void hookf(lua_State *L, lua_Debug *ar)
289{ 289{
290 static const char *const hooknames[] = 290 static const char *const hooknames[] =
291 {"call", "return", "line", "count", "tail return"}; 291 {"call", "return", "line", "count", "tail return"};
292 lua_pushlightuserdata(L, (void *)&KEY_HOOK); 292 lua_pushlightuserdata(L, KEY_HOOK);
293 lua_rawget(L, LUA_REGISTRYINDEX); 293 lua_rawget(L, LUA_REGISTRYINDEX);
294 if (lua_isfunction(L, -1)) { 294 if (lua_isfunction(L, -1)) {
295 lua_pushstring(L, hooknames[(int)ar->event]); 295 lua_pushstring(L, hooknames[(int)ar->event]);
@@ -334,7 +334,7 @@ LJLIB_CF(debug_sethook)
334 count = luaL_optint(L, arg+3, 0); 334 count = luaL_optint(L, arg+3, 0);
335 func = hookf; mask = makemask(smask, count); 335 func = hookf; mask = makemask(smask, count);
336 } 336 }
337 lua_pushlightuserdata(L, (void *)&KEY_HOOK); 337 lua_pushlightuserdata(L, KEY_HOOK);
338 lua_pushvalue(L, arg+1); 338 lua_pushvalue(L, arg+1);
339 lua_rawset(L, LUA_REGISTRYINDEX); 339 lua_rawset(L, LUA_REGISTRYINDEX);
340 lua_sethook(L, func, mask, count); 340 lua_sethook(L, func, mask, count);
@@ -349,7 +349,7 @@ LJLIB_CF(debug_gethook)
349 if (hook != NULL && hook != hookf) { /* external hook? */ 349 if (hook != NULL && hook != hookf) { /* external hook? */
350 lua_pushliteral(L, "external hook"); 350 lua_pushliteral(L, "external hook");
351 } else { 351 } else {
352 lua_pushlightuserdata(L, (void *)&KEY_HOOK); 352 lua_pushlightuserdata(L, KEY_HOOK);
353 lua_rawget(L, LUA_REGISTRYINDEX); /* get hook */ 353 lua_rawget(L, LUA_REGISTRYINDEX); /* get hook */
354 } 354 }
355 lua_pushstring(L, unmakemask(mask, buff)); 355 lua_pushstring(L, unmakemask(mask, buff));
diff --git a/src/lib_ffi.c b/src/lib_ffi.c
index f2f2ede4..136e98e8 100644
--- a/src/lib_ffi.c
+++ b/src/lib_ffi.c
@@ -29,6 +29,7 @@
29#include "lj_ccall.h" 29#include "lj_ccall.h"
30#include "lj_ccallback.h" 30#include "lj_ccallback.h"
31#include "lj_clib.h" 31#include "lj_clib.h"
32#include "lj_strfmt.h"
32#include "lj_ff.h" 33#include "lj_ff.h"
33#include "lj_lib.h" 34#include "lj_lib.h"
34 35
@@ -137,7 +138,7 @@ static int ffi_index_meta(lua_State *L, CTState *cts, CType *ct, MMS mm)
137 } 138 }
138 } 139 }
139 copyTV(L, base, L->top); 140 copyTV(L, base, L->top);
140 tv = L->top-1; 141 tv = L->top-1-LJ_FR2;
141 } 142 }
142 return lj_meta_tailcall(L, tv); 143 return lj_meta_tailcall(L, tv);
143} 144}
@@ -318,7 +319,7 @@ LJLIB_CF(ffi_meta___tostring)
318 } 319 }
319 } 320 }
320 } 321 }
321 lj_str_pushf(L, msg, strdata(lj_ctype_repr(L, id, NULL)), p); 322 lj_strfmt_pushf(L, msg, strdata(lj_ctype_repr(L, id, NULL)), p);
322checkgc: 323checkgc:
323 lj_gc_check(L); 324 lj_gc_check(L);
324 return 1; 325 return 1;
@@ -504,10 +505,7 @@ LJLIB_CF(ffi_new) LJLIB_REC(.)
504 } 505 }
505 if (sz == CTSIZE_INVALID) 506 if (sz == CTSIZE_INVALID)
506 lj_err_arg(L, 1, LJ_ERR_FFI_INVSIZE); 507 lj_err_arg(L, 1, LJ_ERR_FFI_INVSIZE);
507 if (!(info & CTF_VLA) && ctype_align(info) <= CT_MEMALIGN) 508 cd = lj_cdata_newx(cts, id, sz, info);
508 cd = lj_cdata_new(cts, id, sz);
509 else
510 cd = lj_cdata_newv(cts, id, sz, ctype_align(info));
511 setcdataV(L, o-1, cd); /* Anchor the uninitialized cdata. */ 509 setcdataV(L, o-1, cd); /* Anchor the uninitialized cdata. */
512 lj_cconv_ct_init(cts, ct, sz, cdataptr(cd), 510 lj_cconv_ct_init(cts, ct, sz, cdataptr(cd),
513 o, (MSize)(L->top - o)); /* Initialize cdata. */ 511 o, (MSize)(L->top - o)); /* Initialize cdata. */
@@ -558,6 +556,31 @@ LJLIB_CF(ffi_typeof) LJLIB_REC(.)
558 return 1; 556 return 1;
559} 557}
560 558
559/* Internal and unsupported API. */
560LJLIB_CF(ffi_typeinfo)
561{
562 CTState *cts = ctype_cts(L);
563 CTypeID id = (CTypeID)ffi_checkint(L, 1);
564 if (id > 0 && id < cts->top) {
565 CType *ct = ctype_get(cts, id);
566 GCtab *t;
567 lua_createtable(L, 0, 4); /* Increment hash size if fields are added. */
568 t = tabV(L->top-1);
569 setintV(lj_tab_setstr(L, t, lj_str_newlit(L, "info")), (int32_t)ct->info);
570 if (ct->size != CTSIZE_INVALID)
571 setintV(lj_tab_setstr(L, t, lj_str_newlit(L, "size")), (int32_t)ct->size);
572 if (ct->sib)
573 setintV(lj_tab_setstr(L, t, lj_str_newlit(L, "sib")), (int32_t)ct->sib);
574 if (gcref(ct->name)) {
575 GCstr *s = gco2str(gcref(ct->name));
576 setstrV(L, lj_tab_setstr(L, t, lj_str_newlit(L, "name")), s);
577 }
578 lj_gc_check(L);
579 return 1;
580 }
581 return 0;
582}
583
561LJLIB_CF(ffi_istype) LJLIB_REC(.) 584LJLIB_CF(ffi_istype) LJLIB_REC(.)
562{ 585{
563 CTState *cts = ctype_cts(L); 586 CTState *cts = ctype_cts(L);
@@ -725,6 +748,9 @@ LJLIB_CF(ffi_abi) LJLIB_REC(.)
725 case H_(4ab624a8,4ab624a8): b = 1; break; /* win */ 748 case H_(4ab624a8,4ab624a8): b = 1; break; /* win */
726#endif 749#endif
727 case H_(3af93066,1f001464): b = 1; break; /* le/be */ 750 case H_(3af93066,1f001464): b = 1; break; /* le/be */
751#if LJ_GC64
752 case H_(9e89d2c9,13c83c92): b = 1; break; /* gc64 */
753#endif
728 default: 754 default:
729 break; 755 break;
730 } 756 }
@@ -768,19 +794,11 @@ LJLIB_CF(ffi_gc) LJLIB_REC(.)
768 GCcdata *cd = ffi_checkcdata(L, 1); 794 GCcdata *cd = ffi_checkcdata(L, 1);
769 TValue *fin = lj_lib_checkany(L, 2); 795 TValue *fin = lj_lib_checkany(L, 2);
770 CTState *cts = ctype_cts(L); 796 CTState *cts = ctype_cts(L);
771 GCtab *t = cts->finalizer;
772 CType *ct = ctype_raw(cts, cd->ctypeid); 797 CType *ct = ctype_raw(cts, cd->ctypeid);
773 if (!(ctype_isptr(ct->info) || ctype_isstruct(ct->info) || 798 if (!(ctype_isptr(ct->info) || ctype_isstruct(ct->info) ||
774 ctype_isrefarray(ct->info))) 799 ctype_isrefarray(ct->info)))
775 lj_err_arg(L, 1, LJ_ERR_FFI_INVTYPE); 800 lj_err_arg(L, 1, LJ_ERR_FFI_INVTYPE);
776 if (gcref(t->metatable)) { /* Update finalizer table, if still enabled. */ 801 lj_cdata_setfin(L, cd, gcval(fin), itype(fin));
777 copyTV(L, lj_tab_set(L, t, L->base), fin);
778 lj_gc_anybarriert(L, t);
779 if (!tvisnil(fin))
780 cd->marked |= LJ_GC_CDATA_FIN;
781 else
782 cd->marked &= ~LJ_GC_CDATA_FIN;
783 }
784 L->top = L->base+1; /* Pass through the cdata object. */ 802 L->top = L->base+1; /* Pass through the cdata object. */
785 return 1; 803 return 1;
786} 804}
diff --git a/src/lib_io.c b/src/lib_io.c
index 9cdcfcfc..9763ed46 100644
--- a/src/lib_io.c
+++ b/src/lib_io.c
@@ -19,8 +19,10 @@
19#include "lj_obj.h" 19#include "lj_obj.h"
20#include "lj_gc.h" 20#include "lj_gc.h"
21#include "lj_err.h" 21#include "lj_err.h"
22#include "lj_buf.h"
22#include "lj_str.h" 23#include "lj_str.h"
23#include "lj_state.h" 24#include "lj_state.h"
25#include "lj_strfmt.h"
24#include "lj_ff.h" 26#include "lj_ff.h"
25#include "lj_lib.h" 27#include "lj_lib.h"
26 28
@@ -84,7 +86,7 @@ static IOFileUD *io_file_open(lua_State *L, const char *mode)
84 IOFileUD *iof = io_file_new(L); 86 IOFileUD *iof = io_file_new(L);
85 iof->fp = fopen(fname, mode); 87 iof->fp = fopen(fname, mode);
86 if (iof->fp == NULL) 88 if (iof->fp == NULL)
87 luaL_argerror(L, 1, lj_str_pushf(L, "%s: %s", fname, strerror(errno))); 89 luaL_argerror(L, 1, lj_strfmt_pushf(L, "%s: %s", fname, strerror(errno)));
88 return iof; 90 return iof;
89} 91}
90 92
@@ -97,7 +99,7 @@ static int io_file_close(lua_State *L, IOFileUD *iof)
97 int stat = -1; 99 int stat = -1;
98#if LJ_TARGET_POSIX 100#if LJ_TARGET_POSIX
99 stat = pclose(iof->fp); 101 stat = pclose(iof->fp);
100#elif LJ_TARGET_WINDOWS 102#elif LJ_TARGET_WINDOWS && !LJ_TARGET_XBOXONE
101 stat = _pclose(iof->fp); 103 stat = _pclose(iof->fp);
102#else 104#else
103 lua_assert(0); 105 lua_assert(0);
@@ -145,7 +147,7 @@ static int io_file_readline(lua_State *L, FILE *fp, MSize chop)
145 MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0; 147 MSize m = LUAL_BUFFERSIZE, n = 0, ok = 0;
146 char *buf; 148 char *buf;
147 for (;;) { 149 for (;;) {
148 buf = lj_str_needbuf(L, &G(L)->tmpbuf, m); 150 buf = lj_buf_tmp(L, m);
149 if (fgets(buf+n, m-n, fp) == NULL) break; 151 if (fgets(buf+n, m-n, fp) == NULL) break;
150 n += (MSize)strlen(buf+n); 152 n += (MSize)strlen(buf+n);
151 ok |= n; 153 ok |= n;
@@ -161,7 +163,7 @@ static void io_file_readall(lua_State *L, FILE *fp)
161{ 163{
162 MSize m, n; 164 MSize m, n;
163 for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) { 165 for (m = LUAL_BUFFERSIZE, n = 0; ; m += m) {
164 char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m); 166 char *buf = lj_buf_tmp(L, m);
165 n += (MSize)fread(buf+n, 1, m-n, fp); 167 n += (MSize)fread(buf+n, 1, m-n, fp);
166 if (n != m) { 168 if (n != m) {
167 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n)); 169 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
@@ -174,7 +176,7 @@ static void io_file_readall(lua_State *L, FILE *fp)
174static int io_file_readlen(lua_State *L, FILE *fp, MSize m) 176static int io_file_readlen(lua_State *L, FILE *fp, MSize m)
175{ 177{
176 if (m) { 178 if (m) {
177 char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, m); 179 char *buf = lj_buf_tmp(L, m);
178 MSize n = (MSize)fread(buf, 1, m, fp); 180 MSize n = (MSize)fread(buf, 1, m, fp);
179 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n)); 181 setstrV(L, L->top++, lj_str_new(L, buf, (size_t)n));
180 lj_gc_check(L); 182 lj_gc_check(L);
@@ -201,13 +203,12 @@ static int io_file_read(lua_State *L, FILE *fp, int start)
201 for (n = start; nargs-- && ok; n++) { 203 for (n = start; nargs-- && ok; n++) {
202 if (tvisstr(L->base+n)) { 204 if (tvisstr(L->base+n)) {
203 const char *p = strVdata(L->base+n); 205 const char *p = strVdata(L->base+n);
204 if (p[0] != '*') 206 if (p[0] == '*') p++;
205 lj_err_arg(L, n+1, LJ_ERR_INVOPT); 207 if (p[0] == 'n')
206 if (p[1] == 'n')
207 ok = io_file_readnum(L, fp); 208 ok = io_file_readnum(L, fp);
208 else if ((p[1] & ~0x20) == 'L') 209 else if ((p[0] & ~0x20) == 'L')
209 ok = io_file_readline(L, fp, (p[1] == 'l')); 210 ok = io_file_readline(L, fp, (p[0] == 'l'));
210 else if (p[1] == 'a') 211 else if (p[0] == 'a')
211 io_file_readall(L, fp); 212 io_file_readall(L, fp);
212 else 213 else
213 lj_err_arg(L, n+1, LJ_ERR_INVFMT); 214 lj_err_arg(L, n+1, LJ_ERR_INVFMT);
@@ -230,19 +231,11 @@ static int io_file_write(lua_State *L, FILE *fp, int start)
230 cTValue *tv; 231 cTValue *tv;
231 int status = 1; 232 int status = 1;
232 for (tv = L->base+start; tv < L->top; tv++) { 233 for (tv = L->base+start; tv < L->top; tv++) {
233 if (tvisstr(tv)) { 234 MSize len;
234 MSize len = strV(tv)->len; 235 const char *p = lj_strfmt_wstrnum(L, tv, &len);
235 status = status && (fwrite(strVdata(tv), 1, len, fp) == len); 236 if (!p)
236 } else if (tvisint(tv)) {
237 char buf[LJ_STR_INTBUF];
238 char *p = lj_str_bufint(buf, intV(tv));
239 size_t len = (size_t)(buf+LJ_STR_INTBUF-p);
240 status = status && (fwrite(p, 1, len, fp) == len);
241 } else if (tvisnum(tv)) {
242 status = status && (fprintf(fp, LUA_NUMBER_FMT, numV(tv)) > 0);
243 } else {
244 lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING); 237 lj_err_argt(L, (int)(tv - L->base) + 1, LUA_TSTRING);
245 } 238 status = status && (fwrite(p, 1, len, fp) == len);
246 } 239 }
247 if (LJ_52 && status) { 240 if (LJ_52 && status) {
248 L->top = L->base+1; 241 L->top = L->base+1;
@@ -413,7 +406,7 @@ LJLIB_CF(io_open)
413 406
414LJLIB_CF(io_popen) 407LJLIB_CF(io_popen)
415{ 408{
416#if LJ_TARGET_POSIX || LJ_TARGET_WINDOWS 409#if LJ_TARGET_POSIX || (LJ_TARGET_WINDOWS && !LJ_TARGET_XBOXONE)
417 const char *fname = strdata(lj_lib_checkstr(L, 1)); 410 const char *fname = strdata(lj_lib_checkstr(L, 1));
418 GCstr *s = lj_lib_optstr(L, 2); 411 GCstr *s = lj_lib_optstr(L, 2);
419 const char *mode = s ? strdata(s) : "r"; 412 const char *mode = s ? strdata(s) : "r";
diff --git a/src/lib_jit.c b/src/lib_jit.c
index d2fcf21b..22ca0a1a 100644
--- a/src/lib_jit.c
+++ b/src/lib_jit.c
@@ -10,13 +10,17 @@
10#include "lauxlib.h" 10#include "lauxlib.h"
11#include "lualib.h" 11#include "lualib.h"
12 12
13#include "lj_arch.h"
14#include "lj_obj.h" 13#include "lj_obj.h"
14#include "lj_gc.h"
15#include "lj_err.h" 15#include "lj_err.h"
16#include "lj_debug.h" 16#include "lj_debug.h"
17#include "lj_str.h" 17#include "lj_str.h"
18#include "lj_tab.h" 18#include "lj_tab.h"
19#include "lj_state.h"
19#include "lj_bc.h" 20#include "lj_bc.h"
21#if LJ_HASFFI
22#include "lj_ctype.h"
23#endif
20#if LJ_HASJIT 24#if LJ_HASJIT
21#include "lj_ir.h" 25#include "lj_ir.h"
22#include "lj_jit.h" 26#include "lj_jit.h"
@@ -24,6 +28,7 @@
24#include "lj_iropt.h" 28#include "lj_iropt.h"
25#include "lj_target.h" 29#include "lj_target.h"
26#endif 30#endif
31#include "lj_trace.h"
27#include "lj_dispatch.h" 32#include "lj_dispatch.h"
28#include "lj_vm.h" 33#include "lj_vm.h"
29#include "lj_vmevent.h" 34#include "lj_vmevent.h"
@@ -280,7 +285,7 @@ static GCtrace *jit_checktrace(lua_State *L)
280/* Names of link types. ORDER LJ_TRLINK */ 285/* Names of link types. ORDER LJ_TRLINK */
281static const char *const jit_trlinkname[] = { 286static const char *const jit_trlinkname[] = {
282 "none", "root", "loop", "tail-recursion", "up-recursion", "down-recursion", 287 "none", "root", "loop", "tail-recursion", "up-recursion", "down-recursion",
283 "interpreter", "return" 288 "interpreter", "return", "stitch"
284}; 289};
285 290
286/* local info = jit.util.traceinfo(tr) */ 291/* local info = jit.util.traceinfo(tr) */
@@ -333,6 +338,13 @@ LJLIB_CF(jit_util_tracek)
333 slot = ir->op2; 338 slot = ir->op2;
334 ir = &T->ir[ir->op1]; 339 ir = &T->ir[ir->op1];
335 } 340 }
341#if LJ_HASFFI
342 if (ir->o == IR_KINT64 && !ctype_ctsG(G(L))) {
343 ptrdiff_t oldtop = savestack(L, L->top);
344 luaopen_ffi(L); /* Load FFI library on-demand. */
345 L->top = restorestack(L, oldtop);
346 }
347#endif
336 lj_ir_kvalue(L, L->top-2, ir); 348 lj_ir_kvalue(L, L->top-2, ir);
337 setintV(L->top-1, (int32_t)irt_type(ir->t)); 349 setintV(L->top-1, (int32_t)irt_type(ir->t));
338 if (slot == -1) 350 if (slot == -1)
@@ -417,6 +429,12 @@ LJLIB_CF(jit_util_ircalladdr)
417 429
418#include "lj_libdef.h" 430#include "lj_libdef.h"
419 431
432static int luaopen_jit_util(lua_State *L)
433{
434 LJ_LIB_REG(L, NULL, jit_util);
435 return 1;
436}
437
420/* -- jit.opt module ------------------------------------------------------ */ 438/* -- jit.opt module ------------------------------------------------------ */
421 439
422#if LJ_HASJIT 440#if LJ_HASJIT
@@ -514,6 +532,104 @@ LJLIB_CF(jit_opt_start)
514 532
515#endif 533#endif
516 534
535/* -- jit.profile module -------------------------------------------------- */
536
537#if LJ_HASPROFILE
538
539#define LJLIB_MODULE_jit_profile
540
541/* Not loaded by default, use: local profile = require("jit.profile") */
542
543static const char KEY_PROFILE_THREAD = 't';
544static const char KEY_PROFILE_FUNC = 'f';
545
546static void jit_profile_callback(lua_State *L2, lua_State *L, int samples,
547 int vmstate)
548{
549 TValue key;
550 cTValue *tv;
551 setlightudV(&key, (void *)&KEY_PROFILE_FUNC);
552 tv = lj_tab_get(L, tabV(registry(L)), &key);
553 if (tvisfunc(tv)) {
554 char vmst = (char)vmstate;
555 int status;
556 setfuncV(L2, L2->top++, funcV(tv));
557 setthreadV(L2, L2->top++, L);
558 setintV(L2->top++, samples);
559 setstrV(L2, L2->top++, lj_str_new(L2, &vmst, 1));
560 status = lua_pcall(L2, 3, 0, 0); /* callback(thread, samples, vmstate) */
561 if (status) {
562 if (G(L2)->panic) G(L2)->panic(L2);
563 exit(EXIT_FAILURE);
564 }
565 lj_trace_abort(G(L2));
566 }
567}
568
569/* profile.start(mode, cb) */
570LJLIB_CF(jit_profile_start)
571{
572 GCtab *registry = tabV(registry(L));
573 GCstr *mode = lj_lib_optstr(L, 1);
574 GCfunc *func = lj_lib_checkfunc(L, 2);
575 lua_State *L2 = lua_newthread(L); /* Thread that runs profiler callback. */
576 TValue key;
577 /* Anchor thread and function in registry. */
578 setlightudV(&key, (void *)&KEY_PROFILE_THREAD);
579 setthreadV(L, lj_tab_set(L, registry, &key), L2);
580 setlightudV(&key, (void *)&KEY_PROFILE_FUNC);
581 setfuncV(L, lj_tab_set(L, registry, &key), func);
582 lj_gc_anybarriert(L, registry);
583 luaJIT_profile_start(L, mode ? strdata(mode) : "",
584 (luaJIT_profile_callback)jit_profile_callback, L2);
585 return 0;
586}
587
588/* profile.stop() */
589LJLIB_CF(jit_profile_stop)
590{
591 GCtab *registry;
592 TValue key;
593 luaJIT_profile_stop(L);
594 registry = tabV(registry(L));
595 setlightudV(&key, (void *)&KEY_PROFILE_THREAD);
596 setnilV(lj_tab_set(L, registry, &key));
597 setlightudV(&key, (void *)&KEY_PROFILE_FUNC);
598 setnilV(lj_tab_set(L, registry, &key));
599 lj_gc_anybarriert(L, registry);
600 return 0;
601}
602
603/* dump = profile.dumpstack([thread,] fmt, depth) */
604LJLIB_CF(jit_profile_dumpstack)
605{
606 lua_State *L2 = L;
607 int arg = 0;
608 size_t len;
609 int depth;
610 GCstr *fmt;
611 const char *p;
612 if (L->top > L->base && tvisthread(L->base)) {
613 L2 = threadV(L->base);
614 arg = 1;
615 }
616 fmt = lj_lib_checkstr(L, arg+1);
617 depth = lj_lib_checkint(L, arg+2);
618 p = luaJIT_profile_dumpstack(L2, strdata(fmt), depth, &len);
619 lua_pushlstring(L, p, len);
620 return 1;
621}
622
623#include "lj_libdef.h"
624
625static int luaopen_jit_profile(lua_State *L)
626{
627 LJ_LIB_REG(L, NULL, jit_profile);
628 return 1;
629}
630
631#endif
632
517/* -- JIT compiler initialization ----------------------------------------- */ 633/* -- JIT compiler initialization ----------------------------------------- */
518 634
519#if LJ_HASJIT 635#if LJ_HASJIT
@@ -539,38 +655,31 @@ static uint32_t jit_cpudetect(lua_State *L)
539 uint32_t features[4]; 655 uint32_t features[4];
540 if (lj_vm_cpuid(0, vendor) && lj_vm_cpuid(1, features)) { 656 if (lj_vm_cpuid(0, vendor) && lj_vm_cpuid(1, features)) {
541#if !LJ_HASJIT 657#if !LJ_HASJIT
542#define JIT_F_CMOV 1
543#define JIT_F_SSE2 2 658#define JIT_F_SSE2 2
544#endif 659#endif
545 flags |= ((features[3] >> 15)&1) * JIT_F_CMOV;
546 flags |= ((features[3] >> 26)&1) * JIT_F_SSE2; 660 flags |= ((features[3] >> 26)&1) * JIT_F_SSE2;
547#if LJ_HASJIT 661#if LJ_HASJIT
548 flags |= ((features[2] >> 0)&1) * JIT_F_SSE3; 662 flags |= ((features[2] >> 0)&1) * JIT_F_SSE3;
549 flags |= ((features[2] >> 19)&1) * JIT_F_SSE4_1; 663 flags |= ((features[2] >> 19)&1) * JIT_F_SSE4_1;
550 if (vendor[2] == 0x6c65746e) { /* Intel. */ 664 if (vendor[2] == 0x6c65746e) { /* Intel. */
551 if ((features[0] & 0x0ff00f00) == 0x00000f00) /* P4. */ 665 if ((features[0] & 0x0fff0ff0) == 0x000106c0) /* Atom. */
552 flags |= JIT_F_P4; /* Currently unused. */
553 else if ((features[0] & 0x0fff0ff0) == 0x000106c0) /* Atom. */
554 flags |= JIT_F_LEA_AGU; 666 flags |= JIT_F_LEA_AGU;
555 } else if (vendor[2] == 0x444d4163) { /* AMD. */ 667 } else if (vendor[2] == 0x444d4163) { /* AMD. */
556 uint32_t fam = (features[0] & 0x0ff00f00); 668 uint32_t fam = (features[0] & 0x0ff00f00);
557 if (fam == 0x00000f00) /* K8. */
558 flags |= JIT_F_SPLIT_XMM;
559 if (fam >= 0x00000f00) /* K8, K10. */ 669 if (fam >= 0x00000f00) /* K8, K10. */
560 flags |= JIT_F_PREFER_IMUL; 670 flags |= JIT_F_PREFER_IMUL;
561 } 671 }
672 if (vendor[0] >= 7) {
673 uint32_t xfeatures[4];
674 lj_vm_cpuid(7, xfeatures);
675 flags |= ((xfeatures[1] >> 8)&1) * JIT_F_BMI2;
676 }
562#endif 677#endif
563 } 678 }
564 /* Check for required instruction set support on x86 (unnecessary on x64). */ 679 /* Check for required instruction set support on x86 (unnecessary on x64). */
565#if LJ_TARGET_X86 680#if LJ_TARGET_X86
566#if !defined(LUAJIT_CPU_NOCMOV)
567 if (!(flags & JIT_F_CMOV))
568 luaL_error(L, "CPU not supported");
569#endif
570#if defined(LUAJIT_CPU_SSE2)
571 if (!(flags & JIT_F_SSE2)) 681 if (!(flags & JIT_F_SSE2))
572 luaL_error(L, "CPU does not support SSE2 (recompile without -DLUAJIT_CPU_SSE2)"); 682 luaL_error(L, "CPU with SSE2 required");
573#endif
574#endif 683#endif
575#elif LJ_TARGET_ARM 684#elif LJ_TARGET_ARM
576#if LJ_HASJIT 685#if LJ_HASJIT
@@ -592,6 +701,8 @@ static uint32_t jit_cpudetect(lua_State *L)
592 ver >= 60 ? JIT_F_ARMV6_ : 0; 701 ver >= 60 ? JIT_F_ARMV6_ : 0;
593 flags |= LJ_ARCH_HASFPU == 0 ? 0 : ver >= 70 ? JIT_F_VFPV3 : JIT_F_VFPV2; 702 flags |= LJ_ARCH_HASFPU == 0 ? 0 : ver >= 70 ? JIT_F_VFPV3 : JIT_F_VFPV2;
594#endif 703#endif
704#elif LJ_TARGET_ARM64
705 /* No optional CPU features to detect (for now). */
595#elif LJ_TARGET_PPC 706#elif LJ_TARGET_PPC
596#if LJ_HASJIT 707#if LJ_HASJIT
597#if LJ_ARCH_SQRT 708#if LJ_ARCH_SQRT
@@ -601,21 +712,23 @@ static uint32_t jit_cpudetect(lua_State *L)
601 flags |= JIT_F_ROUND; 712 flags |= JIT_F_ROUND;
602#endif 713#endif
603#endif 714#endif
604#elif LJ_TARGET_PPCSPE
605 /* Nothing to do. */
606#elif LJ_TARGET_MIPS 715#elif LJ_TARGET_MIPS
607#if LJ_HASJIT 716#if LJ_HASJIT
608 /* Compile-time MIPS CPU detection. */ 717 /* Compile-time MIPS CPU detection. */
609#if LJ_ARCH_VERSION >= 20 718#if LJ_ARCH_VERSION >= 20
610 flags |= JIT_F_MIPS32R2; 719 flags |= JIT_F_MIPSXXR2;
611#endif 720#endif
612 /* Runtime MIPS CPU detection. */ 721 /* Runtime MIPS CPU detection. */
613#if defined(__GNUC__) 722#if defined(__GNUC__)
614 if (!(flags & JIT_F_MIPS32R2)) { 723 if (!(flags & JIT_F_MIPSXXR2)) {
615 int x; 724 int x;
725#ifdef __mips16
726 x = 0; /* Runtime detection is difficult. Ensure optimal -march flags. */
727#else
616 /* On MIPS32R1 rotr is treated as srl. rotr r2,r2,1 -> srl r2,r2,1. */ 728 /* On MIPS32R1 rotr is treated as srl. rotr r2,r2,1 -> srl r2,r2,1. */
617 __asm__("li $2, 1\n\t.long 0x00221042\n\tmove %0, $2" : "=r"(x) : : "$2"); 729 __asm__("li $2, 1\n\t.long 0x00221042\n\tmove %0, $2" : "=r"(x) : : "$2");
618 if (x) flags |= JIT_F_MIPS32R2; /* Either 0x80000000 (R2) or 0 (R1). */ 730#endif
731 if (x) flags |= JIT_F_MIPSXXR2; /* Either 0x80000000 (R2) or 0 (R1). */
619 } 732 }
620#endif 733#endif
621#endif 734#endif
@@ -632,11 +745,7 @@ static void jit_init(lua_State *L)
632 uint32_t flags = jit_cpudetect(L); 745 uint32_t flags = jit_cpudetect(L);
633#if LJ_HASJIT 746#if LJ_HASJIT
634 jit_State *J = L2J(L); 747 jit_State *J = L2J(L);
635#if LJ_TARGET_X86 748 J->flags = flags | JIT_F_ON | JIT_F_OPT_DEFAULT;
636 /* Silently turn off the JIT compiler on CPUs without SSE2. */
637 if ((flags & JIT_F_SSE2))
638#endif
639 J->flags = flags | JIT_F_ON | JIT_F_OPT_DEFAULT;
640 memcpy(J->param, jit_param_default, sizeof(J->param)); 749 memcpy(J->param, jit_param_default, sizeof(J->param));
641 lj_dispatch_update(G(L)); 750 lj_dispatch_update(G(L));
642#else 751#else
@@ -646,19 +755,23 @@ static void jit_init(lua_State *L)
646 755
647LUALIB_API int luaopen_jit(lua_State *L) 756LUALIB_API int luaopen_jit(lua_State *L)
648{ 757{
758 jit_init(L);
649 lua_pushliteral(L, LJ_OS_NAME); 759 lua_pushliteral(L, LJ_OS_NAME);
650 lua_pushliteral(L, LJ_ARCH_NAME); 760 lua_pushliteral(L, LJ_ARCH_NAME);
651 lua_pushinteger(L, LUAJIT_VERSION_NUM); 761 lua_pushinteger(L, LUAJIT_VERSION_NUM);
652 lua_pushliteral(L, LUAJIT_VERSION); 762 lua_pushliteral(L, LUAJIT_VERSION);
653 LJ_LIB_REG(L, LUA_JITLIBNAME, jit); 763 LJ_LIB_REG(L, LUA_JITLIBNAME, jit);
764#if LJ_HASPROFILE
765 lj_lib_prereg(L, LUA_JITLIBNAME ".profile", luaopen_jit_profile,
766 tabref(L->env));
767#endif
654#ifndef LUAJIT_DISABLE_JITUTIL 768#ifndef LUAJIT_DISABLE_JITUTIL
655 LJ_LIB_REG(L, "jit.util", jit_util); 769 lj_lib_prereg(L, LUA_JITLIBNAME ".util", luaopen_jit_util, tabref(L->env));
656#endif 770#endif
657#if LJ_HASJIT 771#if LJ_HASJIT
658 LJ_LIB_REG(L, "jit.opt", jit_opt); 772 LJ_LIB_REG(L, "jit.opt", jit_opt);
659#endif 773#endif
660 L->top -= 2; 774 L->top -= 2;
661 jit_init(L);
662 return 1; 775 return 1;
663} 776}
664 777
diff --git a/src/lib_math.c b/src/lib_math.c
index 4c708a47..7bb03880 100644
--- a/src/lib_math.c
+++ b/src/lib_math.c
@@ -47,12 +47,6 @@ LJLIB_ASM_(math_tanh) LJLIB_REC(math_htrig IRCALL_tanh)
47LJLIB_ASM_(math_frexp) 47LJLIB_ASM_(math_frexp)
48LJLIB_ASM_(math_modf) LJLIB_REC(.) 48LJLIB_ASM_(math_modf) LJLIB_REC(.)
49 49
50LJLIB_PUSH(57.29577951308232)
51LJLIB_ASM_(math_deg) LJLIB_REC(math_degrad)
52
53LJLIB_PUSH(0.017453292519943295)
54LJLIB_ASM_(math_rad) LJLIB_REC(math_degrad)
55
56LJLIB_ASM(math_log) LJLIB_REC(math_log) 50LJLIB_ASM(math_log) LJLIB_REC(math_log)
57{ 51{
58 double x = lj_lib_checknum(L, 1); 52 double x = lj_lib_checknum(L, 1);
@@ -63,12 +57,15 @@ LJLIB_ASM(math_log) LJLIB_REC(math_log)
63#else 57#else
64 x = lj_vm_log2(x); y = 1.0 / lj_vm_log2(y); 58 x = lj_vm_log2(x); y = 1.0 / lj_vm_log2(y);
65#endif 59#endif
66 setnumV(L->base-1, x*y); /* Do NOT join the expression to x / y. */ 60 setnumV(L->base-1-LJ_FR2, x*y); /* Do NOT join the expression to x / y. */
67 return FFH_RES(1); 61 return FFH_RES(1);
68 } 62 }
69 return FFH_RETRY; 63 return FFH_RETRY;
70} 64}
71 65
66LJLIB_LUA(math_deg) /* function(x) return x * 57.29577951308232 end */
67LJLIB_LUA(math_rad) /* function(x) return x * 0.017453292519943295 end */
68
72LJLIB_ASM(math_atan2) LJLIB_REC(.) 69LJLIB_ASM(math_atan2) LJLIB_REC(.)
73{ 70{
74 lj_lib_checknum(L, 1); 71 lj_lib_checknum(L, 1);
diff --git a/src/lib_os.c b/src/lib_os.c
index 8c96b86c..9e78d49a 100644
--- a/src/lib_os.c
+++ b/src/lib_os.c
@@ -17,7 +17,10 @@
17#include "lualib.h" 17#include "lualib.h"
18 18
19#include "lj_obj.h" 19#include "lj_obj.h"
20#include "lj_gc.h"
20#include "lj_err.h" 21#include "lj_err.h"
22#include "lj_buf.h"
23#include "lj_str.h"
21#include "lj_lib.h" 24#include "lj_lib.h"
22 25
23#if LJ_TARGET_POSIX 26#if LJ_TARGET_POSIX
@@ -188,7 +191,7 @@ LJLIB_CF(os_date)
188#endif 191#endif
189 } 192 }
190 if (stm == NULL) { /* Invalid date? */ 193 if (stm == NULL) { /* Invalid date? */
191 setnilV(L->top-1); 194 setnilV(L->top++);
192 } else if (strcmp(s, "*t") == 0) { 195 } else if (strcmp(s, "*t") == 0) {
193 lua_createtable(L, 0, 9); /* 9 = number of fields */ 196 lua_createtable(L, 0, 9); /* 9 = number of fields */
194 setfield(L, "sec", stm->tm_sec); 197 setfield(L, "sec", stm->tm_sec);
@@ -200,23 +203,25 @@ LJLIB_CF(os_date)
200 setfield(L, "wday", stm->tm_wday+1); 203 setfield(L, "wday", stm->tm_wday+1);
201 setfield(L, "yday", stm->tm_yday+1); 204 setfield(L, "yday", stm->tm_yday+1);
202 setboolfield(L, "isdst", stm->tm_isdst); 205 setboolfield(L, "isdst", stm->tm_isdst);
203 } else { 206 } else if (*s) {
204 char cc[3]; 207 SBuf *sb = &G(L)->tmpbuf;
205 luaL_Buffer b; 208 MSize sz = 0;
206 cc[0] = '%'; cc[2] = '\0'; 209 const char *q;
207 luaL_buffinit(L, &b); 210 for (q = s; *q; q++)
208 for (; *s; s++) { 211 sz += (*q == '%') ? 30 : 1; /* Overflow doesn't matter. */
209 if (*s != '%' || *(s + 1) == '\0') { /* No conversion specifier? */ 212 setsbufL(sb, L);
210 luaL_addchar(&b, *s); 213 for (;;) {
211 } else { 214 char *buf = lj_buf_need(sb, sz);
212 size_t reslen; 215 size_t len = strftime(buf, sbufsz(sb), s, stm);
213 char buff[200]; /* Should be big enough for any conversion result. */ 216 if (len) {
214 cc[1] = *(++s); 217 setstrV(L, L->top++, lj_str_new(L, buf, len));
215 reslen = strftime(buff, sizeof(buff), cc, stm); 218 lj_gc_check(L);
216 luaL_addlstring(&b, buff, reslen); 219 break;
217 } 220 }
221 sz += (sz|1);
218 } 222 }
219 luaL_pushresult(&b); 223 } else {
224 setstrV(L, L->top++, &G(L)->strempty);
220 } 225 }
221 return 1; 226 return 1;
222} 227}
diff --git a/src/lib_package.c b/src/lib_package.c
index 01b63d63..b7655c6b 100644
--- a/src/lib_package.c
+++ b/src/lib_package.c
@@ -96,9 +96,17 @@ static void setprogdir(lua_State *L)
96static void pusherror(lua_State *L) 96static void pusherror(lua_State *L)
97{ 97{
98 DWORD error = GetLastError(); 98 DWORD error = GetLastError();
99#if LJ_TARGET_XBOXONE
100 wchar_t wbuffer[128];
101 char buffer[128*2];
102 if (FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
103 NULL, error, 0, wbuffer, sizeof(wbuffer)/sizeof(wchar_t), NULL) &&
104 WideCharToMultiByte(CP_ACP, 0, wbuffer, 128, buffer, 128*2, NULL, NULL))
105#else
99 char buffer[128]; 106 char buffer[128];
100 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 107 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
101 NULL, error, 0, buffer, sizeof(buffer), NULL)) 108 NULL, error, 0, buffer, sizeof(buffer), NULL))
109#endif
102 lua_pushstring(L, buffer); 110 lua_pushstring(L, buffer);
103 else 111 else
104 lua_pushfstring(L, "system error %d\n", error); 112 lua_pushfstring(L, "system error %d\n", error);
@@ -111,7 +119,7 @@ static void ll_unloadlib(void *lib)
111 119
112static void *ll_load(lua_State *L, const char *path, int gl) 120static void *ll_load(lua_State *L, const char *path, int gl)
113{ 121{
114 HINSTANCE lib = LoadLibraryA(path); 122 HINSTANCE lib = LoadLibraryExA(path, NULL, 0);
115 if (lib == NULL) pusherror(L); 123 if (lib == NULL) pusherror(L);
116 UNUSED(gl); 124 UNUSED(gl);
117 return lib; 125 return lib;
@@ -226,7 +234,7 @@ static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r)
226 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC)); 234 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC));
227 lua_pop(L, 1); 235 lua_pop(L, 1);
228 if (bcdata) { 236 if (bcdata) {
229 if (luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0) 237 if (luaL_loadbuffer(L, bcdata, LJ_MAX_BUF, name) != 0)
230 return PACKAGE_ERR_LOAD; 238 return PACKAGE_ERR_LOAD;
231 return 0; 239 return 0;
232 } 240 }
@@ -383,7 +391,7 @@ static int lj_cf_package_loader_preload(lua_State *L)
383 if (lua_isnil(L, -1)) { /* Not found? */ 391 if (lua_isnil(L, -1)) { /* Not found? */
384 const char *bcname = mksymname(L, name, SYMPREFIX_BC); 392 const char *bcname = mksymname(L, name, SYMPREFIX_BC);
385 const char *bcdata = ll_bcsym(NULL, bcname); 393 const char *bcdata = ll_bcsym(NULL, bcname);
386 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0) 394 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, LJ_MAX_BUF, name) != 0)
387 lua_pushfstring(L, "\n\tno field package.preload['%s']", name); 395 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
388 } 396 }
389 return 1; 397 return 1;
@@ -391,8 +399,7 @@ static int lj_cf_package_loader_preload(lua_State *L)
391 399
392/* ------------------------------------------------------------------------ */ 400/* ------------------------------------------------------------------------ */
393 401
394static const int sentinel_ = 0; 402#define sentinel ((void *)0x4004)
395#define sentinel ((void *)&sentinel_)
396 403
397static int lj_cf_package_require(lua_State *L) 404static int lj_cf_package_require(lua_State *L)
398{ 405{
@@ -582,6 +589,10 @@ LUALIB_API int luaopen_package(lua_State *L)
582 lj_lib_pushcf(L, package_loaders[i], 1); 589 lj_lib_pushcf(L, package_loaders[i], 1);
583 lua_rawseti(L, -2, i+1); 590 lua_rawseti(L, -2, i+1);
584 } 591 }
592#if LJ_52
593 lua_pushvalue(L, -1);
594 lua_setfield(L, -3, "searchers");
595#endif
585 lua_setfield(L, -2, "loaders"); 596 lua_setfield(L, -2, "loaders");
586 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); 597 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
587 noenv = lua_toboolean(L, -1); 598 noenv = lua_toboolean(L, -1);
diff --git a/src/lib_string.c b/src/lib_string.c
index d1a60b61..c7f37bc7 100644
--- a/src/lib_string.c
+++ b/src/lib_string.c
@@ -6,8 +6,6 @@
6** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h 6** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
7*/ 7*/
8 8
9#include <stdio.h>
10
11#define lib_string_c 9#define lib_string_c
12#define LUA_LIB 10#define LUA_LIB
13 11
@@ -18,6 +16,7 @@
18#include "lj_obj.h" 16#include "lj_obj.h"
19#include "lj_gc.h" 17#include "lj_gc.h"
20#include "lj_err.h" 18#include "lj_err.h"
19#include "lj_buf.h"
21#include "lj_str.h" 20#include "lj_str.h"
22#include "lj_tab.h" 21#include "lj_tab.h"
23#include "lj_meta.h" 22#include "lj_meta.h"
@@ -25,17 +24,19 @@
25#include "lj_ff.h" 24#include "lj_ff.h"
26#include "lj_bcdump.h" 25#include "lj_bcdump.h"
27#include "lj_char.h" 26#include "lj_char.h"
27#include "lj_strfmt.h"
28#include "lj_lib.h" 28#include "lj_lib.h"
29 29
30/* ------------------------------------------------------------------------ */ 30/* ------------------------------------------------------------------------ */
31 31
32#define LJLIB_MODULE_string 32#define LJLIB_MODULE_string
33 33
34LJLIB_ASM(string_len) LJLIB_REC(.) 34LJLIB_LUA(string_len) /*
35{ 35 function(s)
36 lj_lib_checkstr(L, 1); 36 CHECK_str(s)
37 return FFH_RETRY; 37 return #s
38} 38 end
39*/
39 40
40LJLIB_ASM(string_byte) LJLIB_REC(string_range 0) 41LJLIB_ASM(string_byte) LJLIB_REC(string_range 0)
41{ 42{
@@ -57,21 +58,21 @@ LJLIB_ASM(string_byte) LJLIB_REC(string_range 0)
57 lj_state_checkstack(L, (MSize)n); 58 lj_state_checkstack(L, (MSize)n);
58 p = (const unsigned char *)strdata(s) + start; 59 p = (const unsigned char *)strdata(s) + start;
59 for (i = 0; i < n; i++) 60 for (i = 0; i < n; i++)
60 setintV(L->base + i-1, p[i]); 61 setintV(L->base + i-1-LJ_FR2, p[i]);
61 return FFH_RES(n); 62 return FFH_RES(n);
62} 63}
63 64
64LJLIB_ASM(string_char) 65LJLIB_ASM(string_char) LJLIB_REC(.)
65{ 66{
66 int i, nargs = (int)(L->top - L->base); 67 int i, nargs = (int)(L->top - L->base);
67 char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, (MSize)nargs); 68 char *buf = lj_buf_tmp(L, (MSize)nargs);
68 for (i = 1; i <= nargs; i++) { 69 for (i = 1; i <= nargs; i++) {
69 int32_t k = lj_lib_checkint(L, i); 70 int32_t k = lj_lib_checkint(L, i);
70 if (!checku8(k)) 71 if (!checku8(k))
71 lj_err_arg(L, i, LJ_ERR_BADVAL); 72 lj_err_arg(L, i, LJ_ERR_BADVAL);
72 buf[i-1] = (char)k; 73 buf[i-1] = (char)k;
73 } 74 }
74 setstrV(L, L->base-1, lj_str_new(L, buf, (size_t)nargs)); 75 setstrV(L, L->base-1-LJ_FR2, lj_str_new(L, buf, (size_t)nargs));
75 return FFH_RES(1); 76 return FFH_RES(1);
76} 77}
77 78
@@ -83,68 +84,38 @@ LJLIB_ASM(string_sub) LJLIB_REC(string_range 1)
83 return FFH_RETRY; 84 return FFH_RETRY;
84} 85}
85 86
86LJLIB_ASM(string_rep) 87LJLIB_CF(string_rep) LJLIB_REC(.)
87{ 88{
88 GCstr *s = lj_lib_checkstr(L, 1); 89 GCstr *s = lj_lib_checkstr(L, 1);
89 int32_t k = lj_lib_checkint(L, 2); 90 int32_t rep = lj_lib_checkint(L, 2);
90 GCstr *sep = lj_lib_optstr(L, 3); 91 GCstr *sep = lj_lib_optstr(L, 3);
91 int32_t len = (int32_t)s->len; 92 SBuf *sb = lj_buf_tmp_(L);
92 global_State *g = G(L); 93 if (sep && rep > 1) {
93 int64_t tlen; 94 GCstr *s2 = lj_buf_cat2str(L, sep, s);
94 const char *src; 95 lj_buf_reset(sb);
95 char *buf; 96 lj_buf_putstr(sb, s);
96 if (k <= 0) { 97 s = s2;
97 empty: 98 rep--;
98 setstrV(L, L->base-1, &g->strempty);
99 return FFH_RES(1);
100 } 99 }
101 if (sep) { 100 sb = lj_buf_putstr_rep(sb, s, rep);
102 tlen = (int64_t)len + sep->len; 101 setstrV(L, L->top-1, lj_buf_str(L, sb));
103 if (tlen > LJ_MAX_STR) 102 lj_gc_check(L);
104 lj_err_caller(L, LJ_ERR_STROV); 103 return 1;
105 tlen *= k;
106 if (tlen > LJ_MAX_STR)
107 lj_err_caller(L, LJ_ERR_STROV);
108 } else {
109 tlen = (int64_t)k * len;
110 if (tlen > LJ_MAX_STR)
111 lj_err_caller(L, LJ_ERR_STROV);
112 }
113 if (tlen == 0) goto empty;
114 buf = lj_str_needbuf(L, &g->tmpbuf, (MSize)tlen);
115 src = strdata(s);
116 if (sep) {
117 tlen -= sep->len; /* Ignore trailing separator. */
118 if (k > 1) { /* Paste one string and one separator. */
119 int32_t i;
120 i = 0; while (i < len) *buf++ = src[i++];
121 src = strdata(sep); len = sep->len;
122 i = 0; while (i < len) *buf++ = src[i++];
123 src = g->tmpbuf.buf; len += s->len; k--; /* Now copy that k-1 times. */
124 }
125 }
126 do {
127 int32_t i = 0;
128 do { *buf++ = src[i++]; } while (i < len);
129 } while (--k > 0);
130 setstrV(L, L->base-1, lj_str_new(L, g->tmpbuf.buf, (size_t)tlen));
131 return FFH_RES(1);
132} 104}
133 105
134LJLIB_ASM(string_reverse) 106LJLIB_ASM(string_reverse) LJLIB_REC(string_op IRCALL_lj_buf_putstr_reverse)
135{ 107{
136 GCstr *s = lj_lib_checkstr(L, 1); 108 lj_lib_checkstr(L, 1);
137 lj_str_needbuf(L, &G(L)->tmpbuf, s->len);
138 return FFH_RETRY; 109 return FFH_RETRY;
139} 110}
140LJLIB_ASM_(string_lower) 111LJLIB_ASM_(string_lower) LJLIB_REC(string_op IRCALL_lj_buf_putstr_lower)
141LJLIB_ASM_(string_upper) 112LJLIB_ASM_(string_upper) LJLIB_REC(string_op IRCALL_lj_buf_putstr_upper)
142 113
143/* ------------------------------------------------------------------------ */ 114/* ------------------------------------------------------------------------ */
144 115
145static int writer_buf(lua_State *L, const void *p, size_t size, void *b) 116static int writer_buf(lua_State *L, const void *p, size_t size, void *sb)
146{ 117{
147 luaL_addlstring((luaL_Buffer *)b, (const char *)p, size); 118 lj_buf_putmem((SBuf *)sb, p, (MSize)size);
148 UNUSED(L); 119 UNUSED(L);
149 return 0; 120 return 0;
150} 121}
@@ -153,12 +124,12 @@ LJLIB_CF(string_dump)
153{ 124{
154 GCfunc *fn = lj_lib_checkfunc(L, 1); 125 GCfunc *fn = lj_lib_checkfunc(L, 1);
155 int strip = L->base+1 < L->top && tvistruecond(L->base+1); 126 int strip = L->base+1 < L->top && tvistruecond(L->base+1);
156 luaL_Buffer b; 127 SBuf *sb = lj_buf_tmp_(L); /* Assumes lj_bcwrite() doesn't use tmpbuf. */
157 L->top = L->base+1; 128 L->top = L->base+1;
158 luaL_buffinit(L, &b); 129 if (!isluafunc(fn) || lj_bcwrite(L, funcproto(fn), writer_buf, sb, strip))
159 if (!isluafunc(fn) || lj_bcwrite(L, funcproto(fn), writer_buf, &b, strip))
160 lj_err_caller(L, LJ_ERR_STRDUMP); 130 lj_err_caller(L, LJ_ERR_STRDUMP);
161 luaL_pushresult(&b); 131 setstrV(L, L->top-1, lj_buf_str(L, sb));
132 lj_gc_check(L);
162 return 1; 133 return 1;
163} 134}
164 135
@@ -183,7 +154,6 @@ typedef struct MatchState {
183} MatchState; 154} MatchState;
184 155
185#define L_ESC '%' 156#define L_ESC '%'
186#define SPECIALS "^$*+?.([%-"
187 157
188static int check_capture(MatchState *ms, int l) 158static int check_capture(MatchState *ms, int l)
189{ 159{
@@ -450,30 +420,6 @@ static const char *match(MatchState *ms, const char *s, const char *p)
450 return s; 420 return s;
451} 421}
452 422
453static const char *lmemfind(const char *s1, size_t l1,
454 const char *s2, size_t l2)
455{
456 if (l2 == 0) {
457 return s1; /* empty strings are everywhere */
458 } else if (l2 > l1) {
459 return NULL; /* avoids a negative `l1' */
460 } else {
461 const char *init; /* to search for a `*s2' inside `s1' */
462 l2--; /* 1st char will be checked by `memchr' */
463 l1 = l1-l2; /* `s2' cannot be found after that */
464 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
465 init++; /* 1st char is already checked */
466 if (memcmp(init, s2+1, l2) == 0) {
467 return init-1;
468 } else { /* correct `l1' and `s1' to try again */
469 l1 -= (size_t)(init-s1);
470 s1 = init;
471 }
472 }
473 return NULL; /* not found */
474 }
475}
476
477static void push_onecapture(MatchState *ms, int i, const char *s, const char *e) 423static void push_onecapture(MatchState *ms, int i, const char *s, const char *e)
478{ 424{
479 if (i >= ms->level) { 425 if (i >= ms->level) {
@@ -501,64 +447,60 @@ static int push_captures(MatchState *ms, const char *s, const char *e)
501 return nlevels; /* number of strings pushed */ 447 return nlevels; /* number of strings pushed */
502} 448}
503 449
504static ptrdiff_t posrelat(ptrdiff_t pos, size_t len)
505{
506 /* relative string position: negative means back from end */
507 if (pos < 0) pos += (ptrdiff_t)len + 1;
508 return (pos >= 0) ? pos : 0;
509}
510
511static int str_find_aux(lua_State *L, int find) 450static int str_find_aux(lua_State *L, int find)
512{ 451{
513 size_t l1, l2; 452 GCstr *s = lj_lib_checkstr(L, 1);
514 const char *s = luaL_checklstring(L, 1, &l1); 453 GCstr *p = lj_lib_checkstr(L, 2);
515 const char *p = luaL_checklstring(L, 2, &l2); 454 int32_t start = lj_lib_optint(L, 3, 1);
516 ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1; 455 MSize st;
517 if (init < 0) { 456 if (start < 0) start += (int32_t)s->len; else start--;
518 init = 0; 457 if (start < 0) start = 0;
519 } else if ((size_t)(init) > l1) { 458 st = (MSize)start;
459 if (st > s->len) {
520#if LJ_52 460#if LJ_52
521 setnilV(L->top-1); 461 setnilV(L->top-1);
522 return 1; 462 return 1;
523#else 463#else
524 init = (ptrdiff_t)l1; 464 st = s->len;
525#endif 465#endif
526 } 466 }
527 if (find && (lua_toboolean(L, 4) || /* explicit request? */ 467 if (find && ((L->base+3 < L->top && tvistruecond(L->base+3)) ||
528 strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */ 468 !lj_str_haspattern(p))) { /* Search for fixed string. */
529 /* do a plain search */ 469 const char *q = lj_str_find(strdata(s)+st, strdata(p), s->len-st, p->len);
530 const char *s2 = lmemfind(s+init, l1-(size_t)init, p, l2); 470 if (q) {
531 if (s2) { 471 setintV(L->top-2, (int32_t)(q-strdata(s)) + 1);
532 lua_pushinteger(L, s2-s+1); 472 setintV(L->top-1, (int32_t)(q-strdata(s)) + (int32_t)p->len);
533 lua_pushinteger(L, s2-s+(ptrdiff_t)l2);
534 return 2; 473 return 2;
535 } 474 }
536 } else { 475 } else { /* Search for pattern. */
537 MatchState ms; 476 MatchState ms;
538 int anchor = (*p == '^') ? (p++, 1) : 0; 477 const char *pstr = strdata(p);
539 const char *s1=s+init; 478 const char *sstr = strdata(s) + st;
479 int anchor = 0;
480 if (*pstr == '^') { pstr++; anchor = 1; }
540 ms.L = L; 481 ms.L = L;
541 ms.src_init = s; 482 ms.src_init = strdata(s);
542 ms.src_end = s+l1; 483 ms.src_end = strdata(s) + s->len;
543 do { 484 do { /* Loop through string and try to match the pattern. */
544 const char *res; 485 const char *q;
545 ms.level = ms.depth = 0; 486 ms.level = ms.depth = 0;
546 if ((res=match(&ms, s1, p)) != NULL) { 487 q = match(&ms, sstr, pstr);
488 if (q) {
547 if (find) { 489 if (find) {
548 lua_pushinteger(L, s1-s+1); /* start */ 490 setintV(L->top++, (int32_t)(sstr-(strdata(s)-1)));
549 lua_pushinteger(L, res-s); /* end */ 491 setintV(L->top++, (int32_t)(q-strdata(s)));
550 return push_captures(&ms, NULL, 0) + 2; 492 return push_captures(&ms, NULL, NULL) + 2;
551 } else { 493 } else {
552 return push_captures(&ms, s1, res); 494 return push_captures(&ms, sstr, q);
553 } 495 }
554 } 496 }
555 } while (s1++ < ms.src_end && !anchor); 497 } while (sstr++ < ms.src_end && !anchor);
556 } 498 }
557 lua_pushnil(L); /* not found */ 499 setnilV(L->top-1); /* Not found. */
558 return 1; 500 return 1;
559} 501}
560 502
561LJLIB_CF(string_find) 503LJLIB_CF(string_find) LJLIB_REC(.)
562{ 504{
563 return str_find_aux(L, 1); 505 return str_find_aux(L, 1);
564} 506}
@@ -698,221 +640,91 @@ LJLIB_CF(string_gsub)
698 640
699/* ------------------------------------------------------------------------ */ 641/* ------------------------------------------------------------------------ */
700 642
701/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ 643/* Emulate tostring() inline. */
702#define MAX_FMTITEM 512 644static GCstr *string_fmt_tostring(lua_State *L, int arg, int retry)
703/* valid flags in a format specification */
704#define FMT_FLAGS "-+ #0"
705/*
706** maximum size of each format specification (such as '%-099.99d')
707** (+10 accounts for %99.99x plus margin of error)
708*/
709#define MAX_FMTSPEC (sizeof(FMT_FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
710
711static void addquoted(lua_State *L, luaL_Buffer *b, int arg)
712{
713 GCstr *str = lj_lib_checkstr(L, arg);
714 int32_t len = (int32_t)str->len;
715 const char *s = strdata(str);
716 luaL_addchar(b, '"');
717 while (len--) {
718 uint32_t c = uchar(*s);
719 if (c == '"' || c == '\\' || c == '\n') {
720 luaL_addchar(b, '\\');
721 } else if (lj_char_iscntrl(c)) { /* This can only be 0-31 or 127. */
722 uint32_t d;
723 luaL_addchar(b, '\\');
724 if (c >= 100 || lj_char_isdigit(uchar(s[1]))) {
725 luaL_addchar(b, '0'+(c >= 100)); if (c >= 100) c -= 100;
726 goto tens;
727 } else if (c >= 10) {
728 tens:
729 d = (c * 205) >> 11; c -= d * 10; luaL_addchar(b, '0'+d);
730 }
731 c += '0';
732 }
733 luaL_addchar(b, c);
734 s++;
735 }
736 luaL_addchar(b, '"');
737}
738
739static const char *scanformat(lua_State *L, const char *strfrmt, char *form)
740{
741 const char *p = strfrmt;
742 while (*p != '\0' && strchr(FMT_FLAGS, *p) != NULL) p++; /* skip flags */
743 if ((size_t)(p - strfrmt) >= sizeof(FMT_FLAGS))
744 lj_err_caller(L, LJ_ERR_STRFMTR);
745 if (lj_char_isdigit(uchar(*p))) p++; /* skip width */
746 if (lj_char_isdigit(uchar(*p))) p++; /* (2 digits at most) */
747 if (*p == '.') {
748 p++;
749 if (lj_char_isdigit(uchar(*p))) p++; /* skip precision */
750 if (lj_char_isdigit(uchar(*p))) p++; /* (2 digits at most) */
751 }
752 if (lj_char_isdigit(uchar(*p)))
753 lj_err_caller(L, LJ_ERR_STRFMTW);
754 *(form++) = '%';
755 strncpy(form, strfrmt, (size_t)(p - strfrmt + 1));
756 form += p - strfrmt + 1;
757 *form = '\0';
758 return p;
759}
760
761static void addintlen(char *form)
762{
763 size_t l = strlen(form);
764 char spec = form[l - 1];
765 strcpy(form + l - 1, LUA_INTFRMLEN);
766 form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
767 form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
768}
769
770static unsigned LUA_INTFRM_T num2intfrm(lua_State *L, int arg)
771{
772 if (sizeof(LUA_INTFRM_T) == 4) {
773 return (LUA_INTFRM_T)lj_lib_checkbit(L, arg);
774 } else {
775 cTValue *o;
776 lj_lib_checknumber(L, arg);
777 o = L->base+arg-1;
778 if (tvisint(o))
779 return (LUA_INTFRM_T)intV(o);
780 else
781 return (LUA_INTFRM_T)numV(o);
782 }
783}
784
785static unsigned LUA_INTFRM_T num2uintfrm(lua_State *L, int arg)
786{
787 if (sizeof(LUA_INTFRM_T) == 4) {
788 return (unsigned LUA_INTFRM_T)lj_lib_checkbit(L, arg);
789 } else {
790 cTValue *o;
791 lj_lib_checknumber(L, arg);
792 o = L->base+arg-1;
793 if (tvisint(o))
794 return (unsigned LUA_INTFRM_T)intV(o);
795 else if ((int32_t)o->u32.hi < 0)
796 return (unsigned LUA_INTFRM_T)(LUA_INTFRM_T)numV(o);
797 else
798 return (unsigned LUA_INTFRM_T)numV(o);
799 }
800}
801
802static GCstr *meta_tostring(lua_State *L, int arg)
803{ 645{
804 TValue *o = L->base+arg-1; 646 TValue *o = L->base+arg-1;
805 cTValue *mo; 647 cTValue *mo;
806 lua_assert(o < L->top); /* Caller already checks for existence. */ 648 lua_assert(o < L->top); /* Caller already checks for existence. */
807 if (LJ_LIKELY(tvisstr(o))) 649 if (LJ_LIKELY(tvisstr(o)))
808 return strV(o); 650 return strV(o);
809 if (!tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) { 651 if (retry != 2 && !tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {
810 copyTV(L, L->top++, mo); 652 copyTV(L, L->top++, mo);
811 copyTV(L, L->top++, o); 653 copyTV(L, L->top++, o);
812 lua_call(L, 1, 1); 654 lua_call(L, 1, 1);
813 L->top--; 655 copyTV(L, L->base+arg-1, --L->top);
814 if (tvisstr(L->top)) 656 return NULL; /* Buffer may be overwritten, retry. */
815 return strV(L->top);
816 o = L->base+arg-1;
817 copyTV(L, o, L->top);
818 }
819 if (tvisnumber(o)) {
820 return lj_str_fromnumber(L, o);
821 } else if (tvisnil(o)) {
822 return lj_str_newlit(L, "nil");
823 } else if (tvisfalse(o)) {
824 return lj_str_newlit(L, "false");
825 } else if (tvistrue(o)) {
826 return lj_str_newlit(L, "true");
827 } else {
828 if (tvisfunc(o) && isffunc(funcV(o)))
829 lj_str_pushf(L, "function: builtin#%d", funcV(o)->c.ffid);
830 else
831 lj_str_pushf(L, "%s: %p", lj_typename(o), lua_topointer(L, arg));
832 L->top--;
833 return strV(L->top);
834 } 657 }
835} 658 return lj_strfmt_obj(L, o);
836 659}
837LJLIB_CF(string_format) 660
838{ 661LJLIB_CF(string_format) LJLIB_REC(.)
839 int arg = 1, top = (int)(L->top - L->base); 662{
840 GCstr *fmt = lj_lib_checkstr(L, arg); 663 int arg, top = (int)(L->top - L->base);
841 const char *strfrmt = strdata(fmt); 664 GCstr *fmt;
842 const char *strfrmt_end = strfrmt + fmt->len; 665 SBuf *sb;
843 luaL_Buffer b; 666 FormatState fs;
844 luaL_buffinit(L, &b); 667 SFormat sf;
845 while (strfrmt < strfrmt_end) { 668 int retry = 0;
846 if (*strfrmt != L_ESC) { 669again:
847 luaL_addchar(&b, *strfrmt++); 670 arg = 1;
848 } else if (*++strfrmt == L_ESC) { 671 sb = lj_buf_tmp_(L);
849 luaL_addchar(&b, *strfrmt++); /* %% */ 672 fmt = lj_lib_checkstr(L, arg);
850 } else { /* format item */ 673 lj_strfmt_init(&fs, strdata(fmt), fmt->len);
851 char form[MAX_FMTSPEC]; /* to store the format (`%...') */ 674 while ((sf = lj_strfmt_parse(&fs)) != STRFMT_EOF) {
852 char buff[MAX_FMTITEM]; /* to store the formatted item */ 675 if (sf == STRFMT_LIT) {
676 lj_buf_putmem(sb, fs.str, fs.len);
677 } else if (sf == STRFMT_ERR) {
678 lj_err_callerv(L, LJ_ERR_STRFMT, strdata(lj_str_new(L, fs.str, fs.len)));
679 } else {
853 if (++arg > top) 680 if (++arg > top)
854 luaL_argerror(L, arg, lj_obj_typename[0]); 681 luaL_argerror(L, arg, lj_obj_typename[0]);
855 strfrmt = scanformat(L, strfrmt, form); 682 switch (STRFMT_TYPE(sf)) {
856 switch (*strfrmt++) { 683 case STRFMT_INT:
857 case 'c': 684 if (tvisint(L->base+arg-1)) {
858 sprintf(buff, form, lj_lib_checkint(L, arg)); 685 int32_t k = intV(L->base+arg-1);
686 if (sf == STRFMT_INT)
687 lj_strfmt_putint(sb, k); /* Shortcut for plain %d. */
688 else
689 lj_strfmt_putfxint(sb, sf, k);
690 } else {
691 lj_strfmt_putfnum_int(sb, sf, lj_lib_checknum(L, arg));
692 }
859 break; 693 break;
860 case 'd': case 'i': 694 case STRFMT_UINT:
861 addintlen(form); 695 if (tvisint(L->base+arg-1))
862 sprintf(buff, form, num2intfrm(L, arg)); 696 lj_strfmt_putfxint(sb, sf, intV(L->base+arg-1));
697 else
698 lj_strfmt_putfnum_uint(sb, sf, lj_lib_checknum(L, arg));
863 break; 699 break;
864 case 'o': case 'u': case 'x': case 'X': 700 case STRFMT_NUM:
865 addintlen(form); 701 lj_strfmt_putfnum(sb, sf, lj_lib_checknum(L, arg));
866 sprintf(buff, form, num2uintfrm(L, arg));
867 break; 702 break;
868 case 'e': case 'E': case 'f': case 'g': case 'G': case 'a': case 'A': { 703 case STRFMT_STR: {
869 TValue tv; 704 GCstr *str = string_fmt_tostring(L, arg, retry);
870 tv.n = lj_lib_checknum(L, arg); 705 if (str == NULL)
871 if (LJ_UNLIKELY((tv.u32.hi << 1) >= 0xffe00000)) { 706 retry = 1;
872 /* Canonicalize output of non-finite values. */ 707 else if ((sf & STRFMT_T_QUOTED))
873 char *p, nbuf[LJ_STR_NUMBUF]; 708 lj_strfmt_putquoted(sb, str); /* No formatting. */
874 size_t len = lj_str_bufnum(nbuf, &tv); 709 else
875 if (strfrmt[-1] < 'a') { 710 lj_strfmt_putfstr(sb, sf, str);
876 nbuf[len-3] = nbuf[len-3] - 0x20;
877 nbuf[len-2] = nbuf[len-2] - 0x20;
878 nbuf[len-1] = nbuf[len-1] - 0x20;
879 }
880 nbuf[len] = '\0';
881 for (p = form; *p < 'A' && *p != '.'; p++) ;
882 *p++ = 's'; *p = '\0';
883 sprintf(buff, form, nbuf);
884 break;
885 }
886 sprintf(buff, form, (double)tv.n);
887 break; 711 break;
888 } 712 }
889 case 'q': 713 case STRFMT_CHAR:
890 addquoted(L, &b, arg); 714 lj_strfmt_putfchar(sb, sf, lj_lib_checkint(L, arg));
891 continue; 715 break;
892 case 'p': 716 case STRFMT_PTR: /* No formatting. */
893 lj_str_pushf(L, "%p", lua_topointer(L, arg)); 717 lj_strfmt_putptr(sb, lj_obj_ptr(L->base+arg-1));
894 luaL_addvalue(&b);
895 continue;
896 case 's': {
897 GCstr *str = meta_tostring(L, arg);
898 if (!strchr(form, '.') && str->len >= 100) {
899 /* no precision and string is too long to be formatted;
900 keep original string */
901 setstrV(L, L->top++, str);
902 luaL_addvalue(&b);
903 continue;
904 }
905 sprintf(buff, form, strdata(str));
906 break; 718 break;
907 }
908 default: 719 default:
909 lj_err_callerv(L, LJ_ERR_STRFMTO, *(strfrmt -1)); 720 lua_assert(0);
910 break; 721 break;
911 } 722 }
912 luaL_addlstring(&b, buff, strlen(buff));
913 } 723 }
914 } 724 }
915 luaL_pushresult(&b); 725 if (retry++ == 1) goto again;
726 setstrV(L, L->top-1, lj_buf_str(L, sb));
727 lj_gc_check(L);
916 return 1; 728 return 1;
917} 729}
918 730
diff --git a/src/lib_table.c b/src/lib_table.c
index b2856ee2..0450f1f6 100644
--- a/src/lib_table.c
+++ b/src/lib_table.c
@@ -16,57 +16,43 @@
16#include "lj_obj.h" 16#include "lj_obj.h"
17#include "lj_gc.h" 17#include "lj_gc.h"
18#include "lj_err.h" 18#include "lj_err.h"
19#include "lj_buf.h"
19#include "lj_tab.h" 20#include "lj_tab.h"
21#include "lj_ff.h"
20#include "lj_lib.h" 22#include "lj_lib.h"
21 23
22/* ------------------------------------------------------------------------ */ 24/* ------------------------------------------------------------------------ */
23 25
24#define LJLIB_MODULE_table 26#define LJLIB_MODULE_table
25 27
26LJLIB_CF(table_foreachi) 28LJLIB_LUA(table_foreachi) /*
27{ 29 function(t, f)
28 GCtab *t = lj_lib_checktab(L, 1); 30 CHECK_tab(t)
29 GCfunc *func = lj_lib_checkfunc(L, 2); 31 CHECK_func(f)
30 MSize i, n = lj_tab_len(t); 32 for i=1,#t do
31 for (i = 1; i <= n; i++) { 33 local r = f(i, t[i])
32 cTValue *val; 34 if r ~= nil then return r end
33 setfuncV(L, L->top, func); 35 end
34 setintV(L->top+1, i); 36 end
35 val = lj_tab_getint(t, (int32_t)i); 37*/
36 if (val) { copyTV(L, L->top+2, val); } else { setnilV(L->top+2); }
37 L->top += 3;
38 lua_call(L, 2, 1);
39 if (!tvisnil(L->top-1))
40 return 1;
41 L->top--;
42 }
43 return 0;
44}
45 38
46LJLIB_CF(table_foreach) 39LJLIB_LUA(table_foreach) /*
47{ 40 function(t, f)
48 GCtab *t = lj_lib_checktab(L, 1); 41 CHECK_tab(t)
49 GCfunc *func = lj_lib_checkfunc(L, 2); 42 CHECK_func(f)
50 L->top = L->base+3; 43 for k, v in PAIRS(t) do
51 setnilV(L->top-1); 44 local r = f(k, v)
52 while (lj_tab_next(L, t, L->top-1)) { 45 if r ~= nil then return r end
53 copyTV(L, L->top+2, L->top); 46 end
54 copyTV(L, L->top+1, L->top-1); 47 end
55 setfuncV(L, L->top, func); 48*/
56 L->top += 3;
57 lua_call(L, 2, 1);
58 if (!tvisnil(L->top-1))
59 return 1;
60 L->top--;
61 }
62 return 0;
63}
64 49
65LJLIB_ASM(table_getn) LJLIB_REC(.) 50LJLIB_LUA(table_getn) /*
66{ 51 function(t)
67 lj_lib_checktab(L, 1); 52 CHECK_tab(t)
68 return FFH_UNREACHABLE; 53 return #t
69} 54 end
55*/
70 56
71LJLIB_CF(table_maxn) 57LJLIB_CF(table_maxn)
72{ 58{
@@ -119,52 +105,67 @@ LJLIB_CF(table_insert) LJLIB_REC(.)
119 return 0; 105 return 0;
120} 106}
121 107
122LJLIB_CF(table_remove) LJLIB_REC(.) 108LJLIB_LUA(table_remove) /*
123{ 109 function(t, pos)
124 GCtab *t = lj_lib_checktab(L, 1); 110 CHECK_tab(t)
125 int32_t e = (int32_t)lj_tab_len(t); 111 local len = #t
126 int32_t pos = lj_lib_optint(L, 2, e); 112 if pos == nil then
127 if (!(1 <= pos && pos <= e)) /* Nothing to remove? */ 113 if len ~= 0 then
128 return 0; 114 local old = t[len]
129 lua_rawgeti(L, 1, pos); /* Get previous value. */ 115 t[len] = nil
130 /* NOBARRIER: This just moves existing elements around. */ 116 return old
131 for (; pos < e; pos++) { 117 end
132 cTValue *src = lj_tab_getint(t, pos+1); 118 else
133 TValue *dst = lj_tab_setint(L, t, pos); 119 CHECK_int(pos)
134 if (src) { 120 if pos >= 1 and pos <= len then
135 copyTV(L, dst, src); 121 local old = t[pos]
136 } else { 122 for i=pos+1,len do
137 setnilV(dst); 123 t[i-1] = t[i]
138 } 124 end
139 } 125 t[len] = nil
140 setnilV(lj_tab_setint(L, t, e)); /* Remove (last) value. */ 126 return old
141 return 1; /* Return previous value. */ 127 end
142} 128 end
129 end
130*/
131
132LJLIB_LUA(table_move) /*
133 function(a1, f, e, t, a2)
134 CHECK_tab(a1)
135 CHECK_int(f)
136 CHECK_int(e)
137 CHECK_int(t)
138 if a2 == nil then a2 = a1 end
139 CHECK_tab(a2)
140 if e >= f then
141 local d = t - f
142 if t > e or t <= f or a2 ~= a1 then
143 for i=f,e do a2[i+d] = a1[i] end
144 else
145 for i=e,f,-1 do a2[i+d] = a1[i] end
146 end
147 end
148 return a2
149 end
150*/
143 151
144LJLIB_CF(table_concat) 152LJLIB_CF(table_concat) LJLIB_REC(.)
145{ 153{
146 luaL_Buffer b;
147 GCtab *t = lj_lib_checktab(L, 1); 154 GCtab *t = lj_lib_checktab(L, 1);
148 GCstr *sep = lj_lib_optstr(L, 2); 155 GCstr *sep = lj_lib_optstr(L, 2);
149 MSize seplen = sep ? sep->len : 0;
150 int32_t i = lj_lib_optint(L, 3, 1); 156 int32_t i = lj_lib_optint(L, 3, 1);
151 int32_t e = (L->base+3 < L->top && !tvisnil(L->base+3)) ? 157 int32_t e = (L->base+3 < L->top && !tvisnil(L->base+3)) ?
152 lj_lib_checkint(L, 4) : (int32_t)lj_tab_len(t); 158 lj_lib_checkint(L, 4) : (int32_t)lj_tab_len(t);
153 luaL_buffinit(L, &b); 159 SBuf *sb = lj_buf_tmp_(L);
154 if (i <= e) { 160 SBuf *sbx = lj_buf_puttab(sb, t, sep, i, e);
155 for (;;) { 161 if (LJ_UNLIKELY(!sbx)) { /* Error: bad element type. */
156 cTValue *o; 162 int32_t idx = (int32_t)(intptr_t)sbufP(sb);
157 lua_rawgeti(L, 1, i); 163 cTValue *o = lj_tab_getint(t, idx);
158 o = L->top-1; 164 lj_err_callerv(L, LJ_ERR_TABCAT,
159 if (!(tvisstr(o) || tvisnumber(o))) 165 lj_obj_itypename[o ? itypemap(o) : ~LJ_TNIL], idx);
160 lj_err_callerv(L, LJ_ERR_TABCAT, lj_typename(o), i);
161 luaL_addvalue(&b);
162 if (i++ == e) break;
163 if (seplen)
164 luaL_addlstring(&b, strdata(sep), seplen);
165 }
166 } 166 }
167 luaL_pushresult(&b); 167 setstrV(L, L->top-1, lj_buf_str(L, sbx));
168 lj_gc_check(L);
168 return 1; 169 return 1;
169} 170}
170 171
@@ -284,6 +285,30 @@ LJLIB_CF(table_pack)
284} 285}
285#endif 286#endif
286 287
288LJLIB_NOREG LJLIB_CF(table_new) LJLIB_REC(.)
289{
290 int32_t a = lj_lib_checkint(L, 1);
291 int32_t h = lj_lib_checkint(L, 2);
292 lua_createtable(L, a, h);
293 return 1;
294}
295
296LJLIB_NOREG LJLIB_CF(table_clear) LJLIB_REC(.)
297{
298 lj_tab_clear(lj_lib_checktab(L, 1));
299 return 0;
300}
301
302static int luaopen_table_new(lua_State *L)
303{
304 return lj_lib_postreg(L, lj_cf_table_new, FF_table_new, "new");
305}
306
307static int luaopen_table_clear(lua_State *L)
308{
309 return lj_lib_postreg(L, lj_cf_table_clear, FF_table_clear, "clear");
310}
311
287/* ------------------------------------------------------------------------ */ 312/* ------------------------------------------------------------------------ */
288 313
289#include "lj_libdef.h" 314#include "lj_libdef.h"
@@ -295,6 +320,8 @@ LUALIB_API int luaopen_table(lua_State *L)
295 lua_getglobal(L, "unpack"); 320 lua_getglobal(L, "unpack");
296 lua_setfield(L, -2, "unpack"); 321 lua_setfield(L, -2, "unpack");
297#endif 322#endif
323 lj_lib_prereg(L, LUA_TABLIBNAME ".new", luaopen_table_new, tabV(L->top-1));
324 lj_lib_prereg(L, LUA_TABLIBNAME ".clear", luaopen_table_clear, tabV(L->top-1));
298 return 1; 325 return 1;
299} 326}
300 327
diff --git a/src/lj_alloc.c b/src/lj_alloc.c
index dc64dca9..95d15d04 100644
--- a/src/lj_alloc.c
+++ b/src/lj_alloc.c
@@ -72,13 +72,56 @@
72 72
73#define IS_DIRECT_BIT (SIZE_T_ONE) 73#define IS_DIRECT_BIT (SIZE_T_ONE)
74 74
75
76/* Determine system-specific block allocation method. */
75#if LJ_TARGET_WINDOWS 77#if LJ_TARGET_WINDOWS
76 78
77#define WIN32_LEAN_AND_MEAN 79#define WIN32_LEAN_AND_MEAN
78#include <windows.h> 80#include <windows.h>
79 81
82#define LJ_ALLOC_VIRTUALALLOC 1
83
84#if LJ_64 && !LJ_GC64
85#define LJ_ALLOC_NTAVM 1
86#endif
87
88#else
89
90#include <errno.h>
91/* If this include fails, then rebuild with: -DLUAJIT_USE_SYSMALLOC */
92#include <sys/mman.h>
93
94#define LJ_ALLOC_MMAP 1
95
80#if LJ_64 96#if LJ_64
81 97
98#define LJ_ALLOC_MMAP_PROBE 1
99
100#if LJ_GC64
101#define LJ_ALLOC_MBITS 47 /* 128 TB in LJ_GC64 mode. */
102#elif LJ_TARGET_X64 && LJ_HASJIT
103/* Due to limitations in the x64 compiler backend. */
104#define LJ_ALLOC_MBITS 31 /* 2 GB on x64 with !LJ_GC64. */
105#else
106#define LJ_ALLOC_MBITS 32 /* 4 GB on other archs with !LJ_GC64. */
107#endif
108
109#endif
110
111#if LJ_64 && !LJ_GC64 && defined(MAP_32BIT)
112#define LJ_ALLOC_MMAP32 1
113#endif
114
115#if LJ_TARGET_LINUX
116#define LJ_ALLOC_MREMAP 1
117#endif
118
119#endif
120
121
122#if LJ_ALLOC_VIRTUALALLOC
123
124#if LJ_ALLOC_NTAVM
82/* Undocumented, but hey, that's what we all love so much about Windows. */ 125/* Undocumented, but hey, that's what we all love so much about Windows. */
83typedef long (*PNTAVM)(HANDLE handle, void **addr, ULONG zbits, 126typedef long (*PNTAVM)(HANDLE handle, void **addr, ULONG zbits,
84 size_t *size, ULONG alloctype, ULONG prot); 127 size_t *size, ULONG alloctype, ULONG prot);
@@ -89,14 +132,15 @@ static PNTAVM ntavm;
89*/ 132*/
90#define NTAVM_ZEROBITS 1 133#define NTAVM_ZEROBITS 1
91 134
92static void INIT_MMAP(void) 135static void init_mmap(void)
93{ 136{
94 ntavm = (PNTAVM)GetProcAddress(GetModuleHandleA("ntdll.dll"), 137 ntavm = (PNTAVM)GetProcAddress(GetModuleHandleA("ntdll.dll"),
95 "NtAllocateVirtualMemory"); 138 "NtAllocateVirtualMemory");
96} 139}
140#define INIT_MMAP() init_mmap()
97 141
98/* Win64 32 bit MMAP via NtAllocateVirtualMemory. */ 142/* Win64 32 bit MMAP via NtAllocateVirtualMemory. */
99static LJ_AINLINE void *CALL_MMAP(size_t size) 143static void *CALL_MMAP(size_t size)
100{ 144{
101 DWORD olderr = GetLastError(); 145 DWORD olderr = GetLastError();
102 void *ptr = NULL; 146 void *ptr = NULL;
@@ -107,7 +151,7 @@ static LJ_AINLINE void *CALL_MMAP(size_t size)
107} 151}
108 152
109/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ 153/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
110static LJ_AINLINE void *DIRECT_MMAP(size_t size) 154static void *DIRECT_MMAP(size_t size)
111{ 155{
112 DWORD olderr = GetLastError(); 156 DWORD olderr = GetLastError();
113 void *ptr = NULL; 157 void *ptr = NULL;
@@ -119,10 +163,8 @@ static LJ_AINLINE void *DIRECT_MMAP(size_t size)
119 163
120#else 164#else
121 165
122#define INIT_MMAP() ((void)0)
123
124/* Win32 MMAP via VirtualAlloc */ 166/* Win32 MMAP via VirtualAlloc */
125static LJ_AINLINE void *CALL_MMAP(size_t size) 167static void *CALL_MMAP(size_t size)
126{ 168{
127 DWORD olderr = GetLastError(); 169 DWORD olderr = GetLastError();
128 void *ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); 170 void *ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE);
@@ -131,7 +173,7 @@ static LJ_AINLINE void *CALL_MMAP(size_t size)
131} 173}
132 174
133/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ 175/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */
134static LJ_AINLINE void *DIRECT_MMAP(size_t size) 176static void *DIRECT_MMAP(size_t size)
135{ 177{
136 DWORD olderr = GetLastError(); 178 DWORD olderr = GetLastError();
137 void *ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, 179 void *ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN,
@@ -143,7 +185,7 @@ static LJ_AINLINE void *DIRECT_MMAP(size_t size)
143#endif 185#endif
144 186
145/* This function supports releasing coalesed segments */ 187/* This function supports releasing coalesed segments */
146static LJ_AINLINE int CALL_MUNMAP(void *ptr, size_t size) 188static int CALL_MUNMAP(void *ptr, size_t size)
147{ 189{
148 DWORD olderr = GetLastError(); 190 DWORD olderr = GetLastError();
149 MEMORY_BASIC_INFORMATION minfo; 191 MEMORY_BASIC_INFORMATION minfo;
@@ -163,10 +205,7 @@ static LJ_AINLINE int CALL_MUNMAP(void *ptr, size_t size)
163 return 0; 205 return 0;
164} 206}
165 207
166#else 208#elif LJ_ALLOC_MMAP
167
168#include <errno.h>
169#include <sys/mman.h>
170 209
171#define MMAP_PROT (PROT_READ|PROT_WRITE) 210#define MMAP_PROT (PROT_READ|PROT_WRITE)
172#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) 211#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)
@@ -174,105 +213,151 @@ static LJ_AINLINE int CALL_MUNMAP(void *ptr, size_t size)
174#endif 213#endif
175#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) 214#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS)
176 215
177#if LJ_64 216#if LJ_ALLOC_MMAP_PROBE
178/* 64 bit mode needs special support for allocating memory in the lower 2GB. */
179
180#if defined(MAP_32BIT)
181 217
182#if defined(__sun__) 218#ifdef MAP_TRYFIXED
183#define MMAP_REGION_START ((uintptr_t)0x1000) 219#define MMAP_FLAGS_PROBE (MMAP_FLAGS|MAP_TRYFIXED)
184#else 220#else
185/* Actually this only gives us max. 1GB in current Linux kernels. */ 221#define MMAP_FLAGS_PROBE MMAP_FLAGS
186#define MMAP_REGION_START ((uintptr_t)0)
187#endif 222#endif
188 223
189static LJ_AINLINE void *CALL_MMAP(size_t size) 224#define LJ_ALLOC_MMAP_PROBE_MAX 30
190{ 225#define LJ_ALLOC_MMAP_PROBE_LINEAR 5
191 int olderr = errno;
192 void *ptr = mmap((void *)MMAP_REGION_START, size, MMAP_PROT, MAP_32BIT|MMAP_FLAGS, -1, 0);
193 errno = olderr;
194 return ptr;
195}
196 226
197#elif LJ_TARGET_OSX || LJ_TARGET_PS4 || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__sun__) || LJ_TARGET_CYGWIN 227#define LJ_ALLOC_MMAP_PROBE_LOWER ((uintptr_t)0x4000)
198 228
199/* OSX and FreeBSD mmap() use a naive first-fit linear search. 229/* No point in a giant ifdef mess. Just try to open /dev/urandom.
200** That's perfect for us. Except that -pagezero_size must be set for OSX, 230** It doesn't really matter if this fails, since we get some ASLR bits from
201** otherwise the lower 4GB are blocked. And the 32GB RLIMIT_DATA needs 231** every unsuitable allocation, too. And we prefer linear allocation, anyway.
202** to be reduced to 250MB on FreeBSD.
203*/ 232*/
204#if LJ_TARGET_OSX || defined(__DragonFly__) 233#include <fcntl.h>
205#define MMAP_REGION_START ((uintptr_t)0x10000) 234#include <unistd.h>
206#elif LJ_TARGET_PS4
207#define MMAP_REGION_START ((uintptr_t)0x4000)
208#else
209#define MMAP_REGION_START ((uintptr_t)0x10000000)
210#endif
211#define MMAP_REGION_END ((uintptr_t)0x80000000)
212 235
213#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) && !LJ_TARGET_PS4 236static uintptr_t mmap_probe_seed(void)
214#include <sys/resource.h> 237{
215#endif 238 uintptr_t val;
239 int fd = open("/dev/urandom", O_RDONLY);
240 if (fd != -1) {
241 int ok = ((size_t)read(fd, &val, sizeof(val)) == sizeof(val));
242 (void)close(fd);
243 if (ok) return val;
244 }
245 return 1; /* Punt. */
246}
216 247
217static LJ_AINLINE void *CALL_MMAP(size_t size) 248static void *mmap_probe(size_t size)
218{ 249{
219 int olderr = errno;
220 /* Hint for next allocation. Doesn't need to be thread-safe. */ 250 /* Hint for next allocation. Doesn't need to be thread-safe. */
221 static uintptr_t alloc_hint = MMAP_REGION_START; 251 static uintptr_t hint_addr = 0;
222 int retry = 0; 252 static uintptr_t hint_prng = 0;
223#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) && !LJ_TARGET_PS4 253 int olderr = errno;
224 static int rlimit_modified = 0; 254 int retry;
225 if (LJ_UNLIKELY(rlimit_modified == 0)) { 255 for (retry = 0; retry < LJ_ALLOC_MMAP_PROBE_MAX; retry++) {
226 struct rlimit rlim; 256 void *p = mmap((void *)hint_addr, size, MMAP_PROT, MMAP_FLAGS_PROBE, -1, 0);
227 rlim.rlim_cur = rlim.rlim_max = MMAP_REGION_START; 257 uintptr_t addr = (uintptr_t)p;
228 setrlimit(RLIMIT_DATA, &rlim); /* Ignore result. May fail below. */ 258 if ((addr >> LJ_ALLOC_MBITS) == 0 && addr >= LJ_ALLOC_MMAP_PROBE_LOWER) {
229 rlimit_modified = 1; 259 /* We got a suitable address. Bump the hint address. */
230 } 260 hint_addr = addr + size;
231#endif
232 for (;;) {
233 void *p = mmap((void *)alloc_hint, size, MMAP_PROT, MMAP_FLAGS, -1, 0);
234 if ((uintptr_t)p >= MMAP_REGION_START &&
235 (uintptr_t)p + size < MMAP_REGION_END) {
236 alloc_hint = (uintptr_t)p + size;
237 errno = olderr; 261 errno = olderr;
238 return p; 262 return p;
239 } 263 }
240 if (p != CMFAIL) munmap(p, size); 264 if (p != MFAIL) {
241#if defined(__sun__) || defined(__DragonFly__) 265 munmap(p, size);
242 alloc_hint += 0x1000000; /* Need near-exhaustive linear scan. */ 266 } else if (errno == ENOMEM) {
243 if (alloc_hint + size < MMAP_REGION_END) continue; 267 return MFAIL;
244#endif 268 }
245 if (retry) break; 269 if (hint_addr) {
246 retry = 1; 270 /* First, try linear probing. */
247 alloc_hint = MMAP_REGION_START; 271 if (retry < LJ_ALLOC_MMAP_PROBE_LINEAR) {
272 hint_addr += 0x1000000;
273 if (((hint_addr + size) >> LJ_ALLOC_MBITS) != 0)
274 hint_addr = 0;
275 continue;
276 } else if (retry == LJ_ALLOC_MMAP_PROBE_LINEAR) {
277 /* Next, try a no-hint probe to get back an ASLR address. */
278 hint_addr = 0;
279 continue;
280 }
281 }
282 /* Finally, try pseudo-random probing. */
283 if (LJ_UNLIKELY(hint_prng == 0)) {
284 hint_prng = mmap_probe_seed();
285 }
286 /* The unsuitable address we got has some ASLR PRNG bits. */
287 hint_addr ^= addr & ~((uintptr_t)(LJ_PAGESIZE-1));
288 do { /* The PRNG itself is very weak, but see above. */
289 hint_prng = hint_prng * 1103515245 + 12345;
290 hint_addr ^= hint_prng * (uintptr_t)LJ_PAGESIZE;
291 hint_addr &= (((uintptr_t)1 << LJ_ALLOC_MBITS)-1);
292 } while (hint_addr < LJ_ALLOC_MMAP_PROBE_LOWER);
248 } 293 }
249 errno = olderr; 294 errno = olderr;
250 return CMFAIL; 295 return MFAIL;
251} 296}
252 297
298#endif
299
300#if LJ_ALLOC_MMAP32
301
302#if defined(__sun__)
303#define LJ_ALLOC_MMAP32_START ((uintptr_t)0x1000)
253#else 304#else
305#define LJ_ALLOC_MMAP32_START ((uintptr_t)0)
306#endif
254 307
255#error "NYI: need an equivalent of MAP_32BIT for this 64 bit OS" 308static void *mmap_map32(size_t size)
309{
310#if LJ_ALLOC_MMAP_PROBE
311 static int fallback = 0;
312 if (fallback)
313 return mmap_probe(size);
314#endif
315 {
316 int olderr = errno;
317 void *ptr = mmap((void *)LJ_ALLOC_MMAP32_START, size, MMAP_PROT, MAP_32BIT|MMAP_FLAGS, -1, 0);
318 errno = olderr;
319 /* This only allows 1GB on Linux. So fallback to probing to get 2GB. */
320#if LJ_ALLOC_MMAP_PROBE
321 if (ptr == MFAIL) {
322 fallback = 1;
323 return mmap_probe(size);
324 }
325#endif
326 return ptr;
327 }
328}
256 329
257#endif 330#endif
258 331
332#if LJ_ALLOC_MMAP32
333#define CALL_MMAP(size) mmap_map32(size)
334#elif LJ_ALLOC_MMAP_PROBE
335#define CALL_MMAP(size) mmap_probe(size)
259#else 336#else
260 337static void *CALL_MMAP(size_t size)
261/* 32 bit mode is easy. */
262static LJ_AINLINE void *CALL_MMAP(size_t size)
263{ 338{
264 int olderr = errno; 339 int olderr = errno;
265 void *ptr = mmap(NULL, size, MMAP_PROT, MMAP_FLAGS, -1, 0); 340 void *ptr = mmap(NULL, size, MMAP_PROT, MMAP_FLAGS, -1, 0);
266 errno = olderr; 341 errno = olderr;
267 return ptr; 342 return ptr;
268} 343}
269
270#endif 344#endif
271 345
272#define INIT_MMAP() ((void)0) 346#if (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) && !LJ_TARGET_PS4
273#define DIRECT_MMAP(s) CALL_MMAP(s) 347
348#include <sys/resource.h>
349
350static void init_mmap(void)
351{
352 struct rlimit rlim;
353 rlim.rlim_cur = rlim.rlim_max = 0x10000;
354 setrlimit(RLIMIT_DATA, &rlim); /* Ignore result. May fail later. */
355}
356#define INIT_MMAP() init_mmap()
274 357
275static LJ_AINLINE int CALL_MUNMAP(void *ptr, size_t size) 358#endif
359
360static int CALL_MUNMAP(void *ptr, size_t size)
276{ 361{
277 int olderr = errno; 362 int olderr = errno;
278 int ret = munmap(ptr, size); 363 int ret = munmap(ptr, size);
@@ -280,10 +365,9 @@ static LJ_AINLINE int CALL_MUNMAP(void *ptr, size_t size)
280 return ret; 365 return ret;
281} 366}
282 367
283#if LJ_TARGET_LINUX 368#if LJ_ALLOC_MREMAP
284/* Need to define _GNU_SOURCE to get the mremap prototype. */ 369/* Need to define _GNU_SOURCE to get the mremap prototype. */
285static LJ_AINLINE void *CALL_MREMAP_(void *ptr, size_t osz, size_t nsz, 370static void *CALL_MREMAP_(void *ptr, size_t osz, size_t nsz, int flags)
286 int flags)
287{ 371{
288 int olderr = errno; 372 int olderr = errno;
289 ptr = mremap(ptr, osz, nsz, flags); 373 ptr = mremap(ptr, osz, nsz, flags);
@@ -294,7 +378,7 @@ static LJ_AINLINE void *CALL_MREMAP_(void *ptr, size_t osz, size_t nsz,
294#define CALL_MREMAP(addr, osz, nsz, mv) CALL_MREMAP_((addr), (osz), (nsz), (mv)) 378#define CALL_MREMAP(addr, osz, nsz, mv) CALL_MREMAP_((addr), (osz), (nsz), (mv))
295#define CALL_MREMAP_NOMOVE 0 379#define CALL_MREMAP_NOMOVE 0
296#define CALL_MREMAP_MAYMOVE 1 380#define CALL_MREMAP_MAYMOVE 1
297#if LJ_64 381#if LJ_64 && !LJ_GC64
298#define CALL_MREMAP_MV CALL_MREMAP_NOMOVE 382#define CALL_MREMAP_MV CALL_MREMAP_NOMOVE
299#else 383#else
300#define CALL_MREMAP_MV CALL_MREMAP_MAYMOVE 384#define CALL_MREMAP_MV CALL_MREMAP_MAYMOVE
@@ -303,6 +387,15 @@ static LJ_AINLINE void *CALL_MREMAP_(void *ptr, size_t osz, size_t nsz,
303 387
304#endif 388#endif
305 389
390
391#ifndef INIT_MMAP
392#define INIT_MMAP() ((void)0)
393#endif
394
395#ifndef DIRECT_MMAP
396#define DIRECT_MMAP(s) CALL_MMAP(s)
397#endif
398
306#ifndef CALL_MREMAP 399#ifndef CALL_MREMAP
307#define CALL_MREMAP(addr, osz, nsz, mv) ((void)osz, MFAIL) 400#define CALL_MREMAP(addr, osz, nsz, mv) ((void)osz, MFAIL)
308#endif 401#endif
diff --git a/src/lj_api.c b/src/lj_api.c
index 7b0b3f9d..d1be3abf 100644
--- a/src/lj_api.c
+++ b/src/lj_api.c
@@ -24,6 +24,7 @@
24#include "lj_trace.h" 24#include "lj_trace.h"
25#include "lj_vm.h" 25#include "lj_vm.h"
26#include "lj_strscan.h" 26#include "lj_strscan.h"
27#include "lj_strfmt.h"
27 28
28/* -- Common helper functions --------------------------------------------- */ 29/* -- Common helper functions --------------------------------------------- */
29 30
@@ -188,7 +189,7 @@ LUA_API int lua_type(lua_State *L, int idx)
188 cTValue *o = index2adr(L, idx); 189 cTValue *o = index2adr(L, idx);
189 if (tvisnumber(o)) { 190 if (tvisnumber(o)) {
190 return LUA_TNUMBER; 191 return LUA_TNUMBER;
191#if LJ_64 192#if LJ_64 && !LJ_GC64
192 } else if (tvislightud(o)) { 193 } else if (tvislightud(o)) {
193 return LUA_TLIGHTUSERDATA; 194 return LUA_TLIGHTUSERDATA;
194#endif 195#endif
@@ -268,7 +269,7 @@ LUA_API int lua_equal(lua_State *L, int idx1, int idx2)
268 return 0; 269 return 0;
269 } else if (tvispri(o1)) { 270 } else if (tvispri(o1)) {
270 return o1 != niltv(L) && o2 != niltv(L); 271 return o1 != niltv(L) && o2 != niltv(L);
271#if LJ_64 272#if LJ_64 && !LJ_GC64
272 } else if (tvislightud(o1)) { 273 } else if (tvislightud(o1)) {
273 return o1->u64 == o2->u64; 274 return o1->u64 == o2->u64;
274#endif 275#endif
@@ -283,8 +284,8 @@ LUA_API int lua_equal(lua_State *L, int idx1, int idx2)
283 } else { 284 } else {
284 L->top = base+2; 285 L->top = base+2;
285 lj_vm_call(L, base, 1+1); 286 lj_vm_call(L, base, 1+1);
286 L->top -= 2; 287 L->top -= 2+LJ_FR2;
287 return tvistruecond(L->top+1); 288 return tvistruecond(L->top+1+LJ_FR2);
288 } 289 }
289 } 290 }
290} 291}
@@ -306,8 +307,8 @@ LUA_API int lua_lessthan(lua_State *L, int idx1, int idx2)
306 } else { 307 } else {
307 L->top = base+2; 308 L->top = base+2;
308 lj_vm_call(L, base, 1+1); 309 lj_vm_call(L, base, 1+1);
309 L->top -= 2; 310 L->top -= 2+LJ_FR2;
310 return tvistruecond(L->top+1); 311 return tvistruecond(L->top+1+LJ_FR2);
311 } 312 }
312 } 313 }
313} 314}
@@ -434,7 +435,7 @@ LUA_API const char *lua_tolstring(lua_State *L, int idx, size_t *len)
434 } else if (tvisnumber(o)) { 435 } else if (tvisnumber(o)) {
435 lj_gc_check(L); 436 lj_gc_check(L);
436 o = index2adr(L, idx); /* GC may move the stack. */ 437 o = index2adr(L, idx); /* GC may move the stack. */
437 s = lj_str_fromnumber(L, o); 438 s = lj_strfmt_number(L, o);
438 setstrV(L, o, s); 439 setstrV(L, o, s);
439 } else { 440 } else {
440 if (len != NULL) *len = 0; 441 if (len != NULL) *len = 0;
@@ -453,7 +454,7 @@ LUALIB_API const char *luaL_checklstring(lua_State *L, int idx, size_t *len)
453 } else if (tvisnumber(o)) { 454 } else if (tvisnumber(o)) {
454 lj_gc_check(L); 455 lj_gc_check(L);
455 o = index2adr(L, idx); /* GC may move the stack. */ 456 o = index2adr(L, idx); /* GC may move the stack. */
456 s = lj_str_fromnumber(L, o); 457 s = lj_strfmt_number(L, o);
457 setstrV(L, o, s); 458 setstrV(L, o, s);
458 } else { 459 } else {
459 lj_err_argt(L, idx, LUA_TSTRING); 460 lj_err_argt(L, idx, LUA_TSTRING);
@@ -475,7 +476,7 @@ LUALIB_API const char *luaL_optlstring(lua_State *L, int idx,
475 } else if (tvisnumber(o)) { 476 } else if (tvisnumber(o)) {
476 lj_gc_check(L); 477 lj_gc_check(L);
477 o = index2adr(L, idx); /* GC may move the stack. */ 478 o = index2adr(L, idx); /* GC may move the stack. */
478 s = lj_str_fromnumber(L, o); 479 s = lj_strfmt_number(L, o);
479 setstrV(L, o, s); 480 setstrV(L, o, s);
480 } else { 481 } else {
481 lj_err_argt(L, idx, LUA_TSTRING); 482 lj_err_argt(L, idx, LUA_TSTRING);
@@ -507,7 +508,7 @@ LUA_API size_t lua_objlen(lua_State *L, int idx)
507 } else if (tvisudata(o)) { 508 } else if (tvisudata(o)) {
508 return udataV(o)->len; 509 return udataV(o)->len;
509 } else if (tvisnumber(o)) { 510 } else if (tvisnumber(o)) {
510 GCstr *s = lj_str_fromnumber(L, o); 511 GCstr *s = lj_strfmt_number(L, o);
511 setstrV(L, o, s); 512 setstrV(L, o, s);
512 return s->len; 513 return s->len;
513 } else { 514 } else {
@@ -545,17 +546,7 @@ LUA_API lua_State *lua_tothread(lua_State *L, int idx)
545 546
546LUA_API const void *lua_topointer(lua_State *L, int idx) 547LUA_API const void *lua_topointer(lua_State *L, int idx)
547{ 548{
548 cTValue *o = index2adr(L, idx); 549 return lj_obj_ptr(index2adr(L, idx));
549 if (tvisudata(o))
550 return uddata(udataV(o));
551 else if (tvislightud(o))
552 return lightudV(o);
553 else if (tviscdata(o))
554 return cdataptr(cdataV(o));
555 else if (tvisgcv(o))
556 return gcV(o);
557 else
558 return NULL;
559} 550}
560 551
561/* -- Stack setters (object creation) ------------------------------------- */ 552/* -- Stack setters (object creation) ------------------------------------- */
@@ -606,7 +597,7 @@ LUA_API const char *lua_pushvfstring(lua_State *L, const char *fmt,
606 va_list argp) 597 va_list argp)
607{ 598{
608 lj_gc_check(L); 599 lj_gc_check(L);
609 return lj_str_pushvf(L, fmt, argp); 600 return lj_strfmt_pushvf(L, fmt, argp);
610} 601}
611 602
612LUA_API const char *lua_pushfstring(lua_State *L, const char *fmt, ...) 603LUA_API const char *lua_pushfstring(lua_State *L, const char *fmt, ...)
@@ -615,7 +606,7 @@ LUA_API const char *lua_pushfstring(lua_State *L, const char *fmt, ...)
615 va_list argp; 606 va_list argp;
616 lj_gc_check(L); 607 lj_gc_check(L);
617 va_start(argp, fmt); 608 va_start(argp, fmt);
618 ret = lj_str_pushvf(L, fmt, argp); 609 ret = lj_strfmt_pushvf(L, fmt, argp);
619 va_end(argp); 610 va_end(argp);
620 return ret; 611 return ret;
621} 612}
@@ -649,10 +640,8 @@ LUA_API void lua_pushlightuserdata(lua_State *L, void *p)
649 640
650LUA_API void lua_createtable(lua_State *L, int narray, int nrec) 641LUA_API void lua_createtable(lua_State *L, int narray, int nrec)
651{ 642{
652 GCtab *t;
653 lj_gc_check(L); 643 lj_gc_check(L);
654 t = lj_tab_new(L, (uint32_t)(narray > 0 ? narray+1 : 0), hsize2hbits(nrec)); 644 settabV(L, L->top, lj_tab_new_ah(L, narray, nrec));
655 settabV(L, L->top, t);
656 incr_top(L); 645 incr_top(L);
657} 646}
658 647
@@ -715,8 +704,8 @@ LUA_API void lua_concat(lua_State *L, int n)
715 n -= (int)(L->top - top); 704 n -= (int)(L->top - top);
716 L->top = top+2; 705 L->top = top+2;
717 lj_vm_call(L, top, 1+1); 706 lj_vm_call(L, top, 1+1);
718 L->top--; 707 L->top -= 1+LJ_FR2;
719 copyTV(L, L->top-1, L->top); 708 copyTV(L, L->top-1, L->top+LJ_FR2);
720 } while (--n > 0); 709 } while (--n > 0);
721 } else if (n == 0) { /* Push empty string. */ 710 } else if (n == 0) { /* Push empty string. */
722 setstrV(L, L->top, &G(L)->strempty); 711 setstrV(L, L->top, &G(L)->strempty);
@@ -735,8 +724,8 @@ LUA_API void lua_gettable(lua_State *L, int idx)
735 if (v == NULL) { 724 if (v == NULL) {
736 L->top += 2; 725 L->top += 2;
737 lj_vm_call(L, L->top-2, 1+1); 726 lj_vm_call(L, L->top-2, 1+1);
738 L->top -= 2; 727 L->top -= 2+LJ_FR2;
739 v = L->top+1; 728 v = L->top+1+LJ_FR2;
740 } 729 }
741 copyTV(L, L->top-1, v); 730 copyTV(L, L->top-1, v);
742} 731}
@@ -751,8 +740,8 @@ LUA_API void lua_getfield(lua_State *L, int idx, const char *k)
751 if (v == NULL) { 740 if (v == NULL) {
752 L->top += 2; 741 L->top += 2;
753 lj_vm_call(L, L->top-2, 1+1); 742 lj_vm_call(L, L->top-2, 1+1);
754 L->top -= 2; 743 L->top -= 2+LJ_FR2;
755 v = L->top+1; 744 v = L->top+1+LJ_FR2;
756 } 745 }
757 copyTV(L, L->top, v); 746 copyTV(L, L->top, v);
758 incr_top(L); 747 incr_top(L);
@@ -893,13 +882,14 @@ LUA_API void lua_settable(lua_State *L, int idx)
893 o = lj_meta_tset(L, t, L->top-2); 882 o = lj_meta_tset(L, t, L->top-2);
894 if (o) { 883 if (o) {
895 /* NOBARRIER: lj_meta_tset ensures the table is not black. */ 884 /* NOBARRIER: lj_meta_tset ensures the table is not black. */
896 copyTV(L, o, L->top-1);
897 L->top -= 2; 885 L->top -= 2;
886 copyTV(L, o, L->top+1);
898 } else { 887 } else {
899 L->top += 3; 888 TValue *base = L->top;
900 copyTV(L, L->top-1, L->top-6); 889 copyTV(L, base+2, base-3-2*LJ_FR2);
901 lj_vm_call(L, L->top-3, 0+1); 890 L->top = base+3;
902 L->top -= 3; 891 lj_vm_call(L, base, 0+1);
892 L->top -= 3+LJ_FR2;
903 } 893 }
904} 894}
905 895
@@ -913,14 +903,14 @@ LUA_API void lua_setfield(lua_State *L, int idx, const char *k)
913 setstrV(L, &key, lj_str_newz(L, k)); 903 setstrV(L, &key, lj_str_newz(L, k));
914 o = lj_meta_tset(L, t, &key); 904 o = lj_meta_tset(L, t, &key);
915 if (o) { 905 if (o) {
916 L->top--;
917 /* NOBARRIER: lj_meta_tset ensures the table is not black. */ 906 /* NOBARRIER: lj_meta_tset ensures the table is not black. */
918 copyTV(L, o, L->top); 907 copyTV(L, o, --L->top);
919 } else { 908 } else {
920 L->top += 3; 909 TValue *base = L->top;
921 copyTV(L, L->top-1, L->top-6); 910 copyTV(L, base+2, base-3-2*LJ_FR2);
922 lj_vm_call(L, L->top-3, 0+1); 911 L->top = base+3;
923 L->top -= 2; 912 lj_vm_call(L, base, 0+1);
913 L->top -= 2+LJ_FR2;
924 } 914 }
925} 915}
926 916
@@ -1027,11 +1017,24 @@ LUA_API const char *lua_setupvalue(lua_State *L, int idx, int n)
1027 1017
1028/* -- Calls --------------------------------------------------------------- */ 1018/* -- Calls --------------------------------------------------------------- */
1029 1019
1020#if LJ_FR2
1021static TValue *api_call_base(lua_State *L, int nargs)
1022{
1023 TValue *o = L->top, *base = o - nargs;
1024 L->top = o+1;
1025 for (; o > base; o--) copyTV(L, o, o-1);
1026 setnilV(o);
1027 return o+1;
1028}
1029#else
1030#define api_call_base(L, nargs) (L->top - (nargs))
1031#endif
1032
1030LUA_API void lua_call(lua_State *L, int nargs, int nresults) 1033LUA_API void lua_call(lua_State *L, int nargs, int nresults)
1031{ 1034{
1032 api_check(L, L->status == 0 || L->status == LUA_ERRERR); 1035 api_check(L, L->status == 0 || L->status == LUA_ERRERR);
1033 api_checknelems(L, nargs+1); 1036 api_checknelems(L, nargs+1);
1034 lj_vm_call(L, L->top - nargs, nresults+1); 1037 lj_vm_call(L, api_call_base(L, nargs), nresults+1);
1035} 1038}
1036 1039
1037LUA_API int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc) 1040LUA_API int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc)
@@ -1049,7 +1052,7 @@ LUA_API int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc)
1049 api_checkvalidindex(L, o); 1052 api_checkvalidindex(L, o);
1050 ef = savestack(L, o); 1053 ef = savestack(L, o);
1051 } 1054 }
1052 status = lj_vm_pcall(L, L->top - nargs, nresults+1, ef); 1055 status = lj_vm_pcall(L, api_call_base(L, nargs), nresults+1, ef);
1053 if (status) hook_restore(g, oldh); 1056 if (status) hook_restore(g, oldh);
1054 return status; 1057 return status;
1055} 1058}
@@ -1057,12 +1060,14 @@ LUA_API int lua_pcall(lua_State *L, int nargs, int nresults, int errfunc)
1057static TValue *cpcall(lua_State *L, lua_CFunction func, void *ud) 1060static TValue *cpcall(lua_State *L, lua_CFunction func, void *ud)
1058{ 1061{
1059 GCfunc *fn = lj_func_newC(L, 0, getcurrenv(L)); 1062 GCfunc *fn = lj_func_newC(L, 0, getcurrenv(L));
1063 TValue *top = L->top;
1060 fn->c.f = func; 1064 fn->c.f = func;
1061 setfuncV(L, L->top, fn); 1065 setfuncV(L, top++, fn);
1062 setlightudV(L->top+1, checklightudptr(L, ud)); 1066 if (LJ_FR2) setnilV(top++);
1067 setlightudV(top++, checklightudptr(L, ud));
1063 cframe_nres(L->cframe) = 1+0; /* Zero results. */ 1068 cframe_nres(L->cframe) = 1+0; /* Zero results. */
1064 L->top += 2; 1069 L->top = top;
1065 return L->top-1; /* Now call the newly allocated C function. */ 1070 return top-1; /* Now call the newly allocated C function. */
1066} 1071}
1067 1072
1068LUA_API int lua_cpcall(lua_State *L, lua_CFunction func, void *ud) 1073LUA_API int lua_cpcall(lua_State *L, lua_CFunction func, void *ud)
@@ -1079,10 +1084,11 @@ LUA_API int lua_cpcall(lua_State *L, lua_CFunction func, void *ud)
1079LUALIB_API int luaL_callmeta(lua_State *L, int idx, const char *field) 1084LUALIB_API int luaL_callmeta(lua_State *L, int idx, const char *field)
1080{ 1085{
1081 if (luaL_getmetafield(L, idx, field)) { 1086 if (luaL_getmetafield(L, idx, field)) {
1082 TValue *base = L->top--; 1087 TValue *top = L->top--;
1083 copyTV(L, base, index2adr(L, idx)); 1088 if (LJ_FR2) setnilV(top++);
1084 L->top = base+1; 1089 copyTV(L, top++, index2adr(L, idx));
1085 lj_vm_call(L, base, 1+1); 1090 L->top = top;
1091 lj_vm_call(L, top-1, 1+1);
1086 return 1; 1092 return 1;
1087 } 1093 }
1088 return 0; 1094 return 0;
@@ -1109,12 +1115,14 @@ LUA_API int lua_yield(lua_State *L, int nresults)
1109 } else { /* Yield from hook: add a pseudo-frame. */ 1115 } else { /* Yield from hook: add a pseudo-frame. */
1110 TValue *top = L->top; 1116 TValue *top = L->top;
1111 hook_leave(g); 1117 hook_leave(g);
1112 top->u64 = cframe_multres(cf); 1118 (top++)->u64 = cframe_multres(cf);
1113 setcont(top+1, lj_cont_hook); 1119 setcont(top, lj_cont_hook);
1114 setframe_pc(top+1, cframe_pc(cf)-1); 1120 if (LJ_FR2) top++;
1115 setframe_gc(top+2, obj2gco(L)); 1121 setframe_pc(top, cframe_pc(cf)-1);
1116 setframe_ftsz(top+2, (int)((char *)(top+3)-(char *)L->base)+FRAME_CONT); 1122 if (LJ_FR2) top++;
1117 L->top = L->base = top+3; 1123 setframe_gc(top, obj2gco(L), LJ_TTHREAD);
1124 setframe_ftsz(top, ((char *)(top+1)-(char *)L->base)+FRAME_CONT);
1125 L->top = L->base = top+1;
1118#if LJ_TARGET_X64 1126#if LJ_TARGET_X64
1119 lj_err_throw(L, LUA_YIELD); 1127 lj_err_throw(L, LUA_YIELD);
1120#else 1128#else
@@ -1131,7 +1139,9 @@ LUA_API int lua_yield(lua_State *L, int nresults)
1131LUA_API int lua_resume(lua_State *L, int nargs) 1139LUA_API int lua_resume(lua_State *L, int nargs)
1132{ 1140{
1133 if (L->cframe == NULL && L->status <= LUA_YIELD) 1141 if (L->cframe == NULL && L->status <= LUA_YIELD)
1134 return lj_vm_resume(L, L->top - nargs, 0, 0); 1142 return lj_vm_resume(L,
1143 L->status == 0 ? api_call_base(L, nargs) : L->top - nargs,
1144 0, 0);
1135 L->top = L->base; 1145 L->top = L->base;
1136 setstrV(L, L->top, lj_err_str(L, LJ_ERR_COSUSP)); 1146 setstrV(L, L->top, lj_err_str(L, LJ_ERR_COSUSP));
1137 incr_top(L); 1147 incr_top(L);
@@ -1161,7 +1171,7 @@ LUA_API int lua_gc(lua_State *L, int what, int data)
1161 res = (int)(g->gc.total & 0x3ff); 1171 res = (int)(g->gc.total & 0x3ff);
1162 break; 1172 break;
1163 case LUA_GCSTEP: { 1173 case LUA_GCSTEP: {
1164 MSize a = (MSize)data << 10; 1174 GCSize a = (GCSize)data << 10;
1165 g->gc.threshold = (a <= g->gc.total) ? (g->gc.total - a) : 0; 1175 g->gc.threshold = (a <= g->gc.total) ? (g->gc.total - a) : 0;
1166 while (g->gc.total >= g->gc.threshold) 1176 while (g->gc.total >= g->gc.threshold)
1167 if (lj_gc_step(L) > 0) { 1177 if (lj_gc_step(L) > 0) {
@@ -1178,6 +1188,9 @@ LUA_API int lua_gc(lua_State *L, int what, int data)
1178 res = (int)(g->gc.stepmul); 1188 res = (int)(g->gc.stepmul);
1179 g->gc.stepmul = (MSize)data; 1189 g->gc.stepmul = (MSize)data;
1180 break; 1190 break;
1191 case LUA_GCISRUNNING:
1192 res = (g->gc.threshold != LJ_MAX_MEM);
1193 break;
1181 default: 1194 default:
1182 res = -1; /* Invalid option. */ 1195 res = -1; /* Invalid option. */
1183 } 1196 }
diff --git a/src/lj_arch.h b/src/lj_arch.h
index e04c4ee9..9bf6f481 100644
--- a/src/lj_arch.h
+++ b/src/lj_arch.h
@@ -19,12 +19,16 @@
19#define LUAJIT_ARCH_x64 2 19#define LUAJIT_ARCH_x64 2
20#define LUAJIT_ARCH_ARM 3 20#define LUAJIT_ARCH_ARM 3
21#define LUAJIT_ARCH_arm 3 21#define LUAJIT_ARCH_arm 3
22#define LUAJIT_ARCH_PPC 4 22#define LUAJIT_ARCH_ARM64 4
23#define LUAJIT_ARCH_ppc 4 23#define LUAJIT_ARCH_arm64 4
24#define LUAJIT_ARCH_PPCSPE 5 24#define LUAJIT_ARCH_PPC 5
25#define LUAJIT_ARCH_ppcspe 5 25#define LUAJIT_ARCH_ppc 5
26#define LUAJIT_ARCH_MIPS 6 26#define LUAJIT_ARCH_MIPS 6
27#define LUAJIT_ARCH_mips 6 27#define LUAJIT_ARCH_mips 6
28#define LUAJIT_ARCH_MIPS32 6
29#define LUAJIT_ARCH_mips32 6
30#define LUAJIT_ARCH_MIPS64 7
31#define LUAJIT_ARCH_mips64 7
28 32
29/* Target OS. */ 33/* Target OS. */
30#define LUAJIT_OS_OTHER 0 34#define LUAJIT_OS_OTHER 0
@@ -43,14 +47,14 @@
43#define LUAJIT_TARGET LUAJIT_ARCH_X64 47#define LUAJIT_TARGET LUAJIT_ARCH_X64
44#elif defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM) 48#elif defined(__arm__) || defined(__arm) || defined(__ARM__) || defined(__ARM)
45#define LUAJIT_TARGET LUAJIT_ARCH_ARM 49#define LUAJIT_TARGET LUAJIT_ARCH_ARM
50#elif defined(__aarch64__)
51#define LUAJIT_TARGET LUAJIT_ARCH_ARM64
46#elif defined(__ppc__) || defined(__ppc) || defined(__PPC__) || defined(__PPC) || defined(__powerpc__) || defined(__powerpc) || defined(__POWERPC__) || defined(__POWERPC) || defined(_M_PPC) 52#elif defined(__ppc__) || defined(__ppc) || defined(__PPC__) || defined(__PPC) || defined(__powerpc__) || defined(__powerpc) || defined(__POWERPC__) || defined(__POWERPC) || defined(_M_PPC)
47#ifdef __NO_FPRS__
48#define LUAJIT_TARGET LUAJIT_ARCH_PPCSPE
49#else
50#define LUAJIT_TARGET LUAJIT_ARCH_PPC 53#define LUAJIT_TARGET LUAJIT_ARCH_PPC
51#endif 54#elif defined(__mips64__) || defined(__mips64) || defined(__MIPS64__) || defined(__MIPS64)
55#define LUAJIT_TARGET LUAJIT_ARCH_MIPS64
52#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(__MIPS) 56#elif defined(__mips__) || defined(__mips) || defined(__MIPS__) || defined(__MIPS)
53#define LUAJIT_TARGET LUAJIT_ARCH_MIPS 57#define LUAJIT_TARGET LUAJIT_ARCH_MIPS32
54#else 58#else
55#error "No support for this architecture (yet)" 59#error "No support for this architecture (yet)"
56#endif 60#endif
@@ -99,7 +103,7 @@
99#define LJ_TARGET_WINDOWS (LUAJIT_OS == LUAJIT_OS_WINDOWS) 103#define LJ_TARGET_WINDOWS (LUAJIT_OS == LUAJIT_OS_WINDOWS)
100#define LJ_TARGET_LINUX (LUAJIT_OS == LUAJIT_OS_LINUX) 104#define LJ_TARGET_LINUX (LUAJIT_OS == LUAJIT_OS_LINUX)
101#define LJ_TARGET_OSX (LUAJIT_OS == LUAJIT_OS_OSX) 105#define LJ_TARGET_OSX (LUAJIT_OS == LUAJIT_OS_OSX)
102#define LJ_TARGET_IOS (LJ_TARGET_OSX && LUAJIT_TARGET == LUAJIT_ARCH_ARM) 106#define LJ_TARGET_IOS (LJ_TARGET_OSX && (LUAJIT_TARGET == LUAJIT_ARCH_ARM || LUAJIT_TARGET == LUAJIT_ARCH_ARM64))
103#define LJ_TARGET_POSIX (LUAJIT_OS > LUAJIT_OS_WINDOWS) 107#define LJ_TARGET_POSIX (LUAJIT_OS > LUAJIT_OS_WINDOWS)
104#define LJ_TARGET_DLOPEN LJ_TARGET_POSIX 108#define LJ_TARGET_DLOPEN LJ_TARGET_POSIX
105 109
@@ -125,6 +129,12 @@
125#define LJ_TARGET_CONSOLE 1 129#define LJ_TARGET_CONSOLE 1
126#endif 130#endif
127 131
132#ifdef _DURANGO
133#define LJ_TARGET_XBOXONE 1
134#define LJ_TARGET_CONSOLE 1
135#define LJ_TARGET_GC64 1
136#endif
137
128#define LJ_NUMMODE_SINGLE 0 /* Single-number mode only. */ 138#define LJ_NUMMODE_SINGLE 0 /* Single-number mode only. */
129#define LJ_NUMMODE_SINGLE_DUAL 1 /* Default to single-number mode. */ 139#define LJ_NUMMODE_SINGLE_DUAL 1 /* Default to single-number mode. */
130#define LJ_NUMMODE_DUAL 2 /* Dual-number mode only. */ 140#define LJ_NUMMODE_DUAL 2 /* Dual-number mode only. */
@@ -167,6 +177,9 @@
167#define LJ_TARGET_MASKROT 1 177#define LJ_TARGET_MASKROT 1
168#define LJ_TARGET_UNALIGNED 1 178#define LJ_TARGET_UNALIGNED 1
169#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL 179#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE_DUAL
180#ifdef LUAJIT_ENABLE_GC64
181#define LJ_TARGET_GC64 1
182#endif
170 183
171#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM 184#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM
172 185
@@ -200,15 +213,44 @@
200#define LJ_ARCH_VERSION 50 213#define LJ_ARCH_VERSION 50
201#endif 214#endif
202 215
216#elif LUAJIT_TARGET == LUAJIT_ARCH_ARM64
217
218#define LJ_ARCH_NAME "arm64"
219#define LJ_ARCH_BITS 64
220#define LJ_ARCH_ENDIAN LUAJIT_LE
221#define LJ_TARGET_ARM64 1
222#define LJ_TARGET_EHRETREG 0
223#define LJ_TARGET_JUMPRANGE 27 /* +-2^27 = +-128MB */
224#define LJ_TARGET_MASKSHIFT 1
225#define LJ_TARGET_MASKROT 1
226#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */
227#define LJ_TARGET_GC64 1
228#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL
229
230#define LJ_ARCH_VERSION 80
231
203#elif LUAJIT_TARGET == LUAJIT_ARCH_PPC 232#elif LUAJIT_TARGET == LUAJIT_ARCH_PPC
204 233
205#define LJ_ARCH_NAME "ppc" 234#ifndef LJ_ARCH_ENDIAN
235#if __BYTE_ORDER__ != __ORDER_BIG_ENDIAN__
236#define LJ_ARCH_ENDIAN LUAJIT_LE
237#else
238#define LJ_ARCH_ENDIAN LUAJIT_BE
239#endif
240#endif
241
206#if _LP64 242#if _LP64
207#define LJ_ARCH_BITS 64 243#define LJ_ARCH_BITS 64
244#if LJ_ARCH_ENDIAN == LUAJIT_LE
245#define LJ_ARCH_NAME "ppc64le"
246#else
247#define LJ_ARCH_NAME "ppc64"
248#endif
208#else 249#else
209#define LJ_ARCH_BITS 32 250#define LJ_ARCH_BITS 32
251#define LJ_ARCH_NAME "ppc"
210#endif 252#endif
211#define LJ_ARCH_ENDIAN LUAJIT_BE 253
212#define LJ_TARGET_PPC 1 254#define LJ_TARGET_PPC 1
213#define LJ_TARGET_EHRETREG 3 255#define LJ_TARGET_EHRETREG 3
214#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */ 256#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */
@@ -217,6 +259,15 @@
217#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */ 259#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */
218#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL_SINGLE 260#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL_SINGLE
219 261
262#if LJ_TARGET_CONSOLE
263#define LJ_ARCH_PPC32ON64 1
264#define LJ_ARCH_NOFFI 1
265#elif LJ_ARCH_BITS == 64
266#define LJ_ARCH_PPC64 1
267#define LJ_TARGET_GC64 1
268#define LJ_ARCH_NOJIT 1 /* NYI */
269#endif
270
220#if _ARCH_PWR7 271#if _ARCH_PWR7
221#define LJ_ARCH_VERSION 70 272#define LJ_ARCH_VERSION 70
222#elif _ARCH_PWR6 273#elif _ARCH_PWR6
@@ -230,10 +281,6 @@
230#else 281#else
231#define LJ_ARCH_VERSION 0 282#define LJ_ARCH_VERSION 0
232#endif 283#endif
233#if __PPC64__ || __powerpc64__ || LJ_TARGET_CONSOLE
234#define LJ_ARCH_PPC64 1
235#define LJ_ARCH_NOFFI 1
236#endif
237#if _ARCH_PPCSQ 284#if _ARCH_PPCSQ
238#define LJ_ARCH_SQRT 1 285#define LJ_ARCH_SQRT 1
239#endif 286#endif
@@ -247,44 +294,60 @@
247#define LJ_ARCH_XENON 1 294#define LJ_ARCH_XENON 1
248#endif 295#endif
249 296
250#elif LUAJIT_TARGET == LUAJIT_ARCH_PPCSPE 297#elif LUAJIT_TARGET == LUAJIT_ARCH_MIPS32 || LUAJIT_TARGET == LUAJIT_ARCH_MIPS64
251
252#define LJ_ARCH_NAME "ppcspe"
253#define LJ_ARCH_BITS 32
254#define LJ_ARCH_ENDIAN LUAJIT_BE
255#ifndef LJ_ABI_SOFTFP
256#define LJ_ABI_SOFTFP 1
257#endif
258#define LJ_ABI_EABI 1
259#define LJ_TARGET_PPCSPE 1
260#define LJ_TARGET_EHRETREG 3
261#define LJ_TARGET_JUMPRANGE 25 /* +-2^25 = +-32MB */
262#define LJ_TARGET_MASKSHIFT 0
263#define LJ_TARGET_MASKROT 1
264#define LJ_TARGET_UNIFYROT 1 /* Want only IR_BROL. */
265#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE
266#define LJ_ARCH_NOFFI 1 /* NYI: comparisons, calls. */
267#define LJ_ARCH_NOJIT 1
268
269#elif LUAJIT_TARGET == LUAJIT_ARCH_MIPS
270 298
271#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) 299#if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL)
300#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32
272#define LJ_ARCH_NAME "mipsel" 301#define LJ_ARCH_NAME "mipsel"
302#else
303#define LJ_ARCH_NAME "mips64el"
304#endif
273#define LJ_ARCH_ENDIAN LUAJIT_LE 305#define LJ_ARCH_ENDIAN LUAJIT_LE
274#else 306#else
307#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32
275#define LJ_ARCH_NAME "mips" 308#define LJ_ARCH_NAME "mips"
309#else
310#define LJ_ARCH_NAME "mips64"
311#endif
276#define LJ_ARCH_ENDIAN LUAJIT_BE 312#define LJ_ARCH_ENDIAN LUAJIT_BE
277#endif 313#endif
314
315#if !defined(LJ_ARCH_HASFPU)
316#ifdef __mips_soft_float
317#define LJ_ARCH_HASFPU 0
318#else
319#define LJ_ARCH_HASFPU 1
320#endif
321#endif
322
323#if !defined(LJ_ABI_SOFTFP)
324#ifdef __mips_soft_float
325#define LJ_ABI_SOFTFP 1
326#else
327#define LJ_ABI_SOFTFP 0
328#endif
329#endif
330
331#if LUAJIT_TARGET == LUAJIT_ARCH_MIPS32
278#define LJ_ARCH_BITS 32 332#define LJ_ARCH_BITS 32
333#define LJ_TARGET_MIPS32 1
334#else
335#if LJ_ABI_SOFTFP || !LJ_ARCH_HASFPU
336#define LJ_ARCH_NOJIT 1 /* NYI */
337#endif
338#define LJ_ARCH_BITS 64
339#define LJ_TARGET_MIPS64 1
340#define LJ_TARGET_GC64 1
341#endif
279#define LJ_TARGET_MIPS 1 342#define LJ_TARGET_MIPS 1
280#define LJ_TARGET_EHRETREG 4 343#define LJ_TARGET_EHRETREG 4
281#define LJ_TARGET_JUMPRANGE 27 /* 2*2^27 = 256MB-aligned region */ 344#define LJ_TARGET_JUMPRANGE 27 /* 2*2^27 = 256MB-aligned region */
282#define LJ_TARGET_MASKSHIFT 1 345#define LJ_TARGET_MASKSHIFT 1
283#define LJ_TARGET_MASKROT 1 346#define LJ_TARGET_MASKROT 1
284#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */ 347#define LJ_TARGET_UNIFYROT 2 /* Want only IR_BROR. */
285#define LJ_ARCH_NUMMODE LJ_NUMMODE_SINGLE 348#define LJ_ARCH_NUMMODE LJ_NUMMODE_DUAL
286 349
287#if _MIPS_ARCH_MIPS32R2 350#if _MIPS_ARCH_MIPS32R2 || _MIPS_ARCH_MIPS64R2
288#define LJ_ARCH_VERSION 20 351#define LJ_ARCH_VERSION 20
289#else 352#else
290#define LJ_ARCH_VERSION 10 353#define LJ_ARCH_VERSION 10
@@ -312,6 +375,16 @@
312#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 2) 375#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 2)
313#error "Need at least GCC 4.2 or newer" 376#error "Need at least GCC 4.2 or newer"
314#endif 377#endif
378#elif LJ_TARGET_ARM64
379#if __clang__
380#if (__clang_major__ < 3) || ((__clang_major__ == 3) && __clang_minor__ < 5)
381#error "Need at least Clang 3.5 or newer"
382#endif
383#else
384#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 8)
385#error "Need at least GCC 4.8 or newer"
386#endif
387#endif
315#elif !LJ_TARGET_PS3 388#elif !LJ_TARGET_PS3
316#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 3) 389#if (__GNUC__ < 4) || ((__GNUC__ == 4) && __GNUC_MINOR__ < 3)
317#error "Need at least GCC 4.3 or newer" 390#error "Need at least GCC 4.3 or newer"
@@ -335,22 +408,33 @@
335#if !(__ARM_EABI__ || LJ_TARGET_IOS) 408#if !(__ARM_EABI__ || LJ_TARGET_IOS)
336#error "Only ARM EABI or iOS 3.0+ ABI is supported" 409#error "Only ARM EABI or iOS 3.0+ ABI is supported"
337#endif 410#endif
338#elif LJ_TARGET_PPC || LJ_TARGET_PPCSPE 411#elif LJ_TARGET_ARM64
412#if defined(__AARCH64EB__)
413#error "No support for big-endian ARM64"
414#endif
415#if defined(_ILP32)
416#error "No support for ILP32 model on ARM64"
417#endif
418#elif LJ_TARGET_PPC
339#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE) 419#if defined(_SOFT_FLOAT) || defined(_SOFT_DOUBLE)
340#error "No support for PowerPC CPUs without double-precision FPU" 420#error "No support for PowerPC CPUs without double-precision FPU"
341#endif 421#endif
342#if defined(_LITTLE_ENDIAN) 422#if !LJ_ARCH_PPC64 && LJ_ARCH_ENDIAN == LUAJIT_LE
343#error "No support for little-endian PowerPC" 423#error "No support for little-endian PPC32"
344#endif 424#endif
345#if defined(_LP64) 425#if LJ_ARCH_PPC64
346#error "No support for PowerPC 64 bit mode" 426#error "No support for PowerPC 64 bit mode (yet)"
347#endif 427#endif
348#elif LJ_TARGET_MIPS 428#ifdef __NO_FPRS__
349#if defined(__mips_soft_float) 429#error "No support for PPC/e500 anymore (use LuaJIT 2.0)"
350#error "No support for MIPS CPUs without FPU" 430#endif
431#elif LJ_TARGET_MIPS32
432#if !((defined(_MIPS_SIM_ABI32) && _MIPS_SIM == _MIPS_SIM_ABI32) || (defined(_ABIO32) && _MIPS_SIM == _ABIO32))
433#error "Only o32 ABI supported for MIPS32"
351#endif 434#endif
352#if defined(_LP64) 435#elif LJ_TARGET_MIPS64
353#error "No support for MIPS64" 436#if !((defined(_MIPS_SIM_ABI64) && _MIPS_SIM == _MIPS_SIM_ABI64) || (defined(_ABI64) && _MIPS_SIM == _ABI64))
437#error "Only n64 ABI supported for MIPS64"
354#endif 438#endif
355#endif 439#endif
356#endif 440#endif
@@ -376,6 +460,20 @@
376#endif 460#endif
377#endif 461#endif
378 462
463/* 64 bit GC references. */
464#if LJ_TARGET_GC64
465#define LJ_GC64 1
466#else
467#define LJ_GC64 0
468#endif
469
470/* 2-slot frame info. */
471#if LJ_GC64
472#define LJ_FR2 1
473#else
474#define LJ_FR2 0
475#endif
476
379/* Disable or enable the JIT compiler. */ 477/* Disable or enable the JIT compiler. */
380#if defined(LUAJIT_DISABLE_JIT) || defined(LJ_ARCH_NOJIT) || defined(LJ_OS_NOJIT) 478#if defined(LUAJIT_DISABLE_JIT) || defined(LJ_ARCH_NOJIT) || defined(LJ_OS_NOJIT)
381#define LJ_HASJIT 0 479#define LJ_HASJIT 0
@@ -390,6 +488,21 @@
390#define LJ_HASFFI 1 488#define LJ_HASFFI 1
391#endif 489#endif
392 490
491#if defined(LUAJIT_DISABLE_PROFILE)
492#define LJ_HASPROFILE 0
493#elif LJ_TARGET_POSIX
494#define LJ_HASPROFILE 1
495#define LJ_PROFILE_SIGPROF 1
496#elif LJ_TARGET_PS3
497#define LJ_HASPROFILE 1
498#define LJ_PROFILE_PTHREAD 1
499#elif LJ_TARGET_WINDOWS || LJ_TARGET_XBOX360
500#define LJ_HASPROFILE 1
501#define LJ_PROFILE_WTHREAD 1
502#else
503#define LJ_HASPROFILE 0
504#endif
505
393#ifndef LJ_ARCH_HASFPU 506#ifndef LJ_ARCH_HASFPU
394#define LJ_ARCH_HASFPU 1 507#define LJ_ARCH_HASFPU 1
395#endif 508#endif
@@ -422,11 +535,11 @@
422#define LJ_TARGET_UNALIGNED 0 535#define LJ_TARGET_UNALIGNED 0
423#endif 536#endif
424 537
425/* Various workarounds for embedded operating systems. */ 538/* Various workarounds for embedded operating systems or weak C runtimes. */
426#if (defined(__ANDROID__) && !defined(LJ_TARGET_X86ORX64)) || defined(__symbian__) || LJ_TARGET_XBOX360 539#if defined(__ANDROID__) || defined(__symbian__) || LJ_TARGET_XBOX360 || LJ_TARGET_WINDOWS
427#define LUAJIT_NO_LOG2 540#define LUAJIT_NO_LOG2
428#endif 541#endif
429#if defined(__symbian__) 542#if defined(__symbian__) || LJ_TARGET_WINDOWS
430#define LUAJIT_NO_EXP2 543#define LUAJIT_NO_EXP2
431#endif 544#endif
432#if LJ_TARGET_CONSOLE || (LJ_TARGET_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) 545#if LJ_TARGET_CONSOLE || (LJ_TARGET_IOS && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)
diff --git a/src/lj_asm.c b/src/lj_asm.c
index 02714d4e..7c09dd9f 100644
--- a/src/lj_asm.c
+++ b/src/lj_asm.c
@@ -91,7 +91,7 @@ typedef struct ASMState {
91 MCode *realign; /* Realign loop if not NULL. */ 91 MCode *realign; /* Realign loop if not NULL. */
92 92
93#ifdef RID_NUM_KREF 93#ifdef RID_NUM_KREF
94 int32_t krefk[RID_NUM_KREF]; 94 intptr_t krefk[RID_NUM_KREF];
95#endif 95#endif
96 IRRef1 phireg[RID_MAX]; /* PHI register references. */ 96 IRRef1 phireg[RID_MAX]; /* PHI register references. */
97 uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */ 97 uint16_t parentmap[LJ_MAX_JSLOTS]; /* Parent instruction to RegSP map. */
@@ -144,7 +144,7 @@ static LJ_AINLINE void checkmclim(ASMState *as)
144#define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref))) 144#define ra_krefreg(ref) ((Reg)(RID_MIN_KREF + (Reg)(ref)))
145#define ra_krefk(as, ref) (as->krefk[(ref)]) 145#define ra_krefk(as, ref) (as->krefk[(ref)])
146 146
147static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, int32_t k) 147static LJ_AINLINE void ra_setkref(ASMState *as, Reg r, intptr_t k)
148{ 148{
149 IRRef ref = (IRRef)(r - RID_MIN_KREF); 149 IRRef ref = (IRRef)(r - RID_MIN_KREF);
150 as->krefk[ref] = k; 150 as->krefk[ref] = k;
@@ -171,6 +171,8 @@ IRFLDEF(FLOFS)
171#include "lj_emit_x86.h" 171#include "lj_emit_x86.h"
172#elif LJ_TARGET_ARM 172#elif LJ_TARGET_ARM
173#include "lj_emit_arm.h" 173#include "lj_emit_arm.h"
174#elif LJ_TARGET_ARM64
175#include "lj_emit_arm64.h"
174#elif LJ_TARGET_PPC 176#elif LJ_TARGET_PPC
175#include "lj_emit_ppc.h" 177#include "lj_emit_ppc.h"
176#elif LJ_TARGET_MIPS 178#elif LJ_TARGET_MIPS
@@ -179,6 +181,12 @@ IRFLDEF(FLOFS)
179#error "Missing instruction emitter for target CPU" 181#error "Missing instruction emitter for target CPU"
180#endif 182#endif
181 183
184/* Generic load/store of register from/to stack slot. */
185#define emit_spload(as, ir, r, ofs) \
186 emit_loadofs(as, ir, (r), RID_SP, (ofs))
187#define emit_spstore(as, ir, r, ofs) \
188 emit_storeofs(as, ir, (r), RID_SP, (ofs))
189
182/* -- Register allocator debugging ---------------------------------------- */ 190/* -- Register allocator debugging ---------------------------------------- */
183 191
184/* #define LUAJIT_DEBUG_RA */ 192/* #define LUAJIT_DEBUG_RA */
@@ -316,7 +324,11 @@ static Reg ra_rematk(ASMState *as, IRRef ref)
316 lua_assert(!rset_test(as->freeset, r)); 324 lua_assert(!rset_test(as->freeset, r));
317 ra_free(as, r); 325 ra_free(as, r);
318 ra_modified(as, r); 326 ra_modified(as, r);
327#if LJ_64
328 emit_loadu64(as, r, ra_krefk(as, ref));
329#else
319 emit_loadi(as, r, ra_krefk(as, ref)); 330 emit_loadi(as, r, ra_krefk(as, ref));
331#endif
320 return r; 332 return r;
321 } 333 }
322 ir = IR(ref); 334 ir = IR(ref);
@@ -328,7 +340,7 @@ static Reg ra_rematk(ASMState *as, IRRef ref)
328 RA_DBGX((as, "remat $i $r", ir, r)); 340 RA_DBGX((as, "remat $i $r", ir, r));
329#if !LJ_SOFTFP 341#if !LJ_SOFTFP
330 if (ir->o == IR_KNUM) { 342 if (ir->o == IR_KNUM) {
331 emit_loadn(as, r, ir_knum(ir)); 343 emit_loadk64(as, r, ir);
332 } else 344 } else
333#endif 345#endif
334 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) { 346 if (emit_canremat(REF_BASE) && ir->o == IR_BASE) {
@@ -336,10 +348,16 @@ static Reg ra_rematk(ASMState *as, IRRef ref)
336 emit_getgl(as, r, jit_base); 348 emit_getgl(as, r, jit_base);
337 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) { 349 } else if (emit_canremat(ASMREF_L) && ir->o == IR_KPRI) {
338 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */ 350 lua_assert(irt_isnil(ir->t)); /* REF_NIL stores ASMREF_L register. */
339 emit_getgl(as, r, jit_L); 351 emit_getgl(as, r, cur_L);
340#if LJ_64 352#if LJ_64
341 } else if (ir->o == IR_KINT64) { 353 } else if (ir->o == IR_KINT64) {
342 emit_loadu64(as, r, ir_kint64(ir)->u64); 354 emit_loadu64(as, r, ir_kint64(ir)->u64);
355#if LJ_GC64
356 } else if (ir->o == IR_KGC) {
357 emit_loadu64(as, r, (uintptr_t)ir_kgc(ir));
358 } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
359 emit_loadu64(as, r, (uintptr_t)ir_kptr(ir));
360#endif
343#endif 361#endif
344 } else { 362 } else {
345 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC || 363 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
@@ -512,7 +530,7 @@ static void ra_evictk(ASMState *as)
512 530
513#ifdef RID_NUM_KREF 531#ifdef RID_NUM_KREF
514/* Allocate a register for a constant. */ 532/* Allocate a register for a constant. */
515static Reg ra_allock(ASMState *as, int32_t k, RegSet allow) 533static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow)
516{ 534{
517 /* First try to find a register which already holds the same constant. */ 535 /* First try to find a register which already holds the same constant. */
518 RegSet pick, work = ~as->freeset & RSET_GPR; 536 RegSet pick, work = ~as->freeset & RSET_GPR;
@@ -521,9 +539,31 @@ static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
521 IRRef ref; 539 IRRef ref;
522 r = rset_pickbot(work); 540 r = rset_pickbot(work);
523 ref = regcost_ref(as->cost[r]); 541 ref = regcost_ref(as->cost[r]);
542#if LJ_64
543 if (ref < ASMREF_L) {
544 if (ra_iskref(ref)) {
545 if (k == ra_krefk(as, ref))
546 return r;
547 } else {
548 IRIns *ir = IR(ref);
549 if ((ir->o == IR_KINT64 && k == (int64_t)ir_kint64(ir)->u64) ||
550#if LJ_GC64
551 (ir->o == IR_KINT && k == ir->i) ||
552 (ir->o == IR_KGC && k == (intptr_t)ir_kgc(ir)) ||
553 ((ir->o == IR_KPTR || ir->o == IR_KKPTR) &&
554 k == (intptr_t)ir_kptr(ir))
555#else
556 (ir->o != IR_KINT64 && k == ir->i)
557#endif
558 )
559 return r;
560 }
561 }
562#else
524 if (ref < ASMREF_L && 563 if (ref < ASMREF_L &&
525 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i)) 564 k == (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i))
526 return r; 565 return r;
566#endif
527 rset_clear(work, r); 567 rset_clear(work, r);
528 } 568 }
529 pick = as->freeset & allow; 569 pick = as->freeset & allow;
@@ -543,7 +583,7 @@ static Reg ra_allock(ASMState *as, int32_t k, RegSet allow)
543} 583}
544 584
545/* Allocate a specific register for a constant. */ 585/* Allocate a specific register for a constant. */
546static void ra_allockreg(ASMState *as, int32_t k, Reg r) 586static void ra_allockreg(ASMState *as, intptr_t k, Reg r)
547{ 587{
548 Reg kr = ra_allock(as, k, RID2RSET(r)); 588 Reg kr = ra_allock(as, k, RID2RSET(r));
549 if (kr != r) { 589 if (kr != r) {
@@ -613,10 +653,20 @@ static Reg ra_alloc1(ASMState *as, IRRef ref, RegSet allow)
613 return r; 653 return r;
614} 654}
615 655
656/* Add a register rename to the IR. */
657static void ra_addrename(ASMState *as, Reg down, IRRef ref, SnapNo snapno)
658{
659 IRRef ren;
660 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, snapno);
661 ren = tref_ref(lj_ir_emit(as->J));
662 as->J->cur.ir[ren].r = (uint8_t)down;
663 as->J->cur.ir[ren].s = SPS_NONE;
664}
665
616/* Rename register allocation and emit move. */ 666/* Rename register allocation and emit move. */
617static void ra_rename(ASMState *as, Reg down, Reg up) 667static void ra_rename(ASMState *as, Reg down, Reg up)
618{ 668{
619 IRRef ren, ref = regcost_ref(as->cost[up] = as->cost[down]); 669 IRRef ref = regcost_ref(as->cost[up] = as->cost[down]);
620 IRIns *ir = IR(ref); 670 IRIns *ir = IR(ref);
621 ir->r = (uint8_t)up; 671 ir->r = (uint8_t)up;
622 as->cost[down] = 0; 672 as->cost[down] = 0;
@@ -629,11 +679,7 @@ static void ra_rename(ASMState *as, Reg down, Reg up)
629 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up)); 679 RA_DBGX((as, "rename $f $r $r", regcost_ref(as->cost[up]), down, up));
630 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */ 680 emit_movrr(as, ir, down, up); /* Backwards codegen needs inverse move. */
631 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */ 681 if (!ra_hasspill(IR(ref)->s)) { /* Add the rename to the IR. */
632 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), ref, as->snapno); 682 ra_addrename(as, down, ref, as->snapno);
633 ren = tref_ref(lj_ir_emit(as->J));
634 as->ir = as->T->ir; /* The IR may have been reallocated. */
635 IR(ren)->r = (uint8_t)down;
636 IR(ren)->s = SPS_NONE;
637 } 683 }
638} 684}
639 685
@@ -683,18 +729,22 @@ static void ra_left(ASMState *as, Reg dest, IRRef lref)
683 if (ra_noreg(left)) { 729 if (ra_noreg(left)) {
684 if (irref_isk(lref)) { 730 if (irref_isk(lref)) {
685 if (ir->o == IR_KNUM) { 731 if (ir->o == IR_KNUM) {
686 cTValue *tv = ir_knum(ir);
687 /* FP remat needs a load except for +0. Still better than eviction. */ 732 /* FP remat needs a load except for +0. Still better than eviction. */
688 if (tvispzero(tv) || !(as->freeset & RSET_FPR)) { 733 if (tvispzero(ir_knum(ir)) || !(as->freeset & RSET_FPR)) {
689 emit_loadn(as, dest, tv); 734 emit_loadk64(as, dest, ir);
690 return; 735 return;
691 } 736 }
692#if LJ_64 737#if LJ_64
693 } else if (ir->o == IR_KINT64) { 738 } else if (ir->o == IR_KINT64) {
694 emit_loadu64(as, dest, ir_kint64(ir)->u64); 739 emit_loadk64(as, dest, ir);
740 return;
741#if LJ_GC64
742 } else if (ir->o == IR_KGC || ir->o == IR_KPTR || ir->o == IR_KKPTR) {
743 emit_loadk64(as, dest, ir);
695 return; 744 return;
696#endif 745#endif
697 } else { 746#endif
747 } else if (ir->o != IR_KPRI) {
698 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC || 748 lua_assert(ir->o == IR_KINT || ir->o == IR_KGC ||
699 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL); 749 ir->o == IR_KPTR || ir->o == IR_KKPTR || ir->o == IR_KNULL);
700 emit_loadi(as, dest, ir->i); 750 emit_loadi(as, dest, ir->i);
@@ -935,7 +985,7 @@ static void asm_snap_prep(ASMState *as)
935 } else { 985 } else {
936 /* Process any renames above the highwater mark. */ 986 /* Process any renames above the highwater mark. */
937 for (; as->snaprename < as->T->nins; as->snaprename++) { 987 for (; as->snaprename < as->T->nins; as->snaprename++) {
938 IRIns *ir = IR(as->snaprename); 988 IRIns *ir = &as->T->ir[as->snaprename];
939 if (asm_snap_checkrename(as, ir->op1)) 989 if (asm_snap_checkrename(as, ir->op1))
940 ir->op2 = REF_BIAS-1; /* Kill rename. */ 990 ir->op2 = REF_BIAS-1; /* Kill rename. */
941 } 991 }
@@ -944,44 +994,6 @@ static void asm_snap_prep(ASMState *as)
944 994
945/* -- Miscellaneous helpers ----------------------------------------------- */ 995/* -- Miscellaneous helpers ----------------------------------------------- */
946 996
947/* Collect arguments from CALL* and CARG instructions. */
948static void asm_collectargs(ASMState *as, IRIns *ir,
949 const CCallInfo *ci, IRRef *args)
950{
951 uint32_t n = CCI_NARGS(ci);
952 lua_assert(n <= CCI_NARGS_MAX*2); /* Account for split args. */
953 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
954 while (n-- > 1) {
955 ir = IR(ir->op1);
956 lua_assert(ir->o == IR_CARG);
957 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
958 }
959 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
960 lua_assert(IR(ir->op1)->o != IR_CARG);
961}
962
963/* Reconstruct CCallInfo flags for CALLX*. */
964static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
965{
966 uint32_t nargs = 0;
967 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
968 IRIns *ira = IR(ir->op1);
969 nargs++;
970 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
971 }
972#if LJ_HASFFI
973 if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
974 CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
975 CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
976 nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
977#if LJ_TARGET_X86
978 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
979#endif
980 }
981#endif
982 return (nargs | (ir->t.irt << CCI_OTSHIFT));
983}
984
985/* Calculate stack adjustment. */ 997/* Calculate stack adjustment. */
986static int32_t asm_stack_adjust(ASMState *as) 998static int32_t asm_stack_adjust(ASMState *as)
987{ 999{
@@ -1066,6 +1078,259 @@ static void asm_gcstep(ASMState *as, IRIns *ir)
1066 as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */ 1078 as->gcsteps = 0x80000000; /* Prevent implicit GC check further up. */
1067} 1079}
1068 1080
1081/* -- Buffer operations --------------------------------------------------- */
1082
1083static void asm_tvptr(ASMState *as, Reg dest, IRRef ref);
1084
1085static void asm_bufhdr(ASMState *as, IRIns *ir)
1086{
1087 Reg sb = ra_dest(as, ir, RSET_GPR);
1088 if ((ir->op2 & IRBUFHDR_APPEND)) {
1089 /* Rematerialize const buffer pointer instead of likely spill. */
1090 IRIns *irp = IR(ir->op1);
1091 if (!(ra_hasreg(irp->r) || irp == ir-1 ||
1092 (irp == ir-2 && !ra_used(ir-1)))) {
1093 while (!(irp->o == IR_BUFHDR && !(irp->op2 & IRBUFHDR_APPEND)))
1094 irp = IR(irp->op1);
1095 if (irref_isk(irp->op1)) {
1096 ra_weak(as, ra_allocref(as, ir->op1, RSET_GPR));
1097 ir = irp;
1098 }
1099 }
1100 } else {
1101 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, sb));
1102 /* Passing ir isn't strictly correct, but it's an IRT_PGC, too. */
1103 emit_storeofs(as, ir, tmp, sb, offsetof(SBuf, p));
1104 emit_loadofs(as, ir, tmp, sb, offsetof(SBuf, b));
1105 }
1106#if LJ_TARGET_X86ORX64
1107 ra_left(as, sb, ir->op1);
1108#else
1109 ra_leftov(as, sb, ir->op1);
1110#endif
1111}
1112
1113static void asm_bufput(ASMState *as, IRIns *ir)
1114{
1115 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_putstr];
1116 IRRef args[3];
1117 IRIns *irs;
1118 int kchar = -1;
1119 args[0] = ir->op1; /* SBuf * */
1120 args[1] = ir->op2; /* GCstr * */
1121 irs = IR(ir->op2);
1122 lua_assert(irt_isstr(irs->t));
1123 if (irs->o == IR_KGC) {
1124 GCstr *s = ir_kstr(irs);
1125 if (s->len == 1) { /* Optimize put of single-char string constant. */
1126 kchar = strdata(s)[0];
1127 args[1] = ASMREF_TMP1; /* int, truncated to char */
1128 ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
1129 }
1130 } else if (mayfuse(as, ir->op2) && ra_noreg(irs->r)) {
1131 if (irs->o == IR_TOSTR) { /* Fuse number to string conversions. */
1132 if (irs->op2 == IRTOSTR_NUM) {
1133 args[1] = ASMREF_TMP1; /* TValue * */
1134 ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putnum];
1135 } else {
1136 lua_assert(irt_isinteger(IR(irs->op1)->t));
1137 args[1] = irs->op1; /* int */
1138 if (irs->op2 == IRTOSTR_INT)
1139 ci = &lj_ir_callinfo[IRCALL_lj_strfmt_putint];
1140 else
1141 ci = &lj_ir_callinfo[IRCALL_lj_buf_putchar];
1142 }
1143 } else if (irs->o == IR_SNEW) { /* Fuse string allocation. */
1144 args[1] = irs->op1; /* const void * */
1145 args[2] = irs->op2; /* MSize */
1146 ci = &lj_ir_callinfo[IRCALL_lj_buf_putmem];
1147 }
1148 }
1149 asm_setupresult(as, ir, ci); /* SBuf * */
1150 asm_gencall(as, ci, args);
1151 if (args[1] == ASMREF_TMP1) {
1152 Reg tmp = ra_releasetmp(as, ASMREF_TMP1);
1153 if (kchar == -1)
1154 asm_tvptr(as, tmp, irs->op1);
1155 else
1156 ra_allockreg(as, kchar, tmp);
1157 }
1158}
1159
1160static void asm_bufstr(ASMState *as, IRIns *ir)
1161{
1162 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_buf_tostr];
1163 IRRef args[1];
1164 args[0] = ir->op1; /* SBuf *sb */
1165 as->gcsteps++;
1166 asm_setupresult(as, ir, ci); /* GCstr * */
1167 asm_gencall(as, ci, args);
1168}
1169
1170/* -- Type conversions ---------------------------------------------------- */
1171
1172static void asm_tostr(ASMState *as, IRIns *ir)
1173{
1174 const CCallInfo *ci;
1175 IRRef args[2];
1176 args[0] = ASMREF_L;
1177 as->gcsteps++;
1178 if (ir->op2 == IRTOSTR_NUM) {
1179 args[1] = ASMREF_TMP1; /* cTValue * */
1180 ci = &lj_ir_callinfo[IRCALL_lj_strfmt_num];
1181 } else {
1182 args[1] = ir->op1; /* int32_t k */
1183 if (ir->op2 == IRTOSTR_INT)
1184 ci = &lj_ir_callinfo[IRCALL_lj_strfmt_int];
1185 else
1186 ci = &lj_ir_callinfo[IRCALL_lj_strfmt_char];
1187 }
1188 asm_setupresult(as, ir, ci); /* GCstr * */
1189 asm_gencall(as, ci, args);
1190 if (ir->op2 == IRTOSTR_NUM)
1191 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1);
1192}
1193
1194#if LJ_32 && LJ_HASFFI && !LJ_SOFTFP && !LJ_TARGET_X86
1195static void asm_conv64(ASMState *as, IRIns *ir)
1196{
1197 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
1198 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
1199 IRCallID id;
1200 IRRef args[2];
1201 lua_assert((ir-1)->o == IR_CONV && ir->o == IR_HIOP);
1202 args[LJ_BE] = (ir-1)->op1;
1203 args[LJ_LE] = ir->op1;
1204 if (st == IRT_NUM || st == IRT_FLOAT) {
1205 id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
1206 ir--;
1207 } else {
1208 id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
1209 }
1210 {
1211#if LJ_TARGET_ARM && !LJ_ABI_SOFTFP
1212 CCallInfo cim = lj_ir_callinfo[id], *ci = &cim;
1213 cim.flags |= CCI_VARARG; /* These calls don't use the hard-float ABI! */
1214#else
1215 const CCallInfo *ci = &lj_ir_callinfo[id];
1216#endif
1217 asm_setupresult(as, ir, ci);
1218 asm_gencall(as, ci, args);
1219 }
1220}
1221#endif
1222
1223/* -- Memory references --------------------------------------------------- */
1224
1225static void asm_newref(ASMState *as, IRIns *ir)
1226{
1227 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
1228 IRRef args[3];
1229 if (ir->r == RID_SINK)
1230 return;
1231 args[0] = ASMREF_L; /* lua_State *L */
1232 args[1] = ir->op1; /* GCtab *t */
1233 args[2] = ASMREF_TMP1; /* cTValue *key */
1234 asm_setupresult(as, ir, ci); /* TValue * */
1235 asm_gencall(as, ci, args);
1236 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2);
1237}
1238
1239static void asm_lref(ASMState *as, IRIns *ir)
1240{
1241 Reg r = ra_dest(as, ir, RSET_GPR);
1242#if LJ_TARGET_X86ORX64
1243 ra_left(as, r, ASMREF_L);
1244#else
1245 ra_leftov(as, r, ASMREF_L);
1246#endif
1247}
1248
1249/* -- Calls --------------------------------------------------------------- */
1250
1251/* Collect arguments from CALL* and CARG instructions. */
1252static void asm_collectargs(ASMState *as, IRIns *ir,
1253 const CCallInfo *ci, IRRef *args)
1254{
1255 uint32_t n = CCI_XNARGS(ci);
1256 lua_assert(n <= CCI_NARGS_MAX*2); /* Account for split args. */
1257 if ((ci->flags & CCI_L)) { *args++ = ASMREF_L; n--; }
1258 while (n-- > 1) {
1259 ir = IR(ir->op1);
1260 lua_assert(ir->o == IR_CARG);
1261 args[n] = ir->op2 == REF_NIL ? 0 : ir->op2;
1262 }
1263 args[0] = ir->op1 == REF_NIL ? 0 : ir->op1;
1264 lua_assert(IR(ir->op1)->o != IR_CARG);
1265}
1266
1267/* Reconstruct CCallInfo flags for CALLX*. */
1268static uint32_t asm_callx_flags(ASMState *as, IRIns *ir)
1269{
1270 uint32_t nargs = 0;
1271 if (ir->op1 != REF_NIL) { /* Count number of arguments first. */
1272 IRIns *ira = IR(ir->op1);
1273 nargs++;
1274 while (ira->o == IR_CARG) { nargs++; ira = IR(ira->op1); }
1275 }
1276#if LJ_HASFFI
1277 if (IR(ir->op2)->o == IR_CARG) { /* Copy calling convention info. */
1278 CTypeID id = (CTypeID)IR(IR(ir->op2)->op2)->i;
1279 CType *ct = ctype_get(ctype_ctsG(J2G(as->J)), id);
1280 nargs |= ((ct->info & CTF_VARARG) ? CCI_VARARG : 0);
1281#if LJ_TARGET_X86
1282 nargs |= (ctype_cconv(ct->info) << CCI_CC_SHIFT);
1283#endif
1284 }
1285#endif
1286 return (nargs | (ir->t.irt << CCI_OTSHIFT));
1287}
1288
1289static void asm_callid(ASMState *as, IRIns *ir, IRCallID id)
1290{
1291 const CCallInfo *ci = &lj_ir_callinfo[id];
1292 IRRef args[2];
1293 args[0] = ir->op1;
1294 args[1] = ir->op2;
1295 asm_setupresult(as, ir, ci);
1296 asm_gencall(as, ci, args);
1297}
1298
1299static void asm_call(ASMState *as, IRIns *ir)
1300{
1301 IRRef args[CCI_NARGS_MAX];
1302 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1303 asm_collectargs(as, ir, ci, args);
1304 asm_setupresult(as, ir, ci);
1305 asm_gencall(as, ci, args);
1306}
1307
1308#if !LJ_SOFTFP
1309static void asm_fppow(ASMState *as, IRIns *ir, IRRef lref, IRRef rref)
1310{
1311 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow];
1312 IRRef args[2];
1313 args[0] = lref;
1314 args[1] = rref;
1315 asm_setupresult(as, ir, ci);
1316 asm_gencall(as, ci, args);
1317}
1318
1319static int asm_fpjoin_pow(ASMState *as, IRIns *ir)
1320{
1321 IRIns *irp = IR(ir->op1);
1322 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) {
1323 IRIns *irpp = IR(irp->op1);
1324 if (irpp == ir-2 && irpp->o == IR_FPMATH &&
1325 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) {
1326 asm_fppow(as, ir, irpp->op1, irp->op2);
1327 return 1;
1328 }
1329 }
1330 return 0;
1331}
1332#endif
1333
1069/* -- PHI and loop handling ----------------------------------------------- */ 1334/* -- PHI and loop handling ----------------------------------------------- */
1070 1335
1071/* Break a PHI cycle by renaming to a free register (evict if needed). */ 1336/* Break a PHI cycle by renaming to a free register (evict if needed). */
@@ -1251,12 +1516,7 @@ static void asm_phi_fixup(ASMState *as)
1251 irt_clearmark(ir->t); 1516 irt_clearmark(ir->t);
1252 /* Left PHI gained a spill slot before the loop? */ 1517 /* Left PHI gained a spill slot before the loop? */
1253 if (ra_hasspill(ir->s)) { 1518 if (ra_hasspill(ir->s)) {
1254 IRRef ren; 1519 ra_addrename(as, r, lref, as->loopsnapno);
1255 lj_ir_set(as->J, IRT(IR_RENAME, IRT_NIL), lref, as->loopsnapno);
1256 ren = tref_ref(lj_ir_emit(as->J));
1257 as->ir = as->T->ir; /* The IR may have been reallocated. */
1258 IR(ren)->r = (uint8_t)r;
1259 IR(ren)->s = SPS_NONE;
1260 } 1520 }
1261 } 1521 }
1262 rset_clear(work, r); 1522 rset_clear(work, r);
@@ -1331,6 +1591,8 @@ static void asm_loop(ASMState *as)
1331#include "lj_asm_x86.h" 1591#include "lj_asm_x86.h"
1332#elif LJ_TARGET_ARM 1592#elif LJ_TARGET_ARM
1333#include "lj_asm_arm.h" 1593#include "lj_asm_arm.h"
1594#elif LJ_TARGET_ARM64
1595#include "lj_asm_arm64.h"
1334#elif LJ_TARGET_PPC 1596#elif LJ_TARGET_PPC
1335#include "lj_asm_ppc.h" 1597#include "lj_asm_ppc.h"
1336#elif LJ_TARGET_MIPS 1598#elif LJ_TARGET_MIPS
@@ -1339,6 +1601,136 @@ static void asm_loop(ASMState *as)
1339#error "Missing assembler for target CPU" 1601#error "Missing assembler for target CPU"
1340#endif 1602#endif
1341 1603
1604/* -- Instruction dispatch ------------------------------------------------ */
1605
1606/* Assemble a single instruction. */
1607static void asm_ir(ASMState *as, IRIns *ir)
1608{
1609 switch ((IROp)ir->o) {
1610 /* Miscellaneous ops. */
1611 case IR_LOOP: asm_loop(as); break;
1612 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
1613 case IR_USE:
1614 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
1615 case IR_PHI: asm_phi(as, ir); break;
1616 case IR_HIOP: asm_hiop(as, ir); break;
1617 case IR_GCSTEP: asm_gcstep(as, ir); break;
1618 case IR_PROF: asm_prof(as, ir); break;
1619
1620 /* Guarded assertions. */
1621 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
1622 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
1623 case IR_ABC:
1624 asm_comp(as, ir);
1625 break;
1626 case IR_EQ: case IR_NE:
1627 if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) {
1628 as->curins--;
1629 asm_href(as, ir-1, (IROp)ir->o);
1630 } else {
1631 asm_equal(as, ir);
1632 }
1633 break;
1634
1635 case IR_RETF: asm_retf(as, ir); break;
1636
1637 /* Bit ops. */
1638 case IR_BNOT: asm_bnot(as, ir); break;
1639 case IR_BSWAP: asm_bswap(as, ir); break;
1640 case IR_BAND: asm_band(as, ir); break;
1641 case IR_BOR: asm_bor(as, ir); break;
1642 case IR_BXOR: asm_bxor(as, ir); break;
1643 case IR_BSHL: asm_bshl(as, ir); break;
1644 case IR_BSHR: asm_bshr(as, ir); break;
1645 case IR_BSAR: asm_bsar(as, ir); break;
1646 case IR_BROL: asm_brol(as, ir); break;
1647 case IR_BROR: asm_bror(as, ir); break;
1648
1649 /* Arithmetic ops. */
1650 case IR_ADD: asm_add(as, ir); break;
1651 case IR_SUB: asm_sub(as, ir); break;
1652 case IR_MUL: asm_mul(as, ir); break;
1653 case IR_MOD: asm_mod(as, ir); break;
1654 case IR_NEG: asm_neg(as, ir); break;
1655#if LJ_SOFTFP
1656 case IR_DIV: case IR_POW: case IR_ABS:
1657 case IR_ATAN2: case IR_LDEXP: case IR_FPMATH: case IR_TOBIT:
1658 lua_assert(0); /* Unused for LJ_SOFTFP. */
1659 break;
1660#else
1661 case IR_DIV: asm_div(as, ir); break;
1662 case IR_POW: asm_pow(as, ir); break;
1663 case IR_ABS: asm_abs(as, ir); break;
1664 case IR_ATAN2: asm_atan2(as, ir); break;
1665 case IR_LDEXP: asm_ldexp(as, ir); break;
1666 case IR_FPMATH: asm_fpmath(as, ir); break;
1667 case IR_TOBIT: asm_tobit(as, ir); break;
1668#endif
1669 case IR_MIN: asm_min(as, ir); break;
1670 case IR_MAX: asm_max(as, ir); break;
1671
1672 /* Overflow-checking arithmetic ops. */
1673 case IR_ADDOV: asm_addov(as, ir); break;
1674 case IR_SUBOV: asm_subov(as, ir); break;
1675 case IR_MULOV: asm_mulov(as, ir); break;
1676
1677 /* Memory references. */
1678 case IR_AREF: asm_aref(as, ir); break;
1679 case IR_HREF: asm_href(as, ir, 0); break;
1680 case IR_HREFK: asm_hrefk(as, ir); break;
1681 case IR_NEWREF: asm_newref(as, ir); break;
1682 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
1683 case IR_FREF: asm_fref(as, ir); break;
1684 case IR_STRREF: asm_strref(as, ir); break;
1685 case IR_LREF: asm_lref(as, ir); break;
1686
1687 /* Loads and stores. */
1688 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1689 asm_ahuvload(as, ir);
1690 break;
1691 case IR_FLOAD: asm_fload(as, ir); break;
1692 case IR_XLOAD: asm_xload(as, ir); break;
1693 case IR_SLOAD: asm_sload(as, ir); break;
1694
1695 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
1696 case IR_FSTORE: asm_fstore(as, ir); break;
1697 case IR_XSTORE: asm_xstore(as, ir); break;
1698
1699 /* Allocations. */
1700 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
1701 case IR_TNEW: asm_tnew(as, ir); break;
1702 case IR_TDUP: asm_tdup(as, ir); break;
1703 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
1704
1705 /* Buffer operations. */
1706 case IR_BUFHDR: asm_bufhdr(as, ir); break;
1707 case IR_BUFPUT: asm_bufput(as, ir); break;
1708 case IR_BUFSTR: asm_bufstr(as, ir); break;
1709
1710 /* Write barriers. */
1711 case IR_TBAR: asm_tbar(as, ir); break;
1712 case IR_OBAR: asm_obar(as, ir); break;
1713
1714 /* Type conversions. */
1715 case IR_CONV: asm_conv(as, ir); break;
1716 case IR_TOSTR: asm_tostr(as, ir); break;
1717 case IR_STRTO: asm_strto(as, ir); break;
1718
1719 /* Calls. */
1720 case IR_CALLA:
1721 as->gcsteps++;
1722 /* fallthrough */
1723 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
1724 case IR_CALLXS: asm_callx(as, ir); break;
1725 case IR_CARG: break;
1726
1727 default:
1728 setintV(&as->J->errinfo, ir->o);
1729 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
1730 break;
1731 }
1732}
1733
1342/* -- Head of trace ------------------------------------------------------- */ 1734/* -- Head of trace ------------------------------------------------------- */
1343 1735
1344/* Head of a root trace. */ 1736/* Head of a root trace. */
@@ -1537,7 +1929,7 @@ static BCReg asm_baseslot(ASMState *as, SnapShot *snap, int *gotframe)
1537 SnapEntry sn = map[n-1]; 1929 SnapEntry sn = map[n-1];
1538 if ((sn & SNAP_FRAME)) { 1930 if ((sn & SNAP_FRAME)) {
1539 *gotframe = 1; 1931 *gotframe = 1;
1540 return snap_slot(sn); 1932 return snap_slot(sn) - LJ_FR2;
1541 } 1933 }
1542 } 1934 }
1543 return 0; 1935 return 0;
@@ -1557,19 +1949,23 @@ static void asm_tail_link(ASMState *as)
1557 1949
1558 if (as->T->link == 0) { 1950 if (as->T->link == 0) {
1559 /* Setup fixed registers for exit to interpreter. */ 1951 /* Setup fixed registers for exit to interpreter. */
1560 const BCIns *pc = snap_pc(as->T->snapmap[snap->mapofs + snap->nent]); 1952 const BCIns *pc = snap_pc(&as->T->snapmap[snap->mapofs + snap->nent]);
1561 int32_t mres; 1953 int32_t mres;
1562 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */ 1954 if (bc_op(*pc) == BC_JLOOP) { /* NYI: find a better way to do this. */
1563 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins; 1955 BCIns *retpc = &traceref(as->J, bc_d(*pc))->startins;
1564 if (bc_isret(bc_op(*retpc))) 1956 if (bc_isret(bc_op(*retpc)))
1565 pc = retpc; 1957 pc = retpc;
1566 } 1958 }
1959#if LJ_GC64
1960 emit_loadu64(as, RID_LPC, u64ptr(pc));
1961#else
1567 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH); 1962 ra_allockreg(as, i32ptr(J2GG(as->J)->dispatch), RID_DISPATCH);
1568 ra_allockreg(as, i32ptr(pc), RID_LPC); 1963 ra_allockreg(as, i32ptr(pc), RID_LPC);
1569 mres = (int32_t)(snap->nslots - baseslot); 1964#endif
1965 mres = (int32_t)(snap->nslots - baseslot - LJ_FR2);
1570 switch (bc_op(*pc)) { 1966 switch (bc_op(*pc)) {
1571 case BC_CALLM: case BC_CALLMT: 1967 case BC_CALLM: case BC_CALLMT:
1572 mres -= (int32_t)(1 + bc_a(*pc) + bc_c(*pc)); break; 1968 mres -= (int32_t)(1 + LJ_FR2 + bc_a(*pc) + bc_c(*pc)); break;
1573 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break; 1969 case BC_RETM: mres -= (int32_t)(bc_a(*pc) + bc_d(*pc)); break;
1574 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break; 1970 case BC_TSETM: mres -= (int32_t)bc_a(*pc); break;
1575 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break; 1971 default: if (bc_op(*pc) < BC_FUNCF) mres = 0; break;
@@ -1581,6 +1977,11 @@ static void asm_tail_link(ASMState *as)
1581 } 1977 }
1582 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot); 1978 emit_addptr(as, RID_BASE, 8*(int32_t)baseslot);
1583 1979
1980 if (as->J->ktrace) { /* Patch ktrace slot with the final GCtrace pointer. */
1981 setgcref(IR(as->J->ktrace)[LJ_GC64].gcr, obj2gco(as->J->curfinal));
1982 IR(as->J->ktrace)->o = IR_KGC;
1983 }
1984
1584 /* Sync the interpreter state with the on-trace state. */ 1985 /* Sync the interpreter state with the on-trace state. */
1585 asm_stack_restore(as, snap); 1986 asm_stack_restore(as, snap);
1586 1987
@@ -1606,17 +2007,22 @@ static void asm_setup_regsp(ASMState *as)
1606 ra_setup(as); 2007 ra_setup(as);
1607 2008
1608 /* Clear reg/sp for constants. */ 2009 /* Clear reg/sp for constants. */
1609 for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++) 2010 for (ir = IR(T->nk), lastir = IR(REF_BASE); ir < lastir; ir++) {
1610 ir->prev = REGSP_INIT; 2011 ir->prev = REGSP_INIT;
2012 if (irt_is64(ir->t) && ir->o != IR_KNULL) {
2013#if LJ_GC64
2014 ir->i = 0; /* Will become non-zero only for RIP-relative addresses. */
2015#else
2016 /* Make life easier for backends by putting address of constant in i. */
2017 ir->i = (int32_t)(intptr_t)(ir+1);
2018#endif
2019 ir++;
2020 }
2021 }
1611 2022
1612 /* REF_BASE is used for implicit references to the BASE register. */ 2023 /* REF_BASE is used for implicit references to the BASE register. */
1613 lastir->prev = REGSP_HINT(RID_BASE); 2024 lastir->prev = REGSP_HINT(RID_BASE);
1614 2025
1615 ir = IR(nins-1);
1616 if (ir->o == IR_RENAME) {
1617 do { ir--; nins--; } while (ir->o == IR_RENAME);
1618 T->nins = nins; /* Remove any renames left over from ASM restart. */
1619 }
1620 as->snaprename = nins; 2026 as->snaprename = nins;
1621 as->snapref = nins; 2027 as->snapref = nins;
1622 as->snapno = T->nsnap; 2028 as->snapno = T->nsnap;
@@ -1677,7 +2083,7 @@ static void asm_setup_regsp(ASMState *as)
1677 as->modset |= RSET_SCRATCH; 2083 as->modset |= RSET_SCRATCH;
1678 continue; 2084 continue;
1679 } 2085 }
1680 case IR_CALLN: case IR_CALLL: case IR_CALLS: { 2086 case IR_CALLN: case IR_CALLA: case IR_CALLL: case IR_CALLS: {
1681 const CCallInfo *ci = &lj_ir_callinfo[ir->op2]; 2087 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
1682 ir->prev = asm_setup_call_slots(as, ir, ci); 2088 ir->prev = asm_setup_call_slots(as, ir, ci);
1683 if (inloop) 2089 if (inloop)
@@ -1722,10 +2128,20 @@ static void asm_setup_regsp(ASMState *as)
1722 /* fallthrough */ 2128 /* fallthrough */
1723#endif 2129#endif
1724 /* C calls evict all scratch regs and return results in RID_RET. */ 2130 /* C calls evict all scratch regs and return results in RID_RET. */
1725 case IR_SNEW: case IR_XSNEW: case IR_NEWREF: 2131 case IR_SNEW: case IR_XSNEW: case IR_NEWREF: case IR_BUFPUT:
1726 if (REGARG_NUMGPR < 3 && as->evenspill < 3) 2132 if (REGARG_NUMGPR < 3 && as->evenspill < 3)
1727 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */ 2133 as->evenspill = 3; /* lj_str_new and lj_tab_newkey need 3 args. */
1728 case IR_TNEW: case IR_TDUP: case IR_CNEW: case IR_CNEWI: case IR_TOSTR: 2134#if LJ_TARGET_X86 && LJ_HASFFI
2135 if (0) {
2136 case IR_CNEW:
2137 if (ir->op2 != REF_NIL && as->evenspill < 4)
2138 as->evenspill = 4; /* lj_cdata_newv needs 4 args. */
2139 }
2140#else
2141 case IR_CNEW:
2142#endif
2143 case IR_TNEW: case IR_TDUP: case IR_CNEWI: case IR_TOSTR:
2144 case IR_BUFSTR:
1729 ir->prev = REGSP_HINT(RID_RET); 2145 ir->prev = REGSP_HINT(RID_RET);
1730 if (inloop) 2146 if (inloop)
1731 as->modset = RSET_SCRATCH; 2147 as->modset = RSET_SCRATCH;
@@ -1734,21 +2150,26 @@ static void asm_setup_regsp(ASMState *as)
1734 if (inloop) 2150 if (inloop)
1735 as->modset = RSET_SCRATCH; 2151 as->modset = RSET_SCRATCH;
1736 break; 2152 break;
1737#if !LJ_TARGET_X86ORX64 && !LJ_SOFTFP 2153#if !LJ_SOFTFP
1738 case IR_ATAN2: case IR_LDEXP: 2154 case IR_ATAN2:
2155#if LJ_TARGET_X86
2156 if (as->evenspill < 4) /* Leave room to call atan2(). */
2157 as->evenspill = 4;
2158#endif
2159#if !LJ_TARGET_X86ORX64
2160 case IR_LDEXP:
2161#endif
1739#endif 2162#endif
1740 case IR_POW: 2163 case IR_POW:
1741 if (!LJ_SOFTFP && irt_isnum(ir->t)) { 2164 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1742#if LJ_TARGET_X86ORX64
1743 ir->prev = REGSP_HINT(RID_XMM0);
1744 if (inloop) 2165 if (inloop)
1745 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM1+1)|RID2RSET(RID_EAX); 2166 as->modset |= RSET_SCRATCH;
2167#if LJ_TARGET_X86
2168 break;
1746#else 2169#else
1747 ir->prev = REGSP_HINT(RID_FPRET); 2170 ir->prev = REGSP_HINT(RID_FPRET);
1748 if (inloop)
1749 as->modset |= RSET_SCRATCH;
1750#endif
1751 continue; 2171 continue;
2172#endif
1752 } 2173 }
1753 /* fallthrough for integer POW */ 2174 /* fallthrough for integer POW */
1754 case IR_DIV: case IR_MOD: 2175 case IR_DIV: case IR_MOD:
@@ -1761,31 +2182,33 @@ static void asm_setup_regsp(ASMState *as)
1761 break; 2182 break;
1762 case IR_FPMATH: 2183 case IR_FPMATH:
1763#if LJ_TARGET_X86ORX64 2184#if LJ_TARGET_X86ORX64
1764 if (ir->op2 == IRFPM_EXP2) { /* May be joined to lj_vm_pow_sse. */ 2185 if (ir->op2 <= IRFPM_TRUNC) {
1765 ir->prev = REGSP_HINT(RID_XMM0); 2186 if (!(as->flags & JIT_F_SSE4_1)) {
1766#if !LJ_64 2187 ir->prev = REGSP_HINT(RID_XMM0);
1767 if (as->evenspill < 4) /* Leave room for 16 byte scratch area. */ 2188 if (inloop)
2189 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
2190 continue;
2191 }
2192 break;
2193 } else if (ir->op2 == IRFPM_EXP2 && !LJ_64) {
2194 if (as->evenspill < 4) /* Leave room to call pow(). */
1768 as->evenspill = 4; 2195 as->evenspill = 4;
1769#endif
1770 if (inloop)
1771 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1772 continue;
1773 } else if (ir->op2 <= IRFPM_TRUNC && !(as->flags & JIT_F_SSE4_1)) {
1774 ir->prev = REGSP_HINT(RID_XMM0);
1775 if (inloop)
1776 as->modset |= RSET_RANGE(RID_XMM0, RID_XMM3+1)|RID2RSET(RID_EAX);
1777 continue;
1778 } 2196 }
2197#endif
2198 if (inloop)
2199 as->modset |= RSET_SCRATCH;
2200#if LJ_TARGET_X86
1779 break; 2201 break;
1780#else 2202#else
1781 ir->prev = REGSP_HINT(RID_FPRET); 2203 ir->prev = REGSP_HINT(RID_FPRET);
1782 if (inloop)
1783 as->modset |= RSET_SCRATCH;
1784 continue; 2204 continue;
1785#endif 2205#endif
1786#if LJ_TARGET_X86ORX64 2206#if LJ_TARGET_X86ORX64
1787 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */ 2207 /* Non-constant shift counts need to be in RID_ECX on x86/x64. */
1788 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR: 2208 case IR_BSHL: case IR_BSHR: case IR_BSAR:
2209 if ((as->flags & JIT_F_BMI2)) /* Except if BMI2 is available. */
2210 break;
2211 case IR_BROL: case IR_BROR:
1789 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) { 2212 if (!irref_isk(ir->op2) && !ra_hashint(IR(ir->op2)->r)) {
1790 IR(ir->op2)->r = REGSP_HINT(RID_ECX); 2213 IR(ir->op2)->r = REGSP_HINT(RID_ECX);
1791 if (inloop) 2214 if (inloop)
@@ -1831,14 +2254,25 @@ void lj_asm_trace(jit_State *J, GCtrace *T)
1831 ASMState *as = &as_; 2254 ASMState *as = &as_;
1832 MCode *origtop; 2255 MCode *origtop;
1833 2256
2257 /* Remove nops/renames left over from ASM restart due to LJ_TRERR_MCODELM. */
2258 {
2259 IRRef nins = T->nins;
2260 IRIns *ir = &T->ir[nins-1];
2261 if (ir->o == IR_NOP || ir->o == IR_RENAME) {
2262 do { ir--; nins--; } while (ir->o == IR_NOP || ir->o == IR_RENAME);
2263 T->nins = nins;
2264 }
2265 }
2266
1834 /* Ensure an initialized instruction beyond the last one for HIOP checks. */ 2267 /* Ensure an initialized instruction beyond the last one for HIOP checks. */
1835 J->cur.nins = lj_ir_nextins(J); 2268 /* This also allows one RENAME to be added without reallocating curfinal. */
1836 J->cur.ir[J->cur.nins].o = IR_NOP; 2269 as->orignins = lj_ir_nextins(J);
2270 J->cur.ir[as->orignins].o = IR_NOP;
1837 2271
1838 /* Setup initial state. Copy some fields to reduce indirections. */ 2272 /* Setup initial state. Copy some fields to reduce indirections. */
1839 as->J = J; 2273 as->J = J;
1840 as->T = T; 2274 as->T = T;
1841 as->ir = T->ir; 2275 J->curfinal = lj_trace_alloc(J->L, T); /* This copies the IR, too. */
1842 as->flags = J->flags; 2276 as->flags = J->flags;
1843 as->loopref = J->loopref; 2277 as->loopref = J->loopref;
1844 as->realign = NULL; 2278 as->realign = NULL;
@@ -1851,12 +2285,41 @@ void lj_asm_trace(jit_State *J, GCtrace *T)
1851 as->mclim = as->mcbot + MCLIM_REDZONE; 2285 as->mclim = as->mcbot + MCLIM_REDZONE;
1852 asm_setup_target(as); 2286 asm_setup_target(as);
1853 2287
1854 do { 2288 /*
2289 ** This is a loop, because the MCode may have to be (re-)assembled
2290 ** multiple times:
2291 **
2292 ** 1. as->realign is set (and the assembly aborted), if the arch-specific
2293 ** backend wants the MCode to be aligned differently.
2294 **
2295 ** This is currently only the case on x86/x64, where small loops get
2296 ** an aligned loop body plus a short branch. Not much effort is wasted,
2297 ** because the abort happens very quickly and only once.
2298 **
2299 ** 2. The IR is immovable, since the MCode embeds pointers to various
2300 ** constants inside the IR. But RENAMEs may need to be added to the IR
2301 ** during assembly, which might grow and reallocate the IR. We check
2302 ** at the end if the IR (in J->cur.ir) has actually grown, resize the
2303 ** copy (in J->curfinal.ir) and try again.
2304 **
2305 ** 95% of all traces have zero RENAMEs, 3% have one RENAME, 1.5% have
2306 ** 2 RENAMEs and only 0.5% have more than that. That's why we opt to
2307 ** always have one spare slot in the IR (see above), which means we
2308 ** have to redo the assembly for only ~2% of all traces.
2309 **
2310 ** Very, very rarely, this needs to be done repeatedly, since the
2311 ** location of constants inside the IR (actually, reachability from
2312 ** a global pointer) may affect register allocation and thus the
2313 ** number of RENAMEs.
2314 */
2315 for (;;) {
1855 as->mcp = as->mctop; 2316 as->mcp = as->mctop;
1856#ifdef LUA_USE_ASSERT 2317#ifdef LUA_USE_ASSERT
1857 as->mcp_prev = as->mcp; 2318 as->mcp_prev = as->mcp;
1858#endif 2319#endif
1859 as->curins = T->nins; 2320 as->ir = J->curfinal->ir; /* Use the copied IR. */
2321 as->curins = J->cur.nins = as->orignins;
2322
1860 RA_DBG_START(); 2323 RA_DBG_START();
1861 RA_DBGX((as, "===== STOP =====")); 2324 RA_DBGX((as, "===== STOP ====="));
1862 2325
@@ -1884,22 +2347,40 @@ void lj_asm_trace(jit_State *J, GCtrace *T)
1884 checkmclim(as); 2347 checkmclim(as);
1885 asm_ir(as, ir); 2348 asm_ir(as, ir);
1886 } 2349 }
1887 } while (as->realign); /* Retry in case the MCode needs to be realigned. */
1888 2350
1889 /* Emit head of trace. */ 2351 if (as->realign && J->curfinal->nins >= T->nins)
1890 RA_DBG_REF(); 2352 continue; /* Retry in case only the MCode needs to be realigned. */
1891 checkmclim(as); 2353
1892 if (as->gcsteps > 0) { 2354 /* Emit head of trace. */
1893 as->curins = as->T->snap[0].ref; 2355 RA_DBG_REF();
1894 asm_snap_prep(as); /* The GC check is a guard. */ 2356 checkmclim(as);
1895 asm_gc_check(as); 2357 if (as->gcsteps > 0) {
2358 as->curins = as->T->snap[0].ref;
2359 asm_snap_prep(as); /* The GC check is a guard. */
2360 asm_gc_check(as);
2361 as->curins = as->stopins;
2362 }
2363 ra_evictk(as);
2364 if (as->parent)
2365 asm_head_side(as);
2366 else
2367 asm_head_root(as);
2368 asm_phi_fixup(as);
2369
2370 if (J->curfinal->nins >= T->nins) { /* IR didn't grow? */
2371 lua_assert(J->curfinal->nk == T->nk);
2372 memcpy(J->curfinal->ir + as->orignins, T->ir + as->orignins,
2373 (T->nins - as->orignins) * sizeof(IRIns)); /* Copy RENAMEs. */
2374 T->nins = J->curfinal->nins;
2375 break; /* Done. */
2376 }
2377
2378 /* Otherwise try again with a bigger IR. */
2379 lj_trace_free(J2G(J), J->curfinal);
2380 J->curfinal = NULL; /* In case lj_trace_alloc() OOMs. */
2381 J->curfinal = lj_trace_alloc(J->L, T);
2382 as->realign = NULL;
1896 } 2383 }
1897 ra_evictk(as);
1898 if (as->parent)
1899 asm_head_side(as);
1900 else
1901 asm_head_root(as);
1902 asm_phi_fixup(as);
1903 2384
1904 RA_DBGX((as, "===== START ====")); 2385 RA_DBGX((as, "===== START ===="));
1905 RA_DBG_FLUSH(); 2386 RA_DBG_FLUSH();
diff --git a/src/lj_asm_arm.h b/src/lj_asm_arm.h
index 961f7e39..37bfa40f 100644
--- a/src/lj_asm_arm.h
+++ b/src/lj_asm_arm.h
@@ -338,7 +338,7 @@ static int asm_fusemadd(ASMState *as, IRIns *ir, ARMIns ai, ARMIns air)
338/* Generate a call to a C function. */ 338/* Generate a call to a C function. */
339static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) 339static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
340{ 340{
341 uint32_t n, nargs = CCI_NARGS(ci); 341 uint32_t n, nargs = CCI_XNARGS(ci);
342 int32_t ofs = 0; 342 int32_t ofs = 0;
343#if LJ_SOFTFP 343#if LJ_SOFTFP
344 Reg gpr = REGARG_FIRSTGPR; 344 Reg gpr = REGARG_FIRSTGPR;
@@ -453,15 +453,6 @@ static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
453 UNUSED(ci); 453 UNUSED(ci);
454} 454}
455 455
456static void asm_call(ASMState *as, IRIns *ir)
457{
458 IRRef args[CCI_NARGS_MAX];
459 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
460 asm_collectargs(as, ir, ci, args);
461 asm_setupresult(as, ir, ci);
462 asm_gencall(as, ci, args);
463}
464
465static void asm_callx(ASMState *as, IRIns *ir) 456static void asm_callx(ASMState *as, IRIns *ir)
466{ 457{
467 IRRef args[CCI_NARGS_MAX*2]; 458 IRRef args[CCI_NARGS_MAX*2];
@@ -490,7 +481,7 @@ static void asm_retf(ASMState *as, IRIns *ir)
490{ 481{
491 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); 482 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
492 void *pc = ir_kptr(IR(ir->op2)); 483 void *pc = ir_kptr(IR(ir->op2));
493 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1)); 484 int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
494 as->topslot -= (BCReg)delta; 485 as->topslot -= (BCReg)delta;
495 if ((int32_t)as->topslot < 0) as->topslot = 0; 486 if ((int32_t)as->topslot < 0) as->topslot = 0;
496 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ 487 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
@@ -601,31 +592,6 @@ static void asm_conv(ASMState *as, IRIns *ir)
601 } 592 }
602} 593}
603 594
604#if !LJ_SOFTFP && LJ_HASFFI
605static void asm_conv64(ASMState *as, IRIns *ir)
606{
607 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
608 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
609 IRCallID id;
610 CCallInfo ci;
611 IRRef args[2];
612 args[0] = (ir-1)->op1;
613 args[1] = ir->op1;
614 if (st == IRT_NUM || st == IRT_FLOAT) {
615 id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
616 ir--;
617 } else {
618 id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
619 }
620 ci = lj_ir_callinfo[id];
621#if !LJ_ABI_SOFTFP
622 ci.flags |= CCI_VARARG; /* These calls don't use the hard-float ABI! */
623#endif
624 asm_setupresult(as, ir, &ci);
625 asm_gencall(as, &ci, args);
626}
627#endif
628
629static void asm_strto(ASMState *as, IRIns *ir) 595static void asm_strto(ASMState *as, IRIns *ir)
630{ 596{
631 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; 597 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
@@ -689,6 +655,8 @@ static void asm_strto(ASMState *as, IRIns *ir)
689 emit_opk(as, ARMI_ADD, tmp, RID_SP, ofs, RSET_GPR); 655 emit_opk(as, ARMI_ADD, tmp, RID_SP, ofs, RSET_GPR);
690} 656}
691 657
658/* -- Memory references --------------------------------------------------- */
659
692/* Get pointer to TValue. */ 660/* Get pointer to TValue. */
693static void asm_tvptr(ASMState *as, Reg dest, IRRef ref) 661static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
694{ 662{
@@ -714,7 +682,7 @@ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
714 Reg src = ra_alloc1(as, ref, allow); 682 Reg src = ra_alloc1(as, ref, allow);
715 emit_lso(as, ARMI_STR, src, RID_SP, 0); 683 emit_lso(as, ARMI_STR, src, RID_SP, 0);
716 } 684 }
717 if ((ir+1)->o == IR_HIOP) 685 if (LJ_SOFTFP && (ir+1)->o == IR_HIOP)
718 type = ra_alloc1(as, ref+1, allow); 686 type = ra_alloc1(as, ref+1, allow);
719 else 687 else
720 type = ra_allock(as, irt_toitype(ir->t), allow); 688 type = ra_allock(as, irt_toitype(ir->t), allow);
@@ -722,27 +690,6 @@ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
722 } 690 }
723} 691}
724 692
725static void asm_tostr(ASMState *as, IRIns *ir)
726{
727 IRRef args[2];
728 args[0] = ASMREF_L;
729 as->gcsteps++;
730 if (irt_isnum(IR(ir->op1)->t) || (ir+1)->o == IR_HIOP) {
731 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum];
732 args[1] = ASMREF_TMP1; /* const lua_Number * */
733 asm_setupresult(as, ir, ci); /* GCstr * */
734 asm_gencall(as, ci, args);
735 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1);
736 } else {
737 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint];
738 args[1] = ir->op1; /* int32_t k */
739 asm_setupresult(as, ir, ci); /* GCstr * */
740 asm_gencall(as, ci, args);
741 }
742}
743
744/* -- Memory references --------------------------------------------------- */
745
746static void asm_aref(ASMState *as, IRIns *ir) 693static void asm_aref(ASMState *as, IRIns *ir)
747{ 694{
748 Reg dest = ra_dest(as, ir, RSET_GPR); 695 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -960,20 +907,6 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
960 emit_opk(as, ARMI_ADD, dest, node, ofs, RSET_GPR); 907 emit_opk(as, ARMI_ADD, dest, node, ofs, RSET_GPR);
961} 908}
962 909
963static void asm_newref(ASMState *as, IRIns *ir)
964{
965 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
966 IRRef args[3];
967 if (ir->r == RID_SINK)
968 return;
969 args[0] = ASMREF_L; /* lua_State *L */
970 args[1] = ir->op1; /* GCtab *t */
971 args[2] = ASMREF_TMP1; /* cTValue *key */
972 asm_setupresult(as, ir, ci); /* TValue * */
973 asm_gencall(as, ci, args);
974 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2);
975}
976
977static void asm_uref(ASMState *as, IRIns *ir) 910static void asm_uref(ASMState *as, IRIns *ir)
978{ 911{
979 Reg dest = ra_dest(as, ir, RSET_GPR); 912 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -1064,22 +997,26 @@ static ARMIns asm_fxstoreins(IRIns *ir)
1064 997
1065static void asm_fload(ASMState *as, IRIns *ir) 998static void asm_fload(ASMState *as, IRIns *ir)
1066{ 999{
1067 Reg dest = ra_dest(as, ir, RSET_GPR); 1000 if (ir->op1 == REF_NIL) {
1068 Reg idx = ra_alloc1(as, ir->op1, RSET_GPR); 1001 lua_assert(!ra_used(ir)); /* We can end up here if DCE is turned off. */
1069 ARMIns ai = asm_fxloadins(ir); 1002 } else {
1070 int32_t ofs; 1003 Reg dest = ra_dest(as, ir, RSET_GPR);
1071 if (ir->op2 == IRFL_TAB_ARRAY) { 1004 Reg idx = ra_alloc1(as, ir->op1, RSET_GPR);
1072 ofs = asm_fuseabase(as, ir->op1); 1005 ARMIns ai = asm_fxloadins(ir);
1073 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ 1006 int32_t ofs;
1074 emit_dn(as, ARMI_ADD|ARMI_K12|ofs, dest, idx); 1007 if (ir->op2 == IRFL_TAB_ARRAY) {
1075 return; 1008 ofs = asm_fuseabase(as, ir->op1);
1009 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */
1010 emit_dn(as, ARMI_ADD|ARMI_K12|ofs, dest, idx);
1011 return;
1012 }
1076 } 1013 }
1014 ofs = field_ofs[ir->op2];
1015 if ((ai & 0x04000000))
1016 emit_lso(as, ai, dest, idx, ofs);
1017 else
1018 emit_lsox(as, ai, dest, idx, ofs);
1077 } 1019 }
1078 ofs = field_ofs[ir->op2];
1079 if ((ai & 0x04000000))
1080 emit_lso(as, ai, dest, idx, ofs);
1081 else
1082 emit_lsox(as, ai, dest, idx, ofs);
1083} 1020}
1084 1021
1085static void asm_fstore(ASMState *as, IRIns *ir) 1022static void asm_fstore(ASMState *as, IRIns *ir)
@@ -1105,7 +1042,7 @@ static void asm_xload(ASMState *as, IRIns *ir)
1105 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0); 1042 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0);
1106} 1043}
1107 1044
1108static void asm_xstore(ASMState *as, IRIns *ir, int32_t ofs) 1045static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs)
1109{ 1046{
1110 if (ir->r != RID_SINK) { 1047 if (ir->r != RID_SINK) {
1111 Reg src = ra_alloc1(as, ir->op2, 1048 Reg src = ra_alloc1(as, ir->op2,
@@ -1115,6 +1052,8 @@ static void asm_xstore(ASMState *as, IRIns *ir, int32_t ofs)
1115 } 1052 }
1116} 1053}
1117 1054
1055#define asm_xstore(as, ir) asm_xstore_(as, ir, 0)
1056
1118static void asm_ahuvload(ASMState *as, IRIns *ir) 1057static void asm_ahuvload(ASMState *as, IRIns *ir)
1119{ 1058{
1120 int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP); 1059 int hiop = (LJ_SOFTFP && (ir+1)->o == IR_HIOP);
@@ -1272,19 +1211,16 @@ dotypecheck:
1272static void asm_cnew(ASMState *as, IRIns *ir) 1211static void asm_cnew(ASMState *as, IRIns *ir)
1273{ 1212{
1274 CTState *cts = ctype_ctsG(J2G(as->J)); 1213 CTState *cts = ctype_ctsG(J2G(as->J));
1275 CTypeID ctypeid = (CTypeID)IR(ir->op1)->i; 1214 CTypeID id = (CTypeID)IR(ir->op1)->i;
1276 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ? 1215 CTSize sz;
1277 lj_ctype_size(cts, ctypeid) : (CTSize)IR(ir->op2)->i; 1216 CTInfo info = lj_ctype_info(cts, id, &sz);
1278 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; 1217 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1279 IRRef args[2]; 1218 IRRef args[4];
1280 RegSet allow = (RSET_GPR & ~RSET_SCRATCH); 1219 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1281 RegSet drop = RSET_SCRATCH; 1220 RegSet drop = RSET_SCRATCH;
1282 lua_assert(sz != CTSIZE_INVALID); 1221 lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));
1283 1222
1284 args[0] = ASMREF_L; /* lua_State *L */
1285 args[1] = ASMREF_TMP1; /* MSize size */
1286 as->gcsteps++; 1223 as->gcsteps++;
1287
1288 if (ra_hasreg(ir->r)) 1224 if (ra_hasreg(ir->r))
1289 rset_clear(drop, ir->r); /* Dest reg handled below. */ 1225 rset_clear(drop, ir->r); /* Dest reg handled below. */
1290 ra_evictset(as, drop); 1226 ra_evictset(as, drop);
@@ -1306,16 +1242,28 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1306 if (ofs == sizeof(GCcdata)) break; 1242 if (ofs == sizeof(GCcdata)) break;
1307 ofs -= 4; ir--; 1243 ofs -= 4; ir--;
1308 } 1244 }
1245 } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */
1246 ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
1247 args[0] = ASMREF_L; /* lua_State *L */
1248 args[1] = ir->op1; /* CTypeID id */
1249 args[2] = ir->op2; /* CTSize sz */
1250 args[3] = ASMREF_TMP1; /* CTSize align */
1251 asm_gencall(as, ci, args);
1252 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
1253 return;
1309 } 1254 }
1255
1310 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ 1256 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */
1311 { 1257 {
1312 uint32_t k = emit_isk12(ARMI_MOV, ctypeid); 1258 uint32_t k = emit_isk12(ARMI_MOV, id);
1313 Reg r = k ? RID_R1 : ra_allock(as, ctypeid, allow); 1259 Reg r = k ? RID_R1 : ra_allock(as, id, allow);
1314 emit_lso(as, ARMI_STRB, RID_TMP, RID_RET, offsetof(GCcdata, gct)); 1260 emit_lso(as, ARMI_STRB, RID_TMP, RID_RET, offsetof(GCcdata, gct));
1315 emit_lsox(as, ARMI_STRH, r, RID_RET, offsetof(GCcdata, ctypeid)); 1261 emit_lsox(as, ARMI_STRH, r, RID_RET, offsetof(GCcdata, ctypeid));
1316 emit_d(as, ARMI_MOV|ARMI_K12|~LJ_TCDATA, RID_TMP); 1262 emit_d(as, ARMI_MOV|ARMI_K12|~LJ_TCDATA, RID_TMP);
1317 if (k) emit_d(as, ARMI_MOV^k, RID_R1); 1263 if (k) emit_d(as, ARMI_MOV^k, RID_R1);
1318 } 1264 }
1265 args[0] = ASMREF_L; /* lua_State *L */
1266 args[1] = ASMREF_TMP1; /* MSize size */
1319 asm_gencall(as, ci, args); 1267 asm_gencall(as, ci, args);
1320 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), 1268 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)),
1321 ra_releasetmp(as, ASMREF_TMP1)); 1269 ra_releasetmp(as, ASMREF_TMP1));
@@ -1392,23 +1340,38 @@ static void asm_fpunary(ASMState *as, IRIns *ir, ARMIns ai)
1392 emit_dm(as, ai, (dest & 15), (left & 15)); 1340 emit_dm(as, ai, (dest & 15), (left & 15));
1393} 1341}
1394 1342
1395static int asm_fpjoin_pow(ASMState *as, IRIns *ir) 1343static void asm_callround(ASMState *as, IRIns *ir, int id)
1396{ 1344{
1397 IRIns *irp = IR(ir->op1); 1345 /* The modified regs must match with the *.dasc implementation. */
1398 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) { 1346 RegSet drop = RID2RSET(RID_R0)|RID2RSET(RID_R1)|RID2RSET(RID_R2)|
1399 IRIns *irpp = IR(irp->op1); 1347 RID2RSET(RID_R3)|RID2RSET(RID_R12);
1400 if (irpp == ir-2 && irpp->o == IR_FPMATH && 1348 RegSet of;
1401 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) { 1349 Reg dest, src;
1402 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow]; 1350 ra_evictset(as, drop);
1403 IRRef args[2]; 1351 dest = ra_dest(as, ir, RSET_FPR);
1404 args[0] = irpp->op1; 1352 emit_dnm(as, ARMI_VMOV_D_RR, RID_RETLO, RID_RETHI, (dest & 15));
1405 args[1] = irp->op2; 1353 emit_call(as, id == IRFPM_FLOOR ? (void *)lj_vm_floor_sf :
1406 asm_setupresult(as, ir, ci); 1354 id == IRFPM_CEIL ? (void *)lj_vm_ceil_sf :
1407 asm_gencall(as, ci, args); 1355 (void *)lj_vm_trunc_sf);
1408 return 1; 1356 /* Workaround to protect argument GPRs from being used for remat. */
1409 } 1357 of = as->freeset;
1410 } 1358 as->freeset &= ~RSET_RANGE(RID_R0, RID_R1+1);
1411 return 0; 1359 as->cost[RID_R0] = as->cost[RID_R1] = REGCOST(~0u, ASMREF_L);
1360 src = ra_alloc1(as, ir->op1, RSET_FPR); /* May alloc GPR to remat FPR. */
1361 as->freeset |= (of & RSET_RANGE(RID_R0, RID_R1+1));
1362 emit_dnm(as, ARMI_VMOV_RR_D, RID_R0, RID_R1, (src & 15));
1363}
1364
1365static void asm_fpmath(ASMState *as, IRIns *ir)
1366{
1367 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
1368 return;
1369 if (ir->op2 <= IRFPM_TRUNC)
1370 asm_callround(as, ir, ir->op2);
1371 else if (ir->op2 == IRFPM_SQRT)
1372 asm_fpunary(as, ir, ARMI_VSQRT_D);
1373 else
1374 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
1412} 1375}
1413#endif 1376#endif
1414 1377
@@ -1459,32 +1422,6 @@ static void asm_intop_s(ASMState *as, IRIns *ir, ARMIns ai)
1459 asm_intop(as, ir, ai); 1422 asm_intop(as, ir, ai);
1460} 1423}
1461 1424
1462static void asm_bitop(ASMState *as, IRIns *ir, ARMIns ai)
1463{
1464 if (as->flagmcp == as->mcp) { /* Try to drop cmp r, #0. */
1465 uint32_t cc = (as->mcp[1] >> 28);
1466 as->flagmcp = NULL;
1467 if (cc <= CC_NE) {
1468 as->mcp++;
1469 ai |= ARMI_S;
1470 } else if (cc == CC_GE) {
1471 *++as->mcp ^= ((CC_GE^CC_PL) << 28);
1472 ai |= ARMI_S;
1473 } else if (cc == CC_LT) {
1474 *++as->mcp ^= ((CC_LT^CC_MI) << 28);
1475 ai |= ARMI_S;
1476 } /* else: other conds don't work with bit ops. */
1477 }
1478 if (ir->op2 == 0) {
1479 Reg dest = ra_dest(as, ir, RSET_GPR);
1480 uint32_t m = asm_fuseopm(as, ai, ir->op1, RSET_GPR);
1481 emit_d(as, ai^m, dest);
1482 } else {
1483 /* NYI: Turn BAND !k12 into uxtb, uxth or bfc or shl+shr. */
1484 asm_intop(as, ir, ai);
1485 }
1486}
1487
1488static void asm_intneg(ASMState *as, IRIns *ir, ARMIns ai) 1425static void asm_intneg(ASMState *as, IRIns *ir, ARMIns ai)
1489{ 1426{
1490 Reg dest = ra_dest(as, ir, RSET_GPR); 1427 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -1550,6 +1487,20 @@ static void asm_mul(ASMState *as, IRIns *ir)
1550 asm_intmul(as, ir); 1487 asm_intmul(as, ir);
1551} 1488}
1552 1489
1490#define asm_addov(as, ir) asm_add(as, ir)
1491#define asm_subov(as, ir) asm_sub(as, ir)
1492#define asm_mulov(as, ir) asm_mul(as, ir)
1493
1494#if !LJ_SOFTFP
1495#define asm_div(as, ir) asm_fparith(as, ir, ARMI_VDIV_D)
1496#define asm_pow(as, ir) asm_callid(as, ir, IRCALL_lj_vm_powi)
1497#define asm_abs(as, ir) asm_fpunary(as, ir, ARMI_VABS_D)
1498#define asm_atan2(as, ir) asm_callid(as, ir, IRCALL_atan2)
1499#define asm_ldexp(as, ir) asm_callid(as, ir, IRCALL_ldexp)
1500#endif
1501
1502#define asm_mod(as, ir) asm_callid(as, ir, IRCALL_lj_vm_modi)
1503
1553static void asm_neg(ASMState *as, IRIns *ir) 1504static void asm_neg(ASMState *as, IRIns *ir)
1554{ 1505{
1555#if !LJ_SOFTFP 1506#if !LJ_SOFTFP
@@ -1561,41 +1512,35 @@ static void asm_neg(ASMState *as, IRIns *ir)
1561 asm_intneg(as, ir, ARMI_RSB); 1512 asm_intneg(as, ir, ARMI_RSB);
1562} 1513}
1563 1514
1564static void asm_callid(ASMState *as, IRIns *ir, IRCallID id) 1515static void asm_bitop(ASMState *as, IRIns *ir, ARMIns ai)
1565{ 1516{
1566 const CCallInfo *ci = &lj_ir_callinfo[id]; 1517 if (as->flagmcp == as->mcp) { /* Try to drop cmp r, #0. */
1567 IRRef args[2]; 1518 uint32_t cc = (as->mcp[1] >> 28);
1568 args[0] = ir->op1; 1519 as->flagmcp = NULL;
1569 args[1] = ir->op2; 1520 if (cc <= CC_NE) {
1570 asm_setupresult(as, ir, ci); 1521 as->mcp++;
1571 asm_gencall(as, ci, args); 1522 ai |= ARMI_S;
1523 } else if (cc == CC_GE) {
1524 *++as->mcp ^= ((CC_GE^CC_PL) << 28);
1525 ai |= ARMI_S;
1526 } else if (cc == CC_LT) {
1527 *++as->mcp ^= ((CC_LT^CC_MI) << 28);
1528 ai |= ARMI_S;
1529 } /* else: other conds don't work with bit ops. */
1530 }
1531 if (ir->op2 == 0) {
1532 Reg dest = ra_dest(as, ir, RSET_GPR);
1533 uint32_t m = asm_fuseopm(as, ai, ir->op1, RSET_GPR);
1534 emit_d(as, ai^m, dest);
1535 } else {
1536 /* NYI: Turn BAND !k12 into uxtb, uxth or bfc or shl+shr. */
1537 asm_intop(as, ir, ai);
1538 }
1572} 1539}
1573 1540
1574#if !LJ_SOFTFP 1541#define asm_bnot(as, ir) asm_bitop(as, ir, ARMI_MVN)
1575static void asm_callround(ASMState *as, IRIns *ir, int id)
1576{
1577 /* The modified regs must match with the *.dasc implementation. */
1578 RegSet drop = RID2RSET(RID_R0)|RID2RSET(RID_R1)|RID2RSET(RID_R2)|
1579 RID2RSET(RID_R3)|RID2RSET(RID_R12);
1580 RegSet of;
1581 Reg dest, src;
1582 ra_evictset(as, drop);
1583 dest = ra_dest(as, ir, RSET_FPR);
1584 emit_dnm(as, ARMI_VMOV_D_RR, RID_RETLO, RID_RETHI, (dest & 15));
1585 emit_call(as, id == IRFPM_FLOOR ? (void *)lj_vm_floor_sf :
1586 id == IRFPM_CEIL ? (void *)lj_vm_ceil_sf :
1587 (void *)lj_vm_trunc_sf);
1588 /* Workaround to protect argument GPRs from being used for remat. */
1589 of = as->freeset;
1590 as->freeset &= ~RSET_RANGE(RID_R0, RID_R1+1);
1591 as->cost[RID_R0] = as->cost[RID_R1] = REGCOST(~0u, ASMREF_L);
1592 src = ra_alloc1(as, ir->op1, RSET_FPR); /* May alloc GPR to remat FPR. */
1593 as->freeset |= (of & RSET_RANGE(RID_R0, RID_R1+1));
1594 emit_dnm(as, ARMI_VMOV_RR_D, RID_R0, RID_R1, (src & 15));
1595}
1596#endif
1597 1542
1598static void asm_bitswap(ASMState *as, IRIns *ir) 1543static void asm_bswap(ASMState *as, IRIns *ir)
1599{ 1544{
1600 Reg dest = ra_dest(as, ir, RSET_GPR); 1545 Reg dest = ra_dest(as, ir, RSET_GPR);
1601 Reg left = ra_alloc1(as, ir->op1, RSET_GPR); 1546 Reg left = ra_alloc1(as, ir->op1, RSET_GPR);
@@ -1612,6 +1557,10 @@ static void asm_bitswap(ASMState *as, IRIns *ir)
1612 } 1557 }
1613} 1558}
1614 1559
1560#define asm_band(as, ir) asm_bitop(as, ir, ARMI_AND)
1561#define asm_bor(as, ir) asm_bitop(as, ir, ARMI_ORR)
1562#define asm_bxor(as, ir) asm_bitop(as, ir, ARMI_EOR)
1563
1615static void asm_bitshift(ASMState *as, IRIns *ir, ARMShift sh) 1564static void asm_bitshift(ASMState *as, IRIns *ir, ARMShift sh)
1616{ 1565{
1617 if (irref_isk(ir->op2)) { /* Constant shifts. */ 1566 if (irref_isk(ir->op2)) { /* Constant shifts. */
@@ -1629,6 +1578,12 @@ static void asm_bitshift(ASMState *as, IRIns *ir, ARMShift sh)
1629 } 1578 }
1630} 1579}
1631 1580
1581#define asm_bshl(as, ir) asm_bitshift(as, ir, ARMSH_LSL)
1582#define asm_bshr(as, ir) asm_bitshift(as, ir, ARMSH_LSR)
1583#define asm_bsar(as, ir) asm_bitshift(as, ir, ARMSH_ASR)
1584#define asm_bror(as, ir) asm_bitshift(as, ir, ARMSH_ROR)
1585#define asm_brol(as, ir) lua_assert(0)
1586
1632static void asm_intmin_max(ASMState *as, IRIns *ir, int cc) 1587static void asm_intmin_max(ASMState *as, IRIns *ir, int cc)
1633{ 1588{
1634 uint32_t kcmp = 0, kmov = 0; 1589 uint32_t kcmp = 0, kmov = 0;
@@ -1702,6 +1657,9 @@ static void asm_min_max(ASMState *as, IRIns *ir, int cc, int fcc)
1702 asm_intmin_max(as, ir, cc); 1657 asm_intmin_max(as, ir, cc);
1703} 1658}
1704 1659
1660#define asm_min(as, ir) asm_min_max(as, ir, CC_GT, CC_HI)
1661#define asm_max(as, ir) asm_min_max(as, ir, CC_LT, CC_LO)
1662
1705/* -- Comparisons --------------------------------------------------------- */ 1663/* -- Comparisons --------------------------------------------------------- */
1706 1664
1707/* Map of comparisons to flags. ORDER IR. */ 1665/* Map of comparisons to flags. ORDER IR. */
@@ -1817,6 +1775,18 @@ notst:
1817 as->flagmcp = as->mcp; /* Allow elimination of the compare. */ 1775 as->flagmcp = as->mcp; /* Allow elimination of the compare. */
1818} 1776}
1819 1777
1778static void asm_comp(ASMState *as, IRIns *ir)
1779{
1780#if !LJ_SOFTFP
1781 if (irt_isnum(ir->t))
1782 asm_fpcomp(as, ir);
1783 else
1784#endif
1785 asm_intcomp(as, ir);
1786}
1787
1788#define asm_equal(as, ir) asm_comp(as, ir)
1789
1820#if LJ_HASFFI 1790#if LJ_HASFFI
1821/* 64 bit integer comparisons. */ 1791/* 64 bit integer comparisons. */
1822static void asm_int64comp(ASMState *as, IRIns *ir) 1792static void asm_int64comp(ASMState *as, IRIns *ir)
@@ -1891,7 +1861,7 @@ static void asm_hiop(ASMState *as, IRIns *ir)
1891#endif 1861#endif
1892 } else if ((ir-1)->o == IR_XSTORE) { 1862 } else if ((ir-1)->o == IR_XSTORE) {
1893 if ((ir-1)->r != RID_SINK) 1863 if ((ir-1)->r != RID_SINK)
1894 asm_xstore(as, ir, 4); 1864 asm_xstore_(as, ir, 4);
1895 return; 1865 return;
1896 } 1866 }
1897 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ 1867 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */
@@ -1939,6 +1909,16 @@ static void asm_hiop(ASMState *as, IRIns *ir)
1939#endif 1909#endif
1940} 1910}
1941 1911
1912/* -- Profiling ----------------------------------------------------------- */
1913
1914static void asm_prof(ASMState *as, IRIns *ir)
1915{
1916 UNUSED(ir);
1917 asm_guardcc(as, CC_NE);
1918 emit_n(as, ARMI_TST|ARMI_K12|HOOK_PROFILE, RID_TMP);
1919 emit_lsptr(as, ARMI_LDRB, RID_TMP, (void *)&J2G(as->J)->hookmask);
1920}
1921
1942/* -- Stack handling ------------------------------------------------------ */ 1922/* -- Stack handling ------------------------------------------------------ */
1943 1923
1944/* Check Lua stack size for overflow. Use exit handler as fallback. */ 1924/* Check Lua stack size for overflow. Use exit handler as fallback. */
@@ -1968,7 +1948,7 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
1968 emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP, 1948 emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP,
1969 (int32_t)offsetof(lua_State, maxstack)); 1949 (int32_t)offsetof(lua_State, maxstack));
1970 if (irp) { /* Must not spill arbitrary registers in head of side trace. */ 1950 if (irp) { /* Must not spill arbitrary registers in head of side trace. */
1971 int32_t i = i32ptr(&J2G(as->J)->jit_L); 1951 int32_t i = i32ptr(&J2G(as->J)->cur_L);
1972 if (ra_hasspill(irp->s)) 1952 if (ra_hasspill(irp->s))
1973 emit_lso(as, ARMI_LDR, pbase, RID_SP, sps_scale(irp->s)); 1953 emit_lso(as, ARMI_LDR, pbase, RID_SP, sps_scale(irp->s));
1974 emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP, (i & 4095)); 1954 emit_lso(as, ARMI_LDR, RID_TMP, RID_TMP, (i & 4095));
@@ -1976,7 +1956,7 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
1976 emit_lso(as, ARMI_STR, RID_RET, RID_SP, 0); /* Save temp. register. */ 1956 emit_lso(as, ARMI_STR, RID_RET, RID_SP, 0); /* Save temp. register. */
1977 emit_loadi(as, RID_TMP, (i & ~4095)); 1957 emit_loadi(as, RID_TMP, (i & ~4095));
1978 } else { 1958 } else {
1979 emit_getgl(as, RID_TMP, jit_L); 1959 emit_getgl(as, RID_TMP, cur_L);
1980 } 1960 }
1981} 1961}
1982 1962
@@ -2085,13 +2065,13 @@ static void asm_loop_fixup(ASMState *as)
2085 2065
2086/* -- Head of trace ------------------------------------------------------- */ 2066/* -- Head of trace ------------------------------------------------------- */
2087 2067
2088/* Reload L register from g->jit_L. */ 2068/* Reload L register from g->cur_L. */
2089static void asm_head_lreg(ASMState *as) 2069static void asm_head_lreg(ASMState *as)
2090{ 2070{
2091 IRIns *ir = IR(ASMREF_L); 2071 IRIns *ir = IR(ASMREF_L);
2092 if (ra_used(ir)) { 2072 if (ra_used(ir)) {
2093 Reg r = ra_dest(as, ir, RSET_GPR); 2073 Reg r = ra_dest(as, ir, RSET_GPR);
2094 emit_getgl(as, r, jit_L); 2074 emit_getgl(as, r, cur_L);
2095 ra_evictk(as); 2075 ra_evictk(as);
2096 } 2076 }
2097} 2077}
@@ -2162,143 +2142,13 @@ static void asm_tail_prep(ASMState *as)
2162 *p = 0; /* Prevent load/store merging. */ 2142 *p = 0; /* Prevent load/store merging. */
2163} 2143}
2164 2144
2165/* -- Instruction dispatch ------------------------------------------------ */
2166
2167/* Assemble a single instruction. */
2168static void asm_ir(ASMState *as, IRIns *ir)
2169{
2170 switch ((IROp)ir->o) {
2171 /* Miscellaneous ops. */
2172 case IR_LOOP: asm_loop(as); break;
2173 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
2174 case IR_USE:
2175 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
2176 case IR_PHI: asm_phi(as, ir); break;
2177 case IR_HIOP: asm_hiop(as, ir); break;
2178 case IR_GCSTEP: asm_gcstep(as, ir); break;
2179
2180 /* Guarded assertions. */
2181 case IR_EQ: case IR_NE:
2182 if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) {
2183 as->curins--;
2184 asm_href(as, ir-1, (IROp)ir->o);
2185 break;
2186 }
2187 /* fallthrough */
2188 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
2189 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
2190 case IR_ABC:
2191#if !LJ_SOFTFP
2192 if (irt_isnum(ir->t)) { asm_fpcomp(as, ir); break; }
2193#endif
2194 asm_intcomp(as, ir);
2195 break;
2196
2197 case IR_RETF: asm_retf(as, ir); break;
2198
2199 /* Bit ops. */
2200 case IR_BNOT: asm_bitop(as, ir, ARMI_MVN); break;
2201 case IR_BSWAP: asm_bitswap(as, ir); break;
2202
2203 case IR_BAND: asm_bitop(as, ir, ARMI_AND); break;
2204 case IR_BOR: asm_bitop(as, ir, ARMI_ORR); break;
2205 case IR_BXOR: asm_bitop(as, ir, ARMI_EOR); break;
2206
2207 case IR_BSHL: asm_bitshift(as, ir, ARMSH_LSL); break;
2208 case IR_BSHR: asm_bitshift(as, ir, ARMSH_LSR); break;
2209 case IR_BSAR: asm_bitshift(as, ir, ARMSH_ASR); break;
2210 case IR_BROR: asm_bitshift(as, ir, ARMSH_ROR); break;
2211 case IR_BROL: lua_assert(0); break;
2212
2213 /* Arithmetic ops. */
2214 case IR_ADD: case IR_ADDOV: asm_add(as, ir); break;
2215 case IR_SUB: case IR_SUBOV: asm_sub(as, ir); break;
2216 case IR_MUL: case IR_MULOV: asm_mul(as, ir); break;
2217 case IR_MOD: asm_callid(as, ir, IRCALL_lj_vm_modi); break;
2218 case IR_NEG: asm_neg(as, ir); break;
2219
2220#if LJ_SOFTFP
2221 case IR_DIV: case IR_POW: case IR_ABS:
2222 case IR_ATAN2: case IR_LDEXP: case IR_FPMATH: case IR_TOBIT:
2223 lua_assert(0); /* Unused for LJ_SOFTFP. */
2224 break;
2225#else
2226 case IR_DIV: asm_fparith(as, ir, ARMI_VDIV_D); break;
2227 case IR_POW: asm_callid(as, ir, IRCALL_lj_vm_powi); break;
2228 case IR_ABS: asm_fpunary(as, ir, ARMI_VABS_D); break;
2229 case IR_ATAN2: asm_callid(as, ir, IRCALL_atan2); break;
2230 case IR_LDEXP: asm_callid(as, ir, IRCALL_ldexp); break;
2231 case IR_FPMATH:
2232 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
2233 break;
2234 if (ir->op2 <= IRFPM_TRUNC)
2235 asm_callround(as, ir, ir->op2);
2236 else if (ir->op2 == IRFPM_SQRT)
2237 asm_fpunary(as, ir, ARMI_VSQRT_D);
2238 else
2239 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
2240 break;
2241 case IR_TOBIT: asm_tobit(as, ir); break;
2242#endif
2243
2244 case IR_MIN: asm_min_max(as, ir, CC_GT, CC_HI); break;
2245 case IR_MAX: asm_min_max(as, ir, CC_LT, CC_LO); break;
2246
2247 /* Memory references. */
2248 case IR_AREF: asm_aref(as, ir); break;
2249 case IR_HREF: asm_href(as, ir, 0); break;
2250 case IR_HREFK: asm_hrefk(as, ir); break;
2251 case IR_NEWREF: asm_newref(as, ir); break;
2252 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
2253 case IR_FREF: asm_fref(as, ir); break;
2254 case IR_STRREF: asm_strref(as, ir); break;
2255
2256 /* Loads and stores. */
2257 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2258 asm_ahuvload(as, ir);
2259 break;
2260 case IR_FLOAD: asm_fload(as, ir); break;
2261 case IR_XLOAD: asm_xload(as, ir); break;
2262 case IR_SLOAD: asm_sload(as, ir); break;
2263
2264 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
2265 case IR_FSTORE: asm_fstore(as, ir); break;
2266 case IR_XSTORE: asm_xstore(as, ir, 0); break;
2267
2268 /* Allocations. */
2269 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
2270 case IR_TNEW: asm_tnew(as, ir); break;
2271 case IR_TDUP: asm_tdup(as, ir); break;
2272 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
2273
2274 /* Write barriers. */
2275 case IR_TBAR: asm_tbar(as, ir); break;
2276 case IR_OBAR: asm_obar(as, ir); break;
2277
2278 /* Type conversions. */
2279 case IR_CONV: asm_conv(as, ir); break;
2280 case IR_TOSTR: asm_tostr(as, ir); break;
2281 case IR_STRTO: asm_strto(as, ir); break;
2282
2283 /* Calls. */
2284 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
2285 case IR_CALLXS: asm_callx(as, ir); break;
2286 case IR_CARG: break;
2287
2288 default:
2289 setintV(&as->J->errinfo, ir->o);
2290 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
2291 break;
2292 }
2293}
2294
2295/* -- Trace setup --------------------------------------------------------- */ 2145/* -- Trace setup --------------------------------------------------------- */
2296 2146
2297/* Ensure there are enough stack slots for call arguments. */ 2147/* Ensure there are enough stack slots for call arguments. */
2298static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) 2148static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
2299{ 2149{
2300 IRRef args[CCI_NARGS_MAX*2]; 2150 IRRef args[CCI_NARGS_MAX*2];
2301 uint32_t i, nargs = (int)CCI_NARGS(ci); 2151 uint32_t i, nargs = CCI_XNARGS(ci);
2302 int nslots = 0, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR, fprodd = 0; 2152 int nslots = 0, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR, fprodd = 0;
2303 asm_collectargs(as, ir, ci, args); 2153 asm_collectargs(as, ir, ci, args);
2304 for (i = 0; i < nargs; i++) { 2154 for (i = 0; i < nargs; i++) {
diff --git a/src/lj_asm_arm64.h b/src/lj_asm_arm64.h
new file mode 100644
index 00000000..328e4d77
--- /dev/null
+++ b/src/lj_asm_arm64.h
@@ -0,0 +1,2008 @@
1/*
2** ARM64 IR assembler (SSA IR -> machine code).
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4**
5** Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
6** Sponsored by Cisco Systems, Inc.
7*/
8
9/* -- Register allocator extensions --------------------------------------- */
10
11/* Allocate a register with a hint. */
12static Reg ra_hintalloc(ASMState *as, IRRef ref, Reg hint, RegSet allow)
13{
14 Reg r = IR(ref)->r;
15 if (ra_noreg(r)) {
16 if (!ra_hashint(r) && !iscrossref(as, ref))
17 ra_sethint(IR(ref)->r, hint); /* Propagate register hint. */
18 r = ra_allocref(as, ref, allow);
19 }
20 ra_noweak(as, r);
21 return r;
22}
23
24/* Allocate two source registers for three-operand instructions. */
25static Reg ra_alloc2(ASMState *as, IRIns *ir, RegSet allow)
26{
27 IRIns *irl = IR(ir->op1), *irr = IR(ir->op2);
28 Reg left = irl->r, right = irr->r;
29 if (ra_hasreg(left)) {
30 ra_noweak(as, left);
31 if (ra_noreg(right))
32 right = ra_allocref(as, ir->op2, rset_exclude(allow, left));
33 else
34 ra_noweak(as, right);
35 } else if (ra_hasreg(right)) {
36 ra_noweak(as, right);
37 left = ra_allocref(as, ir->op1, rset_exclude(allow, right));
38 } else if (ra_hashint(right)) {
39 right = ra_allocref(as, ir->op2, allow);
40 left = ra_alloc1(as, ir->op1, rset_exclude(allow, right));
41 } else {
42 left = ra_allocref(as, ir->op1, allow);
43 right = ra_alloc1(as, ir->op2, rset_exclude(allow, left));
44 }
45 return left | (right << 8);
46}
47
48/* -- Guard handling ------------------------------------------------------ */
49
50/* Setup all needed exit stubs. */
51static void asm_exitstub_setup(ASMState *as, ExitNo nexits)
52{
53 ExitNo i;
54 MCode *mxp = as->mctop;
55 if (mxp - (nexits + 3 + MCLIM_REDZONE) < as->mclim)
56 asm_mclimit(as);
57 /* 1: str lr,[sp]; bl ->vm_exit_handler; movz w0,traceno; bl <1; bl <1; ... */
58 for (i = nexits-1; (int32_t)i >= 0; i--)
59 *--mxp = A64I_BL|((-3-i)&0x03ffffffu);
60 *--mxp = A64I_MOVZw|A64F_U16(as->T->traceno);
61 mxp--;
62 *mxp = A64I_BL|(((MCode *)(void *)lj_vm_exit_handler-mxp)&0x03ffffffu);
63 *--mxp = A64I_STRx|A64F_D(RID_LR)|A64F_N(RID_SP);
64 as->mctop = mxp;
65}
66
67static MCode *asm_exitstub_addr(ASMState *as, ExitNo exitno)
68{
69 /* Keep this in-sync with exitstub_trace_addr(). */
70 return as->mctop + exitno + 3;
71}
72
73/* Emit conditional branch to exit for guard. */
74static void asm_guardcc(ASMState *as, A64CC cc)
75{
76 MCode *target = asm_exitstub_addr(as, as->snapno);
77 MCode *p = as->mcp;
78 if (LJ_UNLIKELY(p == as->invmcp)) {
79 as->loopinv = 1;
80 *p = A64I_B | ((target-p) & 0x03ffffffu);
81 emit_cond_branch(as, cc^1, p-1);
82 return;
83 }
84 emit_cond_branch(as, cc, target);
85}
86
87/* Emit test and branch instruction to exit for guard. */
88static void asm_guardtnb(ASMState *as, A64Ins ai, Reg r, uint32_t bit)
89{
90 MCode *target = asm_exitstub_addr(as, as->snapno);
91 MCode *p = as->mcp;
92 if (LJ_UNLIKELY(p == as->invmcp)) {
93 as->loopinv = 1;
94 *p = A64I_B | ((target-p) & 0x03ffffffu);
95 emit_tnb(as, ai^0x01000000u, r, bit, p-1);
96 return;
97 }
98 emit_tnb(as, ai, r, bit, target);
99}
100
101/* Emit compare and branch instruction to exit for guard. */
102static void asm_guardcnb(ASMState *as, A64Ins ai, Reg r)
103{
104 MCode *target = asm_exitstub_addr(as, as->snapno);
105 MCode *p = as->mcp;
106 if (LJ_UNLIKELY(p == as->invmcp)) {
107 as->loopinv = 1;
108 *p = A64I_B | ((target-p) & 0x03ffffffu);
109 emit_cnb(as, ai^0x01000000u, r, p-1);
110 return;
111 }
112 emit_cnb(as, ai, r, target);
113}
114
115/* -- Operand fusion ------------------------------------------------------ */
116
117/* Limit linear search to this distance. Avoids O(n^2) behavior. */
118#define CONFLICT_SEARCH_LIM 31
119
120static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
121{
122 if (irref_isk(ref)) {
123 IRIns *ir = IR(ref);
124 if (ir->o == IR_KNULL || !irt_is64(ir->t)) {
125 *k = ir->i;
126 return 1;
127 } else if (checki32((int64_t)ir_k64(ir)->u64)) {
128 *k = (int32_t)ir_k64(ir)->u64;
129 return 1;
130 }
131 }
132 return 0;
133}
134
135/* Check if there's no conflicting instruction between curins and ref. */
136static int noconflict(ASMState *as, IRRef ref, IROp conflict)
137{
138 IRIns *ir = as->ir;
139 IRRef i = as->curins;
140 if (i > ref + CONFLICT_SEARCH_LIM)
141 return 0; /* Give up, ref is too far away. */
142 while (--i > ref)
143 if (ir[i].o == conflict)
144 return 0; /* Conflict found. */
145 return 1; /* Ok, no conflict. */
146}
147
148/* Fuse the array base of colocated arrays. */
149static int32_t asm_fuseabase(ASMState *as, IRRef ref)
150{
151 IRIns *ir = IR(ref);
152 if (ir->o == IR_TNEW && ir->op1 <= LJ_MAX_COLOSIZE &&
153 !neverfuse(as) && noconflict(as, ref, IR_NEWREF))
154 return (int32_t)sizeof(GCtab);
155 return 0;
156}
157
158#define FUSE_REG 0x40000000
159
160/* Fuse array/hash/upvalue reference into register+offset operand. */
161static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow,
162 A64Ins ins)
163{
164 IRIns *ir = IR(ref);
165 if (ra_noreg(ir->r)) {
166 if (ir->o == IR_AREF) {
167 if (mayfuse(as, ref)) {
168 if (irref_isk(ir->op2)) {
169 IRRef tab = IR(ir->op1)->op1;
170 int32_t ofs = asm_fuseabase(as, tab);
171 IRRef refa = ofs ? tab : ir->op1;
172 ofs += 8*IR(ir->op2)->i;
173 if (emit_checkofs(ins, ofs)) {
174 *ofsp = ofs;
175 return ra_alloc1(as, refa, allow);
176 }
177 } else {
178 Reg base = ra_alloc1(as, ir->op1, allow);
179 *ofsp = FUSE_REG|ra_alloc1(as, ir->op2, rset_exclude(allow, base));
180 return base;
181 }
182 }
183 } else if (ir->o == IR_HREFK) {
184 if (mayfuse(as, ref)) {
185 int32_t ofs = (int32_t)(IR(ir->op2)->op2 * sizeof(Node));
186 if (emit_checkofs(ins, ofs)) {
187 *ofsp = ofs;
188 return ra_alloc1(as, ir->op1, allow);
189 }
190 }
191 } else if (ir->o == IR_UREFC) {
192 if (irref_isk(ir->op1)) {
193 GCfunc *fn = ir_kfunc(IR(ir->op1));
194 GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv;
195 int64_t ofs = glofs(as, &uv->tv);
196 if (emit_checkofs(ins, ofs)) {
197 *ofsp = (int32_t)ofs;
198 return RID_GL;
199 }
200 }
201 }
202 }
203 *ofsp = 0;
204 return ra_alloc1(as, ref, allow);
205}
206
207/* Fuse m operand into arithmetic/logic instructions. */
208static uint32_t asm_fuseopm(ASMState *as, A64Ins ai, IRRef ref, RegSet allow)
209{
210 IRIns *ir = IR(ref);
211 if (ra_hasreg(ir->r)) {
212 ra_noweak(as, ir->r);
213 return A64F_M(ir->r);
214 } else if (irref_isk(ref)) {
215 uint32_t m;
216 int64_t k = get_k64val(ir);
217 if ((ai & 0x1f000000) == 0x0a000000)
218 m = emit_isk13(k, irt_is64(ir->t));
219 else
220 m = emit_isk12(k);
221 if (m)
222 return m;
223 } else if (mayfuse(as, ref)) {
224 if ((ir->o >= IR_BSHL && ir->o <= IR_BSAR && irref_isk(ir->op2)) ||
225 (ir->o == IR_ADD && ir->op1 == ir->op2)) {
226 A64Shift sh = ir->o == IR_BSHR ? A64SH_LSR :
227 ir->o == IR_BSAR ? A64SH_ASR : A64SH_LSL;
228 int shift = ir->o == IR_ADD ? 1 :
229 (IR(ir->op2)->i & (irt_is64(ir->t) ? 63 : 31));
230 IRIns *irl = IR(ir->op1);
231 if (sh == A64SH_LSL &&
232 irl->o == IR_CONV &&
233 irl->op2 == ((IRT_I64<<IRCONV_DSH)|IRT_INT|IRCONV_SEXT) &&
234 shift <= 4 &&
235 canfuse(as, irl)) {
236 Reg m = ra_alloc1(as, irl->op1, allow);
237 return A64F_M(m) | A64F_EXSH(A64EX_SXTW, shift);
238 } else {
239 Reg m = ra_alloc1(as, ir->op1, allow);
240 return A64F_M(m) | A64F_SH(sh, shift);
241 }
242 } else if (ir->o == IR_CONV &&
243 ir->op2 == ((IRT_I64<<IRCONV_DSH)|IRT_INT|IRCONV_SEXT)) {
244 Reg m = ra_alloc1(as, ir->op1, allow);
245 return A64F_M(m) | A64F_EX(A64EX_SXTW);
246 }
247 }
248 return A64F_M(ra_allocref(as, ref, allow));
249}
250
251/* Fuse XLOAD/XSTORE reference into load/store operand. */
252static void asm_fusexref(ASMState *as, A64Ins ai, Reg rd, IRRef ref,
253 RegSet allow)
254{
255 IRIns *ir = IR(ref);
256 Reg base;
257 int32_t ofs = 0;
258 if (ra_noreg(ir->r) && canfuse(as, ir)) {
259 if (ir->o == IR_ADD) {
260 if (asm_isk32(as, ir->op2, &ofs) && emit_checkofs(ai, ofs)) {
261 ref = ir->op1;
262 } else {
263 Reg rn, rm;
264 IRRef lref = ir->op1, rref = ir->op2;
265 IRIns *irl = IR(lref);
266 if (mayfuse(as, irl->op1)) {
267 unsigned int shift = 4;
268 if (irl->o == IR_BSHL && irref_isk(irl->op2)) {
269 shift = (IR(irl->op2)->i & 63);
270 } else if (irl->o == IR_ADD && irl->op1 == irl->op2) {
271 shift = 1;
272 }
273 if ((ai >> 30) == shift) {
274 lref = irl->op1;
275 irl = IR(lref);
276 ai |= A64I_LS_SH;
277 }
278 }
279 if (irl->o == IR_CONV &&
280 irl->op2 == ((IRT_I64<<IRCONV_DSH)|IRT_INT|IRCONV_SEXT) &&
281 canfuse(as, irl)) {
282 lref = irl->op1;
283 ai |= A64I_LS_SXTWx;
284 } else {
285 ai |= A64I_LS_LSLx;
286 }
287 rm = ra_alloc1(as, lref, allow);
288 rn = ra_alloc1(as, rref, rset_exclude(allow, rm));
289 emit_dnm(as, (ai^A64I_LS_R), rd, rn, rm);
290 return;
291 }
292 } else if (ir->o == IR_STRREF) {
293 if (asm_isk32(as, ir->op2, &ofs)) {
294 ref = ir->op1;
295 } else if (asm_isk32(as, ir->op1, &ofs)) {
296 ref = ir->op2;
297 } else {
298 Reg rn = ra_alloc1(as, ir->op1, allow);
299 IRIns *irr = IR(ir->op2);
300 uint32_t m;
301 if (irr+1 == ir && !ra_used(irr) &&
302 irr->o == IR_ADD && irref_isk(irr->op2)) {
303 ofs = sizeof(GCstr) + IR(irr->op2)->i;
304 if (emit_checkofs(ai, ofs)) {
305 Reg rm = ra_alloc1(as, irr->op1, rset_exclude(allow, rn));
306 m = A64F_M(rm) | A64F_EX(A64EX_SXTW);
307 goto skipopm;
308 }
309 }
310 m = asm_fuseopm(as, 0, ir->op2, rset_exclude(allow, rn));
311 ofs = sizeof(GCstr);
312 skipopm:
313 emit_lso(as, ai, rd, rd, ofs);
314 emit_dn(as, A64I_ADDx^m, rd, rn);
315 return;
316 }
317 ofs += sizeof(GCstr);
318 if (!emit_checkofs(ai, ofs)) {
319 Reg rn = ra_alloc1(as, ref, allow);
320 Reg rm = ra_allock(as, ofs, rset_exclude(allow, rn));
321 emit_dnm(as, (ai^A64I_LS_R)|A64I_LS_UXTWx, rd, rn, rm);
322 return;
323 }
324 }
325 }
326 base = ra_alloc1(as, ref, allow);
327 emit_lso(as, ai, (rd & 31), base, ofs);
328}
329
330/* Fuse FP multiply-add/sub. */
331static int asm_fusemadd(ASMState *as, IRIns *ir, A64Ins ai, A64Ins air)
332{
333 IRRef lref = ir->op1, rref = ir->op2;
334 IRIns *irm;
335 if (lref != rref &&
336 ((mayfuse(as, lref) && (irm = IR(lref), irm->o == IR_MUL) &&
337 ra_noreg(irm->r)) ||
338 (mayfuse(as, rref) && (irm = IR(rref), irm->o == IR_MUL) &&
339 (rref = lref, ai = air, ra_noreg(irm->r))))) {
340 Reg dest = ra_dest(as, ir, RSET_FPR);
341 Reg add = ra_hintalloc(as, rref, dest, RSET_FPR);
342 Reg left = ra_alloc2(as, irm,
343 rset_exclude(rset_exclude(RSET_FPR, dest), add));
344 Reg right = (left >> 8); left &= 255;
345 emit_dnma(as, ai, (dest & 31), (left & 31), (right & 31), (add & 31));
346 return 1;
347 }
348 return 0;
349}
350
351/* Fuse BAND + BSHL/BSHR into UBFM. */
352static int asm_fuseandshift(ASMState *as, IRIns *ir)
353{
354 IRIns *irl = IR(ir->op1);
355 lua_assert(ir->o == IR_BAND);
356 if (canfuse(as, irl) && irref_isk(ir->op2)) {
357 uint64_t mask = get_k64val(IR(ir->op2));
358 if (irref_isk(irl->op2) && (irl->o == IR_BSHR || irl->o == IR_BSHL)) {
359 int32_t shmask = irt_is64(irl->t) ? 63 : 31;
360 int32_t shift = (IR(irl->op2)->i & shmask);
361 int32_t imms = shift;
362 if (irl->o == IR_BSHL) {
363 mask >>= shift;
364 shift = (shmask-shift+1) & shmask;
365 imms = 0;
366 }
367 if (mask && !((mask+1) & mask)) { /* Contiguous 1-bits at the bottom. */
368 Reg dest = ra_dest(as, ir, RSET_GPR);
369 Reg left = ra_alloc1(as, irl->op1, RSET_GPR);
370 A64Ins ai = shmask == 63 ? A64I_UBFMx : A64I_UBFMw;
371 imms += 63 - emit_clz64(mask);
372 if (imms > shmask) imms = shmask;
373 emit_dn(as, ai | A64F_IMMS(imms) | A64F_IMMR(shift), dest, left);
374 return 1;
375 }
376 }
377 }
378 return 0;
379}
380
381/* Fuse BOR(BSHL, BSHR) into EXTR/ROR. */
382static int asm_fuseorshift(ASMState *as, IRIns *ir)
383{
384 IRIns *irl = IR(ir->op1), *irr = IR(ir->op2);
385 lua_assert(ir->o == IR_BOR);
386 if (canfuse(as, irl) && canfuse(as, irr) &&
387 ((irl->o == IR_BSHR && irr->o == IR_BSHL) ||
388 (irl->o == IR_BSHL && irr->o == IR_BSHR))) {
389 if (irref_isk(irl->op2) && irref_isk(irr->op2)) {
390 IRRef lref = irl->op1, rref = irr->op1;
391 uint32_t lshift = IR(irl->op2)->i, rshift = IR(irr->op2)->i;
392 if (irl->o == IR_BSHR) { /* BSHR needs to be the right operand. */
393 uint32_t tmp2;
394 IRRef tmp1 = lref; lref = rref; rref = tmp1;
395 tmp2 = lshift; lshift = rshift; rshift = tmp2;
396 }
397 if (rshift + lshift == (irt_is64(ir->t) ? 64 : 32)) {
398 A64Ins ai = irt_is64(ir->t) ? A64I_EXTRx : A64I_EXTRw;
399 Reg dest = ra_dest(as, ir, RSET_GPR);
400 Reg left = ra_alloc1(as, lref, RSET_GPR);
401 Reg right = ra_alloc1(as, rref, rset_exclude(RSET_GPR, left));
402 emit_dnm(as, ai | A64F_IMMS(rshift), dest, left, right);
403 return 1;
404 }
405 }
406 }
407 return 0;
408}
409
410/* -- Calls --------------------------------------------------------------- */
411
412/* Generate a call to a C function. */
413static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
414{
415 uint32_t n, nargs = CCI_XNARGS(ci);
416 int32_t ofs = 0;
417 Reg gpr, fpr = REGARG_FIRSTFPR;
418 if ((void *)ci->func)
419 emit_call(as, (void *)ci->func);
420 for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++)
421 as->cost[gpr] = REGCOST(~0u, ASMREF_L);
422 gpr = REGARG_FIRSTGPR;
423 for (n = 0; n < nargs; n++) { /* Setup args. */
424 IRRef ref = args[n];
425 IRIns *ir = IR(ref);
426 if (ref) {
427 if (irt_isfp(ir->t)) {
428 if (fpr <= REGARG_LASTFPR) {
429 lua_assert(rset_test(as->freeset, fpr)); /* Must have been evicted. */
430 ra_leftov(as, fpr, ref);
431 fpr++;
432 } else {
433 Reg r = ra_alloc1(as, ref, RSET_FPR);
434 emit_spstore(as, ir, r, ofs);
435 ofs += 8;
436 }
437 } else {
438 if (gpr <= REGARG_LASTGPR) {
439 lua_assert(rset_test(as->freeset, gpr)); /* Must have been evicted. */
440 ra_leftov(as, gpr, ref);
441 gpr++;
442 } else {
443 Reg r = ra_alloc1(as, ref, RSET_GPR);
444 emit_spstore(as, ir, r, ofs);
445 ofs += 8;
446 }
447 }
448 }
449 }
450}
451
452/* Setup result reg/sp for call. Evict scratch regs. */
453static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
454{
455 RegSet drop = RSET_SCRATCH;
456 if (ra_hasreg(ir->r))
457 rset_clear(drop, ir->r); /* Dest reg handled below. */
458 ra_evictset(as, drop); /* Evictions must be performed first. */
459 if (ra_used(ir)) {
460 lua_assert(!irt_ispri(ir->t));
461 if (irt_isfp(ir->t)) {
462 if (ci->flags & CCI_CASTU64) {
463 Reg dest = ra_dest(as, ir, RSET_FPR) & 31;
464 emit_dn(as, irt_isnum(ir->t) ? A64I_FMOV_D_R : A64I_FMOV_S_R,
465 dest, RID_RET);
466 } else {
467 ra_destreg(as, ir, RID_FPRET);
468 }
469 } else {
470 ra_destreg(as, ir, RID_RET);
471 }
472 }
473 UNUSED(ci);
474}
475
476static void asm_callx(ASMState *as, IRIns *ir)
477{
478 IRRef args[CCI_NARGS_MAX*2];
479 CCallInfo ci;
480 IRRef func;
481 IRIns *irf;
482 ci.flags = asm_callx_flags(as, ir);
483 asm_collectargs(as, ir, &ci, args);
484 asm_setupresult(as, ir, &ci);
485 func = ir->op2; irf = IR(func);
486 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); }
487 if (irref_isk(func)) { /* Call to constant address. */
488 ci.func = (ASMFunction)(ir_k64(irf)->u64);
489 } else { /* Need a non-argument register for indirect calls. */
490 Reg freg = ra_alloc1(as, func, RSET_RANGE(RID_X8, RID_MAX_GPR)-RSET_FIXED);
491 emit_n(as, A64I_BLR, freg);
492 ci.func = (ASMFunction)(void *)0;
493 }
494 asm_gencall(as, &ci, args);
495}
496
497/* -- Returns ------------------------------------------------------------- */
498
499/* Return to lower frame. Guard that it goes to the right spot. */
500static void asm_retf(ASMState *as, IRIns *ir)
501{
502 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
503 void *pc = ir_kptr(IR(ir->op2));
504 int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
505 as->topslot -= (BCReg)delta;
506 if ((int32_t)as->topslot < 0) as->topslot = 0;
507 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
508 /* Need to force a spill on REF_BASE now to update the stack slot. */
509 emit_lso(as, A64I_STRx, base, RID_SP, ra_spill(as, IR(REF_BASE)));
510 emit_setgl(as, base, jit_base);
511 emit_addptr(as, base, -8*delta);
512 asm_guardcc(as, CC_NE);
513 emit_nm(as, A64I_CMPx, RID_TMP,
514 ra_allock(as, i64ptr(pc), rset_exclude(RSET_GPR, base)));
515 emit_lso(as, A64I_LDRx, RID_TMP, base, -8);
516}
517
518/* -- Type conversions ---------------------------------------------------- */
519
520static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
521{
522 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
523 Reg dest = ra_dest(as, ir, RSET_GPR);
524 asm_guardcc(as, CC_NE);
525 emit_nm(as, A64I_FCMPd, (tmp & 31), (left & 31));
526 emit_dn(as, A64I_FCVT_F64_S32, (tmp & 31), dest);
527 emit_dn(as, A64I_FCVT_S32_F64, dest, (left & 31));
528}
529
530static void asm_tobit(ASMState *as, IRIns *ir)
531{
532 RegSet allow = RSET_FPR;
533 Reg left = ra_alloc1(as, ir->op1, allow);
534 Reg right = ra_alloc1(as, ir->op2, rset_clear(allow, left));
535 Reg tmp = ra_scratch(as, rset_clear(allow, right));
536 Reg dest = ra_dest(as, ir, RSET_GPR);
537 emit_dn(as, A64I_FMOV_R_S, dest, (tmp & 31));
538 emit_dnm(as, A64I_FADDd, (tmp & 31), (left & 31), (right & 31));
539}
540
541static void asm_conv(ASMState *as, IRIns *ir)
542{
543 IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK);
544 int st64 = (st == IRT_I64 || st == IRT_U64 || st == IRT_P64);
545 int stfp = (st == IRT_NUM || st == IRT_FLOAT);
546 IRRef lref = ir->op1;
547 lua_assert(irt_type(ir->t) != st);
548 if (irt_isfp(ir->t)) {
549 Reg dest = ra_dest(as, ir, RSET_FPR);
550 if (stfp) { /* FP to FP conversion. */
551 emit_dn(as, st == IRT_NUM ? A64I_FCVT_F32_F64 : A64I_FCVT_F64_F32,
552 (dest & 31), (ra_alloc1(as, lref, RSET_FPR) & 31));
553 } else { /* Integer to FP conversion. */
554 Reg left = ra_alloc1(as, lref, RSET_GPR);
555 A64Ins ai = irt_isfloat(ir->t) ?
556 (((IRT_IS64 >> st) & 1) ?
557 (st == IRT_I64 ? A64I_FCVT_F32_S64 : A64I_FCVT_F32_U64) :
558 (st == IRT_INT ? A64I_FCVT_F32_S32 : A64I_FCVT_F32_U32)) :
559 (((IRT_IS64 >> st) & 1) ?
560 (st == IRT_I64 ? A64I_FCVT_F64_S64 : A64I_FCVT_F64_U64) :
561 (st == IRT_INT ? A64I_FCVT_F64_S32 : A64I_FCVT_F64_U32));
562 emit_dn(as, ai, (dest & 31), left);
563 }
564 } else if (stfp) { /* FP to integer conversion. */
565 if (irt_isguard(ir->t)) {
566 /* Checked conversions are only supported from number to int. */
567 lua_assert(irt_isint(ir->t) && st == IRT_NUM);
568 asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR));
569 } else {
570 Reg left = ra_alloc1(as, lref, RSET_FPR);
571 Reg dest = ra_dest(as, ir, RSET_GPR);
572 A64Ins ai = irt_is64(ir->t) ?
573 (st == IRT_NUM ?
574 (irt_isi64(ir->t) ? A64I_FCVT_S64_F64 : A64I_FCVT_U64_F64) :
575 (irt_isi64(ir->t) ? A64I_FCVT_S64_F32 : A64I_FCVT_U64_F32)) :
576 (st == IRT_NUM ?
577 (irt_isint(ir->t) ? A64I_FCVT_S32_F64 : A64I_FCVT_U32_F64) :
578 (irt_isint(ir->t) ? A64I_FCVT_S32_F32 : A64I_FCVT_U32_F32));
579 emit_dn(as, ai, dest, (left & 31));
580 }
581 } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */
582 Reg dest = ra_dest(as, ir, RSET_GPR);
583 Reg left = ra_alloc1(as, lref, RSET_GPR);
584 A64Ins ai = st == IRT_I8 ? A64I_SXTBw :
585 st == IRT_U8 ? A64I_UXTBw :
586 st == IRT_I16 ? A64I_SXTHw : A64I_UXTHw;
587 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t));
588 emit_dn(as, ai, dest, left);
589 } else {
590 Reg dest = ra_dest(as, ir, RSET_GPR);
591 if (irt_is64(ir->t)) {
592 if (st64 || !(ir->op2 & IRCONV_SEXT)) {
593 /* 64/64 bit no-op (cast) or 32 to 64 bit zero extension. */
594 ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */
595 } else { /* 32 to 64 bit sign extension. */
596 Reg left = ra_alloc1(as, lref, RSET_GPR);
597 emit_dn(as, A64I_SXTW, dest, left);
598 }
599 } else {
600 if (st64) {
601 /* This is either a 32 bit reg/reg mov which zeroes the hiword
602 ** or a load of the loword from a 64 bit address.
603 */
604 Reg left = ra_alloc1(as, lref, RSET_GPR);
605 emit_dm(as, A64I_MOVw, dest, left);
606 } else { /* 32/32 bit no-op (cast). */
607 ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */
608 }
609 }
610 }
611}
612
613static void asm_strto(ASMState *as, IRIns *ir)
614{
615 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
616 IRRef args[2];
617 Reg dest = 0, tmp;
618 int destused = ra_used(ir);
619 int32_t ofs = 0;
620 ra_evictset(as, RSET_SCRATCH);
621 if (destused) {
622 if (ra_hasspill(ir->s)) {
623 ofs = sps_scale(ir->s);
624 destused = 0;
625 if (ra_hasreg(ir->r)) {
626 ra_free(as, ir->r);
627 ra_modified(as, ir->r);
628 emit_spload(as, ir, ir->r, ofs);
629 }
630 } else {
631 dest = ra_dest(as, ir, RSET_FPR);
632 }
633 }
634 if (destused)
635 emit_lso(as, A64I_LDRd, (dest & 31), RID_SP, 0);
636 asm_guardcnb(as, A64I_CBZ, RID_RET);
637 args[0] = ir->op1; /* GCstr *str */
638 args[1] = ASMREF_TMP1; /* TValue *n */
639 asm_gencall(as, ci, args);
640 tmp = ra_releasetmp(as, ASMREF_TMP1);
641 emit_opk(as, A64I_ADDx, tmp, RID_SP, ofs, RSET_GPR);
642}
643
644/* -- Memory references --------------------------------------------------- */
645
646/* Store tagged value for ref at base+ofs. */
647static void asm_tvstore64(ASMState *as, Reg base, int32_t ofs, IRRef ref)
648{
649 RegSet allow = rset_exclude(RSET_GPR, base);
650 IRIns *ir = IR(ref);
651 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t));
652 if (irref_isk(ref)) {
653 TValue k;
654 lj_ir_kvalue(as->J->L, &k, ir);
655 emit_lso(as, A64I_STRx, ra_allock(as, k.u64, allow), base, ofs);
656 } else {
657 Reg src = ra_alloc1(as, ref, allow);
658 rset_clear(allow, src);
659 if (irt_isinteger(ir->t)) {
660 Reg type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47, allow);
661 emit_lso(as, A64I_STRx, RID_TMP, base, ofs);
662 emit_dnm(as, A64I_ADDx | A64F_EX(A64EX_UXTW), RID_TMP, type, src);
663 } else {
664 Reg type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow);
665 emit_lso(as, A64I_STRx, RID_TMP, base, ofs);
666 emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 47), RID_TMP, src, type);
667 }
668 }
669}
670
671/* Get pointer to TValue. */
672static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
673{
674 IRIns *ir = IR(ref);
675 if (irt_isnum(ir->t)) {
676 if (irref_isk(ref)) {
677 /* Use the number constant itself as a TValue. */
678 ra_allockreg(as, i64ptr(ir_knum(ir)), dest);
679 } else {
680 /* Otherwise force a spill and use the spill slot. */
681 emit_opk(as, A64I_ADDx, dest, RID_SP, ra_spill(as, ir), RSET_GPR);
682 }
683 } else {
684 /* Otherwise use g->tmptv to hold the TValue. */
685 asm_tvstore64(as, dest, 0, ref);
686 ra_allockreg(as, i64ptr(&J2G(as->J)->tmptv), dest);
687 }
688}
689
690static void asm_aref(ASMState *as, IRIns *ir)
691{
692 Reg dest = ra_dest(as, ir, RSET_GPR);
693 Reg idx, base;
694 if (irref_isk(ir->op2)) {
695 IRRef tab = IR(ir->op1)->op1;
696 int32_t ofs = asm_fuseabase(as, tab);
697 IRRef refa = ofs ? tab : ir->op1;
698 uint32_t k = emit_isk12(ofs + 8*IR(ir->op2)->i);
699 if (k) {
700 base = ra_alloc1(as, refa, RSET_GPR);
701 emit_dn(as, A64I_ADDx^k, dest, base);
702 return;
703 }
704 }
705 base = ra_alloc1(as, ir->op1, RSET_GPR);
706 idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base));
707 emit_dnm(as, A64I_ADDx | A64F_EXSH(A64EX_UXTW, 3), dest, base, idx);
708}
709
710/* Inlined hash lookup. Specialized for key type and for const keys.
711** The equivalent C code is:
712** Node *n = hashkey(t, key);
713** do {
714** if (lj_obj_equal(&n->key, key)) return &n->val;
715** } while ((n = nextnode(n)));
716** return niltv(L);
717*/
718static void asm_href(ASMState *as, IRIns *ir, IROp merge)
719{
720 RegSet allow = RSET_GPR;
721 int destused = ra_used(ir);
722 Reg dest = ra_dest(as, ir, allow);
723 Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest));
724 Reg key = 0, tmp = RID_TMP;
725 IRRef refkey = ir->op2;
726 IRIns *irkey = IR(refkey);
727 int isk = irref_isk(ir->op2);
728 IRType1 kt = irkey->t;
729 uint32_t k = 0;
730 uint32_t khash;
731 MCLabel l_end, l_loop, l_next;
732 rset_clear(allow, tab);
733
734 if (!isk) {
735 key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow);
736 rset_clear(allow, key);
737 if (!irt_isstr(kt)) {
738 tmp = ra_scratch(as, allow);
739 rset_clear(allow, tmp);
740 }
741 } else if (irt_isnum(kt)) {
742 int64_t val = (int64_t)ir_knum(irkey)->u64;
743 if (!(k = emit_isk12(val))) {
744 key = ra_allock(as, val, allow);
745 rset_clear(allow, key);
746 }
747 } else if (!irt_ispri(kt)) {
748 if (!(k = emit_isk12(irkey->i))) {
749 key = ra_alloc1(as, refkey, allow);
750 rset_clear(allow, key);
751 }
752 }
753
754 /* Key not found in chain: jump to exit (if merged) or load niltv. */
755 l_end = emit_label(as);
756 as->invmcp = NULL;
757 if (merge == IR_NE)
758 asm_guardcc(as, CC_AL);
759 else if (destused)
760 emit_loada(as, dest, niltvg(J2G(as->J)));
761
762 /* Follow hash chain until the end. */
763 l_loop = --as->mcp;
764 emit_n(as, A64I_CMPx^A64I_K12^0, dest);
765 emit_lso(as, A64I_LDRx, dest, dest, offsetof(Node, next));
766 l_next = emit_label(as);
767
768 /* Type and value comparison. */
769 if (merge == IR_EQ)
770 asm_guardcc(as, CC_EQ);
771 else
772 emit_cond_branch(as, CC_EQ, l_end);
773
774 if (irt_isnum(kt)) {
775 if (isk) {
776 /* Assumes -0.0 is already canonicalized to +0.0. */
777 if (k)
778 emit_n(as, A64I_CMPx^k, tmp);
779 else
780 emit_nm(as, A64I_CMPx, key, tmp);
781 emit_lso(as, A64I_LDRx, tmp, dest, offsetof(Node, key.u64));
782 } else {
783 Reg tisnum = ra_allock(as, LJ_TISNUM << 15, allow);
784 Reg ftmp = ra_scratch(as, rset_exclude(RSET_FPR, key));
785 rset_clear(allow, tisnum);
786 emit_nm(as, A64I_FCMPd, key, ftmp);
787 emit_dn(as, A64I_FMOV_D_R, (ftmp & 31), (tmp & 31));
788 emit_cond_branch(as, CC_LO, l_next);
789 emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32), tisnum, tmp);
790 emit_lso(as, A64I_LDRx, tmp, dest, offsetof(Node, key.n));
791 }
792 } else if (irt_isaddr(kt)) {
793 Reg scr;
794 if (isk) {
795 int64_t kk = ((int64_t)irt_toitype(irkey->t) << 47) | irkey[1].tv.u64;
796 scr = ra_allock(as, kk, allow);
797 emit_nm(as, A64I_CMPx, scr, tmp);
798 emit_lso(as, A64I_LDRx, tmp, dest, offsetof(Node, key.u64));
799 } else {
800 scr = ra_scratch(as, allow);
801 emit_nm(as, A64I_CMPx, tmp, scr);
802 emit_lso(as, A64I_LDRx, scr, dest, offsetof(Node, key.u64));
803 }
804 rset_clear(allow, scr);
805 } else {
806 Reg type, scr;
807 lua_assert(irt_ispri(kt) && !irt_isnil(kt));
808 type = ra_allock(as, ~((int64_t)~irt_toitype(ir->t) << 47), allow);
809 scr = ra_scratch(as, rset_clear(allow, type));
810 rset_clear(allow, scr);
811 emit_nm(as, A64I_CMPw, scr, type);
812 emit_lso(as, A64I_LDRx, scr, dest, offsetof(Node, key));
813 }
814
815 *l_loop = A64I_BCC | A64F_S19(as->mcp - l_loop) | CC_NE;
816 if (!isk && irt_isaddr(kt)) {
817 Reg type = ra_allock(as, (int32_t)irt_toitype(kt), allow);
818 emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 47), tmp, key, type);
819 rset_clear(allow, type);
820 }
821 /* Load main position relative to tab->node into dest. */
822 khash = isk ? ir_khash(irkey) : 1;
823 if (khash == 0) {
824 emit_lso(as, A64I_LDRx, dest, tab, offsetof(GCtab, node));
825 } else {
826 emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 3), dest, tmp, dest);
827 emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 1), dest, dest, dest);
828 emit_lso(as, A64I_LDRx, tmp, tab, offsetof(GCtab, node));
829 if (isk) {
830 Reg tmphash = ra_allock(as, khash, allow);
831 emit_dnm(as, A64I_ANDw, dest, dest, tmphash);
832 emit_lso(as, A64I_LDRw, dest, tab, offsetof(GCtab, hmask));
833 } else if (irt_isstr(kt)) {
834 /* Fetch of str->hash is cheaper than ra_allock. */
835 emit_dnm(as, A64I_ANDw, dest, dest, tmp);
836 emit_lso(as, A64I_LDRw, tmp, key, offsetof(GCstr, hash));
837 emit_lso(as, A64I_LDRw, dest, tab, offsetof(GCtab, hmask));
838 } else { /* Must match with hash*() in lj_tab.c. */
839 emit_dnm(as, A64I_ANDw, dest, dest, tmp);
840 emit_lso(as, A64I_LDRw, tmp, tab, offsetof(GCtab, hmask));
841 emit_dnm(as, A64I_SUBw, dest, dest, tmp);
842 emit_dnm(as, A64I_EXTRw | (A64F_IMMS(32-HASH_ROT3)), tmp, tmp, tmp);
843 emit_dnm(as, A64I_EORw, dest, dest, tmp);
844 emit_dnm(as, A64I_EXTRw | (A64F_IMMS(32-HASH_ROT2)), dest, dest, dest);
845 emit_dnm(as, A64I_SUBw, tmp, tmp, dest);
846 emit_dnm(as, A64I_EXTRw | (A64F_IMMS(32-HASH_ROT1)), dest, dest, dest);
847 emit_dnm(as, A64I_EORw, tmp, tmp, dest);
848 if (irt_isnum(kt)) {
849 emit_dnm(as, A64I_ADDw, dest, dest, dest);
850 emit_dn(as, A64I_LSRx | A64F_IMMR(32)|A64F_IMMS(32), dest, dest);
851 emit_dm(as, A64I_MOVw, tmp, dest);
852 emit_dn(as, A64I_FMOV_R_D, dest, (key & 31));
853 } else {
854 checkmclim(as);
855 emit_dm(as, A64I_MOVw, tmp, key);
856 emit_dnm(as, A64I_EORw, dest, dest,
857 ra_allock(as, irt_toitype(kt) << 15, allow));
858 emit_dn(as, A64I_LSRx | A64F_IMMR(32)|A64F_IMMS(32), dest, dest);
859 emit_dm(as, A64I_MOVx, dest, key);
860 }
861 }
862 }
863}
864
865static void asm_hrefk(ASMState *as, IRIns *ir)
866{
867 IRIns *kslot = IR(ir->op2);
868 IRIns *irkey = IR(kslot->op1);
869 int32_t ofs = (int32_t)(kslot->op2 * sizeof(Node));
870 int32_t kofs = ofs + (int32_t)offsetof(Node, key);
871 int bigofs = !emit_checkofs(A64I_LDRx, ofs);
872 RegSet allow = RSET_GPR;
873 Reg dest = (ra_used(ir) || bigofs) ? ra_dest(as, ir, RSET_GPR) : RID_NONE;
874 Reg node = ra_alloc1(as, ir->op1, allow);
875 Reg key = ra_scratch(as, rset_clear(allow, node));
876 Reg idx = node;
877 uint64_t k;
878 lua_assert(ofs % sizeof(Node) == 0);
879 rset_clear(allow, key);
880 if (bigofs) {
881 idx = dest;
882 rset_clear(allow, dest);
883 kofs = (int32_t)offsetof(Node, key);
884 } else if (ra_hasreg(dest)) {
885 emit_opk(as, A64I_ADDx, dest, node, ofs, allow);
886 }
887 asm_guardcc(as, CC_NE);
888 if (irt_ispri(irkey->t)) {
889 k = ~((int64_t)~irt_toitype(irkey->t) << 47);
890 } else if (irt_isnum(irkey->t)) {
891 k = ir_knum(irkey)->u64;
892 } else {
893 k = ((uint64_t)irt_toitype(irkey->t) << 47) | (uint64_t)ir_kgc(irkey);
894 }
895 emit_nm(as, A64I_CMPx, key, ra_allock(as, k, allow));
896 emit_lso(as, A64I_LDRx, key, idx, kofs);
897 if (bigofs)
898 emit_opk(as, A64I_ADDx, dest, node, ofs, RSET_GPR);
899}
900
901static void asm_uref(ASMState *as, IRIns *ir)
902{
903 Reg dest = ra_dest(as, ir, RSET_GPR);
904 if (irref_isk(ir->op1)) {
905 GCfunc *fn = ir_kfunc(IR(ir->op1));
906 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
907 emit_lsptr(as, A64I_LDRx, dest, v);
908 } else {
909 Reg uv = ra_scratch(as, RSET_GPR);
910 Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
911 if (ir->o == IR_UREFC) {
912 asm_guardcc(as, CC_NE);
913 emit_n(as, (A64I_CMPx^A64I_K12) | A64F_U12(1), RID_TMP);
914 emit_opk(as, A64I_ADDx, dest, uv,
915 (int32_t)offsetof(GCupval, tv), RSET_GPR);
916 emit_lso(as, A64I_LDRB, RID_TMP, uv, (int32_t)offsetof(GCupval, closed));
917 } else {
918 emit_lso(as, A64I_LDRx, dest, uv, (int32_t)offsetof(GCupval, v));
919 }
920 emit_lso(as, A64I_LDRx, uv, func,
921 (int32_t)offsetof(GCfuncL, uvptr) + 8*(int32_t)(ir->op2 >> 8));
922 }
923}
924
925static void asm_fref(ASMState *as, IRIns *ir)
926{
927 UNUSED(as); UNUSED(ir);
928 lua_assert(!ra_used(ir));
929}
930
931static void asm_strref(ASMState *as, IRIns *ir)
932{
933 RegSet allow = RSET_GPR;
934 Reg dest = ra_dest(as, ir, allow);
935 Reg base = ra_alloc1(as, ir->op1, allow);
936 IRIns *irr = IR(ir->op2);
937 int32_t ofs = sizeof(GCstr);
938 uint32_t m;
939 rset_clear(allow, base);
940 if (irref_isk(ir->op2) && (m = emit_isk12(ofs + irr->i))) {
941 emit_dn(as, A64I_ADDx^m, dest, base);
942 } else {
943 emit_dn(as, (A64I_ADDx^A64I_K12) | A64F_U12(ofs), dest, dest);
944 emit_dnm(as, A64I_ADDx, dest, base, ra_alloc1(as, ir->op2, allow));
945 }
946}
947
948/* -- Loads and stores ---------------------------------------------------- */
949
950static A64Ins asm_fxloadins(IRIns *ir)
951{
952 switch (irt_type(ir->t)) {
953 case IRT_I8: return A64I_LDRB ^ A64I_LS_S;
954 case IRT_U8: return A64I_LDRB;
955 case IRT_I16: return A64I_LDRH ^ A64I_LS_S;
956 case IRT_U16: return A64I_LDRH;
957 case IRT_NUM: return A64I_LDRd;
958 case IRT_FLOAT: return A64I_LDRs;
959 default: return irt_is64(ir->t) ? A64I_LDRx : A64I_LDRw;
960 }
961}
962
963static A64Ins asm_fxstoreins(IRIns *ir)
964{
965 switch (irt_type(ir->t)) {
966 case IRT_I8: case IRT_U8: return A64I_STRB;
967 case IRT_I16: case IRT_U16: return A64I_STRH;
968 case IRT_NUM: return A64I_STRd;
969 case IRT_FLOAT: return A64I_STRs;
970 default: return irt_is64(ir->t) ? A64I_STRx : A64I_STRw;
971 }
972}
973
974static void asm_fload(ASMState *as, IRIns *ir)
975{
976 Reg dest = ra_dest(as, ir, RSET_GPR);
977 Reg idx;
978 A64Ins ai = asm_fxloadins(ir);
979 int32_t ofs;
980 if (ir->op1 == REF_NIL) {
981 idx = RID_GL;
982 ofs = (ir->op2 << 2) - GG_OFS(g);
983 } else {
984 idx = ra_alloc1(as, ir->op1, RSET_GPR);
985 if (ir->op2 == IRFL_TAB_ARRAY) {
986 ofs = asm_fuseabase(as, ir->op1);
987 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */
988 emit_dn(as, (A64I_ADDx^A64I_K12) | A64F_U12(ofs), dest, idx);
989 return;
990 }
991 }
992 ofs = field_ofs[ir->op2];
993 }
994 emit_lso(as, ai, (dest & 31), idx, ofs);
995}
996
997static void asm_fstore(ASMState *as, IRIns *ir)
998{
999 if (ir->r != RID_SINK) {
1000 Reg src = ra_alloc1(as, ir->op2, RSET_GPR);
1001 IRIns *irf = IR(ir->op1);
1002 Reg idx = ra_alloc1(as, irf->op1, rset_exclude(RSET_GPR, src));
1003 int32_t ofs = field_ofs[irf->op2];
1004 emit_lso(as, asm_fxstoreins(ir), (src & 31), idx, ofs);
1005 }
1006}
1007
1008static void asm_xload(ASMState *as, IRIns *ir)
1009{
1010 Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
1011 lua_assert(!(ir->op2 & IRXLOAD_UNALIGNED));
1012 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR);
1013}
1014
1015static void asm_xstore(ASMState *as, IRIns *ir)
1016{
1017 if (ir->r != RID_SINK) {
1018 Reg src = ra_alloc1(as, ir->op2, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
1019 asm_fusexref(as, asm_fxstoreins(ir), src, ir->op1,
1020 rset_exclude(RSET_GPR, src));
1021 }
1022}
1023
1024static void asm_ahuvload(ASMState *as, IRIns *ir)
1025{
1026 Reg idx, tmp, type;
1027 int32_t ofs = 0;
1028 RegSet gpr = RSET_GPR, allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR;
1029 lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) ||
1030 irt_isint(ir->t));
1031 if (ra_used(ir)) {
1032 Reg dest = ra_dest(as, ir, allow);
1033 tmp = irt_isnum(ir->t) ? ra_scratch(as, rset_clear(gpr, dest)) : dest;
1034 if (irt_isaddr(ir->t)) {
1035 emit_dn(as, A64I_ANDx^emit_isk13(LJ_GCVMASK, 1), dest, dest);
1036 } else if (irt_isnum(ir->t)) {
1037 emit_dn(as, A64I_FMOV_D_R, (dest & 31), tmp);
1038 } else if (irt_isint(ir->t)) {
1039 emit_dm(as, A64I_MOVw, dest, dest);
1040 }
1041 } else {
1042 tmp = ra_scratch(as, gpr);
1043 }
1044 type = ra_scratch(as, rset_clear(gpr, tmp));
1045 idx = asm_fuseahuref(as, ir->op1, &ofs, rset_clear(gpr, type), A64I_LDRx);
1046 /* Always do the type check, even if the load result is unused. */
1047 asm_guardcc(as, irt_isnum(ir->t) ? CC_LS : CC_NE);
1048 if (irt_type(ir->t) >= IRT_NUM) {
1049 lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t));
1050 emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32),
1051 ra_allock(as, LJ_TISNUM << 15, rset_exclude(gpr, idx)), tmp);
1052 } else if (irt_isaddr(ir->t)) {
1053 emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(-irt_toitype(ir->t)), type);
1054 emit_dn(as, A64I_ASRx | A64F_IMMR(47), type, tmp);
1055 } else if (irt_isnil(ir->t)) {
1056 emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(1), tmp);
1057 } else {
1058 emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32),
1059 ra_allock(as, (irt_toitype(ir->t) << 15) | 0x7fff, allow), tmp);
1060 }
1061 if (ofs & FUSE_REG)
1062 emit_dnm(as, (A64I_LDRx^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, tmp, idx, (ofs & 31));
1063 else
1064 emit_lso(as, A64I_LDRx, tmp, idx, ofs);
1065}
1066
1067static void asm_ahustore(ASMState *as, IRIns *ir)
1068{
1069 if (ir->r != RID_SINK) {
1070 RegSet allow = RSET_GPR;
1071 Reg idx, src = RID_NONE, tmp = RID_TMP, type = RID_NONE;
1072 int32_t ofs = 0;
1073 if (irt_isnum(ir->t)) {
1074 src = ra_alloc1(as, ir->op2, RSET_FPR);
1075 idx = asm_fuseahuref(as, ir->op1, &ofs, allow, A64I_STRd);
1076 if (ofs & FUSE_REG)
1077 emit_dnm(as, (A64I_STRd^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, (src & 31), idx, (ofs &31));
1078 else
1079 emit_lso(as, A64I_STRd, (src & 31), idx, ofs);
1080 } else {
1081 if (!irt_ispri(ir->t)) {
1082 src = ra_alloc1(as, ir->op2, allow);
1083 rset_clear(allow, src);
1084 if (irt_isinteger(ir->t))
1085 type = ra_allock(as, (int64_t)LJ_TISNUM << 47, allow);
1086 else
1087 type = ra_allock(as, irt_toitype(ir->t), allow);
1088 } else {
1089 tmp = type = ra_allock(as, ~((int64_t)~irt_toitype(ir->t)<<47), allow);
1090 }
1091 idx = asm_fuseahuref(as, ir->op1, &ofs, rset_exclude(allow, type),
1092 A64I_STRx);
1093 if (ofs & FUSE_REG)
1094 emit_dnm(as, (A64I_STRx^A64I_LS_R)|A64I_LS_UXTWx|A64I_LS_SH, tmp, idx, (ofs & 31));
1095 else
1096 emit_lso(as, A64I_STRx, tmp, idx, ofs);
1097 if (ra_hasreg(src)) {
1098 if (irt_isinteger(ir->t)) {
1099 emit_dnm(as, A64I_ADDx | A64F_EX(A64EX_UXTW), tmp, type, src);
1100 } else {
1101 emit_dnm(as, A64I_ADDx | A64F_SH(A64SH_LSL, 47), tmp, src, type);
1102 }
1103 }
1104 }
1105 }
1106}
1107
1108static void asm_sload(ASMState *as, IRIns *ir)
1109{
1110 int32_t ofs = 8*((int32_t)ir->op1-2);
1111 IRType1 t = ir->t;
1112 Reg dest = RID_NONE, base;
1113 RegSet allow = RSET_GPR;
1114 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */
1115 lua_assert(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK));
1116 if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) {
1117 dest = ra_scratch(as, RSET_FPR);
1118 asm_tointg(as, ir, dest);
1119 t.irt = IRT_NUM; /* Continue with a regular number type check. */
1120 } else if (ra_used(ir)) {
1121 Reg tmp = RID_NONE;
1122 if ((ir->op2 & IRSLOAD_CONVERT))
1123 tmp = ra_scratch(as, irt_isint(t) ? RSET_FPR : RSET_GPR);
1124 lua_assert((irt_isnum(t)) || irt_isint(t) || irt_isaddr(t));
1125 dest = ra_dest(as, ir, irt_isnum(t) ? RSET_FPR : allow);
1126 base = ra_alloc1(as, REF_BASE, rset_clear(allow, dest));
1127 if (irt_isaddr(t)) {
1128 emit_dn(as, A64I_ANDx^emit_isk13(LJ_GCVMASK, 1), dest, dest);
1129 } else if ((ir->op2 & IRSLOAD_CONVERT)) {
1130 if (irt_isint(t)) {
1131 emit_dn(as, A64I_FCVT_S32_F64, dest, (tmp & 31));
1132 /* If value is already loaded for type check, move it to FPR. */
1133 if ((ir->op2 & IRSLOAD_TYPECHECK))
1134 emit_dn(as, A64I_FMOV_D_R, (tmp & 31), dest);
1135 else
1136 dest = tmp;
1137 t.irt = IRT_NUM; /* Check for original type. */
1138 } else {
1139 emit_dn(as, A64I_FCVT_F64_S32, (dest & 31), tmp);
1140 dest = tmp;
1141 t.irt = IRT_INT; /* Check for original type. */
1142 }
1143 } else if (irt_isint(t) && (ir->op2 & IRSLOAD_TYPECHECK)) {
1144 emit_dm(as, A64I_MOVw, dest, dest);
1145 }
1146 goto dotypecheck;
1147 }
1148 base = ra_alloc1(as, REF_BASE, allow);
1149dotypecheck:
1150 rset_clear(allow, base);
1151 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1152 Reg tmp;
1153 if (ra_hasreg(dest) && rset_test(RSET_GPR, dest)) {
1154 tmp = dest;
1155 } else {
1156 tmp = ra_scratch(as, allow);
1157 rset_clear(allow, tmp);
1158 }
1159 if (irt_isnum(t) && !(ir->op2 & IRSLOAD_CONVERT))
1160 emit_dn(as, A64I_FMOV_D_R, (dest & 31), tmp);
1161 /* Need type check, even if the load result is unused. */
1162 asm_guardcc(as, irt_isnum(t) ? CC_LS : CC_NE);
1163 if (irt_type(t) >= IRT_NUM) {
1164 lua_assert(irt_isinteger(t) || irt_isnum(t));
1165 emit_nm(as, A64I_CMPx | A64F_SH(A64SH_LSR, 32),
1166 ra_allock(as, LJ_TISNUM << 15, allow), tmp);
1167 } else if (irt_isnil(t)) {
1168 emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(1), tmp);
1169 } else if (irt_ispri(t)) {
1170 emit_nm(as, A64I_CMPx,
1171 ra_allock(as, ~((int64_t)~irt_toitype(t) << 47) , allow), tmp);
1172 } else {
1173 Reg type = ra_scratch(as, allow);
1174 emit_n(as, (A64I_CMNx^A64I_K12) | A64F_U12(-irt_toitype(t)), type);
1175 emit_dn(as, A64I_ASRx | A64F_IMMR(47), type, tmp);
1176 }
1177 emit_lso(as, A64I_LDRx, tmp, base, ofs);
1178 return;
1179 }
1180 if (ra_hasreg(dest)) {
1181 emit_lso(as, irt_isnum(t) ? A64I_LDRd :
1182 (irt_isint(t) ? A64I_LDRw : A64I_LDRx), (dest & 31), base, ofs);
1183 }
1184}
1185
1186/* -- Allocations --------------------------------------------------------- */
1187
1188#if LJ_HASFFI
1189static void asm_cnew(ASMState *as, IRIns *ir)
1190{
1191 CTState *cts = ctype_ctsG(J2G(as->J));
1192 CTypeID id = (CTypeID)IR(ir->op1)->i;
1193 CTSize sz;
1194 CTInfo info = lj_ctype_info(cts, id, &sz);
1195 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1196 IRRef args[4];
1197 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1198 lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));
1199
1200 as->gcsteps++;
1201 asm_setupresult(as, ir, ci); /* GCcdata * */
1202 /* Initialize immutable cdata object. */
1203 if (ir->o == IR_CNEWI) {
1204 int32_t ofs = sizeof(GCcdata);
1205 Reg r = ra_alloc1(as, ir->op2, allow);
1206 lua_assert(sz == 4 || sz == 8);
1207 emit_lso(as, sz == 8 ? A64I_STRx : A64I_STRw, r, RID_RET, ofs);
1208 } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */
1209 ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
1210 args[0] = ASMREF_L; /* lua_State *L */
1211 args[1] = ir->op1; /* CTypeID id */
1212 args[2] = ir->op2; /* CTSize sz */
1213 args[3] = ASMREF_TMP1; /* CTSize align */
1214 asm_gencall(as, ci, args);
1215 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
1216 return;
1217 }
1218
1219 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */
1220 {
1221 Reg r = (id < 65536) ? RID_X1 : ra_allock(as, id, allow);
1222 emit_lso(as, A64I_STRB, RID_TMP, RID_RET, offsetof(GCcdata, gct));
1223 emit_lso(as, A64I_STRH, r, RID_RET, offsetof(GCcdata, ctypeid));
1224 emit_d(as, A64I_MOVZw | A64F_U16(~LJ_TCDATA), RID_TMP);
1225 if (id < 65536) emit_d(as, A64I_MOVZw | A64F_U16(id), RID_X1);
1226 }
1227 args[0] = ASMREF_L; /* lua_State *L */
1228 args[1] = ASMREF_TMP1; /* MSize size */
1229 asm_gencall(as, ci, args);
1230 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)),
1231 ra_releasetmp(as, ASMREF_TMP1));
1232}
1233#else
1234#define asm_cnew(as, ir) ((void)0)
1235#endif
1236
1237/* -- Write barriers ------------------------------------------------------ */
1238
1239static void asm_tbar(ASMState *as, IRIns *ir)
1240{
1241 Reg tab = ra_alloc1(as, ir->op1, RSET_GPR);
1242 Reg link = ra_scratch(as, rset_exclude(RSET_GPR, tab));
1243 Reg gr = ra_allock(as, i64ptr(J2G(as->J)),
1244 rset_exclude(rset_exclude(RSET_GPR, tab), link));
1245 Reg mark = RID_TMP;
1246 MCLabel l_end = emit_label(as);
1247 emit_lso(as, A64I_STRx, link, tab, (int32_t)offsetof(GCtab, gclist));
1248 emit_lso(as, A64I_STRB, mark, tab, (int32_t)offsetof(GCtab, marked));
1249 emit_lso(as, A64I_STRx, tab, gr,
1250 (int32_t)offsetof(global_State, gc.grayagain));
1251 emit_dn(as, A64I_ANDw^emit_isk13(~LJ_GC_BLACK, 0), mark, mark);
1252 emit_lso(as, A64I_LDRx, link, gr,
1253 (int32_t)offsetof(global_State, gc.grayagain));
1254 emit_cond_branch(as, CC_EQ, l_end);
1255 emit_n(as, A64I_TSTw^emit_isk13(LJ_GC_BLACK, 0), mark);
1256 emit_lso(as, A64I_LDRB, mark, tab, (int32_t)offsetof(GCtab, marked));
1257}
1258
1259static void asm_obar(ASMState *as, IRIns *ir)
1260{
1261 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_barrieruv];
1262 IRRef args[2];
1263 MCLabel l_end;
1264 RegSet allow = RSET_GPR;
1265 Reg obj, val, tmp;
1266 /* No need for other object barriers (yet). */
1267 lua_assert(IR(ir->op1)->o == IR_UREFC);
1268 ra_evictset(as, RSET_SCRATCH);
1269 l_end = emit_label(as);
1270 args[0] = ASMREF_TMP1; /* global_State *g */
1271 args[1] = ir->op1; /* TValue *tv */
1272 asm_gencall(as, ci, args);
1273 ra_allockreg(as, i64ptr(J2G(as->J)), ra_releasetmp(as, ASMREF_TMP1) );
1274 obj = IR(ir->op1)->r;
1275 tmp = ra_scratch(as, rset_exclude(allow, obj));
1276 emit_cond_branch(as, CC_EQ, l_end);
1277 emit_n(as, A64I_TSTw^emit_isk13(LJ_GC_BLACK, 0), tmp);
1278 emit_cond_branch(as, CC_EQ, l_end);
1279 emit_n(as, A64I_TSTw^emit_isk13(LJ_GC_WHITES, 0), RID_TMP);
1280 val = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, obj));
1281 emit_lso(as, A64I_LDRB, tmp, obj,
1282 (int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv));
1283 emit_lso(as, A64I_LDRB, RID_TMP, val, (int32_t)offsetof(GChead, marked));
1284}
1285
1286/* -- Arithmetic and logic operations ------------------------------------- */
1287
1288static void asm_fparith(ASMState *as, IRIns *ir, A64Ins ai)
1289{
1290 Reg dest = ra_dest(as, ir, RSET_FPR);
1291 Reg right, left = ra_alloc2(as, ir, RSET_FPR);
1292 right = (left >> 8); left &= 255;
1293 emit_dnm(as, ai, (dest & 31), (left & 31), (right & 31));
1294}
1295
1296static void asm_fpunary(ASMState *as, IRIns *ir, A64Ins ai)
1297{
1298 Reg dest = ra_dest(as, ir, RSET_FPR);
1299 Reg left = ra_hintalloc(as, ir->op1, dest, RSET_FPR);
1300 emit_dn(as, ai, (dest & 31), (left & 31));
1301}
1302
1303static void asm_fpmath(ASMState *as, IRIns *ir)
1304{
1305 IRFPMathOp fpm = (IRFPMathOp)ir->op2;
1306 if (fpm == IRFPM_SQRT) {
1307 asm_fpunary(as, ir, A64I_FSQRTd);
1308 } else if (fpm <= IRFPM_TRUNC) {
1309 asm_fpunary(as, ir, fpm == IRFPM_FLOOR ? A64I_FRINTMd :
1310 fpm == IRFPM_CEIL ? A64I_FRINTPd : A64I_FRINTZd);
1311 } else if (fpm == IRFPM_EXP2 && asm_fpjoin_pow(as, ir)) {
1312 return;
1313 } else {
1314 asm_callid(as, ir, IRCALL_lj_vm_floor + fpm);
1315 }
1316}
1317
1318static int asm_swapops(ASMState *as, IRRef lref, IRRef rref)
1319{
1320 IRIns *ir;
1321 if (irref_isk(rref))
1322 return 0; /* Don't swap constants to the left. */
1323 if (irref_isk(lref))
1324 return 1; /* But swap constants to the right. */
1325 ir = IR(rref);
1326 if ((ir->o >= IR_BSHL && ir->o <= IR_BSAR) ||
1327 (ir->o == IR_ADD && ir->op1 == ir->op2) ||
1328 (ir->o == IR_CONV && ir->op2 == ((IRT_I64<<IRCONV_DSH)|IRT_INT|IRCONV_SEXT)))
1329 return 0; /* Don't swap fusable operands to the left. */
1330 ir = IR(lref);
1331 if ((ir->o >= IR_BSHL && ir->o <= IR_BSAR) ||
1332 (ir->o == IR_ADD && ir->op1 == ir->op2) ||
1333 (ir->o == IR_CONV && ir->op2 == ((IRT_I64<<IRCONV_DSH)|IRT_INT|IRCONV_SEXT)))
1334 return 1; /* But swap fusable operands to the right. */
1335 return 0; /* Otherwise don't swap. */
1336}
1337
1338static void asm_intop(ASMState *as, IRIns *ir, A64Ins ai)
1339{
1340 IRRef lref = ir->op1, rref = ir->op2;
1341 Reg left, dest = ra_dest(as, ir, RSET_GPR);
1342 uint32_t m;
1343 if ((ai & ~A64I_S) != A64I_SUBw && asm_swapops(as, lref, rref)) {
1344 IRRef tmp = lref; lref = rref; rref = tmp;
1345 }
1346 left = ra_hintalloc(as, lref, dest, RSET_GPR);
1347 if (irt_is64(ir->t)) ai |= A64I_X;
1348 m = asm_fuseopm(as, ai, rref, rset_exclude(RSET_GPR, left));
1349 if (irt_isguard(ir->t)) { /* For IR_ADDOV etc. */
1350 asm_guardcc(as, CC_VS);
1351 ai |= A64I_S;
1352 }
1353 emit_dn(as, ai^m, dest, left);
1354}
1355
1356static void asm_intop_s(ASMState *as, IRIns *ir, A64Ins ai)
1357{
1358 if (as->flagmcp == as->mcp) { /* Drop cmp r, #0. */
1359 as->flagmcp = NULL;
1360 as->mcp++;
1361 ai |= A64I_S;
1362 }
1363 asm_intop(as, ir, ai);
1364}
1365
1366static void asm_intneg(ASMState *as, IRIns *ir)
1367{
1368 Reg dest = ra_dest(as, ir, RSET_GPR);
1369 Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1370 emit_dm(as, irt_is64(ir->t) ? A64I_NEGx : A64I_NEGw, dest, left);
1371}
1372
1373/* NYI: use add/shift for MUL(OV) with constants. FOLD only does 2^k. */
1374static void asm_intmul(ASMState *as, IRIns *ir)
1375{
1376 Reg dest = ra_dest(as, ir, RSET_GPR);
1377 Reg left = ra_alloc1(as, ir->op1, rset_exclude(RSET_GPR, dest));
1378 Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1379 if (irt_isguard(ir->t)) { /* IR_MULOV */
1380 asm_guardcc(as, CC_NE);
1381 emit_dm(as, A64I_MOVw, dest, dest); /* Zero-extend. */
1382 emit_nm(as, A64I_CMPw | A64F_SH(A64SH_ASR, 31), RID_TMP, dest);
1383 emit_dn(as, A64I_ASRx | A64F_IMMR(32), RID_TMP, dest);
1384 emit_dnm(as, A64I_SMULL, dest, right, left);
1385 } else {
1386 emit_dnm(as, irt_is64(ir->t) ? A64I_MULx : A64I_MULw, dest, left, right);
1387 }
1388}
1389
1390static void asm_add(ASMState *as, IRIns *ir)
1391{
1392 if (irt_isnum(ir->t)) {
1393 if (!asm_fusemadd(as, ir, A64I_FMADDd, A64I_FMADDd))
1394 asm_fparith(as, ir, A64I_FADDd);
1395 return;
1396 }
1397 asm_intop_s(as, ir, A64I_ADDw);
1398}
1399
1400static void asm_sub(ASMState *as, IRIns *ir)
1401{
1402 if (irt_isnum(ir->t)) {
1403 if (!asm_fusemadd(as, ir, A64I_FNMSUBd, A64I_FMSUBd))
1404 asm_fparith(as, ir, A64I_FSUBd);
1405 return;
1406 }
1407 asm_intop_s(as, ir, A64I_SUBw);
1408}
1409
1410static void asm_mul(ASMState *as, IRIns *ir)
1411{
1412 if (irt_isnum(ir->t)) {
1413 asm_fparith(as, ir, A64I_FMULd);
1414 return;
1415 }
1416 asm_intmul(as, ir);
1417}
1418
1419static void asm_div(ASMState *as, IRIns *ir)
1420{
1421#if LJ_HASFFI
1422 if (!irt_isnum(ir->t))
1423 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
1424 IRCALL_lj_carith_divu64);
1425 else
1426#endif
1427 asm_fparith(as, ir, A64I_FDIVd);
1428}
1429
1430static void asm_pow(ASMState *as, IRIns *ir)
1431{
1432#if LJ_HASFFI
1433 if (!irt_isnum(ir->t))
1434 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
1435 IRCALL_lj_carith_powu64);
1436 else
1437#endif
1438 asm_callid(as, ir, IRCALL_lj_vm_powi);
1439}
1440
1441#define asm_addov(as, ir) asm_add(as, ir)
1442#define asm_subov(as, ir) asm_sub(as, ir)
1443#define asm_mulov(as, ir) asm_mul(as, ir)
1444
1445#define asm_abs(as, ir) asm_fpunary(as, ir, A64I_FABS)
1446#define asm_atan2(as, ir) asm_callid(as, ir, IRCALL_atan2)
1447#define asm_ldexp(as, ir) asm_callid(as, ir, IRCALL_ldexp)
1448
1449static void asm_mod(ASMState *as, IRIns *ir)
1450{
1451#if LJ_HASFFI
1452 if (!irt_isint(ir->t))
1453 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
1454 IRCALL_lj_carith_modu64);
1455 else
1456#endif
1457 asm_callid(as, ir, IRCALL_lj_vm_modi);
1458}
1459
1460static void asm_neg(ASMState *as, IRIns *ir)
1461{
1462 if (irt_isnum(ir->t)) {
1463 asm_fpunary(as, ir, A64I_FNEGd);
1464 return;
1465 }
1466 asm_intneg(as, ir);
1467}
1468
1469static void asm_band(ASMState *as, IRIns *ir)
1470{
1471 A64Ins ai = A64I_ANDw;
1472 if (asm_fuseandshift(as, ir))
1473 return;
1474 if (as->flagmcp == as->mcp) {
1475 /* Try to drop cmp r, #0. */
1476 as->flagmcp = NULL;
1477 as->mcp++;
1478 ai = A64I_ANDSw;
1479 }
1480 asm_intop(as, ir, ai);
1481}
1482
1483static void asm_borbxor(ASMState *as, IRIns *ir, A64Ins ai)
1484{
1485 IRRef lref = ir->op1, rref = ir->op2;
1486 IRIns *irl = IR(lref), *irr = IR(rref);
1487 if ((canfuse(as, irl) && irl->o == IR_BNOT && !irref_isk(rref)) ||
1488 (canfuse(as, irr) && irr->o == IR_BNOT && !irref_isk(lref))) {
1489 Reg left, dest = ra_dest(as, ir, RSET_GPR);
1490 uint32_t m;
1491 if (irl->o == IR_BNOT) {
1492 IRRef tmp = lref; lref = rref; rref = tmp;
1493 }
1494 left = ra_alloc1(as, lref, RSET_GPR);
1495 ai |= A64I_ON;
1496 if (irt_is64(ir->t)) ai |= A64I_X;
1497 m = asm_fuseopm(as, ai, IR(rref)->op1, rset_exclude(RSET_GPR, left));
1498 emit_dn(as, ai^m, dest, left);
1499 } else {
1500 asm_intop(as, ir, ai);
1501 }
1502}
1503
1504static void asm_bor(ASMState *as, IRIns *ir)
1505{
1506 if (asm_fuseorshift(as, ir))
1507 return;
1508 asm_borbxor(as, ir, A64I_ORRw);
1509}
1510
1511#define asm_bxor(as, ir) asm_borbxor(as, ir, A64I_EORw)
1512
1513static void asm_bnot(ASMState *as, IRIns *ir)
1514{
1515 A64Ins ai = A64I_MVNw;
1516 Reg dest = ra_dest(as, ir, RSET_GPR);
1517 uint32_t m = asm_fuseopm(as, ai, ir->op1, RSET_GPR);
1518 if (irt_is64(ir->t)) ai |= A64I_X;
1519 emit_d(as, ai^m, dest);
1520}
1521
1522static void asm_bswap(ASMState *as, IRIns *ir)
1523{
1524 Reg dest = ra_dest(as, ir, RSET_GPR);
1525 Reg left = ra_alloc1(as, ir->op1, RSET_GPR);
1526 emit_dn(as, irt_is64(ir->t) ? A64I_REVx : A64I_REVw, dest, left);
1527}
1528
1529static void asm_bitshift(ASMState *as, IRIns *ir, A64Ins ai, A64Shift sh)
1530{
1531 int32_t shmask = irt_is64(ir->t) ? 63 : 31;
1532 if (irref_isk(ir->op2)) { /* Constant shifts. */
1533 Reg left, dest = ra_dest(as, ir, RSET_GPR);
1534 int32_t shift = (IR(ir->op2)->i & shmask);
1535 IRIns *irl = IR(ir->op1);
1536 if (shmask == 63) ai += A64I_UBFMx - A64I_UBFMw;
1537
1538 /* Fuse BSHL + BSHR/BSAR into UBFM/SBFM aka UBFX/SBFX/UBFIZ/SBFIZ. */
1539 if ((sh == A64SH_LSR || sh == A64SH_ASR) && canfuse(as, irl)) {
1540 if (irl->o == IR_BSHL && irref_isk(irl->op2)) {
1541 int32_t shift2 = (IR(irl->op2)->i & shmask);
1542 shift = ((shift - shift2) & shmask);
1543 shmask -= shift2;
1544 ir = irl;
1545 }
1546 }
1547
1548 left = ra_alloc1(as, ir->op1, RSET_GPR);
1549 switch (sh) {
1550 case A64SH_LSL:
1551 emit_dn(as, ai | A64F_IMMS(shmask-shift) |
1552 A64F_IMMR((shmask-shift+1)&shmask), dest, left);
1553 break;
1554 case A64SH_LSR: case A64SH_ASR:
1555 emit_dn(as, ai | A64F_IMMS(shmask) | A64F_IMMR(shift), dest, left);
1556 break;
1557 case A64SH_ROR:
1558 emit_dnm(as, ai | A64F_IMMS(shift), dest, left, left);
1559 break;
1560 }
1561 } else { /* Variable-length shifts. */
1562 Reg dest = ra_dest(as, ir, RSET_GPR);
1563 Reg left = ra_alloc1(as, ir->op1, RSET_GPR);
1564 Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1565 emit_dnm(as, (shmask == 63 ? A64I_SHRx : A64I_SHRw) | A64F_BSH(sh), dest, left, right);
1566 }
1567}
1568
1569#define asm_bshl(as, ir) asm_bitshift(as, ir, A64I_UBFMw, A64SH_LSL)
1570#define asm_bshr(as, ir) asm_bitshift(as, ir, A64I_UBFMw, A64SH_LSR)
1571#define asm_bsar(as, ir) asm_bitshift(as, ir, A64I_SBFMw, A64SH_ASR)
1572#define asm_bror(as, ir) asm_bitshift(as, ir, A64I_EXTRw, A64SH_ROR)
1573#define asm_brol(as, ir) lua_assert(0)
1574
1575static void asm_intmin_max(ASMState *as, IRIns *ir, A64CC cc)
1576{
1577 Reg dest = ra_dest(as, ir, RSET_GPR);
1578 Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1579 Reg right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1580 emit_dnm(as, A64I_CSELw|A64F_CC(cc), dest, left, right);
1581 emit_nm(as, A64I_CMPw, left, right);
1582}
1583
1584static void asm_fpmin_max(ASMState *as, IRIns *ir, A64CC fcc)
1585{
1586 Reg dest = (ra_dest(as, ir, RSET_FPR) & 31);
1587 Reg right, left = ra_alloc2(as, ir, RSET_FPR);
1588 right = ((left >> 8) & 31); left &= 31;
1589 emit_dnm(as, A64I_FCSELd | A64F_CC(fcc), dest, left, right);
1590 emit_nm(as, A64I_FCMPd, left, right);
1591}
1592
1593static void asm_min_max(ASMState *as, IRIns *ir, A64CC cc, A64CC fcc)
1594{
1595 if (irt_isnum(ir->t))
1596 asm_fpmin_max(as, ir, fcc);
1597 else
1598 asm_intmin_max(as, ir, cc);
1599}
1600
1601#define asm_max(as, ir) asm_min_max(as, ir, CC_GT, CC_HI)
1602#define asm_min(as, ir) asm_min_max(as, ir, CC_LT, CC_LO)
1603
1604/* -- Comparisons --------------------------------------------------------- */
1605
1606/* Map of comparisons to flags. ORDER IR. */
1607static const uint8_t asm_compmap[IR_ABC+1] = {
1608 /* op FP swp int cc FP cc */
1609 /* LT */ CC_GE + (CC_HS << 4),
1610 /* GE x */ CC_LT + (CC_HI << 4),
1611 /* LE */ CC_GT + (CC_HI << 4),
1612 /* GT x */ CC_LE + (CC_HS << 4),
1613 /* ULT x */ CC_HS + (CC_LS << 4),
1614 /* UGE */ CC_LO + (CC_LO << 4),
1615 /* ULE x */ CC_HI + (CC_LO << 4),
1616 /* UGT */ CC_LS + (CC_LS << 4),
1617 /* EQ */ CC_NE + (CC_NE << 4),
1618 /* NE */ CC_EQ + (CC_EQ << 4),
1619 /* ABC */ CC_LS + (CC_LS << 4) /* Same as UGT. */
1620};
1621
1622/* FP comparisons. */
1623static void asm_fpcomp(ASMState *as, IRIns *ir)
1624{
1625 Reg left, right;
1626 A64Ins ai;
1627 int swp = ((ir->o ^ (ir->o >> 2)) & ~(ir->o >> 3) & 1);
1628 if (!swp && irref_isk(ir->op2) && ir_knum(IR(ir->op2))->u64 == 0) {
1629 left = (ra_alloc1(as, ir->op1, RSET_FPR) & 31);
1630 right = 0;
1631 ai = A64I_FCMPZd;
1632 } else {
1633 left = ra_alloc2(as, ir, RSET_FPR);
1634 if (swp) {
1635 right = (left & 31); left = ((left >> 8) & 31);
1636 } else {
1637 right = ((left >> 8) & 31); left &= 31;
1638 }
1639 ai = A64I_FCMPd;
1640 }
1641 asm_guardcc(as, (asm_compmap[ir->o] >> 4));
1642 emit_nm(as, ai, left, right);
1643}
1644
1645/* Integer comparisons. */
1646static void asm_intcomp(ASMState *as, IRIns *ir)
1647{
1648 A64CC oldcc, cc = (asm_compmap[ir->o] & 15);
1649 A64Ins ai = irt_is64(ir->t) ? A64I_CMPx : A64I_CMPw;
1650 IRRef lref = ir->op1, rref = ir->op2;
1651 Reg left;
1652 uint32_t m;
1653 int cmpprev0 = 0;
1654 lua_assert(irt_is64(ir->t) || irt_isint(ir->t) ||
1655 irt_isu32(ir->t) || irt_isaddr(ir->t) || irt_isu8(ir->t));
1656 if (asm_swapops(as, lref, rref)) {
1657 IRRef tmp = lref; lref = rref; rref = tmp;
1658 if (cc >= CC_GE) cc ^= 7; /* LT <-> GT, LE <-> GE */
1659 else if (cc > CC_NE) cc ^= 11; /* LO <-> HI, LS <-> HS */
1660 }
1661 oldcc = cc;
1662 if (irref_isk(rref) && get_k64val(IR(rref)) == 0) {
1663 IRIns *irl = IR(lref);
1664 if (cc == CC_GE) cc = CC_PL;
1665 else if (cc == CC_LT) cc = CC_MI;
1666 else if (cc > CC_NE) goto nocombine; /* Other conds don't work with tst. */
1667 cmpprev0 = (irl+1 == ir);
1668 /* Combine and-cmp-bcc into tbz/tbnz or and-cmp into tst. */
1669 if (cmpprev0 && irl->o == IR_BAND && !ra_used(irl)) {
1670 IRRef blref = irl->op1, brref = irl->op2;
1671 uint32_t m2 = 0;
1672 Reg bleft;
1673 if (asm_swapops(as, blref, brref)) {
1674 Reg tmp = blref; blref = brref; brref = tmp;
1675 }
1676 if (irref_isk(brref)) {
1677 uint64_t k = get_k64val(IR(brref));
1678 if (k && !(k & (k-1)) && (cc == CC_EQ || cc == CC_NE)) {
1679 asm_guardtnb(as, cc == CC_EQ ? A64I_TBZ : A64I_TBNZ,
1680 ra_alloc1(as, blref, RSET_GPR), emit_ctz64(k));
1681 return;
1682 }
1683 m2 = emit_isk13(k, irt_is64(irl->t));
1684 }
1685 bleft = ra_alloc1(as, blref, RSET_GPR);
1686 ai = (irt_is64(irl->t) ? A64I_TSTx : A64I_TSTw);
1687 if (!m2)
1688 m2 = asm_fuseopm(as, ai, brref, rset_exclude(RSET_GPR, bleft));
1689 asm_guardcc(as, cc);
1690 emit_n(as, ai^m2, bleft);
1691 return;
1692 }
1693 if (cc == CC_EQ || cc == CC_NE) {
1694 /* Combine cmp-bcc into cbz/cbnz. */
1695 ai = cc == CC_EQ ? A64I_CBZ : A64I_CBNZ;
1696 if (irt_is64(ir->t)) ai |= A64I_X;
1697 asm_guardcnb(as, ai, ra_alloc1(as, lref, RSET_GPR));
1698 return;
1699 }
1700 }
1701nocombine:
1702 left = ra_alloc1(as, lref, RSET_GPR);
1703 m = asm_fuseopm(as, ai, rref, rset_exclude(RSET_GPR, left));
1704 asm_guardcc(as, cc);
1705 emit_n(as, ai^m, left);
1706 /* Signed comparison with zero and referencing previous ins? */
1707 if (cmpprev0 && (oldcc <= CC_NE || oldcc >= CC_GE))
1708 as->flagmcp = as->mcp; /* Allow elimination of the compare. */
1709}
1710
1711static void asm_comp(ASMState *as, IRIns *ir)
1712{
1713 if (irt_isnum(ir->t))
1714 asm_fpcomp(as, ir);
1715 else
1716 asm_intcomp(as, ir);
1717}
1718
1719#define asm_equal(as, ir) asm_comp(as, ir)
1720
1721/* -- Support for 64 bit ops in 32 bit mode ------------------------------- */
1722
1723/* Hiword op of a split 64 bit op. Previous op must be the loword op. */
1724static void asm_hiop(ASMState *as, IRIns *ir)
1725{
1726 UNUSED(as); UNUSED(ir); lua_assert(0); /* Unused on 64 bit. */
1727}
1728
1729/* -- Profiling ----------------------------------------------------------- */
1730
1731static void asm_prof(ASMState *as, IRIns *ir)
1732{
1733 uint32_t k = emit_isk13(HOOK_PROFILE, 0);
1734 lua_assert(k != 0);
1735 UNUSED(ir);
1736 asm_guardcc(as, CC_NE);
1737 emit_n(as, A64I_TSTw^k, RID_TMP);
1738 emit_lsptr(as, A64I_LDRB, RID_TMP, (void *)&J2G(as->J)->hookmask);
1739}
1740
1741/* -- Stack handling ------------------------------------------------------ */
1742
1743/* Check Lua stack size for overflow. Use exit handler as fallback. */
1744static void asm_stack_check(ASMState *as, BCReg topslot,
1745 IRIns *irp, RegSet allow, ExitNo exitno)
1746{
1747 Reg pbase;
1748 uint32_t k;
1749 if (irp) {
1750 if (!ra_hasspill(irp->s)) {
1751 pbase = irp->r;
1752 lua_assert(ra_hasreg(pbase));
1753 } else if (allow) {
1754 pbase = rset_pickbot(allow);
1755 } else {
1756 pbase = RID_RET;
1757 emit_lso(as, A64I_LDRx, RID_RET, RID_SP, 0); /* Restore temp register. */
1758 }
1759 } else {
1760 pbase = RID_BASE;
1761 }
1762 emit_cond_branch(as, CC_LS, asm_exitstub_addr(as, exitno));
1763 k = emit_isk12((8*topslot));
1764 lua_assert(k);
1765 emit_n(as, A64I_CMPx^k, RID_TMP);
1766 emit_dnm(as, A64I_SUBx, RID_TMP, RID_TMP, pbase);
1767 emit_lso(as, A64I_LDRx, RID_TMP, RID_TMP,
1768 (int32_t)offsetof(lua_State, maxstack));
1769 if (irp) { /* Must not spill arbitrary registers in head of side trace. */
1770 if (ra_hasspill(irp->s))
1771 emit_lso(as, A64I_LDRx, pbase, RID_SP, sps_scale(irp->s));
1772 emit_lso(as, A64I_LDRx, RID_TMP, RID_GL, glofs(as, &J2G(as->J)->cur_L));
1773 if (ra_hasspill(irp->s) && !allow)
1774 emit_lso(as, A64I_STRx, RID_RET, RID_SP, 0); /* Save temp register. */
1775 } else {
1776 emit_getgl(as, RID_TMP, cur_L);
1777 }
1778}
1779
1780/* Restore Lua stack from on-trace state. */
1781static void asm_stack_restore(ASMState *as, SnapShot *snap)
1782{
1783 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1784#ifdef LUA_USE_ASSERT
1785 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2];
1786#endif
1787 MSize n, nent = snap->nent;
1788 /* Store the value of all modified slots to the Lua stack. */
1789 for (n = 0; n < nent; n++) {
1790 SnapEntry sn = map[n];
1791 BCReg s = snap_slot(sn);
1792 int32_t ofs = 8*((int32_t)s-1-LJ_FR2);
1793 IRRef ref = snap_ref(sn);
1794 IRIns *ir = IR(ref);
1795 if ((sn & SNAP_NORESTORE))
1796 continue;
1797 if (irt_isnum(ir->t)) {
1798 Reg src = ra_alloc1(as, ref, RSET_FPR);
1799 emit_lso(as, A64I_STRd, (src & 31), RID_BASE, ofs);
1800 } else {
1801 asm_tvstore64(as, RID_BASE, ofs, ref);
1802 }
1803 checkmclim(as);
1804 }
1805 lua_assert(map + nent == flinks);
1806}
1807
1808/* -- GC handling --------------------------------------------------------- */
1809
1810/* Check GC threshold and do one or more GC steps. */
1811static void asm_gc_check(ASMState *as)
1812{
1813 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_gc_step_jit];
1814 IRRef args[2];
1815 MCLabel l_end;
1816 Reg tmp1, tmp2;
1817 ra_evictset(as, RSET_SCRATCH);
1818 l_end = emit_label(as);
1819 /* Exit trace if in GCSatomic or GCSfinalize. Avoids syncing GC objects. */
1820 asm_guardcnb(as, A64I_CBNZ, RID_RET); /* Assumes asm_snap_prep() is done. */
1821 args[0] = ASMREF_TMP1; /* global_State *g */
1822 args[1] = ASMREF_TMP2; /* MSize steps */
1823 asm_gencall(as, ci, args);
1824 tmp1 = ra_releasetmp(as, ASMREF_TMP1);
1825 tmp2 = ra_releasetmp(as, ASMREF_TMP2);
1826 emit_loadi(as, tmp2, as->gcsteps);
1827 /* Jump around GC step if GC total < GC threshold. */
1828 emit_cond_branch(as, CC_LS, l_end);
1829 emit_nm(as, A64I_CMPx, RID_TMP, tmp2);
1830 emit_lso(as, A64I_LDRx, tmp2, tmp1,
1831 (int32_t)offsetof(global_State, gc.threshold));
1832 emit_lso(as, A64I_LDRx, RID_TMP, tmp1,
1833 (int32_t)offsetof(global_State, gc.total));
1834 ra_allockreg(as, i64ptr(J2G(as->J)), tmp1);
1835 as->gcsteps = 0;
1836 checkmclim(as);
1837}
1838
1839/* -- Loop handling ------------------------------------------------------- */
1840
1841/* Fixup the loop branch. */
1842static void asm_loop_fixup(ASMState *as)
1843{
1844 MCode *p = as->mctop;
1845 MCode *target = as->mcp;
1846 if (as->loopinv) { /* Inverted loop branch? */
1847 uint32_t mask = (p[-2] & 0x7e000000) == 0x36000000 ? 0x3fffu : 0x7ffffu;
1848 ptrdiff_t delta = target - (p - 2);
1849 /* asm_guard* already inverted the bcc/tnb/cnb and patched the final b. */
1850 p[-2] |= ((uint32_t)delta & mask) << 5;
1851 } else {
1852 ptrdiff_t delta = target - (p - 1);
1853 p[-1] = A64I_B | ((uint32_t)(delta) & 0x03ffffffu);
1854 }
1855}
1856
1857/* -- Head of trace ------------------------------------------------------- */
1858
1859/* Reload L register from g->cur_L. */
1860static void asm_head_lreg(ASMState *as)
1861{
1862 IRIns *ir = IR(ASMREF_L);
1863 if (ra_used(ir)) {
1864 Reg r = ra_dest(as, ir, RSET_GPR);
1865 emit_getgl(as, r, cur_L);
1866 ra_evictk(as);
1867 }
1868}
1869
1870/* Coalesce BASE register for a root trace. */
1871static void asm_head_root_base(ASMState *as)
1872{
1873 IRIns *ir;
1874 asm_head_lreg(as);
1875 ir = IR(REF_BASE);
1876 if (ra_hasreg(ir->r) && (rset_test(as->modset, ir->r) || irt_ismarked(ir->t)))
1877 ra_spill(as, ir);
1878 ra_destreg(as, ir, RID_BASE);
1879}
1880
1881/* Coalesce BASE register for a side trace. */
1882static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow)
1883{
1884 IRIns *ir;
1885 asm_head_lreg(as);
1886 ir = IR(REF_BASE);
1887 if (ra_hasreg(ir->r) && (rset_test(as->modset, ir->r) || irt_ismarked(ir->t)))
1888 ra_spill(as, ir);
1889 if (ra_hasspill(irp->s)) {
1890 rset_clear(allow, ra_dest(as, ir, allow));
1891 } else {
1892 Reg r = irp->r;
1893 lua_assert(ra_hasreg(r));
1894 rset_clear(allow, r);
1895 if (r != ir->r && !rset_test(as->freeset, r))
1896 ra_restore(as, regcost_ref(as->cost[r]));
1897 ra_destreg(as, ir, r);
1898 }
1899 return allow;
1900}
1901
1902/* -- Tail of trace ------------------------------------------------------- */
1903
1904/* Fixup the tail code. */
1905static void asm_tail_fixup(ASMState *as, TraceNo lnk)
1906{
1907 MCode *p = as->mctop;
1908 MCode *target;
1909 /* Undo the sp adjustment in BC_JLOOP when exiting to the interpreter. */
1910 int32_t spadj = as->T->spadjust + (lnk ? 0 : sps_scale(SPS_FIXED));
1911 if (spadj == 0) {
1912 *--p = A64I_NOP;
1913 as->mctop = p;
1914 } else {
1915 /* Patch stack adjustment. */
1916 uint32_t k = emit_isk12(spadj);
1917 lua_assert(k);
1918 p[-2] = (A64I_ADDx^k) | A64F_D(RID_SP) | A64F_N(RID_SP);
1919 }
1920 /* Patch exit branch. */
1921 target = lnk ? traceref(as->J, lnk)->mcode : (MCode *)lj_vm_exit_interp;
1922 p[-1] = A64I_B | (((target-p)+1)&0x03ffffffu);
1923}
1924
1925/* Prepare tail of code. */
1926static void asm_tail_prep(ASMState *as)
1927{
1928 MCode *p = as->mctop - 1; /* Leave room for exit branch. */
1929 if (as->loopref) {
1930 as->invmcp = as->mcp = p;
1931 } else {
1932 as->mcp = p-1; /* Leave room for stack pointer adjustment. */
1933 as->invmcp = NULL;
1934 }
1935 *p = 0; /* Prevent load/store merging. */
1936}
1937
1938/* -- Trace setup --------------------------------------------------------- */
1939
1940/* Ensure there are enough stack slots for call arguments. */
1941static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
1942{
1943 IRRef args[CCI_NARGS_MAX*2];
1944 uint32_t i, nargs = CCI_XNARGS(ci);
1945 int nslots = 0, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR;
1946 asm_collectargs(as, ir, ci, args);
1947 for (i = 0; i < nargs; i++) {
1948 if (args[i] && irt_isfp(IR(args[i])->t)) {
1949 if (nfpr > 0) nfpr--; else nslots += 2;
1950 } else {
1951 if (ngpr > 0) ngpr--; else nslots += 2;
1952 }
1953 }
1954 if (nslots > as->evenspill) /* Leave room for args in stack slots. */
1955 as->evenspill = nslots;
1956 return REGSP_HINT(RID_RET);
1957}
1958
1959static void asm_setup_target(ASMState *as)
1960{
1961 /* May need extra exit for asm_stack_check on side traces. */
1962 asm_exitstub_setup(as, as->T->nsnap + (as->parent ? 1 : 0));
1963}
1964
1965/* -- Trace patching ------------------------------------------------------ */
1966
1967/* Patch exit jumps of existing machine code to a new target. */
1968void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target)
1969{
1970 MCode *p = T->mcode;
1971 MCode *pe = (MCode *)((char *)p + T->szmcode);
1972 MCode *cstart = NULL, *cend = p;
1973 MCode *mcarea = lj_mcode_patch(J, p, 0);
1974 MCode *px = exitstub_trace_addr(T, exitno);
1975 for (; p < pe; p++) {
1976 /* Look for exitstub branch, replace with branch to target. */
1977 uint32_t ins = *p;
1978 if ((ins & 0xff000000u) == 0x54000000u &&
1979 ((ins ^ ((px-p)<<5)) & 0x00ffffe0u) == 0) {
1980 /* Patch bcc exitstub. */
1981 *p = (ins & 0xff00001fu) | (((target-p)<<5) & 0x00ffffe0u);
1982 cend = p+1;
1983 if (!cstart) cstart = p;
1984 } else if ((ins & 0xfc000000u) == 0x14000000u &&
1985 ((ins ^ (px-p)) & 0x03ffffffu) == 0) {
1986 /* Patch b exitstub. */
1987 *p = (ins & 0xfc000000u) | ((target-p) & 0x03ffffffu);
1988 cend = p+1;
1989 if (!cstart) cstart = p;
1990 } else if ((ins & 0x7e000000u) == 0x34000000u &&
1991 ((ins ^ ((px-p)<<5)) & 0x00ffffe0u) == 0) {
1992 /* Patch cbz/cbnz exitstub. */
1993 *p = (ins & 0xff00001f) | (((target-p)<<5) & 0x00ffffe0u);
1994 cend = p+1;
1995 if (!cstart) cstart = p;
1996 } else if ((ins & 0x7e000000u) == 0x36000000u &&
1997 ((ins ^ ((px-p)<<5)) & 0x0007ffe0u) == 0) {
1998 /* Patch tbz/tbnz exitstub. */
1999 *p = (ins & 0xfff8001fu) | (((target-p)<<5) & 0x0007ffe0u);
2000 cend = p+1;
2001 if (!cstart) cstart = p;
2002 }
2003 }
2004 lua_assert(cstart != NULL);
2005 lj_mcode_sync(cstart, cend);
2006 lj_mcode_patch(J, mcarea, 1);
2007}
2008
diff --git a/src/lj_asm_mips.h b/src/lj_asm_mips.h
index 03270cca..affe7d89 100644
--- a/src/lj_asm_mips.h
+++ b/src/lj_asm_mips.h
@@ -23,7 +23,7 @@ static Reg ra_alloc1z(ASMState *as, IRRef ref, RegSet allow)
23{ 23{
24 Reg r = IR(ref)->r; 24 Reg r = IR(ref)->r;
25 if (ra_noreg(r)) { 25 if (ra_noreg(r)) {
26 if (!(allow & RSET_FPR) && irref_isk(ref) && IR(ref)->i == 0) 26 if (!(allow & RSET_FPR) && irref_isk(ref) && get_kval(IR(ref)) == 0)
27 return RID_ZERO; 27 return RID_ZERO;
28 r = ra_allocref(as, ref, allow); 28 r = ra_allocref(as, ref, allow);
29 } else { 29 } else {
@@ -166,9 +166,9 @@ static Reg asm_fuseahuref(ASMState *as, IRRef ref, int32_t *ofsp, RegSet allow)
166 } else if (ir->o == IR_UREFC) { 166 } else if (ir->o == IR_UREFC) {
167 if (irref_isk(ir->op1)) { 167 if (irref_isk(ir->op1)) {
168 GCfunc *fn = ir_kfunc(IR(ir->op1)); 168 GCfunc *fn = ir_kfunc(IR(ir->op1));
169 int32_t ofs = i32ptr(&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv); 169 intptr_t ofs = (intptr_t)&gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.tv;
170 int32_t jgl = (intptr_t)J2G(as->J); 170 intptr_t jgl = (intptr_t)J2G(as->J);
171 if ((uint32_t)(ofs-jgl) < 65536) { 171 if ((uintptr_t)(ofs-jgl) < 65536) {
172 *ofsp = ofs-jgl-32768; 172 *ofsp = ofs-jgl-32768;
173 return RID_JGL; 173 return RID_JGL;
174 } else { 174 } else {
@@ -190,20 +190,21 @@ static void asm_fusexref(ASMState *as, MIPSIns mi, Reg rt, IRRef ref,
190 Reg base; 190 Reg base;
191 if (ra_noreg(ir->r) && canfuse(as, ir)) { 191 if (ra_noreg(ir->r) && canfuse(as, ir)) {
192 if (ir->o == IR_ADD) { 192 if (ir->o == IR_ADD) {
193 int32_t ofs2; 193 intptr_t ofs2;
194 if (irref_isk(ir->op2) && (ofs2 = ofs + IR(ir->op2)->i, checki16(ofs2))) { 194 if (irref_isk(ir->op2) && (ofs2 = ofs + get_kval(IR(ir->op2)),
195 checki16(ofs2))) {
195 ref = ir->op1; 196 ref = ir->op1;
196 ofs = ofs2; 197 ofs = (int32_t)ofs2;
197 } 198 }
198 } else if (ir->o == IR_STRREF) { 199 } else if (ir->o == IR_STRREF) {
199 int32_t ofs2 = 65536; 200 intptr_t ofs2 = 65536;
200 lua_assert(ofs == 0); 201 lua_assert(ofs == 0);
201 ofs = (int32_t)sizeof(GCstr); 202 ofs = (int32_t)sizeof(GCstr);
202 if (irref_isk(ir->op2)) { 203 if (irref_isk(ir->op2)) {
203 ofs2 = ofs + IR(ir->op2)->i; 204 ofs2 = ofs + get_kval(IR(ir->op2));
204 ref = ir->op1; 205 ref = ir->op1;
205 } else if (irref_isk(ir->op1)) { 206 } else if (irref_isk(ir->op1)) {
206 ofs2 = ofs + IR(ir->op1)->i; 207 ofs2 = ofs + get_kval(IR(ir->op1));
207 ref = ir->op2; 208 ref = ir->op2;
208 } 209 }
209 if (!checki16(ofs2)) { 210 if (!checki16(ofs2)) {
@@ -211,7 +212,7 @@ static void asm_fusexref(ASMState *as, MIPSIns mi, Reg rt, IRRef ref,
211 Reg right, left = ra_alloc2(as, ir, allow); 212 Reg right, left = ra_alloc2(as, ir, allow);
212 right = (left >> 8); left &= 255; 213 right = (left >> 8); left &= 255;
213 emit_hsi(as, mi, rt, RID_TMP, ofs); 214 emit_hsi(as, mi, rt, RID_TMP, ofs);
214 emit_dst(as, MIPSI_ADDU, RID_TMP, left, right); 215 emit_dst(as, MIPSI_AADDU, RID_TMP, left, right);
215 return; 216 return;
216 } 217 }
217 ofs = ofs2; 218 ofs = ofs2;
@@ -226,29 +227,41 @@ static void asm_fusexref(ASMState *as, MIPSIns mi, Reg rt, IRRef ref,
226/* Generate a call to a C function. */ 227/* Generate a call to a C function. */
227static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) 228static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
228{ 229{
229 uint32_t n, nargs = CCI_NARGS(ci); 230 uint32_t n, nargs = CCI_XNARGS(ci);
230 int32_t ofs = 16; 231 int32_t ofs = LJ_32 ? 16 : 0;
232#if LJ_SOFTFP
233 Reg gpr = REGARG_FIRSTGPR;
234#else
231 Reg gpr, fpr = REGARG_FIRSTFPR; 235 Reg gpr, fpr = REGARG_FIRSTFPR;
236#endif
232 if ((void *)ci->func) 237 if ((void *)ci->func)
233 emit_call(as, (void *)ci->func); 238 emit_call(as, (void *)ci->func, 1);
239#if !LJ_SOFTFP
234 for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++) 240 for (gpr = REGARG_FIRSTGPR; gpr <= REGARG_LASTGPR; gpr++)
235 as->cost[gpr] = REGCOST(~0u, ASMREF_L); 241 as->cost[gpr] = REGCOST(~0u, ASMREF_L);
236 gpr = REGARG_FIRSTGPR; 242 gpr = REGARG_FIRSTGPR;
243#endif
237 for (n = 0; n < nargs; n++) { /* Setup args. */ 244 for (n = 0; n < nargs; n++) { /* Setup args. */
238 IRRef ref = args[n]; 245 IRRef ref = args[n];
239 if (ref) { 246 if (ref) {
240 IRIns *ir = IR(ref); 247 IRIns *ir = IR(ref);
248#if !LJ_SOFTFP
241 if (irt_isfp(ir->t) && fpr <= REGARG_LASTFPR && 249 if (irt_isfp(ir->t) && fpr <= REGARG_LASTFPR &&
242 !(ci->flags & CCI_VARARG)) { 250 !(ci->flags & CCI_VARARG)) {
243 lua_assert(rset_test(as->freeset, fpr)); /* Already evicted. */ 251 lua_assert(rset_test(as->freeset, fpr)); /* Already evicted. */
244 ra_leftov(as, fpr, ref); 252 ra_leftov(as, fpr, ref);
245 fpr += 2; 253 fpr += LJ_32 ? 2 : 1;
246 gpr += irt_isnum(ir->t) ? 2 : 1; 254 gpr += (LJ_32 && irt_isnum(ir->t)) ? 2 : 1;
247 } else { 255 } else
256#endif
257 {
258#if LJ_32 && !LJ_SOFTFP
248 fpr = REGARG_LASTFPR+1; 259 fpr = REGARG_LASTFPR+1;
249 if (irt_isnum(ir->t)) gpr = (gpr+1) & ~1; 260#endif
261 if (LJ_32 && irt_isnum(ir->t)) gpr = (gpr+1) & ~1;
250 if (gpr <= REGARG_LASTGPR) { 262 if (gpr <= REGARG_LASTGPR) {
251 lua_assert(rset_test(as->freeset, gpr)); /* Already evicted. */ 263 lua_assert(rset_test(as->freeset, gpr)); /* Already evicted. */
264#if !LJ_SOFTFP
252 if (irt_isfp(ir->t)) { 265 if (irt_isfp(ir->t)) {
253 RegSet of = as->freeset; 266 RegSet of = as->freeset;
254 Reg r; 267 Reg r;
@@ -257,31 +270,55 @@ static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
257 r = ra_alloc1(as, ref, RSET_FPR); 270 r = ra_alloc1(as, ref, RSET_FPR);
258 as->freeset |= (of & RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1)); 271 as->freeset |= (of & RSET_RANGE(REGARG_FIRSTGPR, REGARG_LASTGPR+1));
259 if (irt_isnum(ir->t)) { 272 if (irt_isnum(ir->t)) {
273#if LJ_32
260 emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?0:1), r+1); 274 emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?0:1), r+1);
261 emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?1:0), r); 275 emit_tg(as, MIPSI_MFC1, gpr+(LJ_BE?1:0), r);
262 lua_assert(rset_test(as->freeset, gpr+1)); /* Already evicted. */ 276 lua_assert(rset_test(as->freeset, gpr+1)); /* Already evicted. */
263 gpr += 2; 277 gpr += 2;
278#else
279 emit_tg(as, MIPSI_DMFC1, gpr, r);
280 gpr++; fpr++;
281#endif
264 } else if (irt_isfloat(ir->t)) { 282 } else if (irt_isfloat(ir->t)) {
265 emit_tg(as, MIPSI_MFC1, gpr, r); 283 emit_tg(as, MIPSI_MFC1, gpr, r);
266 gpr++; 284 gpr++;
285#if LJ_64
286 fpr++;
287#endif
267 } 288 }
268 } else { 289 } else
290#endif
291 {
269 ra_leftov(as, gpr, ref); 292 ra_leftov(as, gpr, ref);
270 gpr++; 293 gpr++;
294#if LJ_64
295 fpr++;
296#endif
271 } 297 }
272 } else { 298 } else {
273 Reg r = ra_alloc1z(as, ref, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); 299 Reg r = ra_alloc1z(as, ref, !LJ_SOFTFP && irt_isfp(ir->t) ? RSET_FPR : RSET_GPR);
300#if LJ_32
274 if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4; 301 if (irt_isnum(ir->t)) ofs = (ofs + 4) & ~4;
275 emit_spstore(as, ir, r, ofs); 302 emit_spstore(as, ir, r, ofs);
276 ofs += irt_isnum(ir->t) ? 8 : 4; 303 ofs += irt_isnum(ir->t) ? 8 : 4;
304#else
305 emit_spstore(as, ir, r, ofs + ((LJ_BE && (LJ_SOFTFP || r < RID_MAX_GPR) && !irt_is64(ir->t)) ? 4 : 0));
306 ofs += 8;
307#endif
277 } 308 }
278 } 309 }
279 } else { 310 } else {
311#if !LJ_SOFTFP
280 fpr = REGARG_LASTFPR+1; 312 fpr = REGARG_LASTFPR+1;
281 if (gpr <= REGARG_LASTGPR) 313#endif
314 if (gpr <= REGARG_LASTGPR) {
282 gpr++; 315 gpr++;
283 else 316#if LJ_64
284 ofs += 4; 317 fpr++;
318#endif
319 } else {
320 ofs += LJ_32 ? 4 : 8;
321 }
285 } 322 }
286 checkmclim(as); 323 checkmclim(as);
287 } 324 }
@@ -291,50 +328,57 @@ static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
291static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci) 328static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
292{ 329{
293 RegSet drop = RSET_SCRATCH; 330 RegSet drop = RSET_SCRATCH;
331#if LJ_32
294 int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t)); 332 int hiop = ((ir+1)->o == IR_HIOP && !irt_isnil((ir+1)->t));
333#endif
334#if !LJ_SOFTFP
295 if ((ci->flags & CCI_NOFPRCLOBBER)) 335 if ((ci->flags & CCI_NOFPRCLOBBER))
296 drop &= ~RSET_FPR; 336 drop &= ~RSET_FPR;
337#endif
297 if (ra_hasreg(ir->r)) 338 if (ra_hasreg(ir->r))
298 rset_clear(drop, ir->r); /* Dest reg handled below. */ 339 rset_clear(drop, ir->r); /* Dest reg handled below. */
340#if LJ_32
299 if (hiop && ra_hasreg((ir+1)->r)) 341 if (hiop && ra_hasreg((ir+1)->r))
300 rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */ 342 rset_clear(drop, (ir+1)->r); /* Dest reg handled below. */
343#endif
301 ra_evictset(as, drop); /* Evictions must be performed first. */ 344 ra_evictset(as, drop); /* Evictions must be performed first. */
302 if (ra_used(ir)) { 345 if (ra_used(ir)) {
303 lua_assert(!irt_ispri(ir->t)); 346 lua_assert(!irt_ispri(ir->t));
304 if (irt_isfp(ir->t)) { 347 if (!LJ_SOFTFP && irt_isfp(ir->t)) {
305 if ((ci->flags & CCI_CASTU64)) { 348 if ((ci->flags & CCI_CASTU64)) {
306 int32_t ofs = sps_scale(ir->s); 349 int32_t ofs = sps_scale(ir->s);
307 Reg dest = ir->r; 350 Reg dest = ir->r;
308 if (ra_hasreg(dest)) { 351 if (ra_hasreg(dest)) {
309 ra_free(as, dest); 352 ra_free(as, dest);
310 ra_modified(as, dest); 353 ra_modified(as, dest);
354#if LJ_32
311 emit_tg(as, MIPSI_MTC1, RID_RETHI, dest+1); 355 emit_tg(as, MIPSI_MTC1, RID_RETHI, dest+1);
312 emit_tg(as, MIPSI_MTC1, RID_RETLO, dest); 356 emit_tg(as, MIPSI_MTC1, RID_RETLO, dest);
357#else
358 emit_tg(as, MIPSI_DMTC1, RID_RET, dest);
359#endif
313 } 360 }
314 if (ofs) { 361 if (ofs) {
362#if LJ_32
315 emit_tsi(as, MIPSI_SW, RID_RETLO, RID_SP, ofs+(LJ_BE?4:0)); 363 emit_tsi(as, MIPSI_SW, RID_RETLO, RID_SP, ofs+(LJ_BE?4:0));
316 emit_tsi(as, MIPSI_SW, RID_RETHI, RID_SP, ofs+(LJ_BE?0:4)); 364 emit_tsi(as, MIPSI_SW, RID_RETHI, RID_SP, ofs+(LJ_BE?0:4));
365#else
366 emit_tsi(as, MIPSI_SD, RID_RET, RID_SP, ofs);
367#endif
317 } 368 }
318 } else { 369 } else {
319 ra_destreg(as, ir, RID_FPRET); 370 ra_destreg(as, ir, RID_FPRET);
320 } 371 }
372#if LJ_32
321 } else if (hiop) { 373 } else if (hiop) {
322 ra_destpair(as, ir); 374 ra_destpair(as, ir);
375#endif
323 } else { 376 } else {
324 ra_destreg(as, ir, RID_RET); 377 ra_destreg(as, ir, RID_RET);
325 } 378 }
326 } 379 }
327} 380}
328 381
329static void asm_call(ASMState *as, IRIns *ir)
330{
331 IRRef args[CCI_NARGS_MAX];
332 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
333 asm_collectargs(as, ir, ci, args);
334 asm_setupresult(as, ir, ci);
335 asm_gencall(as, ci, args);
336}
337
338static void asm_callx(ASMState *as, IRIns *ir) 382static void asm_callx(ASMState *as, IRIns *ir)
339{ 383{
340 IRRef args[CCI_NARGS_MAX*2]; 384 IRRef args[CCI_NARGS_MAX*2];
@@ -347,7 +391,7 @@ static void asm_callx(ASMState *as, IRIns *ir)
347 func = ir->op2; irf = IR(func); 391 func = ir->op2; irf = IR(func);
348 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } 392 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); }
349 if (irref_isk(func)) { /* Call to constant address. */ 393 if (irref_isk(func)) { /* Call to constant address. */
350 ci.func = (ASMFunction)(void *)(irf->i); 394 ci.func = (ASMFunction)(void *)get_kval(irf);
351 } else { /* Need specific register for indirect calls. */ 395 } else { /* Need specific register for indirect calls. */
352 Reg r = ra_alloc1(as, func, RID2RSET(RID_CFUNCADDR)); 396 Reg r = ra_alloc1(as, func, RID2RSET(RID_CFUNCADDR));
353 MCode *p = as->mcp; 397 MCode *p = as->mcp;
@@ -362,16 +406,7 @@ static void asm_callx(ASMState *as, IRIns *ir)
362 asm_gencall(as, &ci, args); 406 asm_gencall(as, &ci, args);
363} 407}
364 408
365static void asm_callid(ASMState *as, IRIns *ir, IRCallID id) 409#if !LJ_SOFTFP
366{
367 const CCallInfo *ci = &lj_ir_callinfo[id];
368 IRRef args[2];
369 args[0] = ir->op1;
370 args[1] = ir->op2;
371 asm_setupresult(as, ir, ci);
372 asm_gencall(as, ci, args);
373}
374
375static void asm_callround(ASMState *as, IRIns *ir, IRCallID id) 410static void asm_callround(ASMState *as, IRIns *ir, IRCallID id)
376{ 411{
377 /* The modified regs must match with the *.dasc implementation. */ 412 /* The modified regs must match with the *.dasc implementation. */
@@ -380,9 +415,10 @@ static void asm_callround(ASMState *as, IRIns *ir, IRCallID id)
380 if (ra_hasreg(ir->r)) rset_clear(drop, ir->r); 415 if (ra_hasreg(ir->r)) rset_clear(drop, ir->r);
381 ra_evictset(as, drop); 416 ra_evictset(as, drop);
382 ra_destreg(as, ir, RID_FPRET); 417 ra_destreg(as, ir, RID_FPRET);
383 emit_call(as, (void *)lj_ir_callinfo[id].func); 418 emit_call(as, (void *)lj_ir_callinfo[id].func, 0);
384 ra_leftov(as, REGARG_FIRSTFPR, ir->op1); 419 ra_leftov(as, REGARG_FIRSTFPR, ir->op1);
385} 420}
421#endif
386 422
387/* -- Returns ------------------------------------------------------------- */ 423/* -- Returns ------------------------------------------------------------- */
388 424
@@ -391,19 +427,20 @@ static void asm_retf(ASMState *as, IRIns *ir)
391{ 427{
392 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); 428 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
393 void *pc = ir_kptr(IR(ir->op2)); 429 void *pc = ir_kptr(IR(ir->op2));
394 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1)); 430 int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
395 as->topslot -= (BCReg)delta; 431 as->topslot -= (BCReg)delta;
396 if ((int32_t)as->topslot < 0) as->topslot = 0; 432 if ((int32_t)as->topslot < 0) as->topslot = 0;
397 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ 433 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
398 emit_setgl(as, base, jit_base); 434 emit_setgl(as, base, jit_base);
399 emit_addptr(as, base, -8*delta); 435 emit_addptr(as, base, -8*delta);
400 asm_guard(as, MIPSI_BNE, RID_TMP, 436 asm_guard(as, MIPSI_BNE, RID_TMP,
401 ra_allock(as, i32ptr(pc), rset_exclude(RSET_GPR, base))); 437 ra_allock(as, igcptr(pc), rset_exclude(RSET_GPR, base)));
402 emit_tsi(as, MIPSI_LW, RID_TMP, base, -8); 438 emit_tsi(as, MIPSI_AL, RID_TMP, base, -8);
403} 439}
404 440
405/* -- Type conversions ---------------------------------------------------- */ 441/* -- Type conversions ---------------------------------------------------- */
406 442
443#if !LJ_SOFTFP
407static void asm_tointg(ASMState *as, IRIns *ir, Reg left) 444static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
408{ 445{
409 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); 446 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
@@ -425,15 +462,28 @@ static void asm_tobit(ASMState *as, IRIns *ir)
425 emit_tg(as, MIPSI_MFC1, dest, tmp); 462 emit_tg(as, MIPSI_MFC1, dest, tmp);
426 emit_fgh(as, MIPSI_ADD_D, tmp, left, right); 463 emit_fgh(as, MIPSI_ADD_D, tmp, left, right);
427} 464}
465#endif
428 466
429static void asm_conv(ASMState *as, IRIns *ir) 467static void asm_conv(ASMState *as, IRIns *ir)
430{ 468{
431 IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK); 469 IRType st = (IRType)(ir->op2 & IRCONV_SRCMASK);
470#if !LJ_SOFTFP
432 int stfp = (st == IRT_NUM || st == IRT_FLOAT); 471 int stfp = (st == IRT_NUM || st == IRT_FLOAT);
472#endif
473#if LJ_64
474 int st64 = (st == IRT_I64 || st == IRT_U64 || st == IRT_P64);
475#endif
433 IRRef lref = ir->op1; 476 IRRef lref = ir->op1;
434 lua_assert(irt_type(ir->t) != st); 477#if LJ_32
435 lua_assert(!(irt_isint64(ir->t) || 478 lua_assert(!(irt_isint64(ir->t) ||
436 (st == IRT_I64 || st == IRT_U64))); /* Handled by SPLIT. */ 479 (st == IRT_I64 || st == IRT_U64))); /* Handled by SPLIT. */
480#endif
481#if LJ_32 && LJ_SOFTFP
482 /* FP conversions are handled by SPLIT. */
483 lua_assert(!irt_isfp(ir->t) && !(st == IRT_NUM || st == IRT_FLOAT));
484 /* Can't check for same types: SPLIT uses CONV int.int + BXOR for sfp NEG. */
485#else
486 lua_assert(irt_type(ir->t) != st);
437 if (irt_isfp(ir->t)) { 487 if (irt_isfp(ir->t)) {
438 Reg dest = ra_dest(as, ir, RSET_FPR); 488 Reg dest = ra_dest(as, ir, RSET_FPR);
439 if (stfp) { /* FP to FP conversion. */ 489 if (stfp) { /* FP to FP conversion. */
@@ -449,16 +499,44 @@ static void asm_conv(ASMState *as, IRIns *ir)
449 emit_fgh(as, MIPSI_ADD_D, dest, dest, tmp); 499 emit_fgh(as, MIPSI_ADD_D, dest, dest, tmp);
450 emit_fg(as, MIPSI_CVT_D_W, dest, dest); 500 emit_fg(as, MIPSI_CVT_D_W, dest, dest);
451 emit_lsptr(as, MIPSI_LDC1, (tmp & 31), 501 emit_lsptr(as, MIPSI_LDC1, (tmp & 31),
452 (void *)lj_ir_k64_find(as->J, U64x(41e00000,00000000)), 502 (void *)&as->J->k64[LJ_K64_2P31], RSET_GPR);
453 RSET_GPR);
454 emit_tg(as, MIPSI_MTC1, RID_TMP, dest); 503 emit_tg(as, MIPSI_MTC1, RID_TMP, dest);
455 emit_dst(as, MIPSI_XOR, RID_TMP, RID_TMP, left); 504 emit_dst(as, MIPSI_XOR, RID_TMP, RID_TMP, left);
456 emit_ti(as, MIPSI_LUI, RID_TMP, 0x8000); 505 emit_ti(as, MIPSI_LUI, RID_TMP, 0x8000);
506#if LJ_64
507 } else if(st == IRT_U64) { /* U64 to FP conversion. */
508 /* if (x >= 1u<<63) y = (double)(int64_t)(x&(1u<<63)-1) + pow(2.0, 63) */
509 Reg left = ra_alloc1(as, lref, RSET_GPR);
510 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, dest));
511 MCLabel l_end = emit_label(as);
512 if (irt_isfloat(ir->t)) {
513 emit_fgh(as, MIPSI_ADD_S, dest, dest, tmp);
514 emit_lsptr(as, MIPSI_LWC1, (tmp & 31), (void *)&as->J->k32[LJ_K32_2P63],
515 rset_exclude(RSET_GPR, left));
516 emit_fg(as, MIPSI_CVT_S_L, dest, dest);
517 } else {
518 emit_fgh(as, MIPSI_ADD_D, dest, dest, tmp);
519 emit_lsptr(as, MIPSI_LDC1, (tmp & 31), (void *)&as->J->k64[LJ_K64_2P63],
520 rset_exclude(RSET_GPR, left));
521 emit_fg(as, MIPSI_CVT_D_L, dest, dest);
522 }
523 emit_branch(as, MIPSI_BGEZ, left, RID_ZERO, l_end);
524 emit_tg(as, MIPSI_DMTC1, RID_TMP, dest);
525 emit_tsml(as, MIPSI_DEXTM, RID_TMP, left, 30, 0);
526#endif
457 } else { /* Integer to FP conversion. */ 527 } else { /* Integer to FP conversion. */
458 Reg left = ra_alloc1(as, lref, RSET_GPR); 528 Reg left = ra_alloc1(as, lref, RSET_GPR);
529#if LJ_32
459 emit_fg(as, irt_isfloat(ir->t) ? MIPSI_CVT_S_W : MIPSI_CVT_D_W, 530 emit_fg(as, irt_isfloat(ir->t) ? MIPSI_CVT_S_W : MIPSI_CVT_D_W,
460 dest, dest); 531 dest, dest);
461 emit_tg(as, MIPSI_MTC1, left, dest); 532 emit_tg(as, MIPSI_MTC1, left, dest);
533#else
534 MIPSIns mi = irt_isfloat(ir->t) ?
535 (st64 ? MIPSI_CVT_S_L : MIPSI_CVT_S_W) :
536 (st64 ? MIPSI_CVT_D_L : MIPSI_CVT_D_W);
537 emit_fg(as, mi, dest, dest);
538 emit_tg(as, st64 ? MIPSI_DMTC1 : MIPSI_MTC1, left, dest);
539#endif
462 } 540 }
463 } else if (stfp) { /* FP to integer conversion. */ 541 } else if (stfp) { /* FP to integer conversion. */
464 if (irt_isguard(ir->t)) { 542 if (irt_isguard(ir->t)) {
@@ -469,7 +547,7 @@ static void asm_conv(ASMState *as, IRIns *ir)
469 Reg dest = ra_dest(as, ir, RSET_GPR); 547 Reg dest = ra_dest(as, ir, RSET_GPR);
470 Reg left = ra_alloc1(as, lref, RSET_FPR); 548 Reg left = ra_alloc1(as, lref, RSET_FPR);
471 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left)); 549 Reg tmp = ra_scratch(as, rset_exclude(RSET_FPR, left));
472 if (irt_isu32(ir->t)) { 550 if (irt_isu32(ir->t)) { /* FP to U32 conversion. */
473 /* y = (int)floor(x - 2147483648.0) ^ 0x80000000 */ 551 /* y = (int)floor(x - 2147483648.0) ^ 0x80000000 */
474 emit_dst(as, MIPSI_XOR, dest, dest, RID_TMP); 552 emit_dst(as, MIPSI_XOR, dest, dest, RID_TMP);
475 emit_ti(as, MIPSI_LUI, RID_TMP, 0x8000); 553 emit_ti(as, MIPSI_LUI, RID_TMP, 0x8000);
@@ -480,25 +558,65 @@ static void asm_conv(ASMState *as, IRIns *ir)
480 tmp, left, tmp); 558 tmp, left, tmp);
481 if (st == IRT_FLOAT) 559 if (st == IRT_FLOAT)
482 emit_lsptr(as, MIPSI_LWC1, (tmp & 31), 560 emit_lsptr(as, MIPSI_LWC1, (tmp & 31),
483 (void *)lj_ir_k64_find(as->J, U64x(4f000000,4f000000)), 561 (void *)&as->J->k32[LJ_K32_2P31], RSET_GPR);
484 RSET_GPR);
485 else 562 else
486 emit_lsptr(as, MIPSI_LDC1, (tmp & 31), 563 emit_lsptr(as, MIPSI_LDC1, (tmp & 31),
487 (void *)lj_ir_k64_find(as->J, U64x(41e00000,00000000)), 564 (void *)&as->J->k64[LJ_K64_2P31], RSET_GPR);
488 RSET_GPR); 565#if LJ_64
566 } else if (irt_isu64(ir->t)) { /* FP to U64 conversion. */
567 MCLabel l_end;
568 emit_tg(as, MIPSI_DMFC1, dest, tmp);
569 l_end = emit_label(as);
570 /* For inputs >= 2^63 add -2^64 and convert again. */
571 if (st == IRT_NUM) {
572 emit_fg(as, MIPSI_TRUNC_L_D, tmp, tmp);
573 emit_fgh(as, MIPSI_ADD_D, tmp, left, tmp);
574 emit_lsptr(as, MIPSI_LDC1, (tmp & 31),
575 (void *)&as->J->k64[LJ_K64_M2P64],
576 rset_exclude(RSET_GPR, dest));
577 emit_fg(as, MIPSI_TRUNC_L_D, tmp, left); /* Delay slot. */
578 emit_branch(as, MIPSI_BC1T, 0, 0, l_end);
579 emit_fgh(as, MIPSI_C_OLT_D, 0, left, tmp);
580 emit_lsptr(as, MIPSI_LDC1, (tmp & 31),
581 (void *)&as->J->k64[LJ_K64_2P63],
582 rset_exclude(RSET_GPR, dest));
583 } else {
584 emit_fg(as, MIPSI_TRUNC_L_S, tmp, tmp);
585 emit_fgh(as, MIPSI_ADD_S, tmp, left, tmp);
586 emit_lsptr(as, MIPSI_LWC1, (tmp & 31),
587 (void *)&as->J->k32[LJ_K32_M2P64],
588 rset_exclude(RSET_GPR, dest));
589 emit_fg(as, MIPSI_TRUNC_L_S, tmp, left); /* Delay slot. */
590 emit_branch(as, MIPSI_BC1T, 0, 0, l_end);
591 emit_fgh(as, MIPSI_C_OLT_S, 0, left, tmp);
592 emit_lsptr(as, MIPSI_LWC1, (tmp & 31),
593 (void *)&as->J->k32[LJ_K32_2P63],
594 rset_exclude(RSET_GPR, dest));
595 }
596#endif
489 } else { 597 } else {
598#if LJ_32
490 emit_tg(as, MIPSI_MFC1, dest, tmp); 599 emit_tg(as, MIPSI_MFC1, dest, tmp);
491 emit_fg(as, st == IRT_FLOAT ? MIPSI_TRUNC_W_S : MIPSI_TRUNC_W_D, 600 emit_fg(as, st == IRT_FLOAT ? MIPSI_TRUNC_W_S : MIPSI_TRUNC_W_D,
492 tmp, left); 601 tmp, left);
602#else
603 MIPSIns mi = irt_is64(ir->t) ?
604 (st == IRT_NUM ? MIPSI_TRUNC_L_D : MIPSI_TRUNC_L_S) :
605 (st == IRT_NUM ? MIPSI_TRUNC_W_D : MIPSI_TRUNC_W_S);
606 emit_tg(as, irt_is64(ir->t) ? MIPSI_DMFC1 : MIPSI_MFC1, dest, left);
607 emit_fg(as, mi, left, left);
608#endif
493 } 609 }
494 } 610 }
495 } else { 611 } else
612#endif
613 {
496 Reg dest = ra_dest(as, ir, RSET_GPR); 614 Reg dest = ra_dest(as, ir, RSET_GPR);
497 if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ 615 if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */
498 Reg left = ra_alloc1(as, ir->op1, RSET_GPR); 616 Reg left = ra_alloc1(as, ir->op1, RSET_GPR);
499 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t)); 617 lua_assert(irt_isint(ir->t) || irt_isu32(ir->t));
500 if ((ir->op2 & IRCONV_SEXT)) { 618 if ((ir->op2 & IRCONV_SEXT)) {
501 if ((as->flags & JIT_F_MIPS32R2)) { 619 if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) {
502 emit_dst(as, st == IRT_I8 ? MIPSI_SEB : MIPSI_SEH, dest, 0, left); 620 emit_dst(as, st == IRT_I8 ? MIPSI_SEB : MIPSI_SEH, dest, 0, left);
503 } else { 621 } else {
504 uint32_t shift = st == IRT_I8 ? 24 : 16; 622 uint32_t shift = st == IRT_I8 ? 24 : 16;
@@ -510,94 +628,141 @@ static void asm_conv(ASMState *as, IRIns *ir)
510 (int32_t)(st == IRT_U8 ? 0xff : 0xffff)); 628 (int32_t)(st == IRT_U8 ? 0xff : 0xffff));
511 } 629 }
512 } else { /* 32/64 bit integer conversions. */ 630 } else { /* 32/64 bit integer conversions. */
631#if LJ_32
513 /* Only need to handle 32/32 bit no-op (cast) on 32 bit archs. */ 632 /* Only need to handle 32/32 bit no-op (cast) on 32 bit archs. */
514 ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */ 633 ra_leftov(as, dest, lref); /* Do nothing, but may need to move regs. */
634#else
635 if (irt_is64(ir->t)) {
636 if (st64) {
637 /* 64/64 bit no-op (cast)*/
638 ra_leftov(as, dest, lref);
639 } else {
640 Reg left = ra_alloc1(as, lref, RSET_GPR);
641 if ((ir->op2 & IRCONV_SEXT)) { /* 32 to 64 bit sign extension. */
642 emit_dta(as, MIPSI_SLL, dest, left, 0);
643 } else { /* 32 to 64 bit zero extension. */
644 emit_tsml(as, MIPSI_DEXT, dest, left, 31, 0);
645 }
646 }
647 } else {
648 if (st64) {
649 /* This is either a 32 bit reg/reg mov which zeroes the hiword
650 ** or a load of the loword from a 64 bit address.
651 */
652 Reg left = ra_alloc1(as, lref, RSET_GPR);
653 emit_tsml(as, MIPSI_DEXT, dest, left, 31, 0);
654 } else { /* 32/32 bit no-op (cast). */
655 /* Do nothing, but may need to move regs. */
656 ra_leftov(as, dest, lref);
657 }
658 }
659#endif
515 } 660 }
516 } 661 }
517} 662}
518 663
519#if LJ_HASFFI
520static void asm_conv64(ASMState *as, IRIns *ir)
521{
522 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
523 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
524 IRCallID id;
525 const CCallInfo *ci;
526 IRRef args[2];
527 args[LJ_BE?0:1] = ir->op1;
528 args[LJ_BE?1:0] = (ir-1)->op1;
529 if (st == IRT_NUM || st == IRT_FLOAT) {
530 id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
531 ir--;
532 } else {
533 id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
534 }
535 ci = &lj_ir_callinfo[id];
536 asm_setupresult(as, ir, ci);
537 asm_gencall(as, ci, args);
538}
539#endif
540
541static void asm_strto(ASMState *as, IRIns *ir) 664static void asm_strto(ASMState *as, IRIns *ir)
542{ 665{
543 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; 666 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
544 IRRef args[2]; 667 IRRef args[2];
668 int32_t ofs = 0;
669#if LJ_SOFTFP
670 ra_evictset(as, RSET_SCRATCH);
671 if (ra_used(ir)) {
672 if (ra_hasspill(ir->s) && ra_hasspill((ir+1)->s) &&
673 (ir->s & 1) == LJ_BE && (ir->s ^ 1) == (ir+1)->s) {
674 int i;
675 for (i = 0; i < 2; i++) {
676 Reg r = (ir+i)->r;
677 if (ra_hasreg(r)) {
678 ra_free(as, r);
679 ra_modified(as, r);
680 emit_spload(as, ir+i, r, sps_scale((ir+i)->s));
681 }
682 }
683 ofs = sps_scale(ir->s & ~1);
684 } else {
685 Reg rhi = ra_dest(as, ir+1, RSET_GPR);
686 Reg rlo = ra_dest(as, ir, rset_exclude(RSET_GPR, rhi));
687 emit_tsi(as, MIPSI_LW, rhi, RID_SP, ofs+(LJ_BE?0:4));
688 emit_tsi(as, MIPSI_LW, rlo, RID_SP, ofs+(LJ_BE?4:0));
689 }
690 }
691#else
545 RegSet drop = RSET_SCRATCH; 692 RegSet drop = RSET_SCRATCH;
546 if (ra_hasreg(ir->r)) rset_set(drop, ir->r); /* Spill dest reg (if any). */ 693 if (ra_hasreg(ir->r)) rset_set(drop, ir->r); /* Spill dest reg (if any). */
547 ra_evictset(as, drop); 694 ra_evictset(as, drop);
695 ofs = sps_scale(ir->s);
696#endif
548 asm_guard(as, MIPSI_BEQ, RID_RET, RID_ZERO); /* Test return status. */ 697 asm_guard(as, MIPSI_BEQ, RID_RET, RID_ZERO); /* Test return status. */
549 args[0] = ir->op1; /* GCstr *str */ 698 args[0] = ir->op1; /* GCstr *str */
550 args[1] = ASMREF_TMP1; /* TValue *n */ 699 args[1] = ASMREF_TMP1; /* TValue *n */
551 asm_gencall(as, ci, args); 700 asm_gencall(as, ci, args);
552 /* Store the result to the spill slot or temp slots. */ 701 /* Store the result to the spill slot or temp slots. */
553 emit_tsi(as, MIPSI_ADDIU, ra_releasetmp(as, ASMREF_TMP1), 702 emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1),
554 RID_SP, sps_scale(ir->s)); 703 RID_SP, ofs);
555} 704}
556 705
706/* -- Memory references --------------------------------------------------- */
707
708#if LJ_64
709/* Store tagged value for ref at base+ofs. */
710static void asm_tvstore64(ASMState *as, Reg base, int32_t ofs, IRRef ref)
711{
712 RegSet allow = rset_exclude(RSET_GPR, base);
713 IRIns *ir = IR(ref);
714 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t));
715 if (irref_isk(ref)) {
716 TValue k;
717 lj_ir_kvalue(as->J->L, &k, ir);
718 emit_tsi(as, MIPSI_SD, ra_allock(as, (int64_t)k.u64, allow), base, ofs);
719 } else {
720 Reg src = ra_alloc1(as, ref, allow);
721 Reg type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47,
722 rset_exclude(allow, src));
723 emit_tsi(as, MIPSI_SD, RID_TMP, base, ofs);
724 if (irt_isinteger(ir->t)) {
725 emit_dst(as, MIPSI_DADDU, RID_TMP, RID_TMP, type);
726 emit_tsml(as, MIPSI_DEXT, RID_TMP, src, 31, 0);
727 } else {
728 emit_dst(as, MIPSI_DADDU, RID_TMP, src, type);
729 }
730 }
731}
732#endif
733
557/* Get pointer to TValue. */ 734/* Get pointer to TValue. */
558static void asm_tvptr(ASMState *as, Reg dest, IRRef ref) 735static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
559{ 736{
560 IRIns *ir = IR(ref); 737 IRIns *ir = IR(ref);
561 if (irt_isnum(ir->t)) { 738 if (irt_isnum(ir->t)) {
562 if (irref_isk(ref)) /* Use the number constant itself as a TValue. */ 739 if (irref_isk(ref)) /* Use the number constant itself as a TValue. */
563 ra_allockreg(as, i32ptr(ir_knum(ir)), dest); 740 ra_allockreg(as, igcptr(ir_knum(ir)), dest);
564 else /* Otherwise force a spill and use the spill slot. */ 741 else /* Otherwise force a spill and use the spill slot. */
565 emit_tsi(as, MIPSI_ADDIU, dest, RID_SP, ra_spill(as, ir)); 742 emit_tsi(as, MIPSI_AADDIU, dest, RID_SP, ra_spill(as, ir));
566 } else { 743 } else {
567 /* Otherwise use g->tmptv to hold the TValue. */ 744 /* Otherwise use g->tmptv to hold the TValue. */
745#if LJ_32
568 RegSet allow = rset_exclude(RSET_GPR, dest); 746 RegSet allow = rset_exclude(RSET_GPR, dest);
569 Reg type; 747 Reg type;
570 emit_tsi(as, MIPSI_ADDIU, dest, RID_JGL, offsetof(global_State, tmptv)-32768); 748 emit_tsi(as, MIPSI_ADDIU, dest, RID_JGL, (int32_t)(offsetof(global_State, tmptv)-32768));
571 if (!irt_ispri(ir->t)) { 749 if (!irt_ispri(ir->t)) {
572 Reg src = ra_alloc1(as, ref, allow); 750 Reg src = ra_alloc1(as, ref, allow);
573 emit_setgl(as, src, tmptv.gcr); 751 emit_setgl(as, src, tmptv.gcr);
574 } 752 }
575 type = ra_allock(as, irt_toitype(ir->t), allow); 753 if (LJ_SOFTFP && (ir+1)->o == IR_HIOP)
754 type = ra_alloc1(as, ref+1, allow);
755 else
756 type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow);
576 emit_setgl(as, type, tmptv.it); 757 emit_setgl(as, type, tmptv.it);
758#else
759 asm_tvstore64(as, dest, 0, ref);
760 emit_tsi(as, MIPSI_DADDIU, dest, RID_JGL,
761 (int32_t)(offsetof(global_State, tmptv)-32768));
762#endif
577 } 763 }
578} 764}
579 765
580static void asm_tostr(ASMState *as, IRIns *ir)
581{
582 IRRef args[2];
583 args[0] = ASMREF_L;
584 as->gcsteps++;
585 if (irt_isnum(IR(ir->op1)->t) || (ir+1)->o == IR_HIOP) {
586 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum];
587 args[1] = ASMREF_TMP1; /* const lua_Number * */
588 asm_setupresult(as, ir, ci); /* GCstr * */
589 asm_gencall(as, ci, args);
590 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1);
591 } else {
592 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint];
593 args[1] = ir->op1; /* int32_t k */
594 asm_setupresult(as, ir, ci); /* GCstr * */
595 asm_gencall(as, ci, args);
596 }
597}
598
599/* -- Memory references --------------------------------------------------- */
600
601static void asm_aref(ASMState *as, IRIns *ir) 766static void asm_aref(ASMState *as, IRIns *ir)
602{ 767{
603 Reg dest = ra_dest(as, ir, RSET_GPR); 768 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -609,13 +774,13 @@ static void asm_aref(ASMState *as, IRIns *ir)
609 ofs += 8*IR(ir->op2)->i; 774 ofs += 8*IR(ir->op2)->i;
610 if (checki16(ofs)) { 775 if (checki16(ofs)) {
611 base = ra_alloc1(as, refa, RSET_GPR); 776 base = ra_alloc1(as, refa, RSET_GPR);
612 emit_tsi(as, MIPSI_ADDIU, dest, base, ofs); 777 emit_tsi(as, MIPSI_AADDIU, dest, base, ofs);
613 return; 778 return;
614 } 779 }
615 } 780 }
616 base = ra_alloc1(as, ir->op1, RSET_GPR); 781 base = ra_alloc1(as, ir->op1, RSET_GPR);
617 idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base)); 782 idx = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, base));
618 emit_dst(as, MIPSI_ADDU, dest, RID_TMP, base); 783 emit_dst(as, MIPSI_AADDU, dest, RID_TMP, base);
619 emit_dta(as, MIPSI_SLL, RID_TMP, idx, 3); 784 emit_dta(as, MIPSI_SLL, RID_TMP, idx, 3);
620} 785}
621 786
@@ -627,7 +792,7 @@ static void asm_aref(ASMState *as, IRIns *ir)
627** } while ((n = nextnode(n))); 792** } while ((n = nextnode(n)));
628** return niltv(L); 793** return niltv(L);
629*/ 794*/
630static void asm_href(ASMState *as, IRIns *ir) 795static void asm_href(ASMState *as, IRIns *ir, IROp merge)
631{ 796{
632 RegSet allow = RSET_GPR; 797 RegSet allow = RSET_GPR;
633 int destused = ra_used(ir); 798 int destused = ra_used(ir);
@@ -636,42 +801,72 @@ static void asm_href(ASMState *as, IRIns *ir)
636 Reg key = RID_NONE, type = RID_NONE, tmpnum = RID_NONE, tmp1 = RID_TMP, tmp2; 801 Reg key = RID_NONE, type = RID_NONE, tmpnum = RID_NONE, tmp1 = RID_TMP, tmp2;
637 IRRef refkey = ir->op2; 802 IRRef refkey = ir->op2;
638 IRIns *irkey = IR(refkey); 803 IRIns *irkey = IR(refkey);
804 int isk = irref_isk(refkey);
639 IRType1 kt = irkey->t; 805 IRType1 kt = irkey->t;
640 uint32_t khash; 806 uint32_t khash;
641 MCLabel l_end, l_loop, l_next; 807 MCLabel l_end, l_loop, l_next;
642 808
643 rset_clear(allow, tab); 809 rset_clear(allow, tab);
810#if LJ_32 && LJ_SOFTFP
811 if (!isk) {
812 key = ra_alloc1(as, refkey, allow);
813 rset_clear(allow, key);
814 if (irkey[1].o == IR_HIOP) {
815 if (ra_hasreg((irkey+1)->r)) {
816 type = tmpnum = (irkey+1)->r;
817 tmp1 = ra_scratch(as, allow);
818 rset_clear(allow, tmp1);
819 ra_noweak(as, tmpnum);
820 } else {
821 type = tmpnum = ra_allocref(as, refkey+1, allow);
822 }
823 rset_clear(allow, tmpnum);
824 } else {
825 type = ra_allock(as, (int32_t)irt_toitype(irkey->t), allow);
826 rset_clear(allow, type);
827 }
828 }
829#else
644 if (irt_isnum(kt)) { 830 if (irt_isnum(kt)) {
645 key = ra_alloc1(as, refkey, RSET_FPR); 831 key = ra_alloc1(as, refkey, RSET_FPR);
646 tmpnum = ra_scratch(as, rset_exclude(RSET_FPR, key)); 832 tmpnum = ra_scratch(as, rset_exclude(RSET_FPR, key));
647 } else if (!irt_ispri(kt)) { 833 } else if (!irt_ispri(kt)) {
648 key = ra_alloc1(as, refkey, allow); 834 key = ra_alloc1(as, refkey, allow);
649 rset_clear(allow, key); 835 rset_clear(allow, key);
650 type = ra_allock(as, irt_toitype(irkey->t), allow); 836#if LJ_32
837 type = ra_allock(as, (int32_t)irt_toitype(irkey->t), allow);
651 rset_clear(allow, type); 838 rset_clear(allow, type);
839#endif
652 } 840 }
841#endif
653 tmp2 = ra_scratch(as, allow); 842 tmp2 = ra_scratch(as, allow);
654 rset_clear(allow, tmp2); 843 rset_clear(allow, tmp2);
655 844
656 /* Key not found in chain: load niltv. */ 845 /* Key not found in chain: jump to exit (if merged) or load niltv. */
657 l_end = emit_label(as); 846 l_end = emit_label(as);
658 if (destused) 847 as->invmcp = NULL;
848 if (merge == IR_NE)
849 asm_guard(as, MIPSI_B, RID_ZERO, RID_ZERO);
850 else if (destused)
659 emit_loada(as, dest, niltvg(J2G(as->J))); 851 emit_loada(as, dest, niltvg(J2G(as->J)));
660 else
661 *--as->mcp = MIPSI_NOP;
662 /* Follow hash chain until the end. */ 852 /* Follow hash chain until the end. */
663 emit_move(as, dest, tmp1); 853 emit_move(as, dest, tmp1);
664 l_loop = --as->mcp; 854 l_loop = --as->mcp;
665 emit_tsi(as, MIPSI_LW, tmp1, dest, (int32_t)offsetof(Node, next)); 855 emit_tsi(as, MIPSI_AL, tmp1, dest, (int32_t)offsetof(Node, next));
666 l_next = emit_label(as); 856 l_next = emit_label(as);
667 857
668 /* Type and value comparison. */ 858 /* Type and value comparison. */
669 if (irt_isnum(kt)) { 859 if (merge == IR_EQ) { /* Must match asm_guard(). */
860 emit_ti(as, MIPSI_LI, RID_TMP, as->snapno);
861 l_end = asm_exitstub_addr(as);
862 }
863 if (!LJ_SOFTFP && irt_isnum(kt)) {
670 emit_branch(as, MIPSI_BC1T, 0, 0, l_end); 864 emit_branch(as, MIPSI_BC1T, 0, 0, l_end);
671 emit_fgh(as, MIPSI_C_EQ_D, 0, tmpnum, key); 865 emit_fgh(as, MIPSI_C_EQ_D, 0, tmpnum, key);
672 emit_tg(as, MIPSI_MFC1, tmp1, key+1); 866 *--as->mcp = MIPSI_NOP; /* Avoid NaN comparison overhead. */
673 emit_branch(as, MIPSI_BEQ, tmp1, RID_ZERO, l_next); 867 emit_branch(as, MIPSI_BEQ, tmp1, RID_ZERO, l_next);
674 emit_tsi(as, MIPSI_SLTIU, tmp1, tmp1, (int32_t)LJ_TISNUM); 868 emit_tsi(as, MIPSI_SLTIU, tmp1, tmp1, (int32_t)LJ_TISNUM);
869#if LJ_32
675 emit_hsi(as, MIPSI_LDC1, tmpnum, dest, (int32_t)offsetof(Node, key.n)); 870 emit_hsi(as, MIPSI_LDC1, tmpnum, dest, (int32_t)offsetof(Node, key.n));
676 } else { 871 } else {
677 if (irt_ispri(kt)) { 872 if (irt_ispri(kt)) {
@@ -684,24 +879,51 @@ static void asm_href(ASMState *as, IRIns *ir)
684 } 879 }
685 emit_tsi(as, MIPSI_LW, tmp1, dest, (int32_t)offsetof(Node, key.it)); 880 emit_tsi(as, MIPSI_LW, tmp1, dest, (int32_t)offsetof(Node, key.it));
686 *l_loop = MIPSI_BNE | MIPSF_S(tmp1) | ((as->mcp-l_loop-1) & 0xffffu); 881 *l_loop = MIPSI_BNE | MIPSF_S(tmp1) | ((as->mcp-l_loop-1) & 0xffffu);
882#else
883 emit_dta(as, MIPSI_DSRA32, tmp1, tmp1, 15);
884 emit_tg(as, MIPSI_DMTC1, tmp1, tmpnum);
885 emit_tsi(as, MIPSI_LD, tmp1, dest, (int32_t)offsetof(Node, key.u64));
886 } else if (irt_isaddr(kt)) {
887 Reg refk = tmp2;
888 if (isk) {
889 int64_t k = ((int64_t)irt_toitype(irkey->t) << 47) | irkey[1].tv.u64;
890 refk = ra_allock(as, k, allow);
891 rset_clear(allow, refk);
892 }
893 emit_branch(as, MIPSI_BEQ, tmp1, refk, l_end);
894 emit_tsi(as, MIPSI_LD, tmp1, dest, offsetof(Node, key));
895 } else {
896 Reg pri = ra_allock(as, ~((int64_t)~irt_toitype(ir->t) << 47), allow);
897 rset_clear(allow, pri);
898 lua_assert(irt_ispri(kt) && !irt_isnil(kt));
899 emit_branch(as, MIPSI_BEQ, tmp1, pri, l_end);
900 emit_tsi(as, MIPSI_LD, tmp1, dest, offsetof(Node, key));
901 }
902 *l_loop = MIPSI_BNE | MIPSF_S(tmp1) | ((as->mcp-l_loop-1) & 0xffffu);
903 if (!isk && irt_isaddr(kt)) {
904 type = ra_allock(as, (int64_t)irt_toitype(kt) << 47, allow);
905 emit_dst(as, MIPSI_DADDU, tmp2, key, type);
906 rset_clear(allow, type);
907 }
908#endif
687 909
688 /* Load main position relative to tab->node into dest. */ 910 /* Load main position relative to tab->node into dest. */
689 khash = irref_isk(refkey) ? ir_khash(irkey) : 1; 911 khash = isk ? ir_khash(irkey) : 1;
690 if (khash == 0) { 912 if (khash == 0) {
691 emit_tsi(as, MIPSI_LW, dest, tab, (int32_t)offsetof(GCtab, node)); 913 emit_tsi(as, MIPSI_AL, dest, tab, (int32_t)offsetof(GCtab, node));
692 } else { 914 } else {
693 Reg tmphash = tmp1; 915 Reg tmphash = tmp1;
694 if (irref_isk(refkey)) 916 if (isk)
695 tmphash = ra_allock(as, khash, allow); 917 tmphash = ra_allock(as, khash, allow);
696 emit_dst(as, MIPSI_ADDU, dest, dest, tmp1); 918 emit_dst(as, MIPSI_AADDU, dest, dest, tmp1);
697 lua_assert(sizeof(Node) == 24); 919 lua_assert(sizeof(Node) == 24);
698 emit_dst(as, MIPSI_SUBU, tmp1, tmp2, tmp1); 920 emit_dst(as, MIPSI_SUBU, tmp1, tmp2, tmp1);
699 emit_dta(as, MIPSI_SLL, tmp1, tmp1, 3); 921 emit_dta(as, MIPSI_SLL, tmp1, tmp1, 3);
700 emit_dta(as, MIPSI_SLL, tmp2, tmp1, 5); 922 emit_dta(as, MIPSI_SLL, tmp2, tmp1, 5);
701 emit_dst(as, MIPSI_AND, tmp1, tmp2, tmphash); 923 emit_dst(as, MIPSI_AND, tmp1, tmp2, tmphash);
702 emit_tsi(as, MIPSI_LW, dest, tab, (int32_t)offsetof(GCtab, node)); 924 emit_tsi(as, MIPSI_AL, dest, tab, (int32_t)offsetof(GCtab, node));
703 emit_tsi(as, MIPSI_LW, tmp2, tab, (int32_t)offsetof(GCtab, hmask)); 925 emit_tsi(as, MIPSI_LW, tmp2, tab, (int32_t)offsetof(GCtab, hmask));
704 if (irref_isk(refkey)) { 926 if (isk) {
705 /* Nothing to do. */ 927 /* Nothing to do. */
706 } else if (irt_isstr(kt)) { 928 } else if (irt_isstr(kt)) {
707 emit_tsi(as, MIPSI_LW, tmp1, key, (int32_t)offsetof(GCstr, hash)); 929 emit_tsi(as, MIPSI_LW, tmp1, key, (int32_t)offsetof(GCstr, hash));
@@ -711,9 +933,10 @@ static void asm_href(ASMState *as, IRIns *ir)
711 emit_dst(as, MIPSI_XOR, tmp1, tmp1, tmp2); 933 emit_dst(as, MIPSI_XOR, tmp1, tmp1, tmp2);
712 emit_rotr(as, tmp1, tmp1, dest, (-HASH_ROT2-HASH_ROT1)&31); 934 emit_rotr(as, tmp1, tmp1, dest, (-HASH_ROT2-HASH_ROT1)&31);
713 emit_dst(as, MIPSI_SUBU, tmp2, tmp2, dest); 935 emit_dst(as, MIPSI_SUBU, tmp2, tmp2, dest);
714 if (irt_isnum(kt)) { 936#if LJ_32
937 if (LJ_SOFTFP ? (irkey[1].o == IR_HIOP) : irt_isnum(kt)) {
715 emit_dst(as, MIPSI_XOR, tmp2, tmp2, tmp1); 938 emit_dst(as, MIPSI_XOR, tmp2, tmp2, tmp1);
716 if ((as->flags & JIT_F_MIPS32R2)) { 939 if ((as->flags & JIT_F_MIPSXXR2)) {
717 emit_dta(as, MIPSI_ROTR, dest, tmp1, (-HASH_ROT1)&31); 940 emit_dta(as, MIPSI_ROTR, dest, tmp1, (-HASH_ROT1)&31);
718 } else { 941 } else {
719 emit_dst(as, MIPSI_OR, dest, dest, tmp1); 942 emit_dst(as, MIPSI_OR, dest, dest, tmp1);
@@ -721,13 +944,35 @@ static void asm_href(ASMState *as, IRIns *ir)
721 emit_dta(as, MIPSI_SRL, dest, tmp1, (-HASH_ROT1)&31); 944 emit_dta(as, MIPSI_SRL, dest, tmp1, (-HASH_ROT1)&31);
722 } 945 }
723 emit_dst(as, MIPSI_ADDU, tmp1, tmp1, tmp1); 946 emit_dst(as, MIPSI_ADDU, tmp1, tmp1, tmp1);
947#if LJ_SOFTFP
948 emit_ds(as, MIPSI_MOVE, tmp1, type);
949 emit_ds(as, MIPSI_MOVE, tmp2, key);
950#else
724 emit_tg(as, MIPSI_MFC1, tmp2, key); 951 emit_tg(as, MIPSI_MFC1, tmp2, key);
725 emit_tg(as, MIPSI_MFC1, tmp1, key+1); 952 emit_tg(as, MIPSI_MFC1, tmp1, key+1);
953#endif
726 } else { 954 } else {
727 emit_dst(as, MIPSI_XOR, tmp2, key, tmp1); 955 emit_dst(as, MIPSI_XOR, tmp2, key, tmp1);
728 emit_rotr(as, dest, tmp1, tmp2, (-HASH_ROT1)&31); 956 emit_rotr(as, dest, tmp1, tmp2, (-HASH_ROT1)&31);
729 emit_dst(as, MIPSI_ADDU, tmp1, key, ra_allock(as, HASH_BIAS, allow)); 957 emit_dst(as, MIPSI_ADDU, tmp1, key, ra_allock(as, HASH_BIAS, allow));
730 } 958 }
959#else
960 emit_dst(as, MIPSI_XOR, tmp2, tmp2, tmp1);
961 emit_dta(as, MIPSI_ROTR, dest, tmp1, (-HASH_ROT1)&31);
962 if (irt_isnum(kt)) {
963 emit_dst(as, MIPSI_ADDU, tmp1, tmp1, tmp1);
964 emit_dta(as, MIPSI_DSRA32, tmp1, tmp1, 0);
965 emit_dta(as, MIPSI_SLL, tmp2, LJ_SOFTFP ? key : tmp1, 0);
966#if !LJ_SOFTFP
967 emit_tg(as, MIPSI_DMFC1, tmp1, key);
968#endif
969 } else {
970 checkmclim(as);
971 emit_dta(as, MIPSI_DSRA32, tmp1, tmp1, 0);
972 emit_dta(as, MIPSI_SLL, tmp2, key, 0);
973 emit_dst(as, MIPSI_DADDU, tmp1, key, type);
974 }
975#endif
731 } 976 }
732 } 977 }
733} 978}
@@ -740,17 +985,24 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
740 int32_t kofs = ofs + (int32_t)offsetof(Node, key); 985 int32_t kofs = ofs + (int32_t)offsetof(Node, key);
741 Reg dest = (ra_used(ir)||ofs > 32736) ? ra_dest(as, ir, RSET_GPR) : RID_NONE; 986 Reg dest = (ra_used(ir)||ofs > 32736) ? ra_dest(as, ir, RSET_GPR) : RID_NONE;
742 Reg node = ra_alloc1(as, ir->op1, RSET_GPR); 987 Reg node = ra_alloc1(as, ir->op1, RSET_GPR);
743 Reg key = RID_NONE, type = RID_TMP, idx = node;
744 RegSet allow = rset_exclude(RSET_GPR, node); 988 RegSet allow = rset_exclude(RSET_GPR, node);
989 Reg idx = node;
990#if LJ_32
991 Reg key = RID_NONE, type = RID_TMP;
745 int32_t lo, hi; 992 int32_t lo, hi;
993#else
994 Reg key = ra_scratch(as, allow);
995 int64_t k;
996#endif
746 lua_assert(ofs % sizeof(Node) == 0); 997 lua_assert(ofs % sizeof(Node) == 0);
747 if (ofs > 32736) { 998 if (ofs > 32736) {
748 idx = dest; 999 idx = dest;
749 rset_clear(allow, dest); 1000 rset_clear(allow, dest);
750 kofs = (int32_t)offsetof(Node, key); 1001 kofs = (int32_t)offsetof(Node, key);
751 } else if (ra_hasreg(dest)) { 1002 } else if (ra_hasreg(dest)) {
752 emit_tsi(as, MIPSI_ADDIU, dest, node, ofs); 1003 emit_tsi(as, MIPSI_AADDIU, dest, node, ofs);
753 } 1004 }
1005#if LJ_32
754 if (!irt_ispri(irkey->t)) { 1006 if (!irt_ispri(irkey->t)) {
755 key = ra_scratch(as, allow); 1007 key = ra_scratch(as, allow);
756 rset_clear(allow, key); 1008 rset_clear(allow, key);
@@ -769,22 +1021,20 @@ nolo:
769 asm_guard(as, MIPSI_BNE, type, hi ? ra_allock(as, hi, allow) : RID_ZERO); 1021 asm_guard(as, MIPSI_BNE, type, hi ? ra_allock(as, hi, allow) : RID_ZERO);
770 if (ra_hasreg(key)) emit_tsi(as, MIPSI_LW, key, idx, kofs+(LJ_BE?4:0)); 1022 if (ra_hasreg(key)) emit_tsi(as, MIPSI_LW, key, idx, kofs+(LJ_BE?4:0));
771 emit_tsi(as, MIPSI_LW, type, idx, kofs+(LJ_BE?0:4)); 1023 emit_tsi(as, MIPSI_LW, type, idx, kofs+(LJ_BE?0:4));
772 if (ofs > 32736) 1024#else
773 emit_tsi(as, MIPSI_ADDU, dest, node, ra_allock(as, ofs, allow)); 1025 if (irt_ispri(irkey->t)) {
774} 1026 lua_assert(!irt_isnil(irkey->t));
775 1027 k = ~((int64_t)~irt_toitype(irkey->t) << 47);
776static void asm_newref(ASMState *as, IRIns *ir) 1028 } else if (irt_isnum(irkey->t)) {
777{ 1029 k = (int64_t)ir_knum(irkey)->u64;
778 if (ir->r != RID_SINK) { 1030 } else {
779 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey]; 1031 k = ((int64_t)irt_toitype(irkey->t) << 47) | (int64_t)ir_kgc(irkey);
780 IRRef args[3];
781 args[0] = ASMREF_L; /* lua_State *L */
782 args[1] = ir->op1; /* GCtab *t */
783 args[2] = ASMREF_TMP1; /* cTValue *key */
784 asm_setupresult(as, ir, ci); /* TValue * */
785 asm_gencall(as, ci, args);
786 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2);
787 } 1032 }
1033 asm_guard(as, MIPSI_BNE, key, ra_allock(as, k, allow));
1034 emit_tsi(as, MIPSI_LD, key, idx, kofs);
1035#endif
1036 if (ofs > 32736)
1037 emit_tsi(as, MIPSI_AADDU, dest, node, ra_allock(as, ofs, allow));
788} 1038}
789 1039
790static void asm_uref(ASMState *as, IRIns *ir) 1040static void asm_uref(ASMState *as, IRIns *ir)
@@ -793,19 +1043,19 @@ static void asm_uref(ASMState *as, IRIns *ir)
793 if (irref_isk(ir->op1)) { 1043 if (irref_isk(ir->op1)) {
794 GCfunc *fn = ir_kfunc(IR(ir->op1)); 1044 GCfunc *fn = ir_kfunc(IR(ir->op1));
795 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; 1045 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
796 emit_lsptr(as, MIPSI_LW, dest, v, RSET_GPR); 1046 emit_lsptr(as, MIPSI_AL, dest, v, RSET_GPR);
797 } else { 1047 } else {
798 Reg uv = ra_scratch(as, RSET_GPR); 1048 Reg uv = ra_scratch(as, RSET_GPR);
799 Reg func = ra_alloc1(as, ir->op1, RSET_GPR); 1049 Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
800 if (ir->o == IR_UREFC) { 1050 if (ir->o == IR_UREFC) {
801 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO); 1051 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO);
802 emit_tsi(as, MIPSI_ADDIU, dest, uv, (int32_t)offsetof(GCupval, tv)); 1052 emit_tsi(as, MIPSI_AADDIU, dest, uv, (int32_t)offsetof(GCupval, tv));
803 emit_tsi(as, MIPSI_LBU, RID_TMP, uv, (int32_t)offsetof(GCupval, closed)); 1053 emit_tsi(as, MIPSI_LBU, RID_TMP, uv, (int32_t)offsetof(GCupval, closed));
804 } else { 1054 } else {
805 emit_tsi(as, MIPSI_LW, dest, uv, (int32_t)offsetof(GCupval, v)); 1055 emit_tsi(as, MIPSI_AL, dest, uv, (int32_t)offsetof(GCupval, v));
806 } 1056 }
807 emit_tsi(as, MIPSI_LW, uv, func, 1057 emit_tsi(as, MIPSI_AL, uv, func, (int32_t)offsetof(GCfuncL, uvptr) +
808 (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8)); 1058 (int32_t)sizeof(MRef) * (int32_t)(ir->op2 >> 8));
809 } 1059 }
810} 1060}
811 1061
@@ -817,6 +1067,7 @@ static void asm_fref(ASMState *as, IRIns *ir)
817 1067
818static void asm_strref(ASMState *as, IRIns *ir) 1068static void asm_strref(ASMState *as, IRIns *ir)
819{ 1069{
1070#if LJ_32
820 Reg dest = ra_dest(as, ir, RSET_GPR); 1071 Reg dest = ra_dest(as, ir, RSET_GPR);
821 IRRef ref = ir->op2, refk = ir->op1; 1072 IRRef ref = ir->op2, refk = ir->op1;
822 int32_t ofs = (int32_t)sizeof(GCstr); 1073 int32_t ofs = (int32_t)sizeof(GCstr);
@@ -848,6 +1099,20 @@ static void asm_strref(ASMState *as, IRIns *ir)
848 else 1099 else
849 emit_dst(as, MIPSI_ADDU, dest, r, 1100 emit_dst(as, MIPSI_ADDU, dest, r,
850 ra_allock(as, ofs, rset_exclude(RSET_GPR, r))); 1101 ra_allock(as, ofs, rset_exclude(RSET_GPR, r)));
1102#else
1103 RegSet allow = RSET_GPR;
1104 Reg dest = ra_dest(as, ir, allow);
1105 Reg base = ra_alloc1(as, ir->op1, allow);
1106 IRIns *irr = IR(ir->op2);
1107 int32_t ofs = sizeof(GCstr);
1108 rset_clear(allow, base);
1109 if (irref_isk(ir->op2) && checki16(ofs + irr->i)) {
1110 emit_tsi(as, MIPSI_DADDIU, dest, base, ofs + irr->i);
1111 } else {
1112 emit_tsi(as, MIPSI_DADDIU, dest, dest, ofs);
1113 emit_dst(as, MIPSI_DADDU, dest, base, ra_alloc1(as, ir->op2, allow));
1114 }
1115#endif
851} 1116}
852 1117
853/* -- Loads and stores ---------------------------------------------------- */ 1118/* -- Loads and stores ---------------------------------------------------- */
@@ -859,9 +1124,9 @@ static MIPSIns asm_fxloadins(IRIns *ir)
859 case IRT_U8: return MIPSI_LBU; 1124 case IRT_U8: return MIPSI_LBU;
860 case IRT_I16: return MIPSI_LH; 1125 case IRT_I16: return MIPSI_LH;
861 case IRT_U16: return MIPSI_LHU; 1126 case IRT_U16: return MIPSI_LHU;
862 case IRT_NUM: return MIPSI_LDC1; 1127 case IRT_NUM: lua_assert(!LJ_SOFTFP); return MIPSI_LDC1;
863 case IRT_FLOAT: return MIPSI_LWC1; 1128 case IRT_FLOAT: if (!LJ_SOFTFP) return MIPSI_LWC1;
864 default: return MIPSI_LW; 1129 default: return (LJ_64 && irt_is64(ir->t)) ? MIPSI_LD : MIPSI_LW;
865 } 1130 }
866} 1131}
867 1132
@@ -870,26 +1135,32 @@ static MIPSIns asm_fxstoreins(IRIns *ir)
870 switch (irt_type(ir->t)) { 1135 switch (irt_type(ir->t)) {
871 case IRT_I8: case IRT_U8: return MIPSI_SB; 1136 case IRT_I8: case IRT_U8: return MIPSI_SB;
872 case IRT_I16: case IRT_U16: return MIPSI_SH; 1137 case IRT_I16: case IRT_U16: return MIPSI_SH;
873 case IRT_NUM: return MIPSI_SDC1; 1138 case IRT_NUM: lua_assert(!LJ_SOFTFP); return MIPSI_SDC1;
874 case IRT_FLOAT: return MIPSI_SWC1; 1139 case IRT_FLOAT: if (!LJ_SOFTFP) return MIPSI_SWC1;
875 default: return MIPSI_SW; 1140 default: return (LJ_64 && irt_is64(ir->t)) ? MIPSI_SD : MIPSI_SW;
876 } 1141 }
877} 1142}
878 1143
879static void asm_fload(ASMState *as, IRIns *ir) 1144static void asm_fload(ASMState *as, IRIns *ir)
880{ 1145{
881 Reg dest = ra_dest(as, ir, RSET_GPR); 1146 Reg dest = ra_dest(as, ir, RSET_GPR);
882 Reg idx = ra_alloc1(as, ir->op1, RSET_GPR);
883 MIPSIns mi = asm_fxloadins(ir); 1147 MIPSIns mi = asm_fxloadins(ir);
1148 Reg idx;
884 int32_t ofs; 1149 int32_t ofs;
885 if (ir->op2 == IRFL_TAB_ARRAY) { 1150 if (ir->op1 == REF_NIL) {
886 ofs = asm_fuseabase(as, ir->op1); 1151 idx = RID_JGL;
887 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ 1152 ofs = (ir->op2 << 2) - 32768 - GG_OFS(g);
888 emit_tsi(as, MIPSI_ADDIU, dest, idx, ofs); 1153 } else {
889 return; 1154 idx = ra_alloc1(as, ir->op1, RSET_GPR);
1155 if (ir->op2 == IRFL_TAB_ARRAY) {
1156 ofs = asm_fuseabase(as, ir->op1);
1157 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */
1158 emit_tsi(as, MIPSI_AADDIU, dest, idx, ofs);
1159 return;
1160 }
890 } 1161 }
1162 ofs = field_ofs[ir->op2];
891 } 1163 }
892 ofs = field_ofs[ir->op2];
893 lua_assert(!irt_isfp(ir->t)); 1164 lua_assert(!irt_isfp(ir->t));
894 emit_tsi(as, mi, dest, idx, ofs); 1165 emit_tsi(as, mi, dest, idx, ofs);
895} 1166}
@@ -909,43 +1180,79 @@ static void asm_fstore(ASMState *as, IRIns *ir)
909 1180
910static void asm_xload(ASMState *as, IRIns *ir) 1181static void asm_xload(ASMState *as, IRIns *ir)
911{ 1182{
912 Reg dest = ra_dest(as, ir, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); 1183 Reg dest = ra_dest(as, ir,
1184 (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR);
913 lua_assert(!(ir->op2 & IRXLOAD_UNALIGNED)); 1185 lua_assert(!(ir->op2 & IRXLOAD_UNALIGNED));
914 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0); 1186 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0);
915} 1187}
916 1188
917static void asm_xstore(ASMState *as, IRIns *ir, int32_t ofs) 1189static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs)
918{ 1190{
919 if (ir->r != RID_SINK) { 1191 if (ir->r != RID_SINK) {
920 Reg src = ra_alloc1z(as, ir->op2, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); 1192 Reg src = ra_alloc1z(as, ir->op2,
1193 (!LJ_SOFTFP && irt_isfp(ir->t)) ? RSET_FPR : RSET_GPR);
921 asm_fusexref(as, asm_fxstoreins(ir), src, ir->op1, 1194 asm_fusexref(as, asm_fxstoreins(ir), src, ir->op1,
922 rset_exclude(RSET_GPR, src), ofs); 1195 rset_exclude(RSET_GPR, src), ofs);
923 } 1196 }
924} 1197}
925 1198
1199#define asm_xstore(as, ir) asm_xstore_(as, ir, 0)
1200
926static void asm_ahuvload(ASMState *as, IRIns *ir) 1201static void asm_ahuvload(ASMState *as, IRIns *ir)
927{ 1202{
928 IRType1 t = ir->t; 1203 int hiop = (LJ_32 && LJ_SOFTFP && (ir+1)->o == IR_HIOP);
929 Reg dest = RID_NONE, type = RID_TMP, idx; 1204 Reg dest = RID_NONE, type = RID_TMP, idx;
930 RegSet allow = RSET_GPR; 1205 RegSet allow = RSET_GPR;
931 int32_t ofs = 0; 1206 int32_t ofs = 0;
1207 IRType1 t = ir->t;
1208 if (hiop) {
1209 t.irt = IRT_NUM;
1210 if (ra_used(ir+1)) {
1211 type = ra_dest(as, ir+1, allow);
1212 rset_clear(allow, type);
1213 }
1214 }
932 if (ra_used(ir)) { 1215 if (ra_used(ir)) {
933 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t)); 1216 lua_assert((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) ||
934 dest = ra_dest(as, ir, irt_isnum(t) ? RSET_FPR : RSET_GPR); 1217 irt_isint(ir->t) || irt_isaddr(ir->t));
1218 dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow);
935 rset_clear(allow, dest); 1219 rset_clear(allow, dest);
1220#if LJ_64
1221 if (irt_isaddr(t))
1222 emit_tsml(as, MIPSI_DEXTM, dest, dest, 14, 0);
1223 else if (irt_isint(t))
1224 emit_dta(as, MIPSI_SLL, dest, dest, 0);
1225#endif
936 } 1226 }
937 idx = asm_fuseahuref(as, ir->op1, &ofs, allow); 1227 idx = asm_fuseahuref(as, ir->op1, &ofs, allow);
938 rset_clear(allow, idx); 1228 rset_clear(allow, idx);
939 if (irt_isnum(t)) { 1229 if (irt_isnum(t)) {
940 asm_guard(as, MIPSI_BEQ, type, RID_ZERO); 1230 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO);
941 emit_tsi(as, MIPSI_SLTIU, type, type, (int32_t)LJ_TISNUM); 1231 emit_tsi(as, MIPSI_SLTIU, RID_TMP, type, (int32_t)LJ_TISNUM);
942 if (ra_hasreg(dest))
943 emit_hsi(as, MIPSI_LDC1, dest, idx, ofs);
944 } else { 1232 } else {
945 asm_guard(as, MIPSI_BNE, type, ra_allock(as, irt_toitype(t), allow)); 1233 asm_guard(as, MIPSI_BNE, type,
946 if (ra_hasreg(dest)) emit_tsi(as, MIPSI_LW, dest, idx, ofs+(LJ_BE?4:0)); 1234 ra_allock(as, (int32_t)irt_toitype(t), allow));
1235 }
1236#if LJ_32
1237 if (ra_hasreg(dest)) {
1238 if (!LJ_SOFTFP && irt_isnum(t))
1239 emit_hsi(as, MIPSI_LDC1, dest, idx, ofs);
1240 else
1241 emit_tsi(as, MIPSI_LW, dest, idx, ofs+(LJ_BE?4:0));
947 } 1242 }
948 emit_tsi(as, MIPSI_LW, type, idx, ofs+(LJ_BE?0:4)); 1243 emit_tsi(as, MIPSI_LW, type, idx, ofs+(LJ_BE?0:4));
1244#else
1245 if (ra_hasreg(dest)) {
1246 if (!LJ_SOFTFP && irt_isnum(t)) {
1247 emit_hsi(as, MIPSI_LDC1, dest, idx, ofs);
1248 dest = type;
1249 }
1250 } else {
1251 dest = type;
1252 }
1253 emit_dta(as, MIPSI_DSRA32, type, dest, 15);
1254 emit_tsi(as, MIPSI_LD, dest, idx, ofs);
1255#endif
949} 1256}
950 1257
951static void asm_ahustore(ASMState *as, IRIns *ir) 1258static void asm_ahustore(ASMState *as, IRIns *ir)
@@ -955,50 +1262,90 @@ static void asm_ahustore(ASMState *as, IRIns *ir)
955 int32_t ofs = 0; 1262 int32_t ofs = 0;
956 if (ir->r == RID_SINK) 1263 if (ir->r == RID_SINK)
957 return; 1264 return;
958 if (irt_isnum(ir->t)) { 1265 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
959 src = ra_alloc1(as, ir->op2, RSET_FPR); 1266 src = ra_alloc1(as, ir->op2, RSET_FPR);
1267 idx = asm_fuseahuref(as, ir->op1, &ofs, allow);
1268 emit_hsi(as, MIPSI_SDC1, src, idx, ofs);
960 } else { 1269 } else {
1270#if LJ_32
961 if (!irt_ispri(ir->t)) { 1271 if (!irt_ispri(ir->t)) {
962 src = ra_alloc1(as, ir->op2, allow); 1272 src = ra_alloc1(as, ir->op2, allow);
963 rset_clear(allow, src); 1273 rset_clear(allow, src);
964 } 1274 }
965 type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); 1275 if (LJ_SOFTFP && (ir+1)->o == IR_HIOP)
1276 type = ra_alloc1(as, (ir+1)->op2, allow);
1277 else
1278 type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow);
966 rset_clear(allow, type); 1279 rset_clear(allow, type);
967 } 1280 idx = asm_fuseahuref(as, ir->op1, &ofs, allow);
968 idx = asm_fuseahuref(as, ir->op1, &ofs, allow);
969 if (irt_isnum(ir->t)) {
970 emit_hsi(as, MIPSI_SDC1, src, idx, ofs);
971 } else {
972 if (ra_hasreg(src)) 1281 if (ra_hasreg(src))
973 emit_tsi(as, MIPSI_SW, src, idx, ofs+(LJ_BE?4:0)); 1282 emit_tsi(as, MIPSI_SW, src, idx, ofs+(LJ_BE?4:0));
974 emit_tsi(as, MIPSI_SW, type, idx, ofs+(LJ_BE?0:4)); 1283 emit_tsi(as, MIPSI_SW, type, idx, ofs+(LJ_BE?0:4));
1284#else
1285 Reg tmp = RID_TMP;
1286 if (irt_ispri(ir->t)) {
1287 tmp = ra_allock(as, ~((int64_t)~irt_toitype(ir->t) << 47), allow);
1288 rset_clear(allow, tmp);
1289 } else {
1290 src = ra_alloc1(as, ir->op2, allow);
1291 rset_clear(allow, src);
1292 type = ra_allock(as, (int64_t)irt_toitype(ir->t) << 47, allow);
1293 rset_clear(allow, type);
1294 }
1295 idx = asm_fuseahuref(as, ir->op1, &ofs, allow);
1296 emit_tsi(as, MIPSI_SD, tmp, idx, ofs);
1297 if (ra_hasreg(src)) {
1298 if (irt_isinteger(ir->t)) {
1299 emit_dst(as, MIPSI_DADDU, tmp, tmp, type);
1300 emit_tsml(as, MIPSI_DEXT, tmp, src, 31, 0);
1301 } else {
1302 emit_dst(as, MIPSI_DADDU, tmp, src, type);
1303 }
1304 }
1305#endif
975 } 1306 }
976} 1307}
977 1308
978static void asm_sload(ASMState *as, IRIns *ir) 1309static void asm_sload(ASMState *as, IRIns *ir)
979{ 1310{
980 int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
981 IRType1 t = ir->t;
982 Reg dest = RID_NONE, type = RID_NONE, base; 1311 Reg dest = RID_NONE, type = RID_NONE, base;
983 RegSet allow = RSET_GPR; 1312 RegSet allow = RSET_GPR;
1313 IRType1 t = ir->t;
1314#if LJ_32
1315 int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
1316 int hiop = (LJ_32 && LJ_SOFTFP && (ir+1)->o == IR_HIOP);
1317 if (hiop)
1318 t.irt = IRT_NUM;
1319#else
1320 int32_t ofs = 8*((int32_t)ir->op1-2);
1321#endif
984 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */ 1322 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */
985 lua_assert(irt_isguard(t) || !(ir->op2 & IRSLOAD_TYPECHECK)); 1323 lua_assert(irt_isguard(ir->t) || !(ir->op2 & IRSLOAD_TYPECHECK));
986 lua_assert(!irt_isint(t) || (ir->op2 & (IRSLOAD_CONVERT|IRSLOAD_FRAME))); 1324#if LJ_32 && LJ_SOFTFP
1325 lua_assert(!(ir->op2 & IRSLOAD_CONVERT)); /* Handled by LJ_SOFTFP SPLIT. */
1326 if (hiop && ra_used(ir+1)) {
1327 type = ra_dest(as, ir+1, allow);
1328 rset_clear(allow, type);
1329 }
1330#else
987 if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) { 1331 if ((ir->op2 & IRSLOAD_CONVERT) && irt_isguard(t) && irt_isint(t)) {
988 dest = ra_scratch(as, RSET_FPR); 1332 dest = ra_scratch(as, RSET_FPR);
989 asm_tointg(as, ir, dest); 1333 asm_tointg(as, ir, dest);
990 t.irt = IRT_NUM; /* Continue with a regular number type check. */ 1334 t.irt = IRT_NUM; /* Continue with a regular number type check. */
991 } else if (ra_used(ir)) { 1335 } else
992 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t)); 1336#endif
993 dest = ra_dest(as, ir, irt_isnum(t) ? RSET_FPR : RSET_GPR); 1337 if (ra_used(ir)) {
1338 lua_assert((LJ_SOFTFP ? 0 : irt_isnum(ir->t)) ||
1339 irt_isint(ir->t) || irt_isaddr(ir->t));
1340 dest = ra_dest(as, ir, (!LJ_SOFTFP && irt_isnum(t)) ? RSET_FPR : allow);
994 rset_clear(allow, dest); 1341 rset_clear(allow, dest);
995 base = ra_alloc1(as, REF_BASE, allow); 1342 base = ra_alloc1(as, REF_BASE, allow);
996 rset_clear(allow, base); 1343 rset_clear(allow, base);
997 if ((ir->op2 & IRSLOAD_CONVERT)) { 1344 if (!LJ_SOFTFP && (ir->op2 & IRSLOAD_CONVERT)) {
998 if (irt_isint(t)) { 1345 if (irt_isint(t)) {
999 Reg tmp = ra_scratch(as, RSET_FPR); 1346 Reg tmp = ra_scratch(as, RSET_FPR);
1000 emit_tg(as, MIPSI_MFC1, dest, tmp); 1347 emit_tg(as, MIPSI_MFC1, dest, tmp);
1001 emit_fg(as, MIPSI_CVT_W_D, tmp, tmp); 1348 emit_fg(as, MIPSI_TRUNC_W_D, tmp, tmp);
1002 dest = tmp; 1349 dest = tmp;
1003 t.irt = IRT_NUM; /* Check for original type. */ 1350 t.irt = IRT_NUM; /* Check for original type. */
1004 } else { 1351 } else {
@@ -1009,27 +1356,67 @@ static void asm_sload(ASMState *as, IRIns *ir)
1009 t.irt = IRT_INT; /* Check for original type. */ 1356 t.irt = IRT_INT; /* Check for original type. */
1010 } 1357 }
1011 } 1358 }
1359#if LJ_64
1360 else if (irt_isaddr(t)) {
1361 /* Clear type from pointers. */
1362 emit_tsml(as, MIPSI_DEXTM, dest, dest, 14, 0);
1363 } else if (irt_isint(t) && (ir->op2 & IRSLOAD_TYPECHECK)) {
1364 /* Sign-extend integers. */
1365 emit_dta(as, MIPSI_SLL, dest, dest, 0);
1366 }
1367#endif
1012 goto dotypecheck; 1368 goto dotypecheck;
1013 } 1369 }
1014 base = ra_alloc1(as, REF_BASE, allow); 1370 base = ra_alloc1(as, REF_BASE, allow);
1015 rset_clear(allow, base); 1371 rset_clear(allow, base);
1016dotypecheck: 1372dotypecheck:
1017 if (irt_isnum(t)) { 1373#if LJ_32
1018 if ((ir->op2 & IRSLOAD_TYPECHECK)) { 1374 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1019 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO); 1375 if (ra_noreg(type))
1020 emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)LJ_TISNUM);
1021 type = RID_TMP; 1376 type = RID_TMP;
1022 } 1377 if (irt_isnum(t)) {
1023 if (ra_hasreg(dest)) emit_hsi(as, MIPSI_LDC1, dest, base, ofs); 1378 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO);
1024 } else { 1379 emit_tsi(as, MIPSI_SLTIU, RID_TMP, type, (int32_t)LJ_TISNUM);
1025 if ((ir->op2 & IRSLOAD_TYPECHECK)) { 1380 } else {
1026 Reg ktype = ra_allock(as, irt_toitype(t), allow); 1381 Reg ktype = ra_allock(as, irt_toitype(t), allow);
1027 asm_guard(as, MIPSI_BNE, RID_TMP, ktype); 1382 asm_guard(as, MIPSI_BNE, type, ktype);
1028 type = RID_TMP;
1029 } 1383 }
1030 if (ra_hasreg(dest)) emit_tsi(as, MIPSI_LW, dest, base, ofs ^ (LJ_BE?4:0));
1031 } 1384 }
1032 if (ra_hasreg(type)) emit_tsi(as, MIPSI_LW, type, base, ofs ^ (LJ_BE?0:4)); 1385 if (ra_hasreg(dest)) {
1386 if (!LJ_SOFTFP && irt_isnum(t))
1387 emit_hsi(as, MIPSI_LDC1, dest, base, ofs);
1388 else
1389 emit_tsi(as, MIPSI_LW, dest, base, ofs ^ (LJ_BE?4:0));
1390 }
1391 if (ra_hasreg(type))
1392 emit_tsi(as, MIPSI_LW, type, base, ofs ^ (LJ_BE?0:4));
1393#else
1394 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1395 type = dest < RID_MAX_GPR ? dest : RID_TMP;
1396 if (irt_ispri(t)) {
1397 asm_guard(as, MIPSI_BNE, type,
1398 ra_allock(as, ~((int64_t)~irt_toitype(t) << 47) , allow));
1399 } else {
1400 if (irt_isnum(t)) {
1401 asm_guard(as, MIPSI_BEQ, RID_TMP, RID_ZERO);
1402 emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)LJ_TISNUM);
1403 if (ra_hasreg(dest))
1404 emit_hsi(as, MIPSI_LDC1, dest, base, ofs);
1405 } else {
1406 asm_guard(as, MIPSI_BNE, RID_TMP,
1407 ra_allock(as, (int32_t)irt_toitype(t), allow));
1408 }
1409 emit_dta(as, MIPSI_DSRA32, RID_TMP, type, 15);
1410 }
1411 emit_tsi(as, MIPSI_LD, type, base, ofs);
1412 } else if (ra_hasreg(dest)) {
1413 if (irt_isnum(t))
1414 emit_hsi(as, MIPSI_LDC1, dest, base, ofs);
1415 else
1416 emit_tsi(as, irt_isint(t) ? MIPSI_LW : MIPSI_LD, dest, base,
1417 ofs ^ ((LJ_BE && irt_isint(t)) ? 4 : 0));
1418 }
1419#endif
1033} 1420}
1034 1421
1035/* -- Allocations --------------------------------------------------------- */ 1422/* -- Allocations --------------------------------------------------------- */
@@ -1038,19 +1425,15 @@ dotypecheck:
1038static void asm_cnew(ASMState *as, IRIns *ir) 1425static void asm_cnew(ASMState *as, IRIns *ir)
1039{ 1426{
1040 CTState *cts = ctype_ctsG(J2G(as->J)); 1427 CTState *cts = ctype_ctsG(J2G(as->J));
1041 CTypeID ctypeid = (CTypeID)IR(ir->op1)->i; 1428 CTypeID id = (CTypeID)IR(ir->op1)->i;
1042 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ? 1429 CTSize sz;
1043 lj_ctype_size(cts, ctypeid) : (CTSize)IR(ir->op2)->i; 1430 CTInfo info = lj_ctype_info(cts, id, &sz);
1044 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; 1431 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1045 IRRef args[2]; 1432 IRRef args[4];
1046 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1047 RegSet drop = RSET_SCRATCH; 1433 RegSet drop = RSET_SCRATCH;
1048 lua_assert(sz != CTSIZE_INVALID); 1434 lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));
1049 1435
1050 args[0] = ASMREF_L; /* lua_State *L */
1051 args[1] = ASMREF_TMP1; /* MSize size */
1052 as->gcsteps++; 1436 as->gcsteps++;
1053
1054 if (ra_hasreg(ir->r)) 1437 if (ra_hasreg(ir->r))
1055 rset_clear(drop, ir->r); /* Dest reg handled below. */ 1438 rset_clear(drop, ir->r); /* Dest reg handled below. */
1056 ra_evictset(as, drop); 1439 ra_evictset(as, drop);
@@ -1059,8 +1442,9 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1059 1442
1060 /* Initialize immutable cdata object. */ 1443 /* Initialize immutable cdata object. */
1061 if (ir->o == IR_CNEWI) { 1444 if (ir->o == IR_CNEWI) {
1445 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1446#if LJ_32
1062 int32_t ofs = sizeof(GCcdata); 1447 int32_t ofs = sizeof(GCcdata);
1063 lua_assert(sz == 4 || sz == 8);
1064 if (sz == 8) { 1448 if (sz == 8) {
1065 ofs += 4; 1449 ofs += 4;
1066 lua_assert((ir+1)->o == IR_HIOP); 1450 lua_assert((ir+1)->o == IR_HIOP);
@@ -1073,12 +1457,29 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1073 if (ofs == sizeof(GCcdata)) break; 1457 if (ofs == sizeof(GCcdata)) break;
1074 ofs -= 4; if (LJ_BE) ir++; else ir--; 1458 ofs -= 4; if (LJ_BE) ir++; else ir--;
1075 } 1459 }
1460#else
1461 emit_tsi(as, MIPSI_SD, ra_alloc1(as, ir->op2, allow),
1462 RID_RET, sizeof(GCcdata));
1463#endif
1464 lua_assert(sz == 4 || sz == 8);
1465 } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */
1466 ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
1467 args[0] = ASMREF_L; /* lua_State *L */
1468 args[1] = ir->op1; /* CTypeID id */
1469 args[2] = ir->op2; /* CTSize sz */
1470 args[3] = ASMREF_TMP1; /* CTSize align */
1471 asm_gencall(as, ci, args);
1472 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
1473 return;
1076 } 1474 }
1475
1077 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ 1476 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */
1078 emit_tsi(as, MIPSI_SB, RID_RET+1, RID_RET, offsetof(GCcdata, gct)); 1477 emit_tsi(as, MIPSI_SB, RID_RET+1, RID_RET, offsetof(GCcdata, gct));
1079 emit_tsi(as, MIPSI_SH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid)); 1478 emit_tsi(as, MIPSI_SH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid));
1080 emit_ti(as, MIPSI_LI, RID_RET+1, ~LJ_TCDATA); 1479 emit_ti(as, MIPSI_LI, RID_RET+1, ~LJ_TCDATA);
1081 emit_ti(as, MIPSI_LI, RID_TMP, ctypeid); /* Lower 16 bit used. Sign-ext ok. */ 1480 emit_ti(as, MIPSI_LI, RID_TMP, id); /* Lower 16 bit used. Sign-ext ok. */
1481 args[0] = ASMREF_L; /* lua_State *L */
1482 args[1] = ASMREF_TMP1; /* MSize size */
1082 asm_gencall(as, ci, args); 1483 asm_gencall(as, ci, args);
1083 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), 1484 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)),
1084 ra_releasetmp(as, ASMREF_TMP1)); 1485 ra_releasetmp(as, ASMREF_TMP1));
@@ -1095,7 +1496,7 @@ static void asm_tbar(ASMState *as, IRIns *ir)
1095 Reg mark = ra_scratch(as, rset_exclude(RSET_GPR, tab)); 1496 Reg mark = ra_scratch(as, rset_exclude(RSET_GPR, tab));
1096 Reg link = RID_TMP; 1497 Reg link = RID_TMP;
1097 MCLabel l_end = emit_label(as); 1498 MCLabel l_end = emit_label(as);
1098 emit_tsi(as, MIPSI_SW, link, tab, (int32_t)offsetof(GCtab, gclist)); 1499 emit_tsi(as, MIPSI_AS, link, tab, (int32_t)offsetof(GCtab, gclist));
1099 emit_tsi(as, MIPSI_SB, mark, tab, (int32_t)offsetof(GCtab, marked)); 1500 emit_tsi(as, MIPSI_SB, mark, tab, (int32_t)offsetof(GCtab, marked));
1100 emit_setgl(as, tab, gc.grayagain); 1501 emit_setgl(as, tab, gc.grayagain);
1101 emit_getgl(as, link, gc.grayagain); 1502 emit_getgl(as, link, gc.grayagain);
@@ -1118,7 +1519,7 @@ static void asm_obar(ASMState *as, IRIns *ir)
1118 args[0] = ASMREF_TMP1; /* global_State *g */ 1519 args[0] = ASMREF_TMP1; /* global_State *g */
1119 args[1] = ir->op1; /* TValue *tv */ 1520 args[1] = ir->op1; /* TValue *tv */
1120 asm_gencall(as, ci, args); 1521 asm_gencall(as, ci, args);
1121 emit_tsi(as, MIPSI_ADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); 1522 emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768);
1122 obj = IR(ir->op1)->r; 1523 obj = IR(ir->op1)->r;
1123 tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj)); 1524 tmp = ra_scratch(as, rset_exclude(RSET_GPR, obj));
1124 emit_branch(as, MIPSI_BEQ, RID_TMP, RID_ZERO, l_end); 1525 emit_branch(as, MIPSI_BEQ, RID_TMP, RID_ZERO, l_end);
@@ -1133,6 +1534,7 @@ static void asm_obar(ASMState *as, IRIns *ir)
1133 1534
1134/* -- Arithmetic and logic operations ------------------------------------- */ 1535/* -- Arithmetic and logic operations ------------------------------------- */
1135 1536
1537#if !LJ_SOFTFP
1136static void asm_fparith(ASMState *as, IRIns *ir, MIPSIns mi) 1538static void asm_fparith(ASMState *as, IRIns *ir, MIPSIns mi)
1137{ 1539{
1138 Reg dest = ra_dest(as, ir, RSET_FPR); 1540 Reg dest = ra_dest(as, ir, RSET_FPR);
@@ -1148,82 +1550,138 @@ static void asm_fpunary(ASMState *as, IRIns *ir, MIPSIns mi)
1148 emit_fg(as, mi, dest, left); 1550 emit_fg(as, mi, dest, left);
1149} 1551}
1150 1552
1151static int asm_fpjoin_pow(ASMState *as, IRIns *ir) 1553static void asm_fpmath(ASMState *as, IRIns *ir)
1152{ 1554{
1153 IRIns *irp = IR(ir->op1); 1555 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
1154 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) { 1556 return;
1155 IRIns *irpp = IR(irp->op1); 1557 if (ir->op2 <= IRFPM_TRUNC)
1156 if (irpp == ir-2 && irpp->o == IR_FPMATH && 1558 asm_callround(as, ir, IRCALL_lj_vm_floor + ir->op2);
1157 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) { 1559 else if (ir->op2 == IRFPM_SQRT)
1158 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow]; 1560 asm_fpunary(as, ir, MIPSI_SQRT_D);
1159 IRRef args[2]; 1561 else
1160 args[0] = irpp->op1; 1562 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
1161 args[1] = irp->op2;
1162 asm_setupresult(as, ir, ci);
1163 asm_gencall(as, ci, args);
1164 return 1;
1165 }
1166 }
1167 return 0;
1168} 1563}
1564#endif
1169 1565
1170static void asm_add(ASMState *as, IRIns *ir) 1566static void asm_add(ASMState *as, IRIns *ir)
1171{ 1567{
1172 if (irt_isnum(ir->t)) { 1568 IRType1 t = ir->t;
1569#if !LJ_SOFTFP
1570 if (irt_isnum(t)) {
1173 asm_fparith(as, ir, MIPSI_ADD_D); 1571 asm_fparith(as, ir, MIPSI_ADD_D);
1174 } else { 1572 } else
1573#endif
1574 {
1175 Reg dest = ra_dest(as, ir, RSET_GPR); 1575 Reg dest = ra_dest(as, ir, RSET_GPR);
1176 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); 1576 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1177 if (irref_isk(ir->op2)) { 1577 if (irref_isk(ir->op2)) {
1178 int32_t k = IR(ir->op2)->i; 1578 intptr_t k = get_kval(IR(ir->op2));
1179 if (checki16(k)) { 1579 if (checki16(k)) {
1180 emit_tsi(as, MIPSI_ADDIU, dest, left, k); 1580 emit_tsi(as, (LJ_64 && irt_is64(t)) ? MIPSI_DADDIU : MIPSI_ADDIU, dest,
1581 left, k);
1181 return; 1582 return;
1182 } 1583 }
1183 } 1584 }
1184 right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left)); 1585 right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1185 emit_dst(as, MIPSI_ADDU, dest, left, right); 1586 emit_dst(as, (LJ_64 && irt_is64(t)) ? MIPSI_DADDU : MIPSI_ADDU, dest,
1587 left, right);
1186 } 1588 }
1187} 1589}
1188 1590
1189static void asm_sub(ASMState *as, IRIns *ir) 1591static void asm_sub(ASMState *as, IRIns *ir)
1190{ 1592{
1593#if !LJ_SOFTFP
1191 if (irt_isnum(ir->t)) { 1594 if (irt_isnum(ir->t)) {
1192 asm_fparith(as, ir, MIPSI_SUB_D); 1595 asm_fparith(as, ir, MIPSI_SUB_D);
1193 } else { 1596 } else
1597#endif
1598 {
1194 Reg dest = ra_dest(as, ir, RSET_GPR); 1599 Reg dest = ra_dest(as, ir, RSET_GPR);
1195 Reg right, left = ra_alloc2(as, ir, RSET_GPR); 1600 Reg right, left = ra_alloc2(as, ir, RSET_GPR);
1196 right = (left >> 8); left &= 255; 1601 right = (left >> 8); left &= 255;
1197 emit_dst(as, MIPSI_SUBU, dest, left, right); 1602 emit_dst(as, (LJ_64 && irt_is64(ir->t)) ? MIPSI_DSUBU : MIPSI_SUBU, dest,
1603 left, right);
1198 } 1604 }
1199} 1605}
1200 1606
1201static void asm_mul(ASMState *as, IRIns *ir) 1607static void asm_mul(ASMState *as, IRIns *ir)
1202{ 1608{
1609#if !LJ_SOFTFP
1203 if (irt_isnum(ir->t)) { 1610 if (irt_isnum(ir->t)) {
1204 asm_fparith(as, ir, MIPSI_MUL_D); 1611 asm_fparith(as, ir, MIPSI_MUL_D);
1205 } else { 1612 } else
1613#endif
1614 {
1206 Reg dest = ra_dest(as, ir, RSET_GPR); 1615 Reg dest = ra_dest(as, ir, RSET_GPR);
1207 Reg right, left = ra_alloc2(as, ir, RSET_GPR); 1616 Reg right, left = ra_alloc2(as, ir, RSET_GPR);
1208 right = (left >> 8); left &= 255; 1617 right = (left >> 8); left &= 255;
1209 emit_dst(as, MIPSI_MUL, dest, left, right); 1618 if (LJ_64 && irt_is64(ir->t)) {
1619 emit_dst(as, MIPSI_MFLO, dest, 0, 0);
1620 emit_dst(as, MIPSI_DMULT, 0, left, right);
1621 } else {
1622 emit_dst(as, MIPSI_MUL, dest, left, right);
1623 }
1210 } 1624 }
1211} 1625}
1212 1626
1627static void asm_mod(ASMState *as, IRIns *ir)
1628{
1629#if LJ_64 && LJ_HASFFI
1630 if (!irt_isint(ir->t))
1631 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
1632 IRCALL_lj_carith_modu64);
1633 else
1634#endif
1635 asm_callid(as, ir, IRCALL_lj_vm_modi);
1636}
1637
1638#if !LJ_SOFTFP
1639static void asm_pow(ASMState *as, IRIns *ir)
1640{
1641#if LJ_64 && LJ_HASFFI
1642 if (!irt_isnum(ir->t))
1643 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
1644 IRCALL_lj_carith_powu64);
1645 else
1646#endif
1647 asm_callid(as, ir, IRCALL_lj_vm_powi);
1648}
1649
1650static void asm_div(ASMState *as, IRIns *ir)
1651{
1652#if LJ_64 && LJ_HASFFI
1653 if (!irt_isnum(ir->t))
1654 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
1655 IRCALL_lj_carith_divu64);
1656 else
1657#endif
1658 asm_fparith(as, ir, MIPSI_DIV_D);
1659}
1660#endif
1661
1213static void asm_neg(ASMState *as, IRIns *ir) 1662static void asm_neg(ASMState *as, IRIns *ir)
1214{ 1663{
1664#if !LJ_SOFTFP
1215 if (irt_isnum(ir->t)) { 1665 if (irt_isnum(ir->t)) {
1216 asm_fpunary(as, ir, MIPSI_NEG_D); 1666 asm_fpunary(as, ir, MIPSI_NEG_D);
1217 } else { 1667 } else
1668#endif
1669 {
1218 Reg dest = ra_dest(as, ir, RSET_GPR); 1670 Reg dest = ra_dest(as, ir, RSET_GPR);
1219 Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); 1671 Reg left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1220 emit_dst(as, MIPSI_SUBU, dest, RID_ZERO, left); 1672 emit_dst(as, (LJ_64 && irt_is64(ir->t)) ? MIPSI_DSUBU : MIPSI_SUBU, dest,
1673 RID_ZERO, left);
1221 } 1674 }
1222} 1675}
1223 1676
1677#define asm_abs(as, ir) asm_fpunary(as, ir, MIPSI_ABS_D)
1678#define asm_atan2(as, ir) asm_callid(as, ir, IRCALL_atan2)
1679#define asm_ldexp(as, ir) asm_callid(as, ir, IRCALL_ldexp)
1680
1224static void asm_arithov(ASMState *as, IRIns *ir) 1681static void asm_arithov(ASMState *as, IRIns *ir)
1225{ 1682{
1226 Reg right, left, tmp, dest = ra_dest(as, ir, RSET_GPR); 1683 Reg right, left, tmp, dest = ra_dest(as, ir, RSET_GPR);
1684 lua_assert(!irt_is64(ir->t));
1227 if (irref_isk(ir->op2)) { 1685 if (irref_isk(ir->op2)) {
1228 int k = IR(ir->op2)->i; 1686 int k = IR(ir->op2)->i;
1229 if (ir->o == IR_SUBOV) k = -k; 1687 if (ir->o == IR_SUBOV) k = -k;
@@ -1254,16 +1712,24 @@ static void asm_arithov(ASMState *as, IRIns *ir)
1254 emit_move(as, RID_TMP, dest == left ? left : right); 1712 emit_move(as, RID_TMP, dest == left ? left : right);
1255} 1713}
1256 1714
1715#define asm_addov(as, ir) asm_arithov(as, ir)
1716#define asm_subov(as, ir) asm_arithov(as, ir)
1717
1257static void asm_mulov(ASMState *as, IRIns *ir) 1718static void asm_mulov(ASMState *as, IRIns *ir)
1258{ 1719{
1259#if LJ_DUALNUM 1720 Reg dest = ra_dest(as, ir, RSET_GPR);
1260#error "NYI: MULOV" 1721 Reg tmp, right, left = ra_alloc2(as, ir, RSET_GPR);
1261#else 1722 right = (left >> 8); left &= 255;
1262 UNUSED(as); UNUSED(ir); lua_assert(0); /* Unused in single-number mode. */ 1723 tmp = ra_scratch(as, rset_exclude(rset_exclude(rset_exclude(RSET_GPR, left),
1263#endif 1724 right), dest));
1725 asm_guard(as, MIPSI_BNE, RID_TMP, tmp);
1726 emit_dta(as, MIPSI_SRA, RID_TMP, dest, 31);
1727 emit_dst(as, MIPSI_MFHI, tmp, 0, 0);
1728 emit_dst(as, MIPSI_MFLO, dest, 0, 0);
1729 emit_dst(as, MIPSI_MULT, 0, left, right);
1264} 1730}
1265 1731
1266#if LJ_HASFFI 1732#if LJ_32 && LJ_HASFFI
1267static void asm_add64(ASMState *as, IRIns *ir) 1733static void asm_add64(ASMState *as, IRIns *ir)
1268{ 1734{
1269 Reg dest = ra_dest(as, ir, RSET_GPR); 1735 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -1347,7 +1813,7 @@ static void asm_neg64(ASMState *as, IRIns *ir)
1347} 1813}
1348#endif 1814#endif
1349 1815
1350static void asm_bitnot(ASMState *as, IRIns *ir) 1816static void asm_bnot(ASMState *as, IRIns *ir)
1351{ 1817{
1352 Reg left, right, dest = ra_dest(as, ir, RSET_GPR); 1818 Reg left, right, dest = ra_dest(as, ir, RSET_GPR);
1353 IRIns *irl = IR(ir->op1); 1819 IRIns *irl = IR(ir->op1);
@@ -1361,11 +1827,12 @@ static void asm_bitnot(ASMState *as, IRIns *ir)
1361 emit_dst(as, MIPSI_NOR, dest, left, right); 1827 emit_dst(as, MIPSI_NOR, dest, left, right);
1362} 1828}
1363 1829
1364static void asm_bitswap(ASMState *as, IRIns *ir) 1830static void asm_bswap(ASMState *as, IRIns *ir)
1365{ 1831{
1366 Reg dest = ra_dest(as, ir, RSET_GPR); 1832 Reg dest = ra_dest(as, ir, RSET_GPR);
1367 Reg left = ra_alloc1(as, ir->op1, RSET_GPR); 1833 Reg left = ra_alloc1(as, ir->op1, RSET_GPR);
1368 if ((as->flags & JIT_F_MIPS32R2)) { 1834#if LJ_32
1835 if ((as->flags & JIT_F_MIPSXXR2)) {
1369 emit_dta(as, MIPSI_ROTR, dest, RID_TMP, 16); 1836 emit_dta(as, MIPSI_ROTR, dest, RID_TMP, 16);
1370 emit_dst(as, MIPSI_WSBH, RID_TMP, 0, left); 1837 emit_dst(as, MIPSI_WSBH, RID_TMP, 0, left);
1371 } else { 1838 } else {
@@ -1380,6 +1847,15 @@ static void asm_bitswap(ASMState *as, IRIns *ir)
1380 emit_dta(as, MIPSI_SRL, tmp, left, 24); 1847 emit_dta(as, MIPSI_SRL, tmp, left, 24);
1381 emit_dta(as, MIPSI_SLL, RID_TMP, left, 24); 1848 emit_dta(as, MIPSI_SLL, RID_TMP, left, 24);
1382 } 1849 }
1850#else
1851 if (irt_is64(ir->t)) {
1852 emit_dst(as, MIPSI_DSHD, dest, 0, RID_TMP);
1853 emit_dst(as, MIPSI_DSBH, RID_TMP, 0, left);
1854 } else {
1855 emit_dta(as, MIPSI_ROTR, dest, RID_TMP, 16);
1856 emit_dst(as, MIPSI_WSBH, RID_TMP, 0, left);
1857 }
1858#endif
1383} 1859}
1384 1860
1385static void asm_bitop(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik) 1861static void asm_bitop(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik)
@@ -1387,7 +1863,7 @@ static void asm_bitop(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik)
1387 Reg dest = ra_dest(as, ir, RSET_GPR); 1863 Reg dest = ra_dest(as, ir, RSET_GPR);
1388 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR); 1864 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1389 if (irref_isk(ir->op2)) { 1865 if (irref_isk(ir->op2)) {
1390 int32_t k = IR(ir->op2)->i; 1866 intptr_t k = get_kval(IR(ir->op2));
1391 if (checku16(k)) { 1867 if (checku16(k)) {
1392 emit_tsi(as, mik, dest, left, k); 1868 emit_tsi(as, mik, dest, left, k);
1393 return; 1869 return;
@@ -1397,22 +1873,34 @@ static void asm_bitop(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik)
1397 emit_dst(as, mi, dest, left, right); 1873 emit_dst(as, mi, dest, left, right);
1398} 1874}
1399 1875
1876#define asm_band(as, ir) asm_bitop(as, ir, MIPSI_AND, MIPSI_ANDI)
1877#define asm_bor(as, ir) asm_bitop(as, ir, MIPSI_OR, MIPSI_ORI)
1878#define asm_bxor(as, ir) asm_bitop(as, ir, MIPSI_XOR, MIPSI_XORI)
1879
1400static void asm_bitshift(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik) 1880static void asm_bitshift(ASMState *as, IRIns *ir, MIPSIns mi, MIPSIns mik)
1401{ 1881{
1402 Reg dest = ra_dest(as, ir, RSET_GPR); 1882 Reg dest = ra_dest(as, ir, RSET_GPR);
1403 if (irref_isk(ir->op2)) { /* Constant shifts. */ 1883 if (irref_isk(ir->op2)) { /* Constant shifts. */
1404 uint32_t shift = (uint32_t)(IR(ir->op2)->i & 31); 1884 uint32_t shift = (uint32_t)IR(ir->op2)->i;
1405 emit_dta(as, mik, dest, ra_hintalloc(as, ir->op1, dest, RSET_GPR), shift); 1885 if (LJ_64 && irt_is64(ir->t)) mik |= (shift & 32) ? MIPSI_D32 : MIPSI_D;
1886 emit_dta(as, mik, dest, ra_hintalloc(as, ir->op1, dest, RSET_GPR),
1887 (shift & 31));
1406 } else { 1888 } else {
1407 Reg right, left = ra_alloc2(as, ir, RSET_GPR); 1889 Reg right, left = ra_alloc2(as, ir, RSET_GPR);
1408 right = (left >> 8); left &= 255; 1890 right = (left >> 8); left &= 255;
1891 if (LJ_64 && irt_is64(ir->t)) mi |= MIPSI_DV;
1409 emit_dst(as, mi, dest, right, left); /* Shift amount is in rs. */ 1892 emit_dst(as, mi, dest, right, left); /* Shift amount is in rs. */
1410 } 1893 }
1411} 1894}
1412 1895
1413static void asm_bitror(ASMState *as, IRIns *ir) 1896#define asm_bshl(as, ir) asm_bitshift(as, ir, MIPSI_SLLV, MIPSI_SLL)
1897#define asm_bshr(as, ir) asm_bitshift(as, ir, MIPSI_SRLV, MIPSI_SRL)
1898#define asm_bsar(as, ir) asm_bitshift(as, ir, MIPSI_SRAV, MIPSI_SRA)
1899#define asm_brol(as, ir) lua_assert(0)
1900
1901static void asm_bror(ASMState *as, IRIns *ir)
1414{ 1902{
1415 if ((as->flags & JIT_F_MIPS32R2)) { 1903 if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) {
1416 asm_bitshift(as, ir, MIPSI_ROTRV, MIPSI_ROTR); 1904 asm_bitshift(as, ir, MIPSI_ROTRV, MIPSI_ROTR);
1417 } else { 1905 } else {
1418 Reg dest = ra_dest(as, ir, RSET_GPR); 1906 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -1431,9 +1919,25 @@ static void asm_bitror(ASMState *as, IRIns *ir)
1431 } 1919 }
1432} 1920}
1433 1921
1922#if LJ_32 && LJ_SOFTFP
1923static void asm_sfpmin_max(ASMState *as, IRIns *ir)
1924{
1925 CCallInfo ci = lj_ir_callinfo[(IROp)ir->o == IR_MIN ? IRCALL_lj_vm_sfmin : IRCALL_lj_vm_sfmax];
1926 IRRef args[4];
1927 args[0^LJ_BE] = ir->op1;
1928 args[1^LJ_BE] = (ir+1)->op1;
1929 args[2^LJ_BE] = ir->op2;
1930 args[3^LJ_BE] = (ir+1)->op2;
1931 asm_setupresult(as, ir, &ci);
1932 emit_call(as, (void *)ci.func, 0);
1933 ci.func = NULL;
1934 asm_gencall(as, &ci, args);
1935}
1936#endif
1937
1434static void asm_min_max(ASMState *as, IRIns *ir, int ismax) 1938static void asm_min_max(ASMState *as, IRIns *ir, int ismax)
1435{ 1939{
1436 if (irt_isnum(ir->t)) { 1940 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1437 Reg dest = ra_dest(as, ir, RSET_FPR); 1941 Reg dest = ra_dest(as, ir, RSET_FPR);
1438 Reg right, left = ra_alloc2(as, ir, RSET_FPR); 1942 Reg right, left = ra_alloc2(as, ir, RSET_FPR);
1439 right = (left >> 8); left &= 255; 1943 right = (left >> 8); left &= 255;
@@ -1459,13 +1963,77 @@ static void asm_min_max(ASMState *as, IRIns *ir, int ismax)
1459 } 1963 }
1460} 1964}
1461 1965
1966#define asm_min(as, ir) asm_min_max(as, ir, 0)
1967#define asm_max(as, ir) asm_min_max(as, ir, 1)
1968
1462/* -- Comparisons --------------------------------------------------------- */ 1969/* -- Comparisons --------------------------------------------------------- */
1463 1970
1971#if LJ_32 && LJ_SOFTFP
1972/* SFP comparisons. */
1973static void asm_sfpcomp(ASMState *as, IRIns *ir)
1974{
1975 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_softfp_cmp];
1976 RegSet drop = RSET_SCRATCH;
1977 Reg r;
1978 IRRef args[4];
1979 args[LJ_LE ? 0 : 1] = ir->op1; args[LJ_LE ? 1 : 0] = (ir+1)->op1;
1980 args[LJ_LE ? 2 : 3] = ir->op2; args[LJ_LE ? 3 : 2] = (ir+1)->op2;
1981
1982 for (r = REGARG_FIRSTGPR; r <= REGARG_FIRSTGPR+3; r++) {
1983 if (!rset_test(as->freeset, r) &&
1984 regcost_ref(as->cost[r]) == args[r-REGARG_FIRSTGPR])
1985 rset_clear(drop, r);
1986 }
1987 ra_evictset(as, drop);
1988
1989 asm_setupresult(as, ir, ci);
1990
1991 switch ((IROp)ir->o) {
1992 case IR_LT:
1993 asm_guard(as, MIPSI_BGEZ, RID_RET, 0);
1994 break;
1995 case IR_ULT:
1996 asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP);
1997 emit_loadi(as, RID_TMP, 1);
1998 asm_guard(as, MIPSI_BEQ, RID_RET, RID_ZERO);
1999 break;
2000 case IR_GE:
2001 asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP);
2002 emit_loadi(as, RID_TMP, 2);
2003 asm_guard(as, MIPSI_BLTZ, RID_RET, 0);
2004 break;
2005 case IR_LE:
2006 asm_guard(as, MIPSI_BGTZ, RID_RET, 0);
2007 break;
2008 case IR_GT:
2009 asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP);
2010 emit_loadi(as, RID_TMP, 2);
2011 asm_guard(as, MIPSI_BLEZ, RID_RET, 0);
2012 break;
2013 case IR_UGE:
2014 asm_guard(as, MIPSI_BLTZ, RID_RET, 0);
2015 break;
2016 case IR_ULE:
2017 asm_guard(as, MIPSI_BEQ, RID_RET, RID_TMP);
2018 emit_loadi(as, RID_TMP, 1);
2019 break;
2020 case IR_UGT: case IR_ABC:
2021 asm_guard(as, MIPSI_BLEZ, RID_RET, 0);
2022 break;
2023 case IR_EQ: case IR_NE:
2024 asm_guard(as, (ir->o & 1) ? MIPSI_BEQ : MIPSI_BNE, RID_RET, RID_ZERO);
2025 default:
2026 break;
2027 }
2028 asm_gencall(as, ci, args);
2029}
2030#endif
2031
1464static void asm_comp(ASMState *as, IRIns *ir) 2032static void asm_comp(ASMState *as, IRIns *ir)
1465{ 2033{
1466 /* ORDER IR: LT GE LE GT ULT UGE ULE UGT. */ 2034 /* ORDER IR: LT GE LE GT ULT UGE ULE UGT. */
1467 IROp op = ir->o; 2035 IROp op = ir->o;
1468 if (irt_isnum(ir->t)) { 2036 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1469 Reg right, left = ra_alloc2(as, ir, RSET_FPR); 2037 Reg right, left = ra_alloc2(as, ir, RSET_FPR);
1470 right = (left >> 8); left &= 255; 2038 right = (left >> 8); left &= 255;
1471 asm_guard(as, (op&1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0); 2039 asm_guard(as, (op&1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0);
@@ -1473,13 +2041,13 @@ static void asm_comp(ASMState *as, IRIns *ir)
1473 } else { 2041 } else {
1474 Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR); 2042 Reg right, left = ra_alloc1(as, ir->op1, RSET_GPR);
1475 if (op == IR_ABC) op = IR_UGT; 2043 if (op == IR_ABC) op = IR_UGT;
1476 if ((op&4) == 0 && irref_isk(ir->op2) && IR(ir->op2)->i == 0) { 2044 if ((op&4) == 0 && irref_isk(ir->op2) && get_kval(IR(ir->op2)) == 0) {
1477 MIPSIns mi = (op&2) ? ((op&1) ? MIPSI_BLEZ : MIPSI_BGTZ) : 2045 MIPSIns mi = (op&2) ? ((op&1) ? MIPSI_BLEZ : MIPSI_BGTZ) :
1478 ((op&1) ? MIPSI_BLTZ : MIPSI_BGEZ); 2046 ((op&1) ? MIPSI_BLTZ : MIPSI_BGEZ);
1479 asm_guard(as, mi, left, 0); 2047 asm_guard(as, mi, left, 0);
1480 } else { 2048 } else {
1481 if (irref_isk(ir->op2)) { 2049 if (irref_isk(ir->op2)) {
1482 int32_t k = IR(ir->op2)->i; 2050 intptr_t k = get_kval(IR(ir->op2));
1483 if ((op&2)) k++; 2051 if ((op&2)) k++;
1484 if (checki16(k)) { 2052 if (checki16(k)) {
1485 asm_guard(as, (op&1) ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO); 2053 asm_guard(as, (op&1) ? MIPSI_BNE : MIPSI_BEQ, RID_TMP, RID_ZERO);
@@ -1496,11 +2064,12 @@ static void asm_comp(ASMState *as, IRIns *ir)
1496 } 2064 }
1497} 2065}
1498 2066
1499static void asm_compeq(ASMState *as, IRIns *ir) 2067static void asm_equal(ASMState *as, IRIns *ir)
1500{ 2068{
1501 Reg right, left = ra_alloc2(as, ir, irt_isnum(ir->t) ? RSET_FPR : RSET_GPR); 2069 Reg right, left = ra_alloc2(as, ir, (!LJ_SOFTFP && irt_isnum(ir->t)) ?
2070 RSET_FPR : RSET_GPR);
1502 right = (left >> 8); left &= 255; 2071 right = (left >> 8); left &= 255;
1503 if (irt_isnum(ir->t)) { 2072 if (!LJ_SOFTFP && irt_isnum(ir->t)) {
1504 asm_guard(as, (ir->o & 1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0); 2073 asm_guard(as, (ir->o & 1) ? MIPSI_BC1T : MIPSI_BC1F, 0, 0);
1505 emit_fgh(as, MIPSI_C_EQ_D, 0, left, right); 2074 emit_fgh(as, MIPSI_C_EQ_D, 0, left, right);
1506 } else { 2075 } else {
@@ -1508,7 +2077,7 @@ static void asm_compeq(ASMState *as, IRIns *ir)
1508 } 2077 }
1509} 2078}
1510 2079
1511#if LJ_HASFFI 2080#if LJ_32 && LJ_HASFFI
1512/* 64 bit integer comparisons. */ 2081/* 64 bit integer comparisons. */
1513static void asm_comp64(ASMState *as, IRIns *ir) 2082static void asm_comp64(ASMState *as, IRIns *ir)
1514{ 2083{
@@ -1550,41 +2119,79 @@ static void asm_comp64eq(ASMState *as, IRIns *ir)
1550/* Hiword op of a split 64 bit op. Previous op must be the loword op. */ 2119/* Hiword op of a split 64 bit op. Previous op must be the loword op. */
1551static void asm_hiop(ASMState *as, IRIns *ir) 2120static void asm_hiop(ASMState *as, IRIns *ir)
1552{ 2121{
1553#if LJ_HASFFI 2122#if LJ_32 && (LJ_HASFFI || LJ_SOFTFP)
1554 /* HIOP is marked as a store because it needs its own DCE logic. */ 2123 /* HIOP is marked as a store because it needs its own DCE logic. */
1555 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ 2124 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */
1556 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; 2125 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1;
1557 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ 2126 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */
1558 as->curins--; /* Always skip the CONV. */ 2127 as->curins--; /* Always skip the CONV. */
2128#if LJ_HASFFI && !LJ_SOFTFP
1559 if (usehi || uselo) 2129 if (usehi || uselo)
1560 asm_conv64(as, ir); 2130 asm_conv64(as, ir);
1561 return; 2131 return;
2132#endif
1562 } else if ((ir-1)->o < IR_EQ) { /* 64 bit integer comparisons. ORDER IR. */ 2133 } else if ((ir-1)->o < IR_EQ) { /* 64 bit integer comparisons. ORDER IR. */
1563 as->curins--; /* Always skip the loword comparison. */ 2134 as->curins--; /* Always skip the loword comparison. */
2135#if LJ_SOFTFP
2136 if (!irt_isint(ir->t)) {
2137 asm_sfpcomp(as, ir-1);
2138 return;
2139 }
2140#endif
2141#if LJ_HASFFI
1564 asm_comp64(as, ir); 2142 asm_comp64(as, ir);
2143#endif
1565 return; 2144 return;
1566 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ 2145 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */
1567 as->curins--; /* Always skip the loword comparison. */ 2146 as->curins--; /* Always skip the loword comparison. */
2147#if LJ_SOFTFP
2148 if (!irt_isint(ir->t)) {
2149 asm_sfpcomp(as, ir-1);
2150 return;
2151 }
2152#endif
2153#if LJ_HASFFI
1568 asm_comp64eq(as, ir); 2154 asm_comp64eq(as, ir);
2155#endif
2156 return;
2157#if LJ_SOFTFP
2158 } else if ((ir-1)->o == IR_MIN || (ir-1)->o == IR_MAX) {
2159 as->curins--; /* Always skip the loword min/max. */
2160 if (uselo || usehi)
2161 asm_sfpmin_max(as, ir-1);
1569 return; 2162 return;
2163#endif
1570 } else if ((ir-1)->o == IR_XSTORE) { 2164 } else if ((ir-1)->o == IR_XSTORE) {
1571 as->curins--; /* Handle both stores here. */ 2165 as->curins--; /* Handle both stores here. */
1572 if ((ir-1)->r != RID_SINK) { 2166 if ((ir-1)->r != RID_SINK) {
1573 asm_xstore(as, ir, LJ_LE ? 4 : 0); 2167 asm_xstore_(as, ir, LJ_LE ? 4 : 0);
1574 asm_xstore(as, ir-1, LJ_LE ? 0 : 4); 2168 asm_xstore_(as, ir-1, LJ_LE ? 0 : 4);
1575 } 2169 }
1576 return; 2170 return;
1577 } 2171 }
1578 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */ 2172 if (!usehi) return; /* Skip unused hiword op for all remaining ops. */
1579 switch ((ir-1)->o) { 2173 switch ((ir-1)->o) {
2174#if LJ_HASFFI
1580 case IR_ADD: as->curins--; asm_add64(as, ir); break; 2175 case IR_ADD: as->curins--; asm_add64(as, ir); break;
1581 case IR_SUB: as->curins--; asm_sub64(as, ir); break; 2176 case IR_SUB: as->curins--; asm_sub64(as, ir); break;
1582 case IR_NEG: as->curins--; asm_neg64(as, ir); break; 2177 case IR_NEG: as->curins--; asm_neg64(as, ir); break;
2178#endif
2179#if LJ_SOFTFP
2180 case IR_SLOAD: case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2181 case IR_STRTO:
2182 if (!uselo)
2183 ra_allocref(as, ir->op1, RSET_GPR); /* Mark lo op as used. */
2184 break;
2185#endif
1583 case IR_CALLN: 2186 case IR_CALLN:
2187 case IR_CALLS:
1584 case IR_CALLXS: 2188 case IR_CALLXS:
1585 if (!uselo) 2189 if (!uselo)
1586 ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */ 2190 ra_allocref(as, ir->op1, RID2RSET(RID_RETLO)); /* Mark lo op as used. */
1587 break; 2191 break;
2192#if LJ_SOFTFP
2193 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: case IR_TOSTR:
2194#endif
1588 case IR_CNEWI: 2195 case IR_CNEWI:
1589 /* Nothing to do here. Handled by lo op itself. */ 2196 /* Nothing to do here. Handled by lo op itself. */
1590 break; 2197 break;
@@ -1595,6 +2202,17 @@ static void asm_hiop(ASMState *as, IRIns *ir)
1595#endif 2202#endif
1596} 2203}
1597 2204
2205/* -- Profiling ----------------------------------------------------------- */
2206
2207static void asm_prof(ASMState *as, IRIns *ir)
2208{
2209 UNUSED(ir);
2210 asm_guard(as, MIPSI_BNE, RID_TMP, RID_ZERO);
2211 emit_tsi(as, MIPSI_ANDI, RID_TMP, RID_TMP, HOOK_PROFILE);
2212 emit_lsglptr(as, MIPSI_LBU, RID_TMP,
2213 (int32_t)offsetof(global_State, hookmask));
2214}
2215
1598/* -- Stack handling ------------------------------------------------------ */ 2216/* -- Stack handling ------------------------------------------------------ */
1599 2217
1600/* Check Lua stack size for overflow. Use exit handler as fallback. */ 2218/* Check Lua stack size for overflow. Use exit handler as fallback. */
@@ -1605,46 +2223,64 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
1605 Reg tmp, pbase = irp ? (ra_hasreg(irp->r) ? irp->r : RID_TMP) : RID_BASE; 2223 Reg tmp, pbase = irp ? (ra_hasreg(irp->r) ? irp->r : RID_TMP) : RID_BASE;
1606 ExitNo oldsnap = as->snapno; 2224 ExitNo oldsnap = as->snapno;
1607 rset_clear(allow, pbase); 2225 rset_clear(allow, pbase);
2226#if LJ_32
1608 tmp = allow ? rset_pickbot(allow) : 2227 tmp = allow ? rset_pickbot(allow) :
1609 (pbase == RID_RETHI ? RID_RETLO : RID_RETHI); 2228 (pbase == RID_RETHI ? RID_RETLO : RID_RETHI);
2229#else
2230 tmp = allow ? rset_pickbot(allow) : RID_RET;
2231#endif
1610 as->snapno = exitno; 2232 as->snapno = exitno;
1611 asm_guard(as, MIPSI_BNE, RID_TMP, RID_ZERO); 2233 asm_guard(as, MIPSI_BNE, RID_TMP, RID_ZERO);
1612 as->snapno = oldsnap; 2234 as->snapno = oldsnap;
1613 if (allow == RSET_EMPTY) /* Restore temp. register. */ 2235 if (allow == RSET_EMPTY) /* Restore temp. register. */
1614 emit_tsi(as, MIPSI_LW, tmp, RID_SP, 0); 2236 emit_tsi(as, MIPSI_AL, tmp, RID_SP, 0);
1615 else 2237 else
1616 ra_modified(as, tmp); 2238 ra_modified(as, tmp);
1617 emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)(8*topslot)); 2239 emit_tsi(as, MIPSI_SLTIU, RID_TMP, RID_TMP, (int32_t)(8*topslot));
1618 emit_dst(as, MIPSI_SUBU, RID_TMP, tmp, pbase); 2240 emit_dst(as, MIPSI_ASUBU, RID_TMP, tmp, pbase);
1619 emit_tsi(as, MIPSI_LW, tmp, tmp, offsetof(lua_State, maxstack)); 2241 emit_tsi(as, MIPSI_AL, tmp, tmp, offsetof(lua_State, maxstack));
1620 if (pbase == RID_TMP) 2242 if (pbase == RID_TMP)
1621 emit_getgl(as, RID_TMP, jit_base); 2243 emit_getgl(as, RID_TMP, jit_base);
1622 emit_getgl(as, tmp, jit_L); 2244 emit_getgl(as, tmp, cur_L);
1623 if (allow == RSET_EMPTY) /* Spill temp. register. */ 2245 if (allow == RSET_EMPTY) /* Spill temp. register. */
1624 emit_tsi(as, MIPSI_SW, tmp, RID_SP, 0); 2246 emit_tsi(as, MIPSI_AS, tmp, RID_SP, 0);
1625} 2247}
1626 2248
1627/* Restore Lua stack from on-trace state. */ 2249/* Restore Lua stack from on-trace state. */
1628static void asm_stack_restore(ASMState *as, SnapShot *snap) 2250static void asm_stack_restore(ASMState *as, SnapShot *snap)
1629{ 2251{
1630 SnapEntry *map = &as->T->snapmap[snap->mapofs]; 2252 SnapEntry *map = &as->T->snapmap[snap->mapofs];
1631 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1]; 2253#if LJ_32 || defined(LUA_USE_ASSERT)
2254 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2];
2255#endif
1632 MSize n, nent = snap->nent; 2256 MSize n, nent = snap->nent;
1633 /* Store the value of all modified slots to the Lua stack. */ 2257 /* Store the value of all modified slots to the Lua stack. */
1634 for (n = 0; n < nent; n++) { 2258 for (n = 0; n < nent; n++) {
1635 SnapEntry sn = map[n]; 2259 SnapEntry sn = map[n];
1636 BCReg s = snap_slot(sn); 2260 BCReg s = snap_slot(sn);
1637 int32_t ofs = 8*((int32_t)s-1); 2261 int32_t ofs = 8*((int32_t)s-1-LJ_FR2);
1638 IRRef ref = snap_ref(sn); 2262 IRRef ref = snap_ref(sn);
1639 IRIns *ir = IR(ref); 2263 IRIns *ir = IR(ref);
1640 if ((sn & SNAP_NORESTORE)) 2264 if ((sn & SNAP_NORESTORE))
1641 continue; 2265 continue;
1642 if (irt_isnum(ir->t)) { 2266 if (irt_isnum(ir->t)) {
2267#if LJ_SOFTFP
2268 Reg tmp;
2269 RegSet allow = rset_exclude(RSET_GPR, RID_BASE);
2270 lua_assert(irref_isk(ref)); /* LJ_SOFTFP: must be a number constant. */
2271 tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.lo, allow);
2272 emit_tsi(as, MIPSI_SW, tmp, RID_BASE, ofs+(LJ_BE?4:0));
2273 if (rset_test(as->freeset, tmp+1)) allow = RID2RSET(tmp+1);
2274 tmp = ra_allock(as, (int32_t)ir_knum(ir)->u32.hi, allow);
2275 emit_tsi(as, MIPSI_SW, tmp, RID_BASE, ofs+(LJ_BE?0:4));
2276#else
1643 Reg src = ra_alloc1(as, ref, RSET_FPR); 2277 Reg src = ra_alloc1(as, ref, RSET_FPR);
1644 emit_hsi(as, MIPSI_SDC1, src, RID_BASE, ofs); 2278 emit_hsi(as, MIPSI_SDC1, src, RID_BASE, ofs);
2279#endif
1645 } else { 2280 } else {
1646 Reg type; 2281#if LJ_32
1647 RegSet allow = rset_exclude(RSET_GPR, RID_BASE); 2282 RegSet allow = rset_exclude(RSET_GPR, RID_BASE);
2283 Reg type;
1648 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t)); 2284 lua_assert(irt_ispri(ir->t) || irt_isaddr(ir->t) || irt_isinteger(ir->t));
1649 if (!irt_ispri(ir->t)) { 2285 if (!irt_ispri(ir->t)) {
1650 Reg src = ra_alloc1(as, ref, allow); 2286 Reg src = ra_alloc1(as, ref, allow);
@@ -1654,10 +2290,17 @@ static void asm_stack_restore(ASMState *as, SnapShot *snap)
1654 if ((sn & (SNAP_CONT|SNAP_FRAME))) { 2290 if ((sn & (SNAP_CONT|SNAP_FRAME))) {
1655 if (s == 0) continue; /* Do not overwrite link to previous frame. */ 2291 if (s == 0) continue; /* Do not overwrite link to previous frame. */
1656 type = ra_allock(as, (int32_t)(*flinks--), allow); 2292 type = ra_allock(as, (int32_t)(*flinks--), allow);
2293#if LJ_SOFTFP
2294 } else if ((sn & SNAP_SOFTFPNUM)) {
2295 type = ra_alloc1(as, ref+1, rset_exclude(RSET_GPR, RID_BASE));
2296#endif
1657 } else { 2297 } else {
1658 type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow); 2298 type = ra_allock(as, (int32_t)irt_toitype(ir->t), allow);
1659 } 2299 }
1660 emit_tsi(as, MIPSI_SW, type, RID_BASE, ofs+(LJ_BE?0:4)); 2300 emit_tsi(as, MIPSI_SW, type, RID_BASE, ofs+(LJ_BE?0:4));
2301#else
2302 asm_tvstore64(as, RID_BASE, ofs, ref);
2303#endif
1661 } 2304 }
1662 checkmclim(as); 2305 checkmclim(as);
1663 } 2306 }
@@ -1681,7 +2324,7 @@ static void asm_gc_check(ASMState *as)
1681 args[0] = ASMREF_TMP1; /* global_State *g */ 2324 args[0] = ASMREF_TMP1; /* global_State *g */
1682 args[1] = ASMREF_TMP2; /* MSize steps */ 2325 args[1] = ASMREF_TMP2; /* MSize steps */
1683 asm_gencall(as, ci, args); 2326 asm_gencall(as, ci, args);
1684 emit_tsi(as, MIPSI_ADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768); 2327 emit_tsi(as, MIPSI_AADDIU, ra_releasetmp(as, ASMREF_TMP1), RID_JGL, -32768);
1685 tmp = ra_releasetmp(as, ASMREF_TMP2); 2328 tmp = ra_releasetmp(as, ASMREF_TMP2);
1686 emit_loadi(as, tmp, as->gcsteps); 2329 emit_loadi(as, tmp, as->gcsteps);
1687 /* Jump around GC step if GC total < GC threshold. */ 2330 /* Jump around GC step if GC total < GC threshold. */
@@ -1756,7 +2399,7 @@ static void asm_tail_fixup(ASMState *as, TraceNo lnk)
1756 MCode *target = lnk ? traceref(as->J,lnk)->mcode : (MCode *)lj_vm_exit_interp; 2399 MCode *target = lnk ? traceref(as->J,lnk)->mcode : (MCode *)lj_vm_exit_interp;
1757 int32_t spadj = as->T->spadjust; 2400 int32_t spadj = as->T->spadjust;
1758 MCode *p = as->mctop-1; 2401 MCode *p = as->mctop-1;
1759 *p = spadj ? (MIPSI_ADDIU|MIPSF_T(RID_SP)|MIPSF_S(RID_SP)|spadj) : MIPSI_NOP; 2402 *p = spadj ? (MIPSI_AADDIU|MIPSF_T(RID_SP)|MIPSF_S(RID_SP)|spadj) : MIPSI_NOP;
1760 p[-1] = MIPSI_J|(((uintptr_t)target>>2)&0x03ffffffu); 2403 p[-1] = MIPSI_J|(((uintptr_t)target>>2)&0x03ffffffu);
1761} 2404}
1762 2405
@@ -1767,139 +2410,26 @@ static void asm_tail_prep(ASMState *as)
1767 as->invmcp = as->loopref ? as->mcp : NULL; 2410 as->invmcp = as->loopref ? as->mcp : NULL;
1768} 2411}
1769 2412
1770/* -- Instruction dispatch ------------------------------------------------ */
1771
1772/* Assemble a single instruction. */
1773static void asm_ir(ASMState *as, IRIns *ir)
1774{
1775 switch ((IROp)ir->o) {
1776 /* Miscellaneous ops. */
1777 case IR_LOOP: asm_loop(as); break;
1778 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
1779 case IR_USE:
1780 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
1781 case IR_PHI: asm_phi(as, ir); break;
1782 case IR_HIOP: asm_hiop(as, ir); break;
1783 case IR_GCSTEP: asm_gcstep(as, ir); break;
1784
1785 /* Guarded assertions. */
1786 case IR_EQ: case IR_NE: asm_compeq(as, ir); break;
1787 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
1788 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
1789 case IR_ABC:
1790 asm_comp(as, ir);
1791 break;
1792
1793 case IR_RETF: asm_retf(as, ir); break;
1794
1795 /* Bit ops. */
1796 case IR_BNOT: asm_bitnot(as, ir); break;
1797 case IR_BSWAP: asm_bitswap(as, ir); break;
1798
1799 case IR_BAND: asm_bitop(as, ir, MIPSI_AND, MIPSI_ANDI); break;
1800 case IR_BOR: asm_bitop(as, ir, MIPSI_OR, MIPSI_ORI); break;
1801 case IR_BXOR: asm_bitop(as, ir, MIPSI_XOR, MIPSI_XORI); break;
1802
1803 case IR_BSHL: asm_bitshift(as, ir, MIPSI_SLLV, MIPSI_SLL); break;
1804 case IR_BSHR: asm_bitshift(as, ir, MIPSI_SRLV, MIPSI_SRL); break;
1805 case IR_BSAR: asm_bitshift(as, ir, MIPSI_SRAV, MIPSI_SRA); break;
1806 case IR_BROL: lua_assert(0); break;
1807 case IR_BROR: asm_bitror(as, ir); break;
1808
1809 /* Arithmetic ops. */
1810 case IR_ADD: asm_add(as, ir); break;
1811 case IR_SUB: asm_sub(as, ir); break;
1812 case IR_MUL: asm_mul(as, ir); break;
1813 case IR_DIV: asm_fparith(as, ir, MIPSI_DIV_D); break;
1814 case IR_MOD: asm_callid(as, ir, IRCALL_lj_vm_modi); break;
1815 case IR_POW: asm_callid(as, ir, IRCALL_lj_vm_powi); break;
1816 case IR_NEG: asm_neg(as, ir); break;
1817
1818 case IR_ABS: asm_fpunary(as, ir, MIPSI_ABS_D); break;
1819 case IR_ATAN2: asm_callid(as, ir, IRCALL_atan2); break;
1820 case IR_LDEXP: asm_callid(as, ir, IRCALL_ldexp); break;
1821 case IR_MIN: asm_min_max(as, ir, 0); break;
1822 case IR_MAX: asm_min_max(as, ir, 1); break;
1823 case IR_FPMATH:
1824 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
1825 break;
1826 if (ir->op2 <= IRFPM_TRUNC)
1827 asm_callround(as, ir, IRCALL_lj_vm_floor + ir->op2);
1828 else if (ir->op2 == IRFPM_SQRT)
1829 asm_fpunary(as, ir, MIPSI_SQRT_D);
1830 else
1831 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
1832 break;
1833
1834 /* Overflow-checking arithmetic ops. */
1835 case IR_ADDOV: asm_arithov(as, ir); break;
1836 case IR_SUBOV: asm_arithov(as, ir); break;
1837 case IR_MULOV: asm_mulov(as, ir); break;
1838
1839 /* Memory references. */
1840 case IR_AREF: asm_aref(as, ir); break;
1841 case IR_HREF: asm_href(as, ir); break;
1842 case IR_HREFK: asm_hrefk(as, ir); break;
1843 case IR_NEWREF: asm_newref(as, ir); break;
1844 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
1845 case IR_FREF: asm_fref(as, ir); break;
1846 case IR_STRREF: asm_strref(as, ir); break;
1847
1848 /* Loads and stores. */
1849 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
1850 asm_ahuvload(as, ir);
1851 break;
1852 case IR_FLOAD: asm_fload(as, ir); break;
1853 case IR_XLOAD: asm_xload(as, ir); break;
1854 case IR_SLOAD: asm_sload(as, ir); break;
1855
1856 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
1857 case IR_FSTORE: asm_fstore(as, ir); break;
1858 case IR_XSTORE: asm_xstore(as, ir, 0); break;
1859
1860 /* Allocations. */
1861 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
1862 case IR_TNEW: asm_tnew(as, ir); break;
1863 case IR_TDUP: asm_tdup(as, ir); break;
1864 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
1865
1866 /* Write barriers. */
1867 case IR_TBAR: asm_tbar(as, ir); break;
1868 case IR_OBAR: asm_obar(as, ir); break;
1869
1870 /* Type conversions. */
1871 case IR_CONV: asm_conv(as, ir); break;
1872 case IR_TOBIT: asm_tobit(as, ir); break;
1873 case IR_TOSTR: asm_tostr(as, ir); break;
1874 case IR_STRTO: asm_strto(as, ir); break;
1875
1876 /* Calls. */
1877 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
1878 case IR_CALLXS: asm_callx(as, ir); break;
1879 case IR_CARG: break;
1880
1881 default:
1882 setintV(&as->J->errinfo, ir->o);
1883 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
1884 break;
1885 }
1886}
1887
1888/* -- Trace setup --------------------------------------------------------- */ 2413/* -- Trace setup --------------------------------------------------------- */
1889 2414
1890/* Ensure there are enough stack slots for call arguments. */ 2415/* Ensure there are enough stack slots for call arguments. */
1891static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) 2416static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
1892{ 2417{
1893 IRRef args[CCI_NARGS_MAX*2]; 2418 IRRef args[CCI_NARGS_MAX*2];
1894 uint32_t i, nargs = (int)CCI_NARGS(ci); 2419 uint32_t i, nargs = CCI_XNARGS(ci);
2420#if LJ_32
1895 int nslots = 4, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; 2421 int nslots = 4, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR;
2422#else
2423 int nslots = 0, ngpr = REGARG_NUMGPR;
2424#endif
1896 asm_collectargs(as, ir, ci, args); 2425 asm_collectargs(as, ir, ci, args);
1897 for (i = 0; i < nargs; i++) { 2426 for (i = 0; i < nargs; i++) {
1898 if (args[i] && irt_isfp(IR(args[i])->t) && 2427#if LJ_32
2428 if (!LJ_SOFTFP && args[i] && irt_isfp(IR(args[i])->t) &&
1899 nfpr > 0 && !(ci->flags & CCI_VARARG)) { 2429 nfpr > 0 && !(ci->flags & CCI_VARARG)) {
1900 nfpr--; 2430 nfpr--;
1901 ngpr -= irt_isnum(IR(args[i])->t) ? 2 : 1; 2431 ngpr -= irt_isnum(IR(args[i])->t) ? 2 : 1;
1902 } else if (args[i] && irt_isnum(IR(args[i])->t)) { 2432 } else if (!LJ_SOFTFP && args[i] && irt_isnum(IR(args[i])->t)) {
1903 nfpr = 0; 2433 nfpr = 0;
1904 ngpr = ngpr & ~1; 2434 ngpr = ngpr & ~1;
1905 if (ngpr > 0) ngpr -= 2; else nslots = (nslots+3) & ~1; 2435 if (ngpr > 0) ngpr -= 2; else nslots = (nslots+3) & ~1;
@@ -1907,6 +2437,9 @@ static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
1907 nfpr = 0; 2437 nfpr = 0;
1908 if (ngpr > 0) ngpr--; else nslots++; 2438 if (ngpr > 0) ngpr--; else nslots++;
1909 } 2439 }
2440#else
2441 if (ngpr > 0) ngpr--; else nslots += 2;
2442#endif
1910 } 2443 }
1911 if (nslots > as->evenspill) /* Leave room for args in stack slots. */ 2444 if (nslots > as->evenspill) /* Leave room for args in stack slots. */
1912 as->evenspill = nslots; 2445 as->evenspill = nslots;
diff --git a/src/lj_asm_ppc.h b/src/lj_asm_ppc.h
index d8a14c83..6daa861b 100644
--- a/src/lj_asm_ppc.h
+++ b/src/lj_asm_ppc.h
@@ -251,7 +251,7 @@ static int asm_fusemadd(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pir)
251/* Generate a call to a C function. */ 251/* Generate a call to a C function. */
252static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) 252static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
253{ 253{
254 uint32_t n, nargs = CCI_NARGS(ci); 254 uint32_t n, nargs = CCI_XNARGS(ci);
255 int32_t ofs = 8; 255 int32_t ofs = 8;
256 Reg gpr = REGARG_FIRSTGPR, fpr = REGARG_FIRSTFPR; 256 Reg gpr = REGARG_FIRSTGPR, fpr = REGARG_FIRSTFPR;
257 if ((void *)ci->func) 257 if ((void *)ci->func)
@@ -323,23 +323,16 @@ static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
323 } else { 323 } else {
324 ra_destreg(as, ir, RID_FPRET); 324 ra_destreg(as, ir, RID_FPRET);
325 } 325 }
326#if LJ_32
326 } else if (hiop) { 327 } else if (hiop) {
327 ra_destpair(as, ir); 328 ra_destpair(as, ir);
329#endif
328 } else { 330 } else {
329 ra_destreg(as, ir, RID_RET); 331 ra_destreg(as, ir, RID_RET);
330 } 332 }
331 } 333 }
332} 334}
333 335
334static void asm_call(ASMState *as, IRIns *ir)
335{
336 IRRef args[CCI_NARGS_MAX];
337 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
338 asm_collectargs(as, ir, ci, args);
339 asm_setupresult(as, ir, ci);
340 asm_gencall(as, ci, args);
341}
342
343static void asm_callx(ASMState *as, IRIns *ir) 336static void asm_callx(ASMState *as, IRIns *ir)
344{ 337{
345 IRRef args[CCI_NARGS_MAX*2]; 338 IRRef args[CCI_NARGS_MAX*2];
@@ -352,7 +345,7 @@ static void asm_callx(ASMState *as, IRIns *ir)
352 func = ir->op2; irf = IR(func); 345 func = ir->op2; irf = IR(func);
353 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); } 346 if (irf->o == IR_CARG) { func = irf->op1; irf = IR(func); }
354 if (irref_isk(func)) { /* Call to constant address. */ 347 if (irref_isk(func)) { /* Call to constant address. */
355 ci.func = (ASMFunction)(void *)(irf->i); 348 ci.func = (ASMFunction)(void *)(intptr_t)(irf->i);
356 } else { /* Need a non-argument register for indirect calls. */ 349 } else { /* Need a non-argument register for indirect calls. */
357 RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1); 350 RegSet allow = RSET_GPR & ~RSET_RANGE(RID_R0, REGARG_LASTGPR+1);
358 Reg freg = ra_alloc1(as, func, allow); 351 Reg freg = ra_alloc1(as, func, allow);
@@ -363,16 +356,6 @@ static void asm_callx(ASMState *as, IRIns *ir)
363 asm_gencall(as, &ci, args); 356 asm_gencall(as, &ci, args);
364} 357}
365 358
366static void asm_callid(ASMState *as, IRIns *ir, IRCallID id)
367{
368 const CCallInfo *ci = &lj_ir_callinfo[id];
369 IRRef args[2];
370 args[0] = ir->op1;
371 args[1] = ir->op2;
372 asm_setupresult(as, ir, ci);
373 asm_gencall(as, ci, args);
374}
375
376/* -- Returns ------------------------------------------------------------- */ 359/* -- Returns ------------------------------------------------------------- */
377 360
378/* Return to lower frame. Guard that it goes to the right spot. */ 361/* Return to lower frame. Guard that it goes to the right spot. */
@@ -380,7 +363,7 @@ static void asm_retf(ASMState *as, IRIns *ir)
380{ 363{
381 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); 364 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
382 void *pc = ir_kptr(IR(ir->op2)); 365 void *pc = ir_kptr(IR(ir->op2));
383 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1)); 366 int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
384 as->topslot -= (BCReg)delta; 367 as->topslot -= (BCReg)delta;
385 if ((int32_t)as->topslot < 0) as->topslot = 0; 368 if ((int32_t)as->topslot < 0) as->topslot = 0;
386 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ 369 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
@@ -410,8 +393,7 @@ static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
410 emit_asi(as, PPCI_XORIS, RID_TMP, dest, 0x8000); 393 emit_asi(as, PPCI_XORIS, RID_TMP, dest, 0x8000);
411 emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); 394 emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO);
412 emit_lsptr(as, PPCI_LFS, (fbias & 31), 395 emit_lsptr(as, PPCI_LFS, (fbias & 31),
413 (void *)lj_ir_k64_find(as->J, U64x(59800004,59800000)), 396 (void *)&as->J->k32[LJ_K32_2P52_2P31], RSET_GPR);
414 RSET_GPR);
415 emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); 397 emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP);
416 emit_fb(as, PPCI_FCTIWZ, tmp, left); 398 emit_fb(as, PPCI_FCTIWZ, tmp, left);
417} 399}
@@ -450,13 +432,11 @@ static void asm_conv(ASMState *as, IRIns *ir)
450 Reg left = ra_alloc1(as, lref, allow); 432 Reg left = ra_alloc1(as, lref, allow);
451 Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, left)); 433 Reg hibias = ra_allock(as, 0x43300000, rset_clear(allow, left));
452 Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); 434 Reg fbias = ra_scratch(as, rset_exclude(RSET_FPR, dest));
453 const float *kbias;
454 if (irt_isfloat(ir->t)) emit_fb(as, PPCI_FRSP, dest, dest); 435 if (irt_isfloat(ir->t)) emit_fb(as, PPCI_FRSP, dest, dest);
455 emit_fab(as, PPCI_FSUB, dest, dest, fbias); 436 emit_fab(as, PPCI_FSUB, dest, dest, fbias);
456 emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); 437 emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP);
457 kbias = (const float *)lj_ir_k64_find(as->J, U64x(59800004,59800000)); 438 emit_lsptr(as, PPCI_LFS, (fbias & 31),
458 if (st == IRT_U32) kbias++; 439 &as->J->k32[st == IRT_U32 ? LJ_K32_2P52 : LJ_K32_2P52_2P31],
459 emit_lsptr(as, PPCI_LFS, (fbias & 31), (void *)kbias,
460 rset_clear(allow, hibias)); 440 rset_clear(allow, hibias));
461 emit_tai(as, PPCI_STW, st == IRT_U32 ? left : RID_TMP, 441 emit_tai(as, PPCI_STW, st == IRT_U32 ? left : RID_TMP,
462 RID_SP, SPOFS_TMPLO); 442 RID_SP, SPOFS_TMPLO);
@@ -489,8 +469,7 @@ static void asm_conv(ASMState *as, IRIns *ir)
489 emit_fb(as, PPCI_FCTIWZ, tmp, tmp); 469 emit_fb(as, PPCI_FCTIWZ, tmp, tmp);
490 emit_fab(as, PPCI_FSUB, tmp, left, tmp); 470 emit_fab(as, PPCI_FSUB, tmp, left, tmp);
491 emit_lsptr(as, PPCI_LFS, (tmp & 31), 471 emit_lsptr(as, PPCI_LFS, (tmp & 31),
492 (void *)lj_ir_k64_find(as->J, U64x(4f000000,00000000)), 472 (void *)&as->J->k32[LJ_K32_2P31], RSET_GPR);
493 RSET_GPR);
494 } else { 473 } else {
495 emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO); 474 emit_tai(as, PPCI_LWZ, dest, RID_SP, SPOFS_TMPLO);
496 emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP); 475 emit_fai(as, PPCI_STFD, tmp, RID_SP, SPOFS_TMP);
@@ -513,28 +492,6 @@ static void asm_conv(ASMState *as, IRIns *ir)
513 } 492 }
514} 493}
515 494
516#if LJ_HASFFI
517static void asm_conv64(ASMState *as, IRIns *ir)
518{
519 IRType st = (IRType)((ir-1)->op2 & IRCONV_SRCMASK);
520 IRType dt = (((ir-1)->op2 & IRCONV_DSTMASK) >> IRCONV_DSH);
521 IRCallID id;
522 const CCallInfo *ci;
523 IRRef args[2];
524 args[0] = ir->op1;
525 args[1] = (ir-1)->op1;
526 if (st == IRT_NUM || st == IRT_FLOAT) {
527 id = IRCALL_fp64_d2l + ((st == IRT_FLOAT) ? 2 : 0) + (dt - IRT_I64);
528 ir--;
529 } else {
530 id = IRCALL_fp64_l2d + ((dt == IRT_FLOAT) ? 2 : 0) + (st - IRT_I64);
531 }
532 ci = &lj_ir_callinfo[id];
533 asm_setupresult(as, ir, ci);
534 asm_gencall(as, ci, args);
535}
536#endif
537
538static void asm_strto(ASMState *as, IRIns *ir) 495static void asm_strto(ASMState *as, IRIns *ir)
539{ 496{
540 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num]; 497 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_strscan_num];
@@ -553,6 +510,8 @@ static void asm_strto(ASMState *as, IRIns *ir)
553 emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_SP, ofs); 510 emit_tai(as, PPCI_ADDI, ra_releasetmp(as, ASMREF_TMP1), RID_SP, ofs);
554} 511}
555 512
513/* -- Memory references --------------------------------------------------- */
514
556/* Get pointer to TValue. */ 515/* Get pointer to TValue. */
557static void asm_tvptr(ASMState *as, Reg dest, IRRef ref) 516static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
558{ 517{
@@ -566,7 +525,7 @@ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
566 /* Otherwise use g->tmptv to hold the TValue. */ 525 /* Otherwise use g->tmptv to hold the TValue. */
567 RegSet allow = rset_exclude(RSET_GPR, dest); 526 RegSet allow = rset_exclude(RSET_GPR, dest);
568 Reg type; 527 Reg type;
569 emit_tai(as, PPCI_ADDI, dest, RID_JGL, offsetof(global_State, tmptv)-32768); 528 emit_tai(as, PPCI_ADDI, dest, RID_JGL, (int32_t)offsetof(global_State, tmptv)-32768);
570 if (!irt_ispri(ir->t)) { 529 if (!irt_ispri(ir->t)) {
571 Reg src = ra_alloc1(as, ref, allow); 530 Reg src = ra_alloc1(as, ref, allow);
572 emit_setgl(as, src, tmptv.gcr); 531 emit_setgl(as, src, tmptv.gcr);
@@ -576,27 +535,6 @@ static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
576 } 535 }
577} 536}
578 537
579static void asm_tostr(ASMState *as, IRIns *ir)
580{
581 IRRef args[2];
582 args[0] = ASMREF_L;
583 as->gcsteps++;
584 if (irt_isnum(IR(ir->op1)->t) || (ir+1)->o == IR_HIOP) {
585 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum];
586 args[1] = ASMREF_TMP1; /* const lua_Number * */
587 asm_setupresult(as, ir, ci); /* GCstr * */
588 asm_gencall(as, ci, args);
589 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op1);
590 } else {
591 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint];
592 args[1] = ir->op1; /* int32_t k */
593 asm_setupresult(as, ir, ci); /* GCstr * */
594 asm_gencall(as, ci, args);
595 }
596}
597
598/* -- Memory references --------------------------------------------------- */
599
600static void asm_aref(ASMState *as, IRIns *ir) 538static void asm_aref(ASMState *as, IRIns *ir)
601{ 539{
602 Reg dest = ra_dest(as, ir, RSET_GPR); 540 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -773,20 +711,6 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
773 } 711 }
774} 712}
775 713
776static void asm_newref(ASMState *as, IRIns *ir)
777{
778 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
779 IRRef args[3];
780 if (ir->r == RID_SINK)
781 return;
782 args[0] = ASMREF_L; /* lua_State *L */
783 args[1] = ir->op1; /* GCtab *t */
784 args[2] = ASMREF_TMP1; /* cTValue *key */
785 asm_setupresult(as, ir, ci); /* TValue * */
786 asm_gencall(as, ci, args);
787 asm_tvptr(as, ra_releasetmp(as, ASMREF_TMP1), ir->op2);
788}
789
790static void asm_uref(ASMState *as, IRIns *ir) 714static void asm_uref(ASMState *as, IRIns *ir)
791{ 715{
792 Reg dest = ra_dest(as, ir, RSET_GPR); 716 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -880,17 +804,23 @@ static PPCIns asm_fxstoreins(IRIns *ir)
880static void asm_fload(ASMState *as, IRIns *ir) 804static void asm_fload(ASMState *as, IRIns *ir)
881{ 805{
882 Reg dest = ra_dest(as, ir, RSET_GPR); 806 Reg dest = ra_dest(as, ir, RSET_GPR);
883 Reg idx = ra_alloc1(as, ir->op1, RSET_GPR);
884 PPCIns pi = asm_fxloadins(ir); 807 PPCIns pi = asm_fxloadins(ir);
808 Reg idx;
885 int32_t ofs; 809 int32_t ofs;
886 if (ir->op2 == IRFL_TAB_ARRAY) { 810 if (ir->op1 == REF_NIL) {
887 ofs = asm_fuseabase(as, ir->op1); 811 idx = RID_JGL;
888 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */ 812 ofs = (ir->op2 << 2) - 32768;
889 emit_tai(as, PPCI_ADDI, dest, idx, ofs); 813 } else {
890 return; 814 idx = ra_alloc1(as, ir->op1, RSET_GPR);
815 if (ir->op2 == IRFL_TAB_ARRAY) {
816 ofs = asm_fuseabase(as, ir->op1);
817 if (ofs) { /* Turn the t->array load into an add for colocated arrays. */
818 emit_tai(as, PPCI_ADDI, dest, idx, ofs);
819 return;
820 }
891 } 821 }
822 ofs = field_ofs[ir->op2];
892 } 823 }
893 ofs = field_ofs[ir->op2];
894 lua_assert(!irt_isi8(ir->t)); 824 lua_assert(!irt_isi8(ir->t));
895 emit_tai(as, pi, dest, idx, ofs); 825 emit_tai(as, pi, dest, idx, ofs);
896} 826}
@@ -916,7 +846,7 @@ static void asm_xload(ASMState *as, IRIns *ir)
916 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0); 846 asm_fusexref(as, asm_fxloadins(ir), dest, ir->op1, RSET_GPR, 0);
917} 847}
918 848
919static void asm_xstore(ASMState *as, IRIns *ir, int32_t ofs) 849static void asm_xstore_(ASMState *as, IRIns *ir, int32_t ofs)
920{ 850{
921 IRIns *irb; 851 IRIns *irb;
922 if (ir->r == RID_SINK) 852 if (ir->r == RID_SINK)
@@ -933,6 +863,8 @@ static void asm_xstore(ASMState *as, IRIns *ir, int32_t ofs)
933 } 863 }
934} 864}
935 865
866#define asm_xstore(as, ir) asm_xstore_(as, ir, 0)
867
936static void asm_ahuvload(ASMState *as, IRIns *ir) 868static void asm_ahuvload(ASMState *as, IRIns *ir)
937{ 869{
938 IRType1 t = ir->t; 870 IRType1 t = ir->t;
@@ -1044,7 +976,7 @@ static void asm_sload(ASMState *as, IRIns *ir)
1044 emit_fab(as, PPCI_FSUB, dest, dest, fbias); 976 emit_fab(as, PPCI_FSUB, dest, dest, fbias);
1045 emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP); 977 emit_fai(as, PPCI_LFD, dest, RID_SP, SPOFS_TMP);
1046 emit_lsptr(as, PPCI_LFS, (fbias & 31), 978 emit_lsptr(as, PPCI_LFS, (fbias & 31),
1047 (void *)lj_ir_k64_find(as->J, U64x(59800004,59800000)), 979 (void *)&as->J->k32[LJ_K32_2P52_2P31],
1048 rset_clear(allow, hibias)); 980 rset_clear(allow, hibias));
1049 emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPLO); 981 emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPLO);
1050 emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI); 982 emit_tai(as, PPCI_STW, hibias, RID_SP, SPOFS_TMPHI);
@@ -1083,19 +1015,15 @@ dotypecheck:
1083static void asm_cnew(ASMState *as, IRIns *ir) 1015static void asm_cnew(ASMState *as, IRIns *ir)
1084{ 1016{
1085 CTState *cts = ctype_ctsG(J2G(as->J)); 1017 CTState *cts = ctype_ctsG(J2G(as->J));
1086 CTypeID ctypeid = (CTypeID)IR(ir->op1)->i; 1018 CTypeID id = (CTypeID)IR(ir->op1)->i;
1087 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ? 1019 CTSize sz;
1088 lj_ctype_size(cts, ctypeid) : (CTSize)IR(ir->op2)->i; 1020 CTInfo info = lj_ctype_info(cts, id, &sz);
1089 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; 1021 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1090 IRRef args[2]; 1022 IRRef args[4];
1091 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1092 RegSet drop = RSET_SCRATCH; 1023 RegSet drop = RSET_SCRATCH;
1093 lua_assert(sz != CTSIZE_INVALID); 1024 lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));
1094 1025
1095 args[0] = ASMREF_L; /* lua_State *L */
1096 args[1] = ASMREF_TMP1; /* MSize size */
1097 as->gcsteps++; 1026 as->gcsteps++;
1098
1099 if (ra_hasreg(ir->r)) 1027 if (ra_hasreg(ir->r))
1100 rset_clear(drop, ir->r); /* Dest reg handled below. */ 1028 rset_clear(drop, ir->r); /* Dest reg handled below. */
1101 ra_evictset(as, drop); 1029 ra_evictset(as, drop);
@@ -1104,6 +1032,7 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1104 1032
1105 /* Initialize immutable cdata object. */ 1033 /* Initialize immutable cdata object. */
1106 if (ir->o == IR_CNEWI) { 1034 if (ir->o == IR_CNEWI) {
1035 RegSet allow = (RSET_GPR & ~RSET_SCRATCH);
1107 int32_t ofs = sizeof(GCcdata); 1036 int32_t ofs = sizeof(GCcdata);
1108 lua_assert(sz == 4 || sz == 8); 1037 lua_assert(sz == 4 || sz == 8);
1109 if (sz == 8) { 1038 if (sz == 8) {
@@ -1117,12 +1046,24 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1117 if (ofs == sizeof(GCcdata)) break; 1046 if (ofs == sizeof(GCcdata)) break;
1118 ofs -= 4; ir++; 1047 ofs -= 4; ir++;
1119 } 1048 }
1049 } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */
1050 ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
1051 args[0] = ASMREF_L; /* lua_State *L */
1052 args[1] = ir->op1; /* CTypeID id */
1053 args[2] = ir->op2; /* CTSize sz */
1054 args[3] = ASMREF_TMP1; /* CTSize align */
1055 asm_gencall(as, ci, args);
1056 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
1057 return;
1120 } 1058 }
1059
1121 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */ 1060 /* Initialize gct and ctypeid. lj_mem_newgco() already sets marked. */
1122 emit_tai(as, PPCI_STB, RID_RET+1, RID_RET, offsetof(GCcdata, gct)); 1061 emit_tai(as, PPCI_STB, RID_RET+1, RID_RET, offsetof(GCcdata, gct));
1123 emit_tai(as, PPCI_STH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid)); 1062 emit_tai(as, PPCI_STH, RID_TMP, RID_RET, offsetof(GCcdata, ctypeid));
1124 emit_ti(as, PPCI_LI, RID_RET+1, ~LJ_TCDATA); 1063 emit_ti(as, PPCI_LI, RID_RET+1, ~LJ_TCDATA);
1125 emit_ti(as, PPCI_LI, RID_TMP, ctypeid); /* Lower 16 bit used. Sign-ext ok. */ 1064 emit_ti(as, PPCI_LI, RID_TMP, id); /* Lower 16 bit used. Sign-ext ok. */
1065 args[0] = ASMREF_L; /* lua_State *L */
1066 args[1] = ASMREF_TMP1; /* MSize size */
1126 asm_gencall(as, ci, args); 1067 asm_gencall(as, ci, args);
1127 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)), 1068 ra_allockreg(as, (int32_t)(sz+sizeof(GCcdata)),
1128 ra_releasetmp(as, ASMREF_TMP1)); 1069 ra_releasetmp(as, ASMREF_TMP1));
@@ -1196,23 +1137,14 @@ static void asm_fpunary(ASMState *as, IRIns *ir, PPCIns pi)
1196 emit_fb(as, pi, dest, left); 1137 emit_fb(as, pi, dest, left);
1197} 1138}
1198 1139
1199static int asm_fpjoin_pow(ASMState *as, IRIns *ir) 1140static void asm_fpmath(ASMState *as, IRIns *ir)
1200{ 1141{
1201 IRIns *irp = IR(ir->op1); 1142 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
1202 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) { 1143 return;
1203 IRIns *irpp = IR(irp->op1); 1144 if (ir->op2 == IRFPM_SQRT && (as->flags & JIT_F_SQRT))
1204 if (irpp == ir-2 && irpp->o == IR_FPMATH && 1145 asm_fpunary(as, ir, PPCI_FSQRT);
1205 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) { 1146 else
1206 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_pow]; 1147 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
1207 IRRef args[2];
1208 args[0] = irpp->op1;
1209 args[1] = irp->op2;
1210 asm_setupresult(as, ir, ci);
1211 asm_gencall(as, ci, args);
1212 return 1;
1213 }
1214 }
1215 return 0;
1216} 1148}
1217 1149
1218static void asm_add(ASMState *as, IRIns *ir) 1150static void asm_add(ASMState *as, IRIns *ir)
@@ -1312,6 +1244,10 @@ static void asm_mul(ASMState *as, IRIns *ir)
1312 } 1244 }
1313} 1245}
1314 1246
1247#define asm_div(as, ir) asm_fparith(as, ir, PPCI_FDIV)
1248#define asm_mod(as, ir) asm_callid(as, ir, IRCALL_lj_vm_modi)
1249#define asm_pow(as, ir) asm_callid(as, ir, IRCALL_lj_vm_powi)
1250
1315static void asm_neg(ASMState *as, IRIns *ir) 1251static void asm_neg(ASMState *as, IRIns *ir)
1316{ 1252{
1317 if (irt_isnum(ir->t)) { 1253 if (irt_isnum(ir->t)) {
@@ -1330,6 +1266,10 @@ static void asm_neg(ASMState *as, IRIns *ir)
1330 } 1266 }
1331} 1267}
1332 1268
1269#define asm_abs(as, ir) asm_fpunary(as, ir, PPCI_FABS)
1270#define asm_atan2(as, ir) asm_callid(as, ir, IRCALL_atan2)
1271#define asm_ldexp(as, ir) asm_callid(as, ir, IRCALL_ldexp)
1272
1333static void asm_arithov(ASMState *as, IRIns *ir, PPCIns pi) 1273static void asm_arithov(ASMState *as, IRIns *ir, PPCIns pi)
1334{ 1274{
1335 Reg dest, left, right; 1275 Reg dest, left, right;
@@ -1345,6 +1285,10 @@ static void asm_arithov(ASMState *as, IRIns *ir, PPCIns pi)
1345 emit_tab(as, pi|PPCF_DOT, dest, left, right); 1285 emit_tab(as, pi|PPCF_DOT, dest, left, right);
1346} 1286}
1347 1287
1288#define asm_addov(as, ir) asm_arithov(as, ir, PPCI_ADDO)
1289#define asm_subov(as, ir) asm_arithov(as, ir, PPCI_SUBFO)
1290#define asm_mulov(as, ir) asm_arithov(as, ir, PPCI_MULLWO)
1291
1348#if LJ_HASFFI 1292#if LJ_HASFFI
1349static void asm_add64(ASMState *as, IRIns *ir) 1293static void asm_add64(ASMState *as, IRIns *ir)
1350{ 1294{
@@ -1424,7 +1368,7 @@ static void asm_neg64(ASMState *as, IRIns *ir)
1424} 1368}
1425#endif 1369#endif
1426 1370
1427static void asm_bitnot(ASMState *as, IRIns *ir) 1371static void asm_bnot(ASMState *as, IRIns *ir)
1428{ 1372{
1429 Reg dest, left, right; 1373 Reg dest, left, right;
1430 PPCIns pi = PPCI_NOR; 1374 PPCIns pi = PPCI_NOR;
@@ -1451,7 +1395,7 @@ nofuse:
1451 emit_asb(as, pi, dest, left, right); 1395 emit_asb(as, pi, dest, left, right);
1452} 1396}
1453 1397
1454static void asm_bitswap(ASMState *as, IRIns *ir) 1398static void asm_bswap(ASMState *as, IRIns *ir)
1455{ 1399{
1456 Reg dest = ra_dest(as, ir, RSET_GPR); 1400 Reg dest = ra_dest(as, ir, RSET_GPR);
1457 IRIns *irx; 1401 IRIns *irx;
@@ -1472,32 +1416,6 @@ static void asm_bitswap(ASMState *as, IRIns *ir)
1472 } 1416 }
1473} 1417}
1474 1418
1475static void asm_bitop(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik)
1476{
1477 Reg dest = ra_dest(as, ir, RSET_GPR);
1478 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1479 if (irref_isk(ir->op2)) {
1480 int32_t k = IR(ir->op2)->i;
1481 Reg tmp = left;
1482 if ((checku16(k) || (k & 0xffff) == 0) || (tmp = dest, !as->sectref)) {
1483 if (!checku16(k)) {
1484 emit_asi(as, pik ^ (PPCI_ORI ^ PPCI_ORIS), dest, tmp, (k >> 16));
1485 if ((k & 0xffff) == 0) return;
1486 }
1487 emit_asi(as, pik, dest, left, k);
1488 return;
1489 }
1490 }
1491 /* May fail due to spills/restores above, but simplifies the logic. */
1492 if (as->flagmcp == as->mcp) {
1493 as->flagmcp = NULL;
1494 as->mcp++;
1495 pi |= PPCF_DOT;
1496 }
1497 right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1498 emit_asb(as, pi, dest, left, right);
1499}
1500
1501/* Fuse BAND with contiguous bitmask and a shift to rlwinm. */ 1419/* Fuse BAND with contiguous bitmask and a shift to rlwinm. */
1502static void asm_fuseandsh(ASMState *as, PPCIns pi, int32_t mask, IRRef ref) 1420static void asm_fuseandsh(ASMState *as, PPCIns pi, int32_t mask, IRRef ref)
1503{ 1421{
@@ -1528,7 +1446,7 @@ nofuse:
1528 *--as->mcp = pi | PPCF_T(left); 1446 *--as->mcp = pi | PPCF_T(left);
1529} 1447}
1530 1448
1531static void asm_bitand(ASMState *as, IRIns *ir) 1449static void asm_band(ASMState *as, IRIns *ir)
1532{ 1450{
1533 Reg dest, left, right; 1451 Reg dest, left, right;
1534 IRRef lref = ir->op1; 1452 IRRef lref = ir->op1;
@@ -1583,6 +1501,35 @@ static void asm_bitand(ASMState *as, IRIns *ir)
1583 emit_asb(as, PPCI_AND ^ dot, dest, left, right); 1501 emit_asb(as, PPCI_AND ^ dot, dest, left, right);
1584} 1502}
1585 1503
1504static void asm_bitop(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik)
1505{
1506 Reg dest = ra_dest(as, ir, RSET_GPR);
1507 Reg right, left = ra_hintalloc(as, ir->op1, dest, RSET_GPR);
1508 if (irref_isk(ir->op2)) {
1509 int32_t k = IR(ir->op2)->i;
1510 Reg tmp = left;
1511 if ((checku16(k) || (k & 0xffff) == 0) || (tmp = dest, !as->sectref)) {
1512 if (!checku16(k)) {
1513 emit_asi(as, pik ^ (PPCI_ORI ^ PPCI_ORIS), dest, tmp, (k >> 16));
1514 if ((k & 0xffff) == 0) return;
1515 }
1516 emit_asi(as, pik, dest, left, k);
1517 return;
1518 }
1519 }
1520 /* May fail due to spills/restores above, but simplifies the logic. */
1521 if (as->flagmcp == as->mcp) {
1522 as->flagmcp = NULL;
1523 as->mcp++;
1524 pi |= PPCF_DOT;
1525 }
1526 right = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, left));
1527 emit_asb(as, pi, dest, left, right);
1528}
1529
1530#define asm_bor(as, ir) asm_bitop(as, ir, PPCI_OR, PPCI_ORI)
1531#define asm_bxor(as, ir) asm_bitop(as, ir, PPCI_XOR, PPCI_XORI)
1532
1586static void asm_bitshift(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik) 1533static void asm_bitshift(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik)
1587{ 1534{
1588 Reg dest, left; 1535 Reg dest, left;
@@ -1608,6 +1555,14 @@ static void asm_bitshift(ASMState *as, IRIns *ir, PPCIns pi, PPCIns pik)
1608 } 1555 }
1609} 1556}
1610 1557
1558#define asm_bshl(as, ir) asm_bitshift(as, ir, PPCI_SLW, 0)
1559#define asm_bshr(as, ir) asm_bitshift(as, ir, PPCI_SRW, 1)
1560#define asm_bsar(as, ir) asm_bitshift(as, ir, PPCI_SRAW, PPCI_SRAWI)
1561#define asm_brol(as, ir) \
1562 asm_bitshift(as, ir, PPCI_RLWNM|PPCF_MB(0)|PPCF_ME(31), \
1563 PPCI_RLWINM|PPCF_MB(0)|PPCF_ME(31))
1564#define asm_bror(as, ir) lua_assert(0)
1565
1611static void asm_min_max(ASMState *as, IRIns *ir, int ismax) 1566static void asm_min_max(ASMState *as, IRIns *ir, int ismax)
1612{ 1567{
1613 if (irt_isnum(ir->t)) { 1568 if (irt_isnum(ir->t)) {
@@ -1638,6 +1593,9 @@ static void asm_min_max(ASMState *as, IRIns *ir, int ismax)
1638 } 1593 }
1639} 1594}
1640 1595
1596#define asm_min(as, ir) asm_min_max(as, ir, 0)
1597#define asm_max(as, ir) asm_min_max(as, ir, 1)
1598
1641/* -- Comparisons --------------------------------------------------------- */ 1599/* -- Comparisons --------------------------------------------------------- */
1642 1600
1643#define CC_UNSIGNED 0x08 /* Unsigned integer comparison. */ 1601#define CC_UNSIGNED 0x08 /* Unsigned integer comparison. */
@@ -1714,6 +1672,8 @@ static void asm_comp(ASMState *as, IRIns *ir)
1714 } 1672 }
1715} 1673}
1716 1674
1675#define asm_equal(as, ir) asm_comp(as, ir)
1676
1717#if LJ_HASFFI 1677#if LJ_HASFFI
1718/* 64 bit integer comparisons. */ 1678/* 64 bit integer comparisons. */
1719static void asm_comp64(ASMState *as, IRIns *ir) 1679static void asm_comp64(ASMState *as, IRIns *ir)
@@ -1759,8 +1719,8 @@ static void asm_hiop(ASMState *as, IRIns *ir)
1759 } else if ((ir-1)->o == IR_XSTORE) { 1719 } else if ((ir-1)->o == IR_XSTORE) {
1760 as->curins--; /* Handle both stores here. */ 1720 as->curins--; /* Handle both stores here. */
1761 if ((ir-1)->r != RID_SINK) { 1721 if ((ir-1)->r != RID_SINK) {
1762 asm_xstore(as, ir, 0); 1722 asm_xstore_(as, ir, 0);
1763 asm_xstore(as, ir-1, 4); 1723 asm_xstore_(as, ir-1, 4);
1764 } 1724 }
1765 return; 1725 return;
1766 } 1726 }
@@ -1784,6 +1744,17 @@ static void asm_hiop(ASMState *as, IRIns *ir)
1784#endif 1744#endif
1785} 1745}
1786 1746
1747/* -- Profiling ----------------------------------------------------------- */
1748
1749static void asm_prof(ASMState *as, IRIns *ir)
1750{
1751 UNUSED(ir);
1752 asm_guardcc(as, CC_NE);
1753 emit_asi(as, PPCI_ANDIDOT, RID_TMP, RID_TMP, HOOK_PROFILE);
1754 emit_lsglptr(as, PPCI_LBZ, RID_TMP,
1755 (int32_t)offsetof(global_State, hookmask));
1756}
1757
1787/* -- Stack handling ------------------------------------------------------ */ 1758/* -- Stack handling ------------------------------------------------------ */
1788 1759
1789/* Check Lua stack size for overflow. Use exit handler as fallback. */ 1760/* Check Lua stack size for overflow. Use exit handler as fallback. */
@@ -1805,7 +1776,7 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
1805 emit_tai(as, PPCI_LWZ, tmp, tmp, offsetof(lua_State, maxstack)); 1776 emit_tai(as, PPCI_LWZ, tmp, tmp, offsetof(lua_State, maxstack));
1806 if (pbase == RID_TMP) 1777 if (pbase == RID_TMP)
1807 emit_getgl(as, RID_TMP, jit_base); 1778 emit_getgl(as, RID_TMP, jit_base);
1808 emit_getgl(as, tmp, jit_L); 1779 emit_getgl(as, tmp, cur_L);
1809 if (allow == RSET_EMPTY) /* Spill temp. register. */ 1780 if (allow == RSET_EMPTY) /* Spill temp. register. */
1810 emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPW); 1781 emit_tai(as, PPCI_STW, tmp, RID_SP, SPOFS_TMPW);
1811} 1782}
@@ -1966,136 +1937,13 @@ static void asm_tail_prep(ASMState *as)
1966 } 1937 }
1967} 1938}
1968 1939
1969/* -- Instruction dispatch ------------------------------------------------ */
1970
1971/* Assemble a single instruction. */
1972static void asm_ir(ASMState *as, IRIns *ir)
1973{
1974 switch ((IROp)ir->o) {
1975 /* Miscellaneous ops. */
1976 case IR_LOOP: asm_loop(as); break;
1977 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
1978 case IR_USE:
1979 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
1980 case IR_PHI: asm_phi(as, ir); break;
1981 case IR_HIOP: asm_hiop(as, ir); break;
1982 case IR_GCSTEP: asm_gcstep(as, ir); break;
1983
1984 /* Guarded assertions. */
1985 case IR_EQ: case IR_NE:
1986 if ((ir-1)->o == IR_HREF && ir->op1 == as->curins-1) {
1987 as->curins--;
1988 asm_href(as, ir-1, (IROp)ir->o);
1989 break;
1990 }
1991 /* fallthrough */
1992 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
1993 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
1994 case IR_ABC:
1995 asm_comp(as, ir);
1996 break;
1997
1998 case IR_RETF: asm_retf(as, ir); break;
1999
2000 /* Bit ops. */
2001 case IR_BNOT: asm_bitnot(as, ir); break;
2002 case IR_BSWAP: asm_bitswap(as, ir); break;
2003
2004 case IR_BAND: asm_bitand(as, ir); break;
2005 case IR_BOR: asm_bitop(as, ir, PPCI_OR, PPCI_ORI); break;
2006 case IR_BXOR: asm_bitop(as, ir, PPCI_XOR, PPCI_XORI); break;
2007
2008 case IR_BSHL: asm_bitshift(as, ir, PPCI_SLW, 0); break;
2009 case IR_BSHR: asm_bitshift(as, ir, PPCI_SRW, 1); break;
2010 case IR_BSAR: asm_bitshift(as, ir, PPCI_SRAW, PPCI_SRAWI); break;
2011 case IR_BROL: asm_bitshift(as, ir, PPCI_RLWNM|PPCF_MB(0)|PPCF_ME(31),
2012 PPCI_RLWINM|PPCF_MB(0)|PPCF_ME(31)); break;
2013 case IR_BROR: lua_assert(0); break;
2014
2015 /* Arithmetic ops. */
2016 case IR_ADD: asm_add(as, ir); break;
2017 case IR_SUB: asm_sub(as, ir); break;
2018 case IR_MUL: asm_mul(as, ir); break;
2019 case IR_DIV: asm_fparith(as, ir, PPCI_FDIV); break;
2020 case IR_MOD: asm_callid(as, ir, IRCALL_lj_vm_modi); break;
2021 case IR_POW: asm_callid(as, ir, IRCALL_lj_vm_powi); break;
2022 case IR_NEG: asm_neg(as, ir); break;
2023
2024 case IR_ABS: asm_fpunary(as, ir, PPCI_FABS); break;
2025 case IR_ATAN2: asm_callid(as, ir, IRCALL_atan2); break;
2026 case IR_LDEXP: asm_callid(as, ir, IRCALL_ldexp); break;
2027 case IR_MIN: asm_min_max(as, ir, 0); break;
2028 case IR_MAX: asm_min_max(as, ir, 1); break;
2029 case IR_FPMATH:
2030 if (ir->op2 == IRFPM_EXP2 && asm_fpjoin_pow(as, ir))
2031 break;
2032 if (ir->op2 == IRFPM_SQRT && (as->flags & JIT_F_SQRT))
2033 asm_fpunary(as, ir, PPCI_FSQRT);
2034 else
2035 asm_callid(as, ir, IRCALL_lj_vm_floor + ir->op2);
2036 break;
2037
2038 /* Overflow-checking arithmetic ops. */
2039 case IR_ADDOV: asm_arithov(as, ir, PPCI_ADDO); break;
2040 case IR_SUBOV: asm_arithov(as, ir, PPCI_SUBFO); break;
2041 case IR_MULOV: asm_arithov(as, ir, PPCI_MULLWO); break;
2042
2043 /* Memory references. */
2044 case IR_AREF: asm_aref(as, ir); break;
2045 case IR_HREF: asm_href(as, ir, 0); break;
2046 case IR_HREFK: asm_hrefk(as, ir); break;
2047 case IR_NEWREF: asm_newref(as, ir); break;
2048 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
2049 case IR_FREF: asm_fref(as, ir); break;
2050 case IR_STRREF: asm_strref(as, ir); break;
2051
2052 /* Loads and stores. */
2053 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2054 asm_ahuvload(as, ir);
2055 break;
2056 case IR_FLOAD: asm_fload(as, ir); break;
2057 case IR_XLOAD: asm_xload(as, ir); break;
2058 case IR_SLOAD: asm_sload(as, ir); break;
2059
2060 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
2061 case IR_FSTORE: asm_fstore(as, ir); break;
2062 case IR_XSTORE: asm_xstore(as, ir, 0); break;
2063
2064 /* Allocations. */
2065 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
2066 case IR_TNEW: asm_tnew(as, ir); break;
2067 case IR_TDUP: asm_tdup(as, ir); break;
2068 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
2069
2070 /* Write barriers. */
2071 case IR_TBAR: asm_tbar(as, ir); break;
2072 case IR_OBAR: asm_obar(as, ir); break;
2073
2074 /* Type conversions. */
2075 case IR_CONV: asm_conv(as, ir); break;
2076 case IR_TOBIT: asm_tobit(as, ir); break;
2077 case IR_TOSTR: asm_tostr(as, ir); break;
2078 case IR_STRTO: asm_strto(as, ir); break;
2079
2080 /* Calls. */
2081 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
2082 case IR_CALLXS: asm_callx(as, ir); break;
2083 case IR_CARG: break;
2084
2085 default:
2086 setintV(&as->J->errinfo, ir->o);
2087 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
2088 break;
2089 }
2090}
2091
2092/* -- Trace setup --------------------------------------------------------- */ 1940/* -- Trace setup --------------------------------------------------------- */
2093 1941
2094/* Ensure there are enough stack slots for call arguments. */ 1942/* Ensure there are enough stack slots for call arguments. */
2095static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci) 1943static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
2096{ 1944{
2097 IRRef args[CCI_NARGS_MAX*2]; 1945 IRRef args[CCI_NARGS_MAX*2];
2098 uint32_t i, nargs = (int)CCI_NARGS(ci); 1946 uint32_t i, nargs = CCI_XNARGS(ci);
2099 int nslots = 2, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR; 1947 int nslots = 2, ngpr = REGARG_NUMGPR, nfpr = REGARG_NUMFPR;
2100 asm_collectargs(as, ir, ci, args); 1948 asm_collectargs(as, ir, ci, args);
2101 for (i = 0; i < nargs; i++) 1949 for (i = 0; i < nargs; i++)
diff --git a/src/lj_asm_x86.h b/src/lj_asm_x86.h
index 10468bb7..fceb1877 100644
--- a/src/lj_asm_x86.h
+++ b/src/lj_asm_x86.h
@@ -21,12 +21,14 @@ static MCode *asm_exitstub_gen(ASMState *as, ExitNo group)
21 } 21 }
22 /* Push the high byte of the exitno for each exit stub group. */ 22 /* Push the high byte of the exitno for each exit stub group. */
23 *mxp++ = XI_PUSHi8; *mxp++ = (MCode)((group*EXITSTUBS_PER_GROUP)>>8); 23 *mxp++ = XI_PUSHi8; *mxp++ = (MCode)((group*EXITSTUBS_PER_GROUP)>>8);
24#if !LJ_GC64
24 /* Store DISPATCH at original stack slot 0. Account for the two push ops. */ 25 /* Store DISPATCH at original stack slot 0. Account for the two push ops. */
25 *mxp++ = XI_MOVmi; 26 *mxp++ = XI_MOVmi;
26 *mxp++ = MODRM(XM_OFS8, 0, RID_ESP); 27 *mxp++ = MODRM(XM_OFS8, 0, RID_ESP);
27 *mxp++ = MODRM(XM_SCALE1, RID_ESP, RID_ESP); 28 *mxp++ = MODRM(XM_SCALE1, RID_ESP, RID_ESP);
28 *mxp++ = 2*sizeof(void *); 29 *mxp++ = 2*sizeof(void *);
29 *(int32_t *)mxp = ptr2addr(J2GG(as->J)->dispatch); mxp += 4; 30 *(int32_t *)mxp = ptr2addr(J2GG(as->J)->dispatch); mxp += 4;
31#endif
30 /* Jump to exit handler which fills in the ExitState. */ 32 /* Jump to exit handler which fills in the ExitState. */
31 *mxp++ = XI_JMP; mxp += 4; 33 *mxp++ = XI_JMP; mxp += 4;
32 *((int32_t *)(mxp-4)) = jmprel(mxp, (MCode *)(void *)lj_vm_exit_handler); 34 *((int32_t *)(mxp-4)) = jmprel(mxp, (MCode *)(void *)lj_vm_exit_handler);
@@ -62,10 +64,14 @@ static void asm_guardcc(ASMState *as, int cc)
62 target = p; 64 target = p;
63 cc ^= 1; 65 cc ^= 1;
64 if (as->realign) { 66 if (as->realign) {
67 if (LJ_GC64 && LJ_UNLIKELY(as->mrm.base == RID_RIP))
68 as->mrm.ofs += 2; /* Fixup RIP offset for pending fused load. */
65 emit_sjcc(as, cc, target); 69 emit_sjcc(as, cc, target);
66 return; 70 return;
67 } 71 }
68 } 72 }
73 if (LJ_GC64 && LJ_UNLIKELY(as->mrm.base == RID_RIP))
74 as->mrm.ofs += 6; /* Fixup RIP offset for pending fused load. */
69 emit_jcc(as, cc, target); 75 emit_jcc(as, cc, target);
70} 76}
71 77
@@ -79,6 +85,15 @@ static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
79{ 85{
80 if (irref_isk(ref)) { 86 if (irref_isk(ref)) {
81 IRIns *ir = IR(ref); 87 IRIns *ir = IR(ref);
88#if LJ_GC64
89 if (ir->o == IR_KNULL || !irt_is64(ir->t)) {
90 *k = ir->i;
91 return 1;
92 } else if (checki32((int64_t)ir_k64(ir)->u64)) {
93 *k = (int32_t)ir_k64(ir)->u64;
94 return 1;
95 }
96#else
82 if (ir->o != IR_KINT64) { 97 if (ir->o != IR_KINT64) {
83 *k = ir->i; 98 *k = ir->i;
84 return 1; 99 return 1;
@@ -86,6 +101,7 @@ static int asm_isk32(ASMState *as, IRRef ref, int32_t *k)
86 *k = (int32_t)ir_kint64(ir)->u64; 101 *k = (int32_t)ir_kint64(ir)->u64;
87 return 1; 102 return 1;
88 } 103 }
104#endif
89 } 105 }
90 return 0; 106 return 0;
91} 107}
@@ -185,9 +201,19 @@ static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow)
185 if (irref_isk(ir->op1)) { 201 if (irref_isk(ir->op1)) {
186 GCfunc *fn = ir_kfunc(IR(ir->op1)); 202 GCfunc *fn = ir_kfunc(IR(ir->op1));
187 GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv; 203 GCupval *uv = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv;
204#if LJ_GC64
205 int64_t ofs = dispofs(as, &uv->tv);
206 if (checki32(ofs) && checki32(ofs+4)) {
207 as->mrm.ofs = (int32_t)ofs;
208 as->mrm.base = RID_DISPATCH;
209 as->mrm.idx = RID_NONE;
210 return;
211 }
212#else
188 as->mrm.ofs = ptr2addr(&uv->tv); 213 as->mrm.ofs = ptr2addr(&uv->tv);
189 as->mrm.base = as->mrm.idx = RID_NONE; 214 as->mrm.base = as->mrm.idx = RID_NONE;
190 return; 215 return;
216#endif
191 } 217 }
192 break; 218 break;
193 default: 219 default:
@@ -205,14 +231,40 @@ static void asm_fuseahuref(ASMState *as, IRRef ref, RegSet allow)
205static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow) 231static void asm_fusefref(ASMState *as, IRIns *ir, RegSet allow)
206{ 232{
207 lua_assert(ir->o == IR_FLOAD || ir->o == IR_FREF); 233 lua_assert(ir->o == IR_FLOAD || ir->o == IR_FREF);
208 as->mrm.ofs = field_ofs[ir->op2];
209 as->mrm.idx = RID_NONE; 234 as->mrm.idx = RID_NONE;
235 if (ir->op1 == REF_NIL) {
236#if LJ_GC64
237 as->mrm.ofs = (int32_t)(ir->op2 << 2) - GG_OFS(dispatch);
238 as->mrm.base = RID_DISPATCH;
239#else
240 as->mrm.ofs = (int32_t)(ir->op2 << 2) + ptr2addr(J2GG(as->J));
241 as->mrm.base = RID_NONE;
242#endif
243 return;
244 }
245 as->mrm.ofs = field_ofs[ir->op2];
210 if (irref_isk(ir->op1)) { 246 if (irref_isk(ir->op1)) {
211 as->mrm.ofs += IR(ir->op1)->i; 247 IRIns *op1 = IR(ir->op1);
248#if LJ_GC64
249 if (ir->op1 == REF_NIL) {
250 as->mrm.ofs -= GG_OFS(dispatch);
251 as->mrm.base = RID_DISPATCH;
252 return;
253 } else if (op1->o == IR_KPTR || op1->o == IR_KKPTR) {
254 intptr_t ofs = dispofs(as, ir_kptr(op1));
255 if (checki32(as->mrm.ofs + ofs)) {
256 as->mrm.ofs += (int32_t)ofs;
257 as->mrm.base = RID_DISPATCH;
258 return;
259 }
260 }
261#else
262 as->mrm.ofs += op1->i;
212 as->mrm.base = RID_NONE; 263 as->mrm.base = RID_NONE;
213 } else { 264 return;
214 as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow); 265#endif
215 } 266 }
267 as->mrm.base = (uint8_t)ra_alloc1(as, ir->op1, allow);
216} 268}
217 269
218/* Fuse string reference into memory operand. */ 270/* Fuse string reference into memory operand. */
@@ -223,7 +275,7 @@ static void asm_fusestrref(ASMState *as, IRIns *ir, RegSet allow)
223 as->mrm.base = as->mrm.idx = RID_NONE; 275 as->mrm.base = as->mrm.idx = RID_NONE;
224 as->mrm.scale = XM_SCALE1; 276 as->mrm.scale = XM_SCALE1;
225 as->mrm.ofs = sizeof(GCstr); 277 as->mrm.ofs = sizeof(GCstr);
226 if (irref_isk(ir->op1)) { 278 if (!LJ_GC64 && irref_isk(ir->op1)) {
227 as->mrm.ofs += IR(ir->op1)->i; 279 as->mrm.ofs += IR(ir->op1)->i;
228 } else { 280 } else {
229 Reg r = ra_alloc1(as, ir->op1, allow); 281 Reg r = ra_alloc1(as, ir->op1, allow);
@@ -255,10 +307,20 @@ static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow)
255 IRIns *ir = IR(ref); 307 IRIns *ir = IR(ref);
256 as->mrm.idx = RID_NONE; 308 as->mrm.idx = RID_NONE;
257 if (ir->o == IR_KPTR || ir->o == IR_KKPTR) { 309 if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
310#if LJ_GC64
311 intptr_t ofs = dispofs(as, ir_kptr(ir));
312 if (checki32(ofs)) {
313 as->mrm.ofs = (int32_t)ofs;
314 as->mrm.base = RID_DISPATCH;
315 return;
316 }
317 } if (0) {
318#else
258 as->mrm.ofs = ir->i; 319 as->mrm.ofs = ir->i;
259 as->mrm.base = RID_NONE; 320 as->mrm.base = RID_NONE;
260 } else if (ir->o == IR_STRREF) { 321 } else if (ir->o == IR_STRREF) {
261 asm_fusestrref(as, ir, allow); 322 asm_fusestrref(as, ir, allow);
323#endif
262 } else { 324 } else {
263 as->mrm.ofs = 0; 325 as->mrm.ofs = 0;
264 if (canfuse(as, ir) && ir->o == IR_ADD && ra_noreg(ir->r)) { 326 if (canfuse(as, ir) && ir->o == IR_ADD && ra_noreg(ir->r)) {
@@ -301,7 +363,45 @@ static void asm_fusexref(ASMState *as, IRRef ref, RegSet allow)
301 } 363 }
302} 364}
303 365
304/* Fuse load into memory operand. */ 366/* Fuse load of 64 bit IR constant into memory operand. */
367static Reg asm_fuseloadk64(ASMState *as, IRIns *ir)
368{
369 const uint64_t *k = &ir_k64(ir)->u64;
370 if (!LJ_GC64 || checki32((intptr_t)k)) {
371 as->mrm.ofs = ptr2addr(k);
372 as->mrm.base = RID_NONE;
373#if LJ_GC64
374 } else if (checki32(dispofs(as, k))) {
375 as->mrm.ofs = (int32_t)dispofs(as, k);
376 as->mrm.base = RID_DISPATCH;
377 } else if (checki32(mcpofs(as, k)) && checki32(mcpofs(as, k+1)) &&
378 checki32(mctopofs(as, k)) && checki32(mctopofs(as, k+1))) {
379 as->mrm.ofs = (int32_t)mcpofs(as, k);
380 as->mrm.base = RID_RIP;
381 } else {
382 if (ir->i) {
383 lua_assert(*k == *(uint64_t*)(as->mctop - ir->i));
384 } else {
385 while ((uintptr_t)as->mcbot & 7) *as->mcbot++ = XI_INT3;
386 *(uint64_t*)as->mcbot = *k;
387 ir->i = (int32_t)(as->mctop - as->mcbot);
388 as->mcbot += 8;
389 as->mclim = as->mcbot + MCLIM_REDZONE;
390 }
391 as->mrm.ofs = (int32_t)mcpofs(as, as->mctop - ir->i);
392 as->mrm.base = RID_RIP;
393#endif
394 }
395 as->mrm.idx = RID_NONE;
396 return RID_MRM;
397}
398
399/* Fuse load into memory operand.
400**
401** Important caveat: this may emit RIP-relative loads! So don't place any
402** code emitters between this function and the use of its result.
403** The only permitted exception is asm_guardcc().
404*/
305static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow) 405static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
306{ 406{
307 IRIns *ir = IR(ref); 407 IRIns *ir = IR(ref);
@@ -320,26 +420,35 @@ static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
320 if (ir->o == IR_KNUM) { 420 if (ir->o == IR_KNUM) {
321 RegSet avail = as->freeset & ~as->modset & RSET_FPR; 421 RegSet avail = as->freeset & ~as->modset & RSET_FPR;
322 lua_assert(allow != RSET_EMPTY); 422 lua_assert(allow != RSET_EMPTY);
323 if (!(avail & (avail-1))) { /* Fuse if less than two regs available. */ 423 if (!(avail & (avail-1))) /* Fuse if less than two regs available. */
324 as->mrm.ofs = ptr2addr(ir_knum(ir)); 424 return asm_fuseloadk64(as, ir);
325 as->mrm.base = as->mrm.idx = RID_NONE;
326 return RID_MRM;
327 }
328 } else if (ref == REF_BASE || ir->o == IR_KINT64) { 425 } else if (ref == REF_BASE || ir->o == IR_KINT64) {
329 RegSet avail = as->freeset & ~as->modset & RSET_GPR; 426 RegSet avail = as->freeset & ~as->modset & RSET_GPR;
330 lua_assert(allow != RSET_EMPTY); 427 lua_assert(allow != RSET_EMPTY);
331 if (!(avail & (avail-1))) { /* Fuse if less than two regs available. */ 428 if (!(avail & (avail-1))) { /* Fuse if less than two regs available. */
332 as->mrm.ofs = ptr2addr(ref == REF_BASE ? (void *)&J2G(as->J)->jit_base : (void *)ir_kint64(ir)); 429 if (ref == REF_BASE) {
333 as->mrm.base = as->mrm.idx = RID_NONE; 430#if LJ_GC64
334 return RID_MRM; 431 as->mrm.ofs = (int32_t)dispofs(as, &J2G(as->J)->jit_base);
432 as->mrm.base = RID_DISPATCH;
433#else
434 as->mrm.ofs = ptr2addr(&J2G(as->J)->jit_base);
435 as->mrm.base = RID_NONE;
436#endif
437 as->mrm.idx = RID_NONE;
438 return RID_MRM;
439 } else {
440 return asm_fuseloadk64(as, ir);
441 }
335 } 442 }
336 } else if (mayfuse(as, ref)) { 443 } else if (mayfuse(as, ref)) {
337 RegSet xallow = (allow & RSET_GPR) ? allow : RSET_GPR; 444 RegSet xallow = (allow & RSET_GPR) ? allow : RSET_GPR;
338 if (ir->o == IR_SLOAD) { 445 if (ir->o == IR_SLOAD) {
339 if (!(ir->op2 & (IRSLOAD_PARENT|IRSLOAD_CONVERT)) && 446 if (!(ir->op2 & (IRSLOAD_PARENT|IRSLOAD_CONVERT)) &&
340 noconflict(as, ref, IR_RETF, 0)) { 447 noconflict(as, ref, IR_RETF, 0) &&
448 !(LJ_GC64 && irt_isaddr(ir->t))) {
341 as->mrm.base = (uint8_t)ra_alloc1(as, REF_BASE, xallow); 449 as->mrm.base = (uint8_t)ra_alloc1(as, REF_BASE, xallow);
342 as->mrm.ofs = 8*((int32_t)ir->op1-1) + ((ir->op2&IRSLOAD_FRAME)?4:0); 450 as->mrm.ofs = 8*((int32_t)ir->op1-1-LJ_FR2) +
451 (!LJ_FR2 && (ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
343 as->mrm.idx = RID_NONE; 452 as->mrm.idx = RID_NONE;
344 return RID_MRM; 453 return RID_MRM;
345 } 454 }
@@ -351,7 +460,8 @@ static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
351 return RID_MRM; 460 return RID_MRM;
352 } 461 }
353 } else if (ir->o == IR_ALOAD || ir->o == IR_HLOAD || ir->o == IR_ULOAD) { 462 } else if (ir->o == IR_ALOAD || ir->o == IR_HLOAD || ir->o == IR_ULOAD) {
354 if (noconflict(as, ref, ir->o + IRDELTA_L2S, 0)) { 463 if (noconflict(as, ref, ir->o + IRDELTA_L2S, 0) &&
464 !(LJ_GC64 && irt_isaddr(ir->t))) {
355 asm_fuseahuref(as, ir->op1, xallow); 465 asm_fuseahuref(as, ir->op1, xallow);
356 return RID_MRM; 466 return RID_MRM;
357 } 467 }
@@ -364,11 +474,15 @@ static Reg asm_fuseload(ASMState *as, IRRef ref, RegSet allow)
364 asm_fusexref(as, ir->op1, xallow); 474 asm_fusexref(as, ir->op1, xallow);
365 return RID_MRM; 475 return RID_MRM;
366 } 476 }
367 } else if (ir->o == IR_VLOAD) { 477 } else if (ir->o == IR_VLOAD && !(LJ_GC64 && irt_isaddr(ir->t))) {
368 asm_fuseahuref(as, ir->op1, xallow); 478 asm_fuseahuref(as, ir->op1, xallow);
369 return RID_MRM; 479 return RID_MRM;
370 } 480 }
371 } 481 }
482 if (ir->o == IR_FLOAD && ir->op1 == REF_NIL) {
483 asm_fusefref(as, ir, RSET_EMPTY);
484 return RID_MRM;
485 }
372 if (!(as->freeset & allow) && !emit_canremat(ref) && 486 if (!(as->freeset & allow) && !emit_canremat(ref) &&
373 (allow == RSET_EMPTY || ra_hasspill(ir->s) || iscrossref(as, ref))) 487 (allow == RSET_EMPTY || ra_hasspill(ir->s) || iscrossref(as, ref)))
374 goto fusespill; 488 goto fusespill;
@@ -392,7 +506,7 @@ static Reg asm_fuseloadm(ASMState *as, IRRef ref, RegSet allow, int is64)
392/* Count the required number of stack slots for a call. */ 506/* Count the required number of stack slots for a call. */
393static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args) 507static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args)
394{ 508{
395 uint32_t i, nargs = CCI_NARGS(ci); 509 uint32_t i, nargs = CCI_XNARGS(ci);
396 int nslots = 0; 510 int nslots = 0;
397#if LJ_64 511#if LJ_64
398 if (LJ_ABI_WIN) { 512 if (LJ_ABI_WIN) {
@@ -425,7 +539,7 @@ static int asm_count_call_slots(ASMState *as, const CCallInfo *ci, IRRef *args)
425/* Generate a call to a C function. */ 539/* Generate a call to a C function. */
426static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args) 540static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
427{ 541{
428 uint32_t n, nargs = CCI_NARGS(ci); 542 uint32_t n, nargs = CCI_XNARGS(ci);
429 int32_t ofs = STACKARG_OFS; 543 int32_t ofs = STACKARG_OFS;
430#if LJ_64 544#if LJ_64
431 uint32_t gprs = REGARG_GPRS; 545 uint32_t gprs = REGARG_GPRS;
@@ -485,8 +599,8 @@ static void asm_gencall(ASMState *as, const CCallInfo *ci, IRRef *args)
485 if (r) { /* Argument is in a register. */ 599 if (r) { /* Argument is in a register. */
486 if (r < RID_MAX_GPR && ref < ASMREF_TMP1) { 600 if (r < RID_MAX_GPR && ref < ASMREF_TMP1) {
487#if LJ_64 601#if LJ_64
488 if (ir->o == IR_KINT64) 602 if (LJ_GC64 ? !(ir->o == IR_KINT || ir->o == IR_KNULL) : ir->o == IR_KINT64)
489 emit_loadu64(as, r, ir_kint64(ir)->u64); 603 emit_loadu64(as, r, ir_k64(ir)->u64);
490 else 604 else
491#endif 605#endif
492 emit_loadi(as, r, ir->i); 606 emit_loadi(as, r, ir->i);
@@ -560,7 +674,7 @@ static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
560 if (ra_hasreg(dest)) { 674 if (ra_hasreg(dest)) {
561 ra_free(as, dest); 675 ra_free(as, dest);
562 ra_modified(as, dest); 676 ra_modified(as, dest);
563 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS, 677 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS,
564 dest, RID_ESP, ofs); 678 dest, RID_ESP, ofs);
565 } 679 }
566 if ((ci->flags & CCI_CASTU64)) { 680 if ((ci->flags & CCI_CASTU64)) {
@@ -584,15 +698,6 @@ static void asm_setupresult(ASMState *as, IRIns *ir, const CCallInfo *ci)
584 } 698 }
585} 699}
586 700
587static void asm_call(ASMState *as, IRIns *ir)
588{
589 IRRef args[CCI_NARGS_MAX];
590 const CCallInfo *ci = &lj_ir_callinfo[ir->op2];
591 asm_collectargs(as, ir, ci, args);
592 asm_setupresult(as, ir, ci);
593 asm_gencall(as, ci, args);
594}
595
596/* Return a constant function pointer or NULL for indirect calls. */ 701/* Return a constant function pointer or NULL for indirect calls. */
597static void *asm_callx_func(ASMState *as, IRIns *irf, IRRef func) 702static void *asm_callx_func(ASMState *as, IRIns *irf, IRRef func)
598{ 703{
@@ -651,15 +756,23 @@ static void asm_callx(ASMState *as, IRIns *ir)
651static void asm_retf(ASMState *as, IRIns *ir) 756static void asm_retf(ASMState *as, IRIns *ir)
652{ 757{
653 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR); 758 Reg base = ra_alloc1(as, REF_BASE, RSET_GPR);
759#if LJ_FR2
760 Reg rpc = ra_scratch(as, rset_exclude(RSET_GPR, base));
761#endif
654 void *pc = ir_kptr(IR(ir->op2)); 762 void *pc = ir_kptr(IR(ir->op2));
655 int32_t delta = 1+bc_a(*((const BCIns *)pc - 1)); 763 int32_t delta = 1+LJ_FR2+bc_a(*((const BCIns *)pc - 1));
656 as->topslot -= (BCReg)delta; 764 as->topslot -= (BCReg)delta;
657 if ((int32_t)as->topslot < 0) as->topslot = 0; 765 if ((int32_t)as->topslot < 0) as->topslot = 0;
658 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */ 766 irt_setmark(IR(REF_BASE)->t); /* Children must not coalesce with BASE reg. */
659 emit_setgl(as, base, jit_base); 767 emit_setgl(as, base, jit_base);
660 emit_addptr(as, base, -8*delta); 768 emit_addptr(as, base, -8*delta);
661 asm_guardcc(as, CC_NE); 769 asm_guardcc(as, CC_NE);
770#if LJ_FR2
771 emit_rmro(as, XO_CMP, rpc|REX_GC64, base, -8);
772 emit_loadu64(as, rpc, u64ptr(pc));
773#else
662 emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc)); 774 emit_gmroi(as, XG_ARITHi(XOg_CMP), base, -4, ptr2addr(pc));
775#endif
663} 776}
664 777
665/* -- Type conversions ---------------------------------------------------- */ 778/* -- Type conversions ---------------------------------------------------- */
@@ -672,8 +785,7 @@ static void asm_tointg(ASMState *as, IRIns *ir, Reg left)
672 asm_guardcc(as, CC_NE); 785 asm_guardcc(as, CC_NE);
673 emit_rr(as, XO_UCOMISD, left, tmp); 786 emit_rr(as, XO_UCOMISD, left, tmp);
674 emit_rr(as, XO_CVTSI2SD, tmp, dest); 787 emit_rr(as, XO_CVTSI2SD, tmp, dest);
675 if (!(as->flags & JIT_F_SPLIT_XMM)) 788 emit_rr(as, XO_XORPS, tmp, tmp); /* Avoid partial register stall. */
676 emit_rr(as, XO_XORPS, tmp, tmp); /* Avoid partial register stall. */
677 emit_rr(as, XO_CVTTSD2SI, dest, left); 789 emit_rr(as, XO_CVTTSD2SI, dest, left);
678 /* Can't fuse since left is needed twice. */ 790 /* Can't fuse since left is needed twice. */
679} 791}
@@ -684,8 +796,9 @@ static void asm_tobit(ASMState *as, IRIns *ir)
684 Reg tmp = ra_noreg(IR(ir->op1)->r) ? 796 Reg tmp = ra_noreg(IR(ir->op1)->r) ?
685 ra_alloc1(as, ir->op1, RSET_FPR) : 797 ra_alloc1(as, ir->op1, RSET_FPR) :
686 ra_scratch(as, RSET_FPR); 798 ra_scratch(as, RSET_FPR);
687 Reg right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp)); 799 Reg right;
688 emit_rr(as, XO_MOVDto, tmp, dest); 800 emit_rr(as, XO_MOVDto, tmp, dest);
801 right = asm_fuseload(as, ir->op2, rset_exclude(RSET_FPR, tmp));
689 emit_mrm(as, XO_ADDSD, tmp, right); 802 emit_mrm(as, XO_ADDSD, tmp, right);
690 ra_left(as, tmp, ir->op1); 803 ra_left(as, tmp, ir->op1);
691} 804}
@@ -706,13 +819,13 @@ static void asm_conv(ASMState *as, IRIns *ir)
706 if (left == dest) return; /* Avoid the XO_XORPS. */ 819 if (left == dest) return; /* Avoid the XO_XORPS. */
707 } else if (LJ_32 && st == IRT_U32) { /* U32 to FP conversion on x86. */ 820 } else if (LJ_32 && st == IRT_U32) { /* U32 to FP conversion on x86. */
708 /* number = (2^52+2^51 .. u32) - (2^52+2^51) */ 821 /* number = (2^52+2^51 .. u32) - (2^52+2^51) */
709 cTValue *k = lj_ir_k64_find(as->J, U64x(43380000,00000000)); 822 cTValue *k = &as->J->k64[LJ_K64_TOBIT];
710 Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest)); 823 Reg bias = ra_scratch(as, rset_exclude(RSET_FPR, dest));
711 if (irt_isfloat(ir->t)) 824 if (irt_isfloat(ir->t))
712 emit_rr(as, XO_CVTSD2SS, dest, dest); 825 emit_rr(as, XO_CVTSD2SS, dest, dest);
713 emit_rr(as, XO_SUBSD, dest, bias); /* Subtract 2^52+2^51 bias. */ 826 emit_rr(as, XO_SUBSD, dest, bias); /* Subtract 2^52+2^51 bias. */
714 emit_rr(as, XO_XORPS, dest, bias); /* Merge bias and integer. */ 827 emit_rr(as, XO_XORPS, dest, bias); /* Merge bias and integer. */
715 emit_loadn(as, bias, k); 828 emit_rma(as, XO_MOVSD, bias, k);
716 emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR)); 829 emit_mrm(as, XO_MOVD, dest, asm_fuseload(as, lref, RSET_GPR));
717 return; 830 return;
718 } else { /* Integer to FP conversion. */ 831 } else { /* Integer to FP conversion. */
@@ -721,7 +834,7 @@ static void asm_conv(ASMState *as, IRIns *ir)
721 asm_fuseloadm(as, lref, RSET_GPR, st64); 834 asm_fuseloadm(as, lref, RSET_GPR, st64);
722 if (LJ_64 && st == IRT_U64) { 835 if (LJ_64 && st == IRT_U64) {
723 MCLabel l_end = emit_label(as); 836 MCLabel l_end = emit_label(as);
724 const void *k = lj_ir_k64_find(as->J, U64x(43f00000,00000000)); 837 cTValue *k = &as->J->k64[LJ_K64_2P64];
725 emit_rma(as, XO_ADDSD, dest, k); /* Add 2^64 to compensate. */ 838 emit_rma(as, XO_ADDSD, dest, k); /* Add 2^64 to compensate. */
726 emit_sjcc(as, CC_NS, l_end); 839 emit_sjcc(as, CC_NS, l_end);
727 emit_rr(as, XO_TEST, left|REX_64, left); /* Check if u64 >= 2^63. */ 840 emit_rr(as, XO_TEST, left|REX_64, left); /* Check if u64 >= 2^63. */
@@ -729,8 +842,7 @@ static void asm_conv(ASMState *as, IRIns *ir)
729 emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS, 842 emit_mrm(as, irt_isnum(ir->t) ? XO_CVTSI2SD : XO_CVTSI2SS,
730 dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left); 843 dest|((LJ_64 && (st64 || st == IRT_U32)) ? REX_64 : 0), left);
731 } 844 }
732 if (!(as->flags & JIT_F_SPLIT_XMM)) 845 emit_rr(as, XO_XORPS, dest, dest); /* Avoid partial register stall. */
733 emit_rr(as, XO_XORPS, dest, dest); /* Avoid partial register stall. */
734 } else if (stfp) { /* FP to integer conversion. */ 846 } else if (stfp) { /* FP to integer conversion. */
735 if (irt_isguard(ir->t)) { 847 if (irt_isguard(ir->t)) {
736 /* Checked conversions are only supported from number to int. */ 848 /* Checked conversions are only supported from number to int. */
@@ -738,9 +850,7 @@ static void asm_conv(ASMState *as, IRIns *ir)
738 asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR)); 850 asm_tointg(as, ir, ra_alloc1(as, lref, RSET_FPR));
739 } else { 851 } else {
740 Reg dest = ra_dest(as, ir, RSET_GPR); 852 Reg dest = ra_dest(as, ir, RSET_GPR);
741 x86Op op = st == IRT_NUM ? 853 x86Op op = st == IRT_NUM ? XO_CVTTSD2SI : XO_CVTTSS2SI;
742 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSD2SI : XO_CVTSD2SI) :
743 ((ir->op2 & IRCONV_TRUNC) ? XO_CVTTSS2SI : XO_CVTSS2SI);
744 if (LJ_64 ? irt_isu64(ir->t) : irt_isu32(ir->t)) { 854 if (LJ_64 ? irt_isu64(ir->t) : irt_isu32(ir->t)) {
745 /* LJ_64: For inputs >= 2^63 add -2^64, convert again. */ 855 /* LJ_64: For inputs >= 2^63 add -2^64, convert again. */
746 /* LJ_32: For inputs >= 2^31 add -2^31, convert again and add 2^31. */ 856 /* LJ_32: For inputs >= 2^31 add -2^31, convert again and add 2^31. */
@@ -751,23 +861,20 @@ static void asm_conv(ASMState *as, IRIns *ir)
751 emit_gri(as, XG_ARITHi(XOg_ADD), dest, (int32_t)0x80000000); 861 emit_gri(as, XG_ARITHi(XOg_ADD), dest, (int32_t)0x80000000);
752 emit_rr(as, op, dest|REX_64, tmp); 862 emit_rr(as, op, dest|REX_64, tmp);
753 if (st == IRT_NUM) 863 if (st == IRT_NUM)
754 emit_rma(as, XO_ADDSD, tmp, lj_ir_k64_find(as->J, 864 emit_rma(as, XO_ADDSD, tmp, &as->J->k64[LJ_K64_M2P64_31]);
755 LJ_64 ? U64x(c3f00000,00000000) : U64x(c1e00000,00000000)));
756 else 865 else
757 emit_rma(as, XO_ADDSS, tmp, lj_ir_k64_find(as->J, 866 emit_rma(as, XO_ADDSS, tmp, &as->J->k32[LJ_K32_M2P64_31]);
758 LJ_64 ? U64x(00000000,df800000) : U64x(00000000,cf000000)));
759 emit_sjcc(as, CC_NS, l_end); 867 emit_sjcc(as, CC_NS, l_end);
760 emit_rr(as, XO_TEST, dest|REX_64, dest); /* Check if dest negative. */ 868 emit_rr(as, XO_TEST, dest|REX_64, dest); /* Check if dest negative. */
761 emit_rr(as, op, dest|REX_64, tmp); 869 emit_rr(as, op, dest|REX_64, tmp);
762 ra_left(as, tmp, lref); 870 ra_left(as, tmp, lref);
763 } else { 871 } else {
764 Reg left = asm_fuseload(as, lref, RSET_FPR);
765 if (LJ_64 && irt_isu32(ir->t)) 872 if (LJ_64 && irt_isu32(ir->t))
766 emit_rr(as, XO_MOV, dest, dest); /* Zero hiword. */ 873 emit_rr(as, XO_MOV, dest, dest); /* Zero hiword. */
767 emit_mrm(as, op, 874 emit_mrm(as, op,
768 dest|((LJ_64 && 875 dest|((LJ_64 &&
769 (irt_is64(ir->t) || irt_isu32(ir->t))) ? REX_64 : 0), 876 (irt_is64(ir->t) || irt_isu32(ir->t))) ? REX_64 : 0),
770 left); 877 asm_fuseload(as, lref, RSET_FPR));
771 } 878 }
772 } 879 }
773 } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */ 880 } else if (st >= IRT_I8 && st <= IRT_U16) { /* Extend to 32 bit integer. */
@@ -834,16 +941,14 @@ static void asm_conv_fp_int64(ASMState *as, IRIns *ir)
834 if (ra_hasreg(dest)) { 941 if (ra_hasreg(dest)) {
835 ra_free(as, dest); 942 ra_free(as, dest);
836 ra_modified(as, dest); 943 ra_modified(as, dest);
837 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS, 944 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, dest, RID_ESP, ofs);
838 dest, RID_ESP, ofs);
839 } 945 }
840 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd, 946 emit_rmro(as, irt_isnum(ir->t) ? XO_FSTPq : XO_FSTPd,
841 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs); 947 irt_isnum(ir->t) ? XOg_FSTPq : XOg_FSTPd, RID_ESP, ofs);
842 if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) { 948 if (((ir-1)->op2 & IRCONV_SRCMASK) == IRT_U64) {
843 /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */ 949 /* For inputs in [2^63,2^64-1] add 2^64 to compensate. */
844 MCLabel l_end = emit_label(as); 950 MCLabel l_end = emit_label(as);
845 emit_rma(as, XO_FADDq, XOg_FADDq, 951 emit_rma(as, XO_FADDq, XOg_FADDq, &as->J->k64[LJ_K64_2P64]);
846 lj_ir_k64_find(as->J, U64x(43f00000,00000000)));
847 emit_sjcc(as, CC_NS, l_end); 952 emit_sjcc(as, CC_NS, l_end);
848 emit_rr(as, XO_TEST, hi, hi); /* Check if u64 >= 2^63. */ 953 emit_rr(as, XO_TEST, hi, hi); /* Check if u64 >= 2^63. */
849 } else { 954 } else {
@@ -863,7 +968,6 @@ static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
863 Reg lo, hi; 968 Reg lo, hi;
864 lua_assert(st == IRT_NUM || st == IRT_FLOAT); 969 lua_assert(st == IRT_NUM || st == IRT_FLOAT);
865 lua_assert(dt == IRT_I64 || dt == IRT_U64); 970 lua_assert(dt == IRT_I64 || dt == IRT_U64);
866 lua_assert(((ir-1)->op2 & IRCONV_TRUNC));
867 hi = ra_dest(as, ir, RSET_GPR); 971 hi = ra_dest(as, ir, RSET_GPR);
868 lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi)); 972 lo = ra_dest(as, ir-1, rset_exclude(RSET_GPR, hi));
869 if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0); 973 if (ra_used(ir-1)) emit_rmro(as, XO_MOV, lo, RID_ESP, 0);
@@ -884,8 +988,7 @@ static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
884 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0); 988 emit_rmro(as, XO_FISTTPq, XOg_FISTTPq, RID_ESP, 0);
885 else 989 else
886 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0); 990 emit_rmro(as, XO_FISTPq, XOg_FISTPq, RID_ESP, 0);
887 emit_rma(as, XO_FADDq, XOg_FADDq, 991 emit_rma(as, XO_FADDq, XOg_FADDq, &as->J->k64[LJ_K64_M2P64]);
888 lj_ir_k64_find(as->J, U64x(c3f00000,00000000)));
889 emit_sjcc(as, CC_NS, l_pop); 992 emit_sjcc(as, CC_NS, l_pop);
890 emit_rr(as, XO_TEST, hi, hi); /* Check if out-of-range (2^63). */ 993 emit_rr(as, XO_TEST, hi, hi); /* Check if out-of-range (2^63). */
891 } 994 }
@@ -906,6 +1009,14 @@ static void asm_conv_int64_fp(ASMState *as, IRIns *ir)
906 st == IRT_NUM ? XOg_FLDq: XOg_FLDd, 1009 st == IRT_NUM ? XOg_FLDq: XOg_FLDd,
907 asm_fuseload(as, ir->op1, RSET_EMPTY)); 1010 asm_fuseload(as, ir->op1, RSET_EMPTY));
908} 1011}
1012
1013static void asm_conv64(ASMState *as, IRIns *ir)
1014{
1015 if (irt_isfp(ir->t))
1016 asm_conv_fp_int64(as, ir);
1017 else
1018 asm_conv_int64_fp(as, ir);
1019}
909#endif 1020#endif
910 1021
911static void asm_strto(ASMState *as, IRIns *ir) 1022static void asm_strto(ASMState *as, IRIns *ir)
@@ -927,54 +1038,60 @@ static void asm_strto(ASMState *as, IRIns *ir)
927 RID_ESP, sps_scale(ir->s)); 1038 RID_ESP, sps_scale(ir->s));
928} 1039}
929 1040
930static void asm_tostr(ASMState *as, IRIns *ir) 1041/* -- Memory references --------------------------------------------------- */
1042
1043/* Get pointer to TValue. */
1044static void asm_tvptr(ASMState *as, Reg dest, IRRef ref)
931{ 1045{
932 IRIns *irl = IR(ir->op1); 1046 IRIns *ir = IR(ref);
933 IRRef args[2]; 1047 if (irt_isnum(ir->t)) {
934 args[0] = ASMREF_L; 1048 /* For numbers use the constant itself or a spill slot as a TValue. */
935 as->gcsteps++; 1049 if (irref_isk(ref))
936 if (irt_isnum(irl->t)) { 1050 emit_loada(as, dest, ir_knum(ir));
937 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromnum]; 1051 else
938 args[1] = ASMREF_TMP1; /* const lua_Number * */ 1052 emit_rmro(as, XO_LEA, dest|REX_64, RID_ESP, ra_spill(as, ir));
939 asm_setupresult(as, ir, ci); /* GCstr * */
940 asm_gencall(as, ci, args);
941 emit_rmro(as, XO_LEA, ra_releasetmp(as, ASMREF_TMP1)|REX_64,
942 RID_ESP, ra_spill(as, irl));
943 } else { 1053 } else {
944 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_str_fromint]; 1054 /* Otherwise use g->tmptv to hold the TValue. */
945 args[1] = ir->op1; /* int32_t k */ 1055#if LJ_GC64
946 asm_setupresult(as, ir, ci); /* GCstr * */ 1056 if (irref_isk(ref)) {
947 asm_gencall(as, ci, args); 1057 TValue k;
1058 lj_ir_kvalue(as->J->L, &k, ir);
1059 emit_movmroi(as, dest, 4, k.u32.hi);
1060 emit_movmroi(as, dest, 0, k.u32.lo);
1061 } else {
1062 /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */
1063 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, dest));
1064 if (irt_is64(ir->t)) {
1065 emit_u32(as, irt_toitype(ir->t) << 15);
1066 emit_rmro(as, XO_ARITHi, XOg_OR, dest, 4);
1067 } else {
1068 /* Currently, no caller passes integers that might end up here. */
1069 emit_movmroi(as, dest, 4, (irt_toitype(ir->t) << 15));
1070 }
1071 emit_movtomro(as, REX_64IR(ir, src), dest, 0);
1072 }
1073#else
1074 if (!irref_isk(ref)) {
1075 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, dest));
1076 emit_movtomro(as, REX_64IR(ir, src), dest, 0);
1077 } else if (!irt_ispri(ir->t)) {
1078 emit_movmroi(as, dest, 0, ir->i);
1079 }
1080 if (!(LJ_64 && irt_islightud(ir->t)))
1081 emit_movmroi(as, dest, 4, irt_toitype(ir->t));
1082#endif
1083 emit_loada(as, dest, &J2G(as->J)->tmptv);
948 } 1084 }
949} 1085}
950 1086
951/* -- Memory references --------------------------------------------------- */
952
953static void asm_aref(ASMState *as, IRIns *ir) 1087static void asm_aref(ASMState *as, IRIns *ir)
954{ 1088{
955 Reg dest = ra_dest(as, ir, RSET_GPR); 1089 Reg dest = ra_dest(as, ir, RSET_GPR);
956 asm_fusearef(as, ir, RSET_GPR); 1090 asm_fusearef(as, ir, RSET_GPR);
957 if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0)) 1091 if (!(as->mrm.idx == RID_NONE && as->mrm.ofs == 0))
958 emit_mrm(as, XO_LEA, dest, RID_MRM); 1092 emit_mrm(as, XO_LEA, dest|REX_GC64, RID_MRM);
959 else if (as->mrm.base != dest) 1093 else if (as->mrm.base != dest)
960 emit_rr(as, XO_MOV, dest, as->mrm.base); 1094 emit_rr(as, XO_MOV, dest|REX_GC64, as->mrm.base);
961}
962
963/* Merge NE(HREF, niltv) check. */
964static MCode *merge_href_niltv(ASMState *as, IRIns *ir)
965{
966 /* Assumes nothing else generates NE of HREF. */
967 if ((ir[1].o == IR_NE || ir[1].o == IR_EQ) && ir[1].op1 == as->curins &&
968 ra_hasreg(ir->r)) {
969 MCode *p = as->mcp;
970 p += (LJ_64 && *p != XI_ARITHi) ? 7+6 : 6+6;
971 /* Ensure no loop branch inversion happened. */
972 if (p[-6] == 0x0f && p[-5] == XI_JCCn+(CC_NE^(ir[1].o & 1))) {
973 as->mcp = p; /* Kill cmp reg, imm32 + jz exit. */
974 return p + *(int32_t *)(p-4); /* Return exit address. */
975 }
976 }
977 return NULL;
978} 1095}
979 1096
980/* Inlined hash lookup. Specialized for key type and for const keys. 1097/* Inlined hash lookup. Specialized for key type and for const keys.
@@ -985,10 +1102,10 @@ static MCode *merge_href_niltv(ASMState *as, IRIns *ir)
985** } while ((n = nextnode(n))); 1102** } while ((n = nextnode(n)));
986** return niltv(L); 1103** return niltv(L);
987*/ 1104*/
988static void asm_href(ASMState *as, IRIns *ir) 1105static void asm_href(ASMState *as, IRIns *ir, IROp merge)
989{ 1106{
990 MCode *nilexit = merge_href_niltv(as, ir); /* Do this before any restores. */
991 RegSet allow = RSET_GPR; 1107 RegSet allow = RSET_GPR;
1108 int destused = ra_used(ir);
992 Reg dest = ra_dest(as, ir, allow); 1109 Reg dest = ra_dest(as, ir, allow);
993 Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest)); 1110 Reg tab = ra_alloc1(as, ir->op1, rset_clear(allow, dest));
994 Reg key = RID_NONE, tmp = RID_NONE; 1111 Reg key = RID_NONE, tmp = RID_NONE;
@@ -1001,28 +1118,26 @@ static void asm_href(ASMState *as, IRIns *ir)
1001 if (!isk) { 1118 if (!isk) {
1002 rset_clear(allow, tab); 1119 rset_clear(allow, tab);
1003 key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow); 1120 key = ra_alloc1(as, ir->op2, irt_isnum(kt) ? RSET_FPR : allow);
1004 if (!irt_isstr(kt)) 1121 if (LJ_GC64 || !irt_isstr(kt))
1005 tmp = ra_scratch(as, rset_exclude(allow, key)); 1122 tmp = ra_scratch(as, rset_exclude(allow, key));
1006 } 1123 }
1007 1124
1008 /* Key not found in chain: jump to exit (if merged with NE) or load niltv. */ 1125 /* Key not found in chain: jump to exit (if merged) or load niltv. */
1009 l_end = emit_label(as); 1126 l_end = emit_label(as);
1010 if (nilexit && ir[1].o == IR_NE) { 1127 if (merge == IR_NE)
1011 emit_jcc(as, CC_E, nilexit); /* XI_JMP is not found by lj_asm_patchexit. */ 1128 asm_guardcc(as, CC_E); /* XI_JMP is not found by lj_asm_patchexit. */
1012 nilexit = NULL; 1129 else if (destused)
1013 } else {
1014 emit_loada(as, dest, niltvg(J2G(as->J))); 1130 emit_loada(as, dest, niltvg(J2G(as->J)));
1015 }
1016 1131
1017 /* Follow hash chain until the end. */ 1132 /* Follow hash chain until the end. */
1018 l_loop = emit_sjcc_label(as, CC_NZ); 1133 l_loop = emit_sjcc_label(as, CC_NZ);
1019 emit_rr(as, XO_TEST, dest, dest); 1134 emit_rr(as, XO_TEST, dest|REX_GC64, dest);
1020 emit_rmro(as, XO_MOV, dest, dest, offsetof(Node, next)); 1135 emit_rmro(as, XO_MOV, dest|REX_GC64, dest, offsetof(Node, next));
1021 l_next = emit_label(as); 1136 l_next = emit_label(as);
1022 1137
1023 /* Type and value comparison. */ 1138 /* Type and value comparison. */
1024 if (nilexit) 1139 if (merge == IR_EQ)
1025 emit_jcc(as, CC_E, nilexit); 1140 asm_guardcc(as, CC_E);
1026 else 1141 else
1027 emit_sjcc(as, CC_E, l_end); 1142 emit_sjcc(as, CC_E, l_end);
1028 if (irt_isnum(kt)) { 1143 if (irt_isnum(kt)) {
@@ -1038,7 +1153,7 @@ static void asm_href(ASMState *as, IRIns *ir)
1038 emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n)); 1153 emit_rmro(as, XO_UCOMISD, key, dest, offsetof(Node, key.n));
1039 emit_sjcc(as, CC_AE, l_next); 1154 emit_sjcc(as, CC_AE, l_next);
1040 /* The type check avoids NaN penalties and complaints from Valgrind. */ 1155 /* The type check avoids NaN penalties and complaints from Valgrind. */
1041#if LJ_64 1156#if LJ_64 && !LJ_GC64
1042 emit_u32(as, LJ_TISNUM); 1157 emit_u32(as, LJ_TISNUM);
1043 emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it)); 1158 emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it));
1044#else 1159#else
@@ -1046,10 +1161,28 @@ static void asm_href(ASMState *as, IRIns *ir)
1046 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it)); 1161 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
1047#endif 1162#endif
1048 } 1163 }
1049#if LJ_64 1164#if LJ_64 && !LJ_GC64
1050 } else if (irt_islightud(kt)) { 1165 } else if (irt_islightud(kt)) {
1051 emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64)); 1166 emit_rmro(as, XO_CMP, key|REX_64, dest, offsetof(Node, key.u64));
1052#endif 1167#endif
1168#if LJ_GC64
1169 } else if (irt_isaddr(kt)) {
1170 if (isk) {
1171 TValue k;
1172 k.u64 = ((uint64_t)irt_toitype(irkey->t) << 47) | irkey[1].tv.u64;
1173 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.lo),
1174 k.u32.lo);
1175 emit_sjcc(as, CC_NE, l_next);
1176 emit_gmroi(as, XG_ARITHi(XOg_CMP), dest, offsetof(Node, key.u32.hi),
1177 k.u32.hi);
1178 } else {
1179 emit_rmro(as, XO_CMP, tmp|REX_64, dest, offsetof(Node, key.u64));
1180 }
1181 } else {
1182 lua_assert(irt_ispri(kt) && !irt_isnil(kt));
1183 emit_u32(as, (irt_toitype(kt)<<15)|0x7fff);
1184 emit_rmro(as, XO_ARITHi, XOg_CMP, dest, offsetof(Node, key.it));
1185#else
1053 } else { 1186 } else {
1054 if (!irt_ispri(kt)) { 1187 if (!irt_ispri(kt)) {
1055 lua_assert(irt_isaddr(kt)); 1188 lua_assert(irt_isaddr(kt));
@@ -1063,16 +1196,23 @@ static void asm_href(ASMState *as, IRIns *ir)
1063 lua_assert(!irt_isnil(kt)); 1196 lua_assert(!irt_isnil(kt));
1064 emit_i8(as, irt_toitype(kt)); 1197 emit_i8(as, irt_toitype(kt));
1065 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it)); 1198 emit_rmro(as, XO_ARITHi8, XOg_CMP, dest, offsetof(Node, key.it));
1199#endif
1066 } 1200 }
1067 emit_sfixup(as, l_loop); 1201 emit_sfixup(as, l_loop);
1068 checkmclim(as); 1202 checkmclim(as);
1203#if LJ_GC64
1204 if (!isk && irt_isaddr(kt)) {
1205 emit_rr(as, XO_OR, tmp|REX_64, key);
1206 emit_loadu64(as, tmp, (uint64_t)irt_toitype(kt) << 47);
1207 }
1208#endif
1069 1209
1070 /* Load main position relative to tab->node into dest. */ 1210 /* Load main position relative to tab->node into dest. */
1071 khash = isk ? ir_khash(irkey) : 1; 1211 khash = isk ? ir_khash(irkey) : 1;
1072 if (khash == 0) { 1212 if (khash == 0) {
1073 emit_rmro(as, XO_MOV, dest, tab, offsetof(GCtab, node)); 1213 emit_rmro(as, XO_MOV, dest|REX_GC64, tab, offsetof(GCtab, node));
1074 } else { 1214 } else {
1075 emit_rmro(as, XO_ARITH(XOg_ADD), dest, tab, offsetof(GCtab, node)); 1215 emit_rmro(as, XO_ARITH(XOg_ADD), dest|REX_GC64, tab, offsetof(GCtab,node));
1076 if ((as->flags & JIT_F_PREFER_IMUL)) { 1216 if ((as->flags & JIT_F_PREFER_IMUL)) {
1077 emit_i8(as, sizeof(Node)); 1217 emit_i8(as, sizeof(Node));
1078 emit_rr(as, XO_IMULi8, dest, dest); 1218 emit_rr(as, XO_IMULi8, dest, dest);
@@ -1107,7 +1247,19 @@ static void asm_href(ASMState *as, IRIns *ir)
1107#endif 1247#endif
1108 } else { 1248 } else {
1109 emit_rr(as, XO_MOV, tmp, key); 1249 emit_rr(as, XO_MOV, tmp, key);
1250#if LJ_GC64
1251 checkmclim(as);
1252 emit_gri(as, XG_ARITHi(XOg_XOR), dest, irt_toitype(kt) << 15);
1253 if ((as->flags & JIT_F_BMI2)) {
1254 emit_i8(as, 32);
1255 emit_mrm(as, XV_RORX|VEX_64, dest, key);
1256 } else {
1257 emit_shifti(as, XOg_SHR|REX_64, dest, 32);
1258 emit_rr(as, XO_MOV, dest|REX_64, key|REX_64);
1259 }
1260#else
1110 emit_rmro(as, XO_LEA, dest, key, HASH_BIAS); 1261 emit_rmro(as, XO_LEA, dest, key, HASH_BIAS);
1262#endif
1111 } 1263 }
1112 } 1264 }
1113 } 1265 }
@@ -1127,11 +1279,11 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
1127 if (ra_hasreg(dest)) { 1279 if (ra_hasreg(dest)) {
1128 if (ofs != 0) { 1280 if (ofs != 0) {
1129 if (dest == node && !(as->flags & JIT_F_LEA_AGU)) 1281 if (dest == node && !(as->flags & JIT_F_LEA_AGU))
1130 emit_gri(as, XG_ARITHi(XOg_ADD), dest, ofs); 1282 emit_gri(as, XG_ARITHi(XOg_ADD), dest|REX_GC64, ofs);
1131 else 1283 else
1132 emit_rmro(as, XO_LEA, dest, node, ofs); 1284 emit_rmro(as, XO_LEA, dest|REX_GC64, node, ofs);
1133 } else if (dest != node) { 1285 } else if (dest != node) {
1134 emit_rr(as, XO_MOV, dest, node); 1286 emit_rr(as, XO_MOV, dest|REX_GC64, node);
1135 } 1287 }
1136 } 1288 }
1137 asm_guardcc(as, CC_NE); 1289 asm_guardcc(as, CC_NE);
@@ -1143,13 +1295,24 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
1143 lua_assert(irt_isnum(irkey->t) || irt_isgcv(irkey->t)); 1295 lua_assert(irt_isnum(irkey->t) || irt_isgcv(irkey->t));
1144 /* Assumes -0.0 is already canonicalized to +0.0. */ 1296 /* Assumes -0.0 is already canonicalized to +0.0. */
1145 emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 : 1297 emit_loadu64(as, key, irt_isnum(irkey->t) ? ir_knum(irkey)->u64 :
1298#if LJ_GC64
1299 ((uint64_t)irt_toitype(irkey->t) << 47) |
1300 (uint64_t)ir_kgc(irkey));
1301#else
1146 ((uint64_t)irt_toitype(irkey->t) << 32) | 1302 ((uint64_t)irt_toitype(irkey->t) << 32) |
1147 (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey))); 1303 (uint64_t)(uint32_t)ptr2addr(ir_kgc(irkey)));
1304#endif
1148 } else { 1305 } else {
1149 lua_assert(!irt_isnil(irkey->t)); 1306 lua_assert(!irt_isnil(irkey->t));
1307#if LJ_GC64
1308 emit_i32(as, (irt_toitype(irkey->t)<<15)|0x7fff);
1309 emit_rmro(as, XO_ARITHi, XOg_CMP, node,
1310 ofs + (int32_t)offsetof(Node, key.it));
1311#else
1150 emit_i8(as, irt_toitype(irkey->t)); 1312 emit_i8(as, irt_toitype(irkey->t));
1151 emit_rmro(as, XO_ARITHi8, XOg_CMP, node, 1313 emit_rmro(as, XO_ARITHi8, XOg_CMP, node,
1152 ofs + (int32_t)offsetof(Node, key.it)); 1314 ofs + (int32_t)offsetof(Node, key.it));
1315#endif
1153 } 1316 }
1154#else 1317#else
1155 l_exit = emit_label(as); 1318 l_exit = emit_label(as);
@@ -1178,61 +1341,27 @@ static void asm_hrefk(ASMState *as, IRIns *ir)
1178#endif 1341#endif
1179} 1342}
1180 1343
1181static void asm_newref(ASMState *as, IRIns *ir)
1182{
1183 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_tab_newkey];
1184 IRRef args[3];
1185 IRIns *irkey;
1186 Reg tmp;
1187 if (ir->r == RID_SINK)
1188 return;
1189 args[0] = ASMREF_L; /* lua_State *L */
1190 args[1] = ir->op1; /* GCtab *t */
1191 args[2] = ASMREF_TMP1; /* cTValue *key */
1192 asm_setupresult(as, ir, ci); /* TValue * */
1193 asm_gencall(as, ci, args);
1194 tmp = ra_releasetmp(as, ASMREF_TMP1);
1195 irkey = IR(ir->op2);
1196 if (irt_isnum(irkey->t)) {
1197 /* For numbers use the constant itself or a spill slot as a TValue. */
1198 if (irref_isk(ir->op2))
1199 emit_loada(as, tmp, ir_knum(irkey));
1200 else
1201 emit_rmro(as, XO_LEA, tmp|REX_64, RID_ESP, ra_spill(as, irkey));
1202 } else {
1203 /* Otherwise use g->tmptv to hold the TValue. */
1204 if (!irref_isk(ir->op2)) {
1205 Reg src = ra_alloc1(as, ir->op2, rset_exclude(RSET_GPR, tmp));
1206 emit_movtomro(as, REX_64IR(irkey, src), tmp, 0);
1207 } else if (!irt_ispri(irkey->t)) {
1208 emit_movmroi(as, tmp, 0, irkey->i);
1209 }
1210 if (!(LJ_64 && irt_islightud(irkey->t)))
1211 emit_movmroi(as, tmp, 4, irt_toitype(irkey->t));
1212 emit_loada(as, tmp, &J2G(as->J)->tmptv);
1213 }
1214}
1215
1216static void asm_uref(ASMState *as, IRIns *ir) 1344static void asm_uref(ASMState *as, IRIns *ir)
1217{ 1345{
1218 Reg dest = ra_dest(as, ir, RSET_GPR); 1346 Reg dest = ra_dest(as, ir, RSET_GPR);
1219 if (irref_isk(ir->op1)) { 1347 if (irref_isk(ir->op1)) {
1220 GCfunc *fn = ir_kfunc(IR(ir->op1)); 1348 GCfunc *fn = ir_kfunc(IR(ir->op1));
1221 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v; 1349 MRef *v = &gcref(fn->l.uvptr[(ir->op2 >> 8)])->uv.v;
1222 emit_rma(as, XO_MOV, dest, v); 1350 emit_rma(as, XO_MOV, dest|REX_GC64, v);
1223 } else { 1351 } else {
1224 Reg uv = ra_scratch(as, RSET_GPR); 1352 Reg uv = ra_scratch(as, RSET_GPR);
1225 Reg func = ra_alloc1(as, ir->op1, RSET_GPR); 1353 Reg func = ra_alloc1(as, ir->op1, RSET_GPR);
1226 if (ir->o == IR_UREFC) { 1354 if (ir->o == IR_UREFC) {
1227 emit_rmro(as, XO_LEA, dest, uv, offsetof(GCupval, tv)); 1355 emit_rmro(as, XO_LEA, dest|REX_GC64, uv, offsetof(GCupval, tv));
1228 asm_guardcc(as, CC_NE); 1356 asm_guardcc(as, CC_NE);
1229 emit_i8(as, 1); 1357 emit_i8(as, 1);
1230 emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed)); 1358 emit_rmro(as, XO_ARITHib, XOg_CMP, uv, offsetof(GCupval, closed));
1231 } else { 1359 } else {
1232 emit_rmro(as, XO_MOV, dest, uv, offsetof(GCupval, v)); 1360 emit_rmro(as, XO_MOV, dest|REX_GC64, uv, offsetof(GCupval, v));
1233 } 1361 }
1234 emit_rmro(as, XO_MOV, uv, func, 1362 emit_rmro(as, XO_MOV, uv|REX_GC64, func,
1235 (int32_t)offsetof(GCfuncL, uvptr) + 4*(int32_t)(ir->op2 >> 8)); 1363 (int32_t)offsetof(GCfuncL, uvptr) +
1364 (int32_t)sizeof(MRef) * (int32_t)(ir->op2 >> 8));
1236 } 1365 }
1237} 1366}
1238 1367
@@ -1250,9 +1379,9 @@ static void asm_strref(ASMState *as, IRIns *ir)
1250 if (as->mrm.base == RID_NONE) 1379 if (as->mrm.base == RID_NONE)
1251 emit_loadi(as, dest, as->mrm.ofs); 1380 emit_loadi(as, dest, as->mrm.ofs);
1252 else if (as->mrm.base == dest && as->mrm.idx == RID_NONE) 1381 else if (as->mrm.base == dest && as->mrm.idx == RID_NONE)
1253 emit_gri(as, XG_ARITHi(XOg_ADD), dest, as->mrm.ofs); 1382 emit_gri(as, XG_ARITHi(XOg_ADD), dest|REX_GC64, as->mrm.ofs);
1254 else 1383 else
1255 emit_mrm(as, XO_LEA, dest, RID_MRM); 1384 emit_mrm(as, XO_LEA, dest|REX_GC64, RID_MRM);
1256} 1385}
1257 1386
1258/* -- Loads and stores ---------------------------------------------------- */ 1387/* -- Loads and stores ---------------------------------------------------- */
@@ -1271,7 +1400,7 @@ static void asm_fxload(ASMState *as, IRIns *ir)
1271 case IRT_U8: xo = XO_MOVZXb; break; 1400 case IRT_U8: xo = XO_MOVZXb; break;
1272 case IRT_I16: xo = XO_MOVSXw; break; 1401 case IRT_I16: xo = XO_MOVSXw; break;
1273 case IRT_U16: xo = XO_MOVZXw; break; 1402 case IRT_U16: xo = XO_MOVZXw; break;
1274 case IRT_NUM: xo = XMM_MOVRM(as); break; 1403 case IRT_NUM: xo = XO_MOVSD; break;
1275 case IRT_FLOAT: xo = XO_MOVSS; break; 1404 case IRT_FLOAT: xo = XO_MOVSS; break;
1276 default: 1405 default:
1277 if (LJ_64 && irt_is64(ir->t)) 1406 if (LJ_64 && irt_is64(ir->t))
@@ -1284,6 +1413,9 @@ static void asm_fxload(ASMState *as, IRIns *ir)
1284 emit_mrm(as, xo, dest, RID_MRM); 1413 emit_mrm(as, xo, dest, RID_MRM);
1285} 1414}
1286 1415
1416#define asm_fload(as, ir) asm_fxload(as, ir)
1417#define asm_xload(as, ir) asm_fxload(as, ir)
1418
1287static void asm_fxstore(ASMState *as, IRIns *ir) 1419static void asm_fxstore(ASMState *as, IRIns *ir)
1288{ 1420{
1289 RegSet allow = RSET_GPR; 1421 RegSet allow = RSET_GPR;
@@ -1318,7 +1450,7 @@ static void asm_fxstore(ASMState *as, IRIns *ir)
1318 case IRT_I16: case IRT_U16: xo = XO_MOVtow; break; 1450 case IRT_I16: case IRT_U16: xo = XO_MOVtow; break;
1319 case IRT_NUM: xo = XO_MOVSDto; break; 1451 case IRT_NUM: xo = XO_MOVSDto; break;
1320 case IRT_FLOAT: xo = XO_MOVSSto; break; 1452 case IRT_FLOAT: xo = XO_MOVSSto; break;
1321#if LJ_64 1453#if LJ_64 && !LJ_GC64
1322 case IRT_LIGHTUD: lua_assert(0); /* NYI: mask 64 bit lightuserdata. */ 1454 case IRT_LIGHTUD: lua_assert(0); /* NYI: mask 64 bit lightuserdata. */
1323#endif 1455#endif
1324 default: 1456 default:
@@ -1347,7 +1479,10 @@ static void asm_fxstore(ASMState *as, IRIns *ir)
1347 } 1479 }
1348} 1480}
1349 1481
1350#if LJ_64 1482#define asm_fstore(as, ir) asm_fxstore(as, ir)
1483#define asm_xstore(as, ir) asm_fxstore(as, ir)
1484
1485#if LJ_64 && !LJ_GC64
1351static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck) 1486static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck)
1352{ 1487{
1353 if (ra_used(ir) || typecheck) { 1488 if (ra_used(ir) || typecheck) {
@@ -1369,9 +1504,12 @@ static Reg asm_load_lightud64(ASMState *as, IRIns *ir, int typecheck)
1369 1504
1370static void asm_ahuvload(ASMState *as, IRIns *ir) 1505static void asm_ahuvload(ASMState *as, IRIns *ir)
1371{ 1506{
1507#if LJ_GC64
1508 Reg tmp = RID_NONE;
1509#endif
1372 lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) || 1510 lua_assert(irt_isnum(ir->t) || irt_ispri(ir->t) || irt_isaddr(ir->t) ||
1373 (LJ_DUALNUM && irt_isint(ir->t))); 1511 (LJ_DUALNUM && irt_isint(ir->t)));
1374#if LJ_64 1512#if LJ_64 && !LJ_GC64
1375 if (irt_islightud(ir->t)) { 1513 if (irt_islightud(ir->t)) {
1376 Reg dest = asm_load_lightud64(as, ir, 1); 1514 Reg dest = asm_load_lightud64(as, ir, 1);
1377 if (ra_hasreg(dest)) { 1515 if (ra_hasreg(dest)) {
@@ -1385,20 +1523,64 @@ static void asm_ahuvload(ASMState *as, IRIns *ir)
1385 RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR; 1523 RegSet allow = irt_isnum(ir->t) ? RSET_FPR : RSET_GPR;
1386 Reg dest = ra_dest(as, ir, allow); 1524 Reg dest = ra_dest(as, ir, allow);
1387 asm_fuseahuref(as, ir->op1, RSET_GPR); 1525 asm_fuseahuref(as, ir->op1, RSET_GPR);
1388 emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XMM_MOVRM(as), dest, RID_MRM); 1526#if LJ_GC64
1527 if (irt_isaddr(ir->t)) {
1528 emit_shifti(as, XOg_SHR|REX_64, dest, 17);
1529 asm_guardcc(as, CC_NE);
1530 emit_i8(as, irt_toitype(ir->t));
1531 emit_rr(as, XO_ARITHi8, XOg_CMP, dest);
1532 emit_i8(as, XI_O16);
1533 if ((as->flags & JIT_F_BMI2)) {
1534 emit_i8(as, 47);
1535 emit_mrm(as, XV_RORX|VEX_64, dest, RID_MRM);
1536 } else {
1537 emit_shifti(as, XOg_ROR|REX_64, dest, 47);
1538 emit_mrm(as, XO_MOV, dest|REX_64, RID_MRM);
1539 }
1540 return;
1541 } else
1542#endif
1543 emit_mrm(as, dest < RID_MAX_GPR ? XO_MOV : XO_MOVSD, dest, RID_MRM);
1389 } else { 1544 } else {
1390 asm_fuseahuref(as, ir->op1, RSET_GPR); 1545 RegSet gpr = RSET_GPR;
1546#if LJ_GC64
1547 if (irt_isaddr(ir->t)) {
1548 tmp = ra_scratch(as, RSET_GPR);
1549 gpr = rset_exclude(gpr, tmp);
1550 }
1551#endif
1552 asm_fuseahuref(as, ir->op1, gpr);
1391 } 1553 }
1392 /* Always do the type check, even if the load result is unused. */ 1554 /* Always do the type check, even if the load result is unused. */
1393 as->mrm.ofs += 4; 1555 as->mrm.ofs += 4;
1394 asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE); 1556 asm_guardcc(as, irt_isnum(ir->t) ? CC_AE : CC_NE);
1395 if (LJ_64 && irt_type(ir->t) >= IRT_NUM) { 1557 if (LJ_64 && irt_type(ir->t) >= IRT_NUM) {
1396 lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t)); 1558 lua_assert(irt_isinteger(ir->t) || irt_isnum(ir->t));
1559#if LJ_GC64
1560 emit_u32(as, LJ_TISNUM << 15);
1561#else
1397 emit_u32(as, LJ_TISNUM); 1562 emit_u32(as, LJ_TISNUM);
1563#endif
1398 emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM); 1564 emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM);
1565#if LJ_GC64
1566 } else if (irt_isaddr(ir->t)) {
1567 as->mrm.ofs -= 4;
1568 emit_i8(as, irt_toitype(ir->t));
1569 emit_mrm(as, XO_ARITHi8, XOg_CMP, tmp);
1570 emit_shifti(as, XOg_SAR|REX_64, tmp, 47);
1571 emit_mrm(as, XO_MOV, tmp|REX_64, RID_MRM);
1572 } else if (irt_isnil(ir->t)) {
1573 as->mrm.ofs -= 4;
1574 emit_i8(as, -1);
1575 emit_mrm(as, XO_ARITHi8, XOg_CMP|REX_64, RID_MRM);
1576 } else {
1577 emit_u32(as, (irt_toitype(ir->t) << 15) | 0x7fff);
1578 emit_mrm(as, XO_ARITHi, XOg_CMP, RID_MRM);
1579#else
1399 } else { 1580 } else {
1400 emit_i8(as, irt_toitype(ir->t)); 1581 emit_i8(as, irt_toitype(ir->t));
1401 emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM); 1582 emit_mrm(as, XO_ARITHi8, XOg_CMP, RID_MRM);
1583#endif
1402 } 1584 }
1403} 1585}
1404 1586
@@ -1410,12 +1592,28 @@ static void asm_ahustore(ASMState *as, IRIns *ir)
1410 Reg src = ra_alloc1(as, ir->op2, RSET_FPR); 1592 Reg src = ra_alloc1(as, ir->op2, RSET_FPR);
1411 asm_fuseahuref(as, ir->op1, RSET_GPR); 1593 asm_fuseahuref(as, ir->op1, RSET_GPR);
1412 emit_mrm(as, XO_MOVSDto, src, RID_MRM); 1594 emit_mrm(as, XO_MOVSDto, src, RID_MRM);
1413#if LJ_64 1595#if LJ_64 && !LJ_GC64
1414 } else if (irt_islightud(ir->t)) { 1596 } else if (irt_islightud(ir->t)) {
1415 Reg src = ra_alloc1(as, ir->op2, RSET_GPR); 1597 Reg src = ra_alloc1(as, ir->op2, RSET_GPR);
1416 asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src)); 1598 asm_fuseahuref(as, ir->op1, rset_exclude(RSET_GPR, src));
1417 emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM); 1599 emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM);
1418#endif 1600#endif
1601#if LJ_GC64
1602 } else if (irref_isk(ir->op2)) {
1603 TValue k;
1604 lj_ir_kvalue(as->J->L, &k, IR(ir->op2));
1605 asm_fuseahuref(as, ir->op1, RSET_GPR);
1606 if (tvisnil(&k)) {
1607 emit_i32(as, -1);
1608 emit_mrm(as, XO_MOVmi, REX_64, RID_MRM);
1609 } else {
1610 emit_u32(as, k.u32.lo);
1611 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1612 as->mrm.ofs += 4;
1613 emit_u32(as, k.u32.hi);
1614 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1615 }
1616#endif
1419 } else { 1617 } else {
1420 IRIns *irr = IR(ir->op2); 1618 IRIns *irr = IR(ir->op2);
1421 RegSet allow = RSET_GPR; 1619 RegSet allow = RSET_GPR;
@@ -1426,6 +1624,17 @@ static void asm_ahustore(ASMState *as, IRIns *ir)
1426 } 1624 }
1427 asm_fuseahuref(as, ir->op1, allow); 1625 asm_fuseahuref(as, ir->op1, allow);
1428 if (ra_hasreg(src)) { 1626 if (ra_hasreg(src)) {
1627#if LJ_GC64
1628 if (!(LJ_DUALNUM && irt_isinteger(ir->t))) {
1629 /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */
1630 as->mrm.ofs += 4;
1631 emit_u32(as, irt_toitype(ir->t) << 15);
1632 emit_mrm(as, XO_ARITHi, XOg_OR, RID_MRM);
1633 as->mrm.ofs -= 4;
1634 emit_mrm(as, XO_MOVto, src|REX_64, RID_MRM);
1635 return;
1636 }
1637#endif
1429 emit_mrm(as, XO_MOVto, src, RID_MRM); 1638 emit_mrm(as, XO_MOVto, src, RID_MRM);
1430 } else if (!irt_ispri(irr->t)) { 1639 } else if (!irt_ispri(irr->t)) {
1431 lua_assert(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t))); 1640 lua_assert(irt_isaddr(ir->t) || (LJ_DUALNUM && irt_isinteger(ir->t)));
@@ -1433,14 +1642,20 @@ static void asm_ahustore(ASMState *as, IRIns *ir)
1433 emit_mrm(as, XO_MOVmi, 0, RID_MRM); 1642 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1434 } 1643 }
1435 as->mrm.ofs += 4; 1644 as->mrm.ofs += 4;
1645#if LJ_GC64
1646 lua_assert(LJ_DUALNUM && irt_isinteger(ir->t));
1647 emit_i32(as, LJ_TNUMX << 15);
1648#else
1436 emit_i32(as, (int32_t)irt_toitype(ir->t)); 1649 emit_i32(as, (int32_t)irt_toitype(ir->t));
1650#endif
1437 emit_mrm(as, XO_MOVmi, 0, RID_MRM); 1651 emit_mrm(as, XO_MOVmi, 0, RID_MRM);
1438 } 1652 }
1439} 1653}
1440 1654
1441static void asm_sload(ASMState *as, IRIns *ir) 1655static void asm_sload(ASMState *as, IRIns *ir)
1442{ 1656{
1443 int32_t ofs = 8*((int32_t)ir->op1-1) + ((ir->op2 & IRSLOAD_FRAME) ? 4 : 0); 1657 int32_t ofs = 8*((int32_t)ir->op1-1-LJ_FR2) +
1658 (!LJ_FR2 && (ir->op2 & IRSLOAD_FRAME) ? 4 : 0);
1444 IRType1 t = ir->t; 1659 IRType1 t = ir->t;
1445 Reg base; 1660 Reg base;
1446 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */ 1661 lua_assert(!(ir->op2 & IRSLOAD_PARENT)); /* Handled by asm_head_side(). */
@@ -1451,9 +1666,9 @@ static void asm_sload(ASMState *as, IRIns *ir)
1451 Reg left = ra_scratch(as, RSET_FPR); 1666 Reg left = ra_scratch(as, RSET_FPR);
1452 asm_tointg(as, ir, left); /* Frees dest reg. Do this before base alloc. */ 1667 asm_tointg(as, ir, left); /* Frees dest reg. Do this before base alloc. */
1453 base = ra_alloc1(as, REF_BASE, RSET_GPR); 1668 base = ra_alloc1(as, REF_BASE, RSET_GPR);
1454 emit_rmro(as, XMM_MOVRM(as), left, base, ofs); 1669 emit_rmro(as, XO_MOVSD, left, base, ofs);
1455 t.irt = IRT_NUM; /* Continue with a regular number type check. */ 1670 t.irt = IRT_NUM; /* Continue with a regular number type check. */
1456#if LJ_64 1671#if LJ_64 && !LJ_GC64
1457 } else if (irt_islightud(t)) { 1672 } else if (irt_islightud(t)) {
1458 Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK)); 1673 Reg dest = asm_load_lightud64(as, ir, (ir->op2 & IRSLOAD_TYPECHECK));
1459 if (ra_hasreg(dest)) { 1674 if (ra_hasreg(dest)) {
@@ -1469,11 +1684,39 @@ static void asm_sload(ASMState *as, IRIns *ir)
1469 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t)); 1684 lua_assert(irt_isnum(t) || irt_isint(t) || irt_isaddr(t));
1470 if ((ir->op2 & IRSLOAD_CONVERT)) { 1685 if ((ir->op2 & IRSLOAD_CONVERT)) {
1471 t.irt = irt_isint(t) ? IRT_NUM : IRT_INT; /* Check for original type. */ 1686 t.irt = irt_isint(t) ? IRT_NUM : IRT_INT; /* Check for original type. */
1472 emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTSD2SI, dest, base, ofs); 1687 emit_rmro(as, irt_isint(t) ? XO_CVTSI2SD : XO_CVTTSD2SI, dest, base, ofs);
1473 } else if (irt_isnum(t)) {
1474 emit_rmro(as, XMM_MOVRM(as), dest, base, ofs);
1475 } else { 1688 } else {
1476 emit_rmro(as, XO_MOV, dest, base, ofs); 1689#if LJ_GC64
1690 if (irt_isaddr(t)) {
1691 /* LJ_GC64 type check + tag removal without BMI2 and with BMI2:
1692 **
1693 ** mov r64, [addr] rorx r64, [addr], 47
1694 ** ror r64, 47
1695 ** cmp r16, itype cmp r16, itype
1696 ** jne ->exit jne ->exit
1697 ** shr r64, 16 shr r64, 16
1698 */
1699 emit_shifti(as, XOg_SHR|REX_64, dest, 17);
1700 if ((ir->op2 & IRSLOAD_TYPECHECK)) {
1701 asm_guardcc(as, CC_NE);
1702 emit_i8(as, irt_toitype(t));
1703 emit_rr(as, XO_ARITHi8, XOg_CMP, dest);
1704 emit_i8(as, XI_O16);
1705 }
1706 if ((as->flags & JIT_F_BMI2)) {
1707 emit_i8(as, 47);
1708 emit_rmro(as, XV_RORX|VEX_64, dest, base, ofs);
1709 } else {
1710 if ((ir->op2 & IRSLOAD_TYPECHECK))
1711 emit_shifti(as, XOg_ROR|REX_64, dest, 47);
1712 else
1713 emit_shifti(as, XOg_SHL|REX_64, dest, 17);
1714 emit_rmro(as, XO_MOV, dest|REX_64, base, ofs);
1715 }
1716 return;
1717 } else
1718#endif
1719 emit_rmro(as, irt_isnum(t) ? XO_MOVSD : XO_MOV, dest, base, ofs);
1477 } 1720 }
1478 } else { 1721 } else {
1479 if (!(ir->op2 & IRSLOAD_TYPECHECK)) 1722 if (!(ir->op2 & IRSLOAD_TYPECHECK))
@@ -1485,11 +1728,42 @@ static void asm_sload(ASMState *as, IRIns *ir)
1485 asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE); 1728 asm_guardcc(as, irt_isnum(t) ? CC_AE : CC_NE);
1486 if (LJ_64 && irt_type(t) >= IRT_NUM) { 1729 if (LJ_64 && irt_type(t) >= IRT_NUM) {
1487 lua_assert(irt_isinteger(t) || irt_isnum(t)); 1730 lua_assert(irt_isinteger(t) || irt_isnum(t));
1731#if LJ_GC64
1732 emit_u32(as, LJ_TISNUM << 15);
1733#else
1488 emit_u32(as, LJ_TISNUM); 1734 emit_u32(as, LJ_TISNUM);
1735#endif
1736 emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4);
1737#if LJ_GC64
1738 } else if (irt_isnil(t)) {
1739 /* LJ_GC64 type check for nil:
1740 **
1741 ** cmp qword [addr], -1
1742 ** jne ->exit
1743 */
1744 emit_i8(as, -1);
1745 emit_rmro(as, XO_ARITHi8, XOg_CMP|REX_64, base, ofs);
1746 } else if (irt_ispri(t)) {
1747 emit_u32(as, (irt_toitype(t) << 15) | 0x7fff);
1489 emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4); 1748 emit_rmro(as, XO_ARITHi, XOg_CMP, base, ofs+4);
1490 } else { 1749 } else {
1750 /* LJ_GC64 type check only:
1751 **
1752 ** mov r64, [addr]
1753 ** sar r64, 47
1754 ** cmp r32, itype
1755 ** jne ->exit
1756 */
1757 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, base));
1758 emit_i8(as, irt_toitype(t));
1759 emit_rr(as, XO_ARITHi8, XOg_CMP, tmp);
1760 emit_shifti(as, XOg_SAR|REX_64, tmp, 47);
1761 emit_rmro(as, XO_MOV, tmp|REX_64, base, ofs+4);
1762#else
1763 } else {
1491 emit_i8(as, irt_toitype(t)); 1764 emit_i8(as, irt_toitype(t));
1492 emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4); 1765 emit_rmro(as, XO_ARITHi8, XOg_CMP, base, ofs+4);
1766#endif
1493 } 1767 }
1494 } 1768 }
1495} 1769}
@@ -1500,15 +1774,13 @@ static void asm_sload(ASMState *as, IRIns *ir)
1500static void asm_cnew(ASMState *as, IRIns *ir) 1774static void asm_cnew(ASMState *as, IRIns *ir)
1501{ 1775{
1502 CTState *cts = ctype_ctsG(J2G(as->J)); 1776 CTState *cts = ctype_ctsG(J2G(as->J));
1503 CTypeID ctypeid = (CTypeID)IR(ir->op1)->i; 1777 CTypeID id = (CTypeID)IR(ir->op1)->i;
1504 CTSize sz = (ir->o == IR_CNEWI || ir->op2 == REF_NIL) ? 1778 CTSize sz;
1505 lj_ctype_size(cts, ctypeid) : (CTSize)IR(ir->op2)->i; 1779 CTInfo info = lj_ctype_info(cts, id, &sz);
1506 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco]; 1780 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_mem_newgco];
1507 IRRef args[2]; 1781 IRRef args[4];
1508 lua_assert(sz != CTSIZE_INVALID); 1782 lua_assert(sz != CTSIZE_INVALID || (ir->o == IR_CNEW && ir->op2 != REF_NIL));
1509 1783
1510 args[0] = ASMREF_L; /* lua_State *L */
1511 args[1] = ASMREF_TMP1; /* MSize size */
1512 as->gcsteps++; 1784 as->gcsteps++;
1513 asm_setupresult(as, ir, ci); /* GCcdata * */ 1785 asm_setupresult(as, ir, ci); /* GCcdata * */
1514 1786
@@ -1551,15 +1823,26 @@ static void asm_cnew(ASMState *as, IRIns *ir)
1551 } while (1); 1823 } while (1);
1552#endif 1824#endif
1553 lua_assert(sz == 4 || sz == 8); 1825 lua_assert(sz == 4 || sz == 8);
1826 } else if (ir->op2 != REF_NIL) { /* Create VLA/VLS/aligned cdata. */
1827 ci = &lj_ir_callinfo[IRCALL_lj_cdata_newv];
1828 args[0] = ASMREF_L; /* lua_State *L */
1829 args[1] = ir->op1; /* CTypeID id */
1830 args[2] = ir->op2; /* CTSize sz */
1831 args[3] = ASMREF_TMP1; /* CTSize align */
1832 asm_gencall(as, ci, args);
1833 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)ctype_align(info));
1834 return;
1554 } 1835 }
1555 1836
1556 /* Combine initialization of marked, gct and ctypeid. */ 1837 /* Combine initialization of marked, gct and ctypeid. */
1557 emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked)); 1838 emit_movtomro(as, RID_ECX, RID_RET, offsetof(GCcdata, marked));
1558 emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX, 1839 emit_gri(as, XG_ARITHi(XOg_OR), RID_ECX,
1559 (int32_t)((~LJ_TCDATA<<8)+(ctypeid<<16))); 1840 (int32_t)((~LJ_TCDATA<<8)+(id<<16)));
1560 emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES); 1841 emit_gri(as, XG_ARITHi(XOg_AND), RID_ECX, LJ_GC_WHITES);
1561 emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite); 1842 emit_opgl(as, XO_MOVZXb, RID_ECX, gc.currentwhite);
1562 1843
1844 args[0] = ASMREF_L; /* lua_State *L */
1845 args[1] = ASMREF_TMP1; /* MSize size */
1563 asm_gencall(as, ci, args); 1846 asm_gencall(as, ci, args);
1564 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata))); 1847 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP1), (int32_t)(sz+sizeof(GCcdata)));
1565} 1848}
@@ -1574,7 +1857,7 @@ static void asm_tbar(ASMState *as, IRIns *ir)
1574 Reg tab = ra_alloc1(as, ir->op1, RSET_GPR); 1857 Reg tab = ra_alloc1(as, ir->op1, RSET_GPR);
1575 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab)); 1858 Reg tmp = ra_scratch(as, rset_exclude(RSET_GPR, tab));
1576 MCLabel l_end = emit_label(as); 1859 MCLabel l_end = emit_label(as);
1577 emit_movtomro(as, tmp, tab, offsetof(GCtab, gclist)); 1860 emit_movtomro(as, tmp|REX_GC64, tab, offsetof(GCtab, gclist));
1578 emit_setgl(as, tab, gc.grayagain); 1861 emit_setgl(as, tab, gc.grayagain);
1579 emit_getgl(as, tmp, gc.grayagain); 1862 emit_getgl(as, tmp, gc.grayagain);
1580 emit_i8(as, ~LJ_GC_BLACK); 1863 emit_i8(as, ~LJ_GC_BLACK);
@@ -1637,36 +1920,9 @@ static void asm_x87load(ASMState *as, IRRef ref)
1637 } 1920 }
1638} 1921}
1639 1922
1640/* Try to rejoin pow from EXP2, MUL and LOG2 (if still unsplit). */
1641static int fpmjoin_pow(ASMState *as, IRIns *ir)
1642{
1643 IRIns *irp = IR(ir->op1);
1644 if (irp == ir-1 && irp->o == IR_MUL && !ra_used(irp)) {
1645 IRIns *irpp = IR(irp->op1);
1646 if (irpp == ir-2 && irpp->o == IR_FPMATH &&
1647 irpp->op2 == IRFPM_LOG2 && !ra_used(irpp)) {
1648 /* The modified regs must match with the *.dasc implementation. */
1649 RegSet drop = RSET_RANGE(RID_XMM0, RID_XMM2+1)|RID2RSET(RID_EAX);
1650 IRIns *irx;
1651 if (ra_hasreg(ir->r))
1652 rset_clear(drop, ir->r); /* Dest reg handled below. */
1653 ra_evictset(as, drop);
1654 ra_destreg(as, ir, RID_XMM0);
1655 emit_call(as, lj_vm_pow_sse);
1656 irx = IR(irpp->op1);
1657 if (ra_noreg(irx->r) && ra_gethint(irx->r) == RID_XMM1)
1658 irx->r = RID_INIT; /* Avoid allocating xmm1 for x. */
1659 ra_left(as, RID_XMM0, irpp->op1);
1660 ra_left(as, RID_XMM1, irp->op2);
1661 return 1;
1662 }
1663 }
1664 return 0;
1665}
1666
1667static void asm_fpmath(ASMState *as, IRIns *ir) 1923static void asm_fpmath(ASMState *as, IRIns *ir)
1668{ 1924{
1669 IRFPMathOp fpm = ir->o == IR_FPMATH ? (IRFPMathOp)ir->op2 : IRFPM_OTHER; 1925 IRFPMathOp fpm = (IRFPMathOp)ir->op2;
1670 if (fpm == IRFPM_SQRT) { 1926 if (fpm == IRFPM_SQRT) {
1671 Reg dest = ra_dest(as, ir, RSET_FPR); 1927 Reg dest = ra_dest(as, ir, RSET_FPR);
1672 Reg left = asm_fuseload(as, ir->op1, RSET_FPR); 1928 Reg left = asm_fuseload(as, ir->op1, RSET_FPR);
@@ -1697,51 +1953,29 @@ static void asm_fpmath(ASMState *as, IRIns *ir)
1697 fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse); 1953 fpm == IRFPM_CEIL ? lj_vm_ceil_sse : lj_vm_trunc_sse);
1698 ra_left(as, RID_XMM0, ir->op1); 1954 ra_left(as, RID_XMM0, ir->op1);
1699 } 1955 }
1700 } else if (fpm == IRFPM_EXP2 && fpmjoin_pow(as, ir)) { 1956 } else if (fpm == IRFPM_EXP2 && asm_fpjoin_pow(as, ir)) {
1701 /* Rejoined to pow(). */ 1957 /* Rejoined to pow(). */
1702 } else { /* Handle x87 ops. */ 1958 } else {
1703 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */ 1959 asm_callid(as, ir, IRCALL_lj_vm_floor + fpm);
1704 Reg dest = ir->r; 1960 }
1705 if (ra_hasreg(dest)) { 1961}
1706 ra_free(as, dest); 1962
1707 ra_modified(as, dest); 1963#define asm_atan2(as, ir) asm_callid(as, ir, IRCALL_atan2)
1708 emit_rmro(as, XMM_MOVRM(as), dest, RID_ESP, ofs); 1964
1709 } 1965static void asm_ldexp(ASMState *as, IRIns *ir)
1710 emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs); 1966{
1711 switch (fpm) { /* st0 = lj_vm_*(st0) */ 1967 int32_t ofs = sps_scale(ir->s); /* Use spill slot or temp slots. */
1712 case IRFPM_EXP: emit_call(as, lj_vm_exp_x87); break; 1968 Reg dest = ir->r;
1713 case IRFPM_EXP2: emit_call(as, lj_vm_exp2_x87); break; 1969 if (ra_hasreg(dest)) {
1714 case IRFPM_SIN: emit_x87op(as, XI_FSIN); break; 1970 ra_free(as, dest);
1715 case IRFPM_COS: emit_x87op(as, XI_FCOS); break; 1971 ra_modified(as, dest);
1716 case IRFPM_TAN: emit_x87op(as, XI_FPOP); emit_x87op(as, XI_FPTAN); break; 1972 emit_rmro(as, XO_MOVSD, dest, RID_ESP, ofs);
1717 case IRFPM_LOG: case IRFPM_LOG2: case IRFPM_LOG10:
1718 /* Note: the use of fyl2xp1 would be pointless here. When computing
1719 ** log(1.0+eps) the precision is already lost after 1.0 is added.
1720 ** Subtracting 1.0 won't recover it. OTOH math.log1p would make sense.
1721 */
1722 emit_x87op(as, XI_FYL2X); break;
1723 case IRFPM_OTHER:
1724 switch (ir->o) {
1725 case IR_ATAN2:
1726 emit_x87op(as, XI_FPATAN); asm_x87load(as, ir->op2); break;
1727 case IR_LDEXP:
1728 emit_x87op(as, XI_FPOP1); emit_x87op(as, XI_FSCALE); break;
1729 default: lua_assert(0); break;
1730 }
1731 break;
1732 default: lua_assert(0); break;
1733 }
1734 asm_x87load(as, ir->op1);
1735 switch (fpm) {
1736 case IRFPM_LOG: emit_x87op(as, XI_FLDLN2); break;
1737 case IRFPM_LOG2: emit_x87op(as, XI_FLD1); break;
1738 case IRFPM_LOG10: emit_x87op(as, XI_FLDLG2); break;
1739 case IRFPM_OTHER:
1740 if (ir->o == IR_LDEXP) asm_x87load(as, ir->op2);
1741 break;
1742 default: break;
1743 }
1744 } 1973 }
1974 emit_rmro(as, XO_FSTPq, XOg_FSTPq, RID_ESP, ofs);
1975 emit_x87op(as, XI_FPOP1);
1976 emit_x87op(as, XI_FSCALE);
1977 asm_x87load(as, ir->op1);
1978 asm_x87load(as, ir->op2);
1745} 1979}
1746 1980
1747static void asm_fppowi(ASMState *as, IRIns *ir) 1981static void asm_fppowi(ASMState *as, IRIns *ir)
@@ -1757,26 +1991,15 @@ static void asm_fppowi(ASMState *as, IRIns *ir)
1757 ra_left(as, RID_EAX, ir->op2); 1991 ra_left(as, RID_EAX, ir->op2);
1758} 1992}
1759 1993
1760#if LJ_64 && LJ_HASFFI 1994static void asm_pow(ASMState *as, IRIns *ir)
1761static void asm_arith64(ASMState *as, IRIns *ir, IRCallID id)
1762{ 1995{
1763 const CCallInfo *ci = &lj_ir_callinfo[id]; 1996#if LJ_64 && LJ_HASFFI
1764 IRRef args[2]; 1997 if (!irt_isnum(ir->t))
1765 args[0] = ir->op1; 1998 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
1766 args[1] = ir->op2; 1999 IRCALL_lj_carith_powu64);
1767 asm_setupresult(as, ir, ci); 2000 else
1768 asm_gencall(as, ci, args);
1769}
1770#endif 2001#endif
1771 2002 asm_fppowi(as, ir);
1772static void asm_intmod(ASMState *as, IRIns *ir)
1773{
1774 const CCallInfo *ci = &lj_ir_callinfo[IRCALL_lj_vm_modi];
1775 IRRef args[2];
1776 args[0] = ir->op1;
1777 args[1] = ir->op2;
1778 asm_setupresult(as, ir, ci);
1779 asm_gencall(as, ci, args);
1780} 2003}
1781 2004
1782static int asm_swapops(ASMState *as, IRIns *ir) 2005static int asm_swapops(ASMState *as, IRIns *ir)
@@ -1959,6 +2182,44 @@ static void asm_add(ASMState *as, IRIns *ir)
1959 asm_intarith(as, ir, XOg_ADD); 2182 asm_intarith(as, ir, XOg_ADD);
1960} 2183}
1961 2184
2185static void asm_sub(ASMState *as, IRIns *ir)
2186{
2187 if (irt_isnum(ir->t))
2188 asm_fparith(as, ir, XO_SUBSD);
2189 else /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */
2190 asm_intarith(as, ir, XOg_SUB);
2191}
2192
2193static void asm_mul(ASMState *as, IRIns *ir)
2194{
2195 if (irt_isnum(ir->t))
2196 asm_fparith(as, ir, XO_MULSD);
2197 else
2198 asm_intarith(as, ir, XOg_X_IMUL);
2199}
2200
2201static void asm_div(ASMState *as, IRIns *ir)
2202{
2203#if LJ_64 && LJ_HASFFI
2204 if (!irt_isnum(ir->t))
2205 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
2206 IRCALL_lj_carith_divu64);
2207 else
2208#endif
2209 asm_fparith(as, ir, XO_DIVSD);
2210}
2211
2212static void asm_mod(ASMState *as, IRIns *ir)
2213{
2214#if LJ_64 && LJ_HASFFI
2215 if (!irt_isint(ir->t))
2216 asm_callid(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
2217 IRCALL_lj_carith_modu64);
2218 else
2219#endif
2220 asm_callid(as, ir, IRCALL_lj_vm_modi);
2221}
2222
1962static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg) 2223static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg)
1963{ 2224{
1964 Reg dest = ra_dest(as, ir, RSET_GPR); 2225 Reg dest = ra_dest(as, ir, RSET_GPR);
@@ -1966,7 +2227,17 @@ static void asm_neg_not(ASMState *as, IRIns *ir, x86Group3 xg)
1966 ra_left(as, dest, ir->op1); 2227 ra_left(as, dest, ir->op1);
1967} 2228}
1968 2229
1969static void asm_min_max(ASMState *as, IRIns *ir, int cc) 2230static void asm_neg(ASMState *as, IRIns *ir)
2231{
2232 if (irt_isnum(ir->t))
2233 asm_fparith(as, ir, XO_XORPS);
2234 else
2235 asm_neg_not(as, ir, XOg_NEG);
2236}
2237
2238#define asm_abs(as, ir) asm_fparith(as, ir, XO_ANDPS)
2239
2240static void asm_intmin_max(ASMState *as, IRIns *ir, int cc)
1970{ 2241{
1971 Reg right, dest = ra_dest(as, ir, RSET_GPR); 2242 Reg right, dest = ra_dest(as, ir, RSET_GPR);
1972 IRRef lref = ir->op1, rref = ir->op2; 2243 IRRef lref = ir->op1, rref = ir->op2;
@@ -1977,7 +2248,30 @@ static void asm_min_max(ASMState *as, IRIns *ir, int cc)
1977 ra_left(as, dest, lref); 2248 ra_left(as, dest, lref);
1978} 2249}
1979 2250
1980static void asm_bitswap(ASMState *as, IRIns *ir) 2251static void asm_min(ASMState *as, IRIns *ir)
2252{
2253 if (irt_isnum(ir->t))
2254 asm_fparith(as, ir, XO_MINSD);
2255 else
2256 asm_intmin_max(as, ir, CC_G);
2257}
2258
2259static void asm_max(ASMState *as, IRIns *ir)
2260{
2261 if (irt_isnum(ir->t))
2262 asm_fparith(as, ir, XO_MAXSD);
2263 else
2264 asm_intmin_max(as, ir, CC_L);
2265}
2266
2267/* Note: don't use LEA for overflow-checking arithmetic! */
2268#define asm_addov(as, ir) asm_intarith(as, ir, XOg_ADD)
2269#define asm_subov(as, ir) asm_intarith(as, ir, XOg_SUB)
2270#define asm_mulov(as, ir) asm_intarith(as, ir, XOg_X_IMUL)
2271
2272#define asm_bnot(as, ir) asm_neg_not(as, ir, XOg_NOT)
2273
2274static void asm_bswap(ASMState *as, IRIns *ir)
1981{ 2275{
1982 Reg dest = ra_dest(as, ir, RSET_GPR); 2276 Reg dest = ra_dest(as, ir, RSET_GPR);
1983 as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24), 2277 as->mcp = emit_op(XO_BSWAP + ((dest&7) << 24),
@@ -1985,7 +2279,11 @@ static void asm_bitswap(ASMState *as, IRIns *ir)
1985 ra_left(as, dest, ir->op1); 2279 ra_left(as, dest, ir->op1);
1986} 2280}
1987 2281
1988static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs) 2282#define asm_band(as, ir) asm_intarith(as, ir, XOg_AND)
2283#define asm_bor(as, ir) asm_intarith(as, ir, XOg_OR)
2284#define asm_bxor(as, ir) asm_intarith(as, ir, XOg_XOR)
2285
2286static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs, x86Op xv)
1989{ 2287{
1990 IRRef rref = ir->op2; 2288 IRRef rref = ir->op2;
1991 IRIns *irr = IR(rref); 2289 IRIns *irr = IR(rref);
@@ -1994,11 +2292,27 @@ static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs)
1994 int shift; 2292 int shift;
1995 dest = ra_dest(as, ir, RSET_GPR); 2293 dest = ra_dest(as, ir, RSET_GPR);
1996 shift = irr->i & (irt_is64(ir->t) ? 63 : 31); 2294 shift = irr->i & (irt_is64(ir->t) ? 63 : 31);
2295 if (!xv && shift && (as->flags & JIT_F_BMI2)) {
2296 Reg left = asm_fuseloadm(as, ir->op1, RSET_GPR, irt_is64(ir->t));
2297 if (left != dest) { /* BMI2 rotate right by constant. */
2298 emit_i8(as, xs == XOg_ROL ? -shift : shift);
2299 emit_mrm(as, VEX_64IR(ir, XV_RORX), dest, left);
2300 return;
2301 }
2302 }
1997 switch (shift) { 2303 switch (shift) {
1998 case 0: break; 2304 case 0: break;
1999 case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break; 2305 case 1: emit_rr(as, XO_SHIFT1, REX_64IR(ir, xs), dest); break;
2000 default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break; 2306 default: emit_shifti(as, REX_64IR(ir, xs), dest, shift); break;
2001 } 2307 }
2308 } else if ((as->flags & JIT_F_BMI2) && xv) { /* BMI2 variable shifts. */
2309 Reg left, right;
2310 dest = ra_dest(as, ir, RSET_GPR);
2311 right = ra_alloc1(as, rref, RSET_GPR);
2312 left = asm_fuseloadm(as, ir->op1, rset_exclude(RSET_GPR, right),
2313 irt_is64(ir->t));
2314 emit_mrm(as, VEX_64IR(ir, xv) ^ (right << 19), dest, left);
2315 return;
2002 } else { /* Variable shifts implicitly use register cl (i.e. ecx). */ 2316 } else { /* Variable shifts implicitly use register cl (i.e. ecx). */
2003 Reg right; 2317 Reg right;
2004 dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX)); 2318 dest = ra_dest(as, ir, rset_exclude(RSET_GPR, RID_ECX));
@@ -2024,6 +2338,12 @@ static void asm_bitshift(ASMState *as, IRIns *ir, x86Shift xs)
2024 */ 2338 */
2025} 2339}
2026 2340
2341#define asm_bshl(as, ir) asm_bitshift(as, ir, XOg_SHL, XV_SHLX)
2342#define asm_bshr(as, ir) asm_bitshift(as, ir, XOg_SHR, XV_SHRX)
2343#define asm_bsar(as, ir) asm_bitshift(as, ir, XOg_SAR, XV_SARX)
2344#define asm_brol(as, ir) asm_bitshift(as, ir, XOg_ROL, 0)
2345#define asm_bror(as, ir) asm_bitshift(as, ir, XOg_ROR, 0)
2346
2027/* -- Comparisons --------------------------------------------------------- */ 2347/* -- Comparisons --------------------------------------------------------- */
2028 2348
2029/* Virtual flags for unordered FP comparisons. */ 2349/* Virtual flags for unordered FP comparisons. */
@@ -2050,8 +2370,9 @@ static const uint16_t asm_compmap[IR_ABC+1] = {
2050}; 2370};
2051 2371
2052/* FP and integer comparisons. */ 2372/* FP and integer comparisons. */
2053static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc) 2373static void asm_comp(ASMState *as, IRIns *ir)
2054{ 2374{
2375 uint32_t cc = asm_compmap[ir->o];
2055 if (irt_isnum(ir->t)) { 2376 if (irt_isnum(ir->t)) {
2056 IRRef lref = ir->op1; 2377 IRRef lref = ir->op1;
2057 IRRef rref = ir->op2; 2378 IRRef rref = ir->op2;
@@ -2072,7 +2393,6 @@ static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc)
2072 cc ^= (VCC_PS|(5<<4)); /* A <-> B, AE <-> BE, PS <-> none */ 2393 cc ^= (VCC_PS|(5<<4)); /* A <-> B, AE <-> BE, PS <-> none */
2073 } 2394 }
2074 left = ra_alloc1(as, lref, RSET_FPR); 2395 left = ra_alloc1(as, lref, RSET_FPR);
2075 right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left));
2076 l_around = emit_label(as); 2396 l_around = emit_label(as);
2077 asm_guardcc(as, cc >> 4); 2397 asm_guardcc(as, cc >> 4);
2078 if (cc & VCC_P) { /* Extra CC_P branch required? */ 2398 if (cc & VCC_P) { /* Extra CC_P branch required? */
@@ -2089,6 +2409,7 @@ static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc)
2089 emit_jcc(as, CC_P, as->mcp); 2409 emit_jcc(as, CC_P, as->mcp);
2090 } 2410 }
2091 } 2411 }
2412 right = asm_fuseload(as, rref, rset_exclude(RSET_FPR, left));
2092 emit_mrm(as, XO_UCOMISD, left, right); 2413 emit_mrm(as, XO_UCOMISD, left, right);
2093 } else { 2414 } else {
2094 IRRef lref = ir->op1, rref = ir->op2; 2415 IRRef lref = ir->op1, rref = ir->op2;
@@ -2206,6 +2527,8 @@ static void asm_comp(ASMState *as, IRIns *ir, uint32_t cc)
2206 } 2527 }
2207} 2528}
2208 2529
2530#define asm_equal(as, ir) asm_comp(as, ir)
2531
2209#if LJ_32 && LJ_HASFFI 2532#if LJ_32 && LJ_HASFFI
2210/* 64 bit integer comparisons in 32 bit mode. */ 2533/* 64 bit integer comparisons in 32 bit mode. */
2211static void asm_comp_int64(ASMState *as, IRIns *ir) 2534static void asm_comp_int64(ASMState *as, IRIns *ir)
@@ -2288,13 +2611,9 @@ static void asm_hiop(ASMState *as, IRIns *ir)
2288 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */ 2611 int uselo = ra_used(ir-1), usehi = ra_used(ir); /* Loword/hiword used? */
2289 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1; 2612 if (LJ_UNLIKELY(!(as->flags & JIT_F_OPT_DCE))) uselo = usehi = 1;
2290 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */ 2613 if ((ir-1)->o == IR_CONV) { /* Conversions to/from 64 bit. */
2291 if (usehi || uselo) {
2292 if (irt_isfp(ir->t))
2293 asm_conv_fp_int64(as, ir);
2294 else
2295 asm_conv_int64_fp(as, ir);
2296 }
2297 as->curins--; /* Always skip the CONV. */ 2614 as->curins--; /* Always skip the CONV. */
2615 if (usehi || uselo)
2616 asm_conv64(as, ir);
2298 return; 2617 return;
2299 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */ 2618 } else if ((ir-1)->o <= IR_NE) { /* 64 bit integer comparisons. ORDER IR. */
2300 asm_comp_int64(as, ir); 2619 asm_comp_int64(as, ir);
@@ -2343,6 +2662,16 @@ static void asm_hiop(ASMState *as, IRIns *ir)
2343#endif 2662#endif
2344} 2663}
2345 2664
2665/* -- Profiling ----------------------------------------------------------- */
2666
2667static void asm_prof(ASMState *as, IRIns *ir)
2668{
2669 UNUSED(ir);
2670 asm_guardcc(as, CC_NE);
2671 emit_i8(as, HOOK_PROFILE);
2672 emit_rma(as, XO_GROUP3b, XOg_TEST, &J2G(as->J)->hookmask);
2673}
2674
2346/* -- Stack handling ------------------------------------------------------ */ 2675/* -- Stack handling ------------------------------------------------------ */
2347 2676
2348/* Check Lua stack size for overflow. Use exit handler as fallback. */ 2677/* Check Lua stack size for overflow. Use exit handler as fallback. */
@@ -2357,14 +2686,19 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
2357 emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0); 2686 emit_rmro(as, XO_MOV, r|REX_64, RID_ESP, 0);
2358 else 2687 else
2359 ra_modified(as, r); 2688 ra_modified(as, r);
2360 emit_gri(as, XG_ARITHi(XOg_CMP), r, (int32_t)(8*topslot)); 2689 emit_gri(as, XG_ARITHi(XOg_CMP), r|REX_GC64, (int32_t)(8*topslot));
2361 if (ra_hasreg(pbase) && pbase != r) 2690 if (ra_hasreg(pbase) && pbase != r)
2362 emit_rr(as, XO_ARITH(XOg_SUB), r, pbase); 2691 emit_rr(as, XO_ARITH(XOg_SUB), r|REX_GC64, pbase);
2363 else 2692 else
2693#if LJ_GC64
2694 emit_rmro(as, XO_ARITH(XOg_SUB), r|REX_64, RID_DISPATCH,
2695 (int32_t)dispofs(as, &J2G(as->J)->jit_base));
2696#else
2364 emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE, 2697 emit_rmro(as, XO_ARITH(XOg_SUB), r, RID_NONE,
2365 ptr2addr(&J2G(as->J)->jit_base)); 2698 ptr2addr(&J2G(as->J)->jit_base));
2366 emit_rmro(as, XO_MOV, r, r, offsetof(lua_State, maxstack)); 2699#endif
2367 emit_getgl(as, r, jit_L); 2700 emit_rmro(as, XO_MOV, r|REX_GC64, r, offsetof(lua_State, maxstack));
2701 emit_getgl(as, r, cur_L);
2368 if (allow == RSET_EMPTY) /* Spill temp. register. */ 2702 if (allow == RSET_EMPTY) /* Spill temp. register. */
2369 emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0); 2703 emit_rmro(as, XO_MOVto, r|REX_64, RID_ESP, 0);
2370} 2704}
@@ -2373,13 +2707,15 @@ static void asm_stack_check(ASMState *as, BCReg topslot,
2373static void asm_stack_restore(ASMState *as, SnapShot *snap) 2707static void asm_stack_restore(ASMState *as, SnapShot *snap)
2374{ 2708{
2375 SnapEntry *map = &as->T->snapmap[snap->mapofs]; 2709 SnapEntry *map = &as->T->snapmap[snap->mapofs];
2376 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1]; 2710#if !LJ_FR2 || defined(LUA_USE_ASSERT)
2711 SnapEntry *flinks = &as->T->snapmap[snap_nextofs(as->T, snap)-1-LJ_FR2];
2712#endif
2377 MSize n, nent = snap->nent; 2713 MSize n, nent = snap->nent;
2378 /* Store the value of all modified slots to the Lua stack. */ 2714 /* Store the value of all modified slots to the Lua stack. */
2379 for (n = 0; n < nent; n++) { 2715 for (n = 0; n < nent; n++) {
2380 SnapEntry sn = map[n]; 2716 SnapEntry sn = map[n];
2381 BCReg s = snap_slot(sn); 2717 BCReg s = snap_slot(sn);
2382 int32_t ofs = 8*((int32_t)s-1); 2718 int32_t ofs = 8*((int32_t)s-1-LJ_FR2);
2383 IRRef ref = snap_ref(sn); 2719 IRRef ref = snap_ref(sn);
2384 IRIns *ir = IR(ref); 2720 IRIns *ir = IR(ref);
2385 if ((sn & SNAP_NORESTORE)) 2721 if ((sn & SNAP_NORESTORE))
@@ -2392,16 +2728,44 @@ static void asm_stack_restore(ASMState *as, SnapShot *snap)
2392 (LJ_DUALNUM && irt_isinteger(ir->t))); 2728 (LJ_DUALNUM && irt_isinteger(ir->t)));
2393 if (!irref_isk(ref)) { 2729 if (!irref_isk(ref)) {
2394 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE)); 2730 Reg src = ra_alloc1(as, ref, rset_exclude(RSET_GPR, RID_BASE));
2731#if LJ_GC64
2732 if (irt_is64(ir->t)) {
2733 /* TODO: 64 bit store + 32 bit load-modify-store is suboptimal. */
2734 emit_u32(as, irt_toitype(ir->t) << 15);
2735 emit_rmro(as, XO_ARITHi, XOg_OR, RID_BASE, ofs+4);
2736 } else if (LJ_DUALNUM && irt_isinteger(ir->t)) {
2737 emit_movmroi(as, RID_BASE, ofs+4, LJ_TISNUM << 15);
2738 } else {
2739 emit_movmroi(as, RID_BASE, ofs+4, (irt_toitype(ir->t)<<15)|0x7fff);
2740 }
2741#endif
2395 emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs); 2742 emit_movtomro(as, REX_64IR(ir, src), RID_BASE, ofs);
2743#if LJ_GC64
2744 } else {
2745 TValue k;
2746 lj_ir_kvalue(as->J->L, &k, ir);
2747 if (tvisnil(&k)) {
2748 emit_i32(as, -1);
2749 emit_rmro(as, XO_MOVmi, REX_64, RID_BASE, ofs);
2750 } else {
2751 emit_movmroi(as, RID_BASE, ofs+4, k.u32.hi);
2752 emit_movmroi(as, RID_BASE, ofs, k.u32.lo);
2753 }
2754#else
2396 } else if (!irt_ispri(ir->t)) { 2755 } else if (!irt_ispri(ir->t)) {
2397 emit_movmroi(as, RID_BASE, ofs, ir->i); 2756 emit_movmroi(as, RID_BASE, ofs, ir->i);
2757#endif
2398 } 2758 }
2399 if ((sn & (SNAP_CONT|SNAP_FRAME))) { 2759 if ((sn & (SNAP_CONT|SNAP_FRAME))) {
2760#if !LJ_FR2
2400 if (s != 0) /* Do not overwrite link to previous frame. */ 2761 if (s != 0) /* Do not overwrite link to previous frame. */
2401 emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--)); 2762 emit_movmroi(as, RID_BASE, ofs+4, (int32_t)(*flinks--));
2763#endif
2764#if !LJ_GC64
2402 } else { 2765 } else {
2403 if (!(LJ_64 && irt_islightud(ir->t))) 2766 if (!(LJ_64 && irt_islightud(ir->t)))
2404 emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t)); 2767 emit_movmroi(as, RID_BASE, ofs+4, irt_toitype(ir->t));
2768#endif
2405 } 2769 }
2406 } 2770 }
2407 checkmclim(as); 2771 checkmclim(as);
@@ -2427,11 +2791,15 @@ static void asm_gc_check(ASMState *as)
2427 args[1] = ASMREF_TMP2; /* MSize steps */ 2791 args[1] = ASMREF_TMP2; /* MSize steps */
2428 asm_gencall(as, ci, args); 2792 asm_gencall(as, ci, args);
2429 tmp = ra_releasetmp(as, ASMREF_TMP1); 2793 tmp = ra_releasetmp(as, ASMREF_TMP1);
2794#if LJ_GC64
2795 emit_rmro(as, XO_LEA, tmp|REX_64, RID_DISPATCH, GG_DISP2G);
2796#else
2430 emit_loada(as, tmp, J2G(as->J)); 2797 emit_loada(as, tmp, J2G(as->J));
2798#endif
2431 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), as->gcsteps); 2799 emit_loadi(as, ra_releasetmp(as, ASMREF_TMP2), as->gcsteps);
2432 /* Jump around GC step if GC total < GC threshold. */ 2800 /* Jump around GC step if GC total < GC threshold. */
2433 emit_sjcc(as, CC_B, l_end); 2801 emit_sjcc(as, CC_B, l_end);
2434 emit_opgl(as, XO_ARITH(XOg_CMP), tmp, gc.threshold); 2802 emit_opgl(as, XO_ARITH(XOg_CMP), tmp|REX_GC64, gc.threshold);
2435 emit_getgl(as, tmp, gc.total); 2803 emit_getgl(as, tmp, gc.total);
2436 as->gcsteps = 0; 2804 as->gcsteps = 0;
2437 checkmclim(as); 2805 checkmclim(as);
@@ -2496,7 +2864,7 @@ static void asm_head_root_base(ASMState *as)
2496 if (rset_test(as->modset, r) || irt_ismarked(ir->t)) 2864 if (rset_test(as->modset, r) || irt_ismarked(ir->t))
2497 ir->r = RID_INIT; /* No inheritance for modified BASE register. */ 2865 ir->r = RID_INIT; /* No inheritance for modified BASE register. */
2498 if (r != RID_BASE) 2866 if (r != RID_BASE)
2499 emit_rr(as, XO_MOV, r, RID_BASE); 2867 emit_rr(as, XO_MOV, r|REX_GC64, RID_BASE);
2500 } 2868 }
2501} 2869}
2502 2870
@@ -2512,8 +2880,9 @@ static RegSet asm_head_side_base(ASMState *as, IRIns *irp, RegSet allow)
2512 if (irp->r == r) { 2880 if (irp->r == r) {
2513 rset_clear(allow, r); /* Mark same BASE register as coalesced. */ 2881 rset_clear(allow, r); /* Mark same BASE register as coalesced. */
2514 } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) { 2882 } else if (ra_hasreg(irp->r) && rset_test(as->freeset, irp->r)) {
2883 /* Move from coalesced parent reg. */
2515 rset_clear(allow, irp->r); 2884 rset_clear(allow, irp->r);
2516 emit_rr(as, XO_MOV, r, irp->r); /* Move from coalesced parent reg. */ 2885 emit_rr(as, XO_MOV, r|REX_GC64, irp->r);
2517 } else { 2886 } else {
2518 emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */ 2887 emit_getgl(as, r, jit_base); /* Otherwise reload BASE. */
2519 } 2888 }
@@ -2592,163 +2961,6 @@ static void asm_tail_prep(ASMState *as)
2592 } 2961 }
2593} 2962}
2594 2963
2595/* -- Instruction dispatch ------------------------------------------------ */
2596
2597/* Assemble a single instruction. */
2598static void asm_ir(ASMState *as, IRIns *ir)
2599{
2600 switch ((IROp)ir->o) {
2601 /* Miscellaneous ops. */
2602 case IR_LOOP: asm_loop(as); break;
2603 case IR_NOP: case IR_XBAR: lua_assert(!ra_used(ir)); break;
2604 case IR_USE:
2605 ra_alloc1(as, ir->op1, irt_isfp(ir->t) ? RSET_FPR : RSET_GPR); break;
2606 case IR_PHI: asm_phi(as, ir); break;
2607 case IR_HIOP: asm_hiop(as, ir); break;
2608 case IR_GCSTEP: asm_gcstep(as, ir); break;
2609
2610 /* Guarded assertions. */
2611 case IR_LT: case IR_GE: case IR_LE: case IR_GT:
2612 case IR_ULT: case IR_UGE: case IR_ULE: case IR_UGT:
2613 case IR_EQ: case IR_NE: case IR_ABC:
2614 asm_comp(as, ir, asm_compmap[ir->o]);
2615 break;
2616
2617 case IR_RETF: asm_retf(as, ir); break;
2618
2619 /* Bit ops. */
2620 case IR_BNOT: asm_neg_not(as, ir, XOg_NOT); break;
2621 case IR_BSWAP: asm_bitswap(as, ir); break;
2622
2623 case IR_BAND: asm_intarith(as, ir, XOg_AND); break;
2624 case IR_BOR: asm_intarith(as, ir, XOg_OR); break;
2625 case IR_BXOR: asm_intarith(as, ir, XOg_XOR); break;
2626
2627 case IR_BSHL: asm_bitshift(as, ir, XOg_SHL); break;
2628 case IR_BSHR: asm_bitshift(as, ir, XOg_SHR); break;
2629 case IR_BSAR: asm_bitshift(as, ir, XOg_SAR); break;
2630 case IR_BROL: asm_bitshift(as, ir, XOg_ROL); break;
2631 case IR_BROR: asm_bitshift(as, ir, XOg_ROR); break;
2632
2633 /* Arithmetic ops. */
2634 case IR_ADD: asm_add(as, ir); break;
2635 case IR_SUB:
2636 if (irt_isnum(ir->t))
2637 asm_fparith(as, ir, XO_SUBSD);
2638 else /* Note: no need for LEA trick here. i-k is encoded as i+(-k). */
2639 asm_intarith(as, ir, XOg_SUB);
2640 break;
2641 case IR_MUL:
2642 if (irt_isnum(ir->t))
2643 asm_fparith(as, ir, XO_MULSD);
2644 else
2645 asm_intarith(as, ir, XOg_X_IMUL);
2646 break;
2647 case IR_DIV:
2648#if LJ_64 && LJ_HASFFI
2649 if (!irt_isnum(ir->t))
2650 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_divi64 :
2651 IRCALL_lj_carith_divu64);
2652 else
2653#endif
2654 asm_fparith(as, ir, XO_DIVSD);
2655 break;
2656 case IR_MOD:
2657#if LJ_64 && LJ_HASFFI
2658 if (!irt_isint(ir->t))
2659 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_modi64 :
2660 IRCALL_lj_carith_modu64);
2661 else
2662#endif
2663 asm_intmod(as, ir);
2664 break;
2665
2666 case IR_NEG:
2667 if (irt_isnum(ir->t))
2668 asm_fparith(as, ir, XO_XORPS);
2669 else
2670 asm_neg_not(as, ir, XOg_NEG);
2671 break;
2672 case IR_ABS: asm_fparith(as, ir, XO_ANDPS); break;
2673
2674 case IR_MIN:
2675 if (irt_isnum(ir->t))
2676 asm_fparith(as, ir, XO_MINSD);
2677 else
2678 asm_min_max(as, ir, CC_G);
2679 break;
2680 case IR_MAX:
2681 if (irt_isnum(ir->t))
2682 asm_fparith(as, ir, XO_MAXSD);
2683 else
2684 asm_min_max(as, ir, CC_L);
2685 break;
2686
2687 case IR_FPMATH: case IR_ATAN2: case IR_LDEXP:
2688 asm_fpmath(as, ir);
2689 break;
2690 case IR_POW:
2691#if LJ_64 && LJ_HASFFI
2692 if (!irt_isnum(ir->t))
2693 asm_arith64(as, ir, irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
2694 IRCALL_lj_carith_powu64);
2695 else
2696#endif
2697 asm_fppowi(as, ir);
2698 break;
2699
2700 /* Overflow-checking arithmetic ops. Note: don't use LEA here! */
2701 case IR_ADDOV: asm_intarith(as, ir, XOg_ADD); break;
2702 case IR_SUBOV: asm_intarith(as, ir, XOg_SUB); break;
2703 case IR_MULOV: asm_intarith(as, ir, XOg_X_IMUL); break;
2704
2705 /* Memory references. */
2706 case IR_AREF: asm_aref(as, ir); break;
2707 case IR_HREF: asm_href(as, ir); break;
2708 case IR_HREFK: asm_hrefk(as, ir); break;
2709 case IR_NEWREF: asm_newref(as, ir); break;
2710 case IR_UREFO: case IR_UREFC: asm_uref(as, ir); break;
2711 case IR_FREF: asm_fref(as, ir); break;
2712 case IR_STRREF: asm_strref(as, ir); break;
2713
2714 /* Loads and stores. */
2715 case IR_ALOAD: case IR_HLOAD: case IR_ULOAD: case IR_VLOAD:
2716 asm_ahuvload(as, ir);
2717 break;
2718 case IR_FLOAD: case IR_XLOAD: asm_fxload(as, ir); break;
2719 case IR_SLOAD: asm_sload(as, ir); break;
2720
2721 case IR_ASTORE: case IR_HSTORE: case IR_USTORE: asm_ahustore(as, ir); break;
2722 case IR_FSTORE: case IR_XSTORE: asm_fxstore(as, ir); break;
2723
2724 /* Allocations. */
2725 case IR_SNEW: case IR_XSNEW: asm_snew(as, ir); break;
2726 case IR_TNEW: asm_tnew(as, ir); break;
2727 case IR_TDUP: asm_tdup(as, ir); break;
2728 case IR_CNEW: case IR_CNEWI: asm_cnew(as, ir); break;
2729
2730 /* Write barriers. */
2731 case IR_TBAR: asm_tbar(as, ir); break;
2732 case IR_OBAR: asm_obar(as, ir); break;
2733
2734 /* Type conversions. */
2735 case IR_TOBIT: asm_tobit(as, ir); break;
2736 case IR_CONV: asm_conv(as, ir); break;
2737 case IR_TOSTR: asm_tostr(as, ir); break;
2738 case IR_STRTO: asm_strto(as, ir); break;
2739
2740 /* Calls. */
2741 case IR_CALLN: case IR_CALLL: case IR_CALLS: asm_call(as, ir); break;
2742 case IR_CALLXS: asm_callx(as, ir); break;
2743 case IR_CARG: break;
2744
2745 default:
2746 setintV(&as->J->errinfo, ir->o);
2747 lj_trace_err_info(as->J, LJ_TRERR_NYIIR);
2748 break;
2749 }
2750}
2751
2752/* -- Trace setup --------------------------------------------------------- */ 2964/* -- Trace setup --------------------------------------------------------- */
2753 2965
2754/* Ensure there are enough stack slots for call arguments. */ 2966/* Ensure there are enough stack slots for call arguments. */
@@ -2771,6 +2983,7 @@ static Reg asm_setup_call_slots(ASMState *as, IRIns *ir, const CCallInfo *ci)
2771static void asm_setup_target(ASMState *as) 2983static void asm_setup_target(ASMState *as)
2772{ 2984{
2773 asm_exitstub_setup(as, as->T->nsnap); 2985 asm_exitstub_setup(as, as->T->nsnap);
2986 as->mrm.base = 0;
2774} 2987}
2775 2988
2776/* -- Trace patching ------------------------------------------------------ */ 2989/* -- Trace patching ------------------------------------------------------ */
@@ -2883,13 +3096,19 @@ void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target)
2883 MSize len = T->szmcode; 3096 MSize len = T->szmcode;
2884 MCode *px = exitstub_addr(J, exitno) - 6; 3097 MCode *px = exitstub_addr(J, exitno) - 6;
2885 MCode *pe = p+len-6; 3098 MCode *pe = p+len-6;
2886 uint32_t stateaddr = u32ptr(&J2G(J)->vmstate); 3099#if LJ_GC64
3100 uint32_t statei = (uint32_t)(GG_OFS(g.vmstate) - GG_OFS(dispatch));
3101#else
3102 uint32_t statei = u32ptr(&J2G(J)->vmstate);
3103#endif
2887 if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px) 3104 if (len > 5 && p[len-5] == XI_JMP && p+len-6 + *(int32_t *)(p+len-4) == px)
2888 *(int32_t *)(p+len-4) = jmprel(p+len, target); 3105 *(int32_t *)(p+len-4) = jmprel(p+len, target);
2889 /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */ 3106 /* Do not patch parent exit for a stack check. Skip beyond vmstate update. */
2890 for (; p < pe; p += asm_x86_inslen(p)) 3107 for (; p < pe; p += asm_x86_inslen(p)) {
2891 if (*(uint32_t *)(p+(LJ_64 ? 3 : 2)) == stateaddr && p[0] == XI_MOVmi) 3108 intptr_t ofs = LJ_GC64 ? (p[0] & 0xf0) == 0x40 : LJ_64;
3109 if (*(uint32_t *)(p+2+ofs) == statei && p[ofs+LJ_GC64-LJ_64] == XI_MOVmi)
2892 break; 3110 break;
3111 }
2893 lua_assert(p < pe); 3112 lua_assert(p < pe);
2894 for (; p < pe; p += asm_x86_inslen(p)) 3113 for (; p < pe; p += asm_x86_inslen(p))
2895 if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px) 3114 if ((*(uint16_t *)p & 0xf0ff) == 0x800f && p + *(int32_t *)(p+2) == px)
diff --git a/src/lj_bc.h b/src/lj_bc.h
index 108c10f2..69a45f28 100644
--- a/src/lj_bc.h
+++ b/src/lj_bc.h
@@ -89,6 +89,8 @@
89 _(ISFC, dst, ___, var, ___) \ 89 _(ISFC, dst, ___, var, ___) \
90 _(IST, ___, ___, var, ___) \ 90 _(IST, ___, ___, var, ___) \
91 _(ISF, ___, ___, var, ___) \ 91 _(ISF, ___, ___, var, ___) \
92 _(ISTYPE, var, ___, lit, ___) \
93 _(ISNUM, var, ___, lit, ___) \
92 \ 94 \
93 /* Unary ops. */ \ 95 /* Unary ops. */ \
94 _(MOV, dst, ___, var, ___) \ 96 _(MOV, dst, ___, var, ___) \
@@ -143,10 +145,12 @@
143 _(TGETV, dst, var, var, index) \ 145 _(TGETV, dst, var, var, index) \
144 _(TGETS, dst, var, str, index) \ 146 _(TGETS, dst, var, str, index) \
145 _(TGETB, dst, var, lit, index) \ 147 _(TGETB, dst, var, lit, index) \
148 _(TGETR, dst, var, var, index) \
146 _(TSETV, var, var, var, newindex) \ 149 _(TSETV, var, var, var, newindex) \
147 _(TSETS, var, var, str, newindex) \ 150 _(TSETS, var, var, str, newindex) \
148 _(TSETB, var, var, lit, newindex) \ 151 _(TSETB, var, var, lit, newindex) \
149 _(TSETM, base, ___, num, newindex) \ 152 _(TSETM, base, ___, num, newindex) \
153 _(TSETR, var, var, var, newindex) \
150 \ 154 \
151 /* Calls and vararg handling. T = tail call. */ \ 155 /* Calls and vararg handling. T = tail call. */ \
152 _(CALLM, base, lit, lit, call) \ 156 _(CALLM, base, lit, lit, call) \
diff --git a/src/lj_bcdump.h b/src/lj_bcdump.h
index ba53c0a1..fdfc6ec0 100644
--- a/src/lj_bcdump.h
+++ b/src/lj_bcdump.h
@@ -36,14 +36,15 @@
36/* If you perform *any* kind of private modifications to the bytecode itself 36/* If you perform *any* kind of private modifications to the bytecode itself
37** or to the dump format, you *must* set BCDUMP_VERSION to 0x80 or higher. 37** or to the dump format, you *must* set BCDUMP_VERSION to 0x80 or higher.
38*/ 38*/
39#define BCDUMP_VERSION 1 39#define BCDUMP_VERSION 2
40 40
41/* Compatibility flags. */ 41/* Compatibility flags. */
42#define BCDUMP_F_BE 0x01 42#define BCDUMP_F_BE 0x01
43#define BCDUMP_F_STRIP 0x02 43#define BCDUMP_F_STRIP 0x02
44#define BCDUMP_F_FFI 0x04 44#define BCDUMP_F_FFI 0x04
45#define BCDUMP_F_FR2 0x08
45 46
46#define BCDUMP_F_KNOWN (BCDUMP_F_FFI*2-1) 47#define BCDUMP_F_KNOWN (BCDUMP_F_FR2*2-1)
47 48
48/* Type codes for the GC constants of a prototype. Plus length for strings. */ 49/* Type codes for the GC constants of a prototype. Plus length for strings. */
49enum { 50enum {
@@ -61,6 +62,7 @@ enum {
61 62
62LJ_FUNC int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, 63LJ_FUNC int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer,
63 void *data, int strip); 64 void *data, int strip);
65LJ_FUNC GCproto *lj_bcread_proto(LexState *ls);
64LJ_FUNC GCproto *lj_bcread(LexState *ls); 66LJ_FUNC GCproto *lj_bcread(LexState *ls);
65 67
66#endif 68#endif
diff --git a/src/lj_bcread.c b/src/lj_bcread.c
index 6a462bd6..48c5e7c7 100644
--- a/src/lj_bcread.c
+++ b/src/lj_bcread.c
@@ -9,6 +9,7 @@
9#include "lj_obj.h" 9#include "lj_obj.h"
10#include "lj_gc.h" 10#include "lj_gc.h"
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_buf.h"
12#include "lj_str.h" 13#include "lj_str.h"
13#include "lj_tab.h" 14#include "lj_tab.h"
14#include "lj_bc.h" 15#include "lj_bc.h"
@@ -20,6 +21,7 @@
20#include "lj_lex.h" 21#include "lj_lex.h"
21#include "lj_bcdump.h" 22#include "lj_bcdump.h"
22#include "lj_state.h" 23#include "lj_state.h"
24#include "lj_strfmt.h"
23 25
24/* Reuse some lexer fields for our own purposes. */ 26/* Reuse some lexer fields for our own purposes. */
25#define bcread_flags(ls) ls->level 27#define bcread_flags(ls) ls->level
@@ -38,84 +40,73 @@ static LJ_NOINLINE void bcread_error(LexState *ls, ErrMsg em)
38 const char *name = ls->chunkarg; 40 const char *name = ls->chunkarg;
39 if (*name == BCDUMP_HEAD1) name = "(binary)"; 41 if (*name == BCDUMP_HEAD1) name = "(binary)";
40 else if (*name == '@' || *name == '=') name++; 42 else if (*name == '@' || *name == '=') name++;
41 lj_str_pushf(L, "%s: %s", name, err2msg(em)); 43 lj_strfmt_pushf(L, "%s: %s", name, err2msg(em));
42 lj_err_throw(L, LUA_ERRSYNTAX); 44 lj_err_throw(L, LUA_ERRSYNTAX);
43} 45}
44 46
45/* Resize input buffer. */ 47/* Refill buffer. */
46static void bcread_resize(LexState *ls, MSize len)
47{
48 if (ls->sb.sz < len) {
49 MSize sz = ls->sb.sz * 2;
50 while (len > sz) sz = sz * 2;
51 lj_str_resizebuf(ls->L, &ls->sb, sz);
52 /* Caveat: this may change ls->sb.buf which may affect ls->p. */
53 }
54}
55
56/* Refill buffer if needed. */
57static LJ_NOINLINE void bcread_fill(LexState *ls, MSize len, int need) 48static LJ_NOINLINE void bcread_fill(LexState *ls, MSize len, int need)
58{ 49{
59 lua_assert(len != 0); 50 lua_assert(len != 0);
60 if (len > LJ_MAX_MEM || ls->current < 0) 51 if (len > LJ_MAX_BUF || ls->c < 0)
61 bcread_error(ls, LJ_ERR_BCBAD); 52 bcread_error(ls, LJ_ERR_BCBAD);
62 do { 53 do {
63 const char *buf; 54 const char *buf;
64 size_t size; 55 size_t sz;
65 if (ls->n) { /* Copy remainder to buffer. */ 56 char *p = sbufB(&ls->sb);
66 if (ls->sb.n) { /* Move down in buffer. */ 57 MSize n = (MSize)(ls->pe - ls->p);
67 lua_assert(ls->p + ls->n == ls->sb.buf + ls->sb.n); 58 if (n) { /* Copy remainder to buffer. */
68 if (ls->n != ls->sb.n) 59 if (sbuflen(&ls->sb)) { /* Move down in buffer. */
69 memmove(ls->sb.buf, ls->p, ls->n); 60 lua_assert(ls->pe == sbufP(&ls->sb));
61 if (ls->p != p) memmove(p, ls->p, n);
70 } else { /* Copy from buffer provided by reader. */ 62 } else { /* Copy from buffer provided by reader. */
71 bcread_resize(ls, len); 63 p = lj_buf_need(&ls->sb, len);
72 memcpy(ls->sb.buf, ls->p, ls->n); 64 memcpy(p, ls->p, n);
73 } 65 }
74 ls->p = ls->sb.buf; 66 ls->p = p;
67 ls->pe = p + n;
75 } 68 }
76 ls->sb.n = ls->n; 69 setsbufP(&ls->sb, p + n);
77 buf = ls->rfunc(ls->L, ls->rdata, &size); /* Get more data from reader. */ 70 buf = ls->rfunc(ls->L, ls->rdata, &sz); /* Get more data from reader. */
78 if (buf == NULL || size == 0) { /* EOF? */ 71 if (buf == NULL || sz == 0) { /* EOF? */
79 if (need) bcread_error(ls, LJ_ERR_BCBAD); 72 if (need) bcread_error(ls, LJ_ERR_BCBAD);
80 ls->current = -1; /* Only bad if we get called again. */ 73 ls->c = -1; /* Only bad if we get called again. */
81 break; 74 break;
82 } 75 }
83 if (ls->sb.n) { /* Append to buffer. */ 76 if (n) { /* Append to buffer. */
84 MSize n = ls->sb.n + (MSize)size; 77 n += (MSize)sz;
85 bcread_resize(ls, n < len ? len : n); 78 p = lj_buf_need(&ls->sb, n < len ? len : n);
86 memcpy(ls->sb.buf + ls->sb.n, buf, size); 79 memcpy(sbufP(&ls->sb), buf, sz);
87 ls->n = ls->sb.n = n; 80 setsbufP(&ls->sb, p + n);
88 ls->p = ls->sb.buf; 81 ls->p = p;
82 ls->pe = p + n;
89 } else { /* Return buffer provided by reader. */ 83 } else { /* Return buffer provided by reader. */
90 ls->n = (MSize)size;
91 ls->p = buf; 84 ls->p = buf;
85 ls->pe = buf + sz;
92 } 86 }
93 } while (ls->n < len); 87 } while (ls->p + len > ls->pe);
94} 88}
95 89
96/* Need a certain number of bytes. */ 90/* Need a certain number of bytes. */
97static LJ_AINLINE void bcread_need(LexState *ls, MSize len) 91static LJ_AINLINE void bcread_need(LexState *ls, MSize len)
98{ 92{
99 if (LJ_UNLIKELY(ls->n < len)) 93 if (LJ_UNLIKELY(ls->p + len > ls->pe))
100 bcread_fill(ls, len, 1); 94 bcread_fill(ls, len, 1);
101} 95}
102 96
103/* Want to read up to a certain number of bytes, but may need less. */ 97/* Want to read up to a certain number of bytes, but may need less. */
104static LJ_AINLINE void bcread_want(LexState *ls, MSize len) 98static LJ_AINLINE void bcread_want(LexState *ls, MSize len)
105{ 99{
106 if (LJ_UNLIKELY(ls->n < len)) 100 if (LJ_UNLIKELY(ls->p + len > ls->pe))
107 bcread_fill(ls, len, 0); 101 bcread_fill(ls, len, 0);
108} 102}
109 103
110#define bcread_dec(ls) check_exp(ls->n > 0, ls->n--)
111#define bcread_consume(ls, len) check_exp(ls->n >= (len), ls->n -= (len))
112
113/* Return memory block from buffer. */ 104/* Return memory block from buffer. */
114static uint8_t *bcread_mem(LexState *ls, MSize len) 105static LJ_AINLINE uint8_t *bcread_mem(LexState *ls, MSize len)
115{ 106{
116 uint8_t *p = (uint8_t *)ls->p; 107 uint8_t *p = (uint8_t *)ls->p;
117 bcread_consume(ls, len); 108 ls->p += len;
118 ls->p = (char *)p + len; 109 lua_assert(ls->p <= ls->pe);
119 return p; 110 return p;
120} 111}
121 112
@@ -128,25 +119,15 @@ static void bcread_block(LexState *ls, void *q, MSize len)
128/* Read byte from buffer. */ 119/* Read byte from buffer. */
129static LJ_AINLINE uint32_t bcread_byte(LexState *ls) 120static LJ_AINLINE uint32_t bcread_byte(LexState *ls)
130{ 121{
131 bcread_dec(ls); 122 lua_assert(ls->p < ls->pe);
132 return (uint32_t)(uint8_t)*ls->p++; 123 return (uint32_t)(uint8_t)*ls->p++;
133} 124}
134 125
135/* Read ULEB128 value from buffer. */ 126/* Read ULEB128 value from buffer. */
136static uint32_t bcread_uleb128(LexState *ls) 127static LJ_AINLINE uint32_t bcread_uleb128(LexState *ls)
137{ 128{
138 const uint8_t *p = (const uint8_t *)ls->p; 129 uint32_t v = lj_buf_ruleb128(&ls->p);
139 uint32_t v = *p++; 130 lua_assert(ls->p <= ls->pe);
140 if (LJ_UNLIKELY(v >= 0x80)) {
141 int sh = 0;
142 v &= 0x7f;
143 do {
144 v |= ((*p & 0x7f) << (sh += 7));
145 bcread_dec(ls);
146 } while (*p++ >= 0x80);
147 }
148 bcread_dec(ls);
149 ls->p = (char *)p;
150 return v; 131 return v;
151} 132}
152 133
@@ -160,11 +141,10 @@ static uint32_t bcread_uleb128_33(LexState *ls)
160 v &= 0x3f; 141 v &= 0x3f;
161 do { 142 do {
162 v |= ((*p & 0x7f) << (sh += 7)); 143 v |= ((*p & 0x7f) << (sh += 7));
163 bcread_dec(ls);
164 } while (*p++ >= 0x80); 144 } while (*p++ >= 0x80);
165 } 145 }
166 bcread_dec(ls);
167 ls->p = (char *)p; 146 ls->p = (char *)p;
147 lua_assert(ls->p <= ls->pe);
168 return v; 148 return v;
169} 149}
170 150
@@ -212,7 +192,7 @@ static void bcread_ktabk(LexState *ls, TValue *o)
212 o->u32.hi = bcread_uleb128(ls); 192 o->u32.hi = bcread_uleb128(ls);
213 } else { 193 } else {
214 lua_assert(tp <= BCDUMP_KTAB_TRUE); 194 lua_assert(tp <= BCDUMP_KTAB_TRUE);
215 setitype(o, ~tp); 195 setpriV(o, ~tp);
216 } 196 }
217} 197}
218 198
@@ -326,25 +306,13 @@ static void bcread_uv(LexState *ls, GCproto *pt, MSize sizeuv)
326} 306}
327 307
328/* Read a prototype. */ 308/* Read a prototype. */
329static GCproto *bcread_proto(LexState *ls) 309GCproto *lj_bcread_proto(LexState *ls)
330{ 310{
331 GCproto *pt; 311 GCproto *pt;
332 MSize framesize, numparams, flags, sizeuv, sizekgc, sizekn, sizebc, sizept; 312 MSize framesize, numparams, flags, sizeuv, sizekgc, sizekn, sizebc, sizept;
333 MSize ofsk, ofsuv, ofsdbg; 313 MSize ofsk, ofsuv, ofsdbg;
334 MSize sizedbg = 0; 314 MSize sizedbg = 0;
335 BCLine firstline = 0, numline = 0; 315 BCLine firstline = 0, numline = 0;
336 MSize len, startn;
337
338 /* Read length. */
339 if (ls->n > 0 && ls->p[0] == 0) { /* Shortcut EOF. */
340 ls->n--; ls->p++;
341 return NULL;
342 }
343 bcread_want(ls, 5);
344 len = bcread_uleb128(ls);
345 if (!len) return NULL; /* EOF */
346 bcread_need(ls, len);
347 startn = ls->n;
348 316
349 /* Read prototype header. */ 317 /* Read prototype header. */
350 flags = bcread_byte(ls); 318 flags = bcread_byte(ls);
@@ -413,9 +381,6 @@ static GCproto *bcread_proto(LexState *ls)
413 setmref(pt->uvinfo, NULL); 381 setmref(pt->uvinfo, NULL);
414 setmref(pt->varinfo, NULL); 382 setmref(pt->varinfo, NULL);
415 } 383 }
416
417 if (len != startn - ls->n)
418 bcread_error(ls, LJ_ERR_BCBAD);
419 return pt; 384 return pt;
420} 385}
421 386
@@ -429,6 +394,7 @@ static int bcread_header(LexState *ls)
429 bcread_byte(ls) != BCDUMP_VERSION) return 0; 394 bcread_byte(ls) != BCDUMP_VERSION) return 0;
430 bcread_flags(ls) = flags = bcread_uleb128(ls); 395 bcread_flags(ls) = flags = bcread_uleb128(ls);
431 if ((flags & ~(BCDUMP_F_KNOWN)) != 0) return 0; 396 if ((flags & ~(BCDUMP_F_KNOWN)) != 0) return 0;
397 if ((flags & BCDUMP_F_FR2) != LJ_FR2*BCDUMP_F_FR2) return 0;
432 if ((flags & BCDUMP_F_FFI)) { 398 if ((flags & BCDUMP_F_FFI)) {
433#if LJ_HASFFI 399#if LJ_HASFFI
434 lua_State *L = ls->L; 400 lua_State *L = ls->L;
@@ -455,19 +421,34 @@ static int bcread_header(LexState *ls)
455GCproto *lj_bcread(LexState *ls) 421GCproto *lj_bcread(LexState *ls)
456{ 422{
457 lua_State *L = ls->L; 423 lua_State *L = ls->L;
458 lua_assert(ls->current == BCDUMP_HEAD1); 424 lua_assert(ls->c == BCDUMP_HEAD1);
459 bcread_savetop(L, ls, L->top); 425 bcread_savetop(L, ls, L->top);
460 lj_str_resetbuf(&ls->sb); 426 lj_buf_reset(&ls->sb);
461 /* Check for a valid bytecode dump header. */ 427 /* Check for a valid bytecode dump header. */
462 if (!bcread_header(ls)) 428 if (!bcread_header(ls))
463 bcread_error(ls, LJ_ERR_BCFMT); 429 bcread_error(ls, LJ_ERR_BCFMT);
464 for (;;) { /* Process all prototypes in the bytecode dump. */ 430 for (;;) { /* Process all prototypes in the bytecode dump. */
465 GCproto *pt = bcread_proto(ls); 431 GCproto *pt;
466 if (!pt) break; 432 MSize len;
433 const char *startp;
434 /* Read length. */
435 if (ls->p < ls->pe && ls->p[0] == 0) { /* Shortcut EOF. */
436 ls->p++;
437 break;
438 }
439 bcread_want(ls, 5);
440 len = bcread_uleb128(ls);
441 if (!len) break; /* EOF */
442 bcread_need(ls, len);
443 startp = ls->p;
444 pt = lj_bcread_proto(ls);
445 if (ls->p != startp + len)
446 bcread_error(ls, LJ_ERR_BCBAD);
467 setprotoV(L, L->top, pt); 447 setprotoV(L, L->top, pt);
468 incr_top(L); 448 incr_top(L);
469 } 449 }
470 if ((int32_t)ls->n > 0 || L->top-1 != bcread_oldtop(L, ls)) 450 if ((int32_t)(2*(uint32_t)(ls->pe - ls->p)) > 0 ||
451 L->top-1 != bcread_oldtop(L, ls))
471 bcread_error(ls, LJ_ERR_BCBAD); 452 bcread_error(ls, LJ_ERR_BCBAD);
472 /* Pop off last prototype. */ 453 /* Pop off last prototype. */
473 L->top--; 454 L->top--;
diff --git a/src/lj_bcwrite.c b/src/lj_bcwrite.c
index fae1ebb3..5e05caea 100644
--- a/src/lj_bcwrite.c
+++ b/src/lj_bcwrite.c
@@ -8,7 +8,7 @@
8 8
9#include "lj_obj.h" 9#include "lj_obj.h"
10#include "lj_gc.h" 10#include "lj_gc.h"
11#include "lj_str.h" 11#include "lj_buf.h"
12#include "lj_bc.h" 12#include "lj_bc.h"
13#if LJ_HASFFI 13#if LJ_HASFFI
14#include "lj_ctype.h" 14#include "lj_ctype.h"
@@ -17,13 +17,13 @@
17#include "lj_dispatch.h" 17#include "lj_dispatch.h"
18#include "lj_jit.h" 18#include "lj_jit.h"
19#endif 19#endif
20#include "lj_strfmt.h"
20#include "lj_bcdump.h" 21#include "lj_bcdump.h"
21#include "lj_vm.h" 22#include "lj_vm.h"
22 23
23/* Context for bytecode writer. */ 24/* Context for bytecode writer. */
24typedef struct BCWriteCtx { 25typedef struct BCWriteCtx {
25 SBuf sb; /* Output buffer. */ 26 SBuf sb; /* Output buffer. */
26 lua_State *L; /* Lua state. */
27 GCproto *pt; /* Root prototype. */ 27 GCproto *pt; /* Root prototype. */
28 lua_Writer wfunc; /* Writer callback. */ 28 lua_Writer wfunc; /* Writer callback. */
29 void *wdata; /* Writer callback data. */ 29 void *wdata; /* Writer callback data. */
@@ -31,85 +31,44 @@ typedef struct BCWriteCtx {
31 int status; /* Status from writer callback. */ 31 int status; /* Status from writer callback. */
32} BCWriteCtx; 32} BCWriteCtx;
33 33
34/* -- Output buffer handling ---------------------------------------------- */
35
36/* Resize buffer if needed. */
37static LJ_NOINLINE void bcwrite_resize(BCWriteCtx *ctx, MSize len)
38{
39 MSize sz = ctx->sb.sz * 2;
40 while (ctx->sb.n + len > sz) sz = sz * 2;
41 lj_str_resizebuf(ctx->L, &ctx->sb, sz);
42}
43
44/* Need a certain amount of buffer space. */
45static LJ_AINLINE void bcwrite_need(BCWriteCtx *ctx, MSize len)
46{
47 if (LJ_UNLIKELY(ctx->sb.n + len > ctx->sb.sz))
48 bcwrite_resize(ctx, len);
49}
50
51/* Add memory block to buffer. */
52static void bcwrite_block(BCWriteCtx *ctx, const void *p, MSize len)
53{
54 uint8_t *q = (uint8_t *)(ctx->sb.buf + ctx->sb.n);
55 MSize i;
56 ctx->sb.n += len;
57 for (i = 0; i < len; i++) q[i] = ((uint8_t *)p)[i];
58}
59
60/* Add byte to buffer. */
61static LJ_AINLINE void bcwrite_byte(BCWriteCtx *ctx, uint8_t b)
62{
63 ctx->sb.buf[ctx->sb.n++] = b;
64}
65
66/* Add ULEB128 value to buffer. */
67static void bcwrite_uleb128(BCWriteCtx *ctx, uint32_t v)
68{
69 MSize n = ctx->sb.n;
70 uint8_t *p = (uint8_t *)ctx->sb.buf;
71 for (; v >= 0x80; v >>= 7)
72 p[n++] = (uint8_t)((v & 0x7f) | 0x80);
73 p[n++] = (uint8_t)v;
74 ctx->sb.n = n;
75}
76
77/* -- Bytecode writer ----------------------------------------------------- */ 34/* -- Bytecode writer ----------------------------------------------------- */
78 35
79/* Write a single constant key/value of a template table. */ 36/* Write a single constant key/value of a template table. */
80static void bcwrite_ktabk(BCWriteCtx *ctx, cTValue *o, int narrow) 37static void bcwrite_ktabk(BCWriteCtx *ctx, cTValue *o, int narrow)
81{ 38{
82 bcwrite_need(ctx, 1+10); 39 char *p = lj_buf_more(&ctx->sb, 1+10);
83 if (tvisstr(o)) { 40 if (tvisstr(o)) {
84 const GCstr *str = strV(o); 41 const GCstr *str = strV(o);
85 MSize len = str->len; 42 MSize len = str->len;
86 bcwrite_need(ctx, 5+len); 43 p = lj_buf_more(&ctx->sb, 5+len);
87 bcwrite_uleb128(ctx, BCDUMP_KTAB_STR+len); 44 p = lj_strfmt_wuleb128(p, BCDUMP_KTAB_STR+len);
88 bcwrite_block(ctx, strdata(str), len); 45 p = lj_buf_wmem(p, strdata(str), len);
89 } else if (tvisint(o)) { 46 } else if (tvisint(o)) {
90 bcwrite_byte(ctx, BCDUMP_KTAB_INT); 47 *p++ = BCDUMP_KTAB_INT;
91 bcwrite_uleb128(ctx, intV(o)); 48 p = lj_strfmt_wuleb128(p, intV(o));
92 } else if (tvisnum(o)) { 49 } else if (tvisnum(o)) {
93 if (!LJ_DUALNUM && narrow) { /* Narrow number constants to integers. */ 50 if (!LJ_DUALNUM && narrow) { /* Narrow number constants to integers. */
94 lua_Number num = numV(o); 51 lua_Number num = numV(o);
95 int32_t k = lj_num2int(num); 52 int32_t k = lj_num2int(num);
96 if (num == (lua_Number)k) { /* -0 is never a constant. */ 53 if (num == (lua_Number)k) { /* -0 is never a constant. */
97 bcwrite_byte(ctx, BCDUMP_KTAB_INT); 54 *p++ = BCDUMP_KTAB_INT;
98 bcwrite_uleb128(ctx, k); 55 p = lj_strfmt_wuleb128(p, k);
56 setsbufP(&ctx->sb, p);
99 return; 57 return;
100 } 58 }
101 } 59 }
102 bcwrite_byte(ctx, BCDUMP_KTAB_NUM); 60 *p++ = BCDUMP_KTAB_NUM;
103 bcwrite_uleb128(ctx, o->u32.lo); 61 p = lj_strfmt_wuleb128(p, o->u32.lo);
104 bcwrite_uleb128(ctx, o->u32.hi); 62 p = lj_strfmt_wuleb128(p, o->u32.hi);
105 } else { 63 } else {
106 lua_assert(tvispri(o)); 64 lua_assert(tvispri(o));
107 bcwrite_byte(ctx, BCDUMP_KTAB_NIL+~itype(o)); 65 *p++ = BCDUMP_KTAB_NIL+~itype(o);
108 } 66 }
67 setsbufP(&ctx->sb, p);
109} 68}
110 69
111/* Write a template table. */ 70/* Write a template table. */
112static void bcwrite_ktab(BCWriteCtx *ctx, const GCtab *t) 71static void bcwrite_ktab(BCWriteCtx *ctx, char *p, const GCtab *t)
113{ 72{
114 MSize narray = 0, nhash = 0; 73 MSize narray = 0, nhash = 0;
115 if (t->asize > 0) { /* Determine max. length of array part. */ 74 if (t->asize > 0) { /* Determine max. length of array part. */
@@ -127,8 +86,9 @@ static void bcwrite_ktab(BCWriteCtx *ctx, const GCtab *t)
127 nhash += !tvisnil(&node[i].val); 86 nhash += !tvisnil(&node[i].val);
128 } 87 }
129 /* Write number of array slots and hash slots. */ 88 /* Write number of array slots and hash slots. */
130 bcwrite_uleb128(ctx, narray); 89 p = lj_strfmt_wuleb128(p, narray);
131 bcwrite_uleb128(ctx, nhash); 90 p = lj_strfmt_wuleb128(p, nhash);
91 setsbufP(&ctx->sb, p);
132 if (narray) { /* Write array entries (may contain nil). */ 92 if (narray) { /* Write array entries (may contain nil). */
133 MSize i; 93 MSize i;
134 TValue *o = tvref(t->array); 94 TValue *o = tvref(t->array);
@@ -155,6 +115,7 @@ static void bcwrite_kgc(BCWriteCtx *ctx, GCproto *pt)
155 for (i = 0; i < sizekgc; i++, kr++) { 115 for (i = 0; i < sizekgc; i++, kr++) {
156 GCobj *o = gcref(*kr); 116 GCobj *o = gcref(*kr);
157 MSize tp, need = 1; 117 MSize tp, need = 1;
118 char *p;
158 /* Determine constant type and needed size. */ 119 /* Determine constant type and needed size. */
159 if (o->gch.gct == ~LJ_TSTR) { 120 if (o->gch.gct == ~LJ_TSTR) {
160 tp = BCDUMP_KGC_STR + gco2str(o)->len; 121 tp = BCDUMP_KGC_STR + gco2str(o)->len;
@@ -181,24 +142,26 @@ static void bcwrite_kgc(BCWriteCtx *ctx, GCproto *pt)
181 need = 1+2*5; 142 need = 1+2*5;
182 } 143 }
183 /* Write constant type. */ 144 /* Write constant type. */
184 bcwrite_need(ctx, need); 145 p = lj_buf_more(&ctx->sb, need);
185 bcwrite_uleb128(ctx, tp); 146 p = lj_strfmt_wuleb128(p, tp);
186 /* Write constant data (if any). */ 147 /* Write constant data (if any). */
187 if (tp >= BCDUMP_KGC_STR) { 148 if (tp >= BCDUMP_KGC_STR) {
188 bcwrite_block(ctx, strdata(gco2str(o)), gco2str(o)->len); 149 p = lj_buf_wmem(p, strdata(gco2str(o)), gco2str(o)->len);
189 } else if (tp == BCDUMP_KGC_TAB) { 150 } else if (tp == BCDUMP_KGC_TAB) {
190 bcwrite_ktab(ctx, gco2tab(o)); 151 bcwrite_ktab(ctx, p, gco2tab(o));
152 continue;
191#if LJ_HASFFI 153#if LJ_HASFFI
192 } else if (tp != BCDUMP_KGC_CHILD) { 154 } else if (tp != BCDUMP_KGC_CHILD) {
193 cTValue *p = (TValue *)cdataptr(gco2cd(o)); 155 cTValue *q = (TValue *)cdataptr(gco2cd(o));
194 bcwrite_uleb128(ctx, p[0].u32.lo); 156 p = lj_strfmt_wuleb128(p, q[0].u32.lo);
195 bcwrite_uleb128(ctx, p[0].u32.hi); 157 p = lj_strfmt_wuleb128(p, q[0].u32.hi);
196 if (tp == BCDUMP_KGC_COMPLEX) { 158 if (tp == BCDUMP_KGC_COMPLEX) {
197 bcwrite_uleb128(ctx, p[1].u32.lo); 159 p = lj_strfmt_wuleb128(p, q[1].u32.lo);
198 bcwrite_uleb128(ctx, p[1].u32.hi); 160 p = lj_strfmt_wuleb128(p, q[1].u32.hi);
199 } 161 }
200#endif 162#endif
201 } 163 }
164 setsbufP(&ctx->sb, p);
202 } 165 }
203} 166}
204 167
@@ -207,7 +170,7 @@ static void bcwrite_knum(BCWriteCtx *ctx, GCproto *pt)
207{ 170{
208 MSize i, sizekn = pt->sizekn; 171 MSize i, sizekn = pt->sizekn;
209 cTValue *o = mref(pt->k, TValue); 172 cTValue *o = mref(pt->k, TValue);
210 bcwrite_need(ctx, 10*sizekn); 173 char *p = lj_buf_more(&ctx->sb, 10*sizekn);
211 for (i = 0; i < sizekn; i++, o++) { 174 for (i = 0; i < sizekn; i++, o++) {
212 int32_t k; 175 int32_t k;
213 if (tvisint(o)) { 176 if (tvisint(o)) {
@@ -220,58 +183,58 @@ static void bcwrite_knum(BCWriteCtx *ctx, GCproto *pt)
220 k = lj_num2int(num); 183 k = lj_num2int(num);
221 if (num == (lua_Number)k) { /* -0 is never a constant. */ 184 if (num == (lua_Number)k) { /* -0 is never a constant. */
222 save_int: 185 save_int:
223 bcwrite_uleb128(ctx, 2*(uint32_t)k | ((uint32_t)k & 0x80000000u)); 186 p = lj_strfmt_wuleb128(p, 2*(uint32_t)k | ((uint32_t)k&0x80000000u));
224 if (k < 0) { 187 if (k < 0)
225 char *p = &ctx->sb.buf[ctx->sb.n-1]; 188 p[-1] = (p[-1] & 7) | ((k>>27) & 0x18);
226 *p = (*p & 7) | ((k>>27) & 0x18);
227 }
228 continue; 189 continue;
229 } 190 }
230 } 191 }
231 bcwrite_uleb128(ctx, 1+(2*o->u32.lo | (o->u32.lo & 0x80000000u))); 192 p = lj_strfmt_wuleb128(p, 1+(2*o->u32.lo | (o->u32.lo & 0x80000000u)));
232 if (o->u32.lo >= 0x80000000u) { 193 if (o->u32.lo >= 0x80000000u)
233 char *p = &ctx->sb.buf[ctx->sb.n-1]; 194 p[-1] = (p[-1] & 7) | ((o->u32.lo>>27) & 0x18);
234 *p = (*p & 7) | ((o->u32.lo>>27) & 0x18); 195 p = lj_strfmt_wuleb128(p, o->u32.hi);
235 }
236 bcwrite_uleb128(ctx, o->u32.hi);
237 } 196 }
238 } 197 }
198 setsbufP(&ctx->sb, p);
239} 199}
240 200
241/* Write bytecode instructions. */ 201/* Write bytecode instructions. */
242static void bcwrite_bytecode(BCWriteCtx *ctx, GCproto *pt) 202static char *bcwrite_bytecode(BCWriteCtx *ctx, char *p, GCproto *pt)
243{ 203{
244 MSize nbc = pt->sizebc-1; /* Omit the [JI]FUNC* header. */ 204 MSize nbc = pt->sizebc-1; /* Omit the [JI]FUNC* header. */
245#if LJ_HASJIT 205#if LJ_HASJIT
246 uint8_t *p = (uint8_t *)&ctx->sb.buf[ctx->sb.n]; 206 uint8_t *q = (uint8_t *)p;
247#endif 207#endif
248 bcwrite_block(ctx, proto_bc(pt)+1, nbc*(MSize)sizeof(BCIns)); 208 p = lj_buf_wmem(p, proto_bc(pt)+1, nbc*(MSize)sizeof(BCIns));
209 UNUSED(ctx);
249#if LJ_HASJIT 210#if LJ_HASJIT
250 /* Unpatch modified bytecode containing ILOOP/JLOOP etc. */ 211 /* Unpatch modified bytecode containing ILOOP/JLOOP etc. */
251 if ((pt->flags & PROTO_ILOOP) || pt->trace) { 212 if ((pt->flags & PROTO_ILOOP) || pt->trace) {
252 jit_State *J = L2J(ctx->L); 213 jit_State *J = L2J(sbufL(&ctx->sb));
253 MSize i; 214 MSize i;
254 for (i = 0; i < nbc; i++, p += sizeof(BCIns)) { 215 for (i = 0; i < nbc; i++, q += sizeof(BCIns)) {
255 BCOp op = (BCOp)p[LJ_ENDIAN_SELECT(0, 3)]; 216 BCOp op = (BCOp)q[LJ_ENDIAN_SELECT(0, 3)];
256 if (op == BC_IFORL || op == BC_IITERL || op == BC_ILOOP || 217 if (op == BC_IFORL || op == BC_IITERL || op == BC_ILOOP ||
257 op == BC_JFORI) { 218 op == BC_JFORI) {
258 p[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_IFORL+BC_FORL); 219 q[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_IFORL+BC_FORL);
259 } else if (op == BC_JFORL || op == BC_JITERL || op == BC_JLOOP) { 220 } else if (op == BC_JFORL || op == BC_JITERL || op == BC_JLOOP) {
260 BCReg rd = p[LJ_ENDIAN_SELECT(2, 1)] + (p[LJ_ENDIAN_SELECT(3, 0)] << 8); 221 BCReg rd = q[LJ_ENDIAN_SELECT(2, 1)] + (q[LJ_ENDIAN_SELECT(3, 0)] << 8);
261 BCIns ins = traceref(J, rd)->startins; 222 BCIns ins = traceref(J, rd)->startins;
262 p[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_JFORL+BC_FORL); 223 q[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_JFORL+BC_FORL);
263 p[LJ_ENDIAN_SELECT(2, 1)] = bc_c(ins); 224 q[LJ_ENDIAN_SELECT(2, 1)] = bc_c(ins);
264 p[LJ_ENDIAN_SELECT(3, 0)] = bc_b(ins); 225 q[LJ_ENDIAN_SELECT(3, 0)] = bc_b(ins);
265 } 226 }
266 } 227 }
267 } 228 }
268#endif 229#endif
230 return p;
269} 231}
270 232
271/* Write prototype. */ 233/* Write prototype. */
272static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt) 234static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt)
273{ 235{
274 MSize sizedbg = 0; 236 MSize sizedbg = 0;
237 char *p;
275 238
276 /* Recursively write children of prototype. */ 239 /* Recursively write children of prototype. */
277 if ((pt->flags & PROTO_CHILD)) { 240 if ((pt->flags & PROTO_CHILD)) {
@@ -285,31 +248,32 @@ static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt)
285 } 248 }
286 249
287 /* Start writing the prototype info to a buffer. */ 250 /* Start writing the prototype info to a buffer. */
288 lj_str_resetbuf(&ctx->sb); 251 p = lj_buf_need(&ctx->sb,
289 ctx->sb.n = 5; /* Leave room for final size. */ 252 5+4+6*5+(pt->sizebc-1)*(MSize)sizeof(BCIns)+pt->sizeuv*2);
290 bcwrite_need(ctx, 4+6*5+(pt->sizebc-1)*(MSize)sizeof(BCIns)+pt->sizeuv*2); 253 p += 5; /* Leave room for final size. */
291 254
292 /* Write prototype header. */ 255 /* Write prototype header. */
293 bcwrite_byte(ctx, (pt->flags & (PROTO_CHILD|PROTO_VARARG|PROTO_FFI))); 256 *p++ = (pt->flags & (PROTO_CHILD|PROTO_VARARG|PROTO_FFI));
294 bcwrite_byte(ctx, pt->numparams); 257 *p++ = pt->numparams;
295 bcwrite_byte(ctx, pt->framesize); 258 *p++ = pt->framesize;
296 bcwrite_byte(ctx, pt->sizeuv); 259 *p++ = pt->sizeuv;
297 bcwrite_uleb128(ctx, pt->sizekgc); 260 p = lj_strfmt_wuleb128(p, pt->sizekgc);
298 bcwrite_uleb128(ctx, pt->sizekn); 261 p = lj_strfmt_wuleb128(p, pt->sizekn);
299 bcwrite_uleb128(ctx, pt->sizebc-1); 262 p = lj_strfmt_wuleb128(p, pt->sizebc-1);
300 if (!ctx->strip) { 263 if (!ctx->strip) {
301 if (proto_lineinfo(pt)) 264 if (proto_lineinfo(pt))
302 sizedbg = pt->sizept - (MSize)((char *)proto_lineinfo(pt) - (char *)pt); 265 sizedbg = pt->sizept - (MSize)((char *)proto_lineinfo(pt) - (char *)pt);
303 bcwrite_uleb128(ctx, sizedbg); 266 p = lj_strfmt_wuleb128(p, sizedbg);
304 if (sizedbg) { 267 if (sizedbg) {
305 bcwrite_uleb128(ctx, pt->firstline); 268 p = lj_strfmt_wuleb128(p, pt->firstline);
306 bcwrite_uleb128(ctx, pt->numline); 269 p = lj_strfmt_wuleb128(p, pt->numline);
307 } 270 }
308 } 271 }
309 272
310 /* Write bytecode instructions and upvalue refs. */ 273 /* Write bytecode instructions and upvalue refs. */
311 bcwrite_bytecode(ctx, pt); 274 p = bcwrite_bytecode(ctx, p, pt);
312 bcwrite_block(ctx, proto_uv(pt), pt->sizeuv*2); 275 p = lj_buf_wmem(p, proto_uv(pt), pt->sizeuv*2);
276 setsbufP(&ctx->sb, p);
313 277
314 /* Write constants. */ 278 /* Write constants. */
315 bcwrite_kgc(ctx, pt); 279 bcwrite_kgc(ctx, pt);
@@ -317,18 +281,19 @@ static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt)
317 281
318 /* Write debug info, if not stripped. */ 282 /* Write debug info, if not stripped. */
319 if (sizedbg) { 283 if (sizedbg) {
320 bcwrite_need(ctx, sizedbg); 284 p = lj_buf_more(&ctx->sb, sizedbg);
321 bcwrite_block(ctx, proto_lineinfo(pt), sizedbg); 285 p = lj_buf_wmem(p, proto_lineinfo(pt), sizedbg);
286 setsbufP(&ctx->sb, p);
322 } 287 }
323 288
324 /* Pass buffer to writer function. */ 289 /* Pass buffer to writer function. */
325 if (ctx->status == 0) { 290 if (ctx->status == 0) {
326 MSize n = ctx->sb.n - 5; 291 MSize n = sbuflen(&ctx->sb) - 5;
327 MSize nn = (lj_fls(n)+8)*9 >> 6; 292 MSize nn = (lj_fls(n)+8)*9 >> 6;
328 ctx->sb.n = 5 - nn; 293 char *q = sbufB(&ctx->sb) + (5 - nn);
329 bcwrite_uleb128(ctx, n); /* Fill in final size. */ 294 p = lj_strfmt_wuleb128(q, n); /* Fill in final size. */
330 lua_assert(ctx->sb.n == 5); 295 lua_assert(p == sbufB(&ctx->sb) + 5);
331 ctx->status = ctx->wfunc(ctx->L, ctx->sb.buf+5-nn, nn+n, ctx->wdata); 296 ctx->status = ctx->wfunc(sbufL(&ctx->sb), q, nn+n, ctx->wdata);
332 } 297 }
333} 298}
334 299
@@ -338,20 +303,21 @@ static void bcwrite_header(BCWriteCtx *ctx)
338 GCstr *chunkname = proto_chunkname(ctx->pt); 303 GCstr *chunkname = proto_chunkname(ctx->pt);
339 const char *name = strdata(chunkname); 304 const char *name = strdata(chunkname);
340 MSize len = chunkname->len; 305 MSize len = chunkname->len;
341 lj_str_resetbuf(&ctx->sb); 306 char *p = lj_buf_need(&ctx->sb, 5+5+len);
342 bcwrite_need(ctx, 5+5+len); 307 *p++ = BCDUMP_HEAD1;
343 bcwrite_byte(ctx, BCDUMP_HEAD1); 308 *p++ = BCDUMP_HEAD2;
344 bcwrite_byte(ctx, BCDUMP_HEAD2); 309 *p++ = BCDUMP_HEAD3;
345 bcwrite_byte(ctx, BCDUMP_HEAD3); 310 *p++ = BCDUMP_VERSION;
346 bcwrite_byte(ctx, BCDUMP_VERSION); 311 *p++ = (ctx->strip ? BCDUMP_F_STRIP : 0) +
347 bcwrite_byte(ctx, (ctx->strip ? BCDUMP_F_STRIP : 0) + 312 LJ_BE*BCDUMP_F_BE +
348 (LJ_BE ? BCDUMP_F_BE : 0) + 313 ((ctx->pt->flags & PROTO_FFI) ? BCDUMP_F_FFI : 0) +
349 ((ctx->pt->flags & PROTO_FFI) ? BCDUMP_F_FFI : 0)); 314 LJ_FR2*BCDUMP_F_FR2;
350 if (!ctx->strip) { 315 if (!ctx->strip) {
351 bcwrite_uleb128(ctx, len); 316 p = lj_strfmt_wuleb128(p, len);
352 bcwrite_block(ctx, name, len); 317 p = lj_buf_wmem(p, name, len);
353 } 318 }
354 ctx->status = ctx->wfunc(ctx->L, ctx->sb.buf, ctx->sb.n, ctx->wdata); 319 ctx->status = ctx->wfunc(sbufL(&ctx->sb), sbufB(&ctx->sb),
320 (MSize)(p - sbufB(&ctx->sb)), ctx->wdata);
355} 321}
356 322
357/* Write footer of bytecode dump. */ 323/* Write footer of bytecode dump. */
@@ -359,7 +325,7 @@ static void bcwrite_footer(BCWriteCtx *ctx)
359{ 325{
360 if (ctx->status == 0) { 326 if (ctx->status == 0) {
361 uint8_t zero = 0; 327 uint8_t zero = 0;
362 ctx->status = ctx->wfunc(ctx->L, &zero, 1, ctx->wdata); 328 ctx->status = ctx->wfunc(sbufL(&ctx->sb), &zero, 1, ctx->wdata);
363 } 329 }
364} 330}
365 331
@@ -367,8 +333,8 @@ static void bcwrite_footer(BCWriteCtx *ctx)
367static TValue *cpwriter(lua_State *L, lua_CFunction dummy, void *ud) 333static TValue *cpwriter(lua_State *L, lua_CFunction dummy, void *ud)
368{ 334{
369 BCWriteCtx *ctx = (BCWriteCtx *)ud; 335 BCWriteCtx *ctx = (BCWriteCtx *)ud;
370 UNUSED(dummy); 336 UNUSED(L); UNUSED(dummy);
371 lj_str_resizebuf(L, &ctx->sb, 1024); /* Avoids resize for most prototypes. */ 337 lj_buf_need(&ctx->sb, 1024); /* Avoids resize for most prototypes. */
372 bcwrite_header(ctx); 338 bcwrite_header(ctx);
373 bcwrite_proto(ctx, ctx->pt); 339 bcwrite_proto(ctx, ctx->pt);
374 bcwrite_footer(ctx); 340 bcwrite_footer(ctx);
@@ -381,16 +347,15 @@ int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, void *data,
381{ 347{
382 BCWriteCtx ctx; 348 BCWriteCtx ctx;
383 int status; 349 int status;
384 ctx.L = L;
385 ctx.pt = pt; 350 ctx.pt = pt;
386 ctx.wfunc = writer; 351 ctx.wfunc = writer;
387 ctx.wdata = data; 352 ctx.wdata = data;
388 ctx.strip = strip; 353 ctx.strip = strip;
389 ctx.status = 0; 354 ctx.status = 0;
390 lj_str_initbuf(&ctx.sb); 355 lj_buf_init(L, &ctx.sb);
391 status = lj_vm_cpcall(L, NULL, &ctx, cpwriter); 356 status = lj_vm_cpcall(L, NULL, &ctx, cpwriter);
392 if (status == 0) status = ctx.status; 357 if (status == 0) status = ctx.status;
393 lj_str_freebuf(G(ctx.L), &ctx.sb); 358 lj_buf_free(G(sbufL(&ctx.sb)), &ctx.sb);
394 return status; 359 return status;
395} 360}
396 361
diff --git a/src/lj_buf.c b/src/lj_buf.c
new file mode 100644
index 00000000..0dfe7f98
--- /dev/null
+++ b/src/lj_buf.c
@@ -0,0 +1,232 @@
1/*
2** Buffer handling.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#define lj_buf_c
7#define LUA_CORE
8
9#include "lj_obj.h"
10#include "lj_gc.h"
11#include "lj_err.h"
12#include "lj_buf.h"
13#include "lj_str.h"
14#include "lj_tab.h"
15#include "lj_strfmt.h"
16
17/* -- Buffer management --------------------------------------------------- */
18
19static void buf_grow(SBuf *sb, MSize sz)
20{
21 MSize osz = sbufsz(sb), len = sbuflen(sb), nsz = osz;
22 char *b;
23 if (nsz < LJ_MIN_SBUF) nsz = LJ_MIN_SBUF;
24 while (nsz < sz) nsz += nsz;
25 b = (char *)lj_mem_realloc(sbufL(sb), sbufB(sb), osz, nsz);
26 setmref(sb->b, b);
27 setmref(sb->p, b + len);
28 setmref(sb->e, b + nsz);
29}
30
31LJ_NOINLINE char *LJ_FASTCALL lj_buf_need2(SBuf *sb, MSize sz)
32{
33 lua_assert(sz > sbufsz(sb));
34 if (LJ_UNLIKELY(sz > LJ_MAX_BUF))
35 lj_err_mem(sbufL(sb));
36 buf_grow(sb, sz);
37 return sbufB(sb);
38}
39
40LJ_NOINLINE char *LJ_FASTCALL lj_buf_more2(SBuf *sb, MSize sz)
41{
42 MSize len = sbuflen(sb);
43 lua_assert(sz > sbufleft(sb));
44 if (LJ_UNLIKELY(sz > LJ_MAX_BUF || len + sz > LJ_MAX_BUF))
45 lj_err_mem(sbufL(sb));
46 buf_grow(sb, len + sz);
47 return sbufP(sb);
48}
49
50void LJ_FASTCALL lj_buf_shrink(lua_State *L, SBuf *sb)
51{
52 char *b = sbufB(sb);
53 MSize osz = (MSize)(sbufE(sb) - b);
54 if (osz > 2*LJ_MIN_SBUF) {
55 MSize n = (MSize)(sbufP(sb) - b);
56 b = lj_mem_realloc(L, b, osz, (osz >> 1));
57 setmref(sb->b, b);
58 setmref(sb->p, b + n);
59 setmref(sb->e, b + (osz >> 1));
60 }
61}
62
63char * LJ_FASTCALL lj_buf_tmp(lua_State *L, MSize sz)
64{
65 SBuf *sb = &G(L)->tmpbuf;
66 setsbufL(sb, L);
67 return lj_buf_need(sb, sz);
68}
69
70/* -- Low-level buffer put operations ------------------------------------- */
71
72SBuf *lj_buf_putmem(SBuf *sb, const void *q, MSize len)
73{
74 char *p = lj_buf_more(sb, len);
75 p = lj_buf_wmem(p, q, len);
76 setsbufP(sb, p);
77 return sb;
78}
79
80SBuf * LJ_FASTCALL lj_buf_putchar(SBuf *sb, int c)
81{
82 char *p = lj_buf_more(sb, 1);
83 *p++ = (char)c;
84 setsbufP(sb, p);
85 return sb;
86}
87
88SBuf * LJ_FASTCALL lj_buf_putstr(SBuf *sb, GCstr *s)
89{
90 MSize len = s->len;
91 char *p = lj_buf_more(sb, len);
92 p = lj_buf_wmem(p, strdata(s), len);
93 setsbufP(sb, p);
94 return sb;
95}
96
97/* -- High-level buffer put operations ------------------------------------ */
98
99SBuf * LJ_FASTCALL lj_buf_putstr_reverse(SBuf *sb, GCstr *s)
100{
101 MSize len = s->len;
102 char *p = lj_buf_more(sb, len), *e = p+len;
103 const char *q = strdata(s)+len-1;
104 while (p < e)
105 *p++ = *q--;
106 setsbufP(sb, p);
107 return sb;
108}
109
110SBuf * LJ_FASTCALL lj_buf_putstr_lower(SBuf *sb, GCstr *s)
111{
112 MSize len = s->len;
113 char *p = lj_buf_more(sb, len), *e = p+len;
114 const char *q = strdata(s);
115 for (; p < e; p++, q++) {
116 uint32_t c = *(unsigned char *)q;
117#if LJ_TARGET_PPC
118 *p = c + ((c >= 'A' && c <= 'Z') << 5);
119#else
120 if (c >= 'A' && c <= 'Z') c += 0x20;
121 *p = c;
122#endif
123 }
124 setsbufP(sb, p);
125 return sb;
126}
127
128SBuf * LJ_FASTCALL lj_buf_putstr_upper(SBuf *sb, GCstr *s)
129{
130 MSize len = s->len;
131 char *p = lj_buf_more(sb, len), *e = p+len;
132 const char *q = strdata(s);
133 for (; p < e; p++, q++) {
134 uint32_t c = *(unsigned char *)q;
135#if LJ_TARGET_PPC
136 *p = c - ((c >= 'a' && c <= 'z') << 5);
137#else
138 if (c >= 'a' && c <= 'z') c -= 0x20;
139 *p = c;
140#endif
141 }
142 setsbufP(sb, p);
143 return sb;
144}
145
146SBuf *lj_buf_putstr_rep(SBuf *sb, GCstr *s, int32_t rep)
147{
148 MSize len = s->len;
149 if (rep > 0 && len) {
150 uint64_t tlen = (uint64_t)rep * len;
151 char *p;
152 if (LJ_UNLIKELY(tlen > LJ_MAX_STR))
153 lj_err_mem(sbufL(sb));
154 p = lj_buf_more(sb, (MSize)tlen);
155 if (len == 1) { /* Optimize a common case. */
156 uint32_t c = strdata(s)[0];
157 do { *p++ = c; } while (--rep > 0);
158 } else {
159 const char *e = strdata(s) + len;
160 do {
161 const char *q = strdata(s);
162 do { *p++ = *q++; } while (q < e);
163 } while (--rep > 0);
164 }
165 setsbufP(sb, p);
166 }
167 return sb;
168}
169
170SBuf *lj_buf_puttab(SBuf *sb, GCtab *t, GCstr *sep, int32_t i, int32_t e)
171{
172 MSize seplen = sep ? sep->len : 0;
173 if (i <= e) {
174 for (;;) {
175 cTValue *o = lj_tab_getint(t, i);
176 char *p;
177 if (!o) {
178 badtype: /* Error: bad element type. */
179 setsbufP(sb, (void *)(intptr_t)i); /* Store failing index. */
180 return NULL;
181 } else if (tvisstr(o)) {
182 MSize len = strV(o)->len;
183 p = lj_buf_wmem(lj_buf_more(sb, len + seplen), strVdata(o), len);
184 } else if (tvisint(o)) {
185 p = lj_strfmt_wint(lj_buf_more(sb, STRFMT_MAXBUF_INT+seplen), intV(o));
186 } else if (tvisnum(o)) {
187 p = lj_buf_more(lj_strfmt_putfnum(sb, STRFMT_G14, numV(o)), seplen);
188 } else {
189 goto badtype;
190 }
191 if (i++ == e) {
192 setsbufP(sb, p);
193 break;
194 }
195 if (seplen) p = lj_buf_wmem(p, strdata(sep), seplen);
196 setsbufP(sb, p);
197 }
198 }
199 return sb;
200}
201
202/* -- Miscellaneous buffer operations ------------------------------------- */
203
204GCstr * LJ_FASTCALL lj_buf_tostr(SBuf *sb)
205{
206 return lj_str_new(sbufL(sb), sbufB(sb), sbuflen(sb));
207}
208
209/* Concatenate two strings. */
210GCstr *lj_buf_cat2str(lua_State *L, GCstr *s1, GCstr *s2)
211{
212 MSize len1 = s1->len, len2 = s2->len;
213 char *buf = lj_buf_tmp(L, len1 + len2);
214 memcpy(buf, strdata(s1), len1);
215 memcpy(buf+len1, strdata(s2), len2);
216 return lj_str_new(L, buf, len1 + len2);
217}
218
219/* Read ULEB128 from buffer. */
220uint32_t LJ_FASTCALL lj_buf_ruleb128(const char **pp)
221{
222 const uint8_t *p = (const uint8_t *)*pp;
223 uint32_t v = *p++;
224 if (LJ_UNLIKELY(v >= 0x80)) {
225 int sh = 0;
226 v &= 0x7f;
227 do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80);
228 }
229 *pp = (const char *)p;
230 return v;
231}
232
diff --git a/src/lj_buf.h b/src/lj_buf.h
new file mode 100644
index 00000000..a4051694
--- /dev/null
+++ b/src/lj_buf.h
@@ -0,0 +1,103 @@
1/*
2** Buffer handling.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_BUF_H
7#define _LJ_BUF_H
8
9#include "lj_obj.h"
10#include "lj_gc.h"
11#include "lj_str.h"
12
13/* Resizable string buffers. Struct definition in lj_obj.h. */
14#define sbufB(sb) (mref((sb)->b, char))
15#define sbufP(sb) (mref((sb)->p, char))
16#define sbufE(sb) (mref((sb)->e, char))
17#define sbufL(sb) (mref((sb)->L, lua_State))
18#define sbufsz(sb) ((MSize)(sbufE((sb)) - sbufB((sb))))
19#define sbuflen(sb) ((MSize)(sbufP((sb)) - sbufB((sb))))
20#define sbufleft(sb) ((MSize)(sbufE((sb)) - sbufP((sb))))
21#define setsbufP(sb, q) (setmref((sb)->p, (q)))
22#define setsbufL(sb, l) (setmref((sb)->L, (l)))
23
24/* Buffer management */
25LJ_FUNC char *LJ_FASTCALL lj_buf_need2(SBuf *sb, MSize sz);
26LJ_FUNC char *LJ_FASTCALL lj_buf_more2(SBuf *sb, MSize sz);
27LJ_FUNC void LJ_FASTCALL lj_buf_shrink(lua_State *L, SBuf *sb);
28LJ_FUNC char * LJ_FASTCALL lj_buf_tmp(lua_State *L, MSize sz);
29
30static LJ_AINLINE void lj_buf_init(lua_State *L, SBuf *sb)
31{
32 setsbufL(sb, L);
33 setmref(sb->p, NULL); setmref(sb->e, NULL); setmref(sb->b, NULL);
34}
35
36static LJ_AINLINE void lj_buf_reset(SBuf *sb)
37{
38 setmrefr(sb->p, sb->b);
39}
40
41static LJ_AINLINE SBuf *lj_buf_tmp_(lua_State *L)
42{
43 SBuf *sb = &G(L)->tmpbuf;
44 setsbufL(sb, L);
45 lj_buf_reset(sb);
46 return sb;
47}
48
49static LJ_AINLINE void lj_buf_free(global_State *g, SBuf *sb)
50{
51 lj_mem_free(g, sbufB(sb), sbufsz(sb));
52}
53
54static LJ_AINLINE char *lj_buf_need(SBuf *sb, MSize sz)
55{
56 if (LJ_UNLIKELY(sz > sbufsz(sb)))
57 return lj_buf_need2(sb, sz);
58 return sbufB(sb);
59}
60
61static LJ_AINLINE char *lj_buf_more(SBuf *sb, MSize sz)
62{
63 if (LJ_UNLIKELY(sz > sbufleft(sb)))
64 return lj_buf_more2(sb, sz);
65 return sbufP(sb);
66}
67
68/* Low-level buffer put operations */
69LJ_FUNC SBuf *lj_buf_putmem(SBuf *sb, const void *q, MSize len);
70LJ_FUNC SBuf * LJ_FASTCALL lj_buf_putchar(SBuf *sb, int c);
71LJ_FUNC SBuf * LJ_FASTCALL lj_buf_putstr(SBuf *sb, GCstr *s);
72
73static LJ_AINLINE char *lj_buf_wmem(char *p, const void *q, MSize len)
74{
75 return (char *)memcpy(p, q, len) + len;
76}
77
78static LJ_AINLINE void lj_buf_putb(SBuf *sb, int c)
79{
80 char *p = lj_buf_more(sb, 1);
81 *p++ = (char)c;
82 setsbufP(sb, p);
83}
84
85/* High-level buffer put operations */
86LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_reverse(SBuf *sb, GCstr *s);
87LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_lower(SBuf *sb, GCstr *s);
88LJ_FUNCA SBuf * LJ_FASTCALL lj_buf_putstr_upper(SBuf *sb, GCstr *s);
89LJ_FUNC SBuf *lj_buf_putstr_rep(SBuf *sb, GCstr *s, int32_t rep);
90LJ_FUNC SBuf *lj_buf_puttab(SBuf *sb, GCtab *t, GCstr *sep,
91 int32_t i, int32_t e);
92
93/* Miscellaneous buffer operations */
94LJ_FUNCA GCstr * LJ_FASTCALL lj_buf_tostr(SBuf *sb);
95LJ_FUNC GCstr *lj_buf_cat2str(lua_State *L, GCstr *s1, GCstr *s2);
96LJ_FUNC uint32_t LJ_FASTCALL lj_buf_ruleb128(const char **pp);
97
98static LJ_AINLINE GCstr *lj_buf_str(lua_State *L, SBuf *sb)
99{
100 return lj_str_new(L, sbufB(sb), sbuflen(sb));
101}
102
103#endif
diff --git a/src/lj_carith.c b/src/lj_carith.c
index 6224dee6..218abd26 100644
--- a/src/lj_carith.c
+++ b/src/lj_carith.c
@@ -11,10 +11,12 @@
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_tab.h" 12#include "lj_tab.h"
13#include "lj_meta.h" 13#include "lj_meta.h"
14#include "lj_ir.h"
14#include "lj_ctype.h" 15#include "lj_ctype.h"
15#include "lj_cconv.h" 16#include "lj_cconv.h"
16#include "lj_cdata.h" 17#include "lj_cdata.h"
17#include "lj_carith.h" 18#include "lj_carith.h"
19#include "lj_strscan.h"
18 20
19/* -- C data arithmetic --------------------------------------------------- */ 21/* -- C data arithmetic --------------------------------------------------- */
20 22
@@ -272,6 +274,80 @@ int lj_carith_op(lua_State *L, MMS mm)
272 return lj_carith_meta(L, cts, &ca, mm); 274 return lj_carith_meta(L, cts, &ca, mm);
273} 275}
274 276
277/* -- 64 bit bit operations helpers --------------------------------------- */
278
279#if LJ_64
280#define B64DEF(name) \
281 static LJ_AINLINE uint64_t lj_carith_##name(uint64_t x, int32_t sh)
282#else
283/* Not inlined on 32 bit archs, since some of these are quite lengthy. */
284#define B64DEF(name) \
285 uint64_t LJ_NOINLINE lj_carith_##name(uint64_t x, int32_t sh)
286#endif
287
288B64DEF(shl64) { return x << (sh&63); }
289B64DEF(shr64) { return x >> (sh&63); }
290B64DEF(sar64) { return (uint64_t)((int64_t)x >> (sh&63)); }
291B64DEF(rol64) { return lj_rol(x, (sh&63)); }
292B64DEF(ror64) { return lj_ror(x, (sh&63)); }
293
294#undef B64DEF
295
296uint64_t lj_carith_shift64(uint64_t x, int32_t sh, int op)
297{
298 switch (op) {
299 case IR_BSHL-IR_BSHL: x = lj_carith_shl64(x, sh); break;
300 case IR_BSHR-IR_BSHL: x = lj_carith_shr64(x, sh); break;
301 case IR_BSAR-IR_BSHL: x = lj_carith_sar64(x, sh); break;
302 case IR_BROL-IR_BSHL: x = lj_carith_rol64(x, sh); break;
303 case IR_BROR-IR_BSHL: x = lj_carith_ror64(x, sh); break;
304 default: lua_assert(0); break;
305 }
306 return x;
307}
308
309/* Equivalent to lj_lib_checkbit(), but handles cdata. */
310uint64_t lj_carith_check64(lua_State *L, int narg, CTypeID *id)
311{
312 TValue *o = L->base + narg-1;
313 if (o >= L->top) {
314 err:
315 lj_err_argt(L, narg, LUA_TNUMBER);
316 } else if (LJ_LIKELY(tvisnumber(o))) {
317 /* Handled below. */
318 } else if (tviscdata(o)) {
319 CTState *cts = ctype_cts(L);
320 uint8_t *sp = (uint8_t *)cdataptr(cdataV(o));
321 CTypeID sid = cdataV(o)->ctypeid;
322 CType *s = ctype_get(cts, sid);
323 uint64_t x;
324 if (ctype_isref(s->info)) {
325 sp = *(void **)sp;
326 sid = ctype_cid(s->info);
327 }
328 s = ctype_raw(cts, sid);
329 if (ctype_isenum(s->info)) s = ctype_child(cts, s);
330 if ((s->info & (CTMASK_NUM|CTF_BOOL|CTF_FP|CTF_UNSIGNED)) ==
331 CTINFO(CT_NUM, CTF_UNSIGNED) && s->size == 8)
332 *id = CTID_UINT64; /* Use uint64_t, since it has the highest rank. */
333 else if (!*id)
334 *id = CTID_INT64; /* Use int64_t, unless already set. */
335 lj_cconv_ct_ct(cts, ctype_get(cts, *id), s,
336 (uint8_t *)&x, sp, CCF_ARG(narg));
337 return x;
338 } else if (!(tvisstr(o) && lj_strscan_number(strV(o), o))) {
339 goto err;
340 }
341 if (LJ_LIKELY(tvisint(o))) {
342 return (uint32_t)intV(o);
343 } else {
344 int32_t i = lj_num2bit(numV(o));
345 if (LJ_DUALNUM) setintV(o, i);
346 return (uint32_t)i;
347 }
348}
349
350
275/* -- 64 bit integer arithmetic helpers ----------------------------------- */ 351/* -- 64 bit integer arithmetic helpers ----------------------------------- */
276 352
277#if LJ_32 && LJ_HASJIT 353#if LJ_32 && LJ_HASJIT
diff --git a/src/lj_carith.h b/src/lj_carith.h
index 3c155910..67d976bf 100644
--- a/src/lj_carith.h
+++ b/src/lj_carith.h
@@ -12,6 +12,16 @@
12 12
13LJ_FUNC int lj_carith_op(lua_State *L, MMS mm); 13LJ_FUNC int lj_carith_op(lua_State *L, MMS mm);
14 14
15#if LJ_32
16LJ_FUNC uint64_t lj_carith_shl64(uint64_t x, int32_t sh);
17LJ_FUNC uint64_t lj_carith_shr64(uint64_t x, int32_t sh);
18LJ_FUNC uint64_t lj_carith_sar64(uint64_t x, int32_t sh);
19LJ_FUNC uint64_t lj_carith_rol64(uint64_t x, int32_t sh);
20LJ_FUNC uint64_t lj_carith_ror64(uint64_t x, int32_t sh);
21#endif
22LJ_FUNC uint64_t lj_carith_shift64(uint64_t x, int32_t sh, int op);
23LJ_FUNC uint64_t lj_carith_check64(lua_State *L, int narg, CTypeID *id);
24
15#if LJ_32 && LJ_HASJIT 25#if LJ_32 && LJ_HASJIT
16LJ_FUNC int64_t lj_carith_mul64(int64_t x, int64_t k); 26LJ_FUNC int64_t lj_carith_mul64(int64_t x, int64_t k);
17#endif 27#endif
diff --git a/src/lj_ccall.c b/src/lj_ccall.c
index 65076e77..2b7ca364 100644
--- a/src/lj_ccall.c
+++ b/src/lj_ccall.c
@@ -9,7 +9,6 @@
9 9
10#include "lj_gc.h" 10#include "lj_gc.h"
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_str.h"
13#include "lj_tab.h" 12#include "lj_tab.h"
14#include "lj_ctype.h" 13#include "lj_ctype.h"
15#include "lj_cconv.h" 14#include "lj_cconv.h"
@@ -291,6 +290,75 @@
291#define CCALL_HANDLE_RET \ 290#define CCALL_HANDLE_RET \
292 if ((ct->info & CTF_VARARG)) sp = (uint8_t *)&cc->gpr[0]; 291 if ((ct->info & CTF_VARARG)) sp = (uint8_t *)&cc->gpr[0];
293 292
293#elif LJ_TARGET_ARM64
294/* -- ARM64 calling conventions ------------------------------------------- */
295
296#define CCALL_HANDLE_STRUCTRET \
297 cc->retref = !ccall_classify_struct(cts, ctr); \
298 if (cc->retref) cc->retp = dp;
299
300#define CCALL_HANDLE_STRUCTRET2 \
301 unsigned int cl = ccall_classify_struct(cts, ctr); \
302 if ((cl & 4)) { /* Combine float HFA from separate registers. */ \
303 CTSize i = (cl >> 8) - 1; \
304 do { ((uint32_t *)dp)[i] = cc->fpr[i].u32; } while (i--); \
305 } else { \
306 if (cl > 1) sp = (uint8_t *)&cc->fpr[0]; \
307 memcpy(dp, sp, ctr->size); \
308 }
309
310#define CCALL_HANDLE_COMPLEXRET \
311 /* Complex values are returned in one or two FPRs. */ \
312 cc->retref = 0;
313
314#define CCALL_HANDLE_COMPLEXRET2 \
315 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \
316 ((float *)dp)[0] = cc->fpr[0].f; \
317 ((float *)dp)[1] = cc->fpr[1].f; \
318 } else { /* Copy complex double from FPRs. */ \
319 ((double *)dp)[0] = cc->fpr[0].d; \
320 ((double *)dp)[1] = cc->fpr[1].d; \
321 }
322
323#define CCALL_HANDLE_STRUCTARG \
324 unsigned int cl = ccall_classify_struct(cts, d); \
325 if (cl == 0) { /* Pass struct by reference. */ \
326 rp = cdataptr(lj_cdata_new(cts, did, sz)); \
327 sz = CTSIZE_PTR; \
328 } else if (cl > 1) { /* Pass struct in FPRs or on stack. */ \
329 isfp = (cl & 4) ? 2 : 1; \
330 } /* else: Pass struct in GPRs or on stack. */
331
332#define CCALL_HANDLE_COMPLEXARG \
333 /* Pass complex by value in separate (!) FPRs or on stack. */ \
334 isfp = sz == 2*sizeof(float) ? 2 : 1;
335
336#define CCALL_HANDLE_REGARG \
337 if (LJ_TARGET_IOS && isva) { \
338 /* IOS: All variadic arguments are on the stack. */ \
339 } else if (isfp) { /* Try to pass argument in FPRs. */ \
340 int n2 = ctype_isvector(d->info) ? 1 : n*isfp; \
341 if (nfpr + n2 <= CCALL_NARG_FPR) { \
342 dp = &cc->fpr[nfpr]; \
343 nfpr += n2; \
344 goto done; \
345 } else { \
346 nfpr = CCALL_NARG_FPR; /* Prevent reordering. */ \
347 if (LJ_TARGET_IOS && d->size < 8) goto err_nyi; \
348 } \
349 } else { /* Try to pass argument in GPRs. */ \
350 if (!LJ_TARGET_IOS && (d->info & CTF_ALIGN) > CTALIGN_PTR) \
351 ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
352 if (ngpr + n <= maxgpr) { \
353 dp = &cc->gpr[ngpr]; \
354 ngpr += n; \
355 goto done; \
356 } else { \
357 ngpr = maxgpr; /* Prevent reordering. */ \
358 if (LJ_TARGET_IOS && d->size < 8) goto err_nyi; \
359 } \
360 }
361
294#elif LJ_TARGET_PPC 362#elif LJ_TARGET_PPC
295/* -- PPC calling conventions --------------------------------------------- */ 363/* -- PPC calling conventions --------------------------------------------- */
296 364
@@ -339,53 +407,116 @@
339 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ 407 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
340 ctr = ctype_get(cts, CTID_DOUBLE); /* FPRs always hold doubles. */ 408 ctr = ctype_get(cts, CTID_DOUBLE); /* FPRs always hold doubles. */
341 409
342#elif LJ_TARGET_PPCSPE 410#elif LJ_TARGET_MIPS32
343/* -- PPC/SPE calling conventions ----------------------------------------- */ 411/* -- MIPS o32 calling conventions ---------------------------------------- */
344 412
345#define CCALL_HANDLE_STRUCTRET \ 413#define CCALL_HANDLE_STRUCTRET \
346 cc->retref = 1; /* Return all structs by reference. */ \ 414 cc->retref = 1; /* Return all structs by reference. */ \
347 cc->gpr[ngpr++] = (GPRArg)dp; 415 cc->gpr[ngpr++] = (GPRArg)dp;
348 416
349#define CCALL_HANDLE_COMPLEXRET \ 417#define CCALL_HANDLE_COMPLEXRET \
350 /* Complex values are returned in 2 or 4 GPRs. */ \ 418 /* Complex values are returned in 1 or 2 FPRs. */ \
351 cc->retref = 0; 419 cc->retref = 0;
352 420
421#if LJ_ABI_SOFTFP
353#define CCALL_HANDLE_COMPLEXRET2 \ 422#define CCALL_HANDLE_COMPLEXRET2 \
354 memcpy(dp, sp, ctr->size); /* Copy complex from GPRs. */ 423 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from GPRs. */ \
424 ((intptr_t *)dp)[0] = cc->gpr[0]; \
425 ((intptr_t *)dp)[1] = cc->gpr[1]; \
426 } else { /* Copy complex double from GPRs. */ \
427 ((intptr_t *)dp)[0] = cc->gpr[0]; \
428 ((intptr_t *)dp)[1] = cc->gpr[1]; \
429 ((intptr_t *)dp)[2] = cc->gpr[2]; \
430 ((intptr_t *)dp)[3] = cc->gpr[3]; \
431 }
432#else
433#define CCALL_HANDLE_COMPLEXRET2 \
434 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \
435 ((float *)dp)[0] = cc->fpr[0].f; \
436 ((float *)dp)[1] = cc->fpr[1].f; \
437 } else { /* Copy complex double from FPRs. */ \
438 ((double *)dp)[0] = cc->fpr[0].d; \
439 ((double *)dp)[1] = cc->fpr[1].d; \
440 }
441#endif
355 442
356#define CCALL_HANDLE_STRUCTARG \ 443#define CCALL_HANDLE_STRUCTARG \
357 rp = cdataptr(lj_cdata_new(cts, did, sz)); \ 444 /* Pass all structs by value in registers and/or on the stack. */
358 sz = CTSIZE_PTR; /* Pass all structs by reference. */
359 445
360#define CCALL_HANDLE_COMPLEXARG \ 446#define CCALL_HANDLE_COMPLEXARG \
361 /* Pass complex by value in 2 or 4 GPRs. */ 447 /* Pass complex by value in 2 or 4 GPRs. */
362 448
363/* PPC/SPE has a softfp ABI. */ 449#define CCALL_HANDLE_GPR \
364#define CCALL_HANDLE_REGARG \ 450 if ((d->info & CTF_ALIGN) > CTALIGN_PTR) \
365 if (n > 1) { /* Doesn't fit in a single GPR? */ \ 451 ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
366 lua_assert(n == 2 || n == 4); /* int64_t, double or complex (float). */ \ 452 if (ngpr < maxgpr) { \
367 if (n == 2) \
368 ngpr = (ngpr + 1u) & ~1u; /* Only align 64 bit value to regpair. */ \
369 else if (ngpr + n > maxgpr) \
370 ngpr = maxgpr; /* Prevent reordering. */ \
371 } \
372 if (ngpr + n <= maxgpr) { \
373 dp = &cc->gpr[ngpr]; \ 453 dp = &cc->gpr[ngpr]; \
374 ngpr += n; \ 454 if (ngpr + n > maxgpr) { \
455 nsp += ngpr + n - maxgpr; /* Assumes contiguous gpr/stack fields. */ \
456 if (nsp > CCALL_MAXSTACK) goto err_nyi; /* Too many arguments. */ \
457 ngpr = maxgpr; \
458 } else { \
459 ngpr += n; \
460 } \
375 goto done; \ 461 goto done; \
376 } 462 }
377 463
378#elif LJ_TARGET_MIPS 464#if !LJ_ABI_SOFTFP /* MIPS32 hard-float */
379/* -- MIPS calling conventions -------------------------------------------- */ 465#define CCALL_HANDLE_REGARG \
466 if (isfp && nfpr < CCALL_NARG_FPR && !(ct->info & CTF_VARARG)) { \
467 /* Try to pass argument in FPRs. */ \
468 dp = n == 1 ? (void *)&cc->fpr[nfpr].f : (void *)&cc->fpr[nfpr].d; \
469 nfpr++; ngpr += n; \
470 goto done; \
471 } else { /* Try to pass argument in GPRs. */ \
472 nfpr = CCALL_NARG_FPR; \
473 CCALL_HANDLE_GPR \
474 }
475#else /* MIPS32 soft-float */
476#define CCALL_HANDLE_REGARG CCALL_HANDLE_GPR
477#endif
478
479#if !LJ_ABI_SOFTFP
480/* On MIPS64 soft-float, position of float return values is endian-dependant. */
481#define CCALL_HANDLE_RET \
482 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
483 sp = (uint8_t *)&cc->fpr[0].f;
484#endif
485
486#elif LJ_TARGET_MIPS64
487/* -- MIPS n64 calling conventions ---------------------------------------- */
380 488
381#define CCALL_HANDLE_STRUCTRET \ 489#define CCALL_HANDLE_STRUCTRET \
382 cc->retref = 1; /* Return all structs by reference. */ \ 490 cc->retref = !(sz <= 16); \
383 cc->gpr[ngpr++] = (GPRArg)dp; 491 if (cc->retref) cc->gpr[ngpr++] = (GPRArg)dp;
492
493#define CCALL_HANDLE_STRUCTRET2 \
494 ccall_copy_struct(cc, ctr, dp, sp, ccall_classify_struct(cts, ctr, ct));
384 495
385#define CCALL_HANDLE_COMPLEXRET \ 496#define CCALL_HANDLE_COMPLEXRET \
386 /* Complex values are returned in 1 or 2 FPRs. */ \ 497 /* Complex values are returned in 1 or 2 FPRs. */ \
387 cc->retref = 0; 498 cc->retref = 0;
388 499
500#if LJ_ABI_SOFTFP /* MIPS64 soft-float */
501
502#define CCALL_HANDLE_COMPLEXRET2 \
503 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from GPRs. */ \
504 ((intptr_t *)dp)[0] = cc->gpr[0]; \
505 } else { /* Copy complex double from GPRs. */ \
506 ((intptr_t *)dp)[0] = cc->gpr[0]; \
507 ((intptr_t *)dp)[1] = cc->gpr[1]; \
508 }
509
510#define CCALL_HANDLE_COMPLEXARG \
511 /* Pass complex by value in 2 or 4 GPRs. */
512
513/* Position of soft-float 'float' return value depends on endianess. */
514#define CCALL_HANDLE_RET \
515 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
516 sp = (uint8_t *)cc->gpr + LJ_ENDIAN_SELECT(0, 4);
517
518#else /* MIPS64 hard-float */
519
389#define CCALL_HANDLE_COMPLEXRET2 \ 520#define CCALL_HANDLE_COMPLEXRET2 \
390 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \ 521 if (ctr->size == 2*sizeof(float)) { /* Copy complex float from FPRs. */ \
391 ((float *)dp)[0] = cc->fpr[0].f; \ 522 ((float *)dp)[0] = cc->fpr[0].f; \
@@ -395,39 +526,35 @@
395 ((double *)dp)[1] = cc->fpr[1].d; \ 526 ((double *)dp)[1] = cc->fpr[1].d; \
396 } 527 }
397 528
398#define CCALL_HANDLE_STRUCTARG \
399 /* Pass all structs by value in registers and/or on the stack. */
400
401#define CCALL_HANDLE_COMPLEXARG \ 529#define CCALL_HANDLE_COMPLEXARG \
402 /* Pass complex by value in 2 or 4 GPRs. */ 530 if (sz == 2*sizeof(float)) { \
403 531 isfp = 2; \
404#define CCALL_HANDLE_REGARG \ 532 if (ngpr < maxgpr) \
405 if (isfp && nfpr < CCALL_NARG_FPR && !(ct->info & CTF_VARARG)) { \ 533 sz *= 2; \
406 /* Try to pass argument in FPRs. */ \
407 dp = n == 1 ? (void *)&cc->fpr[nfpr].f : (void *)&cc->fpr[nfpr].d; \
408 nfpr++; ngpr += n; \
409 goto done; \
410 } else { /* Try to pass argument in GPRs. */ \
411 nfpr = CCALL_NARG_FPR; \
412 if ((d->info & CTF_ALIGN) > CTALIGN_PTR) \
413 ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
414 if (ngpr < maxgpr) { \
415 dp = &cc->gpr[ngpr]; \
416 if (ngpr + n > maxgpr) { \
417 nsp += ngpr + n - maxgpr; /* Assumes contiguous gpr/stack fields. */ \
418 if (nsp > CCALL_MAXSTACK) goto err_nyi; /* Too many arguments. */ \
419 ngpr = maxgpr; \
420 } else { \
421 ngpr += n; \
422 } \
423 goto done; \
424 } \
425 } 534 }
426 535
427#define CCALL_HANDLE_RET \ 536#define CCALL_HANDLE_RET \
428 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ 537 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
429 sp = (uint8_t *)&cc->fpr[0].f; 538 sp = (uint8_t *)&cc->fpr[0].f;
430 539
540#endif
541
542#define CCALL_HANDLE_STRUCTARG \
543 /* Pass all structs by value in registers and/or on the stack. */
544
545#define CCALL_HANDLE_REGARG \
546 if (ngpr < maxgpr) { \
547 dp = &cc->gpr[ngpr]; \
548 if (ngpr + n > maxgpr) { \
549 nsp += ngpr + n - maxgpr; /* Assumes contiguous gpr/stack fields. */ \
550 if (nsp > CCALL_MAXSTACK) goto err_nyi; /* Too many arguments. */ \
551 ngpr = maxgpr; \
552 } else { \
553 ngpr += n; \
554 } \
555 goto done; \
556 }
557
431#else 558#else
432#error "Missing calling convention definitions for this architecture" 559#error "Missing calling convention definitions for this architecture"
433#endif 560#endif
@@ -621,6 +748,124 @@ noth: /* Not a homogeneous float/double aggregate. */
621 748
622#endif 749#endif
623 750
751/* -- ARM64 ABI struct classification ------------------------------------- */
752
753#if LJ_TARGET_ARM64
754
755/* Classify a struct based on its fields. */
756static unsigned int ccall_classify_struct(CTState *cts, CType *ct)
757{
758 CTSize sz = ct->size;
759 unsigned int r = 0, n = 0, isu = (ct->info & CTF_UNION);
760 while (ct->sib) {
761 CType *sct;
762 ct = ctype_get(cts, ct->sib);
763 if (ctype_isfield(ct->info)) {
764 sct = ctype_rawchild(cts, ct);
765 if (ctype_isfp(sct->info)) {
766 r |= sct->size;
767 if (!isu) n++; else if (n == 0) n = 1;
768 } else if (ctype_iscomplex(sct->info)) {
769 r |= (sct->size >> 1);
770 if (!isu) n += 2; else if (n < 2) n = 2;
771 } else if (ctype_isstruct(sct->info)) {
772 goto substruct;
773 } else {
774 goto noth;
775 }
776 } else if (ctype_isbitfield(ct->info)) {
777 goto noth;
778 } else if (ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
779 sct = ctype_rawchild(cts, ct);
780 substruct:
781 if (sct->size > 0) {
782 unsigned int s = ccall_classify_struct(cts, sct);
783 if (s <= 1) goto noth;
784 r |= (s & 255);
785 if (!isu) n += (s >> 8); else if (n < (s >>8)) n = (s >> 8);
786 }
787 }
788 }
789 if ((r == 4 || r == 8) && n <= 4)
790 return r + (n << 8);
791noth: /* Not a homogeneous float/double aggregate. */
792 return (sz <= 16); /* Return structs of size <= 16 in GPRs. */
793}
794
795#endif
796
797/* -- MIPS64 ABI struct classification ---------------------------- */
798
799#if LJ_TARGET_MIPS64
800
801#define FTYPE_FLOAT 1
802#define FTYPE_DOUBLE 2
803
804/* Classify FP fields (max. 2) and their types. */
805static unsigned int ccall_classify_struct(CTState *cts, CType *ct, CType *ctf)
806{
807 int n = 0, ft = 0;
808 if ((ctf->info & CTF_VARARG) || (ct->info & CTF_UNION))
809 goto noth;
810 while (ct->sib) {
811 CType *sct;
812 ct = ctype_get(cts, ct->sib);
813 if (n == 2) {
814 goto noth;
815 } else if (ctype_isfield(ct->info)) {
816 sct = ctype_rawchild(cts, ct);
817 if (ctype_isfp(sct->info)) {
818 ft |= (sct->size == 4 ? FTYPE_FLOAT : FTYPE_DOUBLE) << 2*n;
819 n++;
820 } else {
821 goto noth;
822 }
823 } else if (ctype_isbitfield(ct->info) ||
824 ctype_isxattrib(ct->info, CTA_SUBTYPE)) {
825 goto noth;
826 }
827 }
828 if (n <= 2)
829 return ft;
830noth: /* Not a homogeneous float/double aggregate. */
831 return 0; /* Struct is in GPRs. */
832}
833
834void ccall_copy_struct(CCallState *cc, CType *ctr, void *dp, void *sp, int ft)
835{
836 if (LJ_ABI_SOFTFP ? ft :
837 ((ft & 3) == FTYPE_FLOAT || (ft >> 2) == FTYPE_FLOAT)) {
838 int i, ofs = 0;
839 for (i = 0; ft != 0; i++, ft >>= 2) {
840 if ((ft & 3) == FTYPE_FLOAT) {
841#if LJ_ABI_SOFTFP
842 /* The 2nd FP struct result is in CARG1 (gpr[2]) and not CRET2. */
843 memcpy((uint8_t *)dp + ofs,
844 (uint8_t *)&cc->gpr[2*i] + LJ_ENDIAN_SELECT(0, 4), 4);
845#else
846 *(float *)((uint8_t *)dp + ofs) = cc->fpr[i].f;
847#endif
848 ofs += 4;
849 } else {
850 ofs = (ofs + 7) & ~7; /* 64 bit alignment. */
851#if LJ_ABI_SOFTFP
852 *(intptr_t *)((uint8_t *)dp + ofs) = cc->gpr[2*i];
853#else
854 *(double *)((uint8_t *)dp + ofs) = cc->fpr[i].d;
855#endif
856 ofs += 8;
857 }
858 }
859 } else {
860#if !LJ_ABI_SOFTFP
861 if (ft) sp = (uint8_t *)&cc->fpr[0];
862#endif
863 memcpy(dp, sp, ctr->size);
864 }
865}
866
867#endif
868
624/* -- Common C call handling ---------------------------------------------- */ 869/* -- Common C call handling ---------------------------------------------- */
625 870
626/* Infer the destination CTypeID for a vararg argument. */ 871/* Infer the destination CTypeID for a vararg argument. */
@@ -788,6 +1033,12 @@ static int ccall_set_args(lua_State *L, CTState *cts, CType *ct,
788 *(int32_t *)dp = d->size == 1 ? (int32_t)*(int8_t *)dp : 1033 *(int32_t *)dp = d->size == 1 ? (int32_t)*(int8_t *)dp :
789 (int32_t)*(int16_t *)dp; 1034 (int32_t)*(int16_t *)dp;
790 } 1035 }
1036#if LJ_TARGET_MIPS64
1037 if ((ctype_isinteger_or_bool(d->info) || ctype_isenum(d->info) ||
1038 (isfp && nsp == 0)) && d->size <= 4) {
1039 *(int64_t *)dp = (int64_t)*(int32_t *)dp; /* Sign-extend to 64 bit. */
1040 }
1041#endif
791#if LJ_TARGET_X64 && LJ_ABI_WIN 1042#if LJ_TARGET_X64 && LJ_ABI_WIN
792 if (isva) { /* Windows/x64 mirrors varargs in both register sets. */ 1043 if (isva) { /* Windows/x64 mirrors varargs in both register sets. */
793 if (nfpr == ngpr) 1044 if (nfpr == ngpr)
@@ -803,6 +1054,12 @@ static int ccall_set_args(lua_State *L, CTState *cts, CType *ct,
803 cc->fpr[nfpr-1].d[0] = cc->fpr[nfpr-2].d[1]; /* Split complex double. */ 1054 cc->fpr[nfpr-1].d[0] = cc->fpr[nfpr-2].d[1]; /* Split complex double. */
804 cc->fpr[nfpr-2].d[1] = 0; 1055 cc->fpr[nfpr-2].d[1] = 0;
805 } 1056 }
1057#elif LJ_TARGET_ARM64 || (LJ_TARGET_MIPS64 && !LJ_ABI_SOFTFP)
1058 if (isfp == 2 && (uint8_t *)dp < (uint8_t *)cc->stack) {
1059 /* Split float HFA or complex float into separate registers. */
1060 CTSize i = (sz >> 2) - 1;
1061 do { ((uint64_t *)dp)[i] = ((uint32_t *)dp)[i]; } while (i--);
1062 }
806#else 1063#else
807 UNUSED(isfp); 1064 UNUSED(isfp);
808#endif 1065#endif
@@ -844,7 +1101,8 @@ static int ccall_get_results(lua_State *L, CTState *cts, CType *ct,
844 CCALL_HANDLE_COMPLEXRET2 1101 CCALL_HANDLE_COMPLEXRET2
845 return 1; /* One GC step. */ 1102 return 1; /* One GC step. */
846 } 1103 }
847 if (LJ_BE && ctype_isinteger_or_bool(ctr->info) && ctr->size < CTSIZE_PTR) 1104 if (LJ_BE && ctr->size < CTSIZE_PTR &&
1105 (ctype_isinteger_or_bool(ctr->info) || ctype_isenum(ctr->info)))
848 sp += (CTSIZE_PTR - ctr->size); 1106 sp += (CTSIZE_PTR - ctr->size);
849#if CCALL_NUM_FPR 1107#if CCALL_NUM_FPR
850 if (ctype_isfp(ctr->info) || ctype_isvector(ctr->info)) 1108 if (ctype_isfp(ctr->info) || ctype_isvector(ctr->info))
diff --git a/src/lj_ccall.h b/src/lj_ccall.h
index 9089e6c7..34e800cc 100644
--- a/src/lj_ccall.h
+++ b/src/lj_ccall.h
@@ -68,6 +68,21 @@ typedef union FPRArg {
68 float f[2]; 68 float f[2];
69} FPRArg; 69} FPRArg;
70 70
71#elif LJ_TARGET_ARM64
72
73#define CCALL_NARG_GPR 8
74#define CCALL_NRET_GPR 2
75#define CCALL_NARG_FPR 8
76#define CCALL_NRET_FPR 4
77#define CCALL_SPS_FREE 0
78
79typedef intptr_t GPRArg;
80typedef union FPRArg {
81 double d;
82 float f;
83 uint32_t u32;
84} FPRArg;
85
71#elif LJ_TARGET_PPC 86#elif LJ_TARGET_PPC
72 87
73#define CCALL_NARG_GPR 8 88#define CCALL_NARG_GPR 8
@@ -80,23 +95,29 @@ typedef union FPRArg {
80typedef intptr_t GPRArg; 95typedef intptr_t GPRArg;
81typedef double FPRArg; 96typedef double FPRArg;
82 97
83#elif LJ_TARGET_PPCSPE 98#elif LJ_TARGET_MIPS32
84 99
85#define CCALL_NARG_GPR 8 100#define CCALL_NARG_GPR 4
86#define CCALL_NARG_FPR 0 101#define CCALL_NARG_FPR (LJ_ABI_SOFTFP ? 0 : 2)
87#define CCALL_NRET_GPR 4 /* For softfp complex double. */ 102#define CCALL_NRET_GPR (LJ_ABI_SOFTFP ? 4 : 2)
88#define CCALL_NRET_FPR 0 103#define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 2)
89#define CCALL_SPS_FREE 0 /* NYI */ 104#define CCALL_SPS_EXTRA 7
105#define CCALL_SPS_FREE 1
90 106
91typedef intptr_t GPRArg; 107typedef intptr_t GPRArg;
108typedef union FPRArg {
109 double d;
110 struct { LJ_ENDIAN_LOHI(float f; , float g;) };
111} FPRArg;
92 112
93#elif LJ_TARGET_MIPS 113#elif LJ_TARGET_MIPS64
94 114
95#define CCALL_NARG_GPR 4 115/* FP args are positional and overlay the GPR array. */
96#define CCALL_NARG_FPR 2 116#define CCALL_NARG_GPR 8
117#define CCALL_NARG_FPR 0
97#define CCALL_NRET_GPR 2 118#define CCALL_NRET_GPR 2
98#define CCALL_NRET_FPR 2 119#define CCALL_NRET_FPR (LJ_ABI_SOFTFP ? 0 : 2)
99#define CCALL_SPS_EXTRA 7 120#define CCALL_SPS_EXTRA 3
100#define CCALL_SPS_FREE 1 121#define CCALL_SPS_FREE 1
101 122
102typedef intptr_t GPRArg; 123typedef intptr_t GPRArg;
@@ -145,6 +166,8 @@ typedef LJ_ALIGN(CCALL_ALIGN_CALLSTATE) struct CCallState {
145 uint8_t nfpr; /* Number of arguments in FPRs. */ 166 uint8_t nfpr; /* Number of arguments in FPRs. */
146#elif LJ_TARGET_X86 167#elif LJ_TARGET_X86
147 uint8_t resx87; /* Result on x87 stack: 1:float, 2:double. */ 168 uint8_t resx87; /* Result on x87 stack: 1:float, 2:double. */
169#elif LJ_TARGET_ARM64
170 void *retp; /* Aggregate return pointer in x8. */
148#elif LJ_TARGET_PPC 171#elif LJ_TARGET_PPC
149 uint8_t nfpr; /* Number of arguments in FPRs. */ 172 uint8_t nfpr; /* Number of arguments in FPRs. */
150#endif 173#endif
diff --git a/src/lj_ccallback.c b/src/lj_ccallback.c
index 06a74019..fce6a3ed 100644
--- a/src/lj_ccallback.c
+++ b/src/lj_ccallback.c
@@ -27,7 +27,7 @@
27 27
28#if LJ_OS_NOJIT 28#if LJ_OS_NOJIT
29 29
30/* Disabled callback support. */ 30/* Callbacks disabled. */
31#define CALLBACK_SLOT2OFS(slot) (0*(slot)) 31#define CALLBACK_SLOT2OFS(slot) (0*(slot))
32#define CALLBACK_OFS2SLOT(ofs) (0*(ofs)) 32#define CALLBACK_OFS2SLOT(ofs) (0*(ofs))
33#define CALLBACK_MAX_SLOT 0 33#define CALLBACK_MAX_SLOT 0
@@ -35,7 +35,7 @@
35#elif LJ_TARGET_X86ORX64 35#elif LJ_TARGET_X86ORX64
36 36
37#define CALLBACK_MCODE_HEAD (LJ_64 ? 8 : 0) 37#define CALLBACK_MCODE_HEAD (LJ_64 ? 8 : 0)
38#define CALLBACK_MCODE_GROUP (-2+1+2+5+(LJ_64 ? 6 : 5)) 38#define CALLBACK_MCODE_GROUP (-2+1+2+(LJ_GC64 ? 10 : 5)+(LJ_64 ? 6 : 5))
39 39
40#define CALLBACK_SLOT2OFS(slot) \ 40#define CALLBACK_SLOT2OFS(slot) \
41 (CALLBACK_MCODE_HEAD + CALLBACK_MCODE_GROUP*((slot)/32) + 4*(slot)) 41 (CALLBACK_MCODE_HEAD + CALLBACK_MCODE_GROUP*((slot)/32) + 4*(slot))
@@ -54,23 +54,22 @@ static MSize CALLBACK_OFS2SLOT(MSize ofs)
54#elif LJ_TARGET_ARM 54#elif LJ_TARGET_ARM
55 55
56#define CALLBACK_MCODE_HEAD 32 56#define CALLBACK_MCODE_HEAD 32
57#define CALLBACK_SLOT2OFS(slot) (CALLBACK_MCODE_HEAD + 8*(slot)) 57
58#define CALLBACK_OFS2SLOT(ofs) (((ofs)-CALLBACK_MCODE_HEAD)/8) 58#elif LJ_TARGET_ARM64
59#define CALLBACK_MAX_SLOT (CALLBACK_OFS2SLOT(CALLBACK_MCODE_SIZE)) 59
60#define CALLBACK_MCODE_HEAD 32
60 61
61#elif LJ_TARGET_PPC 62#elif LJ_TARGET_PPC
62 63
63#define CALLBACK_MCODE_HEAD 24 64#define CALLBACK_MCODE_HEAD 24
64#define CALLBACK_SLOT2OFS(slot) (CALLBACK_MCODE_HEAD + 8*(slot))
65#define CALLBACK_OFS2SLOT(ofs) (((ofs)-CALLBACK_MCODE_HEAD)/8)
66#define CALLBACK_MAX_SLOT (CALLBACK_OFS2SLOT(CALLBACK_MCODE_SIZE))
67 65
68#elif LJ_TARGET_MIPS 66#elif LJ_TARGET_MIPS32
69 67
70#define CALLBACK_MCODE_HEAD 24 68#define CALLBACK_MCODE_HEAD 20
71#define CALLBACK_SLOT2OFS(slot) (CALLBACK_MCODE_HEAD + 8*(slot)) 69
72#define CALLBACK_OFS2SLOT(ofs) (((ofs)-CALLBACK_MCODE_HEAD)/8) 70#elif LJ_TARGET_MIPS64
73#define CALLBACK_MAX_SLOT (CALLBACK_OFS2SLOT(CALLBACK_MCODE_SIZE)) 71
72#define CALLBACK_MCODE_HEAD 52
74 73
75#else 74#else
76 75
@@ -81,6 +80,12 @@ static MSize CALLBACK_OFS2SLOT(MSize ofs)
81 80
82#endif 81#endif
83 82
83#ifndef CALLBACK_SLOT2OFS
84#define CALLBACK_SLOT2OFS(slot) (CALLBACK_MCODE_HEAD + 8*(slot))
85#define CALLBACK_OFS2SLOT(ofs) (((ofs)-CALLBACK_MCODE_HEAD)/8)
86#define CALLBACK_MAX_SLOT (CALLBACK_OFS2SLOT(CALLBACK_MCODE_SIZE))
87#endif
88
84/* Convert callback slot number to callback function pointer. */ 89/* Convert callback slot number to callback function pointer. */
85static void *callback_slot2ptr(CTState *cts, MSize slot) 90static void *callback_slot2ptr(CTState *cts, MSize slot)
86{ 91{
@@ -119,8 +124,13 @@ static void callback_mcode_init(global_State *g, uint8_t *page)
119 /* push ebp/rbp; mov ah, slot>>8; mov ebp, &g. */ 124 /* push ebp/rbp; mov ah, slot>>8; mov ebp, &g. */
120 *p++ = XI_PUSH + RID_EBP; 125 *p++ = XI_PUSH + RID_EBP;
121 *p++ = XI_MOVrib | (RID_EAX+4); *p++ = (uint8_t)(slot >> 8); 126 *p++ = XI_MOVrib | (RID_EAX+4); *p++ = (uint8_t)(slot >> 8);
127#if LJ_GC64
128 *p++ = 0x48; *p++ = XI_MOVri | RID_EBP;
129 *(uint64_t *)p = (uint64_t)(g); p += 8;
130#else
122 *p++ = XI_MOVri | RID_EBP; 131 *p++ = XI_MOVri | RID_EBP;
123 *(int32_t *)p = i32ptr(g); p += 4; 132 *(int32_t *)p = i32ptr(g); p += 4;
133#endif
124#if LJ_64 134#if LJ_64
125 /* jmp [rip-pageofs] where lj_vm_ffi_callback is stored. */ 135 /* jmp [rip-pageofs] where lj_vm_ffi_callback is stored. */
126 *p++ = XI_GROUP5; *p++ = XM_OFS0 + (XOg_JMP<<3) + RID_EBP; 136 *p++ = XI_GROUP5; *p++ = XM_OFS0 + (XOg_JMP<<3) + RID_EBP;
@@ -157,6 +167,26 @@ static void callback_mcode_init(global_State *g, uint32_t *page)
157 } 167 }
158 lua_assert(p - page <= CALLBACK_MCODE_SIZE); 168 lua_assert(p - page <= CALLBACK_MCODE_SIZE);
159} 169}
170#elif LJ_TARGET_ARM64
171static void callback_mcode_init(global_State *g, uint32_t *page)
172{
173 uint32_t *p = page;
174 void *target = (void *)lj_vm_ffi_callback;
175 MSize slot;
176 *p++ = A64I_LDRLx | A64F_D(RID_X11) | A64F_S19(4);
177 *p++ = A64I_LDRLx | A64F_D(RID_X10) | A64F_S19(5);
178 *p++ = A64I_BR | A64F_N(RID_X11);
179 *p++ = A64I_NOP;
180 ((void **)p)[0] = target;
181 ((void **)p)[1] = g;
182 p += 4;
183 for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) {
184 *p++ = A64I_MOVZw | A64F_D(RID_X9) | A64F_U16(slot);
185 *p = A64I_B | A64F_S26((page-p) & 0x03ffffffu);
186 p++;
187 }
188 lua_assert(p - page <= CALLBACK_MCODE_SIZE);
189}
160#elif LJ_TARGET_PPC 190#elif LJ_TARGET_PPC
161static void callback_mcode_init(global_State *g, uint32_t *page) 191static void callback_mcode_init(global_State *g, uint32_t *page)
162{ 192{
@@ -180,14 +210,27 @@ static void callback_mcode_init(global_State *g, uint32_t *page)
180static void callback_mcode_init(global_State *g, uint32_t *page) 210static void callback_mcode_init(global_State *g, uint32_t *page)
181{ 211{
182 uint32_t *p = page; 212 uint32_t *p = page;
183 void *target = (void *)lj_vm_ffi_callback; 213 uintptr_t target = (uintptr_t)(void *)lj_vm_ffi_callback;
214 uintptr_t ug = (uintptr_t)(void *)g;
184 MSize slot; 215 MSize slot;
185 *p++ = MIPSI_SW | MIPSF_T(RID_R1)|MIPSF_S(RID_SP) | 0; 216#if LJ_TARGET_MIPS32
186 *p++ = MIPSI_LUI | MIPSF_T(RID_R3) | (u32ptr(target) >> 16); 217 *p++ = MIPSI_LUI | MIPSF_T(RID_R3) | (target >> 16);
187 *p++ = MIPSI_LUI | MIPSF_T(RID_R2) | (u32ptr(g) >> 16); 218 *p++ = MIPSI_LUI | MIPSF_T(RID_R2) | (ug >> 16);
188 *p++ = MIPSI_ORI | MIPSF_T(RID_R3)|MIPSF_S(RID_R3) |(u32ptr(target)&0xffff); 219#else
220 *p++ = MIPSI_LUI | MIPSF_T(RID_R3) | (target >> 48);
221 *p++ = MIPSI_LUI | MIPSF_T(RID_R2) | (ug >> 48);
222 *p++ = MIPSI_ORI | MIPSF_T(RID_R3)|MIPSF_S(RID_R3) | ((target >> 32) & 0xffff);
223 *p++ = MIPSI_ORI | MIPSF_T(RID_R2)|MIPSF_S(RID_R2) | ((ug >> 32) & 0xffff);
224 *p++ = MIPSI_DSLL | MIPSF_D(RID_R3)|MIPSF_T(RID_R3) | MIPSF_A(16);
225 *p++ = MIPSI_DSLL | MIPSF_D(RID_R2)|MIPSF_T(RID_R2) | MIPSF_A(16);
226 *p++ = MIPSI_ORI | MIPSF_T(RID_R3)|MIPSF_S(RID_R3) | ((target >> 16) & 0xffff);
227 *p++ = MIPSI_ORI | MIPSF_T(RID_R2)|MIPSF_S(RID_R2) | ((ug >> 16) & 0xffff);
228 *p++ = MIPSI_DSLL | MIPSF_D(RID_R3)|MIPSF_T(RID_R3) | MIPSF_A(16);
229 *p++ = MIPSI_DSLL | MIPSF_D(RID_R2)|MIPSF_T(RID_R2) | MIPSF_A(16);
230#endif
231 *p++ = MIPSI_ORI | MIPSF_T(RID_R3)|MIPSF_S(RID_R3) | (target & 0xffff);
189 *p++ = MIPSI_JR | MIPSF_S(RID_R3); 232 *p++ = MIPSI_JR | MIPSF_S(RID_R3);
190 *p++ = MIPSI_ORI | MIPSF_T(RID_R2)|MIPSF_S(RID_R2) | (u32ptr(g)&0xffff); 233 *p++ = MIPSI_ORI | MIPSF_T(RID_R2)|MIPSF_S(RID_R2) | (ug & 0xffff);
191 for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { 234 for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) {
192 *p = MIPSI_B | ((page-p-1) & 0x0000ffffu); 235 *p = MIPSI_B | ((page-p-1) & 0x0000ffffu);
193 p++; 236 p++;
@@ -351,6 +394,29 @@ void lj_ccallback_mcode_free(CTState *cts)
351 goto done; \ 394 goto done; \
352 } CALLBACK_HANDLE_REGARG_FP2 395 } CALLBACK_HANDLE_REGARG_FP2
353 396
397#elif LJ_TARGET_ARM64
398
399#define CALLBACK_HANDLE_REGARG \
400 if (isfp) { \
401 if (nfpr + n <= CCALL_NARG_FPR) { \
402 sp = &cts->cb.fpr[nfpr]; \
403 nfpr += n; \
404 goto done; \
405 } else { \
406 nfpr = CCALL_NARG_FPR; /* Prevent reordering. */ \
407 } \
408 } else { \
409 if (!LJ_TARGET_IOS && n > 1) \
410 ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
411 if (ngpr + n <= maxgpr) { \
412 sp = &cts->cb.gpr[ngpr]; \
413 ngpr += n; \
414 goto done; \
415 } else { \
416 ngpr = CCALL_NARG_GPR; /* Prevent reordering. */ \
417 } \
418 }
419
354#elif LJ_TARGET_PPC 420#elif LJ_TARGET_PPC
355 421
356#define CALLBACK_HANDLE_REGARG \ 422#define CALLBACK_HANDLE_REGARG \
@@ -376,8 +442,17 @@ void lj_ccallback_mcode_free(CTState *cts)
376 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ 442 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
377 *(double *)dp = *(float *)dp; /* FPRs always hold doubles. */ 443 *(double *)dp = *(float *)dp; /* FPRs always hold doubles. */
378 444
379#elif LJ_TARGET_MIPS 445#elif LJ_TARGET_MIPS32
380 446
447#define CALLBACK_HANDLE_GPR \
448 if (n > 1) ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \
449 if (ngpr + n <= maxgpr) { \
450 sp = &cts->cb.gpr[ngpr]; \
451 ngpr += n; \
452 goto done; \
453 }
454
455#if !LJ_ABI_SOFTFP /* MIPS32 hard-float */
381#define CALLBACK_HANDLE_REGARG \ 456#define CALLBACK_HANDLE_REGARG \
382 if (isfp && nfpr < CCALL_NARG_FPR) { /* Try to pass argument in FPRs. */ \ 457 if (isfp && nfpr < CCALL_NARG_FPR) { /* Try to pass argument in FPRs. */ \
383 sp = (void *)((uint8_t *)&cts->cb.fpr[nfpr] + ((LJ_BE && n==1) ? 4 : 0)); \ 458 sp = (void *)((uint8_t *)&cts->cb.fpr[nfpr] + ((LJ_BE && n==1) ? 4 : 0)); \
@@ -385,13 +460,36 @@ void lj_ccallback_mcode_free(CTState *cts)
385 goto done; \ 460 goto done; \
386 } else { /* Try to pass argument in GPRs. */ \ 461 } else { /* Try to pass argument in GPRs. */ \
387 nfpr = CCALL_NARG_FPR; \ 462 nfpr = CCALL_NARG_FPR; \
388 if (n > 1) ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \ 463 CALLBACK_HANDLE_GPR \
389 if (ngpr + n <= maxgpr) { \
390 sp = &cts->cb.gpr[ngpr]; \
391 ngpr += n; \
392 goto done; \
393 } \
394 } 464 }
465#else /* MIPS32 soft-float */
466#define CALLBACK_HANDLE_REGARG \
467 CALLBACK_HANDLE_GPR \
468 UNUSED(isfp);
469#endif
470
471#define CALLBACK_HANDLE_RET \
472 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
473 ((float *)dp)[1] = *(float *)dp;
474
475#elif LJ_TARGET_MIPS64
476
477#if !LJ_ABI_SOFTFP /* MIPS64 hard-float */
478#define CALLBACK_HANDLE_REGARG \
479 if (ngpr + n <= maxgpr) { \
480 sp = isfp ? (void*) &cts->cb.fpr[ngpr] : (void*) &cts->cb.gpr[ngpr]; \
481 ngpr += n; \
482 goto done; \
483 }
484#else /* MIPS64 soft-float */
485#define CALLBACK_HANDLE_REGARG \
486 if (ngpr + n <= maxgpr) { \
487 UNUSED(isfp); \
488 sp = (void*) &cts->cb.gpr[ngpr]; \
489 ngpr += n; \
490 goto done; \
491 }
492#endif
395 493
396#define CALLBACK_HANDLE_RET \ 494#define CALLBACK_HANDLE_RET \
397 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ 495 if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \
@@ -411,6 +509,7 @@ static void callback_conv_args(CTState *cts, lua_State *L)
411 int gcsteps = 0; 509 int gcsteps = 0;
412 CType *ct; 510 CType *ct;
413 GCfunc *fn; 511 GCfunc *fn;
512 int fntp;
414 MSize ngpr = 0, nsp = 0, maxgpr = CCALL_NARG_GPR; 513 MSize ngpr = 0, nsp = 0, maxgpr = CCALL_NARG_GPR;
415#if CCALL_NARG_FPR 514#if CCALL_NARG_FPR
416 MSize nfpr = 0; 515 MSize nfpr = 0;
@@ -421,18 +520,27 @@ static void callback_conv_args(CTState *cts, lua_State *L)
421 520
422 if (slot < cts->cb.sizeid && (id = cts->cb.cbid[slot]) != 0) { 521 if (slot < cts->cb.sizeid && (id = cts->cb.cbid[slot]) != 0) {
423 ct = ctype_get(cts, id); 522 ct = ctype_get(cts, id);
424 rid = ctype_cid(ct->info); 523 rid = ctype_cid(ct->info); /* Return type. x86: +(spadj<<16). */
425 fn = funcV(lj_tab_getint(cts->miscmap, (int32_t)slot)); 524 fn = funcV(lj_tab_getint(cts->miscmap, (int32_t)slot));
525 fntp = LJ_TFUNC;
426 } else { /* Must set up frame first, before throwing the error. */ 526 } else { /* Must set up frame first, before throwing the error. */
427 ct = NULL; 527 ct = NULL;
428 rid = 0; 528 rid = 0;
429 fn = (GCfunc *)L; 529 fn = (GCfunc *)L;
530 fntp = LJ_TTHREAD;
531 }
532 /* Continuation returns from callback. */
533 if (LJ_FR2) {
534 (o++)->u64 = LJ_CONT_FFI_CALLBACK;
535 (o++)->u64 = rid;
536 o++;
537 } else {
538 o->u32.lo = LJ_CONT_FFI_CALLBACK;
539 o->u32.hi = rid;
540 o++;
430 } 541 }
431 o->u32.lo = LJ_CONT_FFI_CALLBACK; /* Continuation returns from callback. */ 542 setframe_gc(o, obj2gco(fn), fntp);
432 o->u32.hi = rid; /* Return type. x86: +(spadj<<16). */ 543 setframe_ftsz(o, ((char *)(o+1) - (char *)L->base) + FRAME_CONT);
433 o++;
434 setframe_gc(o, obj2gco(fn));
435 setframe_ftsz(o, (int)((char *)(o+1) - (char *)L->base) + FRAME_CONT);
436 L->top = L->base = ++o; 544 L->top = L->base = ++o;
437 if (!ct) 545 if (!ct)
438 lj_err_caller(cts->L, LJ_ERR_FFI_BADCBACK); 546 lj_err_caller(cts->L, LJ_ERR_FFI_BADCBACK);
@@ -474,7 +582,11 @@ static void callback_conv_args(CTState *cts, lua_State *L)
474 nsp += n; 582 nsp += n;
475 583
476 done: 584 done:
477 if (LJ_BE && cta->size < CTSIZE_PTR) 585 if (LJ_BE && cta->size < CTSIZE_PTR
586#if LJ_TARGET_MIPS64
587 && !(isfp && nsp)
588#endif
589 )
478 sp = (void *)((uint8_t *)sp + CTSIZE_PTR-cta->size); 590 sp = (void *)((uint8_t *)sp + CTSIZE_PTR-cta->size);
479 gcsteps += lj_cconv_tv_ct(cts, cta, 0, o++, sp); 591 gcsteps += lj_cconv_tv_ct(cts, cta, 0, o++, sp);
480 } 592 }
@@ -483,9 +595,14 @@ static void callback_conv_args(CTState *cts, lua_State *L)
483 L->top = o; 595 L->top = o;
484#if LJ_TARGET_X86 596#if LJ_TARGET_X86
485 /* Store stack adjustment for returns from non-cdecl callbacks. */ 597 /* Store stack adjustment for returns from non-cdecl callbacks. */
486 if (ctype_cconv(ct->info) != CTCC_CDECL) 598 if (ctype_cconv(ct->info) != CTCC_CDECL) {
599#if LJ_FR2
600 (L->base-3)->u64 |= (nsp << (16+2));
601#else
487 (L->base-2)->u32.hi |= (nsp << (16+2)); 602 (L->base-2)->u32.hi |= (nsp << (16+2));
488#endif 603#endif
604 }
605#endif
489 while (gcsteps-- > 0) 606 while (gcsteps-- > 0)
490 lj_gc_check(L); 607 lj_gc_check(L);
491} 608}
@@ -493,7 +610,11 @@ static void callback_conv_args(CTState *cts, lua_State *L)
493/* Convert Lua object to callback result. */ 610/* Convert Lua object to callback result. */
494static void callback_conv_result(CTState *cts, lua_State *L, TValue *o) 611static void callback_conv_result(CTState *cts, lua_State *L, TValue *o)
495{ 612{
613#if LJ_FR2
614 CType *ctr = ctype_raw(cts, (uint16_t)(L->base-3)->u64);
615#else
496 CType *ctr = ctype_raw(cts, (uint16_t)(L->base-2)->u32.hi); 616 CType *ctr = ctype_raw(cts, (uint16_t)(L->base-2)->u32.hi);
617#endif
497#if LJ_TARGET_X86 618#if LJ_TARGET_X86
498 cts->cb.gpr[2] = 0; 619 cts->cb.gpr[2] = 0;
499#endif 620#endif
@@ -516,6 +637,12 @@ static void callback_conv_result(CTState *cts, lua_State *L, TValue *o)
516 *(int32_t *)dp = ctr->size == 1 ? (int32_t)*(int8_t *)dp : 637 *(int32_t *)dp = ctr->size == 1 ? (int32_t)*(int8_t *)dp :
517 (int32_t)*(int16_t *)dp; 638 (int32_t)*(int16_t *)dp;
518 } 639 }
640#if LJ_TARGET_MIPS64
641 /* Always sign-extend results to 64 bits. Even a soft-fp 'float'. */
642 if (ctr->size <= 4 &&
643 (LJ_ABI_SOFTFP || ctype_isinteger_or_bool(ctr->info)))
644 *(int64_t *)dp = (int64_t)*(int32_t *)dp;
645#endif
519#if LJ_TARGET_X86 646#if LJ_TARGET_X86
520 if (ctype_isfp(ctr->info)) 647 if (ctype_isfp(ctr->info))
521 cts->cb.gpr[2] = ctr->size == sizeof(float) ? 1 : 2; 648 cts->cb.gpr[2] = ctr->size == sizeof(float) ? 1 : 2;
@@ -529,7 +656,7 @@ lua_State * LJ_FASTCALL lj_ccallback_enter(CTState *cts, void *cf)
529 lua_State *L = cts->L; 656 lua_State *L = cts->L;
530 global_State *g = cts->g; 657 global_State *g = cts->g;
531 lua_assert(L != NULL); 658 lua_assert(L != NULL);
532 if (gcref(g->jit_L)) { 659 if (tvref(g->jit_base)) {
533 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_FFI_BADCBACK)); 660 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_FFI_BADCBACK));
534 if (g->panic) g->panic(L); 661 if (g->panic) g->panic(L);
535 exit(EXIT_FAILURE); 662 exit(EXIT_FAILURE);
@@ -562,9 +689,9 @@ void LJ_FASTCALL lj_ccallback_leave(CTState *cts, TValue *o)
562 } 689 }
563 callback_conv_result(cts, L, o); 690 callback_conv_result(cts, L, o);
564 /* Finally drop C frame and continuation frame. */ 691 /* Finally drop C frame and continuation frame. */
565 L->cframe = cframe_prev(L->cframe); 692 L->top -= 2+2*LJ_FR2;
566 L->top -= 2;
567 L->base = obase; 693 L->base = obase;
694 L->cframe = cframe_prev(L->cframe);
568 cts->cb.slot = 0; /* Blacklist C function that called the callback. */ 695 cts->cb.slot = 0; /* Blacklist C function that called the callback. */
569} 696}
570 697
diff --git a/src/lj_cdata.c b/src/lj_cdata.c
index 49b1aa50..68e16d76 100644
--- a/src/lj_cdata.c
+++ b/src/lj_cdata.c
@@ -9,7 +9,6 @@
9 9
10#include "lj_gc.h" 10#include "lj_gc.h"
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_str.h"
13#include "lj_tab.h" 12#include "lj_tab.h"
14#include "lj_ctype.h" 13#include "lj_ctype.h"
15#include "lj_cconv.h" 14#include "lj_cconv.h"
@@ -27,12 +26,12 @@ GCcdata *lj_cdata_newref(CTState *cts, const void *p, CTypeID id)
27} 26}
28 27
29/* Allocate variable-sized or specially aligned C data object. */ 28/* Allocate variable-sized or specially aligned C data object. */
30GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz, CTSize align) 29GCcdata *lj_cdata_newv(lua_State *L, CTypeID id, CTSize sz, CTSize align)
31{ 30{
32 global_State *g; 31 global_State *g;
33 MSize extra = sizeof(GCcdataVar) + sizeof(GCcdata) + 32 MSize extra = sizeof(GCcdataVar) + sizeof(GCcdata) +
34 (align > CT_MEMALIGN ? (1u<<align) - (1u<<CT_MEMALIGN) : 0); 33 (align > CT_MEMALIGN ? (1u<<align) - (1u<<CT_MEMALIGN) : 0);
35 char *p = lj_mem_newt(cts->L, extra + sz, char); 34 char *p = lj_mem_newt(L, extra + sz, char);
36 uintptr_t adata = (uintptr_t)p + sizeof(GCcdataVar) + sizeof(GCcdata); 35 uintptr_t adata = (uintptr_t)p + sizeof(GCcdataVar) + sizeof(GCcdata);
37 uintptr_t almask = (1u << align) - 1u; 36 uintptr_t almask = (1u << align) - 1u;
38 GCcdata *cd = (GCcdata *)(((adata + almask) & ~almask) - sizeof(GCcdata)); 37 GCcdata *cd = (GCcdata *)(((adata + almask) & ~almask) - sizeof(GCcdata));
@@ -40,7 +39,7 @@ GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz, CTSize align)
40 cdatav(cd)->offset = (uint16_t)((char *)cd - p); 39 cdatav(cd)->offset = (uint16_t)((char *)cd - p);
41 cdatav(cd)->extra = extra; 40 cdatav(cd)->extra = extra;
42 cdatav(cd)->len = sz; 41 cdatav(cd)->len = sz;
43 g = cts->g; 42 g = G(L);
44 setgcrefr(cd->nextgc, g->gc.root); 43 setgcrefr(cd->nextgc, g->gc.root);
45 setgcref(g->gc.root, obj2gco(cd)); 44 setgcref(g->gc.root, obj2gco(cd));
46 newwhite(g, obj2gco(cd)); 45 newwhite(g, obj2gco(cd));
@@ -50,6 +49,15 @@ GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz, CTSize align)
50 return cd; 49 return cd;
51} 50}
52 51
52/* Allocate arbitrary C data object. */
53GCcdata *lj_cdata_newx(CTState *cts, CTypeID id, CTSize sz, CTInfo info)
54{
55 if (!(info & CTF_VLA) && ctype_align(info) <= CT_MEMALIGN)
56 return lj_cdata_new(cts, id, sz);
57 else
58 return lj_cdata_newv(cts->L, id, sz, ctype_align(info));
59}
60
53/* Free a C data object. */ 61/* Free a C data object. */
54void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd) 62void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd)
55{ 63{
@@ -76,21 +84,22 @@ void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd)
76 } 84 }
77} 85}
78 86
79TValue * LJ_FASTCALL lj_cdata_setfin(lua_State *L, GCcdata *cd) 87void lj_cdata_setfin(lua_State *L, GCcdata *cd, GCobj *obj, uint32_t it)
80{ 88{
81 global_State *g = G(L); 89 GCtab *t = ctype_ctsG(G(L))->finalizer;
82 GCtab *t = ctype_ctsG(g)->finalizer;
83 if (gcref(t->metatable)) { 90 if (gcref(t->metatable)) {
84 /* Add cdata to finalizer table, if still enabled. */ 91 /* Add cdata to finalizer table, if still enabled. */
85 TValue *tv, tmp; 92 TValue *tv, tmp;
86 setcdataV(L, &tmp, cd); 93 setcdataV(L, &tmp, cd);
87 lj_gc_anybarriert(L, t); 94 lj_gc_anybarriert(L, t);
88 tv = lj_tab_set(L, t, &tmp); 95 tv = lj_tab_set(L, t, &tmp);
89 cd->marked |= LJ_GC_CDATA_FIN; 96 if (it == LJ_TNIL) {
90 return tv; 97 setnilV(tv);
91 } else { 98 cd->marked &= ~LJ_GC_CDATA_FIN;
92 /* Otherwise return dummy TValue. */ 99 } else {
93 return &g->tmptv; 100 setgcV(L, tv, obj, it);
101 cd->marked |= LJ_GC_CDATA_FIN;
102 }
94 } 103 }
95} 104}
96 105
@@ -123,7 +132,12 @@ collect_attrib:
123 idx = (ptrdiff_t)intV(key); 132 idx = (ptrdiff_t)intV(key);
124 goto integer_key; 133 goto integer_key;
125 } else if (tvisnum(key)) { /* Numeric key. */ 134 } else if (tvisnum(key)) { /* Numeric key. */
126 idx = LJ_64 ? (ptrdiff_t)numV(key) : (ptrdiff_t)lj_num2int(numV(key)); 135#ifdef _MSC_VER
136 /* Workaround for MSVC bug. */
137 volatile
138#endif
139 lua_Number n = numV(key);
140 idx = LJ_64 ? (ptrdiff_t)n : (ptrdiff_t)lj_num2int(n);
127 integer_key: 141 integer_key:
128 if (ctype_ispointer(ct->info)) { 142 if (ctype_ispointer(ct->info)) {
129 CTSize sz = lj_ctype_size(cts, ctype_cid(ct->info)); /* Element size. */ 143 CTSize sz = lj_ctype_size(cts, ctype_cid(ct->info)); /* Element size. */
diff --git a/src/lj_cdata.h b/src/lj_cdata.h
index 4bb65db2..5bb0f5dc 100644
--- a/src/lj_cdata.h
+++ b/src/lj_cdata.h
@@ -58,11 +58,14 @@ static LJ_AINLINE GCcdata *lj_cdata_new_(lua_State *L, CTypeID id, CTSize sz)
58} 58}
59 59
60LJ_FUNC GCcdata *lj_cdata_newref(CTState *cts, const void *pp, CTypeID id); 60LJ_FUNC GCcdata *lj_cdata_newref(CTState *cts, const void *pp, CTypeID id);
61LJ_FUNC GCcdata *lj_cdata_newv(CTState *cts, CTypeID id, CTSize sz, 61LJ_FUNC GCcdata *lj_cdata_newv(lua_State *L, CTypeID id, CTSize sz,
62 CTSize align); 62 CTSize align);
63LJ_FUNC GCcdata *lj_cdata_newx(CTState *cts, CTypeID id, CTSize sz,
64 CTInfo info);
63 65
64LJ_FUNC void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd); 66LJ_FUNC void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd);
65LJ_FUNCA TValue * LJ_FASTCALL lj_cdata_setfin(lua_State *L, GCcdata *cd); 67LJ_FUNC void lj_cdata_setfin(lua_State *L, GCcdata *cd, GCobj *obj,
68 uint32_t it);
66 69
67LJ_FUNC CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key, 70LJ_FUNC CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key,
68 uint8_t **pp, CTInfo *qual); 71 uint8_t **pp, CTInfo *qual);
diff --git a/src/lj_clib.c b/src/lj_clib.c
index 8dc3c10e..61426590 100644
--- a/src/lj_clib.c
+++ b/src/lj_clib.c
@@ -16,6 +16,7 @@
16#include "lj_cconv.h" 16#include "lj_cconv.h"
17#include "lj_cdata.h" 17#include "lj_cdata.h"
18#include "lj_clib.h" 18#include "lj_clib.h"
19#include "lj_strfmt.h"
19 20
20/* -- OS-specific functions ----------------------------------------------- */ 21/* -- OS-specific functions ----------------------------------------------- */
21 22
@@ -61,7 +62,7 @@ static const char *clib_extname(lua_State *L, const char *name)
61#endif 62#endif
62 ) { 63 ) {
63 if (!strchr(name, '.')) { 64 if (!strchr(name, '.')) {
64 name = lj_str_pushf(L, CLIB_SOEXT, name); 65 name = lj_strfmt_pushf(L, CLIB_SOEXT, name);
65 L->top--; 66 L->top--;
66#if LJ_TARGET_CYGWIN 67#if LJ_TARGET_CYGWIN
67 } else { 68 } else {
@@ -70,7 +71,7 @@ static const char *clib_extname(lua_State *L, const char *name)
70 } 71 }
71 if (!(name[0] == CLIB_SOPREFIX[0] && name[1] == CLIB_SOPREFIX[1] && 72 if (!(name[0] == CLIB_SOPREFIX[0] && name[1] == CLIB_SOPREFIX[1] &&
72 name[2] == CLIB_SOPREFIX[2])) { 73 name[2] == CLIB_SOPREFIX[2])) {
73 name = lj_str_pushf(L, CLIB_SOPREFIX "%s", name); 74 name = lj_strfmt_pushf(L, CLIB_SOPREFIX "%s", name);
74 L->top--; 75 L->top--;
75 } 76 }
76 } 77 }
@@ -171,11 +172,19 @@ LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt,
171 const char *name) 172 const char *name)
172{ 173{
173 DWORD err = GetLastError(); 174 DWORD err = GetLastError();
175#if LJ_TARGET_XBOXONE
176 wchar_t wbuf[128];
177 char buf[128*2];
178 if (!FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM,
179 NULL, err, 0, wbuf, sizeof(wbuf)/sizeof(wchar_t), NULL) ||
180 !WideCharToMultiByte(CP_ACP, 0, wbuf, 128, buf, 128*2, NULL, NULL))
181#else
174 char buf[128]; 182 char buf[128];
175 if (!FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM, 183 if (!FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM,
176 NULL, err, 0, buf, sizeof(buf), NULL)) 184 NULL, err, 0, buf, sizeof(buf), NULL))
185#endif
177 buf[0] = '\0'; 186 buf[0] = '\0';
178 lj_err_callermsg(L, lj_str_pushf(L, fmt, name, buf)); 187 lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, buf));
179} 188}
180 189
181static int clib_needext(const char *s) 190static int clib_needext(const char *s)
@@ -190,7 +199,7 @@ static int clib_needext(const char *s)
190static const char *clib_extname(lua_State *L, const char *name) 199static const char *clib_extname(lua_State *L, const char *name)
191{ 200{
192 if (clib_needext(name)) { 201 if (clib_needext(name)) {
193 name = lj_str_pushf(L, "%s.dll", name); 202 name = lj_strfmt_pushf(L, "%s.dll", name);
194 L->top--; 203 L->top--;
195 } 204 }
196 return name; 205 return name;
@@ -199,7 +208,7 @@ static const char *clib_extname(lua_State *L, const char *name)
199static void *clib_loadlib(lua_State *L, const char *name, int global) 208static void *clib_loadlib(lua_State *L, const char *name, int global)
200{ 209{
201 DWORD oldwerr = GetLastError(); 210 DWORD oldwerr = GetLastError();
202 void *h = (void *)LoadLibraryA(clib_extname(L, name)); 211 void *h = (void *)LoadLibraryExA(clib_extname(L, name), NULL, 0);
203 if (!h) clib_error(L, "cannot load module " LUA_QS ": %s", name); 212 if (!h) clib_error(L, "cannot load module " LUA_QS ": %s", name);
204 SetLastError(oldwerr); 213 SetLastError(oldwerr);
205 UNUSED(global); 214 UNUSED(global);
@@ -240,9 +249,9 @@ static void *clib_getsym(CLibrary *cl, const char *name)
240 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, 249 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
241 (const char *)&_fmode, &h); 250 (const char *)&_fmode, &h);
242 break; 251 break;
243 case CLIB_HANDLE_KERNEL32: h = LoadLibraryA("kernel32.dll"); break; 252 case CLIB_HANDLE_KERNEL32: h = LoadLibraryExA("kernel32.dll", NULL, 0); break;
244 case CLIB_HANDLE_USER32: h = LoadLibraryA("user32.dll"); break; 253 case CLIB_HANDLE_USER32: h = LoadLibraryExA("user32.dll", NULL, 0); break;
245 case CLIB_HANDLE_GDI32: h = LoadLibraryA("gdi32.dll"); break; 254 case CLIB_HANDLE_GDI32: h = LoadLibraryExA("gdi32.dll", NULL, 0); break;
246 } 255 }
247 if (!h) continue; 256 if (!h) continue;
248 clib_def_handle[i] = (void *)h; 257 clib_def_handle[i] = (void *)h;
@@ -263,7 +272,7 @@ static void *clib_getsym(CLibrary *cl, const char *name)
263LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt, 272LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt,
264 const char *name) 273 const char *name)
265{ 274{
266 lj_err_callermsg(L, lj_str_pushf(L, fmt, name, "no support for this OS")); 275 lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, "no support for this OS"));
267} 276}
268 277
269static void *clib_loadlib(lua_State *L, const char *name, int global) 278static void *clib_loadlib(lua_State *L, const char *name, int global)
@@ -347,7 +356,7 @@ TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name)
347 CTInfo cconv = ctype_cconv(ct->info); 356 CTInfo cconv = ctype_cconv(ct->info);
348 if (cconv == CTCC_FASTCALL || cconv == CTCC_STDCALL) { 357 if (cconv == CTCC_FASTCALL || cconv == CTCC_STDCALL) {
349 CTSize sz = clib_func_argsize(cts, ct); 358 CTSize sz = clib_func_argsize(cts, ct);
350 const char *symd = lj_str_pushf(L, 359 const char *symd = lj_strfmt_pushf(L,
351 cconv == CTCC_FASTCALL ? "@%s@%d" : "_%s@%d", 360 cconv == CTCC_FASTCALL ? "@%s@%d" : "_%s@%d",
352 sym, sz); 361 sym, sz);
353 L->top--; 362 L->top--;
diff --git a/src/lj_cparse.c b/src/lj_cparse.c
index 2ba50a72..83cfd112 100644
--- a/src/lj_cparse.c
+++ b/src/lj_cparse.c
@@ -9,13 +9,14 @@
9 9
10#include "lj_gc.h" 10#include "lj_gc.h"
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_str.h" 12#include "lj_buf.h"
13#include "lj_ctype.h" 13#include "lj_ctype.h"
14#include "lj_cparse.h" 14#include "lj_cparse.h"
15#include "lj_frame.h" 15#include "lj_frame.h"
16#include "lj_vm.h" 16#include "lj_vm.h"
17#include "lj_char.h" 17#include "lj_char.h"
18#include "lj_strscan.h" 18#include "lj_strscan.h"
19#include "lj_strfmt.h"
19 20
20/* 21/*
21** Important note: this is NOT a validating C parser! This is a minimal 22** Important note: this is NOT a validating C parser! This is a minimal
@@ -46,9 +47,9 @@ static const char *cp_tok2str(CPState *cp, CPToken tok)
46 if (tok > CTOK_OFS) 47 if (tok > CTOK_OFS)
47 return ctoknames[tok-CTOK_OFS-1]; 48 return ctoknames[tok-CTOK_OFS-1];
48 else if (!lj_char_iscntrl(tok)) 49 else if (!lj_char_iscntrl(tok))
49 return lj_str_pushf(cp->L, "%c", tok); 50 return lj_strfmt_pushf(cp->L, "%c", tok);
50 else 51 else
51 return lj_str_pushf(cp->L, "char(%d)", tok); 52 return lj_strfmt_pushf(cp->L, "char(%d)", tok);
52} 53}
53 54
54/* End-of-line? */ 55/* End-of-line? */
@@ -85,24 +86,10 @@ static LJ_NOINLINE CPChar cp_get_bs(CPState *cp)
85 return cp_get(cp); 86 return cp_get(cp);
86} 87}
87 88
88/* Grow save buffer. */
89static LJ_NOINLINE void cp_save_grow(CPState *cp, CPChar c)
90{
91 MSize newsize;
92 if (cp->sb.sz >= CPARSE_MAX_BUF/2)
93 cp_err(cp, LJ_ERR_XELEM);
94 newsize = cp->sb.sz * 2;
95 lj_str_resizebuf(cp->L, &cp->sb, newsize);
96 cp->sb.buf[cp->sb.n++] = (char)c;
97}
98
99/* Save character in buffer. */ 89/* Save character in buffer. */
100static LJ_AINLINE void cp_save(CPState *cp, CPChar c) 90static LJ_AINLINE void cp_save(CPState *cp, CPChar c)
101{ 91{
102 if (LJ_UNLIKELY(cp->sb.n + 1 > cp->sb.sz)) 92 lj_buf_putb(&cp->sb, c);
103 cp_save_grow(cp, c);
104 else
105 cp->sb.buf[cp->sb.n++] = (char)c;
106} 93}
107 94
108/* Skip line break. Handles "\n", "\r", "\r\n" or "\n\r". */ 95/* Skip line break. Handles "\n", "\r", "\r\n" or "\n\r". */
@@ -122,20 +109,20 @@ LJ_NORET static void cp_errmsg(CPState *cp, CPToken tok, ErrMsg em, ...)
122 tokstr = NULL; 109 tokstr = NULL;
123 } else if (tok == CTOK_IDENT || tok == CTOK_INTEGER || tok == CTOK_STRING || 110 } else if (tok == CTOK_IDENT || tok == CTOK_INTEGER || tok == CTOK_STRING ||
124 tok >= CTOK_FIRSTDECL) { 111 tok >= CTOK_FIRSTDECL) {
125 if (cp->sb.n == 0) cp_save(cp, '$'); 112 if (sbufP(&cp->sb) == sbufB(&cp->sb)) cp_save(cp, '$');
126 cp_save(cp, '\0'); 113 cp_save(cp, '\0');
127 tokstr = cp->sb.buf; 114 tokstr = sbufB(&cp->sb);
128 } else { 115 } else {
129 tokstr = cp_tok2str(cp, tok); 116 tokstr = cp_tok2str(cp, tok);
130 } 117 }
131 L = cp->L; 118 L = cp->L;
132 va_start(argp, em); 119 va_start(argp, em);
133 msg = lj_str_pushvf(L, err2msg(em), argp); 120 msg = lj_strfmt_pushvf(L, err2msg(em), argp);
134 va_end(argp); 121 va_end(argp);
135 if (tokstr) 122 if (tokstr)
136 msg = lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tokstr); 123 msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tokstr);
137 if (cp->linenumber > 1) 124 if (cp->linenumber > 1)
138 msg = lj_str_pushf(L, "%s at line %d", msg, cp->linenumber); 125 msg = lj_strfmt_pushf(L, "%s at line %d", msg, cp->linenumber);
139 lj_err_callermsg(L, msg); 126 lj_err_callermsg(L, msg);
140} 127}
141 128
@@ -164,7 +151,7 @@ static CPToken cp_number(CPState *cp)
164 TValue o; 151 TValue o;
165 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp))); 152 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
166 cp_save(cp, '\0'); 153 cp_save(cp, '\0');
167 fmt = lj_strscan_scan((const uint8_t *)cp->sb.buf, &o, STRSCAN_OPT_C); 154 fmt = lj_strscan_scan((const uint8_t *)sbufB(&cp->sb), &o, STRSCAN_OPT_C);
168 if (fmt == STRSCAN_INT) cp->val.id = CTID_INT32; 155 if (fmt == STRSCAN_INT) cp->val.id = CTID_INT32;
169 else if (fmt == STRSCAN_U32) cp->val.id = CTID_UINT32; 156 else if (fmt == STRSCAN_U32) cp->val.id = CTID_UINT32;
170 else if (!(cp->mode & CPARSE_MODE_SKIP)) 157 else if (!(cp->mode & CPARSE_MODE_SKIP))
@@ -177,7 +164,7 @@ static CPToken cp_number(CPState *cp)
177static CPToken cp_ident(CPState *cp) 164static CPToken cp_ident(CPState *cp)
178{ 165{
179 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp))); 166 do { cp_save(cp, cp->c); } while (lj_char_isident(cp_get(cp)));
180 cp->str = lj_str_new(cp->L, cp->sb.buf, cp->sb.n); 167 cp->str = lj_buf_str(cp->L, &cp->sb);
181 cp->val.id = lj_ctype_getname(cp->cts, &cp->ct, cp->str, cp->tmask); 168 cp->val.id = lj_ctype_getname(cp->cts, &cp->ct, cp->str, cp->tmask);
182 if (ctype_type(cp->ct->info) == CT_KW) 169 if (ctype_type(cp->ct->info) == CT_KW)
183 return ctype_cid(cp->ct->info); 170 return ctype_cid(cp->ct->info);
@@ -263,11 +250,11 @@ static CPToken cp_string(CPState *cp)
263 } 250 }
264 cp_get(cp); 251 cp_get(cp);
265 if (delim == '"') { 252 if (delim == '"') {
266 cp->str = lj_str_new(cp->L, cp->sb.buf, cp->sb.n); 253 cp->str = lj_buf_str(cp->L, &cp->sb);
267 return CTOK_STRING; 254 return CTOK_STRING;
268 } else { 255 } else {
269 if (cp->sb.n != 1) cp_err_token(cp, '\''); 256 if (sbuflen(&cp->sb) != 1) cp_err_token(cp, '\'');
270 cp->val.i32 = (int32_t)(char)cp->sb.buf[0]; 257 cp->val.i32 = (int32_t)(char)*sbufB(&cp->sb);
271 cp->val.id = CTID_INT32; 258 cp->val.id = CTID_INT32;
272 return CTOK_INTEGER; 259 return CTOK_INTEGER;
273 } 260 }
@@ -296,7 +283,7 @@ static void cp_comment_cpp(CPState *cp)
296/* Lexical scanner for C. Only a minimal subset is implemented. */ 283/* Lexical scanner for C. Only a minimal subset is implemented. */
297static CPToken cp_next_(CPState *cp) 284static CPToken cp_next_(CPState *cp)
298{ 285{
299 lj_str_resetbuf(&cp->sb); 286 lj_buf_reset(&cp->sb);
300 for (;;) { 287 for (;;) {
301 if (lj_char_isident(cp->c)) 288 if (lj_char_isident(cp->c))
302 return lj_char_isdigit(cp->c) ? cp_number(cp) : cp_ident(cp); 289 return lj_char_isdigit(cp->c) ? cp_number(cp) : cp_ident(cp);
@@ -385,8 +372,7 @@ static void cp_init(CPState *cp)
385 cp->depth = 0; 372 cp->depth = 0;
386 cp->curpack = 0; 373 cp->curpack = 0;
387 cp->packstack[0] = 255; 374 cp->packstack[0] = 255;
388 lj_str_initbuf(&cp->sb); 375 lj_buf_init(cp->L, &cp->sb);
389 lj_str_resizebuf(cp->L, &cp->sb, LJ_MIN_SBUF);
390 lua_assert(cp->p != NULL); 376 lua_assert(cp->p != NULL);
391 cp_get(cp); /* Read-ahead first char. */ 377 cp_get(cp); /* Read-ahead first char. */
392 cp->tok = 0; 378 cp->tok = 0;
@@ -398,7 +384,7 @@ static void cp_init(CPState *cp)
398static void cp_cleanup(CPState *cp) 384static void cp_cleanup(CPState *cp)
399{ 385{
400 global_State *g = G(cp->L); 386 global_State *g = G(cp->L);
401 lj_str_freebuf(g, &cp->sb); 387 lj_buf_free(g, &cp->sb);
402} 388}
403 389
404/* Check and consume optional token. */ 390/* Check and consume optional token. */
@@ -1021,7 +1007,7 @@ static void cp_decl_asm(CPState *cp, CPDecl *decl)
1021 if (cp->tok == CTOK_STRING) { 1007 if (cp->tok == CTOK_STRING) {
1022 GCstr *str = cp->str; 1008 GCstr *str = cp->str;
1023 while (cp_next(cp) == CTOK_STRING) { 1009 while (cp_next(cp) == CTOK_STRING) {
1024 lj_str_pushf(cp->L, "%s%s", strdata(str), strdata(cp->str)); 1010 lj_strfmt_pushf(cp->L, "%s%s", strdata(str), strdata(cp->str));
1025 cp->L->top--; 1011 cp->L->top--;
1026 str = strV(cp->L->top); 1012 str = strV(cp->L->top);
1027 } 1013 }
@@ -1763,6 +1749,16 @@ static void cp_pragma(CPState *cp, BCLine pragmaline)
1763 } 1749 }
1764} 1750}
1765 1751
1752/* Handle line number. */
1753static void cp_line(CPState *cp, BCLine hashline)
1754{
1755 BCLine newline = cp->val.u32;
1756 /* TODO: Handle file name and include it in error messages. */
1757 while (cp->tok != CTOK_EOF && cp->linenumber == hashline)
1758 cp_next(cp);
1759 cp->linenumber = newline;
1760}
1761
1766/* Parse multiple C declarations of types or extern identifiers. */ 1762/* Parse multiple C declarations of types or extern identifiers. */
1767static void cp_decl_multi(CPState *cp) 1763static void cp_decl_multi(CPState *cp)
1768{ 1764{
@@ -1775,12 +1771,23 @@ static void cp_decl_multi(CPState *cp)
1775 continue; 1771 continue;
1776 } 1772 }
1777 if (cp->tok == '#') { /* Workaround, since we have no preprocessor, yet. */ 1773 if (cp->tok == '#') { /* Workaround, since we have no preprocessor, yet. */
1778 BCLine pragmaline = cp->linenumber; 1774 BCLine hashline = cp->linenumber;
1779 if (!(cp_next(cp) == CTOK_IDENT && 1775 CPToken tok = cp_next(cp);
1780 cp->str->hash == H_(f5e6b4f8,1d509107))) /* pragma */ 1776 if (tok == CTOK_INTEGER) {
1777 cp_line(cp, hashline);
1778 continue;
1779 } else if (tok == CTOK_IDENT &&
1780 cp->str->hash == H_(187aab88,fcb60b42)) { /* line */
1781 if (cp_next(cp) != CTOK_INTEGER) cp_err_token(cp, tok);
1782 cp_line(cp, hashline);
1783 continue;
1784 } else if (tok == CTOK_IDENT &&
1785 cp->str->hash == H_(f5e6b4f8,1d509107)) { /* pragma */
1786 cp_pragma(cp, hashline);
1787 continue;
1788 } else {
1781 cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL); 1789 cp_errmsg(cp, cp->tok, LJ_ERR_XSYMBOL);
1782 cp_pragma(cp, pragmaline); 1790 }
1783 continue;
1784 } 1791 }
1785 scl = cp_decl_spec(cp, &decl, CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC); 1792 scl = cp_decl_spec(cp, &decl, CDF_TYPEDEF|CDF_EXTERN|CDF_STATIC);
1786 if ((cp->tok == ';' || cp->tok == CTOK_EOF) && 1793 if ((cp->tok == ';' || cp->tok == CTOK_EOF) &&
diff --git a/src/lj_crecord.c b/src/lj_crecord.c
index 84fc49ee..2db4c86b 100644
--- a/src/lj_crecord.c
+++ b/src/lj_crecord.c
@@ -11,13 +11,13 @@
11#if LJ_HASJIT && LJ_HASFFI 11#if LJ_HASJIT && LJ_HASFFI
12 12
13#include "lj_err.h" 13#include "lj_err.h"
14#include "lj_str.h"
15#include "lj_tab.h" 14#include "lj_tab.h"
16#include "lj_frame.h" 15#include "lj_frame.h"
17#include "lj_ctype.h" 16#include "lj_ctype.h"
18#include "lj_cdata.h" 17#include "lj_cdata.h"
19#include "lj_cparse.h" 18#include "lj_cparse.h"
20#include "lj_cconv.h" 19#include "lj_cconv.h"
20#include "lj_carith.h"
21#include "lj_clib.h" 21#include "lj_clib.h"
22#include "lj_ccall.h" 22#include "lj_ccall.h"
23#include "lj_ff.h" 23#include "lj_ff.h"
@@ -31,6 +31,7 @@
31#include "lj_snap.h" 31#include "lj_snap.h"
32#include "lj_crecord.h" 32#include "lj_crecord.h"
33#include "lj_dispatch.h" 33#include "lj_dispatch.h"
34#include "lj_strfmt.h"
34 35
35/* Some local macros to save typing. Undef'd at the end. */ 36/* Some local macros to save typing. Undef'd at the end. */
36#define IR(ref) (&J->cur.ir[(ref)]) 37#define IR(ref) (&J->cur.ir[(ref)])
@@ -441,7 +442,7 @@ static TRef crec_ct_ct(jit_State *J, CType *d, CType *s, TRef dp, TRef sp,
441 /* fallthrough */ 442 /* fallthrough */
442 case CCX(I, F): 443 case CCX(I, F):
443 if (dt == IRT_CDATA || st == IRT_CDATA) goto err_nyi; 444 if (dt == IRT_CDATA || st == IRT_CDATA) goto err_nyi;
444 sp = emitconv(sp, dsize < 4 ? IRT_INT : dt, st, IRCONV_TRUNC|IRCONV_ANY); 445 sp = emitconv(sp, dsize < 4 ? IRT_INT : dt, st, IRCONV_ANY);
445 goto xstore; 446 goto xstore;
446 case CCX(I, P): 447 case CCX(I, P):
447 case CCX(I, A): 448 case CCX(I, A):
@@ -521,7 +522,7 @@ static TRef crec_ct_ct(jit_State *J, CType *d, CType *s, TRef dp, TRef sp,
521 if (st == IRT_CDATA) goto err_nyi; 522 if (st == IRT_CDATA) goto err_nyi;
522 /* The signed conversion is cheaper. x64 really has 47 bit pointers. */ 523 /* The signed conversion is cheaper. x64 really has 47 bit pointers. */
523 sp = emitconv(sp, (LJ_64 && dsize == 8) ? IRT_I64 : IRT_U32, 524 sp = emitconv(sp, (LJ_64 && dsize == 8) ? IRT_I64 : IRT_U32,
524 st, IRCONV_TRUNC|IRCONV_ANY); 525 st, IRCONV_ANY);
525 goto xstore; 526 goto xstore;
526 527
527 /* Destination is an array. */ 528 /* Destination is an array. */
@@ -640,12 +641,23 @@ static TRef crec_ct_tv(jit_State *J, CType *d, TRef dp, TRef sp, cTValue *sval)
640 sp = emitir(IRT(IR_ADD, IRT_PTR), sp, lj_ir_kintp(J, sizeof(GCstr))); 641 sp = emitir(IRT(IR_ADD, IRT_PTR), sp, lj_ir_kintp(J, sizeof(GCstr)));
641 sid = CTID_A_CCHAR; 642 sid = CTID_A_CCHAR;
642 } 643 }
643 } else { /* NYI: tref_istab(sp), tref_islightud(sp). */ 644 } else if (tref_islightud(sp)) {
645#if LJ_64
646 sp = emitir(IRT(IR_BAND, IRT_P64), sp,
647 lj_ir_kint64(J, U64x(00007fff,ffffffff)));
648#endif
649 } else { /* NYI: tref_istab(sp). */
644 IRType t; 650 IRType t;
645 sid = argv2cdata(J, sp, sval)->ctypeid; 651 sid = argv2cdata(J, sp, sval)->ctypeid;
646 s = ctype_raw(cts, sid); 652 s = ctype_raw(cts, sid);
647 svisnz = cdataptr(cdataV(sval)); 653 svisnz = cdataptr(cdataV(sval));
648 t = crec_ct2irt(cts, s); 654 if (ctype_isfunc(s->info)) {
655 sid = lj_ctype_intern(cts, CTINFO(CT_PTR, CTALIGN_PTR|sid), CTSIZE_PTR);
656 s = ctype_get(cts, sid);
657 t = IRT_PTR;
658 } else {
659 t = crec_ct2irt(cts, s);
660 }
649 if (ctype_isptr(s->info)) { 661 if (ctype_isptr(s->info)) {
650 sp = emitir(IRT(IR_FLOAD, t), sp, IRFL_CDATA_PTR); 662 sp = emitir(IRT(IR_FLOAD, t), sp, IRFL_CDATA_PTR);
651 if (ctype_isref(s->info)) { 663 if (ctype_isref(s->info)) {
@@ -700,6 +712,19 @@ static TRef crec_reassoc_ofs(jit_State *J, TRef tr, ptrdiff_t *ofsp, MSize sz)
700 return tr; 712 return tr;
701} 713}
702 714
715/* Tailcall to function. */
716static void crec_tailcall(jit_State *J, RecordFFData *rd, cTValue *tv)
717{
718 TRef kfunc = lj_ir_kfunc(J, funcV(tv));
719#if LJ_FR2
720 J->base[-2] = kfunc;
721 J->base[-1] = TREF_FRAME;
722#else
723 J->base[-1] = kfunc | TREF_FRAME;
724#endif
725 rd->nres = -1; /* Pending tailcall. */
726}
727
703/* Record ctype __index/__newindex metamethods. */ 728/* Record ctype __index/__newindex metamethods. */
704static void crec_index_meta(jit_State *J, CTState *cts, CType *ct, 729static void crec_index_meta(jit_State *J, CTState *cts, CType *ct,
705 RecordFFData *rd) 730 RecordFFData *rd)
@@ -709,8 +734,7 @@ static void crec_index_meta(jit_State *J, CTState *cts, CType *ct,
709 if (!tv) 734 if (!tv)
710 lj_trace_err(J, LJ_TRERR_BADTYPE); 735 lj_trace_err(J, LJ_TRERR_BADTYPE);
711 if (tvisfunc(tv)) { 736 if (tvisfunc(tv)) {
712 J->base[-1] = lj_ir_kfunc(J, funcV(tv)) | TREF_FRAME; 737 crec_tailcall(J, rd, tv);
713 rd->nres = -1; /* Pending tailcall. */
714 } else if (rd->data == 0 && tvistab(tv) && tref_isstr(J->base[1])) { 738 } else if (rd->data == 0 && tvistab(tv) && tref_isstr(J->base[1])) {
715 /* Specialize to result of __index lookup. */ 739 /* Specialize to result of __index lookup. */
716 cTValue *o = lj_tab_get(J->L, tabV(tv), &rd->argv[1]); 740 cTValue *o = lj_tab_get(J->L, tabV(tv), &rd->argv[1]);
@@ -867,21 +891,17 @@ again:
867} 891}
868 892
869/* Record setting a finalizer. */ 893/* Record setting a finalizer. */
870static void crec_finalizer(jit_State *J, TRef trcd, cTValue *fin) 894static void crec_finalizer(jit_State *J, TRef trcd, TRef trfin, cTValue *fin)
871{ 895{
872 TRef trlo = lj_ir_call(J, IRCALL_lj_cdata_setfin, trcd); 896 if (tvisgcv(fin)) {
873 TRef trhi = emitir(IRT(IR_ADD, IRT_P32), trlo, lj_ir_kint(J, 4)); 897 if (!trfin) trfin = lj_ir_kptr(J, gcval(fin));
874 if (LJ_BE) { TRef tmp = trlo; trlo = trhi; trhi = tmp; } 898 } else if (tvisnil(fin)) {
875 if (tvisfunc(fin)) { 899 trfin = lj_ir_kptr(J, NULL);
876 emitir(IRT(IR_XSTORE, IRT_P32), trlo, lj_ir_kfunc(J, funcV(fin)));
877 emitir(IRTI(IR_XSTORE), trhi, lj_ir_kint(J, LJ_TFUNC));
878 } else if (tviscdata(fin)) {
879 emitir(IRT(IR_XSTORE, IRT_P32), trlo,
880 lj_ir_kgc(J, obj2gco(cdataV(fin)), IRT_CDATA));
881 emitir(IRTI(IR_XSTORE), trhi, lj_ir_kint(J, LJ_TCDATA));
882 } else { 900 } else {
883 lj_trace_err(J, LJ_TRERR_BADTYPE); 901 lj_trace_err(J, LJ_TRERR_BADTYPE);
884 } 902 }
903 lj_ir_call(J, IRCALL_lj_cdata_setfin, trcd,
904 trfin, lj_ir_kint(J, (int32_t)itype(fin)));
885 J->needsnap = 1; 905 J->needsnap = 1;
886} 906}
887 907
@@ -892,10 +912,8 @@ static void crec_alloc(jit_State *J, RecordFFData *rd, CTypeID id)
892 CTSize sz; 912 CTSize sz;
893 CTInfo info = lj_ctype_info(cts, id, &sz); 913 CTInfo info = lj_ctype_info(cts, id, &sz);
894 CType *d = ctype_raw(cts, id); 914 CType *d = ctype_raw(cts, id);
895 TRef trid; 915 TRef trcd, trid = lj_ir_kint(J, id);
896 if (!sz || sz > 128 || (info & CTF_VLA) || ctype_align(info) > CT_MEMALIGN) 916 cTValue *fin;
897 lj_trace_err(J, LJ_TRERR_NYICONV); /* NYI: large/special allocations. */
898 trid = lj_ir_kint(J, id);
899 /* Use special instruction to box pointer or 32/64 bit integer. */ 917 /* Use special instruction to box pointer or 32/64 bit integer. */
900 if (ctype_isptr(info) || (ctype_isinteger(info) && (sz == 4 || sz == 8))) { 918 if (ctype_isptr(info) || (ctype_isinteger(info) && (sz == 4 || sz == 8))) {
901 TRef sp = J->base[1] ? crec_ct_tv(J, d, 0, J->base[1], &rd->argv[1]) : 919 TRef sp = J->base[1] ? crec_ct_tv(J, d, 0, J->base[1], &rd->argv[1]) :
@@ -903,11 +921,36 @@ static void crec_alloc(jit_State *J, RecordFFData *rd, CTypeID id)
903 sz == 4 ? lj_ir_kint(J, 0) : 921 sz == 4 ? lj_ir_kint(J, 0) :
904 (lj_needsplit(J), lj_ir_kint64(J, 0)); 922 (lj_needsplit(J), lj_ir_kint64(J, 0));
905 J->base[0] = emitir(IRTG(IR_CNEWI, IRT_CDATA), trid, sp); 923 J->base[0] = emitir(IRTG(IR_CNEWI, IRT_CDATA), trid, sp);
924 return;
906 } else { 925 } else {
907 TRef trcd = emitir(IRTG(IR_CNEW, IRT_CDATA), trid, TREF_NIL); 926 TRef trsz = TREF_NIL;
908 cTValue *fin; 927 if ((info & CTF_VLA)) { /* Calculate VLA/VLS size at runtime. */
909 J->base[0] = trcd; 928 CTSize sz0, sz1;
910 if (J->base[1] && !J->base[2] && 929 if (!J->base[1] || J->base[2])
930 lj_trace_err(J, LJ_TRERR_NYICONV); /* NYI: init VLA/VLS. */
931 trsz = crec_ct_tv(J, ctype_get(cts, CTID_INT32), 0,
932 J->base[1], &rd->argv[1]);
933 sz0 = lj_ctype_vlsize(cts, d, 0);
934 sz1 = lj_ctype_vlsize(cts, d, 1);
935 trsz = emitir(IRTGI(IR_MULOV), trsz, lj_ir_kint(J, (int32_t)(sz1-sz0)));
936 trsz = emitir(IRTGI(IR_ADDOV), trsz, lj_ir_kint(J, (int32_t)sz0));
937 J->base[1] = 0; /* Simplify logic below. */
938 } else if (ctype_align(info) > CT_MEMALIGN) {
939 trsz = lj_ir_kint(J, sz);
940 }
941 trcd = emitir(IRTG(IR_CNEW, IRT_CDATA), trid, trsz);
942 if (sz > 128 || (info & CTF_VLA)) {
943 TRef dp;
944 CTSize align;
945 special: /* Only handle bulk zero-fill for large/VLA/VLS types. */
946 if (J->base[1])
947 lj_trace_err(J, LJ_TRERR_NYICONV); /* NYI: init large/VLA/VLS types. */
948 dp = emitir(IRT(IR_ADD, IRT_PTR), trcd, lj_ir_kintp(J, sizeof(GCcdata)));
949 if (trsz == TREF_NIL) trsz = lj_ir_kint(J, sz);
950 align = ctype_align(info);
951 if (align < CT_MEMALIGN) align = CT_MEMALIGN;
952 crec_fill(J, dp, trsz, lj_ir_kint(J, 0), (1u << align));
953 } else if (J->base[1] && !J->base[2] &&
911 !lj_cconv_multi_init(cts, d, &rd->argv[1])) { 954 !lj_cconv_multi_init(cts, d, &rd->argv[1])) {
912 goto single_init; 955 goto single_init;
913 } else if (ctype_isarray(d->info)) { 956 } else if (ctype_isarray(d->info)) {
@@ -918,8 +961,9 @@ static void crec_alloc(jit_State *J, RecordFFData *rd, CTypeID id)
918 TValue *sval = &tv; 961 TValue *sval = &tv;
919 MSize i; 962 MSize i;
920 tv.u64 = 0; 963 tv.u64 = 0;
921 if (!(ctype_isnum(dc->info) || ctype_isptr(dc->info))) 964 if (!(ctype_isnum(dc->info) || ctype_isptr(dc->info)) ||
922 lj_trace_err(J, LJ_TRERR_NYICONV); /* NYI: init array of aggregates. */ 965 esize * CREC_FILL_MAXUNROLL < sz)
966 goto special;
923 for (i = 1, ofs = 0; ofs < sz; ofs += esize) { 967 for (i = 1, ofs = 0; ofs < sz; ofs += esize) {
924 TRef dp = emitir(IRT(IR_ADD, IRT_PTR), trcd, 968 TRef dp = emitir(IRT(IR_ADD, IRT_PTR), trcd,
925 lj_ir_kintp(J, ofs + sizeof(GCcdata))); 969 lj_ir_kintp(J, ofs + sizeof(GCcdata)));
@@ -976,11 +1020,12 @@ static void crec_alloc(jit_State *J, RecordFFData *rd, CTypeID id)
976 crec_ct_tv(J, d, dp, lj_ir_kint(J, 0), &tv); 1020 crec_ct_tv(J, d, dp, lj_ir_kint(J, 0), &tv);
977 } 1021 }
978 } 1022 }
979 /* Handle __gc metamethod. */
980 fin = lj_ctype_meta(cts, id, MM_gc);
981 if (fin)
982 crec_finalizer(J, trcd, fin);
983 } 1023 }
1024 J->base[0] = trcd;
1025 /* Handle __gc metamethod. */
1026 fin = lj_ctype_meta(cts, id, MM_gc);
1027 if (fin)
1028 crec_finalizer(J, trcd, 0, fin);
984} 1029}
985 1030
986/* Record argument conversions. */ 1031/* Record argument conversions. */
@@ -1086,20 +1131,20 @@ static void crec_snap_caller(jit_State *J)
1086 lua_State *L = J->L; 1131 lua_State *L = J->L;
1087 TValue *base = L->base, *top = L->top; 1132 TValue *base = L->base, *top = L->top;
1088 const BCIns *pc = J->pc; 1133 const BCIns *pc = J->pc;
1089 TRef ftr = J->base[-1]; 1134 TRef ftr = J->base[-1-LJ_FR2];
1090 ptrdiff_t delta; 1135 ptrdiff_t delta;
1091 if (!frame_islua(base-1) || J->framedepth <= 0) 1136 if (!frame_islua(base-1) || J->framedepth <= 0)
1092 lj_trace_err(J, LJ_TRERR_NYICALL); 1137 lj_trace_err(J, LJ_TRERR_NYICALL);
1093 J->pc = frame_pc(base-1); delta = 1+bc_a(J->pc[-1]); 1138 J->pc = frame_pc(base-1); delta = 1+LJ_FR2+bc_a(J->pc[-1]);
1094 L->top = base; L->base = base - delta; 1139 L->top = base; L->base = base - delta;
1095 J->base[-1] = TREF_FALSE; 1140 J->base[-1-LJ_FR2] = TREF_FALSE;
1096 J->base -= delta; J->baseslot -= (BCReg)delta; 1141 J->base -= delta; J->baseslot -= (BCReg)delta;
1097 J->maxslot = (BCReg)delta; J->framedepth--; 1142 J->maxslot = (BCReg)delta-LJ_FR2; J->framedepth--;
1098 lj_snap_add(J); 1143 lj_snap_add(J);
1099 L->base = base; L->top = top; 1144 L->base = base; L->top = top;
1100 J->framedepth++; J->maxslot = 1; 1145 J->framedepth++; J->maxslot = 1;
1101 J->base += delta; J->baseslot += (BCReg)delta; 1146 J->base += delta; J->baseslot += (BCReg)delta;
1102 J->base[-1] = ftr; J->pc = pc; 1147 J->base[-1-LJ_FR2] = ftr; J->pc = pc;
1103} 1148}
1104 1149
1105/* Record function call. */ 1150/* Record function call. */
@@ -1191,8 +1236,7 @@ void LJ_FASTCALL recff_cdata_call(jit_State *J, RecordFFData *rd)
1191 tv = lj_ctype_meta(cts, ctype_isptr(ct->info) ? ctype_cid(ct->info) : id, mm); 1236 tv = lj_ctype_meta(cts, ctype_isptr(ct->info) ? ctype_cid(ct->info) : id, mm);
1192 if (tv) { 1237 if (tv) {
1193 if (tvisfunc(tv)) { 1238 if (tvisfunc(tv)) {
1194 J->base[-1] = lj_ir_kfunc(J, funcV(tv)) | TREF_FRAME; 1239 crec_tailcall(J, rd, tv);
1195 rd->nres = -1; /* Pending tailcall. */
1196 return; 1240 return;
1197 } 1241 }
1198 } else if (mm == MM_new) { 1242 } else if (mm == MM_new) {
@@ -1233,7 +1277,7 @@ static TRef crec_arith_int64(jit_State *J, TRef *sp, CType **s, MMS mm)
1233 for (i = 0; i < 2; i++) { 1277 for (i = 0; i < 2; i++) {
1234 IRType st = tref_type(sp[i]); 1278 IRType st = tref_type(sp[i]);
1235 if (st == IRT_NUM || st == IRT_FLOAT) 1279 if (st == IRT_NUM || st == IRT_FLOAT)
1236 sp[i] = emitconv(sp[i], dt, st, IRCONV_TRUNC|IRCONV_ANY); 1280 sp[i] = emitconv(sp[i], dt, st, IRCONV_ANY);
1237 else if (!(st == IRT_I64 || st == IRT_U64)) 1281 else if (!(st == IRT_I64 || st == IRT_U64))
1238 sp[i] = emitconv(sp[i], dt, IRT_INT, 1282 sp[i] = emitconv(sp[i], dt, IRT_INT,
1239 (s[i]->info & CTF_UNSIGNED) ? 0 : IRCONV_SEXT); 1283 (s[i]->info & CTF_UNSIGNED) ? 0 : IRCONV_SEXT);
@@ -1302,15 +1346,14 @@ static TRef crec_arith_ptr(jit_State *J, TRef *sp, CType **s, MMS mm)
1302 CTypeID id; 1346 CTypeID id;
1303#if LJ_64 1347#if LJ_64
1304 if (t == IRT_NUM || t == IRT_FLOAT) 1348 if (t == IRT_NUM || t == IRT_FLOAT)
1305 tr = emitconv(tr, IRT_INTP, t, IRCONV_TRUNC|IRCONV_ANY); 1349 tr = emitconv(tr, IRT_INTP, t, IRCONV_ANY);
1306 else if (!(t == IRT_I64 || t == IRT_U64)) 1350 else if (!(t == IRT_I64 || t == IRT_U64))
1307 tr = emitconv(tr, IRT_INTP, IRT_INT, 1351 tr = emitconv(tr, IRT_INTP, IRT_INT,
1308 ((t - IRT_I8) & 1) ? 0 : IRCONV_SEXT); 1352 ((t - IRT_I8) & 1) ? 0 : IRCONV_SEXT);
1309#else 1353#else
1310 if (!tref_typerange(sp[1], IRT_I8, IRT_U32)) { 1354 if (!tref_typerange(sp[1], IRT_I8, IRT_U32)) {
1311 tr = emitconv(tr, IRT_INTP, t, 1355 tr = emitconv(tr, IRT_INTP, t,
1312 (t == IRT_NUM || t == IRT_FLOAT) ? 1356 (t == IRT_NUM || t == IRT_FLOAT) ? IRCONV_ANY : 0);
1313 IRCONV_TRUNC|IRCONV_ANY : 0);
1314 } 1357 }
1315#endif 1358#endif
1316 tr = emitir(IRT(IR_MUL, IRT_INTP), tr, lj_ir_kintp(J, sz)); 1359 tr = emitir(IRT(IR_MUL, IRT_INTP), tr, lj_ir_kintp(J, sz));
@@ -1342,8 +1385,7 @@ static TRef crec_arith_meta(jit_State *J, TRef *sp, CType **s, CTState *cts,
1342 } 1385 }
1343 if (tv) { 1386 if (tv) {
1344 if (tvisfunc(tv)) { 1387 if (tvisfunc(tv)) {
1345 J->base[-1] = lj_ir_kfunc(J, funcV(tv)) | TREF_FRAME; 1388 crec_tailcall(J, rd, tv);
1346 rd->nres = -1; /* Pending tailcall. */
1347 return 0; 1389 return 0;
1348 } /* NYI: non-function metamethods. */ 1390 } /* NYI: non-function metamethods. */
1349 } else if ((MMS)rd->data == MM_eq) { /* Fallback cdata pointer comparison. */ 1391 } else if ((MMS)rd->data == MM_eq) { /* Fallback cdata pointer comparison. */
@@ -1453,8 +1495,7 @@ void LJ_FASTCALL recff_cdata_arith(jit_State *J, RecordFFData *rd)
1453 !irt_isguard(J->guardemit)) { 1495 !irt_isguard(J->guardemit)) {
1454 const BCIns *pc = frame_contpc(J->L->base-1) - 1; 1496 const BCIns *pc = frame_contpc(J->L->base-1) - 1;
1455 if (bc_op(*pc) <= BC_ISNEP) { 1497 if (bc_op(*pc) <= BC_ISNEP) {
1456 setframe_pc(&J2G(J)->tmptv, pc); 1498 J2G(J)->tmptv.u64 = (uint64_t)(uintptr_t)pc;
1457 J2G(J)->tmptv.u32.lo = ((tref_istrue(tr) ^ bc_op(*pc)) & 1);
1458 J->postproc = LJ_POST_FIXCOMP; 1499 J->postproc = LJ_POST_FIXCOMP;
1459 } 1500 }
1460 } 1501 }
@@ -1643,7 +1684,139 @@ void LJ_FASTCALL recff_ffi_xof(jit_State *J, RecordFFData *rd)
1643void LJ_FASTCALL recff_ffi_gc(jit_State *J, RecordFFData *rd) 1684void LJ_FASTCALL recff_ffi_gc(jit_State *J, RecordFFData *rd)
1644{ 1685{
1645 argv2cdata(J, J->base[0], &rd->argv[0]); 1686 argv2cdata(J, J->base[0], &rd->argv[0]);
1646 crec_finalizer(J, J->base[0], &rd->argv[1]); 1687 if (!J->base[1])
1688 lj_trace_err(J, LJ_TRERR_BADTYPE);
1689 crec_finalizer(J, J->base[0], J->base[1], &rd->argv[1]);
1690}
1691
1692/* -- 64 bit bit.* library functions -------------------------------------- */
1693
1694/* Determine bit operation type from argument type. */
1695static CTypeID crec_bit64_type(CTState *cts, cTValue *tv)
1696{
1697 if (tviscdata(tv)) {
1698 CType *ct = lj_ctype_rawref(cts, cdataV(tv)->ctypeid);
1699 if (ctype_isenum(ct->info)) ct = ctype_child(cts, ct);
1700 if ((ct->info & (CTMASK_NUM|CTF_BOOL|CTF_FP|CTF_UNSIGNED)) ==
1701 CTINFO(CT_NUM, CTF_UNSIGNED) && ct->size == 8)
1702 return CTID_UINT64; /* Use uint64_t, since it has the highest rank. */
1703 return CTID_INT64; /* Otherwise use int64_t. */
1704 }
1705 return 0; /* Use regular 32 bit ops. */
1706}
1707
1708void LJ_FASTCALL recff_bit64_tobit(jit_State *J, RecordFFData *rd)
1709{
1710 CTState *cts = ctype_ctsG(J2G(J));
1711 TRef tr = crec_ct_tv(J, ctype_get(cts, CTID_INT64), 0,
1712 J->base[0], &rd->argv[0]);
1713 if (!tref_isinteger(tr))
1714 tr = emitconv(tr, IRT_INT, tref_type(tr), 0);
1715 J->base[0] = tr;
1716}
1717
1718int LJ_FASTCALL recff_bit64_unary(jit_State *J, RecordFFData *rd)
1719{
1720 CTState *cts = ctype_ctsG(J2G(J));
1721 CTypeID id = crec_bit64_type(cts, &rd->argv[0]);
1722 if (id) {
1723 TRef tr = crec_ct_tv(J, ctype_get(cts, id), 0, J->base[0], &rd->argv[0]);
1724 tr = emitir(IRT(rd->data, id-CTID_INT64+IRT_I64), tr, 0);
1725 J->base[0] = emitir(IRTG(IR_CNEWI, IRT_CDATA), lj_ir_kint(J, id), tr);
1726 return 1;
1727 }
1728 return 0;
1729}
1730
1731int LJ_FASTCALL recff_bit64_nary(jit_State *J, RecordFFData *rd)
1732{
1733 CTState *cts = ctype_ctsG(J2G(J));
1734 CTypeID id = 0;
1735 MSize i;
1736 for (i = 0; J->base[i] != 0; i++) {
1737 CTypeID aid = crec_bit64_type(cts, &rd->argv[i]);
1738 if (id < aid) id = aid; /* Determine highest type rank of all arguments. */
1739 }
1740 if (id) {
1741 CType *ct = ctype_get(cts, id);
1742 uint32_t ot = IRT(rd->data, id-CTID_INT64+IRT_I64);
1743 TRef tr = crec_ct_tv(J, ct, 0, J->base[0], &rd->argv[0]);
1744 for (i = 1; J->base[i] != 0; i++) {
1745 TRef tr2 = crec_ct_tv(J, ct, 0, J->base[i], &rd->argv[i]);
1746 tr = emitir(ot, tr, tr2);
1747 }
1748 J->base[0] = emitir(IRTG(IR_CNEWI, IRT_CDATA), lj_ir_kint(J, id), tr);
1749 return 1;
1750 }
1751 return 0;
1752}
1753
1754int LJ_FASTCALL recff_bit64_shift(jit_State *J, RecordFFData *rd)
1755{
1756 CTState *cts = ctype_ctsG(J2G(J));
1757 CTypeID id;
1758 TRef tsh = 0;
1759 if (J->base[0] && tref_iscdata(J->base[1])) {
1760 tsh = crec_ct_tv(J, ctype_get(cts, CTID_INT64), 0,
1761 J->base[1], &rd->argv[1]);
1762 if (!tref_isinteger(tsh))
1763 tsh = emitconv(tsh, IRT_INT, tref_type(tsh), 0);
1764 J->base[1] = tsh;
1765 }
1766 id = crec_bit64_type(cts, &rd->argv[0]);
1767 if (id) {
1768 TRef tr = crec_ct_tv(J, ctype_get(cts, id), 0, J->base[0], &rd->argv[0]);
1769 uint32_t op = rd->data;
1770 if (!tsh) tsh = lj_opt_narrow_tobit(J, J->base[1]);
1771 if (!(op < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) &&
1772 !tref_isk(tsh))
1773 tsh = emitir(IRTI(IR_BAND), tsh, lj_ir_kint(J, 63));
1774#ifdef LJ_TARGET_UNIFYROT
1775 if (op == (LJ_TARGET_UNIFYROT == 1 ? IR_BROR : IR_BROL)) {
1776 op = LJ_TARGET_UNIFYROT == 1 ? IR_BROL : IR_BROR;
1777 tsh = emitir(IRTI(IR_NEG), tsh, tsh);
1778 }
1779#endif
1780 tr = emitir(IRT(op, id-CTID_INT64+IRT_I64), tr, tsh);
1781 J->base[0] = emitir(IRTG(IR_CNEWI, IRT_CDATA), lj_ir_kint(J, id), tr);
1782 return 1;
1783 }
1784 return 0;
1785}
1786
1787TRef recff_bit64_tohex(jit_State *J, RecordFFData *rd, TRef hdr)
1788{
1789 CTState *cts = ctype_ctsG(J2G(J));
1790 CTypeID id = crec_bit64_type(cts, &rd->argv[0]);
1791 TRef tr, trsf = J->base[1];
1792 SFormat sf = (STRFMT_UINT|STRFMT_T_HEX);
1793 int32_t n;
1794 if (trsf) {
1795 CTypeID id2 = 0;
1796 n = (int32_t)lj_carith_check64(J->L, 2, &id2);
1797 if (id2)
1798 trsf = crec_ct_tv(J, ctype_get(cts, CTID_INT32), 0, trsf, &rd->argv[1]);
1799 else
1800 trsf = lj_opt_narrow_tobit(J, trsf);
1801 emitir(IRTGI(IR_EQ), trsf, lj_ir_kint(J, n)); /* Specialize to n. */
1802 } else {
1803 n = id ? 16 : 8;
1804 }
1805 if (n < 0) { n = -n; sf |= STRFMT_F_UPPER; }
1806 sf |= ((SFormat)((n+1)&255) << STRFMT_SH_PREC);
1807 if (id) {
1808 tr = crec_ct_tv(J, ctype_get(cts, id), 0, J->base[0], &rd->argv[0]);
1809 if (n < 16)
1810 tr = emitir(IRT(IR_BAND, IRT_U64), tr,
1811 lj_ir_kint64(J, ((uint64_t)1 << 4*n)-1));
1812 } else {
1813 tr = lj_opt_narrow_tobit(J, J->base[0]);
1814 if (n < 8)
1815 tr = emitir(IRTI(IR_BAND), tr, lj_ir_kint(J, (int32_t)((1u << 4*n)-1)));
1816 tr = emitconv(tr, IRT_U64, IRT_INT, 0); /* No sign-extension. */
1817 lj_needsplit(J);
1818 }
1819 return lj_ir_call(J, IRCALL_lj_strfmt_putfxint, hdr, lj_ir_kint(J, sf), tr);
1647} 1820}
1648 1821
1649/* -- Miscellaneous library functions ------------------------------------- */ 1822/* -- Miscellaneous library functions ------------------------------------- */
diff --git a/src/lj_crecord.h b/src/lj_crecord.h
index 8e0afd18..c165def4 100644
--- a/src/lj_crecord.h
+++ b/src/lj_crecord.h
@@ -25,6 +25,13 @@ LJ_FUNC void LJ_FASTCALL recff_ffi_istype(jit_State *J, RecordFFData *rd);
25LJ_FUNC void LJ_FASTCALL recff_ffi_abi(jit_State *J, RecordFFData *rd); 25LJ_FUNC void LJ_FASTCALL recff_ffi_abi(jit_State *J, RecordFFData *rd);
26LJ_FUNC void LJ_FASTCALL recff_ffi_xof(jit_State *J, RecordFFData *rd); 26LJ_FUNC void LJ_FASTCALL recff_ffi_xof(jit_State *J, RecordFFData *rd);
27LJ_FUNC void LJ_FASTCALL recff_ffi_gc(jit_State *J, RecordFFData *rd); 27LJ_FUNC void LJ_FASTCALL recff_ffi_gc(jit_State *J, RecordFFData *rd);
28
29LJ_FUNC void LJ_FASTCALL recff_bit64_tobit(jit_State *J, RecordFFData *rd);
30LJ_FUNC int LJ_FASTCALL recff_bit64_unary(jit_State *J, RecordFFData *rd);
31LJ_FUNC int LJ_FASTCALL recff_bit64_nary(jit_State *J, RecordFFData *rd);
32LJ_FUNC int LJ_FASTCALL recff_bit64_shift(jit_State *J, RecordFFData *rd);
33LJ_FUNC TRef recff_bit64_tohex(jit_State *J, RecordFFData *rd, TRef hdr);
34
28LJ_FUNC void LJ_FASTCALL lj_crecord_tonumber(jit_State *J, RecordFFData *rd); 35LJ_FUNC void LJ_FASTCALL lj_crecord_tonumber(jit_State *J, RecordFFData *rd);
29#endif 36#endif
30 37
diff --git a/src/lj_ctype.c b/src/lj_ctype.c
index 9417500c..0ea89c74 100644
--- a/src/lj_ctype.c
+++ b/src/lj_ctype.c
@@ -11,8 +11,10 @@
11#include "lj_err.h" 11#include "lj_err.h"
12#include "lj_str.h" 12#include "lj_str.h"
13#include "lj_tab.h" 13#include "lj_tab.h"
14#include "lj_strfmt.h"
14#include "lj_ctype.h" 15#include "lj_ctype.h"
15#include "lj_ccallback.h" 16#include "lj_ccallback.h"
17#include "lj_buf.h"
16 18
17/* -- C type definitions -------------------------------------------------- */ 19/* -- C type definitions -------------------------------------------------- */
18 20
@@ -37,6 +39,8 @@
37 _("uint64_t", UINT64) \ 39 _("uint64_t", UINT64) \
38 _("intptr_t", INT_PSZ) \ 40 _("intptr_t", INT_PSZ) \
39 _("uintptr_t", UINT_PSZ) \ 41 _("uintptr_t", UINT_PSZ) \
42 /* From POSIX. */ \
43 _("ssize_t", INT_PSZ) \
40 /* End of typedef list. */ 44 /* End of typedef list. */
41 45
42/* Keywords (only the ones we actually care for). */ 46/* Keywords (only the ones we actually care for). */
@@ -568,19 +572,18 @@ GCstr *lj_ctype_repr_int64(lua_State *L, uint64_t n, int isunsigned)
568/* Convert complex to string with 'i' or 'I' suffix. */ 572/* Convert complex to string with 'i' or 'I' suffix. */
569GCstr *lj_ctype_repr_complex(lua_State *L, void *sp, CTSize size) 573GCstr *lj_ctype_repr_complex(lua_State *L, void *sp, CTSize size)
570{ 574{
571 char buf[2*LJ_STR_NUMBUF+2+1]; 575 SBuf *sb = lj_buf_tmp_(L);
572 TValue re, im; 576 TValue re, im;
573 size_t len;
574 if (size == 2*sizeof(double)) { 577 if (size == 2*sizeof(double)) {
575 re.n = *(double *)sp; im.n = ((double *)sp)[1]; 578 re.n = *(double *)sp; im.n = ((double *)sp)[1];
576 } else { 579 } else {
577 re.n = (double)*(float *)sp; im.n = (double)((float *)sp)[1]; 580 re.n = (double)*(float *)sp; im.n = (double)((float *)sp)[1];
578 } 581 }
579 len = lj_str_bufnum(buf, &re); 582 lj_strfmt_putfnum(sb, STRFMT_G14, re.n);
580 if (!(im.u32.hi & 0x80000000u) || im.n != im.n) buf[len++] = '+'; 583 if (!(im.u32.hi & 0x80000000u) || im.n != im.n) lj_buf_putchar(sb, '+');
581 len += lj_str_bufnum(buf+len, &im); 584 lj_strfmt_putfnum(sb, STRFMT_G14, im.n);
582 buf[len] = buf[len-1] >= 'a' ? 'I' : 'i'; 585 lj_buf_putchar(sb, sbufP(sb)[-1] >= 'a' ? 'I' : 'i');
583 return lj_str_new(L, buf, len+1); 586 return lj_buf_str(L, sb);
584} 587}
585 588
586/* -- C type state -------------------------------------------------------- */ 589/* -- C type state -------------------------------------------------------- */
diff --git a/src/lj_ctype.h b/src/lj_ctype.h
index 2aefd3b6..0c220a88 100644
--- a/src/lj_ctype.h
+++ b/src/lj_ctype.h
@@ -263,7 +263,7 @@ typedef struct CTState {
263/* -- Predefined types ---------------------------------------------------- */ 263/* -- Predefined types ---------------------------------------------------- */
264 264
265/* Target-dependent types. */ 265/* Target-dependent types. */
266#if LJ_TARGET_PPC || LJ_TARGET_PPCSPE 266#if LJ_TARGET_PPC
267#define CTTYDEFP(_) \ 267#define CTTYDEFP(_) \
268 _(LINT32, 4, CT_NUM, CTF_LONG|CTALIGN(2)) 268 _(LINT32, 4, CT_NUM, CTF_LONG|CTALIGN(2))
269#else 269#else
diff --git a/src/lj_debug.c b/src/lj_debug.c
index a684302c..959dc289 100644
--- a/src/lj_debug.c
+++ b/src/lj_debug.c
@@ -9,12 +9,12 @@
9#include "lj_obj.h" 9#include "lj_obj.h"
10#include "lj_err.h" 10#include "lj_err.h"
11#include "lj_debug.h" 11#include "lj_debug.h"
12#include "lj_str.h" 12#include "lj_buf.h"
13#include "lj_tab.h" 13#include "lj_tab.h"
14#include "lj_state.h" 14#include "lj_state.h"
15#include "lj_frame.h" 15#include "lj_frame.h"
16#include "lj_bc.h" 16#include "lj_bc.h"
17#include "lj_vm.h" 17#include "lj_strfmt.h"
18#if LJ_HASJIT 18#if LJ_HASJIT
19#include "lj_jit.h" 19#include "lj_jit.h"
20#endif 20#endif
@@ -24,11 +24,11 @@
24/* Get frame corresponding to a level. */ 24/* Get frame corresponding to a level. */
25cTValue *lj_debug_frame(lua_State *L, int level, int *size) 25cTValue *lj_debug_frame(lua_State *L, int level, int *size)
26{ 26{
27 cTValue *frame, *nextframe, *bot = tvref(L->stack); 27 cTValue *frame, *nextframe, *bot = tvref(L->stack)+LJ_FR2;
28 /* Traverse frames backwards. */ 28 /* Traverse frames backwards. */
29 for (nextframe = frame = L->base-1; frame > bot; ) { 29 for (nextframe = frame = L->base-1; frame > bot; ) {
30 if (frame_gc(frame) == obj2gco(L)) 30 if (frame_gc(frame) == obj2gco(L))
31 level++; /* Skip dummy frames. See lj_meta_call(). */ 31 level++; /* Skip dummy frames. See lj_err_optype_call(). */
32 if (level-- == 0) { 32 if (level-- == 0) {
33 *size = (int)(nextframe - frame); 33 *size = (int)(nextframe - frame);
34 return frame; /* Level found. */ 34 return frame; /* Level found. */
@@ -87,8 +87,7 @@ static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe)
87 if (frame_islua(f)) { 87 if (frame_islua(f)) {
88 f = frame_prevl(f); 88 f = frame_prevl(f);
89 } else { 89 } else {
90 if (frame_isc(f) || (LJ_HASFFI && frame_iscont(f) && 90 if (frame_isc(f) || (frame_iscont(f) && frame_iscont_fficb(f)))
91 (f-1)->u32.lo == LJ_CONT_FFI_CALLBACK))
92 cf = cframe_raw(cframe_prev(cf)); 91 cf = cframe_raw(cframe_prev(cf));
93 f = frame_prevd(f); 92 f = frame_prevd(f);
94 } 93 }
@@ -142,38 +141,25 @@ static BCLine debug_frameline(lua_State *L, GCfunc *fn, cTValue *nextframe)
142 141
143/* -- Variable names ------------------------------------------------------ */ 142/* -- Variable names ------------------------------------------------------ */
144 143
145/* Read ULEB128 value. */
146static uint32_t debug_read_uleb128(const uint8_t **pp)
147{
148 const uint8_t *p = *pp;
149 uint32_t v = *p++;
150 if (LJ_UNLIKELY(v >= 0x80)) {
151 int sh = 0;
152 v &= 0x7f;
153 do { v |= ((*p & 0x7f) << (sh += 7)); } while (*p++ >= 0x80);
154 }
155 *pp = p;
156 return v;
157}
158
159/* Get name of a local variable from slot number and PC. */ 144/* Get name of a local variable from slot number and PC. */
160static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot) 145static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot)
161{ 146{
162 const uint8_t *p = proto_varinfo(pt); 147 const char *p = (const char *)proto_varinfo(pt);
163 if (p) { 148 if (p) {
164 BCPos lastpc = 0; 149 BCPos lastpc = 0;
165 for (;;) { 150 for (;;) {
166 const char *name = (const char *)p; 151 const char *name = p;
167 uint32_t vn = *p++; 152 uint32_t vn = *(const uint8_t *)p;
168 BCPos startpc, endpc; 153 BCPos startpc, endpc;
169 if (vn < VARNAME__MAX) { 154 if (vn < VARNAME__MAX) {
170 if (vn == VARNAME_END) break; /* End of varinfo. */ 155 if (vn == VARNAME_END) break; /* End of varinfo. */
171 } else { 156 } else {
172 while (*p++) ; /* Skip over variable name string. */ 157 do { p++; } while (*(const uint8_t *)p); /* Skip over variable name. */
173 } 158 }
174 lastpc = startpc = lastpc + debug_read_uleb128(&p); 159 p++;
160 lastpc = startpc = lastpc + lj_buf_ruleb128(&p);
175 if (startpc > pc) break; 161 if (startpc > pc) break;
176 endpc = startpc + debug_read_uleb128(&p); 162 endpc = startpc + lj_buf_ruleb128(&p);
177 if (pc < endpc && slot-- == 0) { 163 if (pc < endpc && slot-- == 0) {
178 if (vn < VARNAME__MAX) { 164 if (vn < VARNAME__MAX) {
179#define VARNAMESTR(name, str) str "\0" 165#define VARNAMESTR(name, str) str "\0"
@@ -198,7 +184,7 @@ static TValue *debug_localname(lua_State *L, const lua_Debug *ar,
198 TValue *nextframe = size ? frame + size : NULL; 184 TValue *nextframe = size ? frame + size : NULL;
199 GCfunc *fn = frame_func(frame); 185 GCfunc *fn = frame_func(frame);
200 BCPos pc = debug_framepc(L, fn, nextframe); 186 BCPos pc = debug_framepc(L, fn, nextframe);
201 if (!nextframe) nextframe = L->top; 187 if (!nextframe) nextframe = L->top+LJ_FR2;
202 if ((int)slot1 < 0) { /* Negative slot number is for varargs. */ 188 if ((int)slot1 < 0) { /* Negative slot number is for varargs. */
203 if (pc != NO_BCPOS) { 189 if (pc != NO_BCPOS) {
204 GCproto *pt = funcproto(fn); 190 GCproto *pt = funcproto(fn);
@@ -208,7 +194,7 @@ static TValue *debug_localname(lua_State *L, const lua_Debug *ar,
208 nextframe = frame; 194 nextframe = frame;
209 frame = frame_prevd(frame); 195 frame = frame_prevd(frame);
210 } 196 }
211 if (frame + slot1 < nextframe) { 197 if (frame + slot1+LJ_FR2 < nextframe) {
212 *name = "(*vararg)"; 198 *name = "(*vararg)";
213 return frame+slot1; 199 return frame+slot1;
214 } 200 }
@@ -219,7 +205,7 @@ static TValue *debug_localname(lua_State *L, const lua_Debug *ar,
219 if (pc != NO_BCPOS && 205 if (pc != NO_BCPOS &&
220 (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL) 206 (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL)
221 ; 207 ;
222 else if (slot1 > 0 && frame + slot1 < nextframe) 208 else if (slot1 > 0 && frame + slot1+LJ_FR2 < nextframe)
223 *name = "(*temporary)"; 209 *name = "(*temporary)";
224 return frame+slot1; 210 return frame+slot1;
225} 211}
@@ -282,7 +268,7 @@ restart:
282 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins)))); 268 *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins))));
283 if (ip > proto_bc(pt)) { 269 if (ip > proto_bc(pt)) {
284 BCIns insp = ip[-1]; 270 BCIns insp = ip[-1];
285 if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1 && 271 if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1+LJ_FR2 &&
286 bc_d(insp) == bc_b(ins)) 272 bc_d(insp) == bc_b(ins))
287 return "method"; 273 return "method";
288 } 274 }
@@ -299,12 +285,12 @@ restart:
299} 285}
300 286
301/* Deduce function name from caller of a frame. */ 287/* Deduce function name from caller of a frame. */
302const char *lj_debug_funcname(lua_State *L, TValue *frame, const char **name) 288const char *lj_debug_funcname(lua_State *L, cTValue *frame, const char **name)
303{ 289{
304 TValue *pframe; 290 cTValue *pframe;
305 GCfunc *fn; 291 GCfunc *fn;
306 BCPos pc; 292 BCPos pc;
307 if (frame <= tvref(L->stack)) 293 if (frame <= tvref(L->stack)+LJ_FR2)
308 return NULL; 294 return NULL;
309 if (frame_isvarg(frame)) 295 if (frame_isvarg(frame))
310 frame = frame_prevd(frame); 296 frame = frame_prevd(frame);
@@ -330,7 +316,7 @@ const char *lj_debug_funcname(lua_State *L, TValue *frame, const char **name)
330/* -- Source code locations ----------------------------------------------- */ 316/* -- Source code locations ----------------------------------------------- */
331 317
332/* Generate shortened source name. */ 318/* Generate shortened source name. */
333void lj_debug_shortname(char *out, GCstr *str) 319void lj_debug_shortname(char *out, GCstr *str, BCLine line)
334{ 320{
335 const char *src = strdata(str); 321 const char *src = strdata(str);
336 if (*src == '=') { 322 if (*src == '=') {
@@ -344,11 +330,11 @@ void lj_debug_shortname(char *out, GCstr *str)
344 *out++ = '.'; *out++ = '.'; *out++ = '.'; 330 *out++ = '.'; *out++ = '.'; *out++ = '.';
345 } 331 }
346 strcpy(out, src); 332 strcpy(out, src);
347 } else { /* Output [string "string"]. */ 333 } else { /* Output [string "string"] or [builtin:name]. */
348 size_t len; /* Length, up to first control char. */ 334 size_t len; /* Length, up to first control char. */
349 for (len = 0; len < LUA_IDSIZE-12; len++) 335 for (len = 0; len < LUA_IDSIZE-12; len++)
350 if (((const unsigned char *)src)[len] < ' ') break; 336 if (((const unsigned char *)src)[len] < ' ') break;
351 strcpy(out, "[string \""); out += 9; 337 strcpy(out, line == ~(BCLine)0 ? "[builtin:" : "[string \""); out += 9;
352 if (src[len] != '\0') { /* Must truncate? */ 338 if (src[len] != '\0') { /* Must truncate? */
353 if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15; 339 if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15;
354 strncpy(out, src, len); out += len; 340 strncpy(out, src, len); out += len;
@@ -356,7 +342,7 @@ void lj_debug_shortname(char *out, GCstr *str)
356 } else { 342 } else {
357 strcpy(out, src); out += len; 343 strcpy(out, src); out += len;
358 } 344 }
359 strcpy(out, "\"]"); 345 strcpy(out, line == ~(BCLine)0 ? "]" : "\"]");
360 } 346 }
361} 347}
362 348
@@ -369,14 +355,15 @@ void lj_debug_addloc(lua_State *L, const char *msg,
369 if (isluafunc(fn)) { 355 if (isluafunc(fn)) {
370 BCLine line = debug_frameline(L, fn, nextframe); 356 BCLine line = debug_frameline(L, fn, nextframe);
371 if (line >= 0) { 357 if (line >= 0) {
358 GCproto *pt = funcproto(fn);
372 char buf[LUA_IDSIZE]; 359 char buf[LUA_IDSIZE];
373 lj_debug_shortname(buf, proto_chunkname(funcproto(fn))); 360 lj_debug_shortname(buf, proto_chunkname(pt), pt->firstline);
374 lj_str_pushf(L, "%s:%d: %s", buf, line, msg); 361 lj_strfmt_pushf(L, "%s:%d: %s", buf, line, msg);
375 return; 362 return;
376 } 363 }
377 } 364 }
378 } 365 }
379 lj_str_pushf(L, "%s", msg); 366 lj_strfmt_pushf(L, "%s", msg);
380} 367}
381 368
382/* Push location string for a bytecode position to Lua stack. */ 369/* Push location string for a bytecode position to Lua stack. */
@@ -386,20 +373,22 @@ void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc)
386 const char *s = strdata(name); 373 const char *s = strdata(name);
387 MSize i, len = name->len; 374 MSize i, len = name->len;
388 BCLine line = lj_debug_line(pt, pc); 375 BCLine line = lj_debug_line(pt, pc);
389 if (*s == '@') { 376 if (pt->firstline == ~(BCLine)0) {
377 lj_strfmt_pushf(L, "builtin:%s", s);
378 } else if (*s == '@') {
390 s++; len--; 379 s++; len--;
391 for (i = len; i > 0; i--) 380 for (i = len; i > 0; i--)
392 if (s[i] == '/' || s[i] == '\\') { 381 if (s[i] == '/' || s[i] == '\\') {
393 s += i+1; 382 s += i+1;
394 break; 383 break;
395 } 384 }
396 lj_str_pushf(L, "%s:%d", s, line); 385 lj_strfmt_pushf(L, "%s:%d", s, line);
397 } else if (len > 40) { 386 } else if (len > 40) {
398 lj_str_pushf(L, "%p:%d", pt, line); 387 lj_strfmt_pushf(L, "%p:%d", pt, line);
399 } else if (*s == '=') { 388 } else if (*s == '=') {
400 lj_str_pushf(L, "%s:%d", s+1, line); 389 lj_strfmt_pushf(L, "%s:%d", s+1, line);
401 } else { 390 } else {
402 lj_str_pushf(L, "\"%s\":%d", s, line); 391 lj_strfmt_pushf(L, "\"%s\":%d", s, line);
403 } 392 }
404} 393}
405 394
@@ -462,7 +451,7 @@ int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, int ext)
462 BCLine firstline = pt->firstline; 451 BCLine firstline = pt->firstline;
463 GCstr *name = proto_chunkname(pt); 452 GCstr *name = proto_chunkname(pt);
464 ar->source = strdata(name); 453 ar->source = strdata(name);
465 lj_debug_shortname(ar->short_src, name); 454 lj_debug_shortname(ar->short_src, name, pt->firstline);
466 ar->linedefined = (int)firstline; 455 ar->linedefined = (int)firstline;
467 ar->lastlinedefined = (int)(firstline + pt->numline); 456 ar->lastlinedefined = (int)(firstline + pt->numline);
468 ar->what = (firstline || !pt->numline) ? "Lua" : "main"; 457 ar->what = (firstline || !pt->numline) ? "Lua" : "main";
@@ -552,6 +541,111 @@ LUA_API int lua_getstack(lua_State *L, int level, lua_Debug *ar)
552 } 541 }
553} 542}
554 543
544#if LJ_HASPROFILE
545/* Put the chunkname into a buffer. */
546static int debug_putchunkname(SBuf *sb, GCproto *pt, int pathstrip)
547{
548 GCstr *name = proto_chunkname(pt);
549 const char *p = strdata(name);
550 if (pt->firstline == ~(BCLine)0) {
551 lj_buf_putmem(sb, "[builtin:", 9);
552 lj_buf_putstr(sb, name);
553 lj_buf_putb(sb, ']');
554 return 0;
555 }
556 if (*p == '=' || *p == '@') {
557 MSize len = name->len-1;
558 p++;
559 if (pathstrip) {
560 int i;
561 for (i = len-1; i >= 0; i--)
562 if (p[i] == '/' || p[i] == '\\') {
563 len -= i+1;
564 p = p+i+1;
565 break;
566 }
567 }
568 lj_buf_putmem(sb, p, len);
569 } else {
570 lj_buf_putmem(sb, "[string]", 8);
571 }
572 return 1;
573}
574
575/* Put a compact stack dump into a buffer. */
576void lj_debug_dumpstack(lua_State *L, SBuf *sb, const char *fmt, int depth)
577{
578 int level = 0, dir = 1, pathstrip = 1;
579 MSize lastlen = 0;
580 if (depth < 0) { level = ~depth; depth = dir = -1; } /* Reverse frames. */
581 while (level != depth) { /* Loop through all frame. */
582 int size;
583 cTValue *frame = lj_debug_frame(L, level, &size);
584 if (frame) {
585 cTValue *nextframe = size ? frame+size : NULL;
586 GCfunc *fn = frame_func(frame);
587 const uint8_t *p = (const uint8_t *)fmt;
588 int c;
589 while ((c = *p++)) {
590 switch (c) {
591 case 'p': /* Preserve full path. */
592 pathstrip = 0;
593 break;
594 case 'F': case 'f': { /* Dump function name. */
595 const char *name;
596 const char *what = lj_debug_funcname(L, frame, &name);
597 if (what) {
598 if (c == 'F' && isluafunc(fn)) { /* Dump module:name for 'F'. */
599 GCproto *pt = funcproto(fn);
600 if (pt->firstline != ~(BCLine)0) { /* Not a bytecode builtin. */
601 debug_putchunkname(sb, pt, pathstrip);
602 lj_buf_putb(sb, ':');
603 }
604 }
605 lj_buf_putmem(sb, name, (MSize)strlen(name));
606 break;
607 } /* else: can't derive a name, dump module:line. */
608 }
609 /* fallthrough */
610 case 'l': /* Dump module:line. */
611 if (isluafunc(fn)) {
612 GCproto *pt = funcproto(fn);
613 if (debug_putchunkname(sb, pt, pathstrip)) {
614 /* Regular Lua function. */
615 BCLine line = c == 'l' ? debug_frameline(L, fn, nextframe) :
616 pt->firstline;
617 lj_buf_putb(sb, ':');
618 lj_strfmt_putint(sb, line >= 0 ? line : pt->firstline);
619 }
620 } else if (isffunc(fn)) { /* Dump numbered builtins. */
621 lj_buf_putmem(sb, "[builtin#", 9);
622 lj_strfmt_putint(sb, fn->c.ffid);
623 lj_buf_putb(sb, ']');
624 } else { /* Dump C function address. */
625 lj_buf_putb(sb, '@');
626 lj_strfmt_putptr(sb, fn->c.f);
627 }
628 break;
629 case 'Z': /* Zap trailing separator. */
630 lastlen = sbuflen(sb);
631 break;
632 default:
633 lj_buf_putb(sb, c);
634 break;
635 }
636 }
637 } else if (dir == 1) {
638 break;
639 } else {
640 level -= size; /* Reverse frame order: quickly skip missing level. */
641 }
642 level += dir;
643 }
644 if (lastlen)
645 setsbufP(sb, sbufB(sb) + lastlen); /* Zap trailing separator. */
646}
647#endif
648
555/* Number of frames for the leading and trailing part of a traceback. */ 649/* Number of frames for the leading and trailing part of a traceback. */
556#define TRACEBACK_LEVELS1 12 650#define TRACEBACK_LEVELS1 12
557#define TRACEBACK_LEVELS2 10 651#define TRACEBACK_LEVELS2 10
diff --git a/src/lj_debug.h b/src/lj_debug.h
index d10d0da2..5917c00b 100644
--- a/src/lj_debug.h
+++ b/src/lj_debug.h
@@ -32,14 +32,18 @@ LJ_FUNC const char *lj_debug_uvname(GCproto *pt, uint32_t idx);
32LJ_FUNC const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp); 32LJ_FUNC const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp);
33LJ_FUNC const char *lj_debug_slotname(GCproto *pt, const BCIns *pc, 33LJ_FUNC const char *lj_debug_slotname(GCproto *pt, const BCIns *pc,
34 BCReg slot, const char **name); 34 BCReg slot, const char **name);
35LJ_FUNC const char *lj_debug_funcname(lua_State *L, TValue *frame, 35LJ_FUNC const char *lj_debug_funcname(lua_State *L, cTValue *frame,
36 const char **name); 36 const char **name);
37LJ_FUNC void lj_debug_shortname(char *out, GCstr *str); 37LJ_FUNC void lj_debug_shortname(char *out, GCstr *str, BCLine line);
38LJ_FUNC void lj_debug_addloc(lua_State *L, const char *msg, 38LJ_FUNC void lj_debug_addloc(lua_State *L, const char *msg,
39 cTValue *frame, cTValue *nextframe); 39 cTValue *frame, cTValue *nextframe);
40LJ_FUNC void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc); 40LJ_FUNC void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc);
41LJ_FUNC int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, 41LJ_FUNC int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar,
42 int ext); 42 int ext);
43#if LJ_HASPROFILE
44LJ_FUNC void lj_debug_dumpstack(lua_State *L, SBuf *sb, const char *fmt,
45 int depth);
46#endif
43 47
44/* Fixed internal variable names. */ 48/* Fixed internal variable names. */
45#define VARNAMEDEF(_) \ 49#define VARNAMEDEF(_) \
diff --git a/src/lj_def.h b/src/lj_def.h
index 21cc59a4..2d8fff66 100644
--- a/src/lj_def.h
+++ b/src/lj_def.h
@@ -46,10 +46,14 @@ typedef unsigned int uintptr_t;
46#include <stdlib.h> 46#include <stdlib.h>
47 47
48/* Various VM limits. */ 48/* Various VM limits. */
49#define LJ_MAX_MEM 0x7fffff00 /* Max. total memory allocation. */ 49#define LJ_MAX_MEM32 0x7fffff00 /* Max. 32 bit memory allocation. */
50#define LJ_MAX_MEM64 ((uint64_t)1<<47) /* Max. 64 bit memory allocation. */
51/* Max. total memory allocation. */
52#define LJ_MAX_MEM (LJ_GC64 ? LJ_MAX_MEM64 : LJ_MAX_MEM32)
50#define LJ_MAX_ALLOC LJ_MAX_MEM /* Max. individual allocation length. */ 53#define LJ_MAX_ALLOC LJ_MAX_MEM /* Max. individual allocation length. */
51#define LJ_MAX_STR LJ_MAX_MEM /* Max. string length. */ 54#define LJ_MAX_STR LJ_MAX_MEM32 /* Max. string length. */
52#define LJ_MAX_UDATA LJ_MAX_MEM /* Max. userdata length. */ 55#define LJ_MAX_BUF LJ_MAX_MEM32 /* Max. buffer length. */
56#define LJ_MAX_UDATA LJ_MAX_MEM32 /* Max. userdata length. */
53 57
54#define LJ_MAX_STRTAB (1<<26) /* Max. string table size. */ 58#define LJ_MAX_STRTAB (1<<26) /* Max. string table size. */
55#define LJ_MAX_HBITS 26 /* Max. hash bits. */ 59#define LJ_MAX_HBITS 26 /* Max. hash bits. */
@@ -57,7 +61,7 @@ typedef unsigned int uintptr_t;
57#define LJ_MAX_ASIZE ((1<<(LJ_MAX_ABITS-1))+1) /* Max. array part size. */ 61#define LJ_MAX_ASIZE ((1<<(LJ_MAX_ABITS-1))+1) /* Max. array part size. */
58#define LJ_MAX_COLOSIZE 16 /* Max. elems for colocated array. */ 62#define LJ_MAX_COLOSIZE 16 /* Max. elems for colocated array. */
59 63
60#define LJ_MAX_LINE LJ_MAX_MEM /* Max. source code line number. */ 64#define LJ_MAX_LINE LJ_MAX_MEM32 /* Max. source code line number. */
61#define LJ_MAX_XLEVEL 200 /* Max. syntactic nesting level. */ 65#define LJ_MAX_XLEVEL 200 /* Max. syntactic nesting level. */
62#define LJ_MAX_BCINS (1<<26) /* Max. # of bytecode instructions. */ 66#define LJ_MAX_BCINS (1<<26) /* Max. # of bytecode instructions. */
63#define LJ_MAX_SLOTS 250 /* Max. # of slots in a Lua func. */ 67#define LJ_MAX_SLOTS 250 /* Max. # of slots in a Lua func. */
@@ -65,7 +69,7 @@ typedef unsigned int uintptr_t;
65#define LJ_MAX_UPVAL 60 /* Max. # of upvalues. */ 69#define LJ_MAX_UPVAL 60 /* Max. # of upvalues. */
66 70
67#define LJ_MAX_IDXCHAIN 100 /* __index/__newindex chain limit. */ 71#define LJ_MAX_IDXCHAIN 100 /* __index/__newindex chain limit. */
68#define LJ_STACK_EXTRA 5 /* Extra stack space (metamethods). */ 72#define LJ_STACK_EXTRA (5+2*LJ_FR2) /* Extra stack space (metamethods). */
69 73
70#define LJ_NUM_CBPAGE 1 /* Number of FFI callback pages. */ 74#define LJ_NUM_CBPAGE 1 /* Number of FFI callback pages. */
71 75
@@ -91,6 +95,9 @@ typedef unsigned int uintptr_t;
91#define U64x(hi, lo) (((uint64_t)0x##hi << 32) + (uint64_t)0x##lo) 95#define U64x(hi, lo) (((uint64_t)0x##hi << 32) + (uint64_t)0x##lo)
92#define i32ptr(p) ((int32_t)(intptr_t)(void *)(p)) 96#define i32ptr(p) ((int32_t)(intptr_t)(void *)(p))
93#define u32ptr(p) ((uint32_t)(intptr_t)(void *)(p)) 97#define u32ptr(p) ((uint32_t)(intptr_t)(void *)(p))
98#define i64ptr(p) ((int64_t)(intptr_t)(void *)(p))
99#define u64ptr(p) ((uint64_t)(intptr_t)(void *)(p))
100#define igcptr(p) (LJ_GC64 ? i64ptr(p) : i32ptr(p))
94 101
95#define checki8(x) ((x) == (int32_t)(int8_t)(x)) 102#define checki8(x) ((x) == (int32_t)(int8_t)(x))
96#define checku8(x) ((x) == (int32_t)(uint8_t)(x)) 103#define checku8(x) ((x) == (int32_t)(uint8_t)(x))
@@ -99,6 +106,8 @@ typedef unsigned int uintptr_t;
99#define checki32(x) ((x) == (int32_t)(x)) 106#define checki32(x) ((x) == (int32_t)(x))
100#define checku32(x) ((x) == (uint32_t)(x)) 107#define checku32(x) ((x) == (uint32_t)(x))
101#define checkptr32(x) ((uintptr_t)(x) == (uint32_t)(uintptr_t)(x)) 108#define checkptr32(x) ((uintptr_t)(x) == (uint32_t)(uintptr_t)(x))
109#define checkptr47(x) (((uint64_t)(uintptr_t)(x) >> 47) == 0)
110#define checkptrGC(x) (LJ_GC64 ? checkptr47((x)) : LJ_64 ? checkptr32((x)) :1)
102 111
103/* Every half-decent C compiler transforms this into a rotate instruction. */ 112/* Every half-decent C compiler transforms this into a rotate instruction. */
104#define lj_rol(x, n) (((x)<<(n)) | ((x)>>(-(int)(n)&(8*sizeof(x)-1)))) 113#define lj_rol(x, n) (((x)<<(n)) | ((x)>>(-(int)(n)&(8*sizeof(x)-1))))
diff --git a/src/lj_dispatch.c b/src/lj_dispatch.c
index 627379a2..5d6795f8 100644
--- a/src/lj_dispatch.c
+++ b/src/lj_dispatch.c
@@ -8,6 +8,7 @@
8 8
9#include "lj_obj.h" 9#include "lj_obj.h"
10#include "lj_err.h" 10#include "lj_err.h"
11#include "lj_buf.h"
11#include "lj_func.h" 12#include "lj_func.h"
12#include "lj_str.h" 13#include "lj_str.h"
13#include "lj_tab.h" 14#include "lj_tab.h"
@@ -17,6 +18,7 @@
17#include "lj_frame.h" 18#include "lj_frame.h"
18#include "lj_bc.h" 19#include "lj_bc.h"
19#include "lj_ff.h" 20#include "lj_ff.h"
21#include "lj_strfmt.h"
20#if LJ_HASJIT 22#if LJ_HASJIT
21#include "lj_jit.h" 23#include "lj_jit.h"
22#endif 24#endif
@@ -25,6 +27,9 @@
25#endif 27#endif
26#include "lj_trace.h" 28#include "lj_trace.h"
27#include "lj_dispatch.h" 29#include "lj_dispatch.h"
30#if LJ_HASPROFILE
31#include "lj_profile.h"
32#endif
28#include "lj_vm.h" 33#include "lj_vm.h"
29#include "luajit.h" 34#include "luajit.h"
30 35
@@ -37,6 +42,12 @@ LJ_STATIC_ASSERT(GG_NUM_ASMFF == FF_NUM_ASMFUNC);
37#include <math.h> 42#include <math.h>
38LJ_FUNCA_NORET void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L, 43LJ_FUNCA_NORET void LJ_FASTCALL lj_ffh_coroutine_wrap_err(lua_State *L,
39 lua_State *co); 44 lua_State *co);
45#if !LJ_HASJIT
46#define lj_dispatch_stitch lj_dispatch_ins
47#endif
48#if !LJ_HASPROFILE
49#define lj_dispatch_profile lj_dispatch_ins
50#endif
40 51
41#define GOTFUNC(name) (ASMFunction)name, 52#define GOTFUNC(name) (ASMFunction)name,
42static const ASMFunction dispatch_got[] = { 53static const ASMFunction dispatch_got[] = {
@@ -64,7 +75,7 @@ void lj_dispatch_init(GG_State *GG)
64 for (i = 0; i < GG_NUM_ASMFF; i++) 75 for (i = 0; i < GG_NUM_ASMFF; i++)
65 GG->bcff[i] = BCINS_AD(BC__MAX+i, 0, 0); 76 GG->bcff[i] = BCINS_AD(BC__MAX+i, 0, 0);
66#if LJ_TARGET_MIPS 77#if LJ_TARGET_MIPS
67 memcpy(GG->got, dispatch_got, LJ_GOT__MAX*4); 78 memcpy(GG->got, dispatch_got, LJ_GOT__MAX*sizeof(ASMFunction *));
68#endif 79#endif
69} 80}
70 81
@@ -82,11 +93,12 @@ void lj_dispatch_init_hotcount(global_State *g)
82#endif 93#endif
83 94
84/* Internal dispatch mode bits. */ 95/* Internal dispatch mode bits. */
85#define DISPMODE_JIT 0x01 /* JIT compiler on. */ 96#define DISPMODE_CALL 0x01 /* Override call dispatch. */
86#define DISPMODE_REC 0x02 /* Recording active. */ 97#define DISPMODE_RET 0x02 /* Override return dispatch. */
87#define DISPMODE_INS 0x04 /* Override instruction dispatch. */ 98#define DISPMODE_INS 0x04 /* Override instruction dispatch. */
88#define DISPMODE_CALL 0x08 /* Override call dispatch. */ 99#define DISPMODE_JIT 0x10 /* JIT compiler on. */
89#define DISPMODE_RET 0x10 /* Override return dispatch. */ 100#define DISPMODE_REC 0x20 /* Recording active. */
101#define DISPMODE_PROF 0x40 /* Profiling active. */
90 102
91/* Update dispatch table depending on various flags. */ 103/* Update dispatch table depending on various flags. */
92void lj_dispatch_update(global_State *g) 104void lj_dispatch_update(global_State *g)
@@ -98,6 +110,9 @@ void lj_dispatch_update(global_State *g)
98 mode |= G2J(g)->state != LJ_TRACE_IDLE ? 110 mode |= G2J(g)->state != LJ_TRACE_IDLE ?
99 (DISPMODE_REC|DISPMODE_INS|DISPMODE_CALL) : 0; 111 (DISPMODE_REC|DISPMODE_INS|DISPMODE_CALL) : 0;
100#endif 112#endif
113#if LJ_HASPROFILE
114 mode |= (g->hookmask & HOOK_PROFILE) ? (DISPMODE_PROF|DISPMODE_INS) : 0;
115#endif
101 mode |= (g->hookmask & (LUA_MASKLINE|LUA_MASKCOUNT)) ? DISPMODE_INS : 0; 116 mode |= (g->hookmask & (LUA_MASKLINE|LUA_MASKCOUNT)) ? DISPMODE_INS : 0;
102 mode |= (g->hookmask & LUA_MASKCALL) ? DISPMODE_CALL : 0; 117 mode |= (g->hookmask & LUA_MASKCALL) ? DISPMODE_CALL : 0;
103 mode |= (g->hookmask & LUA_MASKRET) ? DISPMODE_RET : 0; 118 mode |= (g->hookmask & LUA_MASKRET) ? DISPMODE_RET : 0;
@@ -126,9 +141,9 @@ void lj_dispatch_update(global_State *g)
126 disp[GG_LEN_DDISP+BC_LOOP] = f_loop; 141 disp[GG_LEN_DDISP+BC_LOOP] = f_loop;
127 142
128 /* Set dynamic instruction dispatch. */ 143 /* Set dynamic instruction dispatch. */
129 if ((oldmode ^ mode) & (DISPMODE_REC|DISPMODE_INS)) { 144 if ((oldmode ^ mode) & (DISPMODE_PROF|DISPMODE_REC|DISPMODE_INS)) {
130 /* Need to update the whole table. */ 145 /* Need to update the whole table. */
131 if (!(mode & (DISPMODE_REC|DISPMODE_INS))) { /* No ins dispatch? */ 146 if (!(mode & DISPMODE_INS)) { /* No ins dispatch? */
132 /* Copy static dispatch table to dynamic dispatch table. */ 147 /* Copy static dispatch table to dynamic dispatch table. */
133 memcpy(&disp[0], &disp[GG_LEN_DDISP], GG_LEN_SDISP*sizeof(ASMFunction)); 148 memcpy(&disp[0], &disp[GG_LEN_DDISP], GG_LEN_SDISP*sizeof(ASMFunction));
134 /* Overwrite with dynamic return dispatch. */ 149 /* Overwrite with dynamic return dispatch. */
@@ -140,12 +155,13 @@ void lj_dispatch_update(global_State *g)
140 } 155 }
141 } else { 156 } else {
142 /* The recording dispatch also checks for hooks. */ 157 /* The recording dispatch also checks for hooks. */
143 ASMFunction f = (mode & DISPMODE_REC) ? lj_vm_record : lj_vm_inshook; 158 ASMFunction f = (mode & DISPMODE_PROF) ? lj_vm_profhook :
159 (mode & DISPMODE_REC) ? lj_vm_record : lj_vm_inshook;
144 uint32_t i; 160 uint32_t i;
145 for (i = 0; i < GG_LEN_SDISP; i++) 161 for (i = 0; i < GG_LEN_SDISP; i++)
146 disp[i] = f; 162 disp[i] = f;
147 } 163 }
148 } else if (!(mode & (DISPMODE_REC|DISPMODE_INS))) { 164 } else if (!(mode & DISPMODE_INS)) {
149 /* Otherwise set dynamic counting ins. */ 165 /* Otherwise set dynamic counting ins. */
150 disp[BC_FORL] = f_forl; 166 disp[BC_FORL] = f_forl;
151 disp[BC_ITERL] = f_iterl; 167 disp[BC_ITERL] = f_iterl;
@@ -251,7 +267,7 @@ int luaJIT_setmode(lua_State *L, int idx, int mode)
251 case LUAJIT_MODE_FUNC: 267 case LUAJIT_MODE_FUNC:
252 case LUAJIT_MODE_ALLFUNC: 268 case LUAJIT_MODE_ALLFUNC:
253 case LUAJIT_MODE_ALLSUBFUNC: { 269 case LUAJIT_MODE_ALLSUBFUNC: {
254 cTValue *tv = idx == 0 ? frame_prev(L->base-1) : 270 cTValue *tv = idx == 0 ? frame_prev(L->base-1)-LJ_FR2 :
255 idx > 0 ? L->base + (idx-1) : L->top + idx; 271 idx > 0 ? L->base + (idx-1) : L->top + idx;
256 GCproto *pt; 272 GCproto *pt;
257 if ((idx == 0 || tvisfunc(tv)) && isluafunc(&gcval(tv)->fn)) 273 if ((idx == 0 || tvisfunc(tv)) && isluafunc(&gcval(tv)->fn))
@@ -352,10 +368,19 @@ static void callhook(lua_State *L, int event, BCLine line)
352 /* Top frame, nextframe = NULL. */ 368 /* Top frame, nextframe = NULL. */
353 ar.i_ci = (int)((L->base-1) - tvref(L->stack)); 369 ar.i_ci = (int)((L->base-1) - tvref(L->stack));
354 lj_state_checkstack(L, 1+LUA_MINSTACK); 370 lj_state_checkstack(L, 1+LUA_MINSTACK);
371#if LJ_HASPROFILE && !LJ_PROFILE_SIGPROF
372 lj_profile_hook_enter(g);
373#else
355 hook_enter(g); 374 hook_enter(g);
375#endif
356 hookf(L, &ar); 376 hookf(L, &ar);
357 lua_assert(hook_active(g)); 377 lua_assert(hook_active(g));
378 setgcref(g->cur_L, obj2gco(L));
379#if LJ_HASPROFILE && !LJ_PROFILE_SIGPROF
380 lj_profile_hook_leave(g);
381#else
358 hook_leave(g); 382 hook_leave(g);
383#endif
359 } 384 }
360} 385}
361 386
@@ -368,7 +393,7 @@ static BCReg cur_topslot(GCproto *pt, const BCIns *pc, uint32_t nres)
368 if (bc_op(ins) == BC_UCLO) 393 if (bc_op(ins) == BC_UCLO)
369 ins = pc[bc_j(ins)]; 394 ins = pc[bc_j(ins)];
370 switch (bc_op(ins)) { 395 switch (bc_op(ins)) {
371 case BC_CALLM: case BC_CALLMT: return bc_a(ins) + bc_c(ins) + nres-1+1; 396 case BC_CALLM: case BC_CALLMT: return bc_a(ins) + bc_c(ins) + nres-1+1+LJ_FR2;
372 case BC_RETM: return bc_a(ins) + bc_d(ins) + nres-1; 397 case BC_RETM: return bc_a(ins) + bc_d(ins) + nres-1;
373 case BC_TSETM: return bc_a(ins) + nres-1; 398 case BC_TSETM: return bc_a(ins) + nres-1;
374 default: return pt->framesize; 399 default: return pt->framesize;
@@ -492,3 +517,41 @@ out:
492 return makeasmfunc(lj_bc_ofs[op]); /* Return static dispatch target. */ 517 return makeasmfunc(lj_bc_ofs[op]); /* Return static dispatch target. */
493} 518}
494 519
520#if LJ_HASJIT
521/* Stitch a new trace. */
522void LJ_FASTCALL lj_dispatch_stitch(jit_State *J, const BCIns *pc)
523{
524 ERRNO_SAVE
525 lua_State *L = J->L;
526 void *cf = cframe_raw(L->cframe);
527 const BCIns *oldpc = cframe_pc(cf);
528 setcframe_pc(cf, pc);
529 /* Before dispatch, have to bias PC by 1. */
530 L->top = L->base + cur_topslot(curr_proto(L), pc+1, cframe_multres_n(cf));
531 lj_trace_stitch(J, pc-1); /* Point to the CALL instruction. */
532 setcframe_pc(cf, oldpc);
533 ERRNO_RESTORE
534}
535#endif
536
537#if LJ_HASPROFILE
538/* Profile dispatch. */
539void LJ_FASTCALL lj_dispatch_profile(lua_State *L, const BCIns *pc)
540{
541 ERRNO_SAVE
542 GCfunc *fn = curr_func(L);
543 GCproto *pt = funcproto(fn);
544 void *cf = cframe_raw(L->cframe);
545 const BCIns *oldpc = cframe_pc(cf);
546 global_State *g;
547 setcframe_pc(cf, pc);
548 L->top = L->base + cur_topslot(pt, pc, cframe_multres_n(cf));
549 lj_profile_interpreter(L);
550 setcframe_pc(cf, oldpc);
551 g = G(L);
552 setgcref(g->cur_L, obj2gco(L));
553 setvmstate(g, INTERP);
554 ERRNO_RESTORE
555}
556#endif
557
diff --git a/src/lj_dispatch.h b/src/lj_dispatch.h
index e46a0eee..5bda51a2 100644
--- a/src/lj_dispatch.h
+++ b/src/lj_dispatch.h
@@ -14,6 +14,22 @@
14 14
15#if LJ_TARGET_MIPS 15#if LJ_TARGET_MIPS
16/* Need our own global offset table for the dreaded MIPS calling conventions. */ 16/* Need our own global offset table for the dreaded MIPS calling conventions. */
17
18#ifndef _LJ_VM_H
19LJ_ASMF int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b);
20#endif
21
22#if LJ_SOFTFP
23#ifndef _LJ_IRCALL_H
24extern double __adddf3(double a, double b);
25extern double __subdf3(double a, double b);
26extern double __muldf3(double a, double b);
27extern double __divdf3(double a, double b);
28#endif
29#define SFGOTDEF(_) _(sqrt) _(__adddf3) _(__subdf3) _(__muldf3) _(__divdf3)
30#else
31#define SFGOTDEF(_)
32#endif
17#if LJ_HASJIT 33#if LJ_HASJIT
18#define JITGOTDEF(_) _(lj_trace_exit) _(lj_trace_hot) 34#define JITGOTDEF(_) _(lj_trace_exit) _(lj_trace_hot)
19#else 35#else
@@ -28,16 +44,19 @@
28#define GOTDEF(_) \ 44#define GOTDEF(_) \
29 _(floor) _(ceil) _(trunc) _(log) _(log10) _(exp) _(sin) _(cos) _(tan) \ 45 _(floor) _(ceil) _(trunc) _(log) _(log10) _(exp) _(sin) _(cos) _(tan) \
30 _(asin) _(acos) _(atan) _(sinh) _(cosh) _(tanh) _(frexp) _(modf) _(atan2) \ 46 _(asin) _(acos) _(atan) _(sinh) _(cosh) _(tanh) _(frexp) _(modf) _(atan2) \
31 _(pow) _(fmod) _(ldexp) \ 47 _(pow) _(fmod) _(ldexp) _(lj_vm_modi) \
32 _(lj_dispatch_call) _(lj_dispatch_ins) _(lj_err_throw) \ 48 _(lj_dispatch_call) _(lj_dispatch_ins) _(lj_dispatch_stitch) \
49 _(lj_dispatch_profile) _(lj_err_throw) \
33 _(lj_ffh_coroutine_wrap_err) _(lj_func_closeuv) _(lj_func_newL_gc) \ 50 _(lj_ffh_coroutine_wrap_err) _(lj_func_closeuv) _(lj_func_newL_gc) \
34 _(lj_gc_barrieruv) _(lj_gc_step) _(lj_gc_step_fixtop) _(lj_meta_arith) \ 51 _(lj_gc_barrieruv) _(lj_gc_step) _(lj_gc_step_fixtop) _(lj_meta_arith) \
35 _(lj_meta_call) _(lj_meta_cat) _(lj_meta_comp) _(lj_meta_equal) \ 52 _(lj_meta_call) _(lj_meta_cat) _(lj_meta_comp) _(lj_meta_equal) \
36 _(lj_meta_for) _(lj_meta_len) _(lj_meta_tget) _(lj_meta_tset) \ 53 _(lj_meta_for) _(lj_meta_istype) _(lj_meta_len) _(lj_meta_tget) \
37 _(lj_state_growstack) _(lj_str_fromnum) _(lj_str_fromnumber) _(lj_str_new) \ 54 _(lj_meta_tset) _(lj_state_growstack) _(lj_strfmt_number) \
38 _(lj_tab_dup) _(lj_tab_get) _(lj_tab_getinth) _(lj_tab_len) _(lj_tab_new) \ 55 _(lj_str_new) _(lj_tab_dup) _(lj_tab_get) _(lj_tab_getinth) _(lj_tab_len) \
39 _(lj_tab_newkey) _(lj_tab_next) _(lj_tab_reasize) \ 56 _(lj_tab_new) _(lj_tab_newkey) _(lj_tab_next) _(lj_tab_reasize) \
40 JITGOTDEF(_) FFIGOTDEF(_) 57 _(lj_tab_setinth) _(lj_buf_putstr_reverse) _(lj_buf_putstr_lower) \
58 _(lj_buf_putstr_upper) _(lj_buf_tostr) \
59 JITGOTDEF(_) FFIGOTDEF(_) SFGOTDEF(_)
41 60
42enum { 61enum {
43#define GOTENUM(name) LJ_GOT_##name, 62#define GOTENUM(name) LJ_GOT_##name,
@@ -60,7 +79,7 @@ typedef uint16_t HotCount;
60#define HOTCOUNT_CALL 1 79#define HOTCOUNT_CALL 1
61 80
62/* This solves a circular dependency problem -- bump as needed. Sigh. */ 81/* This solves a circular dependency problem -- bump as needed. Sigh. */
63#define GG_NUM_ASMFF 62 82#define GG_NUM_ASMFF 57
64 83
65#define GG_LEN_DDISP (BC__MAX + GG_NUM_ASMFF) 84#define GG_LEN_DDISP (BC__MAX + GG_NUM_ASMFF)
66#define GG_LEN_SDISP BC_FUNCF 85#define GG_LEN_SDISP BC_FUNCF
@@ -88,6 +107,7 @@ typedef struct GG_State {
88#define J2G(J) (&J2GG(J)->g) 107#define J2G(J) (&J2GG(J)->g)
89#define G2J(gl) (&G2GG(gl)->J) 108#define G2J(gl) (&G2GG(gl)->J)
90#define L2J(L) (&L2GG(L)->J) 109#define L2J(L) (&L2GG(L)->J)
110#define GG_G2J (GG_OFS(J) - GG_OFS(g))
91#define GG_G2DISP (GG_OFS(dispatch) - GG_OFS(g)) 111#define GG_G2DISP (GG_OFS(dispatch) - GG_OFS(g))
92#define GG_DISP2G (GG_OFS(g) - GG_OFS(dispatch)) 112#define GG_DISP2G (GG_OFS(g) - GG_OFS(dispatch))
93#define GG_DISP2J (GG_OFS(J) - GG_OFS(dispatch)) 113#define GG_DISP2J (GG_OFS(J) - GG_OFS(dispatch))
@@ -109,7 +129,12 @@ LJ_FUNC void lj_dispatch_update(global_State *g);
109/* Instruction dispatch callback for hooks or when recording. */ 129/* Instruction dispatch callback for hooks or when recording. */
110LJ_FUNCA void LJ_FASTCALL lj_dispatch_ins(lua_State *L, const BCIns *pc); 130LJ_FUNCA void LJ_FASTCALL lj_dispatch_ins(lua_State *L, const BCIns *pc);
111LJ_FUNCA ASMFunction LJ_FASTCALL lj_dispatch_call(lua_State *L, const BCIns*pc); 131LJ_FUNCA ASMFunction LJ_FASTCALL lj_dispatch_call(lua_State *L, const BCIns*pc);
112LJ_FUNCA void LJ_FASTCALL lj_dispatch_return(lua_State *L, const BCIns *pc); 132#if LJ_HASJIT
133LJ_FUNCA void LJ_FASTCALL lj_dispatch_stitch(jit_State *J, const BCIns *pc);
134#endif
135#if LJ_HASPROFILE
136LJ_FUNCA void LJ_FASTCALL lj_dispatch_profile(lua_State *L, const BCIns *pc);
137#endif
113 138
114#if LJ_HASFFI && !defined(_BUILDVM_H) 139#if LJ_HASFFI && !defined(_BUILDVM_H)
115/* Save/restore errno and GetLastError() around hooks, exits and recording. */ 140/* Save/restore errno and GetLastError() around hooks, exits and recording. */
diff --git a/src/lj_emit_arm.h b/src/lj_emit_arm.h
index 285c98de..dee8bdcc 100644
--- a/src/lj_emit_arm.h
+++ b/src/lj_emit_arm.h
@@ -207,7 +207,7 @@ static void emit_loadi(ASMState *as, Reg r, int32_t i)
207 207
208#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) 208#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr)))
209 209
210static Reg ra_allock(ASMState *as, int32_t k, RegSet allow); 210static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
211 211
212/* Get/set from constant pointer. */ 212/* Get/set from constant pointer. */
213static void emit_lsptr(ASMState *as, ARMIns ai, Reg r, void *p) 213static void emit_lsptr(ASMState *as, ARMIns ai, Reg r, void *p)
@@ -219,8 +219,9 @@ static void emit_lsptr(ASMState *as, ARMIns ai, Reg r, void *p)
219 219
220#if !LJ_SOFTFP 220#if !LJ_SOFTFP
221/* Load a number constant into an FPR. */ 221/* Load a number constant into an FPR. */
222static void emit_loadn(ASMState *as, Reg r, cTValue *tv) 222static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
223{ 223{
224 cTValue *tv = ir_knum(ir);
224 int32_t i; 225 int32_t i;
225 if ((as->flags & JIT_F_VFPV3) && !tv->u32.lo) { 226 if ((as->flags & JIT_F_VFPV3) && !tv->u32.lo) {
226 uint32_t hi = tv->u32.hi; 227 uint32_t hi = tv->u32.hi;
@@ -308,30 +309,30 @@ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
308 emit_dm(as, ARMI_MOV, dst, src); 309 emit_dm(as, ARMI_MOV, dst, src);
309} 310}
310 311
311/* Generic load of register from stack slot. */ 312/* Generic load of register with base and (small) offset address. */
312static void emit_spload(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 313static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
313{ 314{
314#if LJ_SOFTFP 315#if LJ_SOFTFP
315 lua_assert(!irt_isnum(ir->t)); UNUSED(ir); 316 lua_assert(!irt_isnum(ir->t)); UNUSED(ir);
316#else 317#else
317 if (r >= RID_MAX_GPR) 318 if (r >= RID_MAX_GPR)
318 emit_vlso(as, irt_isnum(ir->t) ? ARMI_VLDR_D : ARMI_VLDR_S, r, RID_SP, ofs); 319 emit_vlso(as, irt_isnum(ir->t) ? ARMI_VLDR_D : ARMI_VLDR_S, r, base, ofs);
319 else 320 else
320#endif 321#endif
321 emit_lso(as, ARMI_LDR, r, RID_SP, ofs); 322 emit_lso(as, ARMI_LDR, r, base, ofs);
322} 323}
323 324
324/* Generic store of register to stack slot. */ 325/* Generic store of register with base and (small) offset address. */
325static void emit_spstore(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 326static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
326{ 327{
327#if LJ_SOFTFP 328#if LJ_SOFTFP
328 lua_assert(!irt_isnum(ir->t)); UNUSED(ir); 329 lua_assert(!irt_isnum(ir->t)); UNUSED(ir);
329#else 330#else
330 if (r >= RID_MAX_GPR) 331 if (r >= RID_MAX_GPR)
331 emit_vlso(as, irt_isnum(ir->t) ? ARMI_VSTR_D : ARMI_VSTR_S, r, RID_SP, ofs); 332 emit_vlso(as, irt_isnum(ir->t) ? ARMI_VSTR_D : ARMI_VSTR_S, r, base, ofs);
332 else 333 else
333#endif 334#endif
334 emit_lso(as, ARMI_STR, r, RID_SP, ofs); 335 emit_lso(as, ARMI_STR, r, base, ofs);
335} 336}
336 337
337/* Emit an arithmetic/logic operation with a constant operand. */ 338/* Emit an arithmetic/logic operation with a constant operand. */
diff --git a/src/lj_emit_arm64.h b/src/lj_emit_arm64.h
new file mode 100644
index 00000000..cfa18c83
--- /dev/null
+++ b/src/lj_emit_arm64.h
@@ -0,0 +1,419 @@
1/*
2** ARM64 instruction emitter.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4**
5** Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
6** Sponsored by Cisco Systems, Inc.
7*/
8
9/* -- Constant encoding --------------------------------------------------- */
10
11static uint64_t get_k64val(IRIns *ir)
12{
13 if (ir->o == IR_KINT64) {
14 return ir_kint64(ir)->u64;
15 } else if (ir->o == IR_KGC) {
16 return (uint64_t)ir_kgc(ir);
17 } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
18 return (uint64_t)ir_kptr(ir);
19 } else {
20 lua_assert(ir->o == IR_KINT || ir->o == IR_KNULL);
21 return ir->i; /* Sign-extended. */
22 }
23}
24
25/* Encode constant in K12 format for data processing instructions. */
26static uint32_t emit_isk12(int64_t n)
27{
28 uint64_t k = (n < 0) ? -n : n;
29 uint32_t m = (n < 0) ? 0x40000000 : 0;
30 if (k < 0x1000) {
31 return A64I_K12|m|A64F_U12(k);
32 } else if ((k & 0xfff000) == k) {
33 return A64I_K12|m|0x400000|A64F_U12(k>>12);
34 }
35 return 0;
36}
37
38#define emit_clz64(n) __builtin_clzll(n)
39#define emit_ctz64(n) __builtin_ctzll(n)
40
41/* Encode constant in K13 format for logical data processing instructions. */
42static uint32_t emit_isk13(uint64_t n, int is64)
43{
44 int inv = 0, w = 128, lz, tz;
45 if (n & 1) { n = ~n; w = 64; inv = 1; } /* Avoid wrap-around of ones. */
46 if (!n) return 0; /* Neither all-zero nor all-ones are allowed. */
47 do { /* Find the repeat width. */
48 if (is64 && (uint32_t)(n^(n>>32))) break;
49 n = (uint32_t)n;
50 if (!n) return 0; /* Ditto when passing n=0xffffffff and is64=0. */
51 w = 32; if ((n^(n>>16)) & 0xffff) break;
52 n = n & 0xffff; w = 16; if ((n^(n>>8)) & 0xff) break;
53 n = n & 0xff; w = 8; if ((n^(n>>4)) & 0xf) break;
54 n = n & 0xf; w = 4; if ((n^(n>>2)) & 0x3) break;
55 n = n & 0x3; w = 2;
56 } while (0);
57 lz = emit_clz64(n);
58 tz = emit_ctz64(n);
59 if ((int64_t)(n << lz) >> (lz+tz) != -1ll) return 0; /* Non-contiguous? */
60 if (inv)
61 return A64I_K13 | (((lz-w) & 127) << 16) | (((lz+tz-w-1) & 63) << 10);
62 else
63 return A64I_K13 | ((w-tz) << 16) | (((63-lz-tz-w-w) & 63) << 10);
64}
65
66static uint32_t emit_isfpk64(uint64_t n)
67{
68 uint64_t etop9 = ((n >> 54) & 0x1ff);
69 if ((n << 16) == 0 && (etop9 == 0x100 || etop9 == 0x0ff)) {
70 return (uint32_t)(((n >> 48) & 0x7f) | ((n >> 56) & 0x80));
71 }
72 return ~0u;
73}
74
75/* -- Emit basic instructions --------------------------------------------- */
76
77static void emit_dnma(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm, Reg ra)
78{
79 *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm) | A64F_A(ra);
80}
81
82static void emit_dnm(ASMState *as, A64Ins ai, Reg rd, Reg rn, Reg rm)
83{
84 *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_M(rm);
85}
86
87static void emit_dm(ASMState *as, A64Ins ai, Reg rd, Reg rm)
88{
89 *--as->mcp = ai | A64F_D(rd) | A64F_M(rm);
90}
91
92static void emit_dn(ASMState *as, A64Ins ai, Reg rd, Reg rn)
93{
94 *--as->mcp = ai | A64F_D(rd) | A64F_N(rn);
95}
96
97static void emit_nm(ASMState *as, A64Ins ai, Reg rn, Reg rm)
98{
99 *--as->mcp = ai | A64F_N(rn) | A64F_M(rm);
100}
101
102static void emit_d(ASMState *as, A64Ins ai, Reg rd)
103{
104 *--as->mcp = ai | A64F_D(rd);
105}
106
107static void emit_n(ASMState *as, A64Ins ai, Reg rn)
108{
109 *--as->mcp = ai | A64F_N(rn);
110}
111
112static int emit_checkofs(A64Ins ai, int64_t ofs)
113{
114 int scale = (ai >> 30) & 3;
115 if (ofs < 0 || (ofs & ((1<<scale)-1))) {
116 return (ofs >= -256 && ofs <= 255) ? -1 : 0;
117 } else {
118 return (ofs < (4096<<scale)) ? 1 : 0;
119 }
120}
121
122static void emit_lso(ASMState *as, A64Ins ai, Reg rd, Reg rn, int64_t ofs)
123{
124 int ot = emit_checkofs(ai, ofs), sc = (ai >> 30) & 3;
125 lua_assert(ot);
126 /* Combine LDR/STR pairs to LDP/STP. */
127 if ((sc == 2 || sc == 3) &&
128 (!(ai & 0x400000) || rd != rn) &&
129 as->mcp != as->mcloop) {
130 uint32_t prev = *as->mcp & ~A64F_D(31);
131 int ofsm = ofs - (1<<sc), ofsp = ofs + (1<<sc);
132 A64Ins aip;
133 if (prev == (ai | A64F_N(rn) | A64F_U12(ofsm>>sc)) ||
134 prev == ((ai^A64I_LS_U) | A64F_N(rn) | A64F_S9(ofsm&0x1ff))) {
135 aip = (A64F_A(rd) | A64F_D(*as->mcp & 31));
136 } else if (prev == (ai | A64F_N(rn) | A64F_U12(ofsp>>sc)) ||
137 prev == ((ai^A64I_LS_U) | A64F_N(rn) | A64F_S9(ofsp&0x1ff))) {
138 aip = (A64F_D(rd) | A64F_A(*as->mcp & 31));
139 ofsm = ofs;
140 } else {
141 goto nopair;
142 }
143 if (ofsm >= (-64<<sc) && ofsm <= (63<<sc)) {
144 *as->mcp = aip | A64F_N(rn) | ((ofsm >> sc) << 15) |
145 (ai ^ ((ai == A64I_LDRx || ai == A64I_STRx) ? 0x50000000 : 0x90000000));
146 return;
147 }
148 }
149nopair:
150 if (ot == 1)
151 *--as->mcp = ai | A64F_D(rd) | A64F_N(rn) | A64F_U12(ofs >> sc);
152 else
153 *--as->mcp = (ai^A64I_LS_U) | A64F_D(rd) | A64F_N(rn) | A64F_S9(ofs & 0x1ff);
154}
155
156/* -- Emit loads/stores --------------------------------------------------- */
157
158/* Prefer rematerialization of BASE/L from global_State over spills. */
159#define emit_canremat(ref) ((ref) <= ASMREF_L)
160
161/* Try to find an N-step delta relative to other consts with N < lim. */
162static int emit_kdelta(ASMState *as, Reg rd, uint64_t k, int lim)
163{
164 RegSet work = ~as->freeset & RSET_GPR;
165 if (lim <= 1) return 0; /* Can't beat that. */
166 while (work) {
167 Reg r = rset_picktop(work);
168 IRRef ref = regcost_ref(as->cost[r]);
169 lua_assert(r != rd);
170 if (ref < REF_TRUE) {
171 uint64_t kx = ra_iskref(ref) ? (uint64_t)ra_krefk(as, ref) :
172 get_k64val(IR(ref));
173 int64_t delta = (int64_t)(k - kx);
174 if (delta == 0) {
175 emit_dm(as, A64I_MOVx, rd, r);
176 return 1;
177 } else {
178 uint32_t k12 = emit_isk12(delta < 0 ? -delta : delta);
179 if (k12) {
180 emit_dn(as, (delta < 0 ? A64I_SUBx : A64I_ADDx)^k12, rd, r);
181 return 1;
182 }
183 /* Do other ops or multi-step deltas pay off? Probably not.
184 ** E.g. XOR rarely helps with pointer consts.
185 */
186 }
187 }
188 rset_clear(work, r);
189 }
190 return 0; /* Failed. */
191}
192
193static void emit_loadk(ASMState *as, Reg rd, uint64_t u64, int is64)
194{
195 uint32_t k13 = emit_isk13(u64, is64);
196 if (k13) { /* Can the constant be represented as a bitmask immediate? */
197 emit_dn(as, (is64|A64I_ORRw)^k13, rd, RID_ZERO);
198 } else {
199 int i, zeros = 0, ones = 0, neg;
200 if (!is64) u64 = (int64_t)(int32_t)u64; /* Sign-extend. */
201 /* Count homogeneous 16 bit fragments. */
202 for (i = 0; i < 4; i++) {
203 uint64_t frag = (u64 >> i*16) & 0xffff;
204 zeros += (frag == 0);
205 ones += (frag == 0xffff);
206 }
207 neg = ones > zeros; /* Use MOVN if it pays off. */
208 if (!emit_kdelta(as, rd, u64, 4 - (neg ? ones : zeros))) {
209 int shift = 0, lshift = 0;
210 uint64_t n64 = neg ? ~u64 : u64;
211 if (n64 != 0) {
212 /* Find first/last fragment to be filled. */
213 shift = (63-emit_clz64(n64)) & ~15;
214 lshift = emit_ctz64(n64) & ~15;
215 }
216 /* MOVK requires the original value (u64). */
217 while (shift > lshift) {
218 uint32_t u16 = (u64 >> shift) & 0xffff;
219 /* Skip fragments that are correctly filled by MOVN/MOVZ. */
220 if (u16 != (neg ? 0xffff : 0))
221 emit_d(as, is64 | A64I_MOVKw | A64F_U16(u16) | A64F_LSL16(shift), rd);
222 shift -= 16;
223 }
224 /* But MOVN needs an inverted value (n64). */
225 emit_d(as, (neg ? A64I_MOVNx : A64I_MOVZx) |
226 A64F_U16((n64 >> lshift) & 0xffff) | A64F_LSL16(lshift), rd);
227 }
228 }
229}
230
231/* Load a 32 bit constant into a GPR. */
232#define emit_loadi(as, rd, i) emit_loadk(as, rd, i, 0)
233
234/* Load a 64 bit constant into a GPR. */
235#define emit_loadu64(as, rd, i) emit_loadk(as, rd, i, A64I_X)
236
237#define emit_loada(as, r, addr) emit_loadu64(as, (r), (uintptr_t)(addr))
238
239#define glofs(as, k) \
240 ((intptr_t)((uintptr_t)(k) - (uintptr_t)&J2GG(as->J)->g))
241#define mcpofs(as, k) \
242 ((intptr_t)((uintptr_t)(k) - (uintptr_t)(as->mcp - 1)))
243#define checkmcpofs(as, k) \
244 ((((mcpofs(as, k)>>2) + 0x00040000) >> 19) == 0)
245
246static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
247
248/* Get/set from constant pointer. */
249static void emit_lsptr(ASMState *as, A64Ins ai, Reg r, void *p)
250{
251 /* First, check if ip + offset is in range. */
252 if ((ai & 0x00400000) && checkmcpofs(as, p)) {
253 emit_d(as, A64I_LDRLx | A64F_S19(mcpofs(as, p)>>2), r);
254 } else {
255 Reg base = RID_GL; /* Next, try GL + offset. */
256 int64_t ofs = glofs(as, p);
257 if (!emit_checkofs(ai, ofs)) { /* Else split up into base reg + offset. */
258 int64_t i64 = i64ptr(p);
259 base = ra_allock(as, (i64 & ~0x7fffull), rset_exclude(RSET_GPR, r));
260 ofs = i64 & 0x7fffull;
261 }
262 emit_lso(as, ai, r, base, ofs);
263 }
264}
265
266/* Load 64 bit IR constant into register. */
267static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
268{
269 const uint64_t *k = &ir_k64(ir)->u64;
270 int64_t ofs;
271 if (r >= RID_MAX_GPR) {
272 uint32_t fpk = emit_isfpk64(*k);
273 if (fpk != ~0u) {
274 emit_d(as, A64I_FMOV_DI | A64F_FP8(fpk), (r & 31));
275 return;
276 }
277 }
278 ofs = glofs(as, k);
279 if (emit_checkofs(A64I_LDRx, ofs)) {
280 emit_lso(as, r >= RID_MAX_GPR ? A64I_LDRd : A64I_LDRx,
281 (r & 31), RID_GL, ofs);
282 } else {
283 if (r >= RID_MAX_GPR) {
284 emit_dn(as, A64I_FMOV_D_R, (r & 31), RID_TMP);
285 r = RID_TMP;
286 }
287 if (checkmcpofs(as, k))
288 emit_d(as, A64I_LDRLx | A64F_S19(mcpofs(as, k)>>2), r);
289 else
290 emit_loadu64(as, r, *k);
291 }
292}
293
294/* Get/set global_State fields. */
295#define emit_getgl(as, r, field) \
296 emit_lsptr(as, A64I_LDRx, (r), (void *)&J2G(as->J)->field)
297#define emit_setgl(as, r, field) \
298 emit_lsptr(as, A64I_STRx, (r), (void *)&J2G(as->J)->field)
299
300/* Trace number is determined from pc of exit instruction. */
301#define emit_setvmstate(as, i) UNUSED(i)
302
303/* -- Emit control-flow instructions -------------------------------------- */
304
305/* Label for internal jumps. */
306typedef MCode *MCLabel;
307
308/* Return label pointing to current PC. */
309#define emit_label(as) ((as)->mcp)
310
311static void emit_cond_branch(ASMState *as, A64CC cond, MCode *target)
312{
313 MCode *p = --as->mcp;
314 ptrdiff_t delta = target - p;
315 lua_assert(((delta + 0x40000) >> 19) == 0);
316 *p = A64I_BCC | A64F_S19(delta) | cond;
317}
318
319static void emit_branch(ASMState *as, A64Ins ai, MCode *target)
320{
321 MCode *p = --as->mcp;
322 ptrdiff_t delta = target - p;
323 lua_assert(((delta + 0x02000000) >> 26) == 0);
324 *p = ai | ((uint32_t)delta & 0x03ffffffu);
325}
326
327static void emit_tnb(ASMState *as, A64Ins ai, Reg r, uint32_t bit, MCode *target)
328{
329 MCode *p = --as->mcp;
330 ptrdiff_t delta = target - p;
331 lua_assert(bit < 63 && ((delta + 0x2000) >> 14) == 0);
332 if (bit > 31) ai |= A64I_X;
333 *p = ai | A64F_BIT(bit & 31) | A64F_S14((uint32_t)delta & 0x3fffu) | r;
334}
335
336static void emit_cnb(ASMState *as, A64Ins ai, Reg r, MCode *target)
337{
338 MCode *p = --as->mcp;
339 ptrdiff_t delta = target - p;
340 lua_assert(((delta + 0x40000) >> 19) == 0);
341 *p = ai | A64F_S19(delta) | r;
342}
343
344#define emit_jmp(as, target) emit_branch(as, A64I_B, (target))
345
346static void emit_call(ASMState *as, void *target)
347{
348 MCode *p = --as->mcp;
349 ptrdiff_t delta = (char *)target - (char *)p;
350 if ((((delta>>2) + 0x02000000) >> 26) == 0) {
351 *p = A64I_BL | ((uint32_t)(delta>>2) & 0x03ffffffu);
352 } else { /* Target out of range: need indirect call. But don't use R0-R7. */
353 Reg r = ra_allock(as, i64ptr(target),
354 RSET_RANGE(RID_X8, RID_MAX_GPR)-RSET_FIXED);
355 *p = A64I_BLR | A64F_N(r);
356 }
357}
358
359/* -- Emit generic operations --------------------------------------------- */
360
361/* Generic move between two regs. */
362static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
363{
364 if (dst >= RID_MAX_GPR) {
365 emit_dn(as, irt_isnum(ir->t) ? A64I_FMOV_D : A64I_FMOV_S,
366 (dst & 31), (src & 31));
367 return;
368 }
369 if (as->mcp != as->mcloop) { /* Swap early registers for loads/stores. */
370 MCode ins = *as->mcp, swp = (src^dst);
371 if ((ins & 0xbf800000) == 0xb9000000) {
372 if (!((ins ^ (dst << 5)) & 0x000003e0))
373 *as->mcp = ins ^ (swp << 5); /* Swap N in load/store. */
374 if (!(ins & 0x00400000) && !((ins ^ dst) & 0x0000001f))
375 *as->mcp = ins ^ swp; /* Swap D in store. */
376 }
377 }
378 emit_dm(as, A64I_MOVx, dst, src);
379}
380
381/* Generic load of register with base and (small) offset address. */
382static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
383{
384 if (r >= RID_MAX_GPR)
385 emit_lso(as, irt_isnum(ir->t) ? A64I_LDRd : A64I_LDRs, (r & 31), base, ofs);
386 else
387 emit_lso(as, irt_is64(ir->t) ? A64I_LDRx : A64I_LDRw, r, base, ofs);
388}
389
390/* Generic store of register with base and (small) offset address. */
391static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
392{
393 if (r >= RID_MAX_GPR)
394 emit_lso(as, irt_isnum(ir->t) ? A64I_STRd : A64I_STRs, (r & 31), base, ofs);
395 else
396 emit_lso(as, irt_is64(ir->t) ? A64I_STRx : A64I_STRw, r, base, ofs);
397}
398
399/* Emit an arithmetic operation with a constant operand. */
400static void emit_opk(ASMState *as, A64Ins ai, Reg dest, Reg src,
401 int32_t i, RegSet allow)
402{
403 uint32_t k = emit_isk12(i);
404 if (k)
405 emit_dn(as, ai^k, dest, src);
406 else
407 emit_dnm(as, ai, dest, src, ra_allock(as, i, allow));
408}
409
410/* Add offset to pointer. */
411static void emit_addptr(ASMState *as, Reg r, int32_t ofs)
412{
413 if (ofs)
414 emit_opk(as, ofs < 0 ? A64I_SUBx : A64I_ADDx, r, r,
415 ofs < 0 ? -ofs : ofs, rset_exclude(RSET_GPR, r));
416}
417
418#define emit_spsub(as, ofs) emit_addptr(as, RID_SP, -(ofs))
419
diff --git a/src/lj_emit_mips.h b/src/lj_emit_mips.h
index ed62608a..8a9ee24d 100644
--- a/src/lj_emit_mips.h
+++ b/src/lj_emit_mips.h
@@ -3,6 +3,28 @@
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h 3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/ 4*/
5 5
6#if LJ_64
7static intptr_t get_k64val(IRIns *ir)
8{
9 if (ir->o == IR_KINT64) {
10 return (intptr_t)ir_kint64(ir)->u64;
11 } else if (ir->o == IR_KGC) {
12 return (intptr_t)ir_kgc(ir);
13 } else if (ir->o == IR_KPTR || ir->o == IR_KKPTR) {
14 return (intptr_t)ir_kptr(ir);
15 } else {
16 lua_assert(ir->o == IR_KINT || ir->o == IR_KNULL);
17 return ir->i; /* Sign-extended. */
18 }
19}
20#endif
21
22#if LJ_64
23#define get_kval(ir) get_k64val(ir)
24#else
25#define get_kval(ir) ((ir)->i)
26#endif
27
6/* -- Emit basic instructions --------------------------------------------- */ 28/* -- Emit basic instructions --------------------------------------------- */
7 29
8static void emit_dst(ASMState *as, MIPSIns mi, Reg rd, Reg rs, Reg rt) 30static void emit_dst(ASMState *as, MIPSIns mi, Reg rd, Reg rs, Reg rt)
@@ -35,7 +57,7 @@ static void emit_fgh(ASMState *as, MIPSIns mi, Reg rf, Reg rg, Reg rh)
35 57
36static void emit_rotr(ASMState *as, Reg dest, Reg src, Reg tmp, uint32_t shift) 58static void emit_rotr(ASMState *as, Reg dest, Reg src, Reg tmp, uint32_t shift)
37{ 59{
38 if ((as->flags & JIT_F_MIPS32R2)) { 60 if (LJ_64 || (as->flags & JIT_F_MIPSXXR2)) {
39 emit_dta(as, MIPSI_ROTR, dest, src, shift); 61 emit_dta(as, MIPSI_ROTR, dest, src, shift);
40 } else { 62 } else {
41 emit_dst(as, MIPSI_OR, dest, dest, tmp); 63 emit_dst(as, MIPSI_OR, dest, dest, tmp);
@@ -44,13 +66,21 @@ static void emit_rotr(ASMState *as, Reg dest, Reg src, Reg tmp, uint32_t shift)
44 } 66 }
45} 67}
46 68
69#if LJ_64
70static void emit_tsml(ASMState *as, MIPSIns mi, Reg rt, Reg rs, uint32_t msb,
71 uint32_t lsb)
72{
73 *--as->mcp = mi | MIPSF_T(rt) | MIPSF_S(rs) | MIPSF_M(msb) | MIPSF_L(lsb);
74}
75#endif
76
47/* -- Emit loads/stores --------------------------------------------------- */ 77/* -- Emit loads/stores --------------------------------------------------- */
48 78
49/* Prefer rematerialization of BASE/L from global_State over spills. */ 79/* Prefer rematerialization of BASE/L from global_State over spills. */
50#define emit_canremat(ref) ((ref) <= REF_BASE) 80#define emit_canremat(ref) ((ref) <= REF_BASE)
51 81
52/* Try to find a one step delta relative to another constant. */ 82/* Try to find a one step delta relative to another constant. */
53static int emit_kdelta1(ASMState *as, Reg t, int32_t i) 83static int emit_kdelta1(ASMState *as, Reg t, intptr_t i)
54{ 84{
55 RegSet work = ~as->freeset & RSET_GPR; 85 RegSet work = ~as->freeset & RSET_GPR;
56 while (work) { 86 while (work) {
@@ -58,9 +88,10 @@ static int emit_kdelta1(ASMState *as, Reg t, int32_t i)
58 IRRef ref = regcost_ref(as->cost[r]); 88 IRRef ref = regcost_ref(as->cost[r]);
59 lua_assert(r != t); 89 lua_assert(r != t);
60 if (ref < ASMREF_L) { 90 if (ref < ASMREF_L) {
61 int32_t delta = i - (ra_iskref(ref) ? ra_krefk(as, ref) : IR(ref)->i); 91 intptr_t delta = (intptr_t)((uintptr_t)i -
92 (uintptr_t)(ra_iskref(ref) ? ra_krefk(as, ref) : get_kval(IR(ref))));
62 if (checki16(delta)) { 93 if (checki16(delta)) {
63 emit_tsi(as, MIPSI_ADDIU, t, r, delta); 94 emit_tsi(as, MIPSI_AADDIU, t, r, delta);
64 return 1; 95 return 1;
65 } 96 }
66 } 97 }
@@ -76,8 +107,8 @@ static void emit_loadi(ASMState *as, Reg r, int32_t i)
76 emit_ti(as, MIPSI_LI, r, i); 107 emit_ti(as, MIPSI_LI, r, i);
77 } else { 108 } else {
78 if ((i & 0xffff)) { 109 if ((i & 0xffff)) {
79 int32_t jgl = i32ptr(J2G(as->J)); 110 intptr_t jgl = (intptr_t)(void *)J2G(as->J);
80 if ((uint32_t)(i-jgl) < 65536) { 111 if ((uintptr_t)(i-jgl) < 65536) {
81 emit_tsi(as, MIPSI_ADDIU, r, RID_JGL, i-jgl-32768); 112 emit_tsi(as, MIPSI_ADDIU, r, RID_JGL, i-jgl-32768);
82 return; 113 return;
83 } else if (emit_kdelta1(as, r, i)) { 114 } else if (emit_kdelta1(as, r, i)) {
@@ -92,16 +123,48 @@ static void emit_loadi(ASMState *as, Reg r, int32_t i)
92 } 123 }
93} 124}
94 125
126#if LJ_64
127/* Load a 64 bit constant into a GPR. */
128static void emit_loadu64(ASMState *as, Reg r, uint64_t u64)
129{
130 if (checki32((int64_t)u64)) {
131 emit_loadi(as, r, (int32_t)u64);
132 } else {
133 uint64_t delta = u64 - (uint64_t)(void *)J2G(as->J);
134 if (delta < 65536) {
135 emit_tsi(as, MIPSI_DADDIU, r, RID_JGL, (int32_t)(delta-32768));
136 } else if (emit_kdelta1(as, r, (intptr_t)u64)) {
137 return;
138 } else {
139 if ((u64 & 0xffff)) {
140 emit_tsi(as, MIPSI_ORI, r, r, u64 & 0xffff);
141 }
142 if (((u64 >> 16) & 0xffff)) {
143 emit_dta(as, MIPSI_DSLL, r, r, 16);
144 emit_tsi(as, MIPSI_ORI, r, r, (u64 >> 16) & 0xffff);
145 emit_dta(as, MIPSI_DSLL, r, r, 16);
146 } else {
147 emit_dta(as, MIPSI_DSLL32, r, r, 0);
148 }
149 emit_loadi(as, r, (int32_t)(u64 >> 32));
150 }
151 /* TODO: There are probably more optimization opportunities. */
152 }
153}
154
155#define emit_loada(as, r, addr) emit_loadu64(as, (r), u64ptr((addr)))
156#else
95#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) 157#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr)))
158#endif
96 159
97static Reg ra_allock(ASMState *as, int32_t k, RegSet allow); 160static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
98static void ra_allockreg(ASMState *as, int32_t k, Reg r); 161static void ra_allockreg(ASMState *as, intptr_t k, Reg r);
99 162
100/* Get/set from constant pointer. */ 163/* Get/set from constant pointer. */
101static void emit_lsptr(ASMState *as, MIPSIns mi, Reg r, void *p, RegSet allow) 164static void emit_lsptr(ASMState *as, MIPSIns mi, Reg r, void *p, RegSet allow)
102{ 165{
103 int32_t jgl = i32ptr(J2G(as->J)); 166 intptr_t jgl = (intptr_t)(J2G(as->J));
104 int32_t i = i32ptr(p); 167 intptr_t i = (intptr_t)(p);
105 Reg base; 168 Reg base;
106 if ((uint32_t)(i-jgl) < 65536) { 169 if ((uint32_t)(i-jgl) < 65536) {
107 i = i-jgl-32768; 170 i = i-jgl-32768;
@@ -112,8 +175,24 @@ static void emit_lsptr(ASMState *as, MIPSIns mi, Reg r, void *p, RegSet allow)
112 emit_tsi(as, mi, r, base, i); 175 emit_tsi(as, mi, r, base, i);
113} 176}
114 177
115#define emit_loadn(as, r, tv) \ 178#if LJ_64
116 emit_lsptr(as, MIPSI_LDC1, ((r) & 31), (void *)(tv), RSET_GPR) 179static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
180{
181 const uint64_t *k = &ir_k64(ir)->u64;
182 Reg r64 = r;
183 if (rset_test(RSET_FPR, r)) {
184 r64 = RID_TMP;
185 emit_tg(as, MIPSI_DMTC1, r64, r);
186 }
187 if ((uint32_t)((intptr_t)k-(intptr_t)J2G(as->J)) < 65536)
188 emit_lsptr(as, MIPSI_LD, r64, (void *)k, 0);
189 else
190 emit_loadu64(as, r64, *k);
191}
192#else
193#define emit_loadk64(as, r, ir) \
194 emit_lsptr(as, MIPSI_LDC1, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR)
195#endif
117 196
118/* Get/set global_State fields. */ 197/* Get/set global_State fields. */
119static void emit_lsglptr(ASMState *as, MIPSIns mi, Reg r, int32_t ofs) 198static void emit_lsglptr(ASMState *as, MIPSIns mi, Reg r, int32_t ofs)
@@ -122,9 +201,9 @@ static void emit_lsglptr(ASMState *as, MIPSIns mi, Reg r, int32_t ofs)
122} 201}
123 202
124#define emit_getgl(as, r, field) \ 203#define emit_getgl(as, r, field) \
125 emit_lsglptr(as, MIPSI_LW, (r), (int32_t)offsetof(global_State, field)) 204 emit_lsglptr(as, MIPSI_AL, (r), (int32_t)offsetof(global_State, field))
126#define emit_setgl(as, r, field) \ 205#define emit_setgl(as, r, field) \
127 emit_lsglptr(as, MIPSI_SW, (r), (int32_t)offsetof(global_State, field)) 206 emit_lsglptr(as, MIPSI_AS, (r), (int32_t)offsetof(global_State, field))
128 207
129/* Trace number is determined from per-trace exit stubs. */ 208/* Trace number is determined from per-trace exit stubs. */
130#define emit_setvmstate(as, i) UNUSED(i) 209#define emit_setvmstate(as, i) UNUSED(i)
@@ -152,16 +231,19 @@ static void emit_jmp(ASMState *as, MCode *target)
152 emit_branch(as, MIPSI_B, RID_ZERO, RID_ZERO, (target)); 231 emit_branch(as, MIPSI_B, RID_ZERO, RID_ZERO, (target));
153} 232}
154 233
155static void emit_call(ASMState *as, void *target) 234static void emit_call(ASMState *as, void *target, int needcfa)
156{ 235{
157 MCode *p = as->mcp; 236 MCode *p = as->mcp;
158 *--p = MIPSI_NOP; 237 *--p = MIPSI_NOP;
159 if ((((uintptr_t)target ^ (uintptr_t)p) >> 28) == 0) 238 if ((((uintptr_t)target ^ (uintptr_t)p) >> 28) == 0) {
160 *--p = MIPSI_JAL | (((uintptr_t)target >>2) & 0x03ffffffu); 239 *--p = (((uintptr_t)target & 1) ? MIPSI_JALX : MIPSI_JAL) |
161 else /* Target out of range: need indirect call. */ 240 (((uintptr_t)target >>2) & 0x03ffffffu);
241 } else { /* Target out of range: need indirect call. */
162 *--p = MIPSI_JALR | MIPSF_S(RID_CFUNCADDR); 242 *--p = MIPSI_JALR | MIPSF_S(RID_CFUNCADDR);
243 needcfa = 1;
244 }
163 as->mcp = p; 245 as->mcp = p;
164 ra_allockreg(as, i32ptr(target), RID_CFUNCADDR); 246 if (needcfa) ra_allockreg(as, (intptr_t)target, RID_CFUNCADDR);
165} 247}
166 248
167/* -- Emit generic operations --------------------------------------------- */ 249/* -- Emit generic operations --------------------------------------------- */
@@ -178,24 +260,24 @@ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
178 emit_fg(as, irt_isnum(ir->t) ? MIPSI_MOV_D : MIPSI_MOV_S, dst, src); 260 emit_fg(as, irt_isnum(ir->t) ? MIPSI_MOV_D : MIPSI_MOV_S, dst, src);
179} 261}
180 262
181/* Generic load of register from stack slot. */ 263/* Generic load of register with base and (small) offset address. */
182static void emit_spload(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 264static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
183{ 265{
184 if (r < RID_MAX_GPR) 266 if (r < RID_MAX_GPR)
185 emit_tsi(as, MIPSI_LW, r, RID_SP, ofs); 267 emit_tsi(as, irt_is64(ir->t) ? MIPSI_LD : MIPSI_LW, r, base, ofs);
186 else 268 else
187 emit_tsi(as, irt_isnum(ir->t) ? MIPSI_LDC1 : MIPSI_LWC1, 269 emit_tsi(as, irt_isnum(ir->t) ? MIPSI_LDC1 : MIPSI_LWC1,
188 (r & 31), RID_SP, ofs); 270 (r & 31), base, ofs);
189} 271}
190 272
191/* Generic store of register to stack slot. */ 273/* Generic store of register with base and (small) offset address. */
192static void emit_spstore(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 274static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
193{ 275{
194 if (r < RID_MAX_GPR) 276 if (r < RID_MAX_GPR)
195 emit_tsi(as, MIPSI_SW, r, RID_SP, ofs); 277 emit_tsi(as, irt_is64(ir->t) ? MIPSI_SD : MIPSI_SW, r, base, ofs);
196 else 278 else
197 emit_tsi(as, irt_isnum(ir->t) ? MIPSI_SDC1 : MIPSI_SWC1, 279 emit_tsi(as, irt_isnum(ir->t) ? MIPSI_SDC1 : MIPSI_SWC1,
198 (r&31), RID_SP, ofs); 280 (r&31), base, ofs);
199} 281}
200 282
201/* Add offset to pointer. */ 283/* Add offset to pointer. */
@@ -203,7 +285,7 @@ static void emit_addptr(ASMState *as, Reg r, int32_t ofs)
203{ 285{
204 if (ofs) { 286 if (ofs) {
205 lua_assert(checki16(ofs)); 287 lua_assert(checki16(ofs));
206 emit_tsi(as, MIPSI_ADDIU, r, r, ofs); 288 emit_tsi(as, MIPSI_AADDIU, r, r, ofs);
207 } 289 }
208} 290}
209 291
diff --git a/src/lj_emit_ppc.h b/src/lj_emit_ppc.h
index 14099302..21c3c2ac 100644
--- a/src/lj_emit_ppc.h
+++ b/src/lj_emit_ppc.h
@@ -98,7 +98,7 @@ static void emit_loadi(ASMState *as, Reg r, int32_t i)
98 98
99#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr))) 99#define emit_loada(as, r, addr) emit_loadi(as, (r), i32ptr((addr)))
100 100
101static Reg ra_allock(ASMState *as, int32_t k, RegSet allow); 101static Reg ra_allock(ASMState *as, intptr_t k, RegSet allow);
102 102
103/* Get/set from constant pointer. */ 103/* Get/set from constant pointer. */
104static void emit_lsptr(ASMState *as, PPCIns pi, Reg r, void *p, RegSet allow) 104static void emit_lsptr(ASMState *as, PPCIns pi, Reg r, void *p, RegSet allow)
@@ -115,8 +115,8 @@ static void emit_lsptr(ASMState *as, PPCIns pi, Reg r, void *p, RegSet allow)
115 emit_tai(as, pi, r, base, i); 115 emit_tai(as, pi, r, base, i);
116} 116}
117 117
118#define emit_loadn(as, r, tv) \ 118#define emit_loadk64(as, r, ir) \
119 emit_lsptr(as, PPCI_LFD, ((r) & 31), (void *)(tv), RSET_GPR) 119 emit_lsptr(as, PPCI_LFD, ((r) & 31), (void *)&ir_knum((ir))->u64, RSET_GPR)
120 120
121/* Get/set global_State fields. */ 121/* Get/set global_State fields. */
122static void emit_lsglptr(ASMState *as, PPCIns pi, Reg r, int32_t ofs) 122static void emit_lsglptr(ASMState *as, PPCIns pi, Reg r, int32_t ofs)
@@ -186,22 +186,22 @@ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
186 emit_fb(as, PPCI_FMR, dst, src); 186 emit_fb(as, PPCI_FMR, dst, src);
187} 187}
188 188
189/* Generic load of register from stack slot. */ 189/* Generic load of register with base and (small) offset address. */
190static void emit_spload(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 190static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
191{ 191{
192 if (r < RID_MAX_GPR) 192 if (r < RID_MAX_GPR)
193 emit_tai(as, PPCI_LWZ, r, RID_SP, ofs); 193 emit_tai(as, PPCI_LWZ, r, base, ofs);
194 else 194 else
195 emit_fai(as, irt_isnum(ir->t) ? PPCI_LFD : PPCI_LFS, r, RID_SP, ofs); 195 emit_fai(as, irt_isnum(ir->t) ? PPCI_LFD : PPCI_LFS, r, base, ofs);
196} 196}
197 197
198/* Generic store of register to stack slot. */ 198/* Generic store of register with base and (small) offset address. */
199static void emit_spstore(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 199static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
200{ 200{
201 if (r < RID_MAX_GPR) 201 if (r < RID_MAX_GPR)
202 emit_tai(as, PPCI_STW, r, RID_SP, ofs); 202 emit_tai(as, PPCI_STW, r, base, ofs);
203 else 203 else
204 emit_fai(as, irt_isnum(ir->t) ? PPCI_STFD : PPCI_STFS, r, RID_SP, ofs); 204 emit_fai(as, irt_isnum(ir->t) ? PPCI_STFD : PPCI_STFS, r, base, ofs);
205} 205}
206 206
207/* Emit a compare (for equality) with a constant operand. */ 207/* Emit a compare (for equality) with a constant operand. */
diff --git a/src/lj_emit_x86.h b/src/lj_emit_x86.h
index bcceb93e..a6b8713e 100644
--- a/src/lj_emit_x86.h
+++ b/src/lj_emit_x86.h
@@ -13,10 +13,17 @@
13 if (rex != 0x40) *--(p) = rex; } 13 if (rex != 0x40) *--(p) = rex; }
14#define FORCE_REX 0x200 14#define FORCE_REX 0x200
15#define REX_64 (FORCE_REX|0x080000) 15#define REX_64 (FORCE_REX|0x080000)
16#define VEX_64 0x800000
16#else 17#else
17#define REXRB(p, rr, rb) ((void)0) 18#define REXRB(p, rr, rb) ((void)0)
18#define FORCE_REX 0 19#define FORCE_REX 0
19#define REX_64 0 20#define REX_64 0
21#define VEX_64 0
22#endif
23#if LJ_GC64
24#define REX_GC64 REX_64
25#else
26#define REX_GC64 0
20#endif 27#endif
21 28
22#define emit_i8(as, i) (*--as->mcp = (MCode)(i)) 29#define emit_i8(as, i) (*--as->mcp = (MCode)(i))
@@ -31,6 +38,13 @@ static LJ_AINLINE MCode *emit_op(x86Op xo, Reg rr, Reg rb, Reg rx,
31 MCode *p, int delta) 38 MCode *p, int delta)
32{ 39{
33 int n = (int8_t)xo; 40 int n = (int8_t)xo;
41 if (n == -60) { /* VEX-encoded instruction */
42#if LJ_64
43 xo ^= (((rr>>1)&4)+((rx>>2)&2)+((rb>>3)&1))<<13;
44#endif
45 *(uint32_t *)(p+delta-5) = (uint32_t)xo;
46 return p+delta-5;
47 }
34#if defined(__GNUC__) 48#if defined(__GNUC__)
35 if (__builtin_constant_p(xo) && n == -2) 49 if (__builtin_constant_p(xo) && n == -2)
36 p[delta-2] = (MCode)(xo >> 24); 50 p[delta-2] = (MCode)(xo >> 24);
@@ -85,26 +99,17 @@ static int32_t ptr2addr(const void *p)
85#define ptr2addr(p) (i32ptr((p))) 99#define ptr2addr(p) (i32ptr((p)))
86#endif 100#endif
87 101
88/* op r, [addr] */
89static void emit_rma(ASMState *as, x86Op xo, Reg rr, const void *addr)
90{
91 MCode *p = as->mcp;
92 *(int32_t *)(p-4) = ptr2addr(addr);
93#if LJ_64
94 p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP);
95 as->mcp = emit_opm(xo, XM_OFS0, rr, RID_ESP, p, -5);
96#else
97 as->mcp = emit_opm(xo, XM_OFS0, rr, RID_EBP, p, -4);
98#endif
99}
100
101/* op r, [base+ofs] */ 102/* op r, [base+ofs] */
102static void emit_rmro(ASMState *as, x86Op xo, Reg rr, Reg rb, int32_t ofs) 103static void emit_rmro(ASMState *as, x86Op xo, Reg rr, Reg rb, int32_t ofs)
103{ 104{
104 MCode *p = as->mcp; 105 MCode *p = as->mcp;
105 x86Mode mode; 106 x86Mode mode;
106 if (ra_hasreg(rb)) { 107 if (ra_hasreg(rb)) {
107 if (ofs == 0 && (rb&7) != RID_EBP) { 108 if (LJ_GC64 && rb == RID_RIP) {
109 mode = XM_OFS0;
110 p -= 4;
111 *(int32_t *)p = ofs;
112 } else if (ofs == 0 && (rb&7) != RID_EBP) {
108 mode = XM_OFS0; 113 mode = XM_OFS0;
109 } else if (checki8(ofs)) { 114 } else if (checki8(ofs)) {
110 *--p = (MCode)ofs; 115 *--p = (MCode)ofs;
@@ -202,6 +207,11 @@ static void emit_mrm(ASMState *as, x86Op xo, Reg rr, Reg rb)
202 *--p = MODRM(XM_SCALE1, RID_ESP, RID_EBP); 207 *--p = MODRM(XM_SCALE1, RID_ESP, RID_EBP);
203 rb = RID_ESP; 208 rb = RID_ESP;
204#endif 209#endif
210 } else if (LJ_GC64 && rb == RID_RIP) {
211 lua_assert(as->mrm.idx == RID_NONE);
212 mode = XM_OFS0;
213 p -= 4;
214 *(int32_t *)p = as->mrm.ofs;
205 } else { 215 } else {
206 if (as->mrm.ofs == 0 && (rb&7) != RID_EBP) { 216 if (as->mrm.ofs == 0 && (rb&7) != RID_EBP) {
207 mode = XM_OFS0; 217 mode = XM_OFS0;
@@ -241,10 +251,6 @@ static void emit_gmrmi(ASMState *as, x86Group xg, Reg rb, int32_t i)
241 251
242/* -- Emit loads/stores --------------------------------------------------- */ 252/* -- Emit loads/stores --------------------------------------------------- */
243 253
244/* Instruction selection for XMM moves. */
245#define XMM_MOVRR(as) ((as->flags & JIT_F_SPLIT_XMM) ? XO_MOVSD : XO_MOVAPS)
246#define XMM_MOVRM(as) ((as->flags & JIT_F_SPLIT_XMM) ? XO_MOVLPD : XO_MOVSD)
247
248/* mov [base+ofs], i */ 254/* mov [base+ofs], i */
249static void emit_movmroi(ASMState *as, Reg base, int32_t ofs, int32_t i) 255static void emit_movmroi(ASMState *as, Reg base, int32_t ofs, int32_t i)
250{ 256{
@@ -259,8 +265,8 @@ static void emit_movmroi(ASMState *as, Reg base, int32_t ofs, int32_t i)
259/* Get/set global_State fields. */ 265/* Get/set global_State fields. */
260#define emit_opgl(as, xo, r, field) \ 266#define emit_opgl(as, xo, r, field) \
261 emit_rma(as, (xo), (r), (void *)&J2G(as->J)->field) 267 emit_rma(as, (xo), (r), (void *)&J2G(as->J)->field)
262#define emit_getgl(as, r, field) emit_opgl(as, XO_MOV, (r), field) 268#define emit_getgl(as, r, field) emit_opgl(as, XO_MOV, (r)|REX_GC64, field)
263#define emit_setgl(as, r, field) emit_opgl(as, XO_MOVto, (r), field) 269#define emit_setgl(as, r, field) emit_opgl(as, XO_MOVto, (r)|REX_GC64, field)
264 270
265#define emit_setvmstate(as, i) \ 271#define emit_setvmstate(as, i) \
266 (emit_i32(as, i), emit_opgl(as, XO_MOVmi, 0, vmstate)) 272 (emit_i32(as, i), emit_opgl(as, XO_MOVmi, 0, vmstate))
@@ -283,9 +289,21 @@ static void emit_loadi(ASMState *as, Reg r, int32_t i)
283 } 289 }
284} 290}
285 291
292#if LJ_GC64
293#define dispofs(as, k) \
294 ((intptr_t)((uintptr_t)(k) - (uintptr_t)J2GG(as->J)->dispatch))
295#define mcpofs(as, k) \
296 ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mcp))
297#define mctopofs(as, k) \
298 ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mctop))
299/* mov r, addr */
300#define emit_loada(as, r, addr) \
301 emit_loadu64(as, (r), (uintptr_t)(addr))
302#else
286/* mov r, addr */ 303/* mov r, addr */
287#define emit_loada(as, r, addr) \ 304#define emit_loada(as, r, addr) \
288 emit_loadi(as, (r), ptr2addr((addr))) 305 emit_loadi(as, (r), ptr2addr((addr)))
306#endif
289 307
290#if LJ_64 308#if LJ_64
291/* mov r, imm64 or shorter 32 bit extended load. */ 309/* mov r, imm64 or shorter 32 bit extended load. */
@@ -297,6 +315,15 @@ static void emit_loadu64(ASMState *as, Reg r, uint64_t u64)
297 MCode *p = as->mcp; 315 MCode *p = as->mcp;
298 *(int32_t *)(p-4) = (int32_t)u64; 316 *(int32_t *)(p-4) = (int32_t)u64;
299 as->mcp = emit_opm(XO_MOVmi, XM_REG, REX_64, r, p, -4); 317 as->mcp = emit_opm(XO_MOVmi, XM_REG, REX_64, r, p, -4);
318#if LJ_GC64
319 } else if (checki32(dispofs(as, u64))) {
320 emit_rmro(as, XO_LEA, r|REX_64, RID_DISPATCH, (int32_t)dispofs(as, u64));
321 } else if (checki32(mcpofs(as, u64)) && checki32(mctopofs(as, u64))) {
322 /* Since as->realign assumes the code size doesn't change, check
323 ** RIP-relative addressing reachability for both as->mcp and as->mctop.
324 */
325 emit_rmro(as, XO_LEA, r|REX_64, RID_RIP, (int32_t)mcpofs(as, u64));
326#endif
300 } else { /* Full-size 64 bit load. */ 327 } else { /* Full-size 64 bit load. */
301 MCode *p = as->mcp; 328 MCode *p = as->mcp;
302 *(uint64_t *)(p-8) = u64; 329 *(uint64_t *)(p-8) = u64;
@@ -308,13 +335,70 @@ static void emit_loadu64(ASMState *as, Reg r, uint64_t u64)
308} 335}
309#endif 336#endif
310 337
311/* movsd r, [&tv->n] / xorps r, r */ 338/* op r, [addr] */
312static void emit_loadn(ASMState *as, Reg r, cTValue *tv) 339static void emit_rma(ASMState *as, x86Op xo, Reg rr, const void *addr)
313{ 340{
314 if (tvispzero(tv)) /* Use xor only for +0. */ 341#if LJ_GC64
315 emit_rr(as, XO_XORPS, r, r); 342 if (checki32(dispofs(as, addr))) {
316 else 343 emit_rmro(as, xo, rr, RID_DISPATCH, (int32_t)dispofs(as, addr));
317 emit_rma(as, XMM_MOVRM(as), r, &tv->n); 344 } else if (checki32(mcpofs(as, addr)) && checki32(mctopofs(as, addr))) {
345 emit_rmro(as, xo, rr, RID_RIP, (int32_t)mcpofs(as, addr));
346 } else if (!checki32((intptr_t)addr) && (xo == XO_MOV || xo == XO_MOVSD)) {
347 emit_rmro(as, xo, rr, rr, 0);
348 emit_loadu64(as, rr, (uintptr_t)addr);
349 } else
350#endif
351 {
352 MCode *p = as->mcp;
353 *(int32_t *)(p-4) = ptr2addr(addr);
354#if LJ_64
355 p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP);
356 as->mcp = emit_opm(xo, XM_OFS0, rr, RID_ESP, p, -5);
357#else
358 as->mcp = emit_opm(xo, XM_OFS0, rr, RID_EBP, p, -4);
359#endif
360 }
361}
362
363/* Load 64 bit IR constant into register. */
364static void emit_loadk64(ASMState *as, Reg r, IRIns *ir)
365{
366 Reg r64;
367 x86Op xo;
368 const uint64_t *k = &ir_k64(ir)->u64;
369 if (rset_test(RSET_FPR, r)) {
370 r64 = r;
371 xo = XO_MOVSD;
372 } else {
373 r64 = r | REX_64;
374 xo = XO_MOV;
375 }
376 if (*k == 0) {
377 emit_rr(as, rset_test(RSET_FPR, r) ? XO_XORPS : XO_ARITH(XOg_XOR), r, r);
378#if LJ_GC64
379 } else if (checki32((intptr_t)k) || checki32(dispofs(as, k)) ||
380 (checki32(mcpofs(as, k)) && checki32(mctopofs(as, k)))) {
381 emit_rma(as, xo, r64, k);
382 } else {
383 if (ir->i) {
384 lua_assert(*k == *(uint64_t*)(as->mctop - ir->i));
385 } else if (as->curins <= as->stopins && rset_test(RSET_GPR, r)) {
386 emit_loadu64(as, r, *k);
387 return;
388 } else {
389 /* If all else fails, add the FP constant at the MCode area bottom. */
390 while ((uintptr_t)as->mcbot & 7) *as->mcbot++ = XI_INT3;
391 *(uint64_t *)as->mcbot = *k;
392 ir->i = (int32_t)(as->mctop - as->mcbot);
393 as->mcbot += 8;
394 as->mclim = as->mcbot + MCLIM_REDZONE;
395 }
396 emit_rmro(as, xo, r64, RID_RIP, (int32_t)mcpofs(as, as->mctop - ir->i));
397#else
398 } else {
399 emit_rma(as, xo, r64, k);
400#endif
401 }
318} 402}
319 403
320/* -- Emit control-flow instructions -------------------------------------- */ 404/* -- Emit control-flow instructions -------------------------------------- */
@@ -416,8 +500,10 @@ static void emit_call_(ASMState *as, MCode *target)
416/* Use 64 bit operations to handle 64 bit IR types. */ 500/* Use 64 bit operations to handle 64 bit IR types. */
417#if LJ_64 501#if LJ_64
418#define REX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? REX_64 : 0)) 502#define REX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? REX_64 : 0))
503#define VEX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? VEX_64 : 0))
419#else 504#else
420#define REX_64IR(ir, r) (r) 505#define REX_64IR(ir, r) (r)
506#define VEX_64IR(ir, r) (r)
421#endif 507#endif
422 508
423/* Generic move between two regs. */ 509/* Generic move between two regs. */
@@ -427,25 +513,25 @@ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src)
427 if (dst < RID_MAX_GPR) 513 if (dst < RID_MAX_GPR)
428 emit_rr(as, XO_MOV, REX_64IR(ir, dst), src); 514 emit_rr(as, XO_MOV, REX_64IR(ir, dst), src);
429 else 515 else
430 emit_rr(as, XMM_MOVRR(as), dst, src); 516 emit_rr(as, XO_MOVAPS, dst, src);
431} 517}
432 518
433/* Generic load of register from stack slot. */ 519/* Generic load of register with base and (small) offset address. */
434static void emit_spload(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 520static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
435{ 521{
436 if (r < RID_MAX_GPR) 522 if (r < RID_MAX_GPR)
437 emit_rmro(as, XO_MOV, REX_64IR(ir, r), RID_ESP, ofs); 523 emit_rmro(as, XO_MOV, REX_64IR(ir, r), base, ofs);
438 else 524 else
439 emit_rmro(as, irt_isnum(ir->t) ? XMM_MOVRM(as) : XO_MOVSS, r, RID_ESP, ofs); 525 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, r, base, ofs);
440} 526}
441 527
442/* Generic store of register to stack slot. */ 528/* Generic store of register with base and (small) offset address. */
443static void emit_spstore(ASMState *as, IRIns *ir, Reg r, int32_t ofs) 529static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs)
444{ 530{
445 if (r < RID_MAX_GPR) 531 if (r < RID_MAX_GPR)
446 emit_rmro(as, XO_MOVto, REX_64IR(ir, r), RID_ESP, ofs); 532 emit_rmro(as, XO_MOVto, REX_64IR(ir, r), base, ofs);
447 else 533 else
448 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto, r, RID_ESP, ofs); 534 emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto, r, base, ofs);
449} 535}
450 536
451/* Add offset to pointer. */ 537/* Add offset to pointer. */
@@ -453,9 +539,9 @@ static void emit_addptr(ASMState *as, Reg r, int32_t ofs)
453{ 539{
454 if (ofs) { 540 if (ofs) {
455 if ((as->flags & JIT_F_LEA_AGU)) 541 if ((as->flags & JIT_F_LEA_AGU))
456 emit_rmro(as, XO_LEA, r, r, ofs); 542 emit_rmro(as, XO_LEA, r|REX_GC64, r, ofs);
457 else 543 else
458 emit_gri(as, XG_ARITHi(XOg_ADD), r, ofs); 544 emit_gri(as, XG_ARITHi(XOg_ADD), r|REX_GC64, ofs);
459 } 545 }
460} 546}
461 547
diff --git a/src/lj_err.c b/src/lj_err.c
index 54f42c37..049294ea 100644
--- a/src/lj_err.c
+++ b/src/lj_err.c
@@ -16,6 +16,7 @@
16#include "lj_ff.h" 16#include "lj_ff.h"
17#include "lj_trace.h" 17#include "lj_trace.h"
18#include "lj_vm.h" 18#include "lj_vm.h"
19#include "lj_strfmt.h"
19 20
20/* 21/*
21** LuaJIT can either use internal or external frame unwinding: 22** LuaJIT can either use internal or external frame unwinding:
@@ -45,7 +46,8 @@
45** the wrapper function feature. Lua errors thrown through C++ frames 46** the wrapper function feature. Lua errors thrown through C++ frames
46** cannot be caught by C++ code and C++ destructors are not run. 47** cannot be caught by C++ code and C++ destructors are not run.
47** 48**
48** EXT is the default on x64 systems, INT is the default on all other systems. 49** EXT is the default on x64 systems and on Windows, INT is the default on all
50** other systems.
49** 51**
50** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack 52** EXT can be manually enabled on POSIX systems using GCC and DWARF2 stack
51** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled 53** unwinding with -DLUAJIT_UNWIND_EXTERNAL. *All* C code must be compiled
@@ -54,7 +56,6 @@
54** and all C libraries that have callbacks which may be used to call back 56** and all C libraries that have callbacks which may be used to call back
55** into Lua. C++ code must *not* be compiled with -fno-exceptions. 57** into Lua. C++ code must *not* be compiled with -fno-exceptions.
56** 58**
57** EXT cannot be enabled on WIN32 since system exceptions use code-driven SEH.
58** EXT is mandatory on WIN64 since the calling convention has an abundance 59** EXT is mandatory on WIN64 since the calling convention has an abundance
59** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15). 60** of callee-saved registers (rbx, rbp, rsi, rdi, r12-r15, xmm6-xmm15).
60** The POSIX/x64 interpreter only saves r12/r13 for INT (e.g. PS4). 61** The POSIX/x64 interpreter only saves r12/r13 for INT (e.g. PS4).
@@ -62,7 +63,7 @@
62 63
63#if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL)) && !LJ_NO_UNWIND 64#if defined(__GNUC__) && (LJ_TARGET_X64 || defined(LUAJIT_UNWIND_EXTERNAL)) && !LJ_NO_UNWIND
64#define LJ_UNWIND_EXT 1 65#define LJ_UNWIND_EXT 1
65#elif LJ_TARGET_X64 && LJ_TARGET_WINDOWS 66#elif LJ_TARGET_WINDOWS
66#define LJ_UNWIND_EXT 1 67#define LJ_UNWIND_EXT 1
67#endif 68#endif
68 69
@@ -98,14 +99,14 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
98 TValue *top = restorestack(L, -nres); 99 TValue *top = restorestack(L, -nres);
99 if (frame < top) { /* Frame reached? */ 100 if (frame < top) { /* Frame reached? */
100 if (errcode) { 101 if (errcode) {
101 L->cframe = cframe_prev(cf);
102 L->base = frame+1; 102 L->base = frame+1;
103 L->cframe = cframe_prev(cf);
103 unwindstack(L, top); 104 unwindstack(L, top);
104 } 105 }
105 return cf; 106 return cf;
106 } 107 }
107 } 108 }
108 if (frame <= tvref(L->stack)) 109 if (frame <= tvref(L->stack)+LJ_FR2)
109 break; 110 break;
110 switch (frame_typep(frame)) { 111 switch (frame_typep(frame)) {
111 case FRAME_LUA: /* Lua frame. */ 112 case FRAME_LUA: /* Lua frame. */
@@ -113,14 +114,12 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
113 frame = frame_prevl(frame); 114 frame = frame_prevl(frame);
114 break; 115 break;
115 case FRAME_C: /* C frame. */ 116 case FRAME_C: /* C frame. */
116#if LJ_HASFFI
117 unwind_c: 117 unwind_c:
118#endif
119#if LJ_UNWIND_EXT 118#if LJ_UNWIND_EXT
120 if (errcode) { 119 if (errcode) {
121 L->cframe = cframe_prev(cf);
122 L->base = frame_prevd(frame) + 1; 120 L->base = frame_prevd(frame) + 1;
123 unwindstack(L, frame); 121 L->cframe = cframe_prev(cf);
122 unwindstack(L, frame - LJ_FR2);
124 } else if (cf != stopcf) { 123 } else if (cf != stopcf) {
125 cf = cframe_prev(cf); 124 cf = cframe_prev(cf);
126 frame = frame_prevd(frame); 125 frame = frame_prevd(frame);
@@ -143,16 +142,14 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
143 return cf; 142 return cf;
144 } 143 }
145 if (errcode) { 144 if (errcode) {
146 L->cframe = cframe_prev(cf);
147 L->base = frame_prevd(frame) + 1; 145 L->base = frame_prevd(frame) + 1;
148 unwindstack(L, frame); 146 L->cframe = cframe_prev(cf);
147 unwindstack(L, frame - LJ_FR2);
149 } 148 }
150 return cf; 149 return cf;
151 case FRAME_CONT: /* Continuation frame. */ 150 case FRAME_CONT: /* Continuation frame. */
152#if LJ_HASFFI 151 if (frame_iscont_fficb(frame))
153 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
154 goto unwind_c; 152 goto unwind_c;
155#endif
156 case FRAME_VARG: /* Vararg frame. */ 153 case FRAME_VARG: /* Vararg frame. */
157 frame = frame_prevd(frame); 154 frame = frame_prevd(frame);
158 break; 155 break;
@@ -165,8 +162,8 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
165 } 162 }
166 if (frame_typep(frame) == FRAME_PCALL) 163 if (frame_typep(frame) == FRAME_PCALL)
167 hook_leave(G(L)); 164 hook_leave(G(L));
168 L->cframe = cf;
169 L->base = frame_prevd(frame) + 1; 165 L->base = frame_prevd(frame) + 1;
166 L->cframe = cf;
170 unwindstack(L, L->base); 167 unwindstack(L, L->base);
171 } 168 }
172 return (void *)((intptr_t)cf | CFRAME_UNWIND_FF); 169 return (void *)((intptr_t)cf | CFRAME_UNWIND_FF);
@@ -174,8 +171,8 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
174 } 171 }
175 /* No C frame. */ 172 /* No C frame. */
176 if (errcode) { 173 if (errcode) {
174 L->base = tvref(L->stack)+1+LJ_FR2;
177 L->cframe = NULL; 175 L->cframe = NULL;
178 L->base = tvref(L->stack)+1;
179 unwindstack(L, L->base); 176 unwindstack(L, L->base);
180 if (G(L)->panic) 177 if (G(L)->panic)
181 G(L)->panic(L); 178 G(L)->panic(L);
@@ -193,13 +190,6 @@ static void *err_unwind(lua_State *L, void *stopcf, int errcode)
193** since various OS, distros and compilers mess up the header installation. 190** since various OS, distros and compilers mess up the header installation.
194*/ 191*/
195 192
196typedef struct _Unwind_Exception
197{
198 uint64_t exclass;
199 void (*excleanup)(int, struct _Unwind_Exception *);
200 uintptr_t p1, p2;
201} __attribute__((__aligned__)) _Unwind_Exception;
202
203typedef struct _Unwind_Context _Unwind_Context; 193typedef struct _Unwind_Context _Unwind_Context;
204 194
205#define _URC_OK 0 195#define _URC_OK 0
@@ -209,8 +199,20 @@ typedef struct _Unwind_Context _Unwind_Context;
209#define _URC_CONTINUE_UNWIND 8 199#define _URC_CONTINUE_UNWIND 8
210#define _URC_FAILURE 9 200#define _URC_FAILURE 9
211 201
202#define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */
203#define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c))
204#define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff)
205#define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff))
206
212#if !LJ_TARGET_ARM 207#if !LJ_TARGET_ARM
213 208
209typedef struct _Unwind_Exception
210{
211 uint64_t exclass;
212 void (*excleanup)(int, struct _Unwind_Exception *);
213 uintptr_t p1, p2;
214} __attribute__((__aligned__)) _Unwind_Exception;
215
214extern uintptr_t _Unwind_GetCFA(_Unwind_Context *); 216extern uintptr_t _Unwind_GetCFA(_Unwind_Context *);
215extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t); 217extern void _Unwind_SetGR(_Unwind_Context *, int, uintptr_t);
216extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t); 218extern void _Unwind_SetIP(_Unwind_Context *, uintptr_t);
@@ -222,11 +224,6 @@ extern int _Unwind_RaiseException(_Unwind_Exception *);
222#define _UA_HANDLER_FRAME 4 224#define _UA_HANDLER_FRAME 4
223#define _UA_FORCE_UNWIND 8 225#define _UA_FORCE_UNWIND 8
224 226
225#define LJ_UEXCLASS 0x4c55414a49543200ULL /* LUAJIT2\0 */
226#define LJ_UEXCLASS_MAKE(c) (LJ_UEXCLASS | (uint64_t)(c))
227#define LJ_UEXCLASS_CHECK(cl) (((cl) ^ LJ_UEXCLASS) <= 0xff)
228#define LJ_UEXCLASS_ERRCODE(cl) ((int)((cl) & 0xff))
229
230/* DWARF2 personality handler referenced from interpreter .eh_frame. */ 227/* DWARF2 personality handler referenced from interpreter .eh_frame. */
231LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions, 228LJ_FUNCA int lj_err_unwind_dwarf(int version, int actions,
232 uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx) 229 uint64_t uexclass, _Unwind_Exception *uex, _Unwind_Context *ctx)
@@ -305,10 +302,22 @@ static void err_raise_ext(int errcode)
305} 302}
306#endif 303#endif
307 304
308#else 305#else /* LJ_TARGET_ARM */
309 306
310extern void _Unwind_DeleteException(void *); 307#define _US_VIRTUAL_UNWIND_FRAME 0
311extern int __gnu_unwind_frame (void *, _Unwind_Context *); 308#define _US_UNWIND_FRAME_STARTING 1
309#define _US_ACTION_MASK 3
310#define _US_FORCE_UNWIND 8
311
312typedef struct _Unwind_Control_Block _Unwind_Control_Block;
313
314struct _Unwind_Control_Block {
315 uint64_t exclass;
316 uint32_t misc[20];
317};
318
319extern int _Unwind_RaiseException(_Unwind_Control_Block *);
320extern int __gnu_unwind_frame(_Unwind_Control_Block *, _Unwind_Context *);
312extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *); 321extern int _Unwind_VRS_Set(_Unwind_Context *, int, uint32_t, int, void *);
313extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *); 322extern int _Unwind_VRS_Get(_Unwind_Context *, int, uint32_t, int, void *);
314 323
@@ -324,35 +333,58 @@ static inline void _Unwind_SetGR(_Unwind_Context *ctx, int r, uint32_t v)
324 _Unwind_VRS_Set(ctx, 0, r, 0, &v); 333 _Unwind_VRS_Set(ctx, 0, r, 0, &v);
325} 334}
326 335
327#define _US_VIRTUAL_UNWIND_FRAME 0 336extern void lj_vm_unwind_ext(void);
328#define _US_UNWIND_FRAME_STARTING 1
329#define _US_ACTION_MASK 3
330#define _US_FORCE_UNWIND 8
331 337
332/* ARM unwinder personality handler referenced from interpreter .ARM.extab. */ 338/* ARM unwinder personality handler referenced from interpreter .ARM.extab. */
333LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx) 339LJ_FUNCA int lj_err_unwind_arm(int state, _Unwind_Control_Block *ucb,
340 _Unwind_Context *ctx)
334{ 341{
335 void *cf = (void *)_Unwind_GetGR(ctx, 13); 342 void *cf = (void *)_Unwind_GetGR(ctx, 13);
336 lua_State *L = cframe_L(cf); 343 lua_State *L = cframe_L(cf);
337 if ((state & _US_ACTION_MASK) == _US_VIRTUAL_UNWIND_FRAME) { 344 int errcode;
338 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP)); 345
346 switch ((state & _US_ACTION_MASK)) {
347 case _US_VIRTUAL_UNWIND_FRAME:
348 if ((state & _US_FORCE_UNWIND)) break;
339 return _URC_HANDLER_FOUND; 349 return _URC_HANDLER_FOUND;
340 } 350 case _US_UNWIND_FRAME_STARTING:
341 if ((state&(_US_ACTION_MASK|_US_FORCE_UNWIND)) == _US_UNWIND_FRAME_STARTING) { 351 if (LJ_UEXCLASS_CHECK(ucb->exclass)) {
342 _Unwind_DeleteException(ucb); 352 errcode = LJ_UEXCLASS_ERRCODE(ucb->exclass);
343 _Unwind_SetGR(ctx, 15, (uint32_t)(void *)lj_err_throw); 353 } else {
344 _Unwind_SetGR(ctx, 0, (uint32_t)L); 354 errcode = LUA_ERRRUN;
345 _Unwind_SetGR(ctx, 1, (uint32_t)LUA_ERRRUN); 355 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
356 }
357 cf = err_unwind(L, cf, errcode);
358 if ((state & _US_FORCE_UNWIND) || cf == NULL) break;
359 _Unwind_SetGR(ctx, 15, (uint32_t)lj_vm_unwind_ext);
360 _Unwind_SetGR(ctx, 0, (uint32_t)ucb);
361 _Unwind_SetGR(ctx, 1, (uint32_t)errcode);
362 _Unwind_SetGR(ctx, 2, cframe_unwind_ff(cf) ?
363 (uint32_t)lj_vm_unwind_ff_eh :
364 (uint32_t)lj_vm_unwind_c_eh);
346 return _URC_INSTALL_CONTEXT; 365 return _URC_INSTALL_CONTEXT;
366 default:
367 return _URC_FAILURE;
347 } 368 }
348 if (__gnu_unwind_frame(ucb, ctx) != _URC_OK) 369 if (__gnu_unwind_frame(ucb, ctx) != _URC_OK)
349 return _URC_FAILURE; 370 return _URC_FAILURE;
350 return _URC_CONTINUE_UNWIND; 371 return _URC_CONTINUE_UNWIND;
351} 372}
352 373
374#if LJ_UNWIND_EXT
375static __thread _Unwind_Control_Block static_uex;
376
377static void err_raise_ext(int errcode)
378{
379 memset(&static_uex, 0, sizeof(static_uex));
380 static_uex.exclass = LJ_UEXCLASS_MAKE(errcode);
381 _Unwind_RaiseException(&static_uex);
382}
353#endif 383#endif
354 384
355#elif LJ_TARGET_X64 && LJ_ABI_WIN 385#endif /* LJ_TARGET_ARM */
386
387#elif LJ_ABI_WIN
356 388
357/* 389/*
358** Someone in Redmond owes me several days of my life. A lot of this is 390** Someone in Redmond owes me several days of my life. A lot of this is
@@ -370,6 +402,7 @@ LJ_FUNCA int lj_err_unwind_arm(int state, void *ucb, _Unwind_Context *ctx)
370#define WIN32_LEAN_AND_MEAN 402#define WIN32_LEAN_AND_MEAN
371#include <windows.h> 403#include <windows.h>
372 404
405#if LJ_TARGET_X64
373/* Taken from: http://www.nynaeve.net/?p=99 */ 406/* Taken from: http://www.nynaeve.net/?p=99 */
374typedef struct UndocumentedDispatcherContext { 407typedef struct UndocumentedDispatcherContext {
375 ULONG64 ControlPc; 408 ULONG64 ControlPc;
@@ -384,11 +417,14 @@ typedef struct UndocumentedDispatcherContext {
384 ULONG ScopeIndex; 417 ULONG ScopeIndex;
385 ULONG Fill0; 418 ULONG Fill0;
386} UndocumentedDispatcherContext; 419} UndocumentedDispatcherContext;
420#else
421typedef void *UndocumentedDispatcherContext;
422#endif
387 423
388/* Another wild guess. */ 424/* Another wild guess. */
389extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow); 425extern void __DestructExceptionObject(EXCEPTION_RECORD *rec, int nothrow);
390 426
391#ifdef MINGW_SDK_INIT 427#if LJ_TARGET_X64 && defined(MINGW_SDK_INIT)
392/* Workaround for broken MinGW64 declaration. */ 428/* Workaround for broken MinGW64 declaration. */
393VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx"); 429VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
394#define RtlUnwindEx RtlUnwindEx_FIXED 430#define RtlUnwindEx RtlUnwindEx_FIXED
@@ -402,10 +438,15 @@ VOID RtlUnwindEx_FIXED(PVOID,PVOID,PVOID,PVOID,PVOID,PVOID) asm("RtlUnwindEx");
402#define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff) 438#define LJ_EXCODE_CHECK(cl) (((cl) ^ LJ_EXCODE) <= 0xff)
403#define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff)) 439#define LJ_EXCODE_ERRCODE(cl) ((int)((cl) & 0xff))
404 440
405/* Win64 exception handler for interpreter frame. */ 441/* Windows exception handler for interpreter frame. */
406LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec, 442LJ_FUNCA int lj_err_unwind_win(EXCEPTION_RECORD *rec,
407 void *cf, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch) 443 void *f, CONTEXT *ctx, UndocumentedDispatcherContext *dispatch)
408{ 444{
445#if LJ_TARGET_X64
446 void *cf = f;
447#else
448 void *cf = (char *)f - CFRAME_OFS_SEH;
449#endif
409 lua_State *L = cframe_L(cf); 450 lua_State *L = cframe_L(cf);
410 int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ? 451 int errcode = LJ_EXCODE_CHECK(rec->ExceptionCode) ?
411 LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN; 452 LJ_EXCODE_ERRCODE(rec->ExceptionCode) : LUA_ERRRUN;
@@ -423,8 +464,9 @@ LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
423 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP)); 464 setstrV(L, L->top++, lj_err_str(L, LJ_ERR_ERRCPP));
424 } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) { 465 } else if (!LJ_EXCODE_CHECK(rec->ExceptionCode)) {
425 /* Don't catch access violations etc. */ 466 /* Don't catch access violations etc. */
426 return ExceptionContinueSearch; 467 return 1; /* ExceptionContinueSearch */
427 } 468 }
469#if LJ_TARGET_X64
428 /* Unwind the stack and call all handlers for all lower C frames 470 /* Unwind the stack and call all handlers for all lower C frames
429 ** (including ourselves) again with EH_UNWINDING set. Then set 471 ** (including ourselves) again with EH_UNWINDING set. Then set
430 ** rsp = cf, rax = errcode and jump to the specified target. 472 ** rsp = cf, rax = errcode and jump to the specified target.
@@ -434,9 +476,21 @@ LJ_FUNCA EXCEPTION_DISPOSITION lj_err_unwind_win64(EXCEPTION_RECORD *rec,
434 lj_vm_unwind_c_eh), 476 lj_vm_unwind_c_eh),
435 rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable); 477 rec, (void *)(uintptr_t)errcode, ctx, dispatch->HistoryTable);
436 /* RtlUnwindEx should never return. */ 478 /* RtlUnwindEx should never return. */
479#else
480 UNUSED(ctx);
481 UNUSED(dispatch);
482 /* Call all handlers for all lower C frames (including ourselves) again
483 ** with EH_UNWINDING set. Then call the specified function, passing cf
484 ** and errcode.
485 */
486 lj_vm_rtlunwind(cf, (void *)rec,
487 (cframe_unwind_ff(cf2) && errcode != LUA_YIELD) ?
488 (void *)lj_vm_unwind_ff : (void *)lj_vm_unwind_c, errcode);
489 /* lj_vm_rtlunwind does not return. */
490#endif
437 } 491 }
438 } 492 }
439 return ExceptionContinueSearch; 493 return 1; /* ExceptionContinueSearch */
440} 494}
441 495
442/* Raise Windows exception. */ 496/* Raise Windows exception. */
@@ -454,7 +508,7 @@ LJ_NOINLINE void LJ_FASTCALL lj_err_throw(lua_State *L, int errcode)
454{ 508{
455 global_State *g = G(L); 509 global_State *g = G(L);
456 lj_trace_abort(g); 510 lj_trace_abort(g);
457 setgcrefnull(g->jit_L); 511 setmref(g->jit_base, NULL);
458 L->status = 0; 512 L->status = 0;
459#if LJ_UNWIND_EXT 513#if LJ_UNWIND_EXT
460 err_raise_ext(errcode); 514 err_raise_ext(errcode);
@@ -499,7 +553,7 @@ LJ_NOINLINE void lj_err_mem(lua_State *L)
499/* Find error function for runtime errors. Requires an extra stack traversal. */ 553/* Find error function for runtime errors. Requires an extra stack traversal. */
500static ptrdiff_t finderrfunc(lua_State *L) 554static ptrdiff_t finderrfunc(lua_State *L)
501{ 555{
502 cTValue *frame = L->base-1, *bot = tvref(L->stack); 556 cTValue *frame = L->base-1, *bot = tvref(L->stack)+LJ_FR2;
503 void *cf = L->cframe; 557 void *cf = L->cframe;
504 while (frame > bot && cf) { 558 while (frame > bot && cf) {
505 while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */ 559 while (cframe_nres(cframe_raw(cf)) < 0) { /* cframe without frame? */
@@ -523,10 +577,8 @@ static ptrdiff_t finderrfunc(lua_State *L)
523 frame = frame_prevd(frame); 577 frame = frame_prevd(frame);
524 break; 578 break;
525 case FRAME_CONT: 579 case FRAME_CONT:
526#if LJ_HASFFI 580 if (frame_iscont_fficb(frame))
527 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK)
528 cf = cframe_prev(cf); 581 cf = cframe_prev(cf);
529#endif
530 frame = frame_prevd(frame); 582 frame = frame_prevd(frame);
531 break; 583 break;
532 case FRAME_CP: 584 case FRAME_CP:
@@ -537,8 +589,8 @@ static ptrdiff_t finderrfunc(lua_State *L)
537 break; 589 break;
538 case FRAME_PCALL: 590 case FRAME_PCALL:
539 case FRAME_PCALLH: 591 case FRAME_PCALLH:
540 if (frame_ftsz(frame) >= (ptrdiff_t)(2*sizeof(TValue))) /* xpcall? */ 592 if (frame_func(frame_prevd(frame))->c.ffid == FF_xpcall)
541 return savestack(L, frame-1); /* Point to xpcall's errorfunc. */ 593 return savestack(L, frame_prevd(frame)+1); /* xpcall's errorfunc. */
542 return 0; 594 return 0;
543 default: 595 default:
544 lua_assert(0); 596 lua_assert(0);
@@ -561,8 +613,9 @@ LJ_NOINLINE void lj_err_run(lua_State *L)
561 lj_err_throw(L, LUA_ERRERR); 613 lj_err_throw(L, LUA_ERRERR);
562 } 614 }
563 L->status = LUA_ERRERR; 615 L->status = LUA_ERRERR;
564 copyTV(L, top, top-1); 616 copyTV(L, top+LJ_FR2, top-1);
565 copyTV(L, top-1, errfunc); 617 copyTV(L, top-1, errfunc);
618 if (LJ_FR2) setnilV(top++);
566 L->top = top+1; 619 L->top = top+1;
567 lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */ 620 lj_vm_call(L, top, 1+1); /* Stack: |errfunc|msg| -> |msg| */
568 } 621 }
@@ -576,7 +629,7 @@ LJ_NORET LJ_NOINLINE static void err_msgv(lua_State *L, ErrMsg em, ...)
576 va_list argp; 629 va_list argp;
577 va_start(argp, em); 630 va_start(argp, em);
578 if (curr_funcisL(L)) L->top = curr_topL(L); 631 if (curr_funcisL(L)) L->top = curr_topL(L);
579 msg = lj_str_pushvf(L, err2msg(em), argp); 632 msg = lj_strfmt_pushvf(L, err2msg(em), argp);
580 va_end(argp); 633 va_end(argp);
581 lj_debug_addloc(L, msg, L->base-1, NULL); 634 lj_debug_addloc(L, msg, L->base-1, NULL);
582 lj_err_run(L); 635 lj_err_run(L);
@@ -594,11 +647,11 @@ LJ_NOINLINE void lj_err_lex(lua_State *L, GCstr *src, const char *tok,
594{ 647{
595 char buff[LUA_IDSIZE]; 648 char buff[LUA_IDSIZE];
596 const char *msg; 649 const char *msg;
597 lj_debug_shortname(buff, src); 650 lj_debug_shortname(buff, src, line);
598 msg = lj_str_pushvf(L, err2msg(em), argp); 651 msg = lj_strfmt_pushvf(L, err2msg(em), argp);
599 msg = lj_str_pushf(L, "%s:%d: %s", buff, line, msg); 652 msg = lj_strfmt_pushf(L, "%s:%d: %s", buff, line, msg);
600 if (tok) 653 if (tok)
601 lj_str_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok); 654 lj_strfmt_pushf(L, err2msg(LJ_ERR_XNEAR), msg, tok);
602 lj_err_throw(L, LUA_ERRSYNTAX); 655 lj_err_throw(L, LUA_ERRSYNTAX);
603} 656}
604 657
@@ -637,8 +690,9 @@ LJ_NOINLINE void lj_err_optype_call(lua_State *L, TValue *o)
637 const BCIns *pc = cframe_Lpc(L); 690 const BCIns *pc = cframe_Lpc(L);
638 if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) { 691 if (((ptrdiff_t)pc & FRAME_TYPE) != FRAME_LUA) {
639 const char *tname = lj_typename(o); 692 const char *tname = lj_typename(o);
693 if (LJ_FR2) o++;
640 setframe_pc(o, pc); 694 setframe_pc(o, pc);
641 setframe_gc(o, obj2gco(L)); 695 setframe_gc(o, obj2gco(L), LJ_TTHREAD);
642 L->top = L->base = o+1; 696 L->top = L->base = o+1;
643 err_msgv(L, LJ_ERR_BADCALL, tname); 697 err_msgv(L, LJ_ERR_BADCALL, tname);
644 } 698 }
@@ -653,13 +707,10 @@ LJ_NOINLINE void lj_err_callermsg(lua_State *L, const char *msg)
653 if (frame_islua(frame)) { 707 if (frame_islua(frame)) {
654 pframe = frame_prevl(frame); 708 pframe = frame_prevl(frame);
655 } else if (frame_iscont(frame)) { 709 } else if (frame_iscont(frame)) {
656#if LJ_HASFFI 710 if (frame_iscont_fficb(frame)) {
657 if ((frame-1)->u32.lo == LJ_CONT_FFI_CALLBACK) {
658 pframe = frame; 711 pframe = frame;
659 frame = NULL; 712 frame = NULL;
660 } else 713 } else {
661#endif
662 {
663 pframe = frame_prevd(frame); 714 pframe = frame_prevd(frame);
664#if LJ_HASFFI 715#if LJ_HASFFI
665 /* Remove frame for FFI metamethods. */ 716 /* Remove frame for FFI metamethods. */
@@ -682,7 +733,7 @@ LJ_NOINLINE void lj_err_callerv(lua_State *L, ErrMsg em, ...)
682 const char *msg; 733 const char *msg;
683 va_list argp; 734 va_list argp;
684 va_start(argp, em); 735 va_start(argp, em);
685 msg = lj_str_pushvf(L, err2msg(em), argp); 736 msg = lj_strfmt_pushvf(L, err2msg(em), argp);
686 va_end(argp); 737 va_end(argp);
687 lj_err_callermsg(L, msg); 738 lj_err_callermsg(L, msg);
688} 739}
@@ -702,9 +753,9 @@ LJ_NORET LJ_NOINLINE static void err_argmsg(lua_State *L, int narg,
702 if (narg < 0 && narg > LUA_REGISTRYINDEX) 753 if (narg < 0 && narg > LUA_REGISTRYINDEX)
703 narg = (int)(L->top - L->base) + narg + 1; 754 narg = (int)(L->top - L->base) + narg + 1;
704 if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */ 755 if (ftype && ftype[3] == 'h' && --narg == 0) /* Check for "method". */
705 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg); 756 msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADSELF), fname, msg);
706 else 757 else
707 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg); 758 msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADARG), narg, fname, msg);
708 lj_err_callermsg(L, msg); 759 lj_err_callermsg(L, msg);
709} 760}
710 761
@@ -714,7 +765,7 @@ LJ_NOINLINE void lj_err_argv(lua_State *L, int narg, ErrMsg em, ...)
714 const char *msg; 765 const char *msg;
715 va_list argp; 766 va_list argp;
716 va_start(argp, em); 767 va_start(argp, em);
717 msg = lj_str_pushvf(L, err2msg(em), argp); 768 msg = lj_strfmt_pushvf(L, err2msg(em), argp);
718 va_end(argp); 769 va_end(argp);
719 err_argmsg(L, narg, msg); 770 err_argmsg(L, narg, msg);
720} 771}
@@ -744,7 +795,7 @@ LJ_NOINLINE void lj_err_argtype(lua_State *L, int narg, const char *xname)
744 TValue *o = narg < 0 ? L->top + narg : L->base + narg-1; 795 TValue *o = narg < 0 ? L->top + narg : L->base + narg-1;
745 tname = o < L->top ? lj_typename(o) : lj_obj_typename[0]; 796 tname = o < L->top ? lj_typename(o) : lj_obj_typename[0];
746 } 797 }
747 msg = lj_str_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname); 798 msg = lj_strfmt_pushf(L, err2msg(LJ_ERR_BADTYPE), xname, tname);
748 err_argmsg(L, narg, msg); 799 err_argmsg(L, narg, msg);
749} 800}
750 801
@@ -794,7 +845,7 @@ LUALIB_API int luaL_error(lua_State *L, const char *fmt, ...)
794 const char *msg; 845 const char *msg;
795 va_list argp; 846 va_list argp;
796 va_start(argp, fmt); 847 va_start(argp, fmt);
797 msg = lj_str_pushvf(L, fmt, argp); 848 msg = lj_strfmt_pushvf(L, fmt, argp);
798 va_end(argp); 849 va_end(argp);
799 lj_err_callermsg(L, msg); 850 lj_err_callermsg(L, msg);
800 return 0; /* unreachable */ 851 return 0; /* unreachable */
diff --git a/src/lj_errmsg.h b/src/lj_errmsg.h
index ac552f40..060a9f89 100644
--- a/src/lj_errmsg.h
+++ b/src/lj_errmsg.h
@@ -96,9 +96,7 @@ ERRDEF(STRPATX, "pattern too complex")
96ERRDEF(STRCAPI, "invalid capture index") 96ERRDEF(STRCAPI, "invalid capture index")
97ERRDEF(STRCAPN, "too many captures") 97ERRDEF(STRCAPN, "too many captures")
98ERRDEF(STRCAPU, "unfinished capture") 98ERRDEF(STRCAPU, "unfinished capture")
99ERRDEF(STRFMTO, "invalid option " LUA_QL("%%%c") " to " LUA_QL("format")) 99ERRDEF(STRFMT, "invalid option " LUA_QS " to " LUA_QL("format"))
100ERRDEF(STRFMTR, "invalid format (repeated flags)")
101ERRDEF(STRFMTW, "invalid format (width or precision too long)")
102ERRDEF(STRGSRV, "invalid replacement value (a %s)") 100ERRDEF(STRGSRV, "invalid replacement value (a %s)")
103ERRDEF(BADMODN, "name conflict for module " LUA_QS) 101ERRDEF(BADMODN, "name conflict for module " LUA_QS)
104#if LJ_HASJIT 102#if LJ_HASJIT
@@ -118,7 +116,6 @@ ERRDEF(JITOPT, "unknown or malformed optimization flag " LUA_QS)
118/* Lexer/parser errors. */ 116/* Lexer/parser errors. */
119ERRDEF(XMODE, "attempt to load chunk with wrong mode") 117ERRDEF(XMODE, "attempt to load chunk with wrong mode")
120ERRDEF(XNEAR, "%s near " LUA_QS) 118ERRDEF(XNEAR, "%s near " LUA_QS)
121ERRDEF(XELEM, "lexical element too long")
122ERRDEF(XLINES, "chunk has too many lines") 119ERRDEF(XLINES, "chunk has too many lines")
123ERRDEF(XLEVELS, "chunk has too many syntax levels") 120ERRDEF(XLEVELS, "chunk has too many syntax levels")
124ERRDEF(XNUMBER, "malformed number") 121ERRDEF(XNUMBER, "malformed number")
diff --git a/src/lj_ffrecord.c b/src/lj_ffrecord.c
index da09dca5..dfdee2db 100644
--- a/src/lj_ffrecord.c
+++ b/src/lj_ffrecord.c
@@ -27,6 +27,7 @@
27#include "lj_dispatch.h" 27#include "lj_dispatch.h"
28#include "lj_vm.h" 28#include "lj_vm.h"
29#include "lj_strscan.h" 29#include "lj_strscan.h"
30#include "lj_strfmt.h"
30 31
31/* Some local macros to save typing. Undef'd at the end. */ 32/* Some local macros to save typing. Undef'd at the end. */
32#define IR(ref) (&J->cur.ir[(ref)]) 33#define IR(ref) (&J->cur.ir[(ref)])
@@ -79,10 +80,7 @@ static GCstr *argv2str(jit_State *J, TValue *o)
79 GCstr *s; 80 GCstr *s;
80 if (!tvisnumber(o)) 81 if (!tvisnumber(o))
81 lj_trace_err(J, LJ_TRERR_BADTYPE); 82 lj_trace_err(J, LJ_TRERR_BADTYPE);
82 if (tvisint(o)) 83 s = lj_strfmt_number(J->L, o);
83 s = lj_str_fromint(J->L, intV(o));
84 else
85 s = lj_str_fromnum(J->L, &o->n);
86 setstrV(J->L, o, s); 84 setstrV(J->L, o, s);
87 return s; 85 return s;
88 } 86 }
@@ -98,27 +96,90 @@ static ptrdiff_t results_wanted(jit_State *J)
98 return -1; 96 return -1;
99} 97}
100 98
101/* Throw error for unsupported variant of fast function. */ 99/* Trace stitching: add continuation below frame to start a new trace. */
102LJ_NORET static void recff_nyiu(jit_State *J) 100static void recff_stitch(jit_State *J)
103{ 101{
104 setfuncV(J->L, &J->errinfo, J->fn); 102 ASMFunction cont = lj_cont_stitch;
105 lj_trace_err_info(J, LJ_TRERR_NYIFFU); 103 lua_State *L = J->L;
104 TValue *base = L->base;
105 BCReg nslot = J->maxslot + 1 + LJ_FR2;
106 TValue *nframe = base + 1 + LJ_FR2;
107 const BCIns *pc = frame_pc(base-1);
108 TValue *pframe = frame_prevl(base-1);
109
110 /* Move func + args up in Lua stack and insert continuation. */
111 memmove(&base[1], &base[-1-LJ_FR2], sizeof(TValue)*nslot);
112 setframe_ftsz(nframe, ((char *)nframe - (char *)pframe) + FRAME_CONT);
113 setcont(base-LJ_FR2, cont);
114 setframe_pc(base, pc);
115 setnilV(base-1-LJ_FR2); /* Incorrect, but rec_check_slots() won't run anymore. */
116 L->base += 2 + LJ_FR2;
117 L->top += 2 + LJ_FR2;
118
119 /* Ditto for the IR. */
120 memmove(&J->base[1], &J->base[-1-LJ_FR2], sizeof(TRef)*nslot);
121#if LJ_FR2
122 J->base[2] = TREF_FRAME;
123 J->base[-1] = lj_ir_k64(J, IR_KNUM, u64ptr(contptr(cont)));
124 J->base[0] = lj_ir_k64(J, IR_KNUM, u64ptr(pc)) | TREF_CONT;
125#else
126 J->base[0] = lj_ir_kptr(J, contptr(cont)) | TREF_CONT;
127#endif
128 J->ktrace = tref_ref((J->base[-1-LJ_FR2] = lj_ir_ktrace(J)));
129 J->base += 2 + LJ_FR2;
130 J->baseslot += 2 + LJ_FR2;
131 J->framedepth++;
132
133 lj_record_stop(J, LJ_TRLINK_STITCH, 0);
134
135 /* Undo Lua stack changes. */
136 memmove(&base[-1-LJ_FR2], &base[1], sizeof(TValue)*nslot);
137 setframe_pc(base-1, pc);
138 L->base -= 2 + LJ_FR2;
139 L->top -= 2 + LJ_FR2;
106} 140}
107 141
108/* Fallback handler for all fast functions that are not recorded (yet). */ 142/* Fallback handler for fast functions that are not recorded (yet). */
109static void LJ_FASTCALL recff_nyi(jit_State *J, RecordFFData *rd) 143static void LJ_FASTCALL recff_nyi(jit_State *J, RecordFFData *rd)
110{ 144{
111 setfuncV(J->L, &J->errinfo, J->fn); 145 if (J->cur.nins < (IRRef)J->param[JIT_P_minstitch] + REF_BASE) {
112 lj_trace_err_info(J, LJ_TRERR_NYIFF); 146 lj_trace_err_info(J, LJ_TRERR_TRACEUV);
113 UNUSED(rd); 147 } else {
148 /* Can only stitch from Lua call. */
149 if (J->framedepth && frame_islua(J->L->base-1)) {
150 BCOp op = bc_op(*frame_pc(J->L->base-1));
151 /* Stitched trace cannot start with *M op with variable # of args. */
152 if (!(op == BC_CALLM || op == BC_CALLMT ||
153 op == BC_RETM || op == BC_TSETM)) {
154 switch (J->fn->c.ffid) {
155 case FF_error:
156 case FF_debug_sethook:
157 case FF_jit_flush:
158 break; /* Don't stitch across special builtins. */
159 default:
160 recff_stitch(J); /* Use trace stitching. */
161 rd->nres = -1;
162 return;
163 }
164 }
165 }
166 /* Otherwise stop trace and return to interpreter. */
167 lj_record_stop(J, LJ_TRLINK_RETURN, 0);
168 rd->nres = -1;
169 }
114} 170}
115 171
116/* C functions can have arbitrary side-effects and are not recorded (yet). */ 172/* Fallback handler for unsupported variants of fast functions. */
117static void LJ_FASTCALL recff_c(jit_State *J, RecordFFData *rd) 173#define recff_nyiu recff_nyi
174
175/* Must stop the trace for classic C functions with arbitrary side-effects. */
176#define recff_c recff_nyi
177
178/* Emit BUFHDR for the global temporary buffer. */
179static TRef recff_bufhdr(jit_State *J)
118{ 180{
119 setfuncV(J->L, &J->errinfo, J->fn); 181 return emitir(IRT(IR_BUFHDR, IRT_PGC),
120 lj_trace_err_info(J, LJ_TRERR_NYICF); 182 lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
121 UNUSED(rd);
122} 183}
123 184
124/* -- Base library fast functions ----------------------------------------- */ 185/* -- Base library fast functions ----------------------------------------- */
@@ -135,7 +196,7 @@ static void LJ_FASTCALL recff_type(jit_State *J, RecordFFData *rd)
135 uint32_t t; 196 uint32_t t;
136 if (tvisnumber(&rd->argv[0])) 197 if (tvisnumber(&rd->argv[0]))
137 t = ~LJ_TNUMX; 198 t = ~LJ_TNUMX;
138 else if (LJ_64 && tvislightud(&rd->argv[0])) 199 else if (LJ_64 && !LJ_GC64 && tvislightud(&rd->argv[0]))
139 t = ~LJ_TLIGHTUD; 200 t = ~LJ_TLIGHTUD;
140 else 201 else
141 t = ~itype(&rd->argv[0]); 202 t = ~itype(&rd->argv[0]);
@@ -167,7 +228,7 @@ static void LJ_FASTCALL recff_setmetatable(jit_State *J, RecordFFData *rd)
167 ix.tab = tr; 228 ix.tab = tr;
168 copyTV(J->L, &ix.tabv, &rd->argv[0]); 229 copyTV(J->L, &ix.tabv, &rd->argv[0]);
169 lj_record_mm_lookup(J, &ix, MM_metatable); /* Guard for no __metatable. */ 230 lj_record_mm_lookup(J, &ix, MM_metatable); /* Guard for no __metatable. */
170 fref = emitir(IRT(IR_FREF, IRT_P32), tr, IRFL_TAB_META); 231 fref = emitir(IRT(IR_FREF, IRT_PGC), tr, IRFL_TAB_META);
171 mtref = tref_isnil(mt) ? lj_ir_knull(J, IRT_TAB) : mt; 232 mtref = tref_isnil(mt) ? lj_ir_knull(J, IRT_TAB) : mt;
172 emitir(IRT(IR_FSTORE, IRT_TAB), fref, mtref); 233 emitir(IRT(IR_FSTORE, IRT_TAB), fref, mtref);
173 if (!tref_isnil(mt)) 234 if (!tref_isnil(mt))
@@ -233,7 +294,7 @@ int32_t lj_ffrecord_select_mode(jit_State *J, TRef tr, TValue *tv)
233 if (strV(tv)->len == 1) { 294 if (strV(tv)->len == 1) {
234 emitir(IRTG(IR_EQ, IRT_STR), tr, lj_ir_kstr(J, strV(tv))); 295 emitir(IRTG(IR_EQ, IRT_STR), tr, lj_ir_kstr(J, strV(tv)));
235 } else { 296 } else {
236 TRef trptr = emitir(IRT(IR_STRREF, IRT_P32), tr, lj_ir_kint(J, 0)); 297 TRef trptr = emitir(IRT(IR_STRREF, IRT_PGC), tr, lj_ir_kint(J, 0));
237 TRef trchar = emitir(IRT(IR_XLOAD, IRT_U8), trptr, IRXLOAD_READONLY); 298 TRef trchar = emitir(IRT(IR_XLOAD, IRT_U8), trptr, IRXLOAD_READONLY);
238 emitir(IRTG(IR_EQ, IRT_INT), trchar, lj_ir_kint(J, '#')); 299 emitir(IRTG(IR_EQ, IRT_INT), trchar, lj_ir_kint(J, '#'));
239 } 300 }
@@ -263,7 +324,8 @@ static void LJ_FASTCALL recff_select(jit_State *J, RecordFFData *rd)
263 J->base[i] = J->base[start+i]; 324 J->base[i] = J->base[start+i];
264 } /* else: Interpreter will throw. */ 325 } /* else: Interpreter will throw. */
265 } else { 326 } else {
266 recff_nyiu(J); 327 recff_nyiu(J, rd);
328 return;
267 } 329 }
268 } /* else: Interpreter will throw. */ 330 } /* else: Interpreter will throw. */
269} 331}
@@ -274,14 +336,18 @@ static void LJ_FASTCALL recff_tonumber(jit_State *J, RecordFFData *rd)
274 TRef base = J->base[1]; 336 TRef base = J->base[1];
275 if (tr && !tref_isnil(base)) { 337 if (tr && !tref_isnil(base)) {
276 base = lj_opt_narrow_toint(J, base); 338 base = lj_opt_narrow_toint(J, base);
277 if (!tref_isk(base) || IR(tref_ref(base))->i != 10) 339 if (!tref_isk(base) || IR(tref_ref(base))->i != 10) {
278 recff_nyiu(J); 340 recff_nyiu(J, rd);
341 return;
342 }
279 } 343 }
280 if (tref_isnumber_str(tr)) { 344 if (tref_isnumber_str(tr)) {
281 if (tref_isstr(tr)) { 345 if (tref_isstr(tr)) {
282 TValue tmp; 346 TValue tmp;
283 if (!lj_strscan_num(strV(&rd->argv[0]), &tmp)) 347 if (!lj_strscan_num(strV(&rd->argv[0]), &tmp)) {
284 recff_nyiu(J); /* Would need an inverted STRTO for this case. */ 348 recff_nyiu(J, rd); /* Would need an inverted STRTO for this case. */
349 return;
350 }
285 tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0); 351 tr = emitir(IRTG(IR_STRTO, IRT_NUM), tr, 0);
286 } 352 }
287#if LJ_HASFFI 353#if LJ_HASFFI
@@ -313,10 +379,10 @@ static int recff_metacall(jit_State *J, RecordFFData *rd, MMS mm)
313 int errcode; 379 int errcode;
314 TValue argv0; 380 TValue argv0;
315 /* Temporarily insert metamethod below object. */ 381 /* Temporarily insert metamethod below object. */
316 J->base[1] = J->base[0]; 382 J->base[1+LJ_FR2] = J->base[0];
317 J->base[0] = ix.mobj; 383 J->base[0] = ix.mobj;
318 copyTV(J->L, &argv0, &rd->argv[0]); 384 copyTV(J->L, &argv0, &rd->argv[0]);
319 copyTV(J->L, &rd->argv[1], &rd->argv[0]); 385 copyTV(J->L, &rd->argv[1+LJ_FR2], &rd->argv[0]);
320 copyTV(J->L, &rd->argv[0], &ix.mobjv); 386 copyTV(J->L, &rd->argv[0], &ix.mobjv);
321 /* Need to protect lj_record_tailcall because it may throw. */ 387 /* Need to protect lj_record_tailcall because it may throw. */
322 errcode = lj_vm_cpcall(J->L, NULL, J, recff_metacall_cp); 388 errcode = lj_vm_cpcall(J->L, NULL, J, recff_metacall_cp);
@@ -336,13 +402,15 @@ static void LJ_FASTCALL recff_tostring(jit_State *J, RecordFFData *rd)
336 if (tref_isstr(tr)) { 402 if (tref_isstr(tr)) {
337 /* Ignore __tostring in the string base metatable. */ 403 /* Ignore __tostring in the string base metatable. */
338 /* Pass on result in J->base[0]. */ 404 /* Pass on result in J->base[0]. */
339 } else if (!recff_metacall(J, rd, MM_tostring)) { 405 } else if (tr && !recff_metacall(J, rd, MM_tostring)) {
340 if (tref_isnumber(tr)) { 406 if (tref_isnumber(tr)) {
341 J->base[0] = emitir(IRT(IR_TOSTR, IRT_STR), tr, 0); 407 J->base[0] = emitir(IRT(IR_TOSTR, IRT_STR), tr,
408 tref_isnum(tr) ? IRTOSTR_NUM : IRTOSTR_INT);
342 } else if (tref_ispri(tr)) { 409 } else if (tref_ispri(tr)) {
343 J->base[0] = lj_ir_kstr(J, strV(&J->fn->c.upvalue[tref_type(tr)])); 410 J->base[0] = lj_ir_kstr(J, lj_strfmt_obj(J->L, &rd->argv[0]));
344 } else { 411 } else {
345 recff_nyiu(J); 412 recff_nyiu(J, rd);
413 return;
346 } 414 }
347 } 415 }
348} 416}
@@ -364,15 +432,15 @@ static void LJ_FASTCALL recff_ipairs_aux(jit_State *J, RecordFFData *rd)
364 } /* else: Interpreter will throw. */ 432 } /* else: Interpreter will throw. */
365} 433}
366 434
367static void LJ_FASTCALL recff_ipairs(jit_State *J, RecordFFData *rd) 435static void LJ_FASTCALL recff_xpairs(jit_State *J, RecordFFData *rd)
368{ 436{
369 TRef tr = J->base[0]; 437 TRef tr = J->base[0];
370 if (!((LJ_52 || (LJ_HASFFI && tref_iscdata(tr))) && 438 if (!((LJ_52 || (LJ_HASFFI && tref_iscdata(tr))) &&
371 recff_metacall(J, rd, MM_ipairs))) { 439 recff_metacall(J, rd, MM_pairs + rd->data))) {
372 if (tref_istab(tr)) { 440 if (tref_istab(tr)) {
373 J->base[0] = lj_ir_kfunc(J, funcV(&J->fn->c.upvalue[0])); 441 J->base[0] = lj_ir_kfunc(J, funcV(&J->fn->c.upvalue[0]));
374 J->base[1] = tr; 442 J->base[1] = tr;
375 J->base[2] = lj_ir_kint(J, 0); 443 J->base[2] = rd->data ? lj_ir_kint(J, 0) : TREF_NIL;
376 rd->nres = 3; 444 rd->nres = 3;
377 } /* else: Interpreter will throw. */ 445 } /* else: Interpreter will throw. */
378 } 446 }
@@ -381,6 +449,10 @@ static void LJ_FASTCALL recff_ipairs(jit_State *J, RecordFFData *rd)
381static void LJ_FASTCALL recff_pcall(jit_State *J, RecordFFData *rd) 449static void LJ_FASTCALL recff_pcall(jit_State *J, RecordFFData *rd)
382{ 450{
383 if (J->maxslot >= 1) { 451 if (J->maxslot >= 1) {
452#if LJ_FR2
453 /* Shift function arguments up. */
454 memmove(J->base + 1, J->base, sizeof(TRef) * J->maxslot);
455#endif
384 lj_record_call(J, 0, J->maxslot - 1); 456 lj_record_call(J, 0, J->maxslot - 1);
385 rd->nres = -1; /* Pending call. */ 457 rd->nres = -1; /* Pending call. */
386 } /* else: Interpreter will throw. */ 458 } /* else: Interpreter will throw. */
@@ -406,6 +478,10 @@ static void LJ_FASTCALL recff_xpcall(jit_State *J, RecordFFData *rd)
406 copyTV(J->L, &argv1, &rd->argv[1]); 478 copyTV(J->L, &argv1, &rd->argv[1]);
407 copyTV(J->L, &rd->argv[0], &argv1); 479 copyTV(J->L, &rd->argv[0], &argv1);
408 copyTV(J->L, &rd->argv[1], &argv0); 480 copyTV(J->L, &rd->argv[1], &argv0);
481#if LJ_FR2
482 /* Shift function arguments up. */
483 memmove(J->base + 2, J->base + 1, sizeof(TRef) * (J->maxslot-1));
484#endif
409 /* Need to protect lj_record_call because it may throw. */ 485 /* Need to protect lj_record_call because it may throw. */
410 errcode = lj_vm_cpcall(J->L, NULL, J, recff_xpcall_cp); 486 errcode = lj_vm_cpcall(J->L, NULL, J, recff_xpcall_cp);
411 /* Always undo Lua stack swap to avoid confusing the interpreter. */ 487 /* Always undo Lua stack swap to avoid confusing the interpreter. */
@@ -417,12 +493,24 @@ static void LJ_FASTCALL recff_xpcall(jit_State *J, RecordFFData *rd)
417 } /* else: Interpreter will throw. */ 493 } /* else: Interpreter will throw. */
418} 494}
419 495
496static void LJ_FASTCALL recff_getfenv(jit_State *J, RecordFFData *rd)
497{
498 TRef tr = J->base[0];
499 /* Only support getfenv(0) for now. */
500 if (tref_isint(tr) && tref_isk(tr) && IR(tref_ref(tr))->i == 0) {
501 TRef trl = emitir(IRT(IR_LREF, IRT_THREAD), 0, 0);
502 J->base[0] = emitir(IRT(IR_FLOAD, IRT_TAB), trl, IRFL_THREAD_ENV);
503 return;
504 }
505 recff_nyiu(J, rd);
506}
507
420/* -- Math library fast functions ----------------------------------------- */ 508/* -- Math library fast functions ----------------------------------------- */
421 509
422static void LJ_FASTCALL recff_math_abs(jit_State *J, RecordFFData *rd) 510static void LJ_FASTCALL recff_math_abs(jit_State *J, RecordFFData *rd)
423{ 511{
424 TRef tr = lj_ir_tonum(J, J->base[0]); 512 TRef tr = lj_ir_tonum(J, J->base[0]);
425 J->base[0] = emitir(IRTN(IR_ABS), tr, lj_ir_knum_abs(J)); 513 J->base[0] = emitir(IRTN(IR_ABS), tr, lj_ir_ksimd(J, LJ_KSIMD_ABS));
426 UNUSED(rd); 514 UNUSED(rd);
427} 515}
428 516
@@ -529,14 +617,6 @@ static void LJ_FASTCALL recff_math_modf(jit_State *J, RecordFFData *rd)
529 rd->nres = 2; 617 rd->nres = 2;
530} 618}
531 619
532static void LJ_FASTCALL recff_math_degrad(jit_State *J, RecordFFData *rd)
533{
534 TRef tr = lj_ir_tonum(J, J->base[0]);
535 TRef trm = lj_ir_knum(J, numV(&J->fn->c.upvalue[0]));
536 J->base[0] = emitir(IRTN(IR_MUL), tr, trm);
537 UNUSED(rd);
538}
539
540static void LJ_FASTCALL recff_math_pow(jit_State *J, RecordFFData *rd) 620static void LJ_FASTCALL recff_math_pow(jit_State *J, RecordFFData *rd)
541{ 621{
542 J->base[0] = lj_opt_narrow_pow(J, J->base[0], J->base[1], 622 J->base[0] = lj_opt_narrow_pow(J, J->base[0], J->base[1],
@@ -591,48 +671,105 @@ static void LJ_FASTCALL recff_math_random(jit_State *J, RecordFFData *rd)
591 671
592/* -- Bit library fast functions ------------------------------------------ */ 672/* -- Bit library fast functions ------------------------------------------ */
593 673
594/* Record unary bit.tobit, bit.bnot, bit.bswap. */ 674/* Record bit.tobit. */
675static void LJ_FASTCALL recff_bit_tobit(jit_State *J, RecordFFData *rd)
676{
677 TRef tr = J->base[0];
678#if LJ_HASFFI
679 if (tref_iscdata(tr)) { recff_bit64_tobit(J, rd); return; }
680#endif
681 J->base[0] = lj_opt_narrow_tobit(J, tr);
682 UNUSED(rd);
683}
684
685/* Record unary bit.bnot, bit.bswap. */
595static void LJ_FASTCALL recff_bit_unary(jit_State *J, RecordFFData *rd) 686static void LJ_FASTCALL recff_bit_unary(jit_State *J, RecordFFData *rd)
596{ 687{
597 TRef tr = lj_opt_narrow_tobit(J, J->base[0]); 688#if LJ_HASFFI
598 J->base[0] = (rd->data == IR_TOBIT) ? tr : emitir(IRTI(rd->data), tr, 0); 689 if (recff_bit64_unary(J, rd))
690 return;
691#endif
692 J->base[0] = emitir(IRTI(rd->data), lj_opt_narrow_tobit(J, J->base[0]), 0);
599} 693}
600 694
601/* Record N-ary bit.band, bit.bor, bit.bxor. */ 695/* Record N-ary bit.band, bit.bor, bit.bxor. */
602static void LJ_FASTCALL recff_bit_nary(jit_State *J, RecordFFData *rd) 696static void LJ_FASTCALL recff_bit_nary(jit_State *J, RecordFFData *rd)
603{ 697{
604 TRef tr = lj_opt_narrow_tobit(J, J->base[0]); 698#if LJ_HASFFI
605 uint32_t op = rd->data; 699 if (recff_bit64_nary(J, rd))
606 BCReg i; 700 return;
607 for (i = 1; J->base[i] != 0; i++) 701#endif
608 tr = emitir(IRTI(op), tr, lj_opt_narrow_tobit(J, J->base[i])); 702 {
609 J->base[0] = tr; 703 TRef tr = lj_opt_narrow_tobit(J, J->base[0]);
704 uint32_t ot = IRTI(rd->data);
705 BCReg i;
706 for (i = 1; J->base[i] != 0; i++)
707 tr = emitir(ot, tr, lj_opt_narrow_tobit(J, J->base[i]));
708 J->base[0] = tr;
709 }
610} 710}
611 711
612/* Record bit shifts. */ 712/* Record bit shifts. */
613static void LJ_FASTCALL recff_bit_shift(jit_State *J, RecordFFData *rd) 713static void LJ_FASTCALL recff_bit_shift(jit_State *J, RecordFFData *rd)
614{ 714{
615 TRef tr = lj_opt_narrow_tobit(J, J->base[0]); 715#if LJ_HASFFI
616 TRef tsh = lj_opt_narrow_tobit(J, J->base[1]); 716 if (recff_bit64_shift(J, rd))
617 IROp op = (IROp)rd->data; 717 return;
618 if (!(op < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) && 718#endif
619 !tref_isk(tsh)) 719 {
620 tsh = emitir(IRTI(IR_BAND), tsh, lj_ir_kint(J, 31)); 720 TRef tr = lj_opt_narrow_tobit(J, J->base[0]);
721 TRef tsh = lj_opt_narrow_tobit(J, J->base[1]);
722 IROp op = (IROp)rd->data;
723 if (!(op < IR_BROL ? LJ_TARGET_MASKSHIFT : LJ_TARGET_MASKROT) &&
724 !tref_isk(tsh))
725 tsh = emitir(IRTI(IR_BAND), tsh, lj_ir_kint(J, 31));
621#ifdef LJ_TARGET_UNIFYROT 726#ifdef LJ_TARGET_UNIFYROT
622 if (op == (LJ_TARGET_UNIFYROT == 1 ? IR_BROR : IR_BROL)) { 727 if (op == (LJ_TARGET_UNIFYROT == 1 ? IR_BROR : IR_BROL)) {
623 op = LJ_TARGET_UNIFYROT == 1 ? IR_BROL : IR_BROR; 728 op = LJ_TARGET_UNIFYROT == 1 ? IR_BROL : IR_BROR;
624 tsh = emitir(IRTI(IR_NEG), tsh, tsh); 729 tsh = emitir(IRTI(IR_NEG), tsh, tsh);
730 }
731#endif
732 J->base[0] = emitir(IRTI(op), tr, tsh);
625 } 733 }
734}
735
736static void LJ_FASTCALL recff_bit_tohex(jit_State *J, RecordFFData *rd)
737{
738#if LJ_HASFFI
739 TRef hdr = recff_bufhdr(J);
740 TRef tr = recff_bit64_tohex(J, rd, hdr);
741 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
742#else
743 recff_nyiu(J, rd); /* Don't bother working around this NYI. */
626#endif 744#endif
627 J->base[0] = emitir(IRTI(op), tr, tsh);
628} 745}
629 746
630/* -- String library fast functions --------------------------------------- */ 747/* -- String library fast functions --------------------------------------- */
631 748
632static void LJ_FASTCALL recff_string_len(jit_State *J, RecordFFData *rd) 749/* Specialize to relative starting position for string. */
750static TRef recff_string_start(jit_State *J, GCstr *s, int32_t *st, TRef tr,
751 TRef trlen, TRef tr0)
633{ 752{
634 J->base[0] = emitir(IRTI(IR_FLOAD), lj_ir_tostr(J, J->base[0]), IRFL_STR_LEN); 753 int32_t start = *st;
635 UNUSED(rd); 754 if (start < 0) {
755 emitir(IRTGI(IR_LT), tr, tr0);
756 tr = emitir(IRTI(IR_ADD), trlen, tr);
757 start = start + (int32_t)s->len;
758 emitir(start < 0 ? IRTGI(IR_LT) : IRTGI(IR_GE), tr, tr0);
759 if (start < 0) {
760 tr = tr0;
761 start = 0;
762 }
763 } else if (start == 0) {
764 emitir(IRTGI(IR_EQ), tr, tr0);
765 tr = tr0;
766 } else {
767 tr = emitir(IRTI(IR_ADD), tr, lj_ir_kint(J, -1));
768 emitir(IRTGI(IR_GE), tr, tr0);
769 start--;
770 }
771 *st = start;
772 return tr;
636} 773}
637 774
638/* Handle string.byte (rd->data = 0) and string.sub (rd->data = 1). */ 775/* Handle string.byte (rd->data = 0) and string.sub (rd->data = 1). */
@@ -679,39 +816,21 @@ static void LJ_FASTCALL recff_string_range(jit_State *J, RecordFFData *rd)
679 } else if ((MSize)end <= str->len) { 816 } else if ((MSize)end <= str->len) {
680 emitir(IRTGI(IR_ULE), trend, trlen); 817 emitir(IRTGI(IR_ULE), trend, trlen);
681 } else { 818 } else {
682 emitir(IRTGI(IR_GT), trend, trlen); 819 emitir(IRTGI(IR_UGT), trend, trlen);
683 end = (int32_t)str->len; 820 end = (int32_t)str->len;
684 trend = trlen; 821 trend = trlen;
685 } 822 }
686 if (start < 0) { 823 trstart = recff_string_start(J, str, &start, trstart, trlen, tr0);
687 emitir(IRTGI(IR_LT), trstart, tr0);
688 trstart = emitir(IRTI(IR_ADD), trlen, trstart);
689 start = start+(int32_t)str->len;
690 emitir(start < 0 ? IRTGI(IR_LT) : IRTGI(IR_GE), trstart, tr0);
691 if (start < 0) {
692 trstart = tr0;
693 start = 0;
694 }
695 } else {
696 if (start == 0) {
697 emitir(IRTGI(IR_EQ), trstart, tr0);
698 trstart = tr0;
699 } else {
700 trstart = emitir(IRTI(IR_ADD), trstart, lj_ir_kint(J, -1));
701 emitir(IRTGI(IR_GE), trstart, tr0);
702 start--;
703 }
704 }
705 if (rd->data) { /* Return string.sub result. */ 824 if (rd->data) { /* Return string.sub result. */
706 if (end - start >= 0) { 825 if (end - start >= 0) {
707 /* Also handle empty range here, to avoid extra traces. */ 826 /* Also handle empty range here, to avoid extra traces. */
708 TRef trptr, trslen = emitir(IRTI(IR_SUB), trend, trstart); 827 TRef trptr, trslen = emitir(IRTI(IR_SUB), trend, trstart);
709 emitir(IRTGI(IR_GE), trslen, tr0); 828 emitir(IRTGI(IR_GE), trslen, tr0);
710 trptr = emitir(IRT(IR_STRREF, IRT_P32), trstr, trstart); 829 trptr = emitir(IRT(IR_STRREF, IRT_PGC), trstr, trstart);
711 J->base[0] = emitir(IRT(IR_SNEW, IRT_STR), trptr, trslen); 830 J->base[0] = emitir(IRT(IR_SNEW, IRT_STR), trptr, trslen);
712 } else { /* Range underflow: return empty string. */ 831 } else { /* Range underflow: return empty string. */
713 emitir(IRTGI(IR_LT), trend, trstart); 832 emitir(IRTGI(IR_LT), trend, trstart);
714 J->base[0] = lj_ir_kstr(J, lj_str_new(J->L, strdata(str), 0)); 833 J->base[0] = lj_ir_kstr(J, &J2G(J)->strempty);
715 } 834 }
716 } else { /* Return string.byte result(s). */ 835 } else { /* Return string.byte result(s). */
717 ptrdiff_t i, len = end - start; 836 ptrdiff_t i, len = end - start;
@@ -723,7 +842,7 @@ static void LJ_FASTCALL recff_string_range(jit_State *J, RecordFFData *rd)
723 rd->nres = len; 842 rd->nres = len;
724 for (i = 0; i < len; i++) { 843 for (i = 0; i < len; i++) {
725 TRef tmp = emitir(IRTI(IR_ADD), trstart, lj_ir_kint(J, (int32_t)i)); 844 TRef tmp = emitir(IRTI(IR_ADD), trstart, lj_ir_kint(J, (int32_t)i));
726 tmp = emitir(IRT(IR_STRREF, IRT_P32), trstr, tmp); 845 tmp = emitir(IRT(IR_STRREF, IRT_PGC), trstr, tmp);
727 J->base[i] = emitir(IRT(IR_XLOAD, IRT_U8), tmp, IRXLOAD_READONLY); 846 J->base[i] = emitir(IRT(IR_XLOAD, IRT_U8), tmp, IRXLOAD_READONLY);
728 } 847 }
729 } else { /* Empty range or range underflow: return no results. */ 848 } else { /* Empty range or range underflow: return no results. */
@@ -733,48 +852,200 @@ static void LJ_FASTCALL recff_string_range(jit_State *J, RecordFFData *rd)
733 } 852 }
734} 853}
735 854
736/* -- Table library fast functions ---------------------------------------- */ 855static void LJ_FASTCALL recff_string_char(jit_State *J, RecordFFData *rd)
737
738static void LJ_FASTCALL recff_table_getn(jit_State *J, RecordFFData *rd)
739{ 856{
740 if (tref_istab(J->base[0])) 857 TRef k255 = lj_ir_kint(J, 255);
741 J->base[0] = lj_ir_call(J, IRCALL_lj_tab_len, J->base[0]); 858 BCReg i;
742 /* else: Interpreter will throw. */ 859 for (i = 0; J->base[i] != 0; i++) { /* Convert char values to strings. */
860 TRef tr = lj_opt_narrow_toint(J, J->base[i]);
861 emitir(IRTGI(IR_ULE), tr, k255);
862 J->base[i] = emitir(IRT(IR_TOSTR, IRT_STR), tr, IRTOSTR_CHAR);
863 }
864 if (i > 1) { /* Concatenate the strings, if there's more than one. */
865 TRef hdr = recff_bufhdr(J), tr = hdr;
866 for (i = 0; J->base[i] != 0; i++)
867 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, J->base[i]);
868 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
869 }
743 UNUSED(rd); 870 UNUSED(rd);
744} 871}
745 872
746static void LJ_FASTCALL recff_table_remove(jit_State *J, RecordFFData *rd) 873static void LJ_FASTCALL recff_string_rep(jit_State *J, RecordFFData *rd)
747{ 874{
748 TRef tab = J->base[0]; 875 TRef str = lj_ir_tostr(J, J->base[0]);
749 rd->nres = 0; 876 TRef rep = lj_opt_narrow_toint(J, J->base[1]);
750 if (tref_istab(tab)) { 877 TRef hdr, tr, str2 = 0;
751 if (tref_isnil(J->base[1])) { /* Simple pop: t[#t] = nil */ 878 if (!tref_isnil(J->base[2])) {
752 TRef trlen = lj_ir_call(J, IRCALL_lj_tab_len, tab); 879 TRef sep = lj_ir_tostr(J, J->base[2]);
753 GCtab *t = tabV(&rd->argv[0]); 880 int32_t vrep = argv2int(J, &rd->argv[1]);
754 MSize len = lj_tab_len(t); 881 emitir(IRTGI(vrep > 1 ? IR_GT : IR_LE), rep, lj_ir_kint(J, 1));
755 emitir(IRTGI(len ? IR_NE : IR_EQ), trlen, lj_ir_kint(J, 0)); 882 if (vrep > 1) {
756 if (len) { 883 TRef hdr2 = recff_bufhdr(J);
757 RecordIndex ix; 884 TRef tr2 = emitir(IRT(IR_BUFPUT, IRT_PGC), hdr2, sep);
758 ix.tab = tab; 885 tr2 = emitir(IRT(IR_BUFPUT, IRT_PGC), tr2, str);
759 ix.key = trlen; 886 str2 = emitir(IRT(IR_BUFSTR, IRT_STR), tr2, hdr2);
760 settabV(J->L, &ix.tabv, t); 887 }
761 setintV(&ix.keyv, len); 888 }
762 ix.idxchain = 0; 889 tr = hdr = recff_bufhdr(J);
763 if (results_wanted(J) != 0) { /* Specialize load only if needed. */ 890 if (str2) {
764 ix.val = 0; 891 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, str);
765 J->base[0] = lj_record_idx(J, &ix); /* Load previous value. */ 892 str = str2;
766 rd->nres = 1; 893 rep = emitir(IRTI(IR_ADD), rep, lj_ir_kint(J, -1));
767 /* Assumes ix.key/ix.tab is not modified for raw lj_record_idx(). */ 894 }
768 } 895 tr = lj_ir_call(J, IRCALL_lj_buf_putstr_rep, tr, str, rep);
769 ix.val = TREF_NIL; 896 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
770 lj_record_idx(J, &ix); /* Remove value. */ 897}
898
899static void LJ_FASTCALL recff_string_op(jit_State *J, RecordFFData *rd)
900{
901 TRef str = lj_ir_tostr(J, J->base[0]);
902 TRef hdr = recff_bufhdr(J);
903 TRef tr = lj_ir_call(J, rd->data, hdr, str);
904 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
905}
906
907static void LJ_FASTCALL recff_string_find(jit_State *J, RecordFFData *rd)
908{
909 TRef trstr = lj_ir_tostr(J, J->base[0]);
910 TRef trpat = lj_ir_tostr(J, J->base[1]);
911 TRef trlen = emitir(IRTI(IR_FLOAD), trstr, IRFL_STR_LEN);
912 TRef tr0 = lj_ir_kint(J, 0);
913 TRef trstart;
914 GCstr *str = argv2str(J, &rd->argv[0]);
915 GCstr *pat = argv2str(J, &rd->argv[1]);
916 int32_t start;
917 J->needsnap = 1;
918 if (tref_isnil(J->base[2])) {
919 trstart = lj_ir_kint(J, 1);
920 start = 1;
921 } else {
922 trstart = lj_opt_narrow_toint(J, J->base[2]);
923 start = argv2int(J, &rd->argv[2]);
924 }
925 trstart = recff_string_start(J, str, &start, trstart, trlen, tr0);
926 if ((MSize)start <= str->len) {
927 emitir(IRTGI(IR_ULE), trstart, trlen);
928 } else {
929 emitir(IRTGI(IR_UGT), trstart, trlen);
930#if LJ_52
931 J->base[0] = TREF_NIL;
932 return;
933#else
934 trstart = trlen;
935 start = str->len;
936#endif
937 }
938 /* Fixed arg or no pattern matching chars? (Specialized to pattern string.) */
939 if ((J->base[2] && tref_istruecond(J->base[3])) ||
940 (emitir(IRTG(IR_EQ, IRT_STR), trpat, lj_ir_kstr(J, pat)),
941 !lj_str_haspattern(pat))) { /* Search for fixed string. */
942 TRef trsptr = emitir(IRT(IR_STRREF, IRT_PGC), trstr, trstart);
943 TRef trpptr = emitir(IRT(IR_STRREF, IRT_PGC), trpat, tr0);
944 TRef trslen = emitir(IRTI(IR_SUB), trlen, trstart);
945 TRef trplen = emitir(IRTI(IR_FLOAD), trpat, IRFL_STR_LEN);
946 TRef tr = lj_ir_call(J, IRCALL_lj_str_find, trsptr, trpptr, trslen, trplen);
947 TRef trp0 = lj_ir_kkptr(J, NULL);
948 if (lj_str_find(strdata(str)+(MSize)start, strdata(pat),
949 str->len-(MSize)start, pat->len)) {
950 TRef pos;
951 emitir(IRTG(IR_NE, IRT_PGC), tr, trp0);
952 pos = emitir(IRTI(IR_SUB), tr, emitir(IRT(IR_STRREF, IRT_PGC), trstr, tr0));
953 J->base[0] = emitir(IRTI(IR_ADD), pos, lj_ir_kint(J, 1));
954 J->base[1] = emitir(IRTI(IR_ADD), pos, trplen);
955 rd->nres = 2;
956 } else {
957 emitir(IRTG(IR_EQ, IRT_PGC), tr, trp0);
958 J->base[0] = TREF_NIL;
959 }
960 } else { /* Search for pattern. */
961 recff_nyiu(J, rd);
962 return;
963 }
964}
965
966static void LJ_FASTCALL recff_string_format(jit_State *J, RecordFFData *rd)
967{
968 TRef trfmt = lj_ir_tostr(J, J->base[0]);
969 GCstr *fmt = argv2str(J, &rd->argv[0]);
970 int arg = 1;
971 TRef hdr, tr;
972 FormatState fs;
973 SFormat sf;
974 /* Specialize to the format string. */
975 emitir(IRTG(IR_EQ, IRT_STR), trfmt, lj_ir_kstr(J, fmt));
976 tr = hdr = recff_bufhdr(J);
977 lj_strfmt_init(&fs, strdata(fmt), fmt->len);
978 while ((sf = lj_strfmt_parse(&fs)) != STRFMT_EOF) { /* Parse format. */
979 TRef tra = sf == STRFMT_LIT ? 0 : J->base[arg++];
980 TRef trsf = lj_ir_kint(J, (int32_t)sf);
981 IRCallID id;
982 switch (STRFMT_TYPE(sf)) {
983 case STRFMT_LIT:
984 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr,
985 lj_ir_kstr(J, lj_str_new(J->L, fs.str, fs.len)));
986 break;
987 case STRFMT_INT:
988 id = IRCALL_lj_strfmt_putfnum_int;
989 handle_int:
990 if (!tref_isinteger(tra))
991 goto handle_num;
992 if (sf == STRFMT_INT) { /* Shortcut for plain %d. */
993 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr,
994 emitir(IRT(IR_TOSTR, IRT_STR), tra, IRTOSTR_INT));
995 } else {
996#if LJ_HASFFI
997 tra = emitir(IRT(IR_CONV, IRT_U64), tra,
998 (IRT_INT|(IRT_U64<<5)|IRCONV_SEXT));
999 tr = lj_ir_call(J, IRCALL_lj_strfmt_putfxint, tr, trsf, tra);
1000 lj_needsplit(J);
1001#else
1002 recff_nyiu(J, rd); /* Don't bother working around this NYI. */
1003 return;
1004#endif
1005 }
1006 break;
1007 case STRFMT_UINT:
1008 id = IRCALL_lj_strfmt_putfnum_uint;
1009 goto handle_int;
1010 case STRFMT_NUM:
1011 id = IRCALL_lj_strfmt_putfnum;
1012 handle_num:
1013 tra = lj_ir_tonum(J, tra);
1014 tr = lj_ir_call(J, id, tr, trsf, tra);
1015 if (LJ_SOFTFP) lj_needsplit(J);
1016 break;
1017 case STRFMT_STR:
1018 if (!tref_isstr(tra)) {
1019 recff_nyiu(J, rd); /* NYI: __tostring and non-string types for %s. */
1020 return;
771 } 1021 }
772 } else { /* Complex case: remove in the middle. */ 1022 if (sf == STRFMT_STR) /* Shortcut for plain %s. */
773 recff_nyiu(J); 1023 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, tra);
1024 else if ((sf & STRFMT_T_QUOTED))
1025 tr = lj_ir_call(J, IRCALL_lj_strfmt_putquoted, tr, tra);
1026 else
1027 tr = lj_ir_call(J, IRCALL_lj_strfmt_putfstr, tr, trsf, tra);
1028 break;
1029 case STRFMT_CHAR:
1030 tra = lj_opt_narrow_toint(J, tra);
1031 if (sf == STRFMT_CHAR) /* Shortcut for plain %c. */
1032 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr,
1033 emitir(IRT(IR_TOSTR, IRT_STR), tra, IRTOSTR_CHAR));
1034 else
1035 tr = lj_ir_call(J, IRCALL_lj_strfmt_putfchar, tr, trsf, tra);
1036 break;
1037 case STRFMT_PTR: /* NYI */
1038 case STRFMT_ERR:
1039 default:
1040 recff_nyiu(J, rd);
1041 return;
774 } 1042 }
775 } /* else: Interpreter will throw. */ 1043 }
1044 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
776} 1045}
777 1046
1047/* -- Table library fast functions ---------------------------------------- */
1048
778static void LJ_FASTCALL recff_table_insert(jit_State *J, RecordFFData *rd) 1049static void LJ_FASTCALL recff_table_insert(jit_State *J, RecordFFData *rd)
779{ 1050{
780 RecordIndex ix; 1051 RecordIndex ix;
@@ -791,11 +1062,49 @@ static void LJ_FASTCALL recff_table_insert(jit_State *J, RecordFFData *rd)
791 ix.idxchain = 0; 1062 ix.idxchain = 0;
792 lj_record_idx(J, &ix); /* Set new value. */ 1063 lj_record_idx(J, &ix); /* Set new value. */
793 } else { /* Complex case: insert in the middle. */ 1064 } else { /* Complex case: insert in the middle. */
794 recff_nyiu(J); 1065 recff_nyiu(J, rd);
1066 return;
795 } 1067 }
796 } /* else: Interpreter will throw. */ 1068 } /* else: Interpreter will throw. */
797} 1069}
798 1070
1071static void LJ_FASTCALL recff_table_concat(jit_State *J, RecordFFData *rd)
1072{
1073 TRef tab = J->base[0];
1074 if (tref_istab(tab)) {
1075 TRef sep = !tref_isnil(J->base[1]) ?
1076 lj_ir_tostr(J, J->base[1]) : lj_ir_knull(J, IRT_STR);
1077 TRef tri = (J->base[1] && !tref_isnil(J->base[2])) ?
1078 lj_opt_narrow_toint(J, J->base[2]) : lj_ir_kint(J, 1);
1079 TRef tre = (J->base[1] && J->base[2] && !tref_isnil(J->base[3])) ?
1080 lj_opt_narrow_toint(J, J->base[3]) :
1081 lj_ir_call(J, IRCALL_lj_tab_len, tab);
1082 TRef hdr = recff_bufhdr(J);
1083 TRef tr = lj_ir_call(J, IRCALL_lj_buf_puttab, hdr, tab, sep, tri, tre);
1084 emitir(IRTG(IR_NE, IRT_PTR), tr, lj_ir_kptr(J, NULL));
1085 J->base[0] = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
1086 } /* else: Interpreter will throw. */
1087 UNUSED(rd);
1088}
1089
1090static void LJ_FASTCALL recff_table_new(jit_State *J, RecordFFData *rd)
1091{
1092 TRef tra = lj_opt_narrow_toint(J, J->base[0]);
1093 TRef trh = lj_opt_narrow_toint(J, J->base[1]);
1094 J->base[0] = lj_ir_call(J, IRCALL_lj_tab_new_ah, tra, trh);
1095 UNUSED(rd);
1096}
1097
1098static void LJ_FASTCALL recff_table_clear(jit_State *J, RecordFFData *rd)
1099{
1100 TRef tr = J->base[0];
1101 if (tref_istab(tr)) {
1102 rd->nres = 0;
1103 lj_ir_call(J, IRCALL_lj_tab_clear, tr);
1104 J->needsnap = 1;
1105 } /* else: Interpreter will throw. */
1106}
1107
799/* -- I/O library fast functions ------------------------------------------ */ 1108/* -- I/O library fast functions ------------------------------------------ */
800 1109
801/* Get FILE* for I/O function. Any I/O error aborts recording, so there's 1110/* Get FILE* for I/O function. Any I/O error aborts recording, so there's
@@ -805,8 +1114,13 @@ static TRef recff_io_fp(jit_State *J, TRef *udp, int32_t id)
805{ 1114{
806 TRef tr, ud, fp; 1115 TRef tr, ud, fp;
807 if (id) { /* io.func() */ 1116 if (id) { /* io.func() */
1117#if LJ_GC64
1118 /* TODO: fix ARM32 asm_fload(), so we can use this for all archs. */
1119 ud = lj_ir_ggfload(J, IRT_UDATA, GG_OFS(g.gcroot[id]));
1120#else
808 tr = lj_ir_kptr(J, &J2G(J)->gcroot[id]); 1121 tr = lj_ir_kptr(J, &J2G(J)->gcroot[id]);
809 ud = emitir(IRT(IR_XLOAD, IRT_UDATA), tr, 0); 1122 ud = emitir(IRT(IR_XLOAD, IRT_UDATA), tr, 0);
1123#endif
810 } else { /* fp:method() */ 1124 } else { /* fp:method() */
811 ud = J->base[0]; 1125 ud = J->base[0];
812 if (!tref_isudata(ud)) 1126 if (!tref_isudata(ud))
@@ -828,10 +1142,13 @@ static void LJ_FASTCALL recff_io_write(jit_State *J, RecordFFData *rd)
828 ptrdiff_t i = rd->data == 0 ? 1 : 0; 1142 ptrdiff_t i = rd->data == 0 ? 1 : 0;
829 for (; J->base[i]; i++) { 1143 for (; J->base[i]; i++) {
830 TRef str = lj_ir_tostr(J, J->base[i]); 1144 TRef str = lj_ir_tostr(J, J->base[i]);
831 TRef buf = emitir(IRT(IR_STRREF, IRT_P32), str, zero); 1145 TRef buf = emitir(IRT(IR_STRREF, IRT_PGC), str, zero);
832 TRef len = emitir(IRTI(IR_FLOAD), str, IRFL_STR_LEN); 1146 TRef len = emitir(IRTI(IR_FLOAD), str, IRFL_STR_LEN);
833 if (tref_isk(len) && IR(tref_ref(len))->i == 1) { 1147 if (tref_isk(len) && IR(tref_ref(len))->i == 1) {
834 TRef tr = emitir(IRT(IR_XLOAD, IRT_U8), buf, IRXLOAD_READONLY); 1148 IRIns *irs = IR(tref_ref(str));
1149 TRef tr = (irs->o == IR_TOSTR && irs->op2 == IRTOSTR_CHAR) ?
1150 irs->op1 :
1151 emitir(IRT(IR_XLOAD, IRT_U8), buf, IRXLOAD_READONLY);
835 tr = lj_ir_call(J, IRCALL_fputc, tr, fp); 1152 tr = lj_ir_call(J, IRCALL_fputc, tr, fp);
836 if (results_wanted(J) != 0) /* Check result only if not ignored. */ 1153 if (results_wanted(J) != 0) /* Check result only if not ignored. */
837 emitir(IRTGI(IR_NE), tr, lj_ir_kint(J, -1)); 1154 emitir(IRTGI(IR_NE), tr, lj_ir_kint(J, -1));
@@ -853,6 +1170,28 @@ static void LJ_FASTCALL recff_io_flush(jit_State *J, RecordFFData *rd)
853 J->base[0] = TREF_TRUE; 1170 J->base[0] = TREF_TRUE;
854} 1171}
855 1172
1173/* -- Debug library fast functions ---------------------------------------- */
1174
1175static void LJ_FASTCALL recff_debug_getmetatable(jit_State *J, RecordFFData *rd)
1176{
1177 GCtab *mt;
1178 TRef mtref;
1179 TRef tr = J->base[0];
1180 if (tref_istab(tr)) {
1181 mt = tabref(tabV(&rd->argv[0])->metatable);
1182 mtref = emitir(IRT(IR_FLOAD, IRT_TAB), tr, IRFL_TAB_META);
1183 } else if (tref_isudata(tr)) {
1184 mt = tabref(udataV(&rd->argv[0])->metatable);
1185 mtref = emitir(IRT(IR_FLOAD, IRT_TAB), tr, IRFL_UDATA_META);
1186 } else {
1187 mt = tabref(basemt_obj(J2G(J), &rd->argv[0]));
1188 J->base[0] = mt ? lj_ir_ktab(J, mt) : TREF_NIL;
1189 return;
1190 }
1191 emitir(IRTG(mt ? IR_NE : IR_EQ, IRT_TAB), mtref, lj_ir_knull(J, IRT_TAB));
1192 J->base[0] = mt ? mtref : TREF_NIL;
1193}
1194
856/* -- Record calls to fast functions -------------------------------------- */ 1195/* -- Record calls to fast functions -------------------------------------- */
857 1196
858#include "lj_recdef.h" 1197#include "lj_recdef.h"
diff --git a/src/lj_frame.h b/src/lj_frame.h
index eb5df307..19c49a4a 100644
--- a/src/lj_frame.h
+++ b/src/lj_frame.h
@@ -11,7 +11,16 @@
11 11
12/* -- Lua stack frame ----------------------------------------------------- */ 12/* -- Lua stack frame ----------------------------------------------------- */
13 13
14/* Frame type markers in callee function slot (callee base-1). */ 14/* Frame type markers in LSB of PC (4-byte aligned) or delta (8-byte aligned:
15**
16** PC 00 Lua frame
17** delta 001 C frame
18** delta 010 Continuation frame
19** delta 011 Lua vararg frame
20** delta 101 cpcall() frame
21** delta 110 ff pcall() frame
22** delta 111 ff pcall() frame with active hook
23*/
15enum { 24enum {
16 FRAME_LUA, FRAME_C, FRAME_CONT, FRAME_VARG, 25 FRAME_LUA, FRAME_C, FRAME_CONT, FRAME_VARG,
17 FRAME_LUAP, FRAME_CP, FRAME_PCALL, FRAME_PCALLH 26 FRAME_LUAP, FRAME_CP, FRAME_PCALL, FRAME_PCALLH
@@ -21,9 +30,47 @@ enum {
21#define FRAME_TYPEP (FRAME_TYPE|FRAME_P) 30#define FRAME_TYPEP (FRAME_TYPE|FRAME_P)
22 31
23/* Macros to access and modify Lua frames. */ 32/* Macros to access and modify Lua frames. */
33#if LJ_FR2
34/* Two-slot frame info, required for 64 bit PC/GCRef:
35**
36** base-2 base-1 | base base+1 ...
37** [func PC/delta/ft] | [slots ...]
38** ^-- frame | ^-- base ^-- top
39**
40** Continuation frames:
41**
42** base-4 base-3 base-2 base-1 | base base+1 ...
43** [cont PC ] [func PC/delta/ft] | [slots ...]
44** ^-- frame | ^-- base ^-- top
45*/
46#define frame_gc(f) (gcval((f)-1))
47#define frame_ftsz(f) ((ptrdiff_t)(f)->ftsz)
48#define frame_pc(f) ((const BCIns *)frame_ftsz(f))
49#define setframe_gc(f, p, tp) (setgcVraw((f)-1, (p), (tp)))
50#define setframe_ftsz(f, sz) ((f)->ftsz = (sz))
51#define setframe_pc(f, pc) ((f)->ftsz = (int64_t)(intptr_t)(pc))
52#else
53/* One-slot frame info, sufficient for 32 bit PC/GCRef:
54**
55** base-1 | base base+1 ...
56** lo hi |
57** [func | PC/delta/ft] | [slots ...]
58** ^-- frame | ^-- base ^-- top
59**
60** Continuation frames:
61**
62** base-2 base-1 | base base+1 ...
63** lo hi lo hi |
64** [cont | PC] [func | PC/delta/ft] | [slots ...]
65** ^-- frame | ^-- base ^-- top
66*/
24#define frame_gc(f) (gcref((f)->fr.func)) 67#define frame_gc(f) (gcref((f)->fr.func))
25#define frame_func(f) (&frame_gc(f)->fn) 68#define frame_ftsz(f) ((ptrdiff_t)(f)->fr.tp.ftsz)
26#define frame_ftsz(f) ((f)->fr.tp.ftsz) 69#define frame_pc(f) (mref((f)->fr.tp.pcr, const BCIns))
70#define setframe_gc(f, p, tp) (setgcref((f)->fr.func, (p)), UNUSED(tp))
71#define setframe_ftsz(f, sz) ((f)->fr.tp.ftsz = (int32_t)(sz))
72#define setframe_pc(f, pc) (setmref((f)->fr.tp.pcr, (pc)))
73#endif
27 74
28#define frame_type(f) (frame_ftsz(f) & FRAME_TYPE) 75#define frame_type(f) (frame_ftsz(f) & FRAME_TYPE)
29#define frame_typep(f) (frame_ftsz(f) & FRAME_TYPEP) 76#define frame_typep(f) (frame_ftsz(f) & FRAME_TYPEP)
@@ -33,33 +80,53 @@ enum {
33#define frame_isvarg(f) (frame_typep(f) == FRAME_VARG) 80#define frame_isvarg(f) (frame_typep(f) == FRAME_VARG)
34#define frame_ispcall(f) ((frame_ftsz(f) & 6) == FRAME_PCALL) 81#define frame_ispcall(f) ((frame_ftsz(f) & 6) == FRAME_PCALL)
35 82
36#define frame_pc(f) (mref((f)->fr.tp.pcr, const BCIns)) 83#define frame_func(f) (&frame_gc(f)->fn)
84#define frame_delta(f) (frame_ftsz(f) >> 3)
85#define frame_sized(f) (frame_ftsz(f) & ~FRAME_TYPEP)
86
87enum { LJ_CONT_TAILCALL, LJ_CONT_FFI_CALLBACK }; /* Special continuations. */
88
89#if LJ_FR2
90#define frame_contpc(f) (frame_pc((f)-2))
91#define frame_contv(f) (((f)-3)->u64)
92#else
37#define frame_contpc(f) (frame_pc((f)-1)) 93#define frame_contpc(f) (frame_pc((f)-1))
38#if LJ_64 94#define frame_contv(f) (((f)-1)->u32.lo)
95#endif
96#if LJ_FR2
97#define frame_contf(f) ((ASMFunction)(uintptr_t)((f)-3)->u64)
98#elif LJ_64
39#define frame_contf(f) \ 99#define frame_contf(f) \
40 ((ASMFunction)(void *)((intptr_t)lj_vm_asm_begin + \ 100 ((ASMFunction)(void *)((intptr_t)lj_vm_asm_begin + \
41 (intptr_t)(int32_t)((f)-1)->u32.lo)) 101 (intptr_t)(int32_t)((f)-1)->u32.lo))
42#else 102#else
43#define frame_contf(f) ((ASMFunction)gcrefp(((f)-1)->gcr, void)) 103#define frame_contf(f) ((ASMFunction)gcrefp(((f)-1)->gcr, void))
44#endif 104#endif
45#define frame_delta(f) (frame_ftsz(f) >> 3) 105#define frame_iscont_fficb(f) \
46#define frame_sized(f) (frame_ftsz(f) & ~FRAME_TYPEP) 106 (LJ_HASFFI && frame_contv(f) == LJ_CONT_FFI_CALLBACK)
47 107
48#define frame_prevl(f) ((f) - (1+bc_a(frame_pc(f)[-1]))) 108#define frame_prevl(f) ((f) - (1+LJ_FR2+bc_a(frame_pc(f)[-1])))
49#define frame_prevd(f) ((TValue *)((char *)(f) - frame_sized(f))) 109#define frame_prevd(f) ((TValue *)((char *)(f) - frame_sized(f)))
50#define frame_prev(f) (frame_islua(f)?frame_prevl(f):frame_prevd(f)) 110#define frame_prev(f) (frame_islua(f)?frame_prevl(f):frame_prevd(f))
51/* Note: this macro does not skip over FRAME_VARG. */ 111/* Note: this macro does not skip over FRAME_VARG. */
52 112
53#define setframe_pc(f, pc) (setmref((f)->fr.tp.pcr, (pc)))
54#define setframe_ftsz(f, sz) ((f)->fr.tp.ftsz = (sz))
55#define setframe_gc(f, p) (setgcref((f)->fr.func, (p)))
56
57/* -- C stack frame ------------------------------------------------------- */ 113/* -- C stack frame ------------------------------------------------------- */
58 114
59/* Macros to access and modify the C stack frame chain. */ 115/* Macros to access and modify the C stack frame chain. */
60 116
61/* These definitions must match with the arch-specific *.dasc files. */ 117/* These definitions must match with the arch-specific *.dasc files. */
62#if LJ_TARGET_X86 118#if LJ_TARGET_X86
119#if LJ_ABI_WIN
120#define CFRAME_OFS_ERRF (19*4)
121#define CFRAME_OFS_NRES (18*4)
122#define CFRAME_OFS_PREV (17*4)
123#define CFRAME_OFS_L (16*4)
124#define CFRAME_OFS_SEH (9*4)
125#define CFRAME_OFS_PC (6*4)
126#define CFRAME_OFS_MULTRES (5*4)
127#define CFRAME_SIZE (16*4)
128#define CFRAME_SHIFT_MULTRES 0
129#else
63#define CFRAME_OFS_ERRF (15*4) 130#define CFRAME_OFS_ERRF (15*4)
64#define CFRAME_OFS_NRES (14*4) 131#define CFRAME_OFS_NRES (14*4)
65#define CFRAME_OFS_PREV (13*4) 132#define CFRAME_OFS_PREV (13*4)
@@ -68,24 +135,41 @@ enum {
68#define CFRAME_OFS_MULTRES (5*4) 135#define CFRAME_OFS_MULTRES (5*4)
69#define CFRAME_SIZE (12*4) 136#define CFRAME_SIZE (12*4)
70#define CFRAME_SHIFT_MULTRES 0 137#define CFRAME_SHIFT_MULTRES 0
138#endif
71#elif LJ_TARGET_X64 139#elif LJ_TARGET_X64
72#if LJ_ABI_WIN 140#if LJ_ABI_WIN
73#define CFRAME_OFS_PREV (13*8) 141#define CFRAME_OFS_PREV (13*8)
142#if LJ_GC64
143#define CFRAME_OFS_PC (12*8)
144#define CFRAME_OFS_L (11*8)
145#define CFRAME_OFS_ERRF (21*4)
146#define CFRAME_OFS_NRES (20*4)
147#define CFRAME_OFS_MULTRES (8*4)
148#else
74#define CFRAME_OFS_PC (25*4) 149#define CFRAME_OFS_PC (25*4)
75#define CFRAME_OFS_L (24*4) 150#define CFRAME_OFS_L (24*4)
76#define CFRAME_OFS_ERRF (23*4) 151#define CFRAME_OFS_ERRF (23*4)
77#define CFRAME_OFS_NRES (22*4) 152#define CFRAME_OFS_NRES (22*4)
78#define CFRAME_OFS_MULTRES (21*4) 153#define CFRAME_OFS_MULTRES (21*4)
154#endif
79#define CFRAME_SIZE (10*8) 155#define CFRAME_SIZE (10*8)
80#define CFRAME_SIZE_JIT (CFRAME_SIZE + 9*16 + 4*8) 156#define CFRAME_SIZE_JIT (CFRAME_SIZE + 9*16 + 4*8)
81#define CFRAME_SHIFT_MULTRES 0 157#define CFRAME_SHIFT_MULTRES 0
82#else 158#else
83#define CFRAME_OFS_PREV (4*8) 159#define CFRAME_OFS_PREV (4*8)
160#if LJ_GC64
161#define CFRAME_OFS_PC (3*8)
162#define CFRAME_OFS_L (2*8)
163#define CFRAME_OFS_ERRF (3*4)
164#define CFRAME_OFS_NRES (2*4)
165#define CFRAME_OFS_MULTRES (0*4)
166#else
84#define CFRAME_OFS_PC (7*4) 167#define CFRAME_OFS_PC (7*4)
85#define CFRAME_OFS_L (6*4) 168#define CFRAME_OFS_L (6*4)
86#define CFRAME_OFS_ERRF (5*4) 169#define CFRAME_OFS_ERRF (5*4)
87#define CFRAME_OFS_NRES (4*4) 170#define CFRAME_OFS_NRES (4*4)
88#define CFRAME_OFS_MULTRES (1*4) 171#define CFRAME_OFS_MULTRES (1*4)
172#endif
89#if LJ_NO_UNWIND 173#if LJ_NO_UNWIND
90#define CFRAME_SIZE (12*8) 174#define CFRAME_SIZE (12*8)
91#else 175#else
@@ -107,6 +191,15 @@ enum {
107#define CFRAME_SIZE 64 191#define CFRAME_SIZE 64
108#endif 192#endif
109#define CFRAME_SHIFT_MULTRES 3 193#define CFRAME_SHIFT_MULTRES 3
194#elif LJ_TARGET_ARM64
195#define CFRAME_OFS_ERRF 196
196#define CFRAME_OFS_NRES 200
197#define CFRAME_OFS_PREV 160
198#define CFRAME_OFS_L 176
199#define CFRAME_OFS_PC 168
200#define CFRAME_OFS_MULTRES 192
201#define CFRAME_SIZE 208
202#define CFRAME_SHIFT_MULTRES 3
110#elif LJ_TARGET_PPC 203#elif LJ_TARGET_PPC
111#if LJ_TARGET_XBOX360 204#if LJ_TARGET_XBOX360
112#define CFRAME_OFS_ERRF 424 205#define CFRAME_OFS_ERRF 424
@@ -117,7 +210,7 @@ enum {
117#define CFRAME_OFS_MULTRES 408 210#define CFRAME_OFS_MULTRES 408
118#define CFRAME_SIZE 384 211#define CFRAME_SIZE 384
119#define CFRAME_SHIFT_MULTRES 3 212#define CFRAME_SHIFT_MULTRES 3
120#elif LJ_ARCH_PPC64 213#elif LJ_ARCH_PPC32ON64
121#define CFRAME_OFS_ERRF 472 214#define CFRAME_OFS_ERRF 472
122#define CFRAME_OFS_NRES 468 215#define CFRAME_OFS_NRES 468
123#define CFRAME_OFS_PREV 448 216#define CFRAME_OFS_PREV 448
@@ -136,23 +229,40 @@ enum {
136#define CFRAME_SIZE 272 229#define CFRAME_SIZE 272
137#define CFRAME_SHIFT_MULTRES 3 230#define CFRAME_SHIFT_MULTRES 3
138#endif 231#endif
139#elif LJ_TARGET_PPCSPE 232#elif LJ_TARGET_MIPS32
140#define CFRAME_OFS_ERRF 28 233#if LJ_ARCH_HASFPU
141#define CFRAME_OFS_NRES 24
142#define CFRAME_OFS_PREV 20
143#define CFRAME_OFS_L 16
144#define CFRAME_OFS_PC 12
145#define CFRAME_OFS_MULTRES 8
146#define CFRAME_SIZE 184
147#define CFRAME_SHIFT_MULTRES 3
148#elif LJ_TARGET_MIPS
149#define CFRAME_OFS_ERRF 124 234#define CFRAME_OFS_ERRF 124
150#define CFRAME_OFS_NRES 120 235#define CFRAME_OFS_NRES 120
151#define CFRAME_OFS_PREV 116 236#define CFRAME_OFS_PREV 116
152#define CFRAME_OFS_L 112 237#define CFRAME_OFS_L 112
238#define CFRAME_SIZE 112
239#else
240#define CFRAME_OFS_ERRF 76
241#define CFRAME_OFS_NRES 72
242#define CFRAME_OFS_PREV 68
243#define CFRAME_OFS_L 64
244#define CFRAME_SIZE 64
245#endif
153#define CFRAME_OFS_PC 20 246#define CFRAME_OFS_PC 20
154#define CFRAME_OFS_MULTRES 16 247#define CFRAME_OFS_MULTRES 16
155#define CFRAME_SIZE 112 248#define CFRAME_SHIFT_MULTRES 3
249#elif LJ_TARGET_MIPS64
250#if LJ_ARCH_HASFPU
251#define CFRAME_OFS_ERRF 188
252#define CFRAME_OFS_NRES 184
253#define CFRAME_OFS_PREV 176
254#define CFRAME_OFS_L 168
255#define CFRAME_OFS_PC 160
256#define CFRAME_SIZE 192
257#else
258#define CFRAME_OFS_ERRF 124
259#define CFRAME_OFS_NRES 120
260#define CFRAME_OFS_PREV 112
261#define CFRAME_OFS_L 104
262#define CFRAME_OFS_PC 96
263#define CFRAME_SIZE 128
264#endif
265#define CFRAME_OFS_MULTRES 0
156#define CFRAME_SHIFT_MULTRES 3 266#define CFRAME_SHIFT_MULTRES 3
157#else 267#else
158#error "Missing CFRAME_* definitions for this architecture" 268#error "Missing CFRAME_* definitions for this architecture"
diff --git a/src/lj_gc.c b/src/lj_gc.c
index a5d32ea3..2aaf5b2c 100644
--- a/src/lj_gc.c
+++ b/src/lj_gc.c
@@ -12,6 +12,7 @@
12#include "lj_obj.h" 12#include "lj_obj.h"
13#include "lj_gc.h" 13#include "lj_gc.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_buf.h"
15#include "lj_str.h" 16#include "lj_str.h"
16#include "lj_tab.h" 17#include "lj_tab.h"
17#include "lj_func.h" 18#include "lj_func.h"
@@ -68,7 +69,7 @@ static void gc_mark(global_State *g, GCobj *o)
68 gray2black(o); /* Closed upvalues are never gray. */ 69 gray2black(o); /* Closed upvalues are never gray. */
69 } else if (gct != ~LJ_TSTR && gct != ~LJ_TCDATA) { 70 } else if (gct != ~LJ_TSTR && gct != ~LJ_TCDATA) {
70 lua_assert(gct == ~LJ_TFUNC || gct == ~LJ_TTAB || 71 lua_assert(gct == ~LJ_TFUNC || gct == ~LJ_TTAB ||
71 gct == ~LJ_TTHREAD || gct == ~LJ_TPROTO); 72 gct == ~LJ_TTHREAD || gct == ~LJ_TPROTO || gct == ~LJ_TTRACE);
72 setgcrefr(o->gch.gclist, g->gc.gray); 73 setgcrefr(o->gch.gclist, g->gc.gray);
73 setgcref(g->gc.gray, o); 74 setgcref(g->gc.gray, o);
74 } 75 }
@@ -244,6 +245,8 @@ static void gc_traverse_trace(global_State *g, GCtrace *T)
244 IRIns *ir = &T->ir[ref]; 245 IRIns *ir = &T->ir[ref];
245 if (ir->o == IR_KGC) 246 if (ir->o == IR_KGC)
246 gc_markobj(g, ir_kgc(ir)); 247 gc_markobj(g, ir_kgc(ir));
248 if (irt_is64(ir->t) && ir->o != IR_KNULL)
249 ref++;
247 } 250 }
248 if (T->link) gc_marktrace(g, T->link); 251 if (T->link) gc_marktrace(g, T->link);
249 if (T->nextroot) gc_marktrace(g, T->nextroot); 252 if (T->nextroot) gc_marktrace(g, T->nextroot);
@@ -274,12 +277,12 @@ static MSize gc_traverse_frames(global_State *g, lua_State *th)
274{ 277{
275 TValue *frame, *top = th->top-1, *bot = tvref(th->stack); 278 TValue *frame, *top = th->top-1, *bot = tvref(th->stack);
276 /* Note: extra vararg frame not skipped, marks function twice (harmless). */ 279 /* Note: extra vararg frame not skipped, marks function twice (harmless). */
277 for (frame = th->base-1; frame > bot; frame = frame_prev(frame)) { 280 for (frame = th->base-1; frame > bot+LJ_FR2; frame = frame_prev(frame)) {
278 GCfunc *fn = frame_func(frame); 281 GCfunc *fn = frame_func(frame);
279 TValue *ftop = frame; 282 TValue *ftop = frame;
280 if (isluafunc(fn)) ftop += funcproto(fn)->framesize; 283 if (isluafunc(fn)) ftop += funcproto(fn)->framesize;
281 if (ftop > top) top = ftop; 284 if (ftop > top) top = ftop;
282 gc_markobj(g, fn); /* Need to mark hidden function (or L). */ 285 if (!LJ_FR2) gc_markobj(g, fn); /* Need to mark hidden function (or L). */
283 } 286 }
284 top++; /* Correct bias of -1 (frame == base-1). */ 287 top++; /* Correct bias of -1 (frame == base-1). */
285 if (top > tvref(th->maxstack)) top = tvref(th->maxstack); 288 if (top > tvref(th->maxstack)) top = tvref(th->maxstack);
@@ -290,7 +293,7 @@ static MSize gc_traverse_frames(global_State *g, lua_State *th)
290static void gc_traverse_thread(global_State *g, lua_State *th) 293static void gc_traverse_thread(global_State *g, lua_State *th)
291{ 294{
292 TValue *o, *top = th->top; 295 TValue *o, *top = th->top;
293 for (o = tvref(th->stack)+1; o < top; o++) 296 for (o = tvref(th->stack)+1+LJ_FR2; o < top; o++)
294 gc_marktv(g, o); 297 gc_marktv(g, o);
295 if (g->gc.state == GCSatomic) { 298 if (g->gc.state == GCSatomic) {
296 top = tvref(th->stack) + th->stacksize; 299 top = tvref(th->stack) + th->stacksize;
@@ -355,15 +358,6 @@ static size_t gc_propagate_gray(global_State *g)
355 358
356/* -- Sweep phase --------------------------------------------------------- */ 359/* -- Sweep phase --------------------------------------------------------- */
357 360
358/* Try to shrink some common data structures. */
359static void gc_shrink(global_State *g, lua_State *L)
360{
361 if (g->strnum <= (g->strmask >> 2) && g->strmask > LJ_MIN_STRTAB*2-1)
362 lj_str_resize(L, g->strmask >> 1); /* Shrink string table. */
363 if (g->tmpbuf.sz > LJ_MIN_SBUF*2)
364 lj_str_resizebuf(L, &g->tmpbuf, g->tmpbuf.sz >> 1); /* Shrink temp buf. */
365}
366
367/* Type of GC free functions. */ 361/* Type of GC free functions. */
368typedef void (LJ_FASTCALL *GCFreeFunc)(global_State *g, GCobj *o); 362typedef void (LJ_FASTCALL *GCFreeFunc)(global_State *g, GCobj *o);
369 363
@@ -389,7 +383,7 @@ static const GCFreeFunc gc_freefunc[] = {
389}; 383};
390 384
391/* Full sweep of a GC list. */ 385/* Full sweep of a GC list. */
392#define gc_fullsweep(g, p) gc_sweep(g, (p), LJ_MAX_MEM) 386#define gc_fullsweep(g, p) gc_sweep(g, (p), ~(uint32_t)0)
393 387
394/* Partial sweep of a GC list. */ 388/* Partial sweep of a GC list. */
395static GCRef *gc_sweep(global_State *g, GCRef *p, uint32_t lim) 389static GCRef *gc_sweep(global_State *g, GCRef *p, uint32_t lim)
@@ -467,17 +461,18 @@ static void gc_call_finalizer(global_State *g, lua_State *L,
467{ 461{
468 /* Save and restore lots of state around the __gc callback. */ 462 /* Save and restore lots of state around the __gc callback. */
469 uint8_t oldh = hook_save(g); 463 uint8_t oldh = hook_save(g);
470 MSize oldt = g->gc.threshold; 464 GCSize oldt = g->gc.threshold;
471 int errcode; 465 int errcode;
472 TValue *top; 466 TValue *top;
473 lj_trace_abort(g); 467 lj_trace_abort(g);
474 top = L->top;
475 L->top = top+2;
476 hook_entergc(g); /* Disable hooks and new traces during __gc. */ 468 hook_entergc(g); /* Disable hooks and new traces during __gc. */
477 g->gc.threshold = LJ_MAX_MEM; /* Prevent GC steps. */ 469 g->gc.threshold = LJ_MAX_MEM; /* Prevent GC steps. */
478 copyTV(L, top, mo); 470 top = L->top;
479 setgcV(L, top+1, o, ~o->gch.gct); 471 copyTV(L, top++, mo);
480 errcode = lj_vm_pcall(L, top+1, 1+0, -1); /* Stack: |mo|o| -> | */ 472 if (LJ_FR2) setnilV(top++);
473 setgcV(L, top, o, ~o->gch.gct);
474 L->top = top+1;
475 errcode = lj_vm_pcall(L, top, 1+0, -1); /* Stack: |mo|o| -> | */
481 hook_restore(g, oldh); 476 hook_restore(g, oldh);
482 g->gc.threshold = oldt; /* Restore GC threshold. */ 477 g->gc.threshold = oldt; /* Restore GC threshold. */
483 if (errcode) 478 if (errcode)
@@ -490,7 +485,7 @@ static void gc_finalize(lua_State *L)
490 global_State *g = G(L); 485 global_State *g = G(L);
491 GCobj *o = gcnext(gcref(g->gc.mmudata)); 486 GCobj *o = gcnext(gcref(g->gc.mmudata));
492 cTValue *mo; 487 cTValue *mo;
493 lua_assert(gcref(g->jit_L) == NULL); /* Must not be called on trace. */ 488 lua_assert(tvref(g->jit_base) == NULL); /* Must not be called on trace. */
494 /* Unchain from list of userdata to be finalized. */ 489 /* Unchain from list of userdata to be finalized. */
495 if (o == gcref(g->gc.mmudata)) 490 if (o == gcref(g->gc.mmudata))
496 setgcrefnull(g->gc.mmudata); 491 setgcrefnull(g->gc.mmudata);
@@ -599,11 +594,13 @@ static void atomic(global_State *g, lua_State *L)
599 /* All marking done, clear weak tables. */ 594 /* All marking done, clear weak tables. */
600 gc_clearweak(gcref(g->gc.weak)); 595 gc_clearweak(gcref(g->gc.weak));
601 596
597 lj_buf_shrink(L, &g->tmpbuf); /* Shrink temp buffer. */
598
602 /* Prepare for sweep phase. */ 599 /* Prepare for sweep phase. */
603 g->gc.currentwhite = (uint8_t)otherwhite(g); /* Flip current white. */ 600 g->gc.currentwhite = (uint8_t)otherwhite(g); /* Flip current white. */
604 g->strempty.marked = g->gc.currentwhite; 601 g->strempty.marked = g->gc.currentwhite;
605 setmref(g->gc.sweep, &g->gc.root); 602 setmref(g->gc.sweep, &g->gc.root);
606 g->gc.estimate = g->gc.total - (MSize)udsize; /* Initial estimate. */ 603 g->gc.estimate = g->gc.total - (GCSize)udsize; /* Initial estimate. */
607} 604}
608 605
609/* GC state machine. Returns a cost estimate for each step performed. */ 606/* GC state machine. Returns a cost estimate for each step performed. */
@@ -620,14 +617,14 @@ static size_t gc_onestep(lua_State *L)
620 g->gc.state = GCSatomic; /* End of mark phase. */ 617 g->gc.state = GCSatomic; /* End of mark phase. */
621 return 0; 618 return 0;
622 case GCSatomic: 619 case GCSatomic:
623 if (gcref(g->jit_L)) /* Don't run atomic phase on trace. */ 620 if (tvref(g->jit_base)) /* Don't run atomic phase on trace. */
624 return LJ_MAX_MEM; 621 return LJ_MAX_MEM;
625 atomic(g, L); 622 atomic(g, L);
626 g->gc.state = GCSsweepstring; /* Start of sweep phase. */ 623 g->gc.state = GCSsweepstring; /* Start of sweep phase. */
627 g->gc.sweepstr = 0; 624 g->gc.sweepstr = 0;
628 return 0; 625 return 0;
629 case GCSsweepstring: { 626 case GCSsweepstring: {
630 MSize old = g->gc.total; 627 GCSize old = g->gc.total;
631 gc_fullsweep(g, &g->strhash[g->gc.sweepstr++]); /* Sweep one chain. */ 628 gc_fullsweep(g, &g->strhash[g->gc.sweepstr++]); /* Sweep one chain. */
632 if (g->gc.sweepstr > g->strmask) 629 if (g->gc.sweepstr > g->strmask)
633 g->gc.state = GCSsweep; /* All string hash chains sweeped. */ 630 g->gc.state = GCSsweep; /* All string hash chains sweeped. */
@@ -636,12 +633,13 @@ static size_t gc_onestep(lua_State *L)
636 return GCSWEEPCOST; 633 return GCSWEEPCOST;
637 } 634 }
638 case GCSsweep: { 635 case GCSsweep: {
639 MSize old = g->gc.total; 636 GCSize old = g->gc.total;
640 setmref(g->gc.sweep, gc_sweep(g, mref(g->gc.sweep, GCRef), GCSWEEPMAX)); 637 setmref(g->gc.sweep, gc_sweep(g, mref(g->gc.sweep, GCRef), GCSWEEPMAX));
641 lua_assert(old >= g->gc.total); 638 lua_assert(old >= g->gc.total);
642 g->gc.estimate -= old - g->gc.total; 639 g->gc.estimate -= old - g->gc.total;
643 if (gcref(*mref(g->gc.sweep, GCRef)) == NULL) { 640 if (gcref(*mref(g->gc.sweep, GCRef)) == NULL) {
644 gc_shrink(g, L); 641 if (g->strnum <= (g->strmask >> 2) && g->strmask > LJ_MIN_STRTAB*2-1)
642 lj_str_resize(L, g->strmask >> 1); /* Shrink string table. */
645 if (gcref(g->gc.mmudata)) { /* Need any finalizations? */ 643 if (gcref(g->gc.mmudata)) { /* Need any finalizations? */
646 g->gc.state = GCSfinalize; 644 g->gc.state = GCSfinalize;
647#if LJ_HASFFI 645#if LJ_HASFFI
@@ -656,7 +654,7 @@ static size_t gc_onestep(lua_State *L)
656 } 654 }
657 case GCSfinalize: 655 case GCSfinalize:
658 if (gcref(g->gc.mmudata) != NULL) { 656 if (gcref(g->gc.mmudata) != NULL) {
659 if (gcref(g->jit_L)) /* Don't call finalizers on trace. */ 657 if (tvref(g->jit_base)) /* Don't call finalizers on trace. */
660 return LJ_MAX_MEM; 658 return LJ_MAX_MEM;
661 gc_finalize(L); /* Finalize one userdata object. */ 659 gc_finalize(L); /* Finalize one userdata object. */
662 if (g->gc.estimate > GCFINALIZECOST) 660 if (g->gc.estimate > GCFINALIZECOST)
@@ -679,7 +677,7 @@ static size_t gc_onestep(lua_State *L)
679int LJ_FASTCALL lj_gc_step(lua_State *L) 677int LJ_FASTCALL lj_gc_step(lua_State *L)
680{ 678{
681 global_State *g = G(L); 679 global_State *g = G(L);
682 MSize lim; 680 GCSize lim;
683 int32_t ostate = g->vmstate; 681 int32_t ostate = g->vmstate;
684 setvmstate(g, GC); 682 setvmstate(g, GC);
685 lim = (GCSTEPSIZE/100) * g->gc.stepmul; 683 lim = (GCSTEPSIZE/100) * g->gc.stepmul;
@@ -688,13 +686,13 @@ int LJ_FASTCALL lj_gc_step(lua_State *L)
688 if (g->gc.total > g->gc.threshold) 686 if (g->gc.total > g->gc.threshold)
689 g->gc.debt += g->gc.total - g->gc.threshold; 687 g->gc.debt += g->gc.total - g->gc.threshold;
690 do { 688 do {
691 lim -= (MSize)gc_onestep(L); 689 lim -= (GCSize)gc_onestep(L);
692 if (g->gc.state == GCSpause) { 690 if (g->gc.state == GCSpause) {
693 g->gc.threshold = (g->gc.estimate/100) * g->gc.pause; 691 g->gc.threshold = (g->gc.estimate/100) * g->gc.pause;
694 g->vmstate = ostate; 692 g->vmstate = ostate;
695 return 1; /* Finished a GC cycle. */ 693 return 1; /* Finished a GC cycle. */
696 } 694 }
697 } while ((int32_t)lim > 0); 695 } while (sizeof(lim) == 8 ? ((int64_t)lim > 0) : ((int32_t)lim > 0));
698 if (g->gc.debt < GCSTEPSIZE) { 696 if (g->gc.debt < GCSTEPSIZE) {
699 g->gc.threshold = g->gc.total + GCSTEPSIZE; 697 g->gc.threshold = g->gc.total + GCSTEPSIZE;
700 g->vmstate = ostate; 698 g->vmstate = ostate;
@@ -718,8 +716,8 @@ void LJ_FASTCALL lj_gc_step_fixtop(lua_State *L)
718/* Perform multiple GC steps. Called from JIT-compiled code. */ 716/* Perform multiple GC steps. Called from JIT-compiled code. */
719int LJ_FASTCALL lj_gc_step_jit(global_State *g, MSize steps) 717int LJ_FASTCALL lj_gc_step_jit(global_State *g, MSize steps)
720{ 718{
721 lua_State *L = gco2th(gcref(g->jit_L)); 719 lua_State *L = gco2th(gcref(g->cur_L));
722 L->base = mref(G(L)->jit_base, TValue); 720 L->base = tvref(G(L)->jit_base);
723 L->top = curr_topL(L); 721 L->top = curr_topL(L);
724 while (steps-- > 0 && lj_gc_step(L) == 0) 722 while (steps-- > 0 && lj_gc_step(L) == 0)
725 ; 723 ;
@@ -813,7 +811,7 @@ void lj_gc_barriertrace(global_State *g, uint32_t traceno)
813/* -- Allocator ----------------------------------------------------------- */ 811/* -- Allocator ----------------------------------------------------------- */
814 812
815/* Call pluggable memory allocator to allocate or resize a fragment. */ 813/* Call pluggable memory allocator to allocate or resize a fragment. */
816void *lj_mem_realloc(lua_State *L, void *p, MSize osz, MSize nsz) 814void *lj_mem_realloc(lua_State *L, void *p, GCSize osz, GCSize nsz)
817{ 815{
818 global_State *g = G(L); 816 global_State *g = G(L);
819 lua_assert((osz == 0) == (p == NULL)); 817 lua_assert((osz == 0) == (p == NULL));
@@ -821,19 +819,19 @@ void *lj_mem_realloc(lua_State *L, void *p, MSize osz, MSize nsz)
821 if (p == NULL && nsz > 0) 819 if (p == NULL && nsz > 0)
822 lj_err_mem(L); 820 lj_err_mem(L);
823 lua_assert((nsz == 0) == (p == NULL)); 821 lua_assert((nsz == 0) == (p == NULL));
824 lua_assert(checkptr32(p)); 822 lua_assert(checkptrGC(p));
825 g->gc.total = (g->gc.total - osz) + nsz; 823 g->gc.total = (g->gc.total - osz) + nsz;
826 return p; 824 return p;
827} 825}
828 826
829/* Allocate new GC object and link it to the root set. */ 827/* Allocate new GC object and link it to the root set. */
830void * LJ_FASTCALL lj_mem_newgco(lua_State *L, MSize size) 828void * LJ_FASTCALL lj_mem_newgco(lua_State *L, GCSize size)
831{ 829{
832 global_State *g = G(L); 830 global_State *g = G(L);
833 GCobj *o = (GCobj *)g->allocf(g->allocd, NULL, 0, size); 831 GCobj *o = (GCobj *)g->allocf(g->allocd, NULL, 0, size);
834 if (o == NULL) 832 if (o == NULL)
835 lj_err_mem(L); 833 lj_err_mem(L);
836 lua_assert(checkptr32(o)); 834 lua_assert(checkptrGC(o));
837 g->gc.total += size; 835 g->gc.total += size;
838 setgcrefr(o->gch.nextgc, g->gc.root); 836 setgcrefr(o->gch.nextgc, g->gc.root);
839 setgcref(g->gc.root, o); 837 setgcref(g->gc.root, o);
diff --git a/src/lj_gc.h b/src/lj_gc.h
index 57ac7147..669bbe92 100644
--- a/src/lj_gc.h
+++ b/src/lj_gc.h
@@ -107,8 +107,8 @@ static LJ_AINLINE void lj_gc_barrierback(global_State *g, GCtab *t)
107 lj_gc_barrierf(G(L), obj2gco(p), obj2gco(o)); } 107 lj_gc_barrierf(G(L), obj2gco(p), obj2gco(o)); }
108 108
109/* Allocator. */ 109/* Allocator. */
110LJ_FUNC void *lj_mem_realloc(lua_State *L, void *p, MSize osz, MSize nsz); 110LJ_FUNC void *lj_mem_realloc(lua_State *L, void *p, GCSize osz, GCSize nsz);
111LJ_FUNC void * LJ_FASTCALL lj_mem_newgco(lua_State *L, MSize size); 111LJ_FUNC void * LJ_FASTCALL lj_mem_newgco(lua_State *L, GCSize size);
112LJ_FUNC void *lj_mem_grow(lua_State *L, void *p, 112LJ_FUNC void *lj_mem_grow(lua_State *L, void *p,
113 MSize *szp, MSize lim, MSize esz); 113 MSize *szp, MSize lim, MSize esz);
114 114
@@ -116,13 +116,13 @@ LJ_FUNC void *lj_mem_grow(lua_State *L, void *p,
116 116
117static LJ_AINLINE void lj_mem_free(global_State *g, void *p, size_t osize) 117static LJ_AINLINE void lj_mem_free(global_State *g, void *p, size_t osize)
118{ 118{
119 g->gc.total -= (MSize)osize; 119 g->gc.total -= (GCSize)osize;
120 g->allocf(g->allocd, p, osize, 0); 120 g->allocf(g->allocd, p, osize, 0);
121} 121}
122 122
123#define lj_mem_newvec(L, n, t) ((t *)lj_mem_new(L, (MSize)((n)*sizeof(t)))) 123#define lj_mem_newvec(L, n, t) ((t *)lj_mem_new(L, (GCSize)((n)*sizeof(t))))
124#define lj_mem_reallocvec(L, p, on, n, t) \ 124#define lj_mem_reallocvec(L, p, on, n, t) \
125 ((p) = (t *)lj_mem_realloc(L, p, (on)*sizeof(t), (MSize)((n)*sizeof(t)))) 125 ((p) = (t *)lj_mem_realloc(L, p, (on)*sizeof(t), (GCSize)((n)*sizeof(t))))
126#define lj_mem_growvec(L, p, n, m, t) \ 126#define lj_mem_growvec(L, p, n, m, t) \
127 ((p) = (t *)lj_mem_grow(L, (p), &(n), (m), (MSize)sizeof(t))) 127 ((p) = (t *)lj_mem_grow(L, (p), &(n), (m), (MSize)sizeof(t)))
128#define lj_mem_freevec(g, p, n, t) lj_mem_free(g, (p), (n)*sizeof(t)) 128#define lj_mem_freevec(g, p, n, t) lj_mem_free(g, (p), (n)*sizeof(t))
diff --git a/src/lj_gdbjit.c b/src/lj_gdbjit.c
index eeb017bb..c219ffac 100644
--- a/src/lj_gdbjit.c
+++ b/src/lj_gdbjit.c
@@ -14,6 +14,8 @@
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_debug.h" 15#include "lj_debug.h"
16#include "lj_frame.h" 16#include "lj_frame.h"
17#include "lj_buf.h"
18#include "lj_strfmt.h"
17#include "lj_jit.h" 19#include "lj_jit.h"
18#include "lj_dispatch.h" 20#include "lj_dispatch.h"
19 21
@@ -294,6 +296,9 @@ enum {
294#elif LJ_TARGET_ARM 296#elif LJ_TARGET_ARM
295 DW_REG_SP = 13, 297 DW_REG_SP = 13,
296 DW_REG_RA = 14, 298 DW_REG_RA = 14,
299#elif LJ_TARGET_ARM64
300 DW_REG_SP = 31,
301 DW_REG_RA = 30,
297#elif LJ_TARGET_PPC 302#elif LJ_TARGET_PPC
298 DW_REG_SP = 1, 303 DW_REG_SP = 1,
299 DW_REG_RA = 65, 304 DW_REG_RA = 65,
@@ -372,6 +377,8 @@ static const ELFheader elfhdr_template = {
372 .machine = 62, 377 .machine = 62,
373#elif LJ_TARGET_ARM 378#elif LJ_TARGET_ARM
374 .machine = 40, 379 .machine = 40,
380#elif LJ_TARGET_ARM64
381 .machine = 183,
375#elif LJ_TARGET_PPC 382#elif LJ_TARGET_PPC
376 .machine = 20, 383 .machine = 20,
377#elif LJ_TARGET_MIPS 384#elif LJ_TARGET_MIPS
@@ -428,16 +435,6 @@ static void gdbjit_catnum(GDBJITctx *ctx, uint32_t n)
428 *ctx->p++ = '0' + n; 435 *ctx->p++ = '0' + n;
429} 436}
430 437
431/* Add a ULEB128 value. */
432static void gdbjit_uleb128(GDBJITctx *ctx, uint32_t v)
433{
434 uint8_t *p = ctx->p;
435 for (; v >= 0x80; v >>= 7)
436 *p++ = (uint8_t)((v & 0x7f) | 0x80);
437 *p++ = (uint8_t)v;
438 ctx->p = p;
439}
440
441/* Add a SLEB128 value. */ 438/* Add a SLEB128 value. */
442static void gdbjit_sleb128(GDBJITctx *ctx, int32_t v) 439static void gdbjit_sleb128(GDBJITctx *ctx, int32_t v)
443{ 440{
@@ -454,7 +451,7 @@ static void gdbjit_sleb128(GDBJITctx *ctx, int32_t v)
454#define DU16(x) (*(uint16_t *)p = (x), p += 2) 451#define DU16(x) (*(uint16_t *)p = (x), p += 2)
455#define DU32(x) (*(uint32_t *)p = (x), p += 4) 452#define DU32(x) (*(uint32_t *)p = (x), p += 4)
456#define DADDR(x) (*(uintptr_t *)p = (x), p += sizeof(uintptr_t)) 453#define DADDR(x) (*(uintptr_t *)p = (x), p += sizeof(uintptr_t))
457#define DUV(x) (ctx->p = p, gdbjit_uleb128(ctx, (x)), p = ctx->p) 454#define DUV(x) (p = (uint8_t *)lj_strfmt_wuleb128((char *)p, (x)))
458#define DSV(x) (ctx->p = p, gdbjit_sleb128(ctx, (x)), p = ctx->p) 455#define DSV(x) (ctx->p = p, gdbjit_sleb128(ctx, (x)), p = ctx->p)
459#define DSTR(str) (ctx->p = p, gdbjit_strz(ctx, (str)), p = ctx->p) 456#define DSTR(str) (ctx->p = p, gdbjit_strz(ctx, (str)), p = ctx->p)
460#define DALIGNNOP(s) while ((uintptr_t)p & ((s)-1)) *p++ = DW_CFA_nop 457#define DALIGNNOP(s) while ((uintptr_t)p & ((s)-1)) *p++ = DW_CFA_nop
@@ -564,13 +561,20 @@ static void LJ_FASTCALL gdbjit_ehframe(GDBJITctx *ctx)
564 DB(DW_CFA_offset|DW_REG_15); DUV(4); 561 DB(DW_CFA_offset|DW_REG_15); DUV(4);
565 DB(DW_CFA_offset|DW_REG_14); DUV(5); 562 DB(DW_CFA_offset|DW_REG_14); DUV(5);
566 /* Extra registers saved for JIT-compiled code. */ 563 /* Extra registers saved for JIT-compiled code. */
567 DB(DW_CFA_offset|DW_REG_13); DUV(9); 564 DB(DW_CFA_offset|DW_REG_13); DUV(LJ_GC64 ? 10 : 9);
568 DB(DW_CFA_offset|DW_REG_12); DUV(10); 565 DB(DW_CFA_offset|DW_REG_12); DUV(LJ_GC64 ? 11 : 10);
569#elif LJ_TARGET_ARM 566#elif LJ_TARGET_ARM
570 { 567 {
571 int i; 568 int i;
572 for (i = 11; i >= 4; i--) { DB(DW_CFA_offset|i); DUV(2+(11-i)); } 569 for (i = 11; i >= 4; i--) { DB(DW_CFA_offset|i); DUV(2+(11-i)); }
573 } 570 }
571#elif LJ_TARGET_ARM64
572 {
573 int i;
574 DB(DW_CFA_offset|31); DUV(2);
575 for (i = 28; i >= 19; i--) { DB(DW_CFA_offset|i); DUV(3+(28-i)); }
576 for (i = 15; i >= 8; i--) { DB(DW_CFA_offset|32|i); DUV(28-i); }
577 }
574#elif LJ_TARGET_PPC 578#elif LJ_TARGET_PPC
575 { 579 {
576 int i; 580 int i;
@@ -727,6 +731,20 @@ static void gdbjit_buildobj(GDBJITctx *ctx)
727 731
728/* -- Interface to GDB JIT API -------------------------------------------- */ 732/* -- Interface to GDB JIT API -------------------------------------------- */
729 733
734static int gdbjit_lock;
735
736static void gdbjit_lock_acquire()
737{
738 while (__sync_lock_test_and_set(&gdbjit_lock, 1)) {
739 /* Just spin; futexes or pthreads aren't worth the portability cost. */
740 }
741}
742
743static void gdbjit_lock_release()
744{
745 __sync_lock_release(&gdbjit_lock);
746}
747
730/* Add new entry to GDB JIT symbol chain. */ 748/* Add new entry to GDB JIT symbol chain. */
731static void gdbjit_newentry(lua_State *L, GDBJITctx *ctx) 749static void gdbjit_newentry(lua_State *L, GDBJITctx *ctx)
732{ 750{
@@ -738,6 +756,7 @@ static void gdbjit_newentry(lua_State *L, GDBJITctx *ctx)
738 ctx->T->gdbjit_entry = (void *)eo; 756 ctx->T->gdbjit_entry = (void *)eo;
739 /* Link new entry to chain and register it. */ 757 /* Link new entry to chain and register it. */
740 eo->entry.prev_entry = NULL; 758 eo->entry.prev_entry = NULL;
759 gdbjit_lock_acquire();
741 eo->entry.next_entry = __jit_debug_descriptor.first_entry; 760 eo->entry.next_entry = __jit_debug_descriptor.first_entry;
742 if (eo->entry.next_entry) 761 if (eo->entry.next_entry)
743 eo->entry.next_entry->prev_entry = &eo->entry; 762 eo->entry.next_entry->prev_entry = &eo->entry;
@@ -747,6 +766,7 @@ static void gdbjit_newentry(lua_State *L, GDBJITctx *ctx)
747 __jit_debug_descriptor.relevant_entry = &eo->entry; 766 __jit_debug_descriptor.relevant_entry = &eo->entry;
748 __jit_debug_descriptor.action_flag = GDBJIT_REGISTER; 767 __jit_debug_descriptor.action_flag = GDBJIT_REGISTER;
749 __jit_debug_register_code(); 768 __jit_debug_register_code();
769 gdbjit_lock_release();
750} 770}
751 771
752/* Add debug info for newly compiled trace and notify GDB. */ 772/* Add debug info for newly compiled trace and notify GDB. */
@@ -778,6 +798,7 @@ void lj_gdbjit_deltrace(jit_State *J, GCtrace *T)
778{ 798{
779 GDBJITentryobj *eo = (GDBJITentryobj *)T->gdbjit_entry; 799 GDBJITentryobj *eo = (GDBJITentryobj *)T->gdbjit_entry;
780 if (eo) { 800 if (eo) {
801 gdbjit_lock_acquire();
781 if (eo->entry.prev_entry) 802 if (eo->entry.prev_entry)
782 eo->entry.prev_entry->next_entry = eo->entry.next_entry; 803 eo->entry.prev_entry->next_entry = eo->entry.next_entry;
783 else 804 else
@@ -787,6 +808,7 @@ void lj_gdbjit_deltrace(jit_State *J, GCtrace *T)
787 __jit_debug_descriptor.relevant_entry = &eo->entry; 808 __jit_debug_descriptor.relevant_entry = &eo->entry;
788 __jit_debug_descriptor.action_flag = GDBJIT_UNREGISTER; 809 __jit_debug_descriptor.action_flag = GDBJIT_UNREGISTER;
789 __jit_debug_register_code(); 810 __jit_debug_register_code();
811 gdbjit_lock_release();
790 lj_mem_free(J2G(J), eo, eo->sz); 812 lj_mem_free(J2G(J), eo, eo->sz);
791 } 813 }
792} 814}
diff --git a/src/lj_ir.c b/src/lj_ir.c
index 1e4860df..5baece67 100644
--- a/src/lj_ir.c
+++ b/src/lj_ir.c
@@ -15,6 +15,7 @@
15#if LJ_HASJIT 15#if LJ_HASJIT
16 16
17#include "lj_gc.h" 17#include "lj_gc.h"
18#include "lj_buf.h"
18#include "lj_str.h" 19#include "lj_str.h"
19#include "lj_tab.h" 20#include "lj_tab.h"
20#include "lj_ir.h" 21#include "lj_ir.h"
@@ -29,6 +30,7 @@
29#endif 30#endif
30#include "lj_vm.h" 31#include "lj_vm.h"
31#include "lj_strscan.h" 32#include "lj_strscan.h"
33#include "lj_strfmt.h"
32#include "lj_lib.h" 34#include "lj_lib.h"
33 35
34/* Some local macros to save typing. Undef'd at the end. */ 36/* Some local macros to save typing. Undef'd at the end. */
@@ -89,7 +91,7 @@ static void lj_ir_growbot(jit_State *J)
89 IRIns *baseir = J->irbuf + J->irbotlim; 91 IRIns *baseir = J->irbuf + J->irbotlim;
90 MSize szins = J->irtoplim - J->irbotlim; 92 MSize szins = J->irtoplim - J->irbotlim;
91 lua_assert(szins != 0); 93 lua_assert(szins != 0);
92 lua_assert(J->cur.nk == J->irbotlim); 94 lua_assert(J->cur.nk == J->irbotlim || J->cur.nk-1 == J->irbotlim);
93 if (J->cur.nins + (szins >> 1) < J->irtoplim) { 95 if (J->cur.nins + (szins >> 1) < J->irtoplim) {
94 /* More than half of the buffer is free on top: shift up by a quarter. */ 96 /* More than half of the buffer is free on top: shift up by a quarter. */
95 MSize ofs = szins >> 2; 97 MSize ofs = szins >> 2;
@@ -143,6 +145,16 @@ TRef lj_ir_call(jit_State *J, IRCallID id, ...)
143 return emitir(CCI_OPTYPE(ci), tr, id); 145 return emitir(CCI_OPTYPE(ci), tr, id);
144} 146}
145 147
148/* Load field of type t from GG_State + offset. Must be 32 bit aligned. */
149LJ_FUNC TRef lj_ir_ggfload(jit_State *J, IRType t, uintptr_t ofs)
150{
151 lua_assert((ofs & 3) == 0);
152 ofs >>= 2;
153 lua_assert(ofs >= IRFL__MAX && ofs <= 0x3ff); /* 10 bit FOLD key limit. */
154 lj_ir_set(J, IRT(IR_FLOAD, t), REF_NIL, ofs);
155 return lj_opt_fold(J);
156}
157
146/* -- Interning of constants ---------------------------------------------- */ 158/* -- Interning of constants ---------------------------------------------- */
147 159
148/* 160/*
@@ -163,6 +175,24 @@ static LJ_AINLINE IRRef ir_nextk(jit_State *J)
163 return ref; 175 return ref;
164} 176}
165 177
178/* Get ref of next 64 bit IR constant and optionally grow IR.
179** Note: this may invalidate all IRIns *!
180*/
181static LJ_AINLINE IRRef ir_nextk64(jit_State *J)
182{
183 IRRef ref = J->cur.nk - 2;
184 lua_assert(J->state != LJ_TRACE_ASM);
185 if (LJ_UNLIKELY(ref < J->irbotlim)) lj_ir_growbot(J);
186 J->cur.nk = ref;
187 return ref;
188}
189
190#if LJ_GC64
191#define ir_nextkgc ir_nextk64
192#else
193#define ir_nextkgc ir_nextk
194#endif
195
166/* Intern int32_t constant. */ 196/* Intern int32_t constant. */
167TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k) 197TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k)
168{ 198{
@@ -182,79 +212,21 @@ found:
182 return TREF(ref, IRT_INT); 212 return TREF(ref, IRT_INT);
183} 213}
184 214
185/* The MRef inside the KNUM/KINT64 IR instructions holds the address of the 215/* Intern 64 bit constant, given by its 64 bit pattern. */
186** 64 bit constant. The constants themselves are stored in a chained array 216TRef lj_ir_k64(jit_State *J, IROp op, uint64_t u64)
187** and shared across traces.
188**
189** Rationale for choosing this data structure:
190** - The address of the constants is embedded in the generated machine code
191** and must never move. A resizable array or hash table wouldn't work.
192** - Most apps need very few non-32 bit integer constants (less than a dozen).
193** - Linear search is hard to beat in terms of speed and low complexity.
194*/
195typedef struct K64Array {
196 MRef next; /* Pointer to next list. */
197 MSize numk; /* Number of used elements in this array. */
198 TValue k[LJ_MIN_K64SZ]; /* Array of constants. */
199} K64Array;
200
201/* Free all chained arrays. */
202void lj_ir_k64_freeall(jit_State *J)
203{
204 K64Array *k;
205 for (k = mref(J->k64, K64Array); k; ) {
206 K64Array *next = mref(k->next, K64Array);
207 lj_mem_free(J2G(J), k, sizeof(K64Array));
208 k = next;
209 }
210}
211
212/* Find 64 bit constant in chained array or add it. */
213cTValue *lj_ir_k64_find(jit_State *J, uint64_t u64)
214{
215 K64Array *k, *kp = NULL;
216 TValue *ntv;
217 MSize idx;
218 /* Search for the constant in the whole chain of arrays. */
219 for (k = mref(J->k64, K64Array); k; k = mref(k->next, K64Array)) {
220 kp = k; /* Remember previous element in list. */
221 for (idx = 0; idx < k->numk; idx++) { /* Search one array. */
222 TValue *tv = &k->k[idx];
223 if (tv->u64 == u64) /* Needed for +-0/NaN/absmask. */
224 return tv;
225 }
226 }
227 /* Constant was not found, need to add it. */
228 if (!(kp && kp->numk < LJ_MIN_K64SZ)) { /* Allocate a new array. */
229 K64Array *kn = lj_mem_newt(J->L, sizeof(K64Array), K64Array);
230 setmref(kn->next, NULL);
231 kn->numk = 0;
232 if (kp)
233 setmref(kp->next, kn); /* Chain to the end of the list. */
234 else
235 setmref(J->k64, kn); /* Link first array. */
236 kp = kn;
237 }
238 ntv = &kp->k[kp->numk++]; /* Add to current array. */
239 ntv->u64 = u64;
240 return ntv;
241}
242
243/* Intern 64 bit constant, given by its address. */
244TRef lj_ir_k64(jit_State *J, IROp op, cTValue *tv)
245{ 217{
246 IRIns *ir, *cir = J->cur.ir; 218 IRIns *ir, *cir = J->cur.ir;
247 IRRef ref; 219 IRRef ref;
248 IRType t = op == IR_KNUM ? IRT_NUM : IRT_I64; 220 IRType t = op == IR_KNUM ? IRT_NUM : IRT_I64;
249 for (ref = J->chain[op]; ref; ref = cir[ref].prev) 221 for (ref = J->chain[op]; ref; ref = cir[ref].prev)
250 if (ir_k64(&cir[ref]) == tv) 222 if (ir_k64(&cir[ref])->u64 == u64)
251 goto found; 223 goto found;
252 ref = ir_nextk(J); 224 ref = ir_nextk64(J);
253 ir = IR(ref); 225 ir = IR(ref);
254 lua_assert(checkptr32(tv)); 226 ir[1].tv.u64 = u64;
255 setmref(ir->ptr, tv);
256 ir->t.irt = t; 227 ir->t.irt = t;
257 ir->o = op; 228 ir->o = op;
229 ir->op12 = 0;
258 ir->prev = J->chain[op]; 230 ir->prev = J->chain[op];
259 J->chain[op] = (IRRef1)ref; 231 J->chain[op] = (IRRef1)ref;
260found: 232found:
@@ -264,13 +236,13 @@ found:
264/* Intern FP constant, given by its 64 bit pattern. */ 236/* Intern FP constant, given by its 64 bit pattern. */
265TRef lj_ir_knum_u64(jit_State *J, uint64_t u64) 237TRef lj_ir_knum_u64(jit_State *J, uint64_t u64)
266{ 238{
267 return lj_ir_k64(J, IR_KNUM, lj_ir_k64_find(J, u64)); 239 return lj_ir_k64(J, IR_KNUM, u64);
268} 240}
269 241
270/* Intern 64 bit integer constant. */ 242/* Intern 64 bit integer constant. */
271TRef lj_ir_kint64(jit_State *J, uint64_t u64) 243TRef lj_ir_kint64(jit_State *J, uint64_t u64)
272{ 244{
273 return lj_ir_k64(J, IR_KINT64, lj_ir_k64_find(J, u64)); 245 return lj_ir_k64(J, IR_KINT64, u64);
274} 246}
275 247
276/* Check whether a number is int and return it. -0 is NOT considered an int. */ 248/* Check whether a number is int and return it. -0 is NOT considered an int. */
@@ -309,10 +281,11 @@ TRef lj_ir_kgc(jit_State *J, GCobj *o, IRType t)
309 for (ref = J->chain[IR_KGC]; ref; ref = cir[ref].prev) 281 for (ref = J->chain[IR_KGC]; ref; ref = cir[ref].prev)
310 if (ir_kgc(&cir[ref]) == o) 282 if (ir_kgc(&cir[ref]) == o)
311 goto found; 283 goto found;
312 ref = ir_nextk(J); 284 ref = ir_nextkgc(J);
313 ir = IR(ref); 285 ir = IR(ref);
314 /* NOBARRIER: Current trace is a GC root. */ 286 /* NOBARRIER: Current trace is a GC root. */
315 setgcref(ir->gcr, o); 287 ir->op12 = 0;
288 setgcref(ir[LJ_GC64].gcr, o);
316 ir->t.irt = (uint8_t)t; 289 ir->t.irt = (uint8_t)t;
317 ir->o = IR_KGC; 290 ir->o = IR_KGC;
318 ir->prev = J->chain[IR_KGC]; 291 ir->prev = J->chain[IR_KGC];
@@ -321,24 +294,44 @@ found:
321 return TREF(ref, t); 294 return TREF(ref, t);
322} 295}
323 296
324/* Intern 32 bit pointer constant. */ 297/* Allocate GCtrace constant placeholder (no interning). */
298TRef lj_ir_ktrace(jit_State *J)
299{
300 IRRef ref = ir_nextkgc(J);
301 IRIns *ir = IR(ref);
302 lua_assert(irt_toitype_(IRT_P64) == LJ_TTRACE);
303 ir->t.irt = IRT_P64;
304 ir->o = LJ_GC64 ? IR_KNUM : IR_KNULL; /* Not IR_KGC yet, but same size. */
305 ir->op12 = 0;
306 ir->prev = 0;
307 return TREF(ref, IRT_P64);
308}
309
310/* Intern pointer constant. */
325TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr) 311TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr)
326{ 312{
327 IRIns *ir, *cir = J->cur.ir; 313 IRIns *ir, *cir = J->cur.ir;
328 IRRef ref; 314 IRRef ref;
329 lua_assert((void *)(intptr_t)i32ptr(ptr) == ptr); 315#if LJ_64 && !LJ_GC64
316 lua_assert((void *)(uintptr_t)u32ptr(ptr) == ptr);
317#endif
330 for (ref = J->chain[op]; ref; ref = cir[ref].prev) 318 for (ref = J->chain[op]; ref; ref = cir[ref].prev)
331 if (mref(cir[ref].ptr, void) == ptr) 319 if (ir_kptr(&cir[ref]) == ptr)
332 goto found; 320 goto found;
321#if LJ_GC64
322 ref = ir_nextk64(J);
323#else
333 ref = ir_nextk(J); 324 ref = ir_nextk(J);
325#endif
334 ir = IR(ref); 326 ir = IR(ref);
335 setmref(ir->ptr, ptr); 327 ir->op12 = 0;
336 ir->t.irt = IRT_P32; 328 setmref(ir[LJ_GC64].ptr, ptr);
329 ir->t.irt = IRT_PGC;
337 ir->o = op; 330 ir->o = op;
338 ir->prev = J->chain[op]; 331 ir->prev = J->chain[op];
339 J->chain[op] = (IRRef1)ref; 332 J->chain[op] = (IRRef1)ref;
340found: 333found:
341 return TREF(ref, IRT_P32); 334 return TREF(ref, IRT_PGC);
342} 335}
343 336
344/* Intern typed NULL constant. */ 337/* Intern typed NULL constant. */
@@ -390,12 +383,11 @@ void lj_ir_kvalue(lua_State *L, TValue *tv, const IRIns *ir)
390 UNUSED(L); 383 UNUSED(L);
391 lua_assert(ir->o != IR_KSLOT); /* Common mistake. */ 384 lua_assert(ir->o != IR_KSLOT); /* Common mistake. */
392 switch (ir->o) { 385 switch (ir->o) {
393 case IR_KPRI: setitype(tv, irt_toitype(ir->t)); break; 386 case IR_KPRI: setpriV(tv, irt_toitype(ir->t)); break;
394 case IR_KINT: setintV(tv, ir->i); break; 387 case IR_KINT: setintV(tv, ir->i); break;
395 case IR_KGC: setgcV(L, tv, ir_kgc(ir), irt_toitype(ir->t)); break; 388 case IR_KGC: setgcV(L, tv, ir_kgc(ir), irt_toitype(ir->t)); break;
396 case IR_KPTR: case IR_KKPTR: case IR_KNULL: 389 case IR_KPTR: case IR_KKPTR: setlightudV(tv, ir_kptr(ir)); break;
397 setlightudV(tv, mref(ir->ptr, void)); 390 case IR_KNULL: setlightudV(tv, NULL); break;
398 break;
399 case IR_KNUM: setnumV(tv, ir_knum(ir)->n); break; 391 case IR_KNUM: setnumV(tv, ir_knum(ir)->n); break;
400#if LJ_HASFFI 392#if LJ_HASFFI
401 case IR_KINT64: { 393 case IR_KINT64: {
@@ -443,7 +435,8 @@ TRef LJ_FASTCALL lj_ir_tostr(jit_State *J, TRef tr)
443 if (!tref_isstr(tr)) { 435 if (!tref_isstr(tr)) {
444 if (!tref_isnumber(tr)) 436 if (!tref_isnumber(tr))
445 lj_trace_err(J, LJ_TRERR_BADTYPE); 437 lj_trace_err(J, LJ_TRERR_BADTYPE);
446 tr = emitir(IRT(IR_TOSTR, IRT_STR), tr, 0); 438 tr = emitir(IRT(IR_TOSTR, IRT_STR), tr,
439 tref_isnum(tr) ? IRTOSTR_NUM : IRTOSTR_INT);
447 } 440 }
448 return tr; 441 return tr;
449} 442}
diff --git a/src/lj_ir.h b/src/lj_ir.h
index ded3e0eb..34c27853 100644
--- a/src/lj_ir.h
+++ b/src/lj_ir.h
@@ -40,6 +40,7 @@
40 _(USE, S , ref, ___) \ 40 _(USE, S , ref, ___) \
41 _(PHI, S , ref, ref) \ 41 _(PHI, S , ref, ref) \
42 _(RENAME, S , ref, lit) \ 42 _(RENAME, S , ref, lit) \
43 _(PROF, S , ___, ___) \
43 \ 44 \
44 /* Constants. */ \ 45 /* Constants. */ \
45 _(KPRI, N , ___, ___) \ 46 _(KPRI, N , ___, ___) \
@@ -96,6 +97,7 @@
96 _(UREFC, LW, ref, lit) \ 97 _(UREFC, LW, ref, lit) \
97 _(FREF, R , ref, lit) \ 98 _(FREF, R , ref, lit) \
98 _(STRREF, N , ref, ref) \ 99 _(STRREF, N , ref, ref) \
100 _(LREF, L , ___, ___) \
99 \ 101 \
100 /* Loads and Stores. These must be in the same order. */ \ 102 /* Loads and Stores. These must be in the same order. */ \
101 _(ALOAD, L , ref, ___) \ 103 _(ALOAD, L , ref, ___) \
@@ -120,6 +122,11 @@
120 _(CNEW, AW, ref, ref) \ 122 _(CNEW, AW, ref, ref) \
121 _(CNEWI, NW, ref, ref) /* CSE is ok, not marked as A. */ \ 123 _(CNEWI, NW, ref, ref) /* CSE is ok, not marked as A. */ \
122 \ 124 \
125 /* Buffer operations. */ \
126 _(BUFHDR, L , ref, lit) \
127 _(BUFPUT, L , ref, ref) \
128 _(BUFSTR, A , ref, ref) \
129 \
123 /* Barriers. */ \ 130 /* Barriers. */ \
124 _(TBAR, S , ref, ___) \ 131 _(TBAR, S , ref, ___) \
125 _(OBAR, S , ref, ref) \ 132 _(OBAR, S , ref, ref) \
@@ -128,11 +135,12 @@
128 /* Type conversions. */ \ 135 /* Type conversions. */ \
129 _(CONV, NW, ref, lit) \ 136 _(CONV, NW, ref, lit) \
130 _(TOBIT, N , ref, ref) \ 137 _(TOBIT, N , ref, ref) \
131 _(TOSTR, N , ref, ___) \ 138 _(TOSTR, N , ref, lit) \
132 _(STRTO, N , ref, ___) \ 139 _(STRTO, N , ref, ___) \
133 \ 140 \
134 /* Calls. */ \ 141 /* Calls. */ \
135 _(CALLN, N , ref, lit) \ 142 _(CALLN, N , ref, lit) \
143 _(CALLA, A , ref, lit) \
136 _(CALLL, L , ref, lit) \ 144 _(CALLL, L , ref, lit) \
137 _(CALLS, S , ref, lit) \ 145 _(CALLS, S , ref, lit) \
138 _(CALLXS, S , ref, ref) \ 146 _(CALLXS, S , ref, ref) \
@@ -186,6 +194,8 @@ IRFPMDEF(FPMENUM)
186 _(STR_LEN, offsetof(GCstr, len)) \ 194 _(STR_LEN, offsetof(GCstr, len)) \
187 _(FUNC_ENV, offsetof(GCfunc, l.env)) \ 195 _(FUNC_ENV, offsetof(GCfunc, l.env)) \
188 _(FUNC_PC, offsetof(GCfunc, l.pc)) \ 196 _(FUNC_PC, offsetof(GCfunc, l.pc)) \
197 _(FUNC_FFID, offsetof(GCfunc, l.ffid)) \
198 _(THREAD_ENV, offsetof(lua_State, env)) \
189 _(TAB_META, offsetof(GCtab, metatable)) \ 199 _(TAB_META, offsetof(GCtab, metatable)) \
190 _(TAB_ARRAY, offsetof(GCtab, array)) \ 200 _(TAB_ARRAY, offsetof(GCtab, array)) \
191 _(TAB_NODE, offsetof(GCtab, node)) \ 201 _(TAB_NODE, offsetof(GCtab, node)) \
@@ -210,7 +220,7 @@ IRFLDEF(FLENUM)
210 220
211/* SLOAD mode bits, stored in op2. */ 221/* SLOAD mode bits, stored in op2. */
212#define IRSLOAD_PARENT 0x01 /* Coalesce with parent trace. */ 222#define IRSLOAD_PARENT 0x01 /* Coalesce with parent trace. */
213#define IRSLOAD_FRAME 0x02 /* Load hiword of frame. */ 223#define IRSLOAD_FRAME 0x02 /* Load 32 bits of ftsz. */
214#define IRSLOAD_TYPECHECK 0x04 /* Needs type check. */ 224#define IRSLOAD_TYPECHECK 0x04 /* Needs type check. */
215#define IRSLOAD_CONVERT 0x08 /* Number to integer conversion. */ 225#define IRSLOAD_CONVERT 0x08 /* Number to integer conversion. */
216#define IRSLOAD_READONLY 0x10 /* Read-only, omit slot store. */ 226#define IRSLOAD_READONLY 0x10 /* Read-only, omit slot store. */
@@ -221,13 +231,16 @@ IRFLDEF(FLENUM)
221#define IRXLOAD_VOLATILE 2 /* Load from volatile data. */ 231#define IRXLOAD_VOLATILE 2 /* Load from volatile data. */
222#define IRXLOAD_UNALIGNED 4 /* Unaligned load. */ 232#define IRXLOAD_UNALIGNED 4 /* Unaligned load. */
223 233
234/* BUFHDR mode, stored in op2. */
235#define IRBUFHDR_RESET 0 /* Reset buffer. */
236#define IRBUFHDR_APPEND 1 /* Append to buffer. */
237
224/* CONV mode, stored in op2. */ 238/* CONV mode, stored in op2. */
225#define IRCONV_SRCMASK 0x001f /* Source IRType. */ 239#define IRCONV_SRCMASK 0x001f /* Source IRType. */
226#define IRCONV_DSTMASK 0x03e0 /* Dest. IRType (also in ir->t). */ 240#define IRCONV_DSTMASK 0x03e0 /* Dest. IRType (also in ir->t). */
227#define IRCONV_DSH 5 241#define IRCONV_DSH 5
228#define IRCONV_NUM_INT ((IRT_NUM<<IRCONV_DSH)|IRT_INT) 242#define IRCONV_NUM_INT ((IRT_NUM<<IRCONV_DSH)|IRT_INT)
229#define IRCONV_INT_NUM ((IRT_INT<<IRCONV_DSH)|IRT_NUM) 243#define IRCONV_INT_NUM ((IRT_INT<<IRCONV_DSH)|IRT_NUM)
230#define IRCONV_TRUNC 0x0400 /* Truncate number to integer. */
231#define IRCONV_SEXT 0x0800 /* Sign-extend integer to integer. */ 244#define IRCONV_SEXT 0x0800 /* Sign-extend integer to integer. */
232#define IRCONV_MODEMASK 0x0fff 245#define IRCONV_MODEMASK 0x0fff
233#define IRCONV_CONVMASK 0xf000 246#define IRCONV_CONVMASK 0xf000
@@ -238,6 +251,11 @@ IRFLDEF(FLENUM)
238#define IRCONV_INDEX (2<<IRCONV_CSH) /* Check + special backprop rules. */ 251#define IRCONV_INDEX (2<<IRCONV_CSH) /* Check + special backprop rules. */
239#define IRCONV_CHECK (3<<IRCONV_CSH) /* Number checked for integerness. */ 252#define IRCONV_CHECK (3<<IRCONV_CSH) /* Number checked for integerness. */
240 253
254/* TOSTR mode, stored in op2. */
255#define IRTOSTR_INT 0 /* Convert integer to string. */
256#define IRTOSTR_NUM 1 /* Convert number to string. */
257#define IRTOSTR_CHAR 2 /* Convert char value to string. */
258
241/* -- IR operands --------------------------------------------------------- */ 259/* -- IR operands --------------------------------------------------------- */
242 260
243/* IR operand mode (2 bit). */ 261/* IR operand mode (2 bit). */
@@ -276,7 +294,9 @@ LJ_DATA const uint8_t lj_ir_mode[IR__MAX+1];
276 294
277/* -- IR instruction types ------------------------------------------------ */ 295/* -- IR instruction types ------------------------------------------------ */
278 296
279/* Map of itypes to non-negative numbers. ORDER LJ_T. 297#define IRTSIZE_PGC (LJ_GC64 ? 8 : 4)
298
299/* Map of itypes to non-negative numbers and their sizes. ORDER LJ_T.
280** LJ_TUPVAL/LJ_TTRACE never appear in a TValue. Use these itypes for 300** LJ_TUPVAL/LJ_TTRACE never appear in a TValue. Use these itypes for
281** IRT_P32 and IRT_P64, which never escape the IR. 301** IRT_P32 and IRT_P64, which never escape the IR.
282** The various integers are only used in the IR and can only escape to 302** The various integers are only used in the IR and can only escape to
@@ -284,12 +304,13 @@ LJ_DATA const uint8_t lj_ir_mode[IR__MAX+1];
284** contiguous and next to IRT_NUM (see the typerange macros below). 304** contiguous and next to IRT_NUM (see the typerange macros below).
285*/ 305*/
286#define IRTDEF(_) \ 306#define IRTDEF(_) \
287 _(NIL, 4) _(FALSE, 4) _(TRUE, 4) _(LIGHTUD, LJ_64 ? 8 : 4) _(STR, 4) \ 307 _(NIL, 4) _(FALSE, 4) _(TRUE, 4) _(LIGHTUD, LJ_64 ? 8 : 4) \
288 _(P32, 4) _(THREAD, 4) _(PROTO, 4) _(FUNC, 4) _(P64, 8) _(CDATA, 4) \ 308 _(STR, IRTSIZE_PGC) _(P32, 4) _(THREAD, IRTSIZE_PGC) _(PROTO, IRTSIZE_PGC) \
289 _(TAB, 4) _(UDATA, 4) \ 309 _(FUNC, IRTSIZE_PGC) _(P64, 8) _(CDATA, IRTSIZE_PGC) _(TAB, IRTSIZE_PGC) \
310 _(UDATA, IRTSIZE_PGC) \
290 _(FLOAT, 4) _(NUM, 8) _(I8, 1) _(U8, 1) _(I16, 2) _(U16, 2) \ 311 _(FLOAT, 4) _(NUM, 8) _(I8, 1) _(U8, 1) _(I16, 2) _(U16, 2) \
291 _(INT, 4) _(U32, 4) _(I64, 8) _(U64, 8) \ 312 _(INT, 4) _(U32, 4) _(I64, 8) _(U64, 8) \
292 _(SOFTFP, 4) /* There is room for 9 more types. */ 313 _(SOFTFP, 4) /* There is room for 8 more types. */
293 314
294/* IR result type and flags (8 bit). */ 315/* IR result type and flags (8 bit). */
295typedef enum { 316typedef enum {
@@ -300,6 +321,8 @@ IRTDEF(IRTENUM)
300 321
301 /* Native pointer type and the corresponding integer type. */ 322 /* Native pointer type and the corresponding integer type. */
302 IRT_PTR = LJ_64 ? IRT_P64 : IRT_P32, 323 IRT_PTR = LJ_64 ? IRT_P64 : IRT_P32,
324 IRT_PGC = LJ_GC64 ? IRT_P64 : IRT_P32,
325 IRT_IGC = LJ_GC64 ? IRT_I64 : IRT_INT,
303 IRT_INTP = LJ_64 ? IRT_I64 : IRT_INT, 326 IRT_INTP = LJ_64 ? IRT_I64 : IRT_INT,
304 IRT_UINTP = LJ_64 ? IRT_U64 : IRT_U32, 327 IRT_UINTP = LJ_64 ? IRT_U64 : IRT_U32,
305 328
@@ -353,7 +376,12 @@ typedef struct IRType1 { uint8_t irt; } IRType1;
353#define irt_isaddr(t) (irt_typerange((t), IRT_LIGHTUD, IRT_UDATA)) 376#define irt_isaddr(t) (irt_typerange((t), IRT_LIGHTUD, IRT_UDATA))
354#define irt_isint64(t) (irt_typerange((t), IRT_I64, IRT_U64)) 377#define irt_isint64(t) (irt_typerange((t), IRT_I64, IRT_U64))
355 378
356#if LJ_64 379#if LJ_GC64
380#define IRT_IS64 \
381 ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)|(1u<<IRT_P64)|\
382 (1u<<IRT_LIGHTUD)|(1u<<IRT_STR)|(1u<<IRT_THREAD)|(1u<<IRT_PROTO)|\
383 (1u<<IRT_FUNC)|(1u<<IRT_CDATA)|(1u<<IRT_TAB)|(1u<<IRT_UDATA))
384#elif LJ_64
357#define IRT_IS64 \ 385#define IRT_IS64 \
358 ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)|(1u<<IRT_P64)|(1u<<IRT_LIGHTUD)) 386 ((1u<<IRT_NUM)|(1u<<IRT_I64)|(1u<<IRT_U64)|(1u<<IRT_P64)|(1u<<IRT_LIGHTUD))
359#else 387#else
@@ -374,7 +402,7 @@ static LJ_AINLINE IRType itype2irt(const TValue *tv)
374 return IRT_INT; 402 return IRT_INT;
375 else if (tvisnum(tv)) 403 else if (tvisnum(tv))
376 return IRT_NUM; 404 return IRT_NUM;
377#if LJ_64 405#if LJ_64 && !LJ_GC64
378 else if (tvislightud(tv)) 406 else if (tvislightud(tv))
379 return IRT_LIGHTUD; 407 return IRT_LIGHTUD;
380#endif 408#endif
@@ -384,7 +412,7 @@ static LJ_AINLINE IRType itype2irt(const TValue *tv)
384 412
385static LJ_AINLINE uint32_t irt_toitype_(IRType t) 413static LJ_AINLINE uint32_t irt_toitype_(IRType t)
386{ 414{
387 lua_assert(!LJ_64 || t != IRT_LIGHTUD); 415 lua_assert(!LJ_64 || LJ_GC64 || t != IRT_LIGHTUD);
388 if (LJ_DUALNUM && t > IRT_NUM) { 416 if (LJ_DUALNUM && t > IRT_NUM) {
389 return LJ_TISNUM; 417 return LJ_TISNUM;
390 } else { 418 } else {
@@ -464,6 +492,7 @@ typedef uint32_t TRef;
464#define tref_isnil(tr) (tref_istype((tr), IRT_NIL)) 492#define tref_isnil(tr) (tref_istype((tr), IRT_NIL))
465#define tref_isfalse(tr) (tref_istype((tr), IRT_FALSE)) 493#define tref_isfalse(tr) (tref_istype((tr), IRT_FALSE))
466#define tref_istrue(tr) (tref_istype((tr), IRT_TRUE)) 494#define tref_istrue(tr) (tref_istype((tr), IRT_TRUE))
495#define tref_islightud(tr) (tref_istype((tr), IRT_LIGHTUD))
467#define tref_isstr(tr) (tref_istype((tr), IRT_STR)) 496#define tref_isstr(tr) (tref_istype((tr), IRT_STR))
468#define tref_isfunc(tr) (tref_istype((tr), IRT_FUNC)) 497#define tref_isfunc(tr) (tref_istype((tr), IRT_FUNC))
469#define tref_iscdata(tr) (tref_istype((tr), IRT_CDATA)) 498#define tref_iscdata(tr) (tref_istype((tr), IRT_CDATA))
@@ -496,7 +525,9 @@ typedef uint32_t TRef;
496** +-------+-------+---+---+---+---+ 525** +-------+-------+---+---+---+---+
497** | op1 | op2 | t | o | r | s | 526** | op1 | op2 | t | o | r | s |
498** +-------+-------+---+---+---+---+ 527** +-------+-------+---+---+---+---+
499** | op12/i/gco | ot | prev | (alternative fields in union) 528** | op12/i/gco32 | ot | prev | (alternative fields in union)
529** +-------+-------+---+---+---+---+
530** | TValue/gco64 | (2nd IR slot for 64 bit constants)
500** +---------------+-------+-------+ 531** +---------------+-------+-------+
501** 32 16 16 532** 32 16 16
502** 533**
@@ -524,21 +555,27 @@ typedef union IRIns {
524 ) 555 )
525 }; 556 };
526 int32_t i; /* 32 bit signed integer literal (overlaps op12). */ 557 int32_t i; /* 32 bit signed integer literal (overlaps op12). */
527 GCRef gcr; /* GCobj constant (overlaps op12). */ 558 GCRef gcr; /* GCobj constant (overlaps op12 or entire slot). */
528 MRef ptr; /* Pointer constant (overlaps op12). */ 559 MRef ptr; /* Pointer constant (overlaps op12 or entire slot). */
560 TValue tv; /* TValue constant (overlaps entire slot). */
529} IRIns; 561} IRIns;
530 562
531#define ir_kgc(ir) check_exp((ir)->o == IR_KGC, gcref((ir)->gcr)) 563#define ir_kgc(ir) check_exp((ir)->o == IR_KGC, gcref((ir)[LJ_GC64].gcr))
532#define ir_kstr(ir) (gco2str(ir_kgc((ir)))) 564#define ir_kstr(ir) (gco2str(ir_kgc((ir))))
533#define ir_ktab(ir) (gco2tab(ir_kgc((ir)))) 565#define ir_ktab(ir) (gco2tab(ir_kgc((ir))))
534#define ir_kfunc(ir) (gco2func(ir_kgc((ir)))) 566#define ir_kfunc(ir) (gco2func(ir_kgc((ir))))
535#define ir_kcdata(ir) (gco2cd(ir_kgc((ir)))) 567#define ir_kcdata(ir) (gco2cd(ir_kgc((ir))))
536#define ir_knum(ir) check_exp((ir)->o == IR_KNUM, mref((ir)->ptr, cTValue)) 568#define ir_knum(ir) check_exp((ir)->o == IR_KNUM, &(ir)[1].tv)
537#define ir_kint64(ir) check_exp((ir)->o == IR_KINT64, mref((ir)->ptr,cTValue)) 569#define ir_kint64(ir) check_exp((ir)->o == IR_KINT64, &(ir)[1].tv)
538#define ir_k64(ir) \ 570#define ir_k64(ir) \
539 check_exp((ir)->o == IR_KNUM || (ir)->o == IR_KINT64, mref((ir)->ptr,cTValue)) 571 check_exp((ir)->o == IR_KNUM || (ir)->o == IR_KINT64 || \
572 (LJ_GC64 && \
573 ((ir)->o == IR_KGC || \
574 (ir)->o == IR_KPTR || (ir)->o == IR_KKPTR)), \
575 &(ir)[1].tv)
540#define ir_kptr(ir) \ 576#define ir_kptr(ir) \
541 check_exp((ir)->o == IR_KPTR || (ir)->o == IR_KKPTR, mref((ir)->ptr, void)) 577 check_exp((ir)->o == IR_KPTR || (ir)->o == IR_KKPTR, \
578 mref((ir)[LJ_GC64].ptr, void))
542 579
543/* A store or any other op with a non-weak guard has a side-effect. */ 580/* A store or any other op with a non-weak guard has a side-effect. */
544static LJ_AINLINE int ir_sideeff(IRIns *ir) 581static LJ_AINLINE int ir_sideeff(IRIns *ir)
diff --git a/src/lj_ircall.h b/src/lj_ircall.h
index 44afde3a..973c36e6 100644
--- a/src/lj_ircall.h
+++ b/src/lj_ircall.h
@@ -16,7 +16,7 @@ typedef struct CCallInfo {
16 uint32_t flags; /* Number of arguments and flags. */ 16 uint32_t flags; /* Number of arguments and flags. */
17} CCallInfo; 17} CCallInfo;
18 18
19#define CCI_NARGS(ci) ((ci)->flags & 0xff) /* Extract # of args. */ 19#define CCI_NARGS(ci) ((ci)->flags & 0xff) /* # of args. */
20#define CCI_NARGS_MAX 32 /* Max. # of args. */ 20#define CCI_NARGS_MAX 32 /* Max. # of args. */
21 21
22#define CCI_OTSHIFT 16 22#define CCI_OTSHIFT 16
@@ -25,6 +25,7 @@ typedef struct CCallInfo {
25#define CCI_OP(ci) ((ci)->flags >> CCI_OPSHIFT) /* Get op. */ 25#define CCI_OP(ci) ((ci)->flags >> CCI_OPSHIFT) /* Get op. */
26 26
27#define CCI_CALL_N (IR_CALLN << CCI_OPSHIFT) 27#define CCI_CALL_N (IR_CALLN << CCI_OPSHIFT)
28#define CCI_CALL_A (IR_CALLA << CCI_OPSHIFT)
28#define CCI_CALL_L (IR_CALLL << CCI_OPSHIFT) 29#define CCI_CALL_L (IR_CALLL << CCI_OPSHIFT)
29#define CCI_CALL_S (IR_CALLS << CCI_OPSHIFT) 30#define CCI_CALL_S (IR_CALLS << CCI_OPSHIFT)
30#define CCI_CALL_FN (CCI_CALL_N|CCI_CC_FASTCALL) 31#define CCI_CALL_FN (CCI_CALL_N|CCI_CC_FASTCALL)
@@ -45,6 +46,17 @@ typedef struct CCallInfo {
45#define CCI_CC_FASTCALL 0x2000 /* Fastcall calling convention. */ 46#define CCI_CC_FASTCALL 0x2000 /* Fastcall calling convention. */
46#define CCI_CC_STDCALL 0x3000 /* Stdcall calling convention. */ 47#define CCI_CC_STDCALL 0x3000 /* Stdcall calling convention. */
47 48
49/* Extra args for SOFTFP, SPLIT 64 bit. */
50#define CCI_XARGS_SHIFT 14
51#define CCI_XARGS(ci) (((ci)->flags >> CCI_XARGS_SHIFT) & 3)
52#define CCI_XA (1u << CCI_XARGS_SHIFT)
53
54#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
55#define CCI_XNARGS(ci) (CCI_NARGS((ci)) + CCI_XARGS((ci)))
56#else
57#define CCI_XNARGS(ci) CCI_NARGS((ci))
58#endif
59
48/* Helpers for conditional function definitions. */ 60/* Helpers for conditional function definitions. */
49#define IRCALLCOND_ANY(x) x 61#define IRCALLCOND_ANY(x) x
50 62
@@ -66,7 +78,13 @@ typedef struct CCallInfo {
66#define IRCALLCOND_SOFTFP_FFI(x) NULL 78#define IRCALLCOND_SOFTFP_FFI(x) NULL
67#endif 79#endif
68 80
69#define LJ_NEED_FP64 (LJ_TARGET_ARM || LJ_TARGET_PPC || LJ_TARGET_MIPS) 81#if LJ_SOFTFP && LJ_TARGET_MIPS32
82#define IRCALLCOND_SOFTFP_MIPS(x) x
83#else
84#define IRCALLCOND_SOFTFP_MIPS(x) NULL
85#endif
86
87#define LJ_NEED_FP64 (LJ_TARGET_ARM || LJ_TARGET_PPC || LJ_TARGET_MIPS32)
70 88
71#if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64) 89#if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64)
72#define IRCALLCOND_FP64_FFI(x) x 90#define IRCALLCOND_FP64_FFI(x) x
@@ -87,56 +105,82 @@ typedef struct CCallInfo {
87#endif 105#endif
88 106
89#if LJ_SOFTFP 107#if LJ_SOFTFP
90#define ARG1_FP 2 /* Treat as 2 32 bit arguments. */ 108#define XA_FP CCI_XA
109#define XA2_FP (CCI_XA+CCI_XA)
91#else 110#else
92#define ARG1_FP 1 111#define XA_FP 0
112#define XA2_FP 0
93#endif 113#endif
94 114
95#if LJ_32 115#if LJ_32
96#define ARG2_64 4 /* Treat as 4 32 bit arguments. */ 116#define XA_64 CCI_XA
117#define XA2_64 (CCI_XA+CCI_XA)
97#else 118#else
98#define ARG2_64 2 119#define XA_64 0
120#define XA2_64 0
99#endif 121#endif
100 122
101/* Function definitions for CALL* instructions. */ 123/* Function definitions for CALL* instructions. */
102#define IRCALLDEF(_) \ 124#define IRCALLDEF(_) \
103 _(ANY, lj_str_cmp, 2, FN, INT, CCI_NOFPRCLOBBER) \ 125 _(ANY, lj_str_cmp, 2, FN, INT, CCI_NOFPRCLOBBER) \
126 _(ANY, lj_str_find, 4, N, PGC, 0) \
104 _(ANY, lj_str_new, 3, S, STR, CCI_L) \ 127 _(ANY, lj_str_new, 3, S, STR, CCI_L) \
105 _(ANY, lj_strscan_num, 2, FN, INT, 0) \ 128 _(ANY, lj_strscan_num, 2, FN, INT, 0) \
106 _(ANY, lj_str_fromint, 2, FN, STR, CCI_L) \ 129 _(ANY, lj_strfmt_int, 2, FN, STR, CCI_L) \
107 _(ANY, lj_str_fromnum, 2, FN, STR, CCI_L) \ 130 _(ANY, lj_strfmt_num, 2, FN, STR, CCI_L) \
131 _(ANY, lj_strfmt_char, 2, FN, STR, CCI_L) \
132 _(ANY, lj_strfmt_putint, 2, FL, PGC, 0) \
133 _(ANY, lj_strfmt_putnum, 2, FL, PGC, 0) \
134 _(ANY, lj_strfmt_putquoted, 2, FL, PGC, 0) \
135 _(ANY, lj_strfmt_putfxint, 3, L, PGC, XA_64) \
136 _(ANY, lj_strfmt_putfnum_int, 3, L, PGC, XA_FP) \
137 _(ANY, lj_strfmt_putfnum_uint, 3, L, PGC, XA_FP) \
138 _(ANY, lj_strfmt_putfnum, 3, L, PGC, XA_FP) \
139 _(ANY, lj_strfmt_putfstr, 3, L, PGC, 0) \
140 _(ANY, lj_strfmt_putfchar, 3, L, PGC, 0) \
141 _(ANY, lj_buf_putmem, 3, S, PGC, 0) \
142 _(ANY, lj_buf_putstr, 2, FL, PGC, 0) \
143 _(ANY, lj_buf_putchar, 2, FL, PGC, 0) \
144 _(ANY, lj_buf_putstr_reverse, 2, FL, PGC, 0) \
145 _(ANY, lj_buf_putstr_lower, 2, FL, PGC, 0) \
146 _(ANY, lj_buf_putstr_upper, 2, FL, PGC, 0) \
147 _(ANY, lj_buf_putstr_rep, 3, L, PGC, 0) \
148 _(ANY, lj_buf_puttab, 5, L, PGC, 0) \
149 _(ANY, lj_buf_tostr, 1, FL, STR, 0) \
150 _(ANY, lj_tab_new_ah, 3, A, TAB, CCI_L) \
108 _(ANY, lj_tab_new1, 2, FS, TAB, CCI_L) \ 151 _(ANY, lj_tab_new1, 2, FS, TAB, CCI_L) \
109 _(ANY, lj_tab_dup, 2, FS, TAB, CCI_L) \ 152 _(ANY, lj_tab_dup, 2, FS, TAB, CCI_L) \
110 _(ANY, lj_tab_newkey, 3, S, P32, CCI_L) \ 153 _(ANY, lj_tab_clear, 1, FS, NIL, 0) \
154 _(ANY, lj_tab_newkey, 3, S, PGC, CCI_L) \
111 _(ANY, lj_tab_len, 1, FL, INT, 0) \ 155 _(ANY, lj_tab_len, 1, FL, INT, 0) \
112 _(ANY, lj_gc_step_jit, 2, FS, NIL, CCI_L) \ 156 _(ANY, lj_gc_step_jit, 2, FS, NIL, CCI_L) \
113 _(ANY, lj_gc_barrieruv, 2, FS, NIL, 0) \ 157 _(ANY, lj_gc_barrieruv, 2, FS, NIL, 0) \
114 _(ANY, lj_mem_newgco, 2, FS, P32, CCI_L) \ 158 _(ANY, lj_mem_newgco, 2, FS, PGC, CCI_L) \
115 _(ANY, lj_math_random_step, 1, FS, NUM, CCI_CASTU64) \ 159 _(ANY, lj_math_random_step, 1, FS, NUM, CCI_CASTU64) \
116 _(ANY, lj_vm_modi, 2, FN, INT, 0) \ 160 _(ANY, lj_vm_modi, 2, FN, INT, 0) \
117 _(ANY, sinh, ARG1_FP, N, NUM, 0) \ 161 _(ANY, sinh, 1, N, NUM, XA_FP) \
118 _(ANY, cosh, ARG1_FP, N, NUM, 0) \ 162 _(ANY, cosh, 1, N, NUM, XA_FP) \
119 _(ANY, tanh, ARG1_FP, N, NUM, 0) \ 163 _(ANY, tanh, 1, N, NUM, XA_FP) \
120 _(ANY, fputc, 2, S, INT, 0) \ 164 _(ANY, fputc, 2, S, INT, 0) \
121 _(ANY, fwrite, 4, S, INT, 0) \ 165 _(ANY, fwrite, 4, S, INT, 0) \
122 _(ANY, fflush, 1, S, INT, 0) \ 166 _(ANY, fflush, 1, S, INT, 0) \
123 /* ORDER FPM */ \ 167 /* ORDER FPM */ \
124 _(FPMATH, lj_vm_floor, ARG1_FP, N, NUM, 0) \ 168 _(FPMATH, lj_vm_floor, 1, N, NUM, XA_FP) \
125 _(FPMATH, lj_vm_ceil, ARG1_FP, N, NUM, 0) \ 169 _(FPMATH, lj_vm_ceil, 1, N, NUM, XA_FP) \
126 _(FPMATH, lj_vm_trunc, ARG1_FP, N, NUM, 0) \ 170 _(FPMATH, lj_vm_trunc, 1, N, NUM, XA_FP) \
127 _(FPMATH, sqrt, ARG1_FP, N, NUM, 0) \ 171 _(FPMATH, sqrt, 1, N, NUM, XA_FP) \
128 _(FPMATH, exp, ARG1_FP, N, NUM, 0) \ 172 _(ANY, exp, 1, N, NUM, XA_FP) \
129 _(FPMATH, lj_vm_exp2, ARG1_FP, N, NUM, 0) \ 173 _(ANY, lj_vm_exp2, 1, N, NUM, XA_FP) \
130 _(FPMATH, log, ARG1_FP, N, NUM, 0) \ 174 _(ANY, log, 1, N, NUM, XA_FP) \
131 _(FPMATH, lj_vm_log2, ARG1_FP, N, NUM, 0) \ 175 _(ANY, lj_vm_log2, 1, N, NUM, XA_FP) \
132 _(FPMATH, log10, ARG1_FP, N, NUM, 0) \ 176 _(ANY, log10, 1, N, NUM, XA_FP) \
133 _(FPMATH, sin, ARG1_FP, N, NUM, 0) \ 177 _(ANY, sin, 1, N, NUM, XA_FP) \
134 _(FPMATH, cos, ARG1_FP, N, NUM, 0) \ 178 _(ANY, cos, 1, N, NUM, XA_FP) \
135 _(FPMATH, tan, ARG1_FP, N, NUM, 0) \ 179 _(ANY, tan, 1, N, NUM, XA_FP) \
136 _(FPMATH, lj_vm_powi, ARG1_FP+1, N, NUM, 0) \ 180 _(ANY, lj_vm_powi, 2, N, NUM, XA_FP) \
137 _(FPMATH, pow, ARG1_FP*2, N, NUM, 0) \ 181 _(ANY, pow, 2, N, NUM, XA2_FP) \
138 _(FPMATH, atan2, ARG1_FP*2, N, NUM, 0) \ 182 _(ANY, atan2, 2, N, NUM, XA2_FP) \
139 _(FPMATH, ldexp, ARG1_FP+1, N, NUM, 0) \ 183 _(ANY, ldexp, 2, N, NUM, XA_FP) \
140 _(SOFTFP, lj_vm_tobit, 2, N, INT, 0) \ 184 _(SOFTFP, lj_vm_tobit, 2, N, INT, 0) \
141 _(SOFTFP, softfp_add, 4, N, NUM, 0) \ 185 _(SOFTFP, softfp_add, 4, N, NUM, 0) \
142 _(SOFTFP, softfp_sub, 4, N, NUM, 0) \ 186 _(SOFTFP, softfp_sub, 4, N, NUM, 0) \
@@ -145,6 +189,8 @@ typedef struct CCallInfo {
145 _(SOFTFP, softfp_cmp, 4, N, NIL, 0) \ 189 _(SOFTFP, softfp_cmp, 4, N, NIL, 0) \
146 _(SOFTFP, softfp_i2d, 1, N, NUM, 0) \ 190 _(SOFTFP, softfp_i2d, 1, N, NUM, 0) \
147 _(SOFTFP, softfp_d2i, 2, N, INT, 0) \ 191 _(SOFTFP, softfp_d2i, 2, N, INT, 0) \
192 _(SOFTFP_MIPS, lj_vm_sfmin, 4, N, NUM, 0) \
193 _(SOFTFP_MIPS, lj_vm_sfmax, 4, N, NUM, 0) \
148 _(SOFTFP_FFI, softfp_ui2d, 1, N, NUM, 0) \ 194 _(SOFTFP_FFI, softfp_ui2d, 1, N, NUM, 0) \
149 _(SOFTFP_FFI, softfp_f2d, 1, N, NUM, 0) \ 195 _(SOFTFP_FFI, softfp_f2d, 1, N, NUM, 0) \
150 _(SOFTFP_FFI, softfp_d2ui, 2, N, INT, 0) \ 196 _(SOFTFP_FFI, softfp_d2ui, 2, N, INT, 0) \
@@ -153,26 +199,32 @@ typedef struct CCallInfo {
153 _(SOFTFP_FFI, softfp_ui2f, 1, N, FLOAT, 0) \ 199 _(SOFTFP_FFI, softfp_ui2f, 1, N, FLOAT, 0) \
154 _(SOFTFP_FFI, softfp_f2i, 1, N, INT, 0) \ 200 _(SOFTFP_FFI, softfp_f2i, 1, N, INT, 0) \
155 _(SOFTFP_FFI, softfp_f2ui, 1, N, INT, 0) \ 201 _(SOFTFP_FFI, softfp_f2ui, 1, N, INT, 0) \
156 _(FP64_FFI, fp64_l2d, 2, N, NUM, 0) \ 202 _(FP64_FFI, fp64_l2d, 1, N, NUM, XA_64) \
157 _(FP64_FFI, fp64_ul2d, 2, N, NUM, 0) \ 203 _(FP64_FFI, fp64_ul2d, 1, N, NUM, XA_64) \
158 _(FP64_FFI, fp64_l2f, 2, N, FLOAT, 0) \ 204 _(FP64_FFI, fp64_l2f, 1, N, FLOAT, XA_64) \
159 _(FP64_FFI, fp64_ul2f, 2, N, FLOAT, 0) \ 205 _(FP64_FFI, fp64_ul2f, 1, N, FLOAT, XA_64) \
160 _(FP64_FFI, fp64_d2l, ARG1_FP, N, I64, 0) \ 206 _(FP64_FFI, fp64_d2l, 1, N, I64, XA_FP) \
161 _(FP64_FFI, fp64_d2ul, ARG1_FP, N, U64, 0) \ 207 _(FP64_FFI, fp64_d2ul, 1, N, U64, XA_FP) \
162 _(FP64_FFI, fp64_f2l, 1, N, I64, 0) \ 208 _(FP64_FFI, fp64_f2l, 1, N, I64, 0) \
163 _(FP64_FFI, fp64_f2ul, 1, N, U64, 0) \ 209 _(FP64_FFI, fp64_f2ul, 1, N, U64, 0) \
164 _(FFI, lj_carith_divi64, ARG2_64, N, I64, CCI_NOFPRCLOBBER) \ 210 _(FFI, lj_carith_divi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \
165 _(FFI, lj_carith_divu64, ARG2_64, N, U64, CCI_NOFPRCLOBBER) \ 211 _(FFI, lj_carith_divu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \
166 _(FFI, lj_carith_modi64, ARG2_64, N, I64, CCI_NOFPRCLOBBER) \ 212 _(FFI, lj_carith_modi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \
167 _(FFI, lj_carith_modu64, ARG2_64, N, U64, CCI_NOFPRCLOBBER) \ 213 _(FFI, lj_carith_modu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \
168 _(FFI, lj_carith_powi64, ARG2_64, N, I64, CCI_NOFPRCLOBBER) \ 214 _(FFI, lj_carith_powi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \
169 _(FFI, lj_carith_powu64, ARG2_64, N, U64, CCI_NOFPRCLOBBER) \ 215 _(FFI, lj_carith_powu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \
170 _(FFI, lj_cdata_setfin, 2, FN, P32, CCI_L) \ 216 _(FFI, lj_cdata_newv, 4, S, CDATA, CCI_L) \
171 _(FFI, strlen, 1, L, INTP, 0) \ 217 _(FFI, lj_cdata_setfin, 4, S, NIL, CCI_L) \
172 _(FFI, memcpy, 3, S, PTR, 0) \ 218 _(FFI, strlen, 1, L, INTP, 0) \
173 _(FFI, memset, 3, S, PTR, 0) \ 219 _(FFI, memcpy, 3, S, PTR, 0) \
174 _(FFI, lj_vm_errno, 0, S, INT, CCI_NOFPRCLOBBER) \ 220 _(FFI, memset, 3, S, PTR, 0) \
175 _(FFI32, lj_carith_mul64, ARG2_64, N, I64, CCI_NOFPRCLOBBER) 221 _(FFI, lj_vm_errno, 0, S, INT, CCI_NOFPRCLOBBER) \
222 _(FFI32, lj_carith_mul64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \
223 _(FFI32, lj_carith_shl64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \
224 _(FFI32, lj_carith_shr64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \
225 _(FFI32, lj_carith_sar64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \
226 _(FFI32, lj_carith_rol64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \
227 _(FFI32, lj_carith_ror64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \
176 \ 228 \
177 /* End of list. */ 229 /* End of list. */
178 230
@@ -220,6 +272,22 @@ LJ_DATA const CCallInfo lj_ir_callinfo[IRCALL__MAX+1];
220#define fp64_f2l __aeabi_f2lz 272#define fp64_f2l __aeabi_f2lz
221#define fp64_f2ul __aeabi_f2ulz 273#define fp64_f2ul __aeabi_f2ulz
222#endif 274#endif
275#elif LJ_TARGET_MIPS
276#define softfp_add __adddf3
277#define softfp_sub __subdf3
278#define softfp_mul __muldf3
279#define softfp_div __divdf3
280#define softfp_cmp __ledf2
281#define softfp_i2d __floatsidf
282#define softfp_d2i __fixdfsi
283#define softfp_ui2d __floatunsidf
284#define softfp_f2d __extendsfdf2
285#define softfp_d2ui __fixunsdfsi
286#define softfp_d2f __truncdfsf2
287#define softfp_i2f __floatsisf
288#define softfp_ui2f __floatunsisf
289#define softfp_f2i __fixsfsi
290#define softfp_f2ui __fixunssfsi
223#else 291#else
224#error "Missing soft-float definitions for target architecture" 292#error "Missing soft-float definitions for target architecture"
225#endif 293#endif
@@ -240,6 +308,10 @@ extern float softfp_ui2f(uint32_t a);
240extern int32_t softfp_f2i(float a); 308extern int32_t softfp_f2i(float a);
241extern uint32_t softfp_f2ui(float a); 309extern uint32_t softfp_f2ui(float a);
242#endif 310#endif
311#if LJ_TARGET_MIPS
312extern double lj_vm_sfmin(double a, double b);
313extern double lj_vm_sfmax(double a, double b);
314#endif
243#endif 315#endif
244 316
245#if LJ_HASFFI && LJ_NEED_FP64 && !(LJ_TARGET_ARM && LJ_SOFTFP) 317#if LJ_HASFFI && LJ_NEED_FP64 && !(LJ_TARGET_ARM && LJ_SOFTFP)
diff --git a/src/lj_iropt.h b/src/lj_iropt.h
index b5081e06..73aef0ef 100644
--- a/src/lj_iropt.h
+++ b/src/lj_iropt.h
@@ -36,11 +36,11 @@ static LJ_AINLINE IRRef lj_ir_nextins(jit_State *J)
36 return ref; 36 return ref;
37} 37}
38 38
39LJ_FUNC TRef lj_ir_ggfload(jit_State *J, IRType t, uintptr_t ofs);
40
39/* Interning of constants. */ 41/* Interning of constants. */
40LJ_FUNC TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k); 42LJ_FUNC TRef LJ_FASTCALL lj_ir_kint(jit_State *J, int32_t k);
41LJ_FUNC void lj_ir_k64_freeall(jit_State *J); 43LJ_FUNC TRef lj_ir_k64(jit_State *J, IROp op, uint64_t u64);
42LJ_FUNC TRef lj_ir_k64(jit_State *J, IROp op, cTValue *tv);
43LJ_FUNC cTValue *lj_ir_k64_find(jit_State *J, uint64_t u64);
44LJ_FUNC TRef lj_ir_knum_u64(jit_State *J, uint64_t u64); 44LJ_FUNC TRef lj_ir_knum_u64(jit_State *J, uint64_t u64);
45LJ_FUNC TRef lj_ir_knumint(jit_State *J, lua_Number n); 45LJ_FUNC TRef lj_ir_knumint(jit_State *J, lua_Number n);
46LJ_FUNC TRef lj_ir_kint64(jit_State *J, uint64_t u64); 46LJ_FUNC TRef lj_ir_kint64(jit_State *J, uint64_t u64);
@@ -48,6 +48,7 @@ LJ_FUNC TRef lj_ir_kgc(jit_State *J, GCobj *o, IRType t);
48LJ_FUNC TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr); 48LJ_FUNC TRef lj_ir_kptr_(jit_State *J, IROp op, void *ptr);
49LJ_FUNC TRef lj_ir_knull(jit_State *J, IRType t); 49LJ_FUNC TRef lj_ir_knull(jit_State *J, IRType t);
50LJ_FUNC TRef lj_ir_kslot(jit_State *J, TRef key, IRRef slot); 50LJ_FUNC TRef lj_ir_kslot(jit_State *J, TRef key, IRRef slot);
51LJ_FUNC TRef lj_ir_ktrace(jit_State *J);
51 52
52#if LJ_64 53#if LJ_64
53#define lj_ir_kintp(J, k) lj_ir_kint64(J, (uint64_t)(k)) 54#define lj_ir_kintp(J, k) lj_ir_kint64(J, (uint64_t)(k))
@@ -74,8 +75,8 @@ static LJ_AINLINE TRef lj_ir_knum(jit_State *J, lua_Number n)
74#define lj_ir_knum_tobit(J) lj_ir_knum_u64(J, U64x(43380000,00000000)) 75#define lj_ir_knum_tobit(J) lj_ir_knum_u64(J, U64x(43380000,00000000))
75 76
76/* Special 128 bit SIMD constants. */ 77/* Special 128 bit SIMD constants. */
77#define lj_ir_knum_abs(J) lj_ir_k64(J, IR_KNUM, LJ_KSIMD(J, LJ_KSIMD_ABS)) 78#define lj_ir_ksimd(J, idx) \
78#define lj_ir_knum_neg(J) lj_ir_k64(J, IR_KNUM, LJ_KSIMD(J, LJ_KSIMD_NEG)) 79 lj_ir_ggfload(J, IRT_NUM, (uintptr_t)LJ_KSIMD(J, idx) - (uintptr_t)J2GG(J))
79 80
80/* Access to constants. */ 81/* Access to constants. */
81LJ_FUNC void lj_ir_kvalue(lua_State *L, TValue *tv, const IRIns *ir); 82LJ_FUNC void lj_ir_kvalue(lua_State *L, TValue *tv, const IRIns *ir);
diff --git a/src/lj_jit.h b/src/lj_jit.h
index a2e8fd92..92054e3d 100644
--- a/src/lj_jit.h
+++ b/src/lj_jit.h
@@ -14,18 +14,16 @@
14 14
15/* CPU-specific JIT engine flags. */ 15/* CPU-specific JIT engine flags. */
16#if LJ_TARGET_X86ORX64 16#if LJ_TARGET_X86ORX64
17#define JIT_F_CMOV 0x00000010 17#define JIT_F_SSE2 0x00000010
18#define JIT_F_SSE2 0x00000020 18#define JIT_F_SSE3 0x00000020
19#define JIT_F_SSE3 0x00000040 19#define JIT_F_SSE4_1 0x00000040
20#define JIT_F_SSE4_1 0x00000080 20#define JIT_F_PREFER_IMUL 0x00000080
21#define JIT_F_P4 0x00000100 21#define JIT_F_LEA_AGU 0x00000100
22#define JIT_F_PREFER_IMUL 0x00000200 22#define JIT_F_BMI2 0x00000200
23#define JIT_F_SPLIT_XMM 0x00000400
24#define JIT_F_LEA_AGU 0x00000800
25 23
26/* Names for the CPU-specific flags. Must match the order above. */ 24/* Names for the CPU-specific flags. Must match the order above. */
27#define JIT_F_CPU_FIRST JIT_F_CMOV 25#define JIT_F_CPU_FIRST JIT_F_SSE2
28#define JIT_F_CPUSTRING "\4CMOV\4SSE2\4SSE3\6SSE4.1\2P4\3AMD\2K8\4ATOM" 26#define JIT_F_CPUSTRING "\4SSE2\4SSE3\6SSE4.1\3AMD\4ATOM\4BMI2"
29#elif LJ_TARGET_ARM 27#elif LJ_TARGET_ARM
30#define JIT_F_ARMV6_ 0x00000010 28#define JIT_F_ARMV6_ 0x00000010
31#define JIT_F_ARMV6T2_ 0x00000020 29#define JIT_F_ARMV6T2_ 0x00000020
@@ -48,12 +46,16 @@
48#define JIT_F_CPU_FIRST JIT_F_SQRT 46#define JIT_F_CPU_FIRST JIT_F_SQRT
49#define JIT_F_CPUSTRING "\4SQRT\5ROUND" 47#define JIT_F_CPUSTRING "\4SQRT\5ROUND"
50#elif LJ_TARGET_MIPS 48#elif LJ_TARGET_MIPS
51#define JIT_F_MIPS32R2 0x00000010 49#define JIT_F_MIPSXXR2 0x00000010
52 50
53/* Names for the CPU-specific flags. Must match the order above. */ 51/* Names for the CPU-specific flags. Must match the order above. */
54#define JIT_F_CPU_FIRST JIT_F_MIPS32R2 52#define JIT_F_CPU_FIRST JIT_F_MIPSXXR2
53#if LJ_TARGET_MIPS32
55#define JIT_F_CPUSTRING "\010MIPS32R2" 54#define JIT_F_CPUSTRING "\010MIPS32R2"
56#else 55#else
56#define JIT_F_CPUSTRING "\010MIPS64R2"
57#endif
58#else
57#define JIT_F_CPU_FIRST 0 59#define JIT_F_CPU_FIRST 0
58#define JIT_F_CPUSTRING "" 60#define JIT_F_CPUSTRING ""
59#endif 61#endif
@@ -100,6 +102,7 @@
100 _(\012, maxirconst, 500) /* Max. # of IR constants of a trace. */ \ 102 _(\012, maxirconst, 500) /* Max. # of IR constants of a trace. */ \
101 _(\007, maxside, 100) /* Max. # of side traces of a root trace. */ \ 103 _(\007, maxside, 100) /* Max. # of side traces of a root trace. */ \
102 _(\007, maxsnap, 500) /* Max. # of snapshots for a trace. */ \ 104 _(\007, maxsnap, 500) /* Max. # of snapshots for a trace. */ \
105 _(\011, minstitch, 0) /* Min. # of IR ins for a stitched trace. */ \
103 \ 106 \
104 _(\007, hotloop, 56) /* # of iter. to detect a hot loop/call. */ \ 107 _(\007, hotloop, 56) /* # of iter. to detect a hot loop/call. */ \
105 _(\007, hotexit, 10) /* # of taken exits to start a side trace. */ \ 108 _(\007, hotexit, 10) /* # of taken exits to start a side trace. */ \
@@ -180,14 +183,26 @@ LJ_STATIC_ASSERT(SNAP_CONT == TREF_CONT);
180#define SNAP(slot, flags, ref) (((SnapEntry)(slot) << 24) + (flags) + (ref)) 183#define SNAP(slot, flags, ref) (((SnapEntry)(slot) << 24) + (flags) + (ref))
181#define SNAP_TR(slot, tr) \ 184#define SNAP_TR(slot, tr) \
182 (((SnapEntry)(slot) << 24) + ((tr) & (TREF_CONT|TREF_FRAME|TREF_REFMASK))) 185 (((SnapEntry)(slot) << 24) + ((tr) & (TREF_CONT|TREF_FRAME|TREF_REFMASK)))
186#if !LJ_FR2
183#define SNAP_MKPC(pc) ((SnapEntry)u32ptr(pc)) 187#define SNAP_MKPC(pc) ((SnapEntry)u32ptr(pc))
188#endif
184#define SNAP_MKFTSZ(ftsz) ((SnapEntry)(ftsz)) 189#define SNAP_MKFTSZ(ftsz) ((SnapEntry)(ftsz))
185#define snap_ref(sn) ((sn) & 0xffff) 190#define snap_ref(sn) ((sn) & 0xffff)
186#define snap_slot(sn) ((BCReg)((sn) >> 24)) 191#define snap_slot(sn) ((BCReg)((sn) >> 24))
187#define snap_isframe(sn) ((sn) & SNAP_FRAME) 192#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)) 193#define snap_setref(sn, ref) (((sn) & (0xffff0000&~SNAP_NORESTORE)) | (ref))
190 194
195static LJ_AINLINE const BCIns *snap_pc(SnapEntry *sn)
196{
197#if LJ_FR2
198 uint64_t pcbase;
199 memcpy(&pcbase, sn, sizeof(uint64_t));
200 return (const BCIns *)(pcbase >> 8);
201#else
202 return (const BCIns *)(uintptr_t)*sn;
203#endif
204}
205
191/* Snapshot and exit numbers. */ 206/* Snapshot and exit numbers. */
192typedef uint32_t SnapNo; 207typedef uint32_t SnapNo;
193typedef uint32_t ExitNo; 208typedef uint32_t ExitNo;
@@ -205,7 +220,8 @@ typedef enum {
205 LJ_TRLINK_UPREC, /* Up-recursion. */ 220 LJ_TRLINK_UPREC, /* Up-recursion. */
206 LJ_TRLINK_DOWNREC, /* Down-recursion. */ 221 LJ_TRLINK_DOWNREC, /* Down-recursion. */
207 LJ_TRLINK_INTERP, /* Fallback to interpreter. */ 222 LJ_TRLINK_INTERP, /* Fallback to interpreter. */
208 LJ_TRLINK_RETURN /* Return to interpreter. */ 223 LJ_TRLINK_RETURN, /* Return to interpreter. */
224 LJ_TRLINK_STITCH /* Trace stitching. */
209} TraceLink; 225} TraceLink;
210 226
211/* Trace object. */ 227/* Trace object. */
@@ -214,6 +230,9 @@ typedef struct GCtrace {
214 uint8_t topslot; /* Top stack slot already checked to be allocated. */ 230 uint8_t topslot; /* Top stack slot already checked to be allocated. */
215 uint8_t linktype; /* Type of link. */ 231 uint8_t linktype; /* Type of link. */
216 IRRef nins; /* Next IR instruction. Biased with REF_BIAS. */ 232 IRRef nins; /* Next IR instruction. Biased with REF_BIAS. */
233#if LJ_GC64
234 uint32_t unused_gc64;
235#endif
217 GCRef gclist; 236 GCRef gclist;
218 IRIns *ir; /* IR instructions/constants. Biased with REF_BIAS. */ 237 IRIns *ir; /* IR instructions/constants. Biased with REF_BIAS. */
219 IRRef nk; /* Lowest IR constant. Biased with REF_BIAS. */ 238 IRRef nk; /* Lowest IR constant. Biased with REF_BIAS. */
@@ -288,6 +307,16 @@ typedef struct ScEvEntry {
288 uint8_t dir; /* Direction. 1: +, 0: -. */ 307 uint8_t dir; /* Direction. 1: +, 0: -. */
289} ScEvEntry; 308} ScEvEntry;
290 309
310/* Reverse bytecode map (IRRef -> PC). Only for selected instructions. */
311typedef struct RBCHashEntry {
312 MRef pc; /* Bytecode PC. */
313 GCRef pt; /* Prototype. */
314 IRRef ref; /* IR reference. */
315} RBCHashEntry;
316
317/* Number of slots in the reverse bytecode hash table. Must be a power of 2. */
318#define RBCHASH_SLOTS 8
319
291/* 128 bit SIMD constants. */ 320/* 128 bit SIMD constants. */
292enum { 321enum {
293 LJ_KSIMD_ABS, 322 LJ_KSIMD_ABS,
@@ -295,6 +324,45 @@ enum {
295 LJ_KSIMD__MAX 324 LJ_KSIMD__MAX
296}; 325};
297 326
327enum {
328#if LJ_TARGET_X86ORX64
329 LJ_K64_TOBIT, /* 2^52 + 2^51 */
330 LJ_K64_2P64, /* 2^64 */
331 LJ_K64_M2P64, /* -2^64 */
332#if LJ_32
333 LJ_K64_M2P64_31, /* -2^64 or -2^31 */
334#else
335 LJ_K64_M2P64_31 = LJ_K64_M2P64,
336#endif
337#endif
338#if LJ_TARGET_MIPS
339 LJ_K64_2P31, /* 2^31 */
340#if LJ_64
341 LJ_K64_2P63, /* 2^63 */
342 LJ_K64_M2P64, /* -2^64 */
343#endif
344#endif
345 LJ_K64__MAX,
346};
347
348enum {
349#if LJ_TARGET_X86ORX64
350 LJ_K32_M2P64_31, /* -2^64 or -2^31 */
351#endif
352#if LJ_TARGET_PPC
353 LJ_K32_2P52_2P31, /* 2^52 + 2^31 */
354 LJ_K32_2P52, /* 2^52 */
355#endif
356#if LJ_TARGET_PPC || LJ_TARGET_MIPS
357 LJ_K32_2P31, /* 2^31 */
358#endif
359#if LJ_TARGET_MIPS64
360 LJ_K32_2P63, /* 2^63 */
361 LJ_K32_M2P64, /* -2^64 */
362#endif
363 LJ_K32__MAX
364};
365
298/* Get 16 byte aligned pointer to SIMD constant. */ 366/* Get 16 byte aligned pointer to SIMD constant. */
299#define LJ_KSIMD(J, n) \ 367#define LJ_KSIMD(J, n) \
300 ((TValue *)(((intptr_t)&J->ksimd[2*(n)] + 15) & ~(intptr_t)15)) 368 ((TValue *)(((intptr_t)&J->ksimd[2*(n)] + 15) & ~(intptr_t)15))
@@ -311,13 +379,14 @@ enum {
311/* Fold state is used to fold instructions on-the-fly. */ 379/* Fold state is used to fold instructions on-the-fly. */
312typedef struct FoldState { 380typedef struct FoldState {
313 IRIns ins; /* Currently emitted instruction. */ 381 IRIns ins; /* Currently emitted instruction. */
314 IRIns left; /* Instruction referenced by left operand. */ 382 IRIns left[2]; /* Instruction referenced by left operand. */
315 IRIns right; /* Instruction referenced by right operand. */ 383 IRIns right[2]; /* Instruction referenced by right operand. */
316} FoldState; 384} FoldState;
317 385
318/* JIT compiler state. */ 386/* JIT compiler state. */
319typedef struct jit_State { 387typedef struct jit_State {
320 GCtrace cur; /* Current trace. */ 388 GCtrace cur; /* Current trace. */
389 GCtrace *curfinal; /* Final address of current trace (set during asm). */
321 390
322 lua_State *L; /* Current Lua state. */ 391 lua_State *L; /* Current Lua state. */
323 const BCIns *pc; /* Current PC. */ 392 const BCIns *pc; /* Current PC. */
@@ -347,8 +416,9 @@ typedef struct jit_State {
347 int32_t framedepth; /* Current frame depth. */ 416 int32_t framedepth; /* Current frame depth. */
348 int32_t retdepth; /* Return frame depth (count of RETF). */ 417 int32_t retdepth; /* Return frame depth (count of RETF). */
349 418
350 MRef k64; /* Pointer to chained array of 64 bit constants. */
351 TValue ksimd[LJ_KSIMD__MAX*2+1]; /* 16 byte aligned SIMD constants. */ 419 TValue ksimd[LJ_KSIMD__MAX*2+1]; /* 16 byte aligned SIMD constants. */
420 TValue k64[LJ_K64__MAX]; /* Common 8 byte constants used by backends. */
421 uint32_t k32[LJ_K32__MAX]; /* Ditto for 4 byte constants. */
352 422
353 IRIns *irbuf; /* Temp. IR instruction buffer. Biased with REF_BIAS. */ 423 IRIns *irbuf; /* Temp. IR instruction buffer. Biased with REF_BIAS. */
354 IRRef irtoplim; /* Upper limit of instuction buffer (biased). */ 424 IRRef irtoplim; /* Upper limit of instuction buffer (biased). */
@@ -362,12 +432,14 @@ typedef struct jit_State {
362 432
363 PostProc postproc; /* Required post-processing after execution. */ 433 PostProc postproc; /* Required post-processing after execution. */
364#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI) 434#if LJ_SOFTFP || (LJ_32 && LJ_HASFFI)
365 int needsplit; /* Need SPLIT pass. */ 435 uint8_t needsplit; /* Need SPLIT pass. */
366#endif 436#endif
437 uint8_t retryrec; /* Retry recording. */
367 438
368 GCRef *trace; /* Array of traces. */ 439 GCRef *trace; /* Array of traces. */
369 TraceNo freetrace; /* Start of scan for next free trace. */ 440 TraceNo freetrace; /* Start of scan for next free trace. */
370 MSize sizetrace; /* Size of trace array. */ 441 MSize sizetrace; /* Size of trace array. */
442 IRRef1 ktrace; /* Reference to KGC with GCtrace. */
371 443
372 IRRef1 chain[IR__MAX]; /* IR instruction skip-list chain anchors. */ 444 IRRef1 chain[IR__MAX]; /* IR instruction skip-list chain anchors. */
373 TRef slot[LJ_MAX_JSLOTS+LJ_STACK_EXTRA]; /* Stack slot map. */ 445 TRef slot[LJ_MAX_JSLOTS+LJ_STACK_EXTRA]; /* Stack slot map. */
@@ -380,6 +452,10 @@ typedef struct jit_State {
380 uint32_t penaltyslot; /* Round-robin index into penalty slots. */ 452 uint32_t penaltyslot; /* Round-robin index into penalty slots. */
381 uint32_t prngstate; /* PRNG state. */ 453 uint32_t prngstate; /* PRNG state. */
382 454
455#ifdef LUAJIT_ENABLE_TABLE_BUMP
456 RBCHashEntry rbchash[RBCHASH_SLOTS]; /* Reverse bytecode map. */
457#endif
458
383 BPropEntry bpropcache[BPROP_SLOTS]; /* Backpropagation cache slots. */ 459 BPropEntry bpropcache[BPROP_SLOTS]; /* Backpropagation cache slots. */
384 uint32_t bpropslot; /* Round-robin index into bpropcache slots. */ 460 uint32_t bpropslot; /* Round-robin index into bpropcache slots. */
385 461
@@ -400,6 +476,12 @@ typedef struct jit_State {
400 size_t szallmcarea; /* Total size of all allocated mcode areas. */ 476 size_t szallmcarea; /* Total size of all allocated mcode areas. */
401 477
402 TValue errinfo; /* Additional info element for trace errors. */ 478 TValue errinfo; /* Additional info element for trace errors. */
479
480#if LJ_HASPROFILE
481 GCproto *prev_pt; /* Previous prototype. */
482 BCLine prev_line; /* Previous line. */
483 int prof_mode; /* Profiling mode: 0, 'f', 'l'. */
484#endif
403} 485}
404#if LJ_TARGET_ARM 486#if LJ_TARGET_ARM
405LJ_ALIGN(16) /* For DISPATCH-relative addresses in assembler part. */ 487LJ_ALIGN(16) /* For DISPATCH-relative addresses in assembler part. */
diff --git a/src/lj_lex.c b/src/lj_lex.c
index 36603168..2d2f8194 100644
--- a/src/lj_lex.c
+++ b/src/lj_lex.c
@@ -12,6 +12,7 @@
12#include "lj_obj.h" 12#include "lj_obj.h"
13#include "lj_gc.h" 13#include "lj_gc.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_buf.h"
15#include "lj_str.h" 16#include "lj_str.h"
16#if LJ_HASFFI 17#if LJ_HASFFI
17#include "lj_tab.h" 18#include "lj_tab.h"
@@ -24,6 +25,7 @@
24#include "lj_parse.h" 25#include "lj_parse.h"
25#include "lj_char.h" 26#include "lj_char.h"
26#include "lj_strscan.h" 27#include "lj_strscan.h"
28#include "lj_strfmt.h"
27 29
28/* Lua lexer token names. */ 30/* Lua lexer token names. */
29static const char *const tokennames[] = { 31static const char *const tokennames[] = {
@@ -37,50 +39,48 @@ TKDEF(TKSTR1, TKSTR2)
37 39
38/* -- Buffer handling ----------------------------------------------------- */ 40/* -- Buffer handling ----------------------------------------------------- */
39 41
40#define char2int(c) ((int)(uint8_t)(c)) 42#define LEX_EOF (-1)
41#define next(ls) \ 43#define lex_iseol(ls) (ls->c == '\n' || ls->c == '\r')
42 (ls->current = (ls->n--) > 0 ? char2int(*ls->p++) : fillbuf(ls))
43#define save_and_next(ls) (save(ls, ls->current), next(ls))
44#define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r')
45#define END_OF_STREAM (-1)
46 44
47static int fillbuf(LexState *ls) 45/* Get more input from reader. */
46static LJ_NOINLINE LexChar lex_more(LexState *ls)
48{ 47{
49 size_t sz; 48 size_t sz;
50 const char *buf = ls->rfunc(ls->L, ls->rdata, &sz); 49 const char *p = ls->rfunc(ls->L, ls->rdata, &sz);
51 if (buf == NULL || sz == 0) return END_OF_STREAM; 50 if (p == NULL || sz == 0) return LEX_EOF;
52 ls->n = (MSize)sz - 1; 51 ls->pe = p + sz;
53 ls->p = buf; 52 ls->p = p + 1;
54 return char2int(*(ls->p++)); 53 return (LexChar)(uint8_t)p[0];
55} 54}
56 55
57static LJ_NOINLINE void save_grow(LexState *ls, int c) 56/* Get next character. */
57static LJ_AINLINE LexChar lex_next(LexState *ls)
58{ 58{
59 MSize newsize; 59 return (ls->c = ls->p < ls->pe ? (LexChar)(uint8_t)*ls->p++ : lex_more(ls));
60 if (ls->sb.sz >= LJ_MAX_STR/2)
61 lj_lex_error(ls, 0, LJ_ERR_XELEM);
62 newsize = ls->sb.sz * 2;
63 lj_str_resizebuf(ls->L, &ls->sb, newsize);
64 ls->sb.buf[ls->sb.n++] = (char)c;
65} 60}
66 61
67static LJ_AINLINE void save(LexState *ls, int c) 62/* Save character. */
63static LJ_AINLINE void lex_save(LexState *ls, LexChar c)
68{ 64{
69 if (LJ_UNLIKELY(ls->sb.n + 1 > ls->sb.sz)) 65 lj_buf_putb(&ls->sb, c);
70 save_grow(ls, c);
71 else
72 ls->sb.buf[ls->sb.n++] = (char)c;
73} 66}
74 67
75static void inclinenumber(LexState *ls) 68/* Save previous character and get next character. */
69static LJ_AINLINE LexChar lex_savenext(LexState *ls)
76{ 70{
77 int old = ls->current; 71 lex_save(ls, ls->c);
78 lua_assert(currIsNewline(ls)); 72 return lex_next(ls);
79 next(ls); /* skip `\n' or `\r' */ 73}
80 if (currIsNewline(ls) && ls->current != old) 74
81 next(ls); /* skip `\n\r' or `\r\n' */ 75/* Skip line break. Handles "\n", "\r", "\r\n" or "\n\r". */
76static void lex_newline(LexState *ls)
77{
78 LexChar old = ls->c;
79 lua_assert(lex_iseol(ls));
80 lex_next(ls); /* Skip "\n" or "\r". */
81 if (lex_iseol(ls) && ls->c != old) lex_next(ls); /* Skip "\n\r" or "\r\n". */
82 if (++ls->linenumber >= LJ_MAX_LINE) 82 if (++ls->linenumber >= LJ_MAX_LINE)
83 lj_lex_error(ls, ls->token, LJ_ERR_XLINES); 83 lj_lex_error(ls, ls->tok, LJ_ERR_XLINES);
84} 84}
85 85
86/* -- Scanner for terminals ----------------------------------------------- */ 86/* -- Scanner for terminals ----------------------------------------------- */
@@ -89,19 +89,17 @@ static void inclinenumber(LexState *ls)
89static void lex_number(LexState *ls, TValue *tv) 89static void lex_number(LexState *ls, TValue *tv)
90{ 90{
91 StrScanFmt fmt; 91 StrScanFmt fmt;
92 int c, xp = 'e'; 92 LexChar c, xp = 'e';
93 lua_assert(lj_char_isdigit(ls->current)); 93 lua_assert(lj_char_isdigit(ls->c));
94 if ((c = ls->current) == '0') { 94 if ((c = ls->c) == '0' && (lex_savenext(ls) | 0x20) == 'x')
95 save_and_next(ls); 95 xp = 'p';
96 if ((ls->current | 0x20) == 'x') xp = 'p'; 96 while (lj_char_isident(ls->c) || ls->c == '.' ||
97 } 97 ((ls->c == '-' || ls->c == '+') && (c | 0x20) == xp)) {
98 while (lj_char_isident(ls->current) || ls->current == '.' || 98 c = ls->c;
99 ((ls->current == '-' || ls->current == '+') && (c | 0x20) == xp)) { 99 lex_savenext(ls);
100 c = ls->current;
101 save_and_next(ls);
102 } 100 }
103 save(ls, '\0'); 101 lex_save(ls, '\0');
104 fmt = lj_strscan_scan((const uint8_t *)ls->sb.buf, tv, 102 fmt = lj_strscan_scan((const uint8_t *)sbufB(&ls->sb), tv,
105 (LJ_DUALNUM ? STRSCAN_OPT_TOINT : STRSCAN_OPT_TONUM) | 103 (LJ_DUALNUM ? STRSCAN_OPT_TOINT : STRSCAN_OPT_TONUM) |
106 (LJ_HASFFI ? (STRSCAN_OPT_LL|STRSCAN_OPT_IMAG) : 0)); 104 (LJ_HASFFI ? (STRSCAN_OPT_LL|STRSCAN_OPT_IMAG) : 0));
107 if (LJ_DUALNUM && fmt == STRSCAN_INT) { 105 if (LJ_DUALNUM && fmt == STRSCAN_INT) {
@@ -134,60 +132,60 @@ static void lex_number(LexState *ls, TValue *tv)
134 } 132 }
135} 133}
136 134
137static int skip_sep(LexState *ls) 135/* Skip equal signs for "[=...=[" and "]=...=]" and return their count. */
136static int lex_skipeq(LexState *ls)
138{ 137{
139 int count = 0; 138 int count = 0;
140 int s = ls->current; 139 LexChar s = ls->c;
141 lua_assert(s == '[' || s == ']'); 140 lua_assert(s == '[' || s == ']');
142 save_and_next(ls); 141 while (lex_savenext(ls) == '=')
143 while (ls->current == '=') {
144 save_and_next(ls);
145 count++; 142 count++;
146 } 143 return (ls->c == s) ? count : (-count) - 1;
147 return (ls->current == s) ? count : (-count) - 1;
148} 144}
149 145
150static void read_long_string(LexState *ls, TValue *tv, int sep) 146/* Parse a long string or long comment (tv set to NULL). */
147static void lex_longstring(LexState *ls, TValue *tv, int sep)
151{ 148{
152 save_and_next(ls); /* skip 2nd `[' */ 149 lex_savenext(ls); /* Skip second '['. */
153 if (currIsNewline(ls)) /* string starts with a newline? */ 150 if (lex_iseol(ls)) /* Skip initial newline. */
154 inclinenumber(ls); /* skip it */ 151 lex_newline(ls);
155 for (;;) { 152 for (;;) {
156 switch (ls->current) { 153 switch (ls->c) {
157 case END_OF_STREAM: 154 case LEX_EOF:
158 lj_lex_error(ls, TK_eof, tv ? LJ_ERR_XLSTR : LJ_ERR_XLCOM); 155 lj_lex_error(ls, TK_eof, tv ? LJ_ERR_XLSTR : LJ_ERR_XLCOM);
159 break; 156 break;
160 case ']': 157 case ']':
161 if (skip_sep(ls) == sep) { 158 if (lex_skipeq(ls) == sep) {
162 save_and_next(ls); /* skip 2nd `]' */ 159 lex_savenext(ls); /* Skip second ']'. */
163 goto endloop; 160 goto endloop;
164 } 161 }
165 break; 162 break;
166 case '\n': 163 case '\n':
167 case '\r': 164 case '\r':
168 save(ls, '\n'); 165 lex_save(ls, '\n');
169 inclinenumber(ls); 166 lex_newline(ls);
170 if (!tv) lj_str_resetbuf(&ls->sb); /* avoid wasting space */ 167 if (!tv) lj_buf_reset(&ls->sb); /* Don't waste space for comments. */
171 break; 168 break;
172 default: 169 default:
173 if (tv) save_and_next(ls); 170 lex_savenext(ls);
174 else next(ls);
175 break; 171 break;
176 } 172 }
177 } endloop: 173 } endloop:
178 if (tv) { 174 if (tv) {
179 GCstr *str = lj_parse_keepstr(ls, ls->sb.buf + (2 + (MSize)sep), 175 GCstr *str = lj_parse_keepstr(ls, sbufB(&ls->sb) + (2 + (MSize)sep),
180 ls->sb.n - 2*(2 + (MSize)sep)); 176 sbuflen(&ls->sb) - 2*(2 + (MSize)sep));
181 setstrV(ls->L, tv, str); 177 setstrV(ls->L, tv, str);
182 } 178 }
183} 179}
184 180
185static void read_string(LexState *ls, int delim, TValue *tv) 181/* Parse a string. */
182static void lex_string(LexState *ls, TValue *tv)
186{ 183{
187 save_and_next(ls); 184 LexChar delim = ls->c; /* Delimiter is '\'' or '"'. */
188 while (ls->current != delim) { 185 lex_savenext(ls);
189 switch (ls->current) { 186 while (ls->c != delim) {
190 case END_OF_STREAM: 187 switch (ls->c) {
188 case LEX_EOF:
191 lj_lex_error(ls, TK_eof, LJ_ERR_XSTR); 189 lj_lex_error(ls, TK_eof, LJ_ERR_XSTR);
192 continue; 190 continue;
193 case '\n': 191 case '\n':
@@ -195,7 +193,7 @@ static void read_string(LexState *ls, int delim, TValue *tv)
195 lj_lex_error(ls, TK_string, LJ_ERR_XSTR); 193 lj_lex_error(ls, TK_string, LJ_ERR_XSTR);
196 continue; 194 continue;
197 case '\\': { 195 case '\\': {
198 int c = next(ls); /* Skip the '\\'. */ 196 LexChar c = lex_next(ls); /* Skip the '\\'. */
199 switch (c) { 197 switch (c) {
200 case 'a': c = '\a'; break; 198 case 'a': c = '\a'; break;
201 case 'b': c = '\b'; break; 199 case 'b': c = '\b'; break;
@@ -205,111 +203,139 @@ static void read_string(LexState *ls, int delim, TValue *tv)
205 case 't': c = '\t'; break; 203 case 't': c = '\t'; break;
206 case 'v': c = '\v'; break; 204 case 'v': c = '\v'; break;
207 case 'x': /* Hexadecimal escape '\xXX'. */ 205 case 'x': /* Hexadecimal escape '\xXX'. */
208 c = (next(ls) & 15u) << 4; 206 c = (lex_next(ls) & 15u) << 4;
209 if (!lj_char_isdigit(ls->current)) { 207 if (!lj_char_isdigit(ls->c)) {
210 if (!lj_char_isxdigit(ls->current)) goto err_xesc; 208 if (!lj_char_isxdigit(ls->c)) goto err_xesc;
211 c += 9 << 4; 209 c += 9 << 4;
212 } 210 }
213 c += (next(ls) & 15u); 211 c += (lex_next(ls) & 15u);
214 if (!lj_char_isdigit(ls->current)) { 212 if (!lj_char_isdigit(ls->c)) {
215 if (!lj_char_isxdigit(ls->current)) goto err_xesc; 213 if (!lj_char_isxdigit(ls->c)) goto err_xesc;
216 c += 9; 214 c += 9;
217 } 215 }
218 break; 216 break;
217 case 'u': /* Unicode escape '\u{XX...}'. */
218 if (lex_next(ls) != '{') goto err_xesc;
219 lex_next(ls);
220 c = 0;
221 do {
222 c = (c << 4) | (ls->c & 15u);
223 if (!lj_char_isdigit(ls->c)) {
224 if (!lj_char_isxdigit(ls->c)) goto err_xesc;
225 c += 9;
226 }
227 if (c >= 0x110000) goto err_xesc; /* Out of Unicode range. */
228 } while (lex_next(ls) != '}');
229 if (c < 0x800) {
230 if (c < 0x80) break;
231 lex_save(ls, 0xc0 | (c >> 6));
232 } else {
233 if (c >= 0x10000) {
234 lex_save(ls, 0xf0 | (c >> 18));
235 lex_save(ls, 0x80 | ((c >> 12) & 0x3f));
236 } else {
237 if (c >= 0xd800 && c < 0xe000) goto err_xesc; /* No surrogates. */
238 lex_save(ls, 0xe0 | (c >> 12));
239 }
240 lex_save(ls, 0x80 | ((c >> 6) & 0x3f));
241 }
242 c = 0x80 | (c & 0x3f);
243 break;
219 case 'z': /* Skip whitespace. */ 244 case 'z': /* Skip whitespace. */
220 next(ls); 245 lex_next(ls);
221 while (lj_char_isspace(ls->current)) 246 while (lj_char_isspace(ls->c))
222 if (currIsNewline(ls)) inclinenumber(ls); else next(ls); 247 if (lex_iseol(ls)) lex_newline(ls); else lex_next(ls);
223 continue; 248 continue;
224 case '\n': case '\r': save(ls, '\n'); inclinenumber(ls); continue; 249 case '\n': case '\r': lex_save(ls, '\n'); lex_newline(ls); continue;
225 case '\\': case '\"': case '\'': break; 250 case '\\': case '\"': case '\'': break;
226 case END_OF_STREAM: continue; 251 case LEX_EOF: continue;
227 default: 252 default:
228 if (!lj_char_isdigit(c)) 253 if (!lj_char_isdigit(c))
229 goto err_xesc; 254 goto err_xesc;
230 c -= '0'; /* Decimal escape '\ddd'. */ 255 c -= '0'; /* Decimal escape '\ddd'. */
231 if (lj_char_isdigit(next(ls))) { 256 if (lj_char_isdigit(lex_next(ls))) {
232 c = c*10 + (ls->current - '0'); 257 c = c*10 + (ls->c - '0');
233 if (lj_char_isdigit(next(ls))) { 258 if (lj_char_isdigit(lex_next(ls))) {
234 c = c*10 + (ls->current - '0'); 259 c = c*10 + (ls->c - '0');
235 if (c > 255) { 260 if (c > 255) {
236 err_xesc: 261 err_xesc:
237 lj_lex_error(ls, TK_string, LJ_ERR_XESC); 262 lj_lex_error(ls, TK_string, LJ_ERR_XESC);
238 } 263 }
239 next(ls); 264 lex_next(ls);
240 } 265 }
241 } 266 }
242 save(ls, c); 267 lex_save(ls, c);
243 continue; 268 continue;
244 } 269 }
245 save(ls, c); 270 lex_save(ls, c);
246 next(ls); 271 lex_next(ls);
247 continue; 272 continue;
248 } 273 }
249 default: 274 default:
250 save_and_next(ls); 275 lex_savenext(ls);
251 break; 276 break;
252 } 277 }
253 } 278 }
254 save_and_next(ls); /* skip delimiter */ 279 lex_savenext(ls); /* Skip trailing delimiter. */
255 setstrV(ls->L, tv, lj_parse_keepstr(ls, ls->sb.buf + 1, ls->sb.n - 2)); 280 setstrV(ls->L, tv,
281 lj_parse_keepstr(ls, sbufB(&ls->sb)+1, sbuflen(&ls->sb)-2));
256} 282}
257 283
258/* -- Main lexical scanner ------------------------------------------------ */ 284/* -- Main lexical scanner ------------------------------------------------ */
259 285
260static int llex(LexState *ls, TValue *tv) 286/* Get next lexical token. */
287static LexToken lex_scan(LexState *ls, TValue *tv)
261{ 288{
262 lj_str_resetbuf(&ls->sb); 289 lj_buf_reset(&ls->sb);
263 for (;;) { 290 for (;;) {
264 if (lj_char_isident(ls->current)) { 291 if (lj_char_isident(ls->c)) {
265 GCstr *s; 292 GCstr *s;
266 if (lj_char_isdigit(ls->current)) { /* Numeric literal. */ 293 if (lj_char_isdigit(ls->c)) { /* Numeric literal. */
267 lex_number(ls, tv); 294 lex_number(ls, tv);
268 return TK_number; 295 return TK_number;
269 } 296 }
270 /* Identifier or reserved word. */ 297 /* Identifier or reserved word. */
271 do { 298 do {
272 save_and_next(ls); 299 lex_savenext(ls);
273 } while (lj_char_isident(ls->current)); 300 } while (lj_char_isident(ls->c));
274 s = lj_parse_keepstr(ls, ls->sb.buf, ls->sb.n); 301 s = lj_parse_keepstr(ls, sbufB(&ls->sb), sbuflen(&ls->sb));
275 setstrV(ls->L, tv, s); 302 setstrV(ls->L, tv, s);
276 if (s->reserved > 0) /* Reserved word? */ 303 if (s->reserved > 0) /* Reserved word? */
277 return TK_OFS + s->reserved; 304 return TK_OFS + s->reserved;
278 return TK_name; 305 return TK_name;
279 } 306 }
280 switch (ls->current) { 307 switch (ls->c) {
281 case '\n': 308 case '\n':
282 case '\r': 309 case '\r':
283 inclinenumber(ls); 310 lex_newline(ls);
284 continue; 311 continue;
285 case ' ': 312 case ' ':
286 case '\t': 313 case '\t':
287 case '\v': 314 case '\v':
288 case '\f': 315 case '\f':
289 next(ls); 316 lex_next(ls);
290 continue; 317 continue;
291 case '-': 318 case '-':
292 next(ls); 319 lex_next(ls);
293 if (ls->current != '-') return '-'; 320 if (ls->c != '-') return '-';
294 /* else is a comment */ 321 lex_next(ls);
295 next(ls); 322 if (ls->c == '[') { /* Long comment "--[=*[...]=*]". */
296 if (ls->current == '[') { 323 int sep = lex_skipeq(ls);
297 int sep = skip_sep(ls); 324 lj_buf_reset(&ls->sb); /* `lex_skipeq' may dirty the buffer */
298 lj_str_resetbuf(&ls->sb); /* `skip_sep' may dirty the buffer */
299 if (sep >= 0) { 325 if (sep >= 0) {
300 read_long_string(ls, NULL, sep); /* long comment */ 326 lex_longstring(ls, NULL, sep);
301 lj_str_resetbuf(&ls->sb); 327 lj_buf_reset(&ls->sb);
302 continue; 328 continue;
303 } 329 }
304 } 330 }
305 /* else short comment */ 331 /* Short comment "--.*\n". */
306 while (!currIsNewline(ls) && ls->current != END_OF_STREAM) 332 while (!lex_iseol(ls) && ls->c != LEX_EOF)
307 next(ls); 333 lex_next(ls);
308 continue; 334 continue;
309 case '[': { 335 case '[': {
310 int sep = skip_sep(ls); 336 int sep = lex_skipeq(ls);
311 if (sep >= 0) { 337 if (sep >= 0) {
312 read_long_string(ls, tv, sep); 338 lex_longstring(ls, tv, sep);
313 return TK_string; 339 return TK_string;
314 } else if (sep == -1) { 340 } else if (sep == -1) {
315 return '['; 341 return '[';
@@ -319,44 +345,43 @@ static int llex(LexState *ls, TValue *tv)
319 } 345 }
320 } 346 }
321 case '=': 347 case '=':
322 next(ls); 348 lex_next(ls);
323 if (ls->current != '=') return '='; else { next(ls); return TK_eq; } 349 if (ls->c != '=') return '='; else { lex_next(ls); return TK_eq; }
324 case '<': 350 case '<':
325 next(ls); 351 lex_next(ls);
326 if (ls->current != '=') return '<'; else { next(ls); return TK_le; } 352 if (ls->c != '=') return '<'; else { lex_next(ls); return TK_le; }
327 case '>': 353 case '>':
328 next(ls); 354 lex_next(ls);
329 if (ls->current != '=') return '>'; else { next(ls); return TK_ge; } 355 if (ls->c != '=') return '>'; else { lex_next(ls); return TK_ge; }
330 case '~': 356 case '~':
331 next(ls); 357 lex_next(ls);
332 if (ls->current != '=') return '~'; else { next(ls); return TK_ne; } 358 if (ls->c != '=') return '~'; else { lex_next(ls); return TK_ne; }
333 case ':': 359 case ':':
334 next(ls); 360 lex_next(ls);
335 if (ls->current != ':') return ':'; else { next(ls); return TK_label; } 361 if (ls->c != ':') return ':'; else { lex_next(ls); return TK_label; }
336 case '"': 362 case '"':
337 case '\'': 363 case '\'':
338 read_string(ls, ls->current, tv); 364 lex_string(ls, tv);
339 return TK_string; 365 return TK_string;
340 case '.': 366 case '.':
341 save_and_next(ls); 367 if (lex_savenext(ls) == '.') {
342 if (ls->current == '.') { 368 lex_next(ls);
343 next(ls); 369 if (ls->c == '.') {
344 if (ls->current == '.') { 370 lex_next(ls);
345 next(ls);
346 return TK_dots; /* ... */ 371 return TK_dots; /* ... */
347 } 372 }
348 return TK_concat; /* .. */ 373 return TK_concat; /* .. */
349 } else if (!lj_char_isdigit(ls->current)) { 374 } else if (!lj_char_isdigit(ls->c)) {
350 return '.'; 375 return '.';
351 } else { 376 } else {
352 lex_number(ls, tv); 377 lex_number(ls, tv);
353 return TK_number; 378 return TK_number;
354 } 379 }
355 case END_OF_STREAM: 380 case LEX_EOF:
356 return TK_eof; 381 return TK_eof;
357 default: { 382 default: {
358 int c = ls->current; 383 LexChar c = ls->c;
359 next(ls); 384 lex_next(ls);
360 return c; /* Single-char tokens (+ - / ...). */ 385 return c; /* Single-char tokens (+ - / ...). */
361 } 386 }
362 } 387 }
@@ -371,35 +396,32 @@ int lj_lex_setup(lua_State *L, LexState *ls)
371 int header = 0; 396 int header = 0;
372 ls->L = L; 397 ls->L = L;
373 ls->fs = NULL; 398 ls->fs = NULL;
374 ls->n = 0; 399 ls->pe = ls->p = NULL;
375 ls->p = NULL;
376 ls->vstack = NULL; 400 ls->vstack = NULL;
377 ls->sizevstack = 0; 401 ls->sizevstack = 0;
378 ls->vtop = 0; 402 ls->vtop = 0;
379 ls->bcstack = NULL; 403 ls->bcstack = NULL;
380 ls->sizebcstack = 0; 404 ls->sizebcstack = 0;
381 ls->token = 0; 405 ls->tok = 0;
382 ls->lookahead = TK_eof; /* No look-ahead token. */ 406 ls->lookahead = TK_eof; /* No look-ahead token. */
383 ls->linenumber = 1; 407 ls->linenumber = 1;
384 ls->lastline = 1; 408 ls->lastline = 1;
385 lj_str_resizebuf(ls->L, &ls->sb, LJ_MIN_SBUF); 409 lex_next(ls); /* Read-ahead first char. */
386 next(ls); /* Read-ahead first char. */ 410 if (ls->c == 0xef && ls->p + 2 <= ls->pe && (uint8_t)ls->p[0] == 0xbb &&
387 if (ls->current == 0xef && ls->n >= 2 && char2int(ls->p[0]) == 0xbb && 411 (uint8_t)ls->p[1] == 0xbf) { /* Skip UTF-8 BOM (if buffered). */
388 char2int(ls->p[1]) == 0xbf) { /* Skip UTF-8 BOM (if buffered). */
389 ls->n -= 2;
390 ls->p += 2; 412 ls->p += 2;
391 next(ls); 413 lex_next(ls);
392 header = 1; 414 header = 1;
393 } 415 }
394 if (ls->current == '#') { /* Skip POSIX #! header line. */ 416 if (ls->c == '#') { /* Skip POSIX #! header line. */
395 do { 417 do {
396 next(ls); 418 lex_next(ls);
397 if (ls->current == END_OF_STREAM) return 0; 419 if (ls->c == LEX_EOF) return 0;
398 } while (!currIsNewline(ls)); 420 } while (!lex_iseol(ls));
399 inclinenumber(ls); 421 lex_newline(ls);
400 header = 1; 422 header = 1;
401 } 423 }
402 if (ls->current == LUA_SIGNATURE[0]) { /* Bytecode dump. */ 424 if (ls->c == LUA_SIGNATURE[0]) { /* Bytecode dump. */
403 if (header) { 425 if (header) {
404 /* 426 /*
405 ** Loading bytecode with an extra header is disabled for security 427 ** Loading bytecode with an extra header is disabled for security
@@ -421,55 +443,60 @@ void lj_lex_cleanup(lua_State *L, LexState *ls)
421 global_State *g = G(L); 443 global_State *g = G(L);
422 lj_mem_freevec(g, ls->bcstack, ls->sizebcstack, BCInsLine); 444 lj_mem_freevec(g, ls->bcstack, ls->sizebcstack, BCInsLine);
423 lj_mem_freevec(g, ls->vstack, ls->sizevstack, VarInfo); 445 lj_mem_freevec(g, ls->vstack, ls->sizevstack, VarInfo);
424 lj_str_freebuf(g, &ls->sb); 446 lj_buf_free(g, &ls->sb);
425} 447}
426 448
449/* Return next lexical token. */
427void lj_lex_next(LexState *ls) 450void lj_lex_next(LexState *ls)
428{ 451{
429 ls->lastline = ls->linenumber; 452 ls->lastline = ls->linenumber;
430 if (LJ_LIKELY(ls->lookahead == TK_eof)) { /* No lookahead token? */ 453 if (LJ_LIKELY(ls->lookahead == TK_eof)) { /* No lookahead token? */
431 ls->token = llex(ls, &ls->tokenval); /* Get next token. */ 454 ls->tok = lex_scan(ls, &ls->tokval); /* Get next token. */
432 } else { /* Otherwise return lookahead token. */ 455 } else { /* Otherwise return lookahead token. */
433 ls->token = ls->lookahead; 456 ls->tok = ls->lookahead;
434 ls->lookahead = TK_eof; 457 ls->lookahead = TK_eof;
435 ls->tokenval = ls->lookaheadval; 458 ls->tokval = ls->lookaheadval;
436 } 459 }
437} 460}
438 461
462/* Look ahead for the next token. */
439LexToken lj_lex_lookahead(LexState *ls) 463LexToken lj_lex_lookahead(LexState *ls)
440{ 464{
441 lua_assert(ls->lookahead == TK_eof); 465 lua_assert(ls->lookahead == TK_eof);
442 ls->lookahead = llex(ls, &ls->lookaheadval); 466 ls->lookahead = lex_scan(ls, &ls->lookaheadval);
443 return ls->lookahead; 467 return ls->lookahead;
444} 468}
445 469
446const char *lj_lex_token2str(LexState *ls, LexToken token) 470/* Convert token to string. */
471const char *lj_lex_token2str(LexState *ls, LexToken tok)
447{ 472{
448 if (token > TK_OFS) 473 if (tok > TK_OFS)
449 return tokennames[token-TK_OFS-1]; 474 return tokennames[tok-TK_OFS-1];
450 else if (!lj_char_iscntrl(token)) 475 else if (!lj_char_iscntrl(tok))
451 return lj_str_pushf(ls->L, "%c", token); 476 return lj_strfmt_pushf(ls->L, "%c", tok);
452 else 477 else
453 return lj_str_pushf(ls->L, "char(%d)", token); 478 return lj_strfmt_pushf(ls->L, "char(%d)", tok);
454} 479}
455 480
456void lj_lex_error(LexState *ls, LexToken token, ErrMsg em, ...) 481/* Lexer error. */
482void lj_lex_error(LexState *ls, LexToken tok, ErrMsg em, ...)
457{ 483{
458 const char *tok; 484 const char *tokstr;
459 va_list argp; 485 va_list argp;
460 if (token == 0) { 486 if (tok == 0) {
461 tok = NULL; 487 tokstr = NULL;
462 } else if (token == TK_name || token == TK_string || token == TK_number) { 488 } else if (tok == TK_name || tok == TK_string || tok == TK_number) {
463 save(ls, '\0'); 489 lex_save(ls, '\0');
464 tok = ls->sb.buf; 490 tokstr = sbufB(&ls->sb);
465 } else { 491 } else {
466 tok = lj_lex_token2str(ls, token); 492 tokstr = lj_lex_token2str(ls, tok);
467 } 493 }
468 va_start(argp, em); 494 va_start(argp, em);
469 lj_err_lex(ls->L, ls->chunkname, tok, ls->linenumber, em, argp); 495 lj_err_lex(ls->L, ls->chunkname, tokstr, ls->linenumber, em, argp);
470 va_end(argp); 496 va_end(argp);
471} 497}
472 498
499/* Initialize strings for reserved words. */
473void lj_lex_init(lua_State *L) 500void lj_lex_init(lua_State *L)
474{ 501{
475 uint32_t i; 502 uint32_t i;
diff --git a/src/lj_lex.h b/src/lj_lex.h
index 41c03f93..33fa8657 100644
--- a/src/lj_lex.h
+++ b/src/lj_lex.h
@@ -30,7 +30,8 @@ TKDEF(TKENUM1, TKENUM2)
30 TK_RESERVED = TK_while - TK_OFS 30 TK_RESERVED = TK_while - TK_OFS
31}; 31};
32 32
33typedef int LexToken; 33typedef int LexChar; /* Lexical character. Unsigned ext. from char. */
34typedef int LexToken; /* Lexical token. */
34 35
35/* Combined bytecode ins/line. Only used during bytecode generation. */ 36/* Combined bytecode ins/line. Only used during bytecode generation. */
36typedef struct BCInsLine { 37typedef struct BCInsLine {
@@ -51,13 +52,13 @@ typedef struct VarInfo {
51typedef struct LexState { 52typedef struct LexState {
52 struct FuncState *fs; /* Current FuncState. Defined in lj_parse.c. */ 53 struct FuncState *fs; /* Current FuncState. Defined in lj_parse.c. */
53 struct lua_State *L; /* Lua state. */ 54 struct lua_State *L; /* Lua state. */
54 TValue tokenval; /* Current token value. */ 55 TValue tokval; /* Current token value. */
55 TValue lookaheadval; /* Lookahead token value. */ 56 TValue lookaheadval; /* Lookahead token value. */
56 int current; /* Current character (charint). */
57 LexToken token; /* Current token. */
58 LexToken lookahead; /* Lookahead token. */
59 MSize n; /* Bytes left in input buffer. */
60 const char *p; /* Current position in input buffer. */ 57 const char *p; /* Current position in input buffer. */
58 const char *pe; /* End of input buffer. */
59 LexChar c; /* Current character. */
60 LexToken tok; /* Current token. */
61 LexToken lookahead; /* Lookahead token. */
61 SBuf sb; /* String buffer for tokens. */ 62 SBuf sb; /* String buffer for tokens. */
62 lua_Reader rfunc; /* Reader callback. */ 63 lua_Reader rfunc; /* Reader callback. */
63 void *rdata; /* Reader callback data. */ 64 void *rdata; /* Reader callback data. */
@@ -78,8 +79,8 @@ LJ_FUNC int lj_lex_setup(lua_State *L, LexState *ls);
78LJ_FUNC void lj_lex_cleanup(lua_State *L, LexState *ls); 79LJ_FUNC void lj_lex_cleanup(lua_State *L, LexState *ls);
79LJ_FUNC void lj_lex_next(LexState *ls); 80LJ_FUNC void lj_lex_next(LexState *ls);
80LJ_FUNC LexToken lj_lex_lookahead(LexState *ls); 81LJ_FUNC LexToken lj_lex_lookahead(LexState *ls);
81LJ_FUNC const char *lj_lex_token2str(LexState *ls, LexToken token); 82LJ_FUNC const char *lj_lex_token2str(LexState *ls, LexToken tok);
82LJ_FUNC_NORET void lj_lex_error(LexState *ls, LexToken token, ErrMsg em, ...); 83LJ_FUNC_NORET void lj_lex_error(LexState *ls, LexToken tok, ErrMsg em, ...);
83LJ_FUNC void lj_lex_init(lua_State *L); 84LJ_FUNC void lj_lex_init(lua_State *L);
84 85
85#endif 86#endif
diff --git a/src/lj_lib.c b/src/lj_lib.c
index a1bb6a2a..b8638de6 100644
--- a/src/lj_lib.c
+++ b/src/lj_lib.c
@@ -18,6 +18,9 @@
18#include "lj_dispatch.h" 18#include "lj_dispatch.h"
19#include "lj_vm.h" 19#include "lj_vm.h"
20#include "lj_strscan.h" 20#include "lj_strscan.h"
21#include "lj_strfmt.h"
22#include "lj_lex.h"
23#include "lj_bcdump.h"
21#include "lj_lib.h" 24#include "lj_lib.h"
22 25
23/* -- Library initialization ---------------------------------------------- */ 26/* -- Library initialization ---------------------------------------------- */
@@ -43,6 +46,28 @@ static GCtab *lib_create_table(lua_State *L, const char *libname, int hsize)
43 return tabV(L->top-1); 46 return tabV(L->top-1);
44} 47}
45 48
49static const uint8_t *lib_read_lfunc(lua_State *L, const uint8_t *p, GCtab *tab)
50{
51 int len = *p++;
52 GCstr *name = lj_str_new(L, (const char *)p, len);
53 LexState ls;
54 GCproto *pt;
55 GCfunc *fn;
56 memset(&ls, 0, sizeof(ls));
57 ls.L = L;
58 ls.p = (const char *)(p+len);
59 ls.pe = (const char *)~(uintptr_t)0;
60 ls.c = -1;
61 ls.level = (BCDUMP_F_STRIP|(LJ_BE*BCDUMP_F_BE));
62 ls.chunkname = name;
63 pt = lj_bcread_proto(&ls);
64 pt->firstline = ~(BCLine)0;
65 fn = lj_func_newL_empty(L, pt, tabref(L->env));
66 /* NOBARRIER: See below for common barrier. */
67 setfuncV(L, lj_tab_setstr(L, tab, name), fn);
68 return (const uint8_t *)ls.p;
69}
70
46void lj_lib_register(lua_State *L, const char *libname, 71void lj_lib_register(lua_State *L, const char *libname,
47 const uint8_t *p, const lua_CFunction *cf) 72 const uint8_t *p, const lua_CFunction *cf)
48{ 73{
@@ -87,6 +112,9 @@ void lj_lib_register(lua_State *L, const char *libname,
87 ofn = fn; 112 ofn = fn;
88 } else { 113 } else {
89 switch (tag | len) { 114 switch (tag | len) {
115 case LIBINIT_LUA:
116 p = lib_read_lfunc(L, p, tab);
117 break;
90 case LIBINIT_SET: 118 case LIBINIT_SET:
91 L->top -= 2; 119 L->top -= 2;
92 if (tvisstr(L->top+1) && strV(L->top+1)->len == 0) 120 if (tvisstr(L->top+1) && strV(L->top+1)->len == 0)
@@ -120,6 +148,37 @@ void lj_lib_register(lua_State *L, const char *libname,
120 } 148 }
121} 149}
122 150
151/* Push internal function on the stack. */
152GCfunc *lj_lib_pushcc(lua_State *L, lua_CFunction f, int id, int n)
153{
154 GCfunc *fn;
155 lua_pushcclosure(L, f, n);
156 fn = funcV(L->top-1);
157 fn->c.ffid = (uint8_t)id;
158 setmref(fn->c.pc, &G(L)->bc_cfunc_int);
159 return fn;
160}
161
162void lj_lib_prereg(lua_State *L, const char *name, lua_CFunction f, GCtab *env)
163{
164 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4);
165 lua_pushcfunction(L, f);
166 /* NOBARRIER: The function is new (marked white). */
167 setgcref(funcV(L->top-1)->c.env, obj2gco(env));
168 lua_setfield(L, -2, name);
169 L->top--;
170}
171
172int lj_lib_postreg(lua_State *L, lua_CFunction cf, int id, const char *name)
173{
174 GCfunc *fn = lj_lib_pushcf(L, cf, id);
175 GCtab *t = tabref(curr_func(L)->c.env); /* Reference to parent table. */
176 setfuncV(L, lj_tab_setstr(L, t, lj_str_newz(L, name)), fn);
177 lj_gc_anybarriert(L, t);
178 setfuncV(L, L->top++, fn);
179 return 1;
180}
181
123/* -- Type checks --------------------------------------------------------- */ 182/* -- Type checks --------------------------------------------------------- */
124 183
125TValue *lj_lib_checkany(lua_State *L, int narg) 184TValue *lj_lib_checkany(lua_State *L, int narg)
@@ -137,7 +196,7 @@ GCstr *lj_lib_checkstr(lua_State *L, int narg)
137 if (LJ_LIKELY(tvisstr(o))) { 196 if (LJ_LIKELY(tvisstr(o))) {
138 return strV(o); 197 return strV(o);
139 } else if (tvisnumber(o)) { 198 } else if (tvisnumber(o)) {
140 GCstr *s = lj_str_fromnumber(L, o); 199 GCstr *s = lj_strfmt_number(L, o);
141 setstrV(L, o, s); 200 setstrV(L, o, s);
142 return s; 201 return s;
143 } 202 }
@@ -196,20 +255,6 @@ int32_t lj_lib_optint(lua_State *L, int narg, int32_t def)
196 return (o < L->top && !tvisnil(o)) ? lj_lib_checkint(L, narg) : def; 255 return (o < L->top && !tvisnil(o)) ? lj_lib_checkint(L, narg) : def;
197} 256}
198 257
199int32_t lj_lib_checkbit(lua_State *L, int narg)
200{
201 TValue *o = L->base + narg-1;
202 if (!(o < L->top && lj_strscan_numberobj(o)))
203 lj_err_argt(L, narg, LUA_TNUMBER);
204 if (LJ_LIKELY(tvisint(o))) {
205 return intV(o);
206 } else {
207 int32_t i = lj_num2bit(numV(o));
208 if (LJ_DUALNUM) setintV(o, i);
209 return i;
210 }
211}
212
213GCfunc *lj_lib_checkfunc(lua_State *L, int narg) 258GCfunc *lj_lib_checkfunc(lua_State *L, int narg)
214{ 259{
215 TValue *o = L->base + narg-1; 260 TValue *o = L->base + narg-1;
diff --git a/src/lj_lib.h b/src/lj_lib.h
index aa874076..37ec9d78 100644
--- a/src/lj_lib.h
+++ b/src/lj_lib.h
@@ -41,15 +41,22 @@ LJ_FUNC void lj_lib_checknumber(lua_State *L, int narg);
41LJ_FUNC lua_Number lj_lib_checknum(lua_State *L, int narg); 41LJ_FUNC lua_Number lj_lib_checknum(lua_State *L, int narg);
42LJ_FUNC int32_t lj_lib_checkint(lua_State *L, int narg); 42LJ_FUNC int32_t lj_lib_checkint(lua_State *L, int narg);
43LJ_FUNC int32_t lj_lib_optint(lua_State *L, int narg, int32_t def); 43LJ_FUNC int32_t lj_lib_optint(lua_State *L, int narg, int32_t def);
44LJ_FUNC int32_t lj_lib_checkbit(lua_State *L, int narg);
45LJ_FUNC GCfunc *lj_lib_checkfunc(lua_State *L, int narg); 44LJ_FUNC GCfunc *lj_lib_checkfunc(lua_State *L, int narg);
46LJ_FUNC GCtab *lj_lib_checktab(lua_State *L, int narg); 45LJ_FUNC GCtab *lj_lib_checktab(lua_State *L, int narg);
47LJ_FUNC GCtab *lj_lib_checktabornil(lua_State *L, int narg); 46LJ_FUNC GCtab *lj_lib_checktabornil(lua_State *L, int narg);
48LJ_FUNC int lj_lib_checkopt(lua_State *L, int narg, int def, const char *lst); 47LJ_FUNC int lj_lib_checkopt(lua_State *L, int narg, int def, const char *lst);
49 48
50/* Avoid including lj_frame.h. */ 49/* Avoid including lj_frame.h. */
50#if LJ_GC64
51#define lj_lib_upvalue(L, n) \
52 (&gcval(L->base-2)->fn.c.upvalue[(n)-1])
53#elif LJ_FR2
54#define lj_lib_upvalue(L, n) \
55 (&gcref((L->base-2)->gcr)->fn.c.upvalue[(n)-1])
56#else
51#define lj_lib_upvalue(L, n) \ 57#define lj_lib_upvalue(L, n) \
52 (&gcref((L->base-1)->fr.func)->fn.c.upvalue[(n)-1]) 58 (&gcref((L->base-1)->fr.func)->fn.c.upvalue[(n)-1])
59#endif
53 60
54#if LJ_TARGET_WINDOWS 61#if LJ_TARGET_WINDOWS
55#define lj_lib_checkfpu(L) \ 62#define lj_lib_checkfpu(L) \
@@ -60,23 +67,14 @@ LJ_FUNC int lj_lib_checkopt(lua_State *L, int narg, int def, const char *lst);
60#define lj_lib_checkfpu(L) UNUSED(L) 67#define lj_lib_checkfpu(L) UNUSED(L)
61#endif 68#endif
62 69
63/* Push internal function on the stack. */ 70LJ_FUNC GCfunc *lj_lib_pushcc(lua_State *L, lua_CFunction f, int id, int n);
64static LJ_AINLINE void lj_lib_pushcc(lua_State *L, lua_CFunction f,
65 int id, int n)
66{
67 GCfunc *fn;
68 lua_pushcclosure(L, f, n);
69 fn = funcV(L->top-1);
70 fn->c.ffid = (uint8_t)id;
71 setmref(fn->c.pc, &G(L)->bc_cfunc_int);
72}
73
74#define lj_lib_pushcf(L, fn, id) (lj_lib_pushcc(L, (fn), (id), 0)) 71#define lj_lib_pushcf(L, fn, id) (lj_lib_pushcc(L, (fn), (id), 0))
75 72
76/* Library function declarations. Scanned by buildvm. */ 73/* Library function declarations. Scanned by buildvm. */
77#define LJLIB_CF(name) static int lj_cf_##name(lua_State *L) 74#define LJLIB_CF(name) static int lj_cf_##name(lua_State *L)
78#define LJLIB_ASM(name) static int lj_ffh_##name(lua_State *L) 75#define LJLIB_ASM(name) static int lj_ffh_##name(lua_State *L)
79#define LJLIB_ASM_(name) 76#define LJLIB_ASM_(name)
77#define LJLIB_LUA(name)
80#define LJLIB_SET(name) 78#define LJLIB_SET(name)
81#define LJLIB_PUSH(arg) 79#define LJLIB_PUSH(arg)
82#define LJLIB_REC(handler) 80#define LJLIB_REC(handler)
@@ -88,6 +86,10 @@ static LJ_AINLINE void lj_lib_pushcc(lua_State *L, lua_CFunction f,
88 86
89LJ_FUNC void lj_lib_register(lua_State *L, const char *libname, 87LJ_FUNC void lj_lib_register(lua_State *L, const char *libname,
90 const uint8_t *init, const lua_CFunction *cf); 88 const uint8_t *init, const lua_CFunction *cf);
89LJ_FUNC void lj_lib_prereg(lua_State *L, const char *name, lua_CFunction f,
90 GCtab *env);
91LJ_FUNC int lj_lib_postreg(lua_State *L, lua_CFunction cf, int id,
92 const char *name);
91 93
92/* Library init data tags. */ 94/* Library init data tags. */
93#define LIBINIT_LENMASK 0x3f 95#define LIBINIT_LENMASK 0x3f
@@ -96,7 +98,8 @@ LJ_FUNC void lj_lib_register(lua_State *L, const char *libname,
96#define LIBINIT_ASM 0x40 98#define LIBINIT_ASM 0x40
97#define LIBINIT_ASM_ 0x80 99#define LIBINIT_ASM_ 0x80
98#define LIBINIT_STRING 0xc0 100#define LIBINIT_STRING 0xc0
99#define LIBINIT_MAXSTR 0x39 101#define LIBINIT_MAXSTR 0x38
102#define LIBINIT_LUA 0xf9
100#define LIBINIT_SET 0xfa 103#define LIBINIT_SET 0xfa
101#define LIBINIT_NUMBER 0xfb 104#define LIBINIT_NUMBER 0xfb
102#define LIBINIT_COPY 0xfc 105#define LIBINIT_COPY 0xfc
diff --git a/src/lj_load.c b/src/lj_load.c
index 20be8ebe..9a31d9a1 100644
--- a/src/lj_load.c
+++ b/src/lj_load.c
@@ -15,7 +15,7 @@
15#include "lj_obj.h" 15#include "lj_obj.h"
16#include "lj_gc.h" 16#include "lj_gc.h"
17#include "lj_err.h" 17#include "lj_err.h"
18#include "lj_str.h" 18#include "lj_buf.h"
19#include "lj_func.h" 19#include "lj_func.h"
20#include "lj_frame.h" 20#include "lj_frame.h"
21#include "lj_vm.h" 21#include "lj_vm.h"
@@ -54,7 +54,7 @@ LUA_API int lua_loadx(lua_State *L, lua_Reader reader, void *data,
54 ls.rdata = data; 54 ls.rdata = data;
55 ls.chunkarg = chunkname ? chunkname : "?"; 55 ls.chunkarg = chunkname ? chunkname : "?";
56 ls.mode = mode; 56 ls.mode = mode;
57 lj_str_initbuf(&ls.sb); 57 lj_buf_init(L, &ls.sb);
58 status = lj_vm_cpcall(L, NULL, &ls, cpparser); 58 status = lj_vm_cpcall(L, NULL, &ls, cpparser);
59 lj_lex_cleanup(L, &ls); 59 lj_lex_cleanup(L, &ls);
60 lj_gc_check(L); 60 lj_gc_check(L);
diff --git a/src/lj_mcode.c b/src/lj_mcode.c
index f0a1f699..77035bf7 100644
--- a/src/lj_mcode.c
+++ b/src/lj_mcode.c
@@ -221,8 +221,8 @@ static void *mcode_alloc(jit_State *J, size_t sz)
221 */ 221 */
222#if LJ_TARGET_MIPS 222#if LJ_TARGET_MIPS
223 /* Use the middle of the 256MB-aligned region. */ 223 /* Use the middle of the 256MB-aligned region. */
224 uintptr_t target = ((uintptr_t)(void *)lj_vm_exit_handler & 0xf0000000u) + 224 uintptr_t target = ((uintptr_t)(void *)lj_vm_exit_handler &
225 0x08000000u; 225 ~(uintptr_t)0x0fffffffu) + 0x08000000u;
226#else 226#else
227 uintptr_t target = (uintptr_t)(void *)lj_vm_exit_handler & ~(uintptr_t)0xffff; 227 uintptr_t target = (uintptr_t)(void *)lj_vm_exit_handler & ~(uintptr_t)0xffff;
228#endif 228#endif
diff --git a/src/lj_meta.c b/src/lj_meta.c
index 10e34984..0bd4d842 100644
--- a/src/lj_meta.c
+++ b/src/lj_meta.c
@@ -12,6 +12,7 @@
12#include "lj_obj.h" 12#include "lj_obj.h"
13#include "lj_gc.h" 13#include "lj_gc.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_buf.h"
15#include "lj_str.h" 16#include "lj_str.h"
16#include "lj_tab.h" 17#include "lj_tab.h"
17#include "lj_meta.h" 18#include "lj_meta.h"
@@ -19,6 +20,8 @@
19#include "lj_bc.h" 20#include "lj_bc.h"
20#include "lj_vm.h" 21#include "lj_vm.h"
21#include "lj_strscan.h" 22#include "lj_strscan.h"
23#include "lj_strfmt.h"
24#include "lj_lib.h"
22 25
23/* -- Metamethod handling ------------------------------------------------- */ 26/* -- Metamethod handling ------------------------------------------------- */
24 27
@@ -77,12 +80,16 @@ int lj_meta_tailcall(lua_State *L, cTValue *tv)
77 TValue *base = L->base; 80 TValue *base = L->base;
78 TValue *top = L->top; 81 TValue *top = L->top;
79 const BCIns *pc = frame_pc(base-1); /* Preserve old PC from frame. */ 82 const BCIns *pc = frame_pc(base-1); /* Preserve old PC from frame. */
80 copyTV(L, base-1, tv); /* Replace frame with new object. */ 83 copyTV(L, base-1-LJ_FR2, tv); /* Replace frame with new object. */
81 top->u32.lo = LJ_CONT_TAILCALL; 84 if (LJ_FR2)
82 setframe_pc(top, pc); 85 (top++)->u64 = LJ_CONT_TAILCALL;
83 setframe_gc(top+1, obj2gco(L)); /* Dummy frame object. */ 86 else
84 setframe_ftsz(top+1, (int)((char *)(top+2) - (char *)base) + FRAME_CONT); 87 top->u32.lo = LJ_CONT_TAILCALL;
85 L->base = L->top = top+2; 88 setframe_pc(top++, pc);
89 if (LJ_FR2) top++;
90 setframe_gc(top, obj2gco(L), LJ_TTHREAD); /* Dummy frame object. */
91 setframe_ftsz(top, ((char *)(top+1) - (char *)base) + FRAME_CONT);
92 L->base = L->top = top+1;
86 /* 93 /*
87 ** before: [old_mo|PC] [... ...] 94 ** before: [old_mo|PC] [... ...]
88 ** ^base ^top 95 ** ^base ^top
@@ -113,11 +120,13 @@ static TValue *mmcall(lua_State *L, ASMFunction cont, cTValue *mo,
113 */ 120 */
114 TValue *top = L->top; 121 TValue *top = L->top;
115 if (curr_funcisL(L)) top = curr_topL(L); 122 if (curr_funcisL(L)) top = curr_topL(L);
116 setcont(top, cont); /* Assembler VM stores PC in upper word. */ 123 setcont(top++, cont); /* Assembler VM stores PC in upper word or FR2. */
117 copyTV(L, top+1, mo); /* Store metamethod and two arguments. */ 124 if (LJ_FR2) setnilV(top++);
118 copyTV(L, top+2, a); 125 copyTV(L, top++, mo); /* Store metamethod and two arguments. */
119 copyTV(L, top+3, b); 126 if (LJ_FR2) setnilV(top++);
120 return top+2; /* Return new base. */ 127 copyTV(L, top, a);
128 copyTV(L, top+1, b);
129 return top; /* Return new base. */
121} 130}
122 131
123/* -- C helpers for some instructions, called from assembler VM ----------- */ 132/* -- C helpers for some instructions, called from assembler VM ----------- */
@@ -225,27 +234,14 @@ TValue *lj_meta_arith(lua_State *L, TValue *ra, cTValue *rb, cTValue *rc,
225 } 234 }
226} 235}
227 236
228/* In-place coercion of a number to a string. */
229static LJ_AINLINE int tostring(lua_State *L, TValue *o)
230{
231 if (tvisstr(o)) {
232 return 1;
233 } else if (tvisnumber(o)) {
234 setstrV(L, o, lj_str_fromnumber(L, o));
235 return 1;
236 } else {
237 return 0;
238 }
239}
240
241/* Helper for CAT. Coercion, iterative concat, __concat metamethod. */ 237/* Helper for CAT. Coercion, iterative concat, __concat metamethod. */
242TValue *lj_meta_cat(lua_State *L, TValue *top, int left) 238TValue *lj_meta_cat(lua_State *L, TValue *top, int left)
243{ 239{
244 int fromc = 0; 240 int fromc = 0;
245 if (left < 0) { left = -left; fromc = 1; } 241 if (left < 0) { left = -left; fromc = 1; }
246 do { 242 do {
247 int n = 1; 243 if (!(tvisstr(top) || tvisnumber(top)) ||
248 if (!(tvisstr(top-1) || tvisnumber(top-1)) || !tostring(L, top)) { 244 !(tvisstr(top-1) || tvisnumber(top-1))) {
249 cTValue *mo = lj_meta_lookup(L, top-1, MM_concat); 245 cTValue *mo = lj_meta_lookup(L, top-1, MM_concat);
250 if (tvisnil(mo)) { 246 if (tvisnil(mo)) {
251 mo = lj_meta_lookup(L, top, MM_concat); 247 mo = lj_meta_lookup(L, top, MM_concat);
@@ -266,13 +262,12 @@ TValue *lj_meta_cat(lua_State *L, TValue *top, int left)
266 ** after mm: [...][CAT stack ...] <--push-- [result] 262 ** after mm: [...][CAT stack ...] <--push-- [result]
267 ** next step: [...][CAT stack .............] 263 ** next step: [...][CAT stack .............]
268 */ 264 */
269 copyTV(L, top+2, top); /* Careful with the order of stack copies! */ 265 copyTV(L, top+2*LJ_FR2+2, top); /* Carefully ordered stack copies! */
270 copyTV(L, top+1, top-1); 266 copyTV(L, top+2*LJ_FR2+1, top-1);
271 copyTV(L, top, mo); 267 copyTV(L, top+LJ_FR2, mo);
272 setcont(top-1, lj_cont_cat); 268 setcont(top-1, lj_cont_cat);
269 if (LJ_FR2) { setnilV(top); setnilV(top+2); top += 2; }
273 return top+1; /* Trigger metamethod call. */ 270 return top+1; /* Trigger metamethod call. */
274 } else if (strV(top)->len == 0) { /* Shortcut. */
275 (void)tostring(L, top-1);
276 } else { 271 } else {
277 /* Pick as many strings as possible from the top and concatenate them: 272 /* Pick as many strings as possible from the top and concatenate them:
278 ** 273 **
@@ -281,27 +276,28 @@ TValue *lj_meta_cat(lua_State *L, TValue *top, int left)
281 ** concat: [...][CAT stack ...] [result] 276 ** concat: [...][CAT stack ...] [result]
282 ** next step: [...][CAT stack ............] 277 ** next step: [...][CAT stack ............]
283 */ 278 */
284 MSize tlen = strV(top)->len; 279 TValue *e, *o = top;
285 char *buffer; 280 uint64_t tlen = tvisstr(o) ? strV(o)->len : STRFMT_MAXBUF_NUM;
286 int i; 281 SBuf *sb;
287 for (n = 1; n <= left && tostring(L, top-n); n++) { 282 do {
288 MSize len = strV(top-n)->len; 283 o--; tlen += tvisstr(o) ? strV(o)->len : STRFMT_MAXBUF_NUM;
289 if (len >= LJ_MAX_STR - tlen) 284 } while (--left > 0 && (tvisstr(o-1) || tvisnumber(o-1)));
290 lj_err_msg(L, LJ_ERR_STROV); 285 if (tlen >= LJ_MAX_STR) lj_err_msg(L, LJ_ERR_STROV);
291 tlen += len; 286 sb = lj_buf_tmp_(L);
292 } 287 lj_buf_more(sb, (MSize)tlen);
293 buffer = lj_str_needbuf(L, &G(L)->tmpbuf, tlen); 288 for (e = top, top = o; o <= e; o++) {
294 n--; 289 if (tvisstr(o)) {
295 tlen = 0; 290 GCstr *s = strV(o);
296 for (i = n; i >= 0; i--) { 291 MSize len = s->len;
297 MSize len = strV(top-i)->len; 292 lj_buf_putmem(sb, strdata(s), len);
298 memcpy(buffer + tlen, strVdata(top-i), len); 293 } else if (tvisint(o)) {
299 tlen += len; 294 lj_strfmt_putint(sb, intV(o));
295 } else {
296 lj_strfmt_putfnum(sb, STRFMT_G14, numV(o));
297 }
300 } 298 }
301 setstrV(L, top-n, lj_str_new(L, buffer, tlen)); 299 setstrV(L, top, lj_buf_str(L, sb));
302 } 300 }
303 left -= n;
304 top -= n;
305 } while (left >= 1); 301 } while (left >= 1);
306 if (LJ_UNLIKELY(G(L)->gc.total >= G(L)->gc.threshold)) { 302 if (LJ_UNLIKELY(G(L)->gc.total >= G(L)->gc.threshold)) {
307 if (!fromc) L->top = curr_topL(L); 303 if (!fromc) L->top = curr_topL(L);
@@ -338,12 +334,14 @@ TValue *lj_meta_equal(lua_State *L, GCobj *o1, GCobj *o2, int ne)
338 return (TValue *)(intptr_t)ne; 334 return (TValue *)(intptr_t)ne;
339 } 335 }
340 top = curr_top(L); 336 top = curr_top(L);
341 setcont(top, ne ? lj_cont_condf : lj_cont_condt); 337 setcont(top++, ne ? lj_cont_condf : lj_cont_condt);
342 copyTV(L, top+1, mo); 338 if (LJ_FR2) setnilV(top++);
339 copyTV(L, top++, mo);
340 if (LJ_FR2) setnilV(top++);
343 it = ~(uint32_t)o1->gch.gct; 341 it = ~(uint32_t)o1->gch.gct;
344 setgcV(L, top+2, o1, it); 342 setgcV(L, top, o1, it);
345 setgcV(L, top+3, o2, it); 343 setgcV(L, top+1, o2, it);
346 return top+2; /* Trigger metamethod call. */ 344 return top; /* Trigger metamethod call. */
347 } 345 }
348 return (TValue *)(intptr_t)ne; 346 return (TValue *)(intptr_t)ne;
349} 347}
@@ -366,7 +364,7 @@ TValue * LJ_FASTCALL lj_meta_equal_cd(lua_State *L, BCIns ins)
366 o2 = &mref(curr_proto(L)->k, cTValue)[bc_d(ins)]; 364 o2 = &mref(curr_proto(L)->k, cTValue)[bc_d(ins)];
367 } else { 365 } else {
368 lua_assert(op == BC_ISEQP); 366 lua_assert(op == BC_ISEQP);
369 setitype(&tv, ~bc_d(ins)); 367 setpriV(&tv, ~bc_d(ins));
370 o2 = &tv; 368 o2 = &tv;
371 } 369 }
372 mo = lj_meta_lookup(L, o1mm, MM_eq); 370 mo = lj_meta_lookup(L, o1mm, MM_eq);
@@ -423,6 +421,18 @@ TValue *lj_meta_comp(lua_State *L, cTValue *o1, cTValue *o2, int op)
423 } 421 }
424} 422}
425 423
424/* Helper for ISTYPE and ISNUM. Implicit coercion or error. */
425void lj_meta_istype(lua_State *L, BCReg ra, BCReg tp)
426{
427 L->top = curr_topL(L);
428 ra++; tp--;
429 lua_assert(LJ_DUALNUM || tp != ~LJ_TNUMX); /* ISTYPE -> ISNUM broken. */
430 if (LJ_DUALNUM && tp == ~LJ_TNUMX) lj_lib_checkint(L, ra);
431 else if (tp == ~LJ_TNUMX+1) lj_lib_checknum(L, ra);
432 else if (tp == ~LJ_TSTR) lj_lib_checkstr(L, ra);
433 else lj_err_argtype(L, ra, lj_obj_itypename[tp]);
434}
435
426/* Helper for calls. __call metamethod. */ 436/* Helper for calls. __call metamethod. */
427void lj_meta_call(lua_State *L, TValue *func, TValue *top) 437void lj_meta_call(lua_State *L, TValue *func, TValue *top)
428{ 438{
@@ -430,7 +440,8 @@ void lj_meta_call(lua_State *L, TValue *func, TValue *top)
430 TValue *p; 440 TValue *p;
431 if (!tvisfunc(mo)) 441 if (!tvisfunc(mo))
432 lj_err_optype_call(L, func); 442 lj_err_optype_call(L, func);
433 for (p = top; p > func; p--) copyTV(L, p, p-1); 443 for (p = top; p > func+2*LJ_FR2; p--) copyTV(L, p, p-1);
444 if (LJ_FR2) copyTV(L, func+2, func);
434 copyTV(L, func, mo); 445 copyTV(L, func, mo);
435} 446}
436 447
diff --git a/src/lj_meta.h b/src/lj_meta.h
index e061d99e..73b45724 100644
--- a/src/lj_meta.h
+++ b/src/lj_meta.h
@@ -31,6 +31,7 @@ LJ_FUNCA TValue * LJ_FASTCALL lj_meta_len(lua_State *L, cTValue *o);
31LJ_FUNCA TValue *lj_meta_equal(lua_State *L, GCobj *o1, GCobj *o2, int ne); 31LJ_FUNCA TValue *lj_meta_equal(lua_State *L, GCobj *o1, GCobj *o2, int ne);
32LJ_FUNCA TValue * LJ_FASTCALL lj_meta_equal_cd(lua_State *L, BCIns ins); 32LJ_FUNCA TValue * LJ_FASTCALL lj_meta_equal_cd(lua_State *L, BCIns ins);
33LJ_FUNCA TValue *lj_meta_comp(lua_State *L, cTValue *o1, cTValue *o2, int op); 33LJ_FUNCA TValue *lj_meta_comp(lua_State *L, cTValue *o1, cTValue *o2, int op);
34LJ_FUNCA void lj_meta_istype(lua_State *L, BCReg ra, BCReg tp);
34LJ_FUNCA void lj_meta_call(lua_State *L, TValue *func, TValue *top); 35LJ_FUNCA void lj_meta_call(lua_State *L, TValue *func, TValue *top);
35LJ_FUNCA void LJ_FASTCALL lj_meta_for(lua_State *L, TValue *o); 36LJ_FUNCA void LJ_FASTCALL lj_meta_for(lua_State *L, TValue *o);
36 37
diff --git a/src/lj_obj.c b/src/lj_obj.c
index 4779d26d..ee33aeb3 100644
--- a/src/lj_obj.c
+++ b/src/lj_obj.c
@@ -20,7 +20,7 @@ LJ_DATADEF const char *const lj_obj_itypename[] = { /* ORDER LJ_T */
20}; 20};
21 21
22/* Compare two objects without calling metamethods. */ 22/* Compare two objects without calling metamethods. */
23int lj_obj_equal(cTValue *o1, cTValue *o2) 23int LJ_FASTCALL lj_obj_equal(cTValue *o1, cTValue *o2)
24{ 24{
25 if (itype(o1) == itype(o2)) { 25 if (itype(o1) == itype(o2)) {
26 if (tvispri(o1)) 26 if (tvispri(o1))
@@ -33,3 +33,18 @@ int lj_obj_equal(cTValue *o1, cTValue *o2)
33 return numberVnum(o1) == numberVnum(o2); 33 return numberVnum(o1) == numberVnum(o2);
34} 34}
35 35
36/* Return pointer to object or its object data. */
37const void * LJ_FASTCALL lj_obj_ptr(cTValue *o)
38{
39 if (tvisudata(o))
40 return uddata(udataV(o));
41 else if (tvislightud(o))
42 return lightudV(o);
43 else if (LJ_HASFFI && tviscdata(o))
44 return cdataptr(cdataV(o));
45 else if (tvisgcv(o))
46 return gcV(o);
47 else
48 return NULL;
49}
50
diff --git a/src/lj_obj.h b/src/lj_obj.h
index e70b0032..52372c3e 100644
--- a/src/lj_obj.h
+++ b/src/lj_obj.h
@@ -15,42 +15,75 @@
15 15
16/* -- Memory references (32 bit address space) ---------------------------- */ 16/* -- Memory references (32 bit address space) ---------------------------- */
17 17
18/* Memory size. */ 18/* Memory and GC object sizes. */
19typedef uint32_t MSize; 19typedef uint32_t MSize;
20#if LJ_GC64
21typedef uint64_t GCSize;
22#else
23typedef uint32_t GCSize;
24#endif
20 25
21/* Memory reference */ 26/* Memory reference */
22typedef struct MRef { 27typedef struct MRef {
28#if LJ_GC64
29 uint64_t ptr64; /* True 64 bit pointer. */
30#else
23 uint32_t ptr32; /* Pseudo 32 bit pointer. */ 31 uint32_t ptr32; /* Pseudo 32 bit pointer. */
32#endif
24} MRef; 33} MRef;
25 34
35#if LJ_GC64
36#define mref(r, t) ((t *)(void *)(r).ptr64)
37
38#define setmref(r, p) ((r).ptr64 = (uint64_t)(void *)(p))
39#define setmrefr(r, v) ((r).ptr64 = (v).ptr64)
40#else
26#define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32) 41#define mref(r, t) ((t *)(void *)(uintptr_t)(r).ptr32)
27 42
28#define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p)) 43#define setmref(r, p) ((r).ptr32 = (uint32_t)(uintptr_t)(void *)(p))
29#define setmrefr(r, v) ((r).ptr32 = (v).ptr32) 44#define setmrefr(r, v) ((r).ptr32 = (v).ptr32)
45#endif
30 46
31/* -- GC object references (32 bit address space) ------------------------- */ 47/* -- GC object references (32 bit address space) ------------------------- */
32 48
33/* GCobj reference */ 49/* GCobj reference */
34typedef struct GCRef { 50typedef struct GCRef {
51#if LJ_GC64
52 uint64_t gcptr64; /* True 64 bit pointer. */
53#else
35 uint32_t gcptr32; /* Pseudo 32 bit pointer. */ 54 uint32_t gcptr32; /* Pseudo 32 bit pointer. */
55#endif
36} GCRef; 56} GCRef;
37 57
38/* Common GC header for all collectable objects. */ 58/* Common GC header for all collectable objects. */
39#define GCHeader GCRef nextgc; uint8_t marked; uint8_t gct 59#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. */ 60/* This occupies 6 bytes, so use the next 2 bytes for non-32 bit fields. */
41 61
62#if LJ_GC64
63#define gcref(r) ((GCobj *)(r).gcptr64)
64#define gcrefp(r, t) ((t *)(void *)(r).gcptr64)
65#define gcrefu(r) ((r).gcptr64)
66#define gcrefeq(r1, r2) ((r1).gcptr64 == (r2).gcptr64)
67
68#define setgcref(r, gc) ((r).gcptr64 = (uint64_t)&(gc)->gch)
69#define setgcreft(r, gc, it) \
70 (r).gcptr64 = (uint64_t)&(gc)->gch | (((uint64_t)(it)) << 47)
71#define setgcrefp(r, p) ((r).gcptr64 = (uint64_t)(p))
72#define setgcrefnull(r) ((r).gcptr64 = 0)
73#define setgcrefr(r, v) ((r).gcptr64 = (v).gcptr64)
74#else
42#define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32) 75#define gcref(r) ((GCobj *)(uintptr_t)(r).gcptr32)
43#define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32) 76#define gcrefp(r, t) ((t *)(void *)(uintptr_t)(r).gcptr32)
44#define gcrefu(r) ((r).gcptr32) 77#define gcrefu(r) ((r).gcptr32)
45#define gcrefi(r) ((int32_t)(r).gcptr32)
46#define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32) 78#define gcrefeq(r1, r2) ((r1).gcptr32 == (r2).gcptr32)
47#define gcnext(gc) (gcref((gc)->gch.nextgc))
48 79
49#define setgcref(r, gc) ((r).gcptr32 = (uint32_t)(uintptr_t)&(gc)->gch) 80#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)) 81#define setgcrefp(r, p) ((r).gcptr32 = (uint32_t)(uintptr_t)(p))
52#define setgcrefnull(r) ((r).gcptr32 = 0) 82#define setgcrefnull(r) ((r).gcptr32 = 0)
53#define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32) 83#define setgcrefr(r, v) ((r).gcptr32 = (v).gcptr32)
84#endif
85
86#define gcnext(gc) (gcref((gc)->gch.nextgc))
54 87
55/* IMPORTANT NOTE: 88/* IMPORTANT NOTE:
56** 89**
@@ -119,11 +152,12 @@ typedef int32_t BCLine; /* Bytecode line number. */
119/* Internal assembler functions. Never call these directly from C. */ 152/* Internal assembler functions. Never call these directly from C. */
120typedef void (*ASMFunction)(void); 153typedef void (*ASMFunction)(void);
121 154
122/* Resizable string buffer. Need this here, details in lj_str.h. */ 155/* Resizable string buffer. Need this here, details in lj_buf.h. */
123typedef struct SBuf { 156typedef struct SBuf {
124 char *buf; /* String buffer base. */ 157 MRef p; /* String buffer pointer. */
125 MSize n; /* String buffer length. */ 158 MRef e; /* String buffer end pointer. */
126 MSize sz; /* String buffer size. */ 159 MRef b; /* String buffer base. */
160 MRef L; /* lua_State, used for buffer resizing. */
127} SBuf; 161} SBuf;
128 162
129/* -- Tags and values ----------------------------------------------------- */ 163/* -- Tags and values ----------------------------------------------------- */
@@ -131,13 +165,23 @@ typedef struct SBuf {
131/* Frame link. */ 165/* Frame link. */
132typedef union { 166typedef union {
133 int32_t ftsz; /* Frame type and size of previous frame. */ 167 int32_t ftsz; /* Frame type and size of previous frame. */
134 MRef pcr; /* Overlaps PC for Lua frames. */ 168 MRef pcr; /* Or PC for Lua frames. */
135} FrameLink; 169} FrameLink;
136 170
137/* Tagged value. */ 171/* Tagged value. */
138typedef LJ_ALIGN(8) union TValue { 172typedef LJ_ALIGN(8) union TValue {
139 uint64_t u64; /* 64 bit pattern overlaps number. */ 173 uint64_t u64; /* 64 bit pattern overlaps number. */
140 lua_Number n; /* Number object overlaps split tag/value object. */ 174 lua_Number n; /* Number object overlaps split tag/value object. */
175#if LJ_GC64
176 GCRef gcr; /* GCobj reference with tag. */
177 int64_t it64;
178 struct {
179 LJ_ENDIAN_LOHI(
180 int32_t i; /* Integer value. */
181 , uint32_t it; /* Internal object tag. Must overlap MSW of number. */
182 )
183 };
184#else
141 struct { 185 struct {
142 LJ_ENDIAN_LOHI( 186 LJ_ENDIAN_LOHI(
143 union { 187 union {
@@ -147,12 +191,17 @@ typedef LJ_ALIGN(8) union TValue {
147 , uint32_t it; /* Internal object tag. Must overlap MSW of number. */ 191 , uint32_t it; /* Internal object tag. Must overlap MSW of number. */
148 ) 192 )
149 }; 193 };
194#endif
195#if LJ_FR2
196 int64_t ftsz; /* Frame type and size of previous frame, or PC. */
197#else
150 struct { 198 struct {
151 LJ_ENDIAN_LOHI( 199 LJ_ENDIAN_LOHI(
152 GCRef func; /* Function for next frame (or dummy L). */ 200 GCRef func; /* Function for next frame (or dummy L). */
153 , FrameLink tp; /* Link to previous frame. */ 201 , FrameLink tp; /* Link to previous frame. */
154 ) 202 )
155 } fr; 203 } fr;
204#endif
156 struct { 205 struct {
157 LJ_ENDIAN_LOHI( 206 LJ_ENDIAN_LOHI(
158 uint32_t lo; /* Lower 32 bits of number. */ 207 uint32_t lo; /* Lower 32 bits of number. */
@@ -172,6 +221,8 @@ typedef const TValue cTValue;
172 221
173/* Internal object tags. 222/* Internal object tags.
174** 223**
224** Format for 32 bit GC references (!LJ_GC64):
225**
175** Internal tags overlap the MSW of a number object (must be a double). 226** Internal tags overlap the MSW of a number object (must be a double).
176** Interpreted as a double these are special NaNs. The FPU only generates 227** Interpreted as a double these are special NaNs. The FPU only generates
177** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available 228** one type of NaN (0xfff8_0000_0000_0000). So MSWs > 0xfff80000 are available
@@ -186,6 +237,18 @@ typedef const TValue cTValue;
186** int (LJ_DUALNUM)| itype | int | 237** int (LJ_DUALNUM)| itype | int |
187** number -------double------ 238** number -------double------
188** 239**
240** Format for 64 bit GC references (LJ_GC64):
241**
242** The upper 13 bits must be 1 (0xfff8...) for a special NaN. The next
243** 4 bits hold the internal tag. The lowest 47 bits either hold a pointer,
244** a zero-extended 32 bit integer or all bits set to 1 for primitive types.
245**
246** ------MSW------.------LSW------
247** primitive types |1..1|itype|1..................1|
248** GC objects/lightud |1..1|itype|-------GCRef--------|
249** int (LJ_DUALNUM) |1..1|itype|0..0|-----int-------|
250** number ------------double-------------
251**
189** ORDER LJ_T 252** ORDER LJ_T
190** Primitive types nil/false/true must be first, lightuserdata next. 253** Primitive types nil/false/true must be first, lightuserdata next.
191** GC objects are at the end, table/userdata must be lowest. 254** GC objects are at the end, table/userdata must be lowest.
@@ -208,7 +271,7 @@ typedef const TValue cTValue;
208#define LJ_TNUMX (~13u) 271#define LJ_TNUMX (~13u)
209 272
210/* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */ 273/* Integers have itype == LJ_TISNUM doubles have itype < LJ_TISNUM */
211#if LJ_64 274#if LJ_64 && !LJ_GC64
212#define LJ_TISNUM 0xfffeffffu 275#define LJ_TISNUM 0xfffeffffu
213#else 276#else
214#define LJ_TISNUM LJ_TNUMX 277#define LJ_TISNUM LJ_TNUMX
@@ -218,6 +281,10 @@ typedef const TValue cTValue;
218#define LJ_TISGCV (LJ_TSTR+1) 281#define LJ_TISGCV (LJ_TSTR+1)
219#define LJ_TISTABUD LJ_TTAB 282#define LJ_TISTABUD LJ_TTAB
220 283
284#if LJ_GC64
285#define LJ_GCVMASK (((uint64_t)1 << 47) - 1)
286#endif
287
221/* -- String object ------------------------------------------------------- */ 288/* -- String object ------------------------------------------------------- */
222 289
223/* String object header. String payload follows. */ 290/* String object header. String payload follows. */
@@ -291,6 +358,9 @@ typedef struct GCproto {
291 uint8_t numparams; /* Number of parameters. */ 358 uint8_t numparams; /* Number of parameters. */
292 uint8_t framesize; /* Fixed frame size. */ 359 uint8_t framesize; /* Fixed frame size. */
293 MSize sizebc; /* Number of bytecode instructions. */ 360 MSize sizebc; /* Number of bytecode instructions. */
361#if LJ_GC64
362 uint32_t unused_gc64;
363#endif
294 GCRef gclist; 364 GCRef gclist;
295 MRef k; /* Split constant array (points to the middle). */ 365 MRef k; /* Split constant array (points to the middle). */
296 MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */ 366 MRef uv; /* Upvalue list. local slot|0x8000 or parent uv idx. */
@@ -402,7 +472,9 @@ typedef struct Node {
402 TValue val; /* Value object. Must be first field. */ 472 TValue val; /* Value object. Must be first field. */
403 TValue key; /* Key object. */ 473 TValue key; /* Key object. */
404 MRef next; /* Hash chain. */ 474 MRef next; /* Hash chain. */
475#if !LJ_GC64
405 MRef freetop; /* Top of free elements (stored in t->node[0]). */ 476 MRef freetop; /* Top of free elements (stored in t->node[0]). */
477#endif
406} Node; 478} Node;
407 479
408LJ_STATIC_ASSERT(offsetof(Node, val) == 0); 480LJ_STATIC_ASSERT(offsetof(Node, val) == 0);
@@ -417,12 +489,22 @@ typedef struct GCtab {
417 MRef node; /* Hash part. */ 489 MRef node; /* Hash part. */
418 uint32_t asize; /* Size of array part (keys [0, asize-1]). */ 490 uint32_t asize; /* Size of array part (keys [0, asize-1]). */
419 uint32_t hmask; /* Hash part mask (size of hash part - 1). */ 491 uint32_t hmask; /* Hash part mask (size of hash part - 1). */
492#if LJ_GC64
493 MRef freetop; /* Top of free elements. */
494#endif
420} GCtab; 495} GCtab;
421 496
422#define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab)) 497#define sizetabcolo(n) ((n)*sizeof(TValue) + sizeof(GCtab))
423#define tabref(r) (&gcref((r))->tab) 498#define tabref(r) (&gcref((r))->tab)
424#define noderef(r) (mref((r), Node)) 499#define noderef(r) (mref((r), Node))
425#define nextnode(n) (mref((n)->next, Node)) 500#define nextnode(n) (mref((n)->next, Node))
501#if LJ_GC64
502#define getfreetop(t, n) (noderef((t)->freetop))
503#define setfreetop(t, n, v) (setmref((t)->freetop, (v)))
504#else
505#define getfreetop(t, n) (noderef((n)->freetop))
506#define setfreetop(t, n, v) (setmref((n)->freetop, (v)))
507#endif
426 508
427/* -- State objects ------------------------------------------------------- */ 509/* -- State objects ------------------------------------------------------- */
428 510
@@ -489,8 +571,8 @@ typedef enum {
489#define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)])) 571#define mmname_str(g, mm) (strref((g)->gcroot[GCROOT_MMNAME+(mm)]))
490 572
491typedef struct GCState { 573typedef struct GCState {
492 MSize total; /* Memory currently allocated. */ 574 GCSize total; /* Memory currently allocated. */
493 MSize threshold; /* Memory threshold. */ 575 GCSize threshold; /* Memory threshold. */
494 uint8_t currentwhite; /* Current white color. */ 576 uint8_t currentwhite; /* Current white color. */
495 uint8_t state; /* GC state. */ 577 uint8_t state; /* GC state. */
496 uint8_t nocdatafin; /* No cdata finalizer called. */ 578 uint8_t nocdatafin; /* No cdata finalizer called. */
@@ -502,9 +584,9 @@ typedef struct GCState {
502 GCRef grayagain; /* List of objects for atomic traversal. */ 584 GCRef grayagain; /* List of objects for atomic traversal. */
503 GCRef weak; /* List of weak tables (to be cleared). */ 585 GCRef weak; /* List of weak tables (to be cleared). */
504 GCRef mmudata; /* List of userdata (to be finalized). */ 586 GCRef mmudata; /* List of userdata (to be finalized). */
587 GCSize debt; /* Debt (how much GC is behind schedule). */
588 GCSize estimate; /* Estimate of memory actually in use. */
505 MSize stepmul; /* Incremental GC step granularity. */ 589 MSize stepmul; /* Incremental GC step granularity. */
506 MSize debt; /* Debt (how much GC is behind schedule). */
507 MSize estimate; /* Estimate of memory actually in use. */
508 MSize pause; /* Pause between successive GC cycles. */ 590 MSize pause; /* Pause between successive GC cycles. */
509} GCState; 591} GCState;
510 592
@@ -516,8 +598,8 @@ typedef struct global_State {
516 lua_Alloc allocf; /* Memory allocator. */ 598 lua_Alloc allocf; /* Memory allocator. */
517 void *allocd; /* Memory allocator data. */ 599 void *allocd; /* Memory allocator data. */
518 GCState gc; /* Garbage collector. */ 600 GCState gc; /* Garbage collector. */
519 SBuf tmpbuf; /* Temporary buffer for string concatenation. */ 601 volatile int32_t vmstate; /* VM state or current JIT code trace number. */
520 Node nilnode; /* Fallback 1-element hash part (nil key and value). */ 602 SBuf tmpbuf; /* Temporary string buffer. */
521 GCstr strempty; /* Empty string. */ 603 GCstr strempty; /* Empty string. */
522 uint8_t stremptyz; /* Zero terminator of empty string. */ 604 uint8_t stremptyz; /* Zero terminator of empty string. */
523 uint8_t hookmask; /* Hook mask. */ 605 uint8_t hookmask; /* Hook mask. */
@@ -526,17 +608,17 @@ typedef struct global_State {
526 GCRef mainthref; /* Link to main thread. */ 608 GCRef mainthref; /* Link to main thread. */
527 TValue registrytv; /* Anchor for registry. */ 609 TValue registrytv; /* Anchor for registry. */
528 TValue tmptv, tmptv2; /* Temporary TValues. */ 610 TValue tmptv, tmptv2; /* Temporary TValues. */
611 Node nilnode; /* Fallback 1-element hash part (nil key and value). */
529 GCupval uvhead; /* Head of double-linked list of all open upvalues. */ 612 GCupval uvhead; /* Head of double-linked list of all open upvalues. */
530 int32_t hookcount; /* Instruction hook countdown. */ 613 int32_t hookcount; /* Instruction hook countdown. */
531 int32_t hookcstart; /* Start count for instruction hook counter. */ 614 int32_t hookcstart; /* Start count for instruction hook counter. */
532 lua_Hook hookf; /* Hook function. */ 615 lua_Hook hookf; /* Hook function. */
533 lua_CFunction wrapf; /* Wrapper for C function calls. */ 616 lua_CFunction wrapf; /* Wrapper for C function calls. */
534 lua_CFunction panic; /* Called as a last resort for errors. */ 617 lua_CFunction panic; /* Called as a last resort for errors. */
535 volatile int32_t vmstate; /* VM state or current JIT code trace number. */
536 BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */ 618 BCIns bc_cfunc_int; /* Bytecode for internal C function calls. */
537 BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */ 619 BCIns bc_cfunc_ext; /* Bytecode for external C function calls. */
538 GCRef jit_L; /* Current JIT code lua_State or NULL. */ 620 GCRef cur_L; /* Currently executing lua_State. */
539 MRef jit_base; /* Current JIT code L->base. */ 621 MRef jit_base; /* Current JIT code L->base or NULL. */
540 MRef ctype_state; /* Pointer to C type state. */ 622 MRef ctype_state; /* Pointer to C type state. */
541 GCRef gcroot[GCROOT_MAX]; /* GC roots. */ 623 GCRef gcroot[GCROOT_MAX]; /* GC roots. */
542} global_State; 624} global_State;
@@ -553,6 +635,7 @@ typedef struct global_State {
553#define HOOK_ACTIVE_SHIFT 4 635#define HOOK_ACTIVE_SHIFT 4
554#define HOOK_VMEVENT 0x20 636#define HOOK_VMEVENT 0x20
555#define HOOK_GC 0x40 637#define HOOK_GC 0x40
638#define HOOK_PROFILE 0x80
556#define hook_active(g) ((g)->hookmask & HOOK_ACTIVE) 639#define hook_active(g) ((g)->hookmask & HOOK_ACTIVE)
557#define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE) 640#define hook_enter(g) ((g)->hookmask |= HOOK_ACTIVE)
558#define hook_entergc(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_GC)) 641#define hook_entergc(g) ((g)->hookmask |= (HOOK_ACTIVE|HOOK_GC))
@@ -583,7 +666,13 @@ struct lua_State {
583#define registry(L) (&G(L)->registrytv) 666#define registry(L) (&G(L)->registrytv)
584 667
585/* Macros to access the currently executing (Lua) function. */ 668/* Macros to access the currently executing (Lua) function. */
669#if LJ_GC64
670#define curr_func(L) (&gcval(L->base-2)->fn)
671#elif LJ_FR2
672#define curr_func(L) (&gcref((L->base-2)->gcr)->fn)
673#else
586#define curr_func(L) (&gcref((L->base-1)->fr.func)->fn) 674#define curr_func(L) (&gcref((L->base-1)->fr.func)->fn)
675#endif
587#define curr_funcisL(L) (isluafunc(curr_func(L))) 676#define curr_funcisL(L) (isluafunc(curr_func(L)))
588#define curr_proto(L) (funcproto(curr_func(L))) 677#define curr_proto(L) (funcproto(curr_func(L)))
589#define curr_topL(L) (L->base + curr_proto(L)->framesize) 678#define curr_topL(L) (L->base + curr_proto(L)->framesize)
@@ -647,12 +736,17 @@ typedef union GCobj {
647#endif 736#endif
648 737
649/* Macros to test types. */ 738/* Macros to test types. */
739#if LJ_GC64
740#define itype(o) ((uint32_t)((o)->it64 >> 47))
741#define tvisnil(o) ((o)->it64 == -1)
742#else
650#define itype(o) ((o)->it) 743#define itype(o) ((o)->it)
651#define tvisnil(o) (itype(o) == LJ_TNIL) 744#define tvisnil(o) (itype(o) == LJ_TNIL)
745#endif
652#define tvisfalse(o) (itype(o) == LJ_TFALSE) 746#define tvisfalse(o) (itype(o) == LJ_TFALSE)
653#define tvistrue(o) (itype(o) == LJ_TTRUE) 747#define tvistrue(o) (itype(o) == LJ_TTRUE)
654#define tvisbool(o) (tvisfalse(o) || tvistrue(o)) 748#define tvisbool(o) (tvisfalse(o) || tvistrue(o))
655#if LJ_64 749#if LJ_64 && !LJ_GC64
656#define tvislightud(o) (((int32_t)itype(o) >> 15) == -2) 750#define tvislightud(o) (((int32_t)itype(o) >> 15) == -2)
657#else 751#else
658#define tvislightud(o) (itype(o) == LJ_TLIGHTUD) 752#define tvislightud(o) (itype(o) == LJ_TLIGHTUD)
@@ -686,7 +780,7 @@ typedef union GCobj {
686#define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64) 780#define rawnumequal(o1, o2) ((o1)->u64 == (o2)->u64)
687 781
688/* Macros to convert type ids. */ 782/* Macros to convert type ids. */
689#if LJ_64 783#if LJ_64 && !LJ_GC64
690#define itypemap(o) \ 784#define itypemap(o) \
691 (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o)) 785 (tvisnumber(o) ? ~LJ_TNUMX : tvislightud(o) ? ~LJ_TLIGHTUD : ~itype(o))
692#else 786#else
@@ -694,8 +788,12 @@ typedef union GCobj {
694#endif 788#endif
695 789
696/* Macros to get tagged values. */ 790/* Macros to get tagged values. */
791#if LJ_GC64
792#define gcval(o) ((GCobj *)(gcrefu((o)->gcr) & LJ_GCVMASK))
793#else
697#define gcval(o) (gcref((o)->gcr)) 794#define gcval(o) (gcref((o)->gcr))
698#define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - (o)->it)) 795#endif
796#define boolV(o) check_exp(tvisbool(o), (LJ_TFALSE - itype(o)))
699#if LJ_64 797#if LJ_64
700#define lightudV(o) \ 798#define lightudV(o) \
701 check_exp(tvislightud(o), (void *)((o)->u64 & U64x(00007fff,ffffffff))) 799 check_exp(tvislightud(o), (void *)((o)->u64 & U64x(00007fff,ffffffff)))
@@ -714,13 +812,23 @@ typedef union GCobj {
714#define intV(o) check_exp(tvisint(o), (int32_t)(o)->i) 812#define intV(o) check_exp(tvisint(o), (int32_t)(o)->i)
715 813
716/* Macros to set tagged values. */ 814/* Macros to set tagged values. */
815#if LJ_GC64
816#define setitype(o, i) ((o)->it = ((i) << 15))
817#define setnilV(o) ((o)->it64 = -1)
818#define setpriV(o, x) ((o)->it64 = (int64_t)~((uint64_t)~(x)<<47))
819#define setboolV(o, x) ((o)->it64 = (int64_t)~((uint64_t)((x)+1)<<47))
820#else
717#define setitype(o, i) ((o)->it = (i)) 821#define setitype(o, i) ((o)->it = (i))
718#define setnilV(o) ((o)->it = LJ_TNIL) 822#define setnilV(o) ((o)->it = LJ_TNIL)
719#define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x)) 823#define setboolV(o, x) ((o)->it = LJ_TFALSE-(uint32_t)(x))
824#define setpriV(o, i) (setitype((o), (i)))
825#endif
720 826
721static LJ_AINLINE void setlightudV(TValue *o, void *p) 827static LJ_AINLINE void setlightudV(TValue *o, void *p)
722{ 828{
723#if LJ_64 829#if LJ_GC64
830 o->u64 = (uint64_t)p | (((uint64_t)LJ_TLIGHTUD) << 47);
831#elif LJ_64
724 o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48); 832 o->u64 = (uint64_t)p | (((uint64_t)0xffff) << 48);
725#else 833#else
726 setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD); 834 setgcrefp(o->gcr, p); setitype(o, LJ_TLIGHTUD);
@@ -730,20 +838,39 @@ static LJ_AINLINE void setlightudV(TValue *o, void *p)
730#if LJ_64 838#if LJ_64
731#define checklightudptr(L, p) \ 839#define checklightudptr(L, p) \
732 (((uint64_t)(p) >> 47) ? (lj_err_msg(L, LJ_ERR_BADLU), NULL) : (p)) 840 (((uint64_t)(p) >> 47) ? (lj_err_msg(L, LJ_ERR_BADLU), NULL) : (p))
841#else
842#define checklightudptr(L, p) (p)
843#endif
844
845#if LJ_FR2
846#define contptr(f) ((void *)(f))
847#define setcont(o, f) ((o)->u64 = (uint64_t)(uintptr_t)contptr(f))
848#elif LJ_64
849#define contptr(f) \
850 ((void *)(uintptr_t)(uint32_t)((intptr_t)(f) - (intptr_t)lj_vm_asm_begin))
733#define setcont(o, f) \ 851#define setcont(o, f) \
734 ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin) 852 ((o)->u64 = (uint64_t)(void *)(f) - (uint64_t)lj_vm_asm_begin)
735#else 853#else
736#define checklightudptr(L, p) (p) 854#define contptr(f) ((void *)(f))
737#define setcont(o, f) setlightudV((o), (void *)(f)) 855#define setcont(o, f) setlightudV((o), contptr(f))
738#endif 856#endif
739 857
740#define tvchecklive(L, o) \ 858#define tvchecklive(L, o) \
741 UNUSED(L), lua_assert(!tvisgcv(o) || \ 859 UNUSED(L), lua_assert(!tvisgcv(o) || \
742 ((~itype(o) == gcval(o)->gch.gct) && !isdead(G(L), gcval(o)))) 860 ((~itype(o) == gcval(o)->gch.gct) && !isdead(G(L), gcval(o))))
743 861
744static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t itype) 862static LJ_AINLINE void setgcVraw(TValue *o, GCobj *v, uint32_t itype)
745{ 863{
746 setgcref(o->gcr, v); setitype(o, itype); tvchecklive(L, o); 864#if LJ_GC64
865 setgcreft(o->gcr, v, itype);
866#else
867 setgcref(o->gcr, v); setitype(o, itype);
868#endif
869}
870
871static LJ_AINLINE void setgcV(lua_State *L, TValue *o, GCobj *v, uint32_t it)
872{
873 setgcVraw(o, v, it); tvchecklive(L, o);
747} 874}
748 875
749#define define_setV(name, type, tag) \ 876#define define_setV(name, type, tag) \
@@ -810,11 +937,7 @@ static LJ_AINLINE int32_t lj_num2bit(lua_Number n)
810#endif 937#endif
811} 938}
812 939
813#if LJ_TARGET_X86 && !defined(__SSE2__)
814#define lj_num2int(n) lj_num2bit((n))
815#else
816#define lj_num2int(n) ((int32_t)(n)) 940#define lj_num2int(n) ((int32_t)(n))
817#endif
818 941
819static LJ_AINLINE uint64_t lj_num2u64(lua_Number n) 942static LJ_AINLINE uint64_t lj_num2u64(lua_Number n)
820{ 943{
@@ -851,6 +974,7 @@ LJ_DATA const char *const lj_obj_itypename[~LJ_TNUMX+1];
851#define lj_typename(o) (lj_obj_itypename[itypemap(o)]) 974#define lj_typename(o) (lj_obj_itypename[itypemap(o)])
852 975
853/* Compare two objects without calling metamethods. */ 976/* Compare two objects without calling metamethods. */
854LJ_FUNC int lj_obj_equal(cTValue *o1, cTValue *o2); 977LJ_FUNC int LJ_FASTCALL lj_obj_equal(cTValue *o1, cTValue *o2);
978LJ_FUNC const void * LJ_FASTCALL lj_obj_ptr(cTValue *o);
855 979
856#endif 980#endif
diff --git a/src/lj_opt_fold.c b/src/lj_opt_fold.c
index b2d35c42..408811f2 100644
--- a/src/lj_opt_fold.c
+++ b/src/lj_opt_fold.c
@@ -14,18 +14,21 @@
14 14
15#if LJ_HASJIT 15#if LJ_HASJIT
16 16
17#include "lj_buf.h"
17#include "lj_str.h" 18#include "lj_str.h"
18#include "lj_tab.h" 19#include "lj_tab.h"
19#include "lj_ir.h" 20#include "lj_ir.h"
20#include "lj_jit.h" 21#include "lj_jit.h"
22#include "lj_ircall.h"
21#include "lj_iropt.h" 23#include "lj_iropt.h"
22#include "lj_trace.h" 24#include "lj_trace.h"
23#if LJ_HASFFI 25#if LJ_HASFFI
24#include "lj_ctype.h" 26#include "lj_ctype.h"
25#endif
26#include "lj_carith.h" 27#include "lj_carith.h"
28#endif
27#include "lj_vm.h" 29#include "lj_vm.h"
28#include "lj_strscan.h" 30#include "lj_strscan.h"
31#include "lj_strfmt.h"
29 32
30/* Here's a short description how the FOLD engine processes instructions: 33/* Here's a short description how the FOLD engine processes instructions:
31** 34**
@@ -133,8 +136,8 @@
133/* Some local macros to save typing. Undef'd at the end. */ 136/* Some local macros to save typing. Undef'd at the end. */
134#define IR(ref) (&J->cur.ir[(ref)]) 137#define IR(ref) (&J->cur.ir[(ref)])
135#define fins (&J->fold.ins) 138#define fins (&J->fold.ins)
136#define fleft (&J->fold.left) 139#define fleft (J->fold.left)
137#define fright (&J->fold.right) 140#define fright (J->fold.right)
138#define knumleft (ir_knum(fleft)->n) 141#define knumleft (ir_knum(fleft)->n)
139#define knumright (ir_knum(fright)->n) 142#define knumright (ir_knum(fright)->n)
140 143
@@ -155,13 +158,14 @@ typedef IRRef (LJ_FASTCALL *FoldFunc)(jit_State *J);
155 158
156/* Barrier to prevent folding across a GC step. 159/* Barrier to prevent folding across a GC step.
157** GC steps can only happen at the head of a trace and at LOOP. 160** GC steps can only happen at the head of a trace and at LOOP.
158** And the GC is only driven forward if there is at least one allocation. 161** And the GC is only driven forward if there's at least one allocation.
159*/ 162*/
160#define gcstep_barrier(J, ref) \ 163#define gcstep_barrier(J, ref) \
161 ((ref) < J->chain[IR_LOOP] && \ 164 ((ref) < J->chain[IR_LOOP] && \
162 (J->chain[IR_SNEW] || J->chain[IR_XSNEW] || \ 165 (J->chain[IR_SNEW] || J->chain[IR_XSNEW] || \
163 J->chain[IR_TNEW] || J->chain[IR_TDUP] || \ 166 J->chain[IR_TNEW] || J->chain[IR_TDUP] || \
164 J->chain[IR_CNEW] || J->chain[IR_CNEWI] || J->chain[IR_TOSTR])) 167 J->chain[IR_CNEW] || J->chain[IR_CNEWI] || \
168 J->chain[IR_BUFSTR] || J->chain[IR_TOSTR] || J->chain[IR_CALLA]))
165 169
166/* -- Constant folding for FP numbers ------------------------------------- */ 170/* -- Constant folding for FP numbers ------------------------------------- */
167 171
@@ -169,8 +173,6 @@ LJFOLD(ADD KNUM KNUM)
169LJFOLD(SUB KNUM KNUM) 173LJFOLD(SUB KNUM KNUM)
170LJFOLD(MUL KNUM KNUM) 174LJFOLD(MUL KNUM KNUM)
171LJFOLD(DIV KNUM KNUM) 175LJFOLD(DIV KNUM KNUM)
172LJFOLD(NEG KNUM KNUM)
173LJFOLD(ABS KNUM KNUM)
174LJFOLD(ATAN2 KNUM KNUM) 176LJFOLD(ATAN2 KNUM KNUM)
175LJFOLD(LDEXP KNUM KNUM) 177LJFOLD(LDEXP KNUM KNUM)
176LJFOLD(MIN KNUM KNUM) 178LJFOLD(MIN KNUM KNUM)
@@ -183,6 +185,15 @@ LJFOLDF(kfold_numarith)
183 return lj_ir_knum(J, y); 185 return lj_ir_knum(J, y);
184} 186}
185 187
188LJFOLD(NEG KNUM FLOAD)
189LJFOLD(ABS KNUM FLOAD)
190LJFOLDF(kfold_numabsneg)
191{
192 lua_Number a = knumleft;
193 lua_Number y = lj_vm_foldarith(a, a, fins->o - IR_ADD);
194 return lj_ir_knum(J, y);
195}
196
186LJFOLD(LDEXP KNUM KINT) 197LJFOLD(LDEXP KNUM KINT)
187LJFOLDF(kfold_ldexp) 198LJFOLDF(kfold_ldexp)
188{ 199{
@@ -336,15 +347,18 @@ LJFOLDF(kfold_intcomp0)
336static uint64_t kfold_int64arith(uint64_t k1, uint64_t k2, IROp op) 347static uint64_t kfold_int64arith(uint64_t k1, uint64_t k2, IROp op)
337{ 348{
338 switch (op) { 349 switch (op) {
339#if LJ_64 || LJ_HASFFI 350#if LJ_HASFFI
340 case IR_ADD: k1 += k2; break; 351 case IR_ADD: k1 += k2; break;
341 case IR_SUB: k1 -= k2; break; 352 case IR_SUB: k1 -= k2; break;
342#endif
343#if LJ_HASFFI
344 case IR_MUL: k1 *= k2; break; 353 case IR_MUL: k1 *= k2; break;
345 case IR_BAND: k1 &= k2; break; 354 case IR_BAND: k1 &= k2; break;
346 case IR_BOR: k1 |= k2; break; 355 case IR_BOR: k1 |= k2; break;
347 case IR_BXOR: k1 ^= k2; break; 356 case IR_BXOR: k1 ^= k2; break;
357 case IR_BSHL: k1 <<= (k2 & 63); break;
358 case IR_BSHR: k1 = (int32_t)((uint32_t)k1 >> (k2 & 63)); break;
359 case IR_BSAR: k1 >>= (k2 & 63); break;
360 case IR_BROL: k1 = (int32_t)lj_rol((uint32_t)k1, (k2 & 63)); break;
361 case IR_BROR: k1 = (int32_t)lj_ror((uint32_t)k1, (k2 & 63)); break;
348#endif 362#endif
349 default: UNUSED(k2); lua_assert(0); break; 363 default: UNUSED(k2); lua_assert(0); break;
350 } 364 }
@@ -392,20 +406,10 @@ LJFOLD(BROL KINT64 KINT)
392LJFOLD(BROR KINT64 KINT) 406LJFOLD(BROR KINT64 KINT)
393LJFOLDF(kfold_int64shift) 407LJFOLDF(kfold_int64shift)
394{ 408{
395#if LJ_HASFFI || LJ_64 409#if LJ_HASFFI
396 uint64_t k = ir_k64(fleft)->u64; 410 uint64_t k = ir_k64(fleft)->u64;
397 int32_t sh = (fright->i & 63); 411 int32_t sh = (fright->i & 63);
398 switch ((IROp)fins->o) { 412 return INT64FOLD(lj_carith_shift64(k, sh, fins->o - IR_BSHL));
399 case IR_BSHL: k <<= sh; break;
400#if LJ_HASFFI
401 case IR_BSHR: k >>= sh; break;
402 case IR_BSAR: k = (uint64_t)((int64_t)k >> sh); break;
403 case IR_BROL: k = lj_rol(k, sh); break;
404 case IR_BROR: k = lj_ror(k, sh); break;
405#endif
406 default: lua_assert(0); break;
407 }
408 return INT64FOLD(k);
409#else 413#else
410 UNUSED(J); lua_assert(0); return FAILFOLD; 414 UNUSED(J); lua_assert(0); return FAILFOLD;
411#endif 415#endif
@@ -510,7 +514,7 @@ LJFOLDF(kfold_strref_snew)
510 PHIBARRIER(ir); 514 PHIBARRIER(ir);
511 fins->op2 = emitir(IRTI(IR_ADD), ir->op2, fins->op2); /* Clobbers fins! */ 515 fins->op2 = emitir(IRTI(IR_ADD), ir->op2, fins->op2); /* Clobbers fins! */
512 fins->op1 = str; 516 fins->op1 = str;
513 fins->ot = IRT(IR_STRREF, IRT_P32); 517 fins->ot = IRT(IR_STRREF, IRT_PGC);
514 return RETRYFOLD; 518 return RETRYFOLD;
515 } 519 }
516 } 520 }
@@ -528,6 +532,180 @@ LJFOLDF(kfold_strcmp)
528 return NEXTFOLD; 532 return NEXTFOLD;
529} 533}
530 534
535/* -- Constant folding and forwarding for buffers ------------------------- */
536
537/*
538** Buffer ops perform stores, but their effect is limited to the buffer
539** itself. Also, buffer ops are chained: a use of an op implies a use of
540** all other ops up the chain. Conversely, if an op is unused, all ops
541** up the chain can go unsed. This largely eliminates the need to treat
542** them as stores.
543**
544** Alas, treating them as normal (IRM_N) ops doesn't work, because they
545** cannot be CSEd in isolation. CSE for IRM_N is implicitly done in LOOP
546** or if FOLD is disabled.
547**
548** The compromise is to declare them as loads, emit them like stores and
549** CSE whole chains manually when the BUFSTR is to be emitted. Any chain
550** fragments left over from CSE are eliminated by DCE.
551*/
552
553/* BUFHDR is emitted like a store, see below. */
554
555LJFOLD(BUFPUT BUFHDR BUFSTR)
556LJFOLDF(bufput_append)
557{
558 /* New buffer, no other buffer op inbetween and same buffer? */
559 if ((J->flags & JIT_F_OPT_FWD) &&
560 !(fleft->op2 & IRBUFHDR_APPEND) &&
561 fleft->prev == fright->op2 &&
562 fleft->op1 == IR(fright->op2)->op1) {
563 IRRef ref = fins->op1;
564 IR(ref)->op2 = (fleft->op2 | IRBUFHDR_APPEND); /* Modify BUFHDR. */
565 IR(ref)->op1 = fright->op1;
566 return ref;
567 }
568 return EMITFOLD; /* Always emit, CSE later. */
569}
570
571LJFOLD(BUFPUT any any)
572LJFOLDF(bufput_kgc)
573{
574 if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fright->o == IR_KGC) {
575 GCstr *s2 = ir_kstr(fright);
576 if (s2->len == 0) { /* Empty string? */
577 return LEFTFOLD;
578 } else {
579 if (fleft->o == IR_BUFPUT && irref_isk(fleft->op2) &&
580 !irt_isphi(fleft->t)) { /* Join two constant string puts in a row. */
581 GCstr *s1 = ir_kstr(IR(fleft->op2));
582 IRRef kref = lj_ir_kstr(J, lj_buf_cat2str(J->L, s1, s2));
583 /* lj_ir_kstr() may realloc the IR and invalidates any IRIns *. */
584 IR(fins->op1)->op2 = kref; /* Modify previous BUFPUT. */
585 return fins->op1;
586 }
587 }
588 }
589 return EMITFOLD; /* Always emit, CSE later. */
590}
591
592LJFOLD(BUFSTR any any)
593LJFOLDF(bufstr_kfold_cse)
594{
595 lua_assert(fleft->o == IR_BUFHDR || fleft->o == IR_BUFPUT ||
596 fleft->o == IR_CALLL);
597 if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD)) {
598 if (fleft->o == IR_BUFHDR) { /* No put operations? */
599 if (!(fleft->op2 & IRBUFHDR_APPEND)) /* Empty buffer? */
600 return lj_ir_kstr(J, &J2G(J)->strempty);
601 fins->op1 = fleft->op1;
602 fins->op2 = fleft->prev; /* Relies on checks in bufput_append. */
603 return CSEFOLD;
604 } else if (fleft->o == IR_BUFPUT) {
605 IRIns *irb = IR(fleft->op1);
606 if (irb->o == IR_BUFHDR && !(irb->op2 & IRBUFHDR_APPEND))
607 return fleft->op2; /* Shortcut for a single put operation. */
608 }
609 }
610 /* Try to CSE the whole chain. */
611 if (LJ_LIKELY(J->flags & JIT_F_OPT_CSE)) {
612 IRRef ref = J->chain[IR_BUFSTR];
613 while (ref) {
614 IRIns *irs = IR(ref), *ira = fleft, *irb = IR(irs->op1);
615 while (ira->o == irb->o && ira->op2 == irb->op2) {
616 lua_assert(ira->o == IR_BUFHDR || ira->o == IR_BUFPUT ||
617 ira->o == IR_CALLL || ira->o == IR_CARG);
618 if (ira->o == IR_BUFHDR && !(ira->op2 & IRBUFHDR_APPEND))
619 return ref; /* CSE succeeded. */
620 if (ira->o == IR_CALLL && ira->op2 == IRCALL_lj_buf_puttab)
621 break;
622 ira = IR(ira->op1);
623 irb = IR(irb->op1);
624 }
625 ref = irs->prev;
626 }
627 }
628 return EMITFOLD; /* No CSE possible. */
629}
630
631LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_reverse)
632LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_upper)
633LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_lower)
634LJFOLD(CALLL CARG IRCALL_lj_strfmt_putquoted)
635LJFOLDF(bufput_kfold_op)
636{
637 if (irref_isk(fleft->op2)) {
638 const CCallInfo *ci = &lj_ir_callinfo[fins->op2];
639 SBuf *sb = lj_buf_tmp_(J->L);
640 sb = ((SBuf * (LJ_FASTCALL *)(SBuf *, GCstr *))ci->func)(sb,
641 ir_kstr(IR(fleft->op2)));
642 fins->o = IR_BUFPUT;
643 fins->op1 = fleft->op1;
644 fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
645 return RETRYFOLD;
646 }
647 return EMITFOLD; /* Always emit, CSE later. */
648}
649
650LJFOLD(CALLL CARG IRCALL_lj_buf_putstr_rep)
651LJFOLDF(bufput_kfold_rep)
652{
653 if (irref_isk(fleft->op2)) {
654 IRIns *irc = IR(fleft->op1);
655 if (irref_isk(irc->op2)) {
656 SBuf *sb = lj_buf_tmp_(J->L);
657 sb = lj_buf_putstr_rep(sb, ir_kstr(IR(irc->op2)), IR(fleft->op2)->i);
658 fins->o = IR_BUFPUT;
659 fins->op1 = irc->op1;
660 fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
661 return RETRYFOLD;
662 }
663 }
664 return EMITFOLD; /* Always emit, CSE later. */
665}
666
667LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfxint)
668LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_int)
669LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum_uint)
670LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfnum)
671LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfstr)
672LJFOLD(CALLL CARG IRCALL_lj_strfmt_putfchar)
673LJFOLDF(bufput_kfold_fmt)
674{
675 IRIns *irc = IR(fleft->op1);
676 lua_assert(irref_isk(irc->op2)); /* SFormat must be const. */
677 if (irref_isk(fleft->op2)) {
678 SFormat sf = (SFormat)IR(irc->op2)->i;
679 IRIns *ira = IR(fleft->op2);
680 SBuf *sb = lj_buf_tmp_(J->L);
681 switch (fins->op2) {
682 case IRCALL_lj_strfmt_putfxint:
683 sb = lj_strfmt_putfxint(sb, sf, ir_k64(ira)->u64);
684 break;
685 case IRCALL_lj_strfmt_putfstr:
686 sb = lj_strfmt_putfstr(sb, sf, ir_kstr(ira));
687 break;
688 case IRCALL_lj_strfmt_putfchar:
689 sb = lj_strfmt_putfchar(sb, sf, ira->i);
690 break;
691 case IRCALL_lj_strfmt_putfnum_int:
692 case IRCALL_lj_strfmt_putfnum_uint:
693 case IRCALL_lj_strfmt_putfnum:
694 default: {
695 const CCallInfo *ci = &lj_ir_callinfo[fins->op2];
696 sb = ((SBuf * (*)(SBuf *, SFormat, lua_Number))ci->func)(sb, sf,
697 ir_knum(ira)->n);
698 break;
699 }
700 }
701 fins->o = IR_BUFPUT;
702 fins->op1 = irc->op1;
703 fins->op2 = lj_ir_kstr(J, lj_buf_tostr(sb));
704 return RETRYFOLD;
705 }
706 return EMITFOLD; /* Always emit, CSE later. */
707}
708
531/* -- Constant folding of pointer arithmetic ------------------------------ */ 709/* -- Constant folding of pointer arithmetic ------------------------------ */
532 710
533LJFOLD(ADD KGC KINT) 711LJFOLD(ADD KGC KINT)
@@ -648,27 +826,22 @@ LJFOLD(CONV KNUM IRCONV_INT_NUM)
648LJFOLDF(kfold_conv_knum_int_num) 826LJFOLDF(kfold_conv_knum_int_num)
649{ 827{
650 lua_Number n = knumleft; 828 lua_Number n = knumleft;
651 if (!(fins->op2 & IRCONV_TRUNC)) { 829 int32_t k = lj_num2int(n);
652 int32_t k = lj_num2int(n); 830 if (irt_isguard(fins->t) && n != (lua_Number)k) {
653 if (irt_isguard(fins->t) && n != (lua_Number)k) { 831 /* We're about to create a guard which always fails, like CONV +1.5.
654 /* We're about to create a guard which always fails, like CONV +1.5. 832 ** Some pathological loops cause this during LICM, e.g.:
655 ** Some pathological loops cause this during LICM, e.g.: 833 ** local x,k,t = 0,1.5,{1,[1.5]=2}
656 ** local x,k,t = 0,1.5,{1,[1.5]=2} 834 ** for i=1,200 do x = x+ t[k]; k = k == 1 and 1.5 or 1 end
657 ** for i=1,200 do x = x+ t[k]; k = k == 1 and 1.5 or 1 end 835 ** assert(x == 300)
658 ** assert(x == 300) 836 */
659 */ 837 return FAILFOLD;
660 return FAILFOLD;
661 }
662 return INTFOLD(k);
663 } else {
664 return INTFOLD((int32_t)n);
665 } 838 }
839 return INTFOLD(k);
666} 840}
667 841
668LJFOLD(CONV KNUM IRCONV_U32_NUM) 842LJFOLD(CONV KNUM IRCONV_U32_NUM)
669LJFOLDF(kfold_conv_knum_u32_num) 843LJFOLDF(kfold_conv_knum_u32_num)
670{ 844{
671 lua_assert((fins->op2 & IRCONV_TRUNC));
672#ifdef _MSC_VER 845#ifdef _MSC_VER
673 { /* Workaround for MSVC bug. */ 846 { /* Workaround for MSVC bug. */
674 volatile uint32_t u = (uint32_t)knumleft; 847 volatile uint32_t u = (uint32_t)knumleft;
@@ -682,27 +855,27 @@ LJFOLDF(kfold_conv_knum_u32_num)
682LJFOLD(CONV KNUM IRCONV_I64_NUM) 855LJFOLD(CONV KNUM IRCONV_I64_NUM)
683LJFOLDF(kfold_conv_knum_i64_num) 856LJFOLDF(kfold_conv_knum_i64_num)
684{ 857{
685 lua_assert((fins->op2 & IRCONV_TRUNC));
686 return INT64FOLD((uint64_t)(int64_t)knumleft); 858 return INT64FOLD((uint64_t)(int64_t)knumleft);
687} 859}
688 860
689LJFOLD(CONV KNUM IRCONV_U64_NUM) 861LJFOLD(CONV KNUM IRCONV_U64_NUM)
690LJFOLDF(kfold_conv_knum_u64_num) 862LJFOLDF(kfold_conv_knum_u64_num)
691{ 863{
692 lua_assert((fins->op2 & IRCONV_TRUNC));
693 return INT64FOLD(lj_num2u64(knumleft)); 864 return INT64FOLD(lj_num2u64(knumleft));
694} 865}
695 866
696LJFOLD(TOSTR KNUM) 867LJFOLD(TOSTR KNUM any)
697LJFOLDF(kfold_tostr_knum) 868LJFOLDF(kfold_tostr_knum)
698{ 869{
699 return lj_ir_kstr(J, lj_str_fromnum(J->L, &knumleft)); 870 return lj_ir_kstr(J, lj_strfmt_num(J->L, ir_knum(fleft)));
700} 871}
701 872
702LJFOLD(TOSTR KINT) 873LJFOLD(TOSTR KINT any)
703LJFOLDF(kfold_tostr_kint) 874LJFOLDF(kfold_tostr_kint)
704{ 875{
705 return lj_ir_kstr(J, lj_str_fromint(J->L, fleft->i)); 876 return lj_ir_kstr(J, fins->op2 == IRTOSTR_INT ?
877 lj_strfmt_int(J->L, fleft->i) :
878 lj_strfmt_char(J->L, fleft->i));
706} 879}
707 880
708LJFOLD(STRTO KGC) 881LJFOLD(STRTO KGC)
@@ -750,13 +923,13 @@ LJFOLDF(shortcut_round)
750 return NEXTFOLD; 923 return NEXTFOLD;
751} 924}
752 925
753LJFOLD(ABS ABS KNUM) 926LJFOLD(ABS ABS FLOAD)
754LJFOLDF(shortcut_left) 927LJFOLDF(shortcut_left)
755{ 928{
756 return LEFTFOLD; /* f(g(x)) ==> g(x) */ 929 return LEFTFOLD; /* f(g(x)) ==> g(x) */
757} 930}
758 931
759LJFOLD(ABS NEG KNUM) 932LJFOLD(ABS NEG FLOAD)
760LJFOLDF(shortcut_dropleft) 933LJFOLDF(shortcut_dropleft)
761{ 934{
762 PHIBARRIER(fleft); 935 PHIBARRIER(fleft);
@@ -837,8 +1010,10 @@ LJFOLDF(simplify_nummuldiv_k)
837 if (n == 1.0) { /* x o 1 ==> x */ 1010 if (n == 1.0) { /* x o 1 ==> x */
838 return LEFTFOLD; 1011 return LEFTFOLD;
839 } else if (n == -1.0) { /* x o -1 ==> -x */ 1012 } else if (n == -1.0) { /* x o -1 ==> -x */
1013 IRRef op1 = fins->op1;
1014 fins->op2 = (IRRef1)lj_ir_ksimd(J, LJ_KSIMD_NEG); /* Modifies fins. */
1015 fins->op1 = op1;
840 fins->o = IR_NEG; 1016 fins->o = IR_NEG;
841 fins->op2 = (IRRef1)lj_ir_knum_neg(J);
842 return RETRYFOLD; 1017 return RETRYFOLD;
843 } else if (fins->o == IR_MUL && n == 2.0) { /* x * 2 ==> x + x */ 1018 } else if (fins->o == IR_MUL && n == 2.0) { /* x * 2 ==> x + x */
844 fins->o = IR_ADD; 1019 fins->o = IR_ADD;
@@ -1205,7 +1380,9 @@ static TRef simplify_intmul_k(jit_State *J, int32_t k)
1205 ** But this is mainly intended for simple address arithmetic. 1380 ** But this is mainly intended for simple address arithmetic.
1206 ** Also it's easier for the backend to optimize the original multiplies. 1381 ** Also it's easier for the backend to optimize the original multiplies.
1207 */ 1382 */
1208 if (k == 1) { /* i * 1 ==> i */ 1383 if (k == 0) { /* i * 0 ==> 0 */
1384 return RIGHTFOLD;
1385 } else if (k == 1) { /* i * 1 ==> i */
1209 return LEFTFOLD; 1386 return LEFTFOLD;
1210 } else if ((k & (k-1)) == 0) { /* i * 2^k ==> i << k */ 1387 } else if ((k & (k-1)) == 0) { /* i * 2^k ==> i << k */
1211 fins->o = IR_BSHL; 1388 fins->o = IR_BSHL;
@@ -1218,9 +1395,7 @@ static TRef simplify_intmul_k(jit_State *J, int32_t k)
1218LJFOLD(MUL any KINT) 1395LJFOLD(MUL any KINT)
1219LJFOLDF(simplify_intmul_k32) 1396LJFOLDF(simplify_intmul_k32)
1220{ 1397{
1221 if (fright->i == 0) /* i * 0 ==> 0 */ 1398 if (fright->i >= 0)
1222 return INTFOLD(0);
1223 else if (fright->i > 0)
1224 return simplify_intmul_k(J, fright->i); 1399 return simplify_intmul_k(J, fright->i);
1225 return NEXTFOLD; 1400 return NEXTFOLD;
1226} 1401}
@@ -1228,14 +1403,13 @@ LJFOLDF(simplify_intmul_k32)
1228LJFOLD(MUL any KINT64) 1403LJFOLD(MUL any KINT64)
1229LJFOLDF(simplify_intmul_k64) 1404LJFOLDF(simplify_intmul_k64)
1230{ 1405{
1231 if (ir_kint64(fright)->u64 == 0) /* i * 0 ==> 0 */ 1406#if LJ_HASFFI
1232 return INT64FOLD(0); 1407 if (ir_kint64(fright)->u64 < 0x80000000u)
1233#if LJ_64
1234 /* NYI: SPLIT for BSHL and 32 bit backend support. */
1235 else if (ir_kint64(fright)->u64 < 0x80000000u)
1236 return simplify_intmul_k(J, (int32_t)ir_kint64(fright)->u64); 1408 return simplify_intmul_k(J, (int32_t)ir_kint64(fright)->u64);
1237#endif
1238 return NEXTFOLD; 1409 return NEXTFOLD;
1410#else
1411 UNUSED(J); lua_assert(0); return FAILFOLD;
1412#endif
1239} 1413}
1240 1414
1241LJFOLD(MOD any KINT) 1415LJFOLD(MOD any KINT)
@@ -1491,6 +1665,14 @@ LJFOLDF(simplify_shiftk_andk)
1491 fins->op2 = (IRRef1)lj_ir_kint(J, k); 1665 fins->op2 = (IRRef1)lj_ir_kint(J, k);
1492 fins->ot = IRTI(IR_BAND); 1666 fins->ot = IRTI(IR_BAND);
1493 return RETRYFOLD; 1667 return RETRYFOLD;
1668 } else if (irk->o == IR_KINT64) {
1669 uint64_t k = kfold_int64arith(ir_k64(irk)->u64, fright->i, (IROp)fins->o);
1670 IROpT ot = fleft->ot;
1671 fins->op1 = fleft->op1;
1672 fins->op1 = (IRRef1)lj_opt_fold(J);
1673 fins->op2 = (IRRef1)lj_ir_kint64(J, k);
1674 fins->ot = ot;
1675 return RETRYFOLD;
1494 } 1676 }
1495 return NEXTFOLD; 1677 return NEXTFOLD;
1496} 1678}
@@ -1535,7 +1717,7 @@ LJFOLD(BOR BOR KINT64)
1535LJFOLD(BXOR BXOR KINT64) 1717LJFOLD(BXOR BXOR KINT64)
1536LJFOLDF(reassoc_intarith_k64) 1718LJFOLDF(reassoc_intarith_k64)
1537{ 1719{
1538#if LJ_HASFFI || LJ_64 1720#if LJ_HASFFI
1539 IRIns *irk = IR(fleft->op2); 1721 IRIns *irk = IR(fleft->op2);
1540 if (irk->o == IR_KINT64) { 1722 if (irk->o == IR_KINT64) {
1541 uint64_t k = kfold_int64arith(ir_k64(irk)->u64, 1723 uint64_t k = kfold_int64arith(ir_k64(irk)->u64,
@@ -1953,6 +2135,7 @@ LJFOLDF(fwd_href_tdup)
1953** an aliased table, as it may invalidate all of the pointers and fields. 2135** an aliased table, as it may invalidate all of the pointers and fields.
1954** Only HREF needs the NEWREF check -- AREF and HREFK already depend on 2136** Only HREF needs the NEWREF check -- AREF and HREFK already depend on
1955** FLOADs. And NEWREF itself is treated like a store (see below). 2137** FLOADs. And NEWREF itself is treated like a store (see below).
2138** LREF is constant (per trace) since coroutine switches are not inlined.
1956*/ 2139*/
1957LJFOLD(FLOAD TNEW IRFL_TAB_ASIZE) 2140LJFOLD(FLOAD TNEW IRFL_TAB_ASIZE)
1958LJFOLDF(fload_tab_tnew_asize) 2141LJFOLDF(fload_tab_tnew_asize)
@@ -2016,6 +2199,14 @@ LJFOLDF(fload_str_len_snew)
2016 return NEXTFOLD; 2199 return NEXTFOLD;
2017} 2200}
2018 2201
2202LJFOLD(FLOAD TOSTR IRFL_STR_LEN)
2203LJFOLDF(fload_str_len_tostr)
2204{
2205 if (LJ_LIKELY(J->flags & JIT_F_OPT_FOLD) && fleft->op2 == IRTOSTR_CHAR)
2206 return INTFOLD(1);
2207 return NEXTFOLD;
2208}
2209
2019/* The C type ID of cdata objects is immutable. */ 2210/* The C type ID of cdata objects is immutable. */
2020LJFOLD(FLOAD KGC IRFL_CDATA_CTYPEID) 2211LJFOLD(FLOAD KGC IRFL_CDATA_CTYPEID)
2021LJFOLDF(fload_cdata_typeid_kgc) 2212LJFOLDF(fload_cdata_typeid_kgc)
@@ -2062,6 +2253,8 @@ LJFOLDF(fload_cdata_ptr_int64_cnew)
2062} 2253}
2063 2254
2064LJFOLD(FLOAD any IRFL_STR_LEN) 2255LJFOLD(FLOAD any IRFL_STR_LEN)
2256LJFOLD(FLOAD any IRFL_FUNC_ENV)
2257LJFOLD(FLOAD any IRFL_THREAD_ENV)
2065LJFOLD(FLOAD any IRFL_CDATA_CTYPEID) 2258LJFOLD(FLOAD any IRFL_CDATA_CTYPEID)
2066LJFOLD(FLOAD any IRFL_CDATA_PTR) 2259LJFOLD(FLOAD any IRFL_CDATA_PTR)
2067LJFOLD(FLOAD any IRFL_CDATA_INT) 2260LJFOLD(FLOAD any IRFL_CDATA_INT)
@@ -2127,6 +2320,17 @@ LJFOLDF(barrier_tnew_tdup)
2127 return DROPFOLD; 2320 return DROPFOLD;
2128} 2321}
2129 2322
2323/* -- Profiling ----------------------------------------------------------- */
2324
2325LJFOLD(PROF any any)
2326LJFOLDF(prof)
2327{
2328 IRRef ref = J->chain[IR_PROF];
2329 if (ref+1 == J->cur.nins) /* Drop neighbouring IR_PROF. */
2330 return ref;
2331 return EMITFOLD;
2332}
2333
2130/* -- Stores and allocations ---------------------------------------------- */ 2334/* -- Stores and allocations ---------------------------------------------- */
2131 2335
2132/* Stores and allocations cannot be folded or passed on to CSE in general. 2336/* Stores and allocations cannot be folded or passed on to CSE in general.
@@ -2149,8 +2353,9 @@ LJFOLD(XSTORE any any)
2149LJFOLDX(lj_opt_dse_xstore) 2353LJFOLDX(lj_opt_dse_xstore)
2150 2354
2151LJFOLD(NEWREF any any) /* Treated like a store. */ 2355LJFOLD(NEWREF any any) /* Treated like a store. */
2152LJFOLD(CALLS any any) 2356LJFOLD(CALLA any any)
2153LJFOLD(CALLL any any) /* Safeguard fallback. */ 2357LJFOLD(CALLL any any) /* Safeguard fallback. */
2358LJFOLD(CALLS any any)
2154LJFOLD(CALLXS any any) 2359LJFOLD(CALLXS any any)
2155LJFOLD(XBAR) 2360LJFOLD(XBAR)
2156LJFOLD(RETF any any) /* Modifies BASE. */ 2361LJFOLD(RETF any any) /* Modifies BASE. */
@@ -2158,6 +2363,7 @@ LJFOLD(TNEW any any)
2158LJFOLD(TDUP any) 2363LJFOLD(TDUP any)
2159LJFOLD(CNEW any any) 2364LJFOLD(CNEW any any)
2160LJFOLD(XSNEW any any) 2365LJFOLD(XSNEW any any)
2366LJFOLD(BUFHDR any any)
2161LJFOLDX(lj_ir_emit) 2367LJFOLDX(lj_ir_emit)
2162 2368
2163/* ------------------------------------------------------------------------ */ 2369/* ------------------------------------------------------------------------ */
@@ -2209,10 +2415,14 @@ retry:
2209 if (fins->op1 >= J->cur.nk) { 2415 if (fins->op1 >= J->cur.nk) {
2210 key += (uint32_t)IR(fins->op1)->o << 10; 2416 key += (uint32_t)IR(fins->op1)->o << 10;
2211 *fleft = *IR(fins->op1); 2417 *fleft = *IR(fins->op1);
2418 if (fins->op1 < REF_TRUE)
2419 fleft[1] = IR(fins->op1)[1];
2212 } 2420 }
2213 if (fins->op2 >= J->cur.nk) { 2421 if (fins->op2 >= J->cur.nk) {
2214 key += (uint32_t)IR(fins->op2)->o; 2422 key += (uint32_t)IR(fins->op2)->o;
2215 *fright = *IR(fins->op2); 2423 *fright = *IR(fins->op2);
2424 if (fins->op2 < REF_TRUE)
2425 fright[1] = IR(fins->op2)[1];
2216 } else { 2426 } else {
2217 key += (fins->op2 & 0x3ffu); /* Literal mask. Must include IRCONV_*MASK. */ 2427 key += (fins->op2 & 0x3ffu); /* Literal mask. Must include IRCONV_*MASK. */
2218 } 2428 }
diff --git a/src/lj_opt_loop.c b/src/lj_opt_loop.c
index 36317b34..04c6d06d 100644
--- a/src/lj_opt_loop.c
+++ b/src/lj_opt_loop.c
@@ -11,7 +11,7 @@
11#if LJ_HASJIT 11#if LJ_HASJIT
12 12
13#include "lj_err.h" 13#include "lj_err.h"
14#include "lj_str.h" 14#include "lj_buf.h"
15#include "lj_ir.h" 15#include "lj_ir.h"
16#include "lj_jit.h" 16#include "lj_jit.h"
17#include "lj_iropt.h" 17#include "lj_iropt.h"
@@ -254,9 +254,16 @@ static void loop_subst_snap(jit_State *J, SnapShot *osnap,
254 J->cur.nsnapmap = (uint16_t)(nmap - J->cur.snapmap); 254 J->cur.nsnapmap = (uint16_t)(nmap - J->cur.snapmap);
255} 255}
256 256
257typedef struct LoopState {
258 jit_State *J;
259 IRRef1 *subst;
260 MSize sizesubst;
261} LoopState;
262
257/* Unroll loop. */ 263/* Unroll loop. */
258static void loop_unroll(jit_State *J) 264static void loop_unroll(LoopState *lps)
259{ 265{
266 jit_State *J = lps->J;
260 IRRef1 phi[LJ_MAX_PHI]; 267 IRRef1 phi[LJ_MAX_PHI];
261 uint32_t nphi = 0; 268 uint32_t nphi = 0;
262 IRRef1 *subst; 269 IRRef1 *subst;
@@ -265,13 +272,13 @@ static void loop_unroll(jit_State *J)
265 SnapEntry *loopmap, *psentinel; 272 SnapEntry *loopmap, *psentinel;
266 IRRef ins, invar; 273 IRRef ins, invar;
267 274
268 /* Use temp buffer for substitution table. 275 /* Allocate substitution table.
269 ** Only non-constant refs in [REF_BIAS,invar) are valid indexes. 276 ** Only non-constant refs in [REF_BIAS,invar) are valid indexes.
270 ** Caveat: don't call into the VM or run the GC or the buffer may be gone.
271 */ 277 */
272 invar = J->cur.nins; 278 invar = J->cur.nins;
273 subst = (IRRef1 *)lj_str_needbuf(J->L, &G(J->L)->tmpbuf, 279 lps->sizesubst = invar - REF_BIAS;
274 (invar-REF_BIAS)*sizeof(IRRef1)) - REF_BIAS; 280 lps->subst = lj_mem_newvec(J->L, lps->sizesubst, IRRef1);
281 subst = lps->subst - REF_BIAS;
275 subst[REF_BASE] = REF_BASE; 282 subst[REF_BASE] = REF_BASE;
276 283
277 /* LOOP separates the pre-roll from the loop body. */ 284 /* LOOP separates the pre-roll from the loop body. */
@@ -396,7 +403,7 @@ static void loop_undo(jit_State *J, IRRef ins, SnapNo nsnap, MSize nsnapmap)
396static TValue *cploop_opt(lua_State *L, lua_CFunction dummy, void *ud) 403static TValue *cploop_opt(lua_State *L, lua_CFunction dummy, void *ud)
397{ 404{
398 UNUSED(L); UNUSED(dummy); 405 UNUSED(L); UNUSED(dummy);
399 loop_unroll((jit_State *)ud); 406 loop_unroll((LoopState *)ud);
400 return NULL; 407 return NULL;
401} 408}
402 409
@@ -406,7 +413,13 @@ int lj_opt_loop(jit_State *J)
406 IRRef nins = J->cur.nins; 413 IRRef nins = J->cur.nins;
407 SnapNo nsnap = J->cur.nsnap; 414 SnapNo nsnap = J->cur.nsnap;
408 MSize nsnapmap = J->cur.nsnapmap; 415 MSize nsnapmap = J->cur.nsnapmap;
409 int errcode = lj_vm_cpcall(J->L, NULL, J, cploop_opt); 416 LoopState lps;
417 int errcode;
418 lps.J = J;
419 lps.subst = NULL;
420 lps.sizesubst = 0;
421 errcode = lj_vm_cpcall(J->L, NULL, &lps, cploop_opt);
422 lj_mem_freevec(J2G(J), lps.subst, lps.sizesubst, IRRef1);
410 if (LJ_UNLIKELY(errcode)) { 423 if (LJ_UNLIKELY(errcode)) {
411 lua_State *L = J->L; 424 lua_State *L = J->L;
412 if (errcode == LUA_ERRRUN && tvisnumber(L->top-1)) { /* Trace error? */ 425 if (errcode == LUA_ERRRUN && tvisnumber(L->top-1)) { /* Trace error? */
diff --git a/src/lj_opt_mem.c b/src/lj_opt_mem.c
index 9f714056..cc177d39 100644
--- a/src/lj_opt_mem.c
+++ b/src/lj_opt_mem.c
@@ -17,12 +17,13 @@
17#include "lj_ir.h" 17#include "lj_ir.h"
18#include "lj_jit.h" 18#include "lj_jit.h"
19#include "lj_iropt.h" 19#include "lj_iropt.h"
20#include "lj_ircall.h"
20 21
21/* Some local macros to save typing. Undef'd at the end. */ 22/* Some local macros to save typing. Undef'd at the end. */
22#define IR(ref) (&J->cur.ir[(ref)]) 23#define IR(ref) (&J->cur.ir[(ref)])
23#define fins (&J->fold.ins) 24#define fins (&J->fold.ins)
24#define fleft (&J->fold.left) 25#define fleft (J->fold.left)
25#define fright (&J->fold.right) 26#define fright (J->fold.right)
26 27
27/* 28/*
28** Caveat #1: return value is not always a TRef -- only use with tref_ref(). 29** Caveat #1: return value is not always a TRef -- only use with tref_ref().
@@ -308,7 +309,21 @@ int LJ_FASTCALL lj_opt_fwd_href_nokey(jit_State *J)
308 return 1; /* No conflict. Can fold to niltv. */ 309 return 1; /* No conflict. Can fold to niltv. */
309} 310}
310 311
311/* Check whether there's no aliasing NEWREF for the left operand. */ 312/* Check whether there's no aliasing table.clear. */
313static int fwd_aa_tab_clear(jit_State *J, IRRef lim, IRRef ta)
314{
315 IRRef ref = J->chain[IR_CALLS];
316 while (ref > lim) {
317 IRIns *calls = IR(ref);
318 if (calls->op2 == IRCALL_lj_tab_clear &&
319 (ta == calls->op1 || aa_table(J, ta, calls->op1) != ALIAS_NO))
320 return 0; /* Conflict. */
321 ref = calls->prev;
322 }
323 return 1; /* No conflict. Can safely FOLD/CSE. */
324}
325
326/* Check whether there's no aliasing NEWREF/table.clear for the left operand. */
312int LJ_FASTCALL lj_opt_fwd_tptr(jit_State *J, IRRef lim) 327int LJ_FASTCALL lj_opt_fwd_tptr(jit_State *J, IRRef lim)
313{ 328{
314 IRRef ta = fins->op1; 329 IRRef ta = fins->op1;
@@ -319,7 +334,7 @@ int LJ_FASTCALL lj_opt_fwd_tptr(jit_State *J, IRRef lim)
319 return 0; /* Conflict. */ 334 return 0; /* Conflict. */
320 ref = newref->prev; 335 ref = newref->prev;
321 } 336 }
322 return 1; /* No conflict. Can safely FOLD/CSE. */ 337 return fwd_aa_tab_clear(J, lim, ta);
323} 338}
324 339
325/* ASTORE/HSTORE elimination. */ 340/* ASTORE/HSTORE elimination. */
@@ -854,6 +869,10 @@ TRef LJ_FASTCALL lj_opt_fwd_tab_len(jit_State *J)
854 ref = store->prev; 869 ref = store->prev;
855 } 870 }
856 871
872 /* Search for aliasing table.clear. */
873 if (!fwd_aa_tab_clear(J, lim, tab))
874 return lj_ir_emit(J);
875
857 /* Try to find a matching load. Below the conflicting store, if any. */ 876 /* Try to find a matching load. Below the conflicting store, if any. */
858 return lj_opt_cselim(J, lim); 877 return lj_opt_cselim(J, lim);
859} 878}
diff --git a/src/lj_opt_narrow.c b/src/lj_opt_narrow.c
index 73365953..cd96ca4b 100644
--- a/src/lj_opt_narrow.c
+++ b/src/lj_opt_narrow.c
@@ -555,7 +555,7 @@ TRef lj_opt_narrow_unm(jit_State *J, TRef rc, TValue *vc)
555 return emitir(IRTGI(IR_SUBOV), lj_ir_kint(J, 0), rc); 555 return emitir(IRTGI(IR_SUBOV), lj_ir_kint(J, 0), rc);
556 rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT); 556 rc = emitir(IRTN(IR_CONV), rc, IRCONV_NUM_INT);
557 } 557 }
558 return emitir(IRTN(IR_NEG), rc, lj_ir_knum_neg(J)); 558 return emitir(IRTN(IR_NEG), rc, lj_ir_ksimd(J, LJ_KSIMD_NEG));
559} 559}
560 560
561/* Narrowing of modulo operator. */ 561/* Narrowing of modulo operator. */
diff --git a/src/lj_opt_sink.c b/src/lj_opt_sink.c
index 6a00d04c..929ccb61 100644
--- a/src/lj_opt_sink.c
+++ b/src/lj_opt_sink.c
@@ -165,8 +165,8 @@ static void sink_remark_phi(jit_State *J)
165/* Sweep instructions and tag sunken allocations and stores. */ 165/* Sweep instructions and tag sunken allocations and stores. */
166static void sink_sweep_ins(jit_State *J) 166static void sink_sweep_ins(jit_State *J)
167{ 167{
168 IRIns *ir, *irfirst = IR(J->cur.nk); 168 IRIns *ir, *irbase = IR(REF_BASE);
169 for (ir = IR(J->cur.nins-1) ; ir >= irfirst; ir--) { 169 for (ir = IR(J->cur.nins-1) ; ir >= irbase; ir--) {
170 switch (ir->o) { 170 switch (ir->o) {
171 case IR_ASTORE: case IR_HSTORE: case IR_FSTORE: case IR_XSTORE: { 171 case IR_ASTORE: case IR_HSTORE: case IR_FSTORE: case IR_XSTORE: {
172 IRIns *ira = sink_checkalloc(J, ir); 172 IRIns *ira = sink_checkalloc(J, ir);
@@ -216,6 +216,12 @@ static void sink_sweep_ins(jit_State *J)
216 break; 216 break;
217 } 217 }
218 } 218 }
219 for (ir = IR(J->cur.nk); ir < irbase; ir++) {
220 irt_clearmark(ir->t);
221 ir->prev = REGSP_INIT;
222 if (irt_is64(ir->t) && ir->o != IR_KNULL)
223 ir++;
224 }
219} 225}
220 226
221/* Allocation sinking and store sinking. 227/* Allocation sinking and store sinking.
diff --git a/src/lj_opt_split.c b/src/lj_opt_split.c
index 8d7cd4c2..fc935204 100644
--- a/src/lj_opt_split.c
+++ b/src/lj_opt_split.c
@@ -11,11 +11,12 @@
11#if LJ_HASJIT && (LJ_SOFTFP || (LJ_32 && LJ_HASFFI)) 11#if LJ_HASJIT && (LJ_SOFTFP || (LJ_32 && LJ_HASFFI))
12 12
13#include "lj_err.h" 13#include "lj_err.h"
14#include "lj_str.h" 14#include "lj_buf.h"
15#include "lj_ir.h" 15#include "lj_ir.h"
16#include "lj_jit.h" 16#include "lj_jit.h"
17#include "lj_ircall.h" 17#include "lj_ircall.h"
18#include "lj_iropt.h" 18#include "lj_iropt.h"
19#include "lj_dispatch.h"
19#include "lj_vm.h" 20#include "lj_vm.h"
20 21
21/* SPLIT pass: 22/* SPLIT pass:
@@ -139,6 +140,7 @@ static IRRef split_call_l(jit_State *J, IRRef1 *hisubst, IRIns *oir,
139 ir->prev = tmp = split_emit(J, IRTI(IR_CALLN), tmp, id); 140 ir->prev = tmp = split_emit(J, IRTI(IR_CALLN), tmp, id);
140 return split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), tmp, tmp); 141 return split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), tmp, tmp);
141} 142}
143#endif
142 144
143/* Emit a CALLN with one split 64 bit argument and a 32 bit argument. */ 145/* Emit a CALLN with one split 64 bit argument and a 32 bit argument. */
144static IRRef split_call_li(jit_State *J, IRRef1 *hisubst, IRIns *oir, 146static IRRef split_call_li(jit_State *J, IRRef1 *hisubst, IRIns *oir,
@@ -155,7 +157,6 @@ static IRRef split_call_li(jit_State *J, IRRef1 *hisubst, IRIns *oir,
155 ir->prev = tmp = split_emit(J, IRTI(IR_CALLN), tmp, id); 157 ir->prev = tmp = split_emit(J, IRTI(IR_CALLN), tmp, id);
156 return split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), tmp, tmp); 158 return split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), tmp, tmp);
157} 159}
158#endif
159 160
160/* Emit a CALLN with two split 64 bit arguments. */ 161/* Emit a CALLN with two split 64 bit arguments. */
161static IRRef split_call_ll(jit_State *J, IRRef1 *hisubst, IRIns *oir, 162static IRRef split_call_ll(jit_State *J, IRRef1 *hisubst, IRIns *oir,
@@ -192,9 +193,121 @@ static IRRef split_ptr(jit_State *J, IRIns *oir, IRRef ref)
192 nref = ir->op1; 193 nref = ir->op1;
193 if (ofs == 0) return nref; 194 if (ofs == 0) return nref;
194 } 195 }
195 return split_emit(J, IRTI(IR_ADD), nref, lj_ir_kint(J, ofs)); 196 return split_emit(J, IRT(IR_ADD, IRT_PTR), nref, lj_ir_kint(J, ofs));
197}
198
199#if LJ_HASFFI
200static IRRef split_bitshift(jit_State *J, IRRef1 *hisubst,
201 IRIns *oir, IRIns *nir, IRIns *ir)
202{
203 IROp op = ir->o;
204 IRRef kref = nir->op2;
205 if (irref_isk(kref)) { /* Optimize constant shifts. */
206 int32_t k = (IR(kref)->i & 63);
207 IRRef lo = nir->op1, hi = hisubst[ir->op1];
208 if (op == IR_BROL || op == IR_BROR) {
209 if (op == IR_BROR) k = (-k & 63);
210 if (k >= 32) { IRRef t = lo; lo = hi; hi = t; k -= 32; }
211 if (k == 0) {
212 passthrough:
213 J->cur.nins--;
214 ir->prev = lo;
215 return hi;
216 } else {
217 TRef k1, k2;
218 IRRef t1, t2, t3, t4;
219 J->cur.nins--;
220 k1 = lj_ir_kint(J, k);
221 k2 = lj_ir_kint(J, (-k & 31));
222 t1 = split_emit(J, IRTI(IR_BSHL), lo, k1);
223 t2 = split_emit(J, IRTI(IR_BSHL), hi, k1);
224 t3 = split_emit(J, IRTI(IR_BSHR), lo, k2);
225 t4 = split_emit(J, IRTI(IR_BSHR), hi, k2);
226 ir->prev = split_emit(J, IRTI(IR_BOR), t1, t4);
227 return split_emit(J, IRTI(IR_BOR), t2, t3);
228 }
229 } else if (k == 0) {
230 goto passthrough;
231 } else if (k < 32) {
232 if (op == IR_BSHL) {
233 IRRef t1 = split_emit(J, IRTI(IR_BSHL), hi, kref);
234 IRRef t2 = split_emit(J, IRTI(IR_BSHR), lo, lj_ir_kint(J, (-k&31)));
235 return split_emit(J, IRTI(IR_BOR), t1, t2);
236 } else {
237 IRRef t1 = ir->prev, t2;
238 lua_assert(op == IR_BSHR || op == IR_BSAR);
239 nir->o = IR_BSHR;
240 t2 = split_emit(J, IRTI(IR_BSHL), hi, lj_ir_kint(J, (-k&31)));
241 ir->prev = split_emit(J, IRTI(IR_BOR), t1, t2);
242 return split_emit(J, IRTI(op), hi, kref);
243 }
244 } else {
245 if (op == IR_BSHL) {
246 if (k == 32)
247 J->cur.nins--;
248 else
249 lo = ir->prev;
250 ir->prev = lj_ir_kint(J, 0);
251 return lo;
252 } else {
253 lua_assert(op == IR_BSHR || op == IR_BSAR);
254 if (k == 32) {
255 J->cur.nins--;
256 ir->prev = hi;
257 } else {
258 nir->op1 = hi;
259 }
260 if (op == IR_BSHR)
261 return lj_ir_kint(J, 0);
262 else
263 return split_emit(J, IRTI(IR_BSAR), hi, lj_ir_kint(J, 31));
264 }
265 }
266 }
267 return split_call_li(J, hisubst, oir, ir,
268 op - IR_BSHL + IRCALL_lj_carith_shl64);
196} 269}
197 270
271static IRRef split_bitop(jit_State *J, IRRef1 *hisubst,
272 IRIns *nir, IRIns *ir)
273{
274 IROp op = ir->o;
275 IRRef hi, kref = nir->op2;
276 if (irref_isk(kref)) { /* Optimize bit operations with lo constant. */
277 int32_t k = IR(kref)->i;
278 if (k == 0 || k == -1) {
279 if (op == IR_BAND) k = ~k;
280 if (k == 0) {
281 J->cur.nins--;
282 ir->prev = nir->op1;
283 } else if (op == IR_BXOR) {
284 nir->o = IR_BNOT;
285 nir->op2 = 0;
286 } else {
287 J->cur.nins--;
288 ir->prev = kref;
289 }
290 }
291 }
292 hi = hisubst[ir->op1];
293 kref = hisubst[ir->op2];
294 if (irref_isk(kref)) { /* Optimize bit operations with hi constant. */
295 int32_t k = IR(kref)->i;
296 if (k == 0 || k == -1) {
297 if (op == IR_BAND) k = ~k;
298 if (k == 0) {
299 return hi;
300 } else if (op == IR_BXOR) {
301 return split_emit(J, IRTI(IR_BNOT), hi, 0);
302 } else {
303 return kref;
304 }
305 }
306 }
307 return split_emit(J, IRTI(op), hi, kref);
308}
309#endif
310
198/* Substitute references of a snapshot. */ 311/* Substitute references of a snapshot. */
199static void split_subst_snap(jit_State *J, SnapShot *snap, IRIns *oir) 312static void split_subst_snap(jit_State *J, SnapShot *snap, IRIns *oir)
200{ 313{
@@ -214,7 +327,7 @@ static void split_ir(jit_State *J)
214 IRRef nins = J->cur.nins, nk = J->cur.nk; 327 IRRef nins = J->cur.nins, nk = J->cur.nk;
215 MSize irlen = nins - nk; 328 MSize irlen = nins - nk;
216 MSize need = (irlen+1)*(sizeof(IRIns) + sizeof(IRRef1)); 329 MSize need = (irlen+1)*(sizeof(IRIns) + sizeof(IRRef1));
217 IRIns *oir = (IRIns *)lj_str_needbuf(J->L, &G(J->L)->tmpbuf, need); 330 IRIns *oir = (IRIns *)lj_buf_tmp(J->L, need);
218 IRRef1 *hisubst; 331 IRRef1 *hisubst;
219 IRRef ref, snref; 332 IRRef ref, snref;
220 SnapShot *snap; 333 SnapShot *snap;
@@ -241,6 +354,8 @@ static void split_ir(jit_State *J)
241 ir->prev = ref; /* Identity substitution for loword. */ 354 ir->prev = ref; /* Identity substitution for loword. */
242 hisubst[ref] = 0; 355 hisubst[ref] = 0;
243 } 356 }
357 if (irt_is64(ir->t) && ir->o != IR_KNULL)
358 ref++;
244 } 359 }
245 360
246 /* Process old IR instructions. */ 361 /* Process old IR instructions. */
@@ -321,7 +436,8 @@ static void split_ir(jit_State *J)
321 nir->o = IR_CONV; /* Pass through loword. */ 436 nir->o = IR_CONV; /* Pass through loword. */
322 nir->op2 = (IRT_INT << 5) | IRT_INT; 437 nir->op2 = (IRT_INT << 5) | IRT_INT;
323 hi = split_emit(J, IRT(ir->o == IR_NEG ? IR_BXOR : IR_BAND, IRT_SOFTFP), 438 hi = split_emit(J, IRT(ir->o == IR_NEG ? IR_BXOR : IR_BAND, IRT_SOFTFP),
324 hisubst[ir->op1], hisubst[ir->op2]); 439 hisubst[ir->op1],
440 lj_ir_kint(J, (int32_t)(0x7fffffffu + (ir->o == IR_NEG))));
325 break; 441 break;
326 case IR_SLOAD: 442 case IR_SLOAD:
327 if ((nir->op2 & IRSLOAD_CONVERT)) { /* Convert from int to number. */ 443 if ((nir->op2 & IRSLOAD_CONVERT)) { /* Convert from int to number. */
@@ -336,15 +452,24 @@ static void split_ir(jit_State *J)
336 case IR_STRTO: 452 case IR_STRTO:
337 hi = split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), nref, nref); 453 hi = split_emit(J, IRT(IR_HIOP, IRT_SOFTFP), nref, nref);
338 break; 454 break;
455 case IR_FLOAD:
456 lua_assert(ir->op1 == REF_NIL);
457 hi = lj_ir_kint(J, *(int32_t*)((char*)J2GG(J) + ir->op2 + LJ_LE*4));
458 nir->op2 += LJ_BE*4;
459 break;
339 case IR_XLOAD: { 460 case IR_XLOAD: {
340 IRIns inslo = *nir; /* Save/undo the emit of the lo XLOAD. */ 461 IRIns inslo = *nir; /* Save/undo the emit of the lo XLOAD. */
341 J->cur.nins--; 462 J->cur.nins--;
342 hi = split_ptr(J, oir, ir->op1); /* Insert the hiref ADD. */ 463 hi = split_ptr(J, oir, ir->op1); /* Insert the hiref ADD. */
464#if LJ_BE
465 hi = split_emit(J, IRT(IR_XLOAD, IRT_INT), hi, ir->op2);
466 inslo.t.irt = IRT_SOFTFP | (inslo.t.irt & IRT_GUARD);
467#endif
343 nref = lj_ir_nextins(J); 468 nref = lj_ir_nextins(J);
344 nir = IR(nref); 469 nir = IR(nref);
345 *nir = inslo; /* Re-emit lo XLOAD immediately before hi XLOAD. */ 470 *nir = inslo; /* Re-emit lo XLOAD. */
346 hi = split_emit(J, IRT(IR_XLOAD, IRT_SOFTFP), hi, ir->op2);
347#if LJ_LE 471#if LJ_LE
472 hi = split_emit(J, IRT(IR_XLOAD, IRT_SOFTFP), hi, ir->op2);
348 ir->prev = nref; 473 ir->prev = nref;
349#else 474#else
350 ir->prev = hi; hi = nref; 475 ir->prev = hi; hi = nref;
@@ -438,6 +563,19 @@ static void split_ir(jit_State *J)
438 irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 : 563 irt_isi64(ir->t) ? IRCALL_lj_carith_powi64 :
439 IRCALL_lj_carith_powu64); 564 IRCALL_lj_carith_powu64);
440 break; 565 break;
566 case IR_BNOT:
567 hi = split_emit(J, IRTI(IR_BNOT), hiref, 0);
568 break;
569 case IR_BSWAP:
570 ir->prev = split_emit(J, IRTI(IR_BSWAP), hiref, 0);
571 hi = nref;
572 break;
573 case IR_BAND: case IR_BOR: case IR_BXOR:
574 hi = split_bitop(J, hisubst, nir, ir);
575 break;
576 case IR_BSHL: case IR_BSHR: case IR_BSAR: case IR_BROL: case IR_BROR:
577 hi = split_bitshift(J, hisubst, oir, nir, ir);
578 break;
441 case IR_FLOAD: 579 case IR_FLOAD:
442 lua_assert(ir->op2 == IRFL_CDATA_INT64); 580 lua_assert(ir->op2 == IRFL_CDATA_INT64);
443 hi = split_emit(J, IRTI(IR_FLOAD), nir->op1, IRFL_CDATA_INT64_4); 581 hi = split_emit(J, IRTI(IR_FLOAD), nir->op1, IRFL_CDATA_INT64_4);
diff --git a/src/lj_parse.c b/src/lj_parse.c
index 9e5976f7..08f7cfa6 100644
--- a/src/lj_parse.c
+++ b/src/lj_parse.c
@@ -13,6 +13,7 @@
13#include "lj_gc.h" 13#include "lj_gc.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_debug.h" 15#include "lj_debug.h"
16#include "lj_buf.h"
16#include "lj_str.h" 17#include "lj_str.h"
17#include "lj_tab.h" 18#include "lj_tab.h"
18#include "lj_func.h" 19#include "lj_func.h"
@@ -21,6 +22,7 @@
21#if LJ_HASFFI 22#if LJ_HASFFI
22#include "lj_ctype.h" 23#include "lj_ctype.h"
23#endif 24#endif
25#include "lj_strfmt.h"
24#include "lj_lex.h" 26#include "lj_lex.h"
25#include "lj_parse.h" 27#include "lj_parse.h"
26#include "lj_vm.h" 28#include "lj_vm.h"
@@ -165,12 +167,12 @@ LJ_STATIC_ASSERT((int)BC_MODVV-(int)BC_ADDVV == (int)OPR_MOD-(int)OPR_ADD);
165 167
166LJ_NORET LJ_NOINLINE static void err_syntax(LexState *ls, ErrMsg em) 168LJ_NORET LJ_NOINLINE static void err_syntax(LexState *ls, ErrMsg em)
167{ 169{
168 lj_lex_error(ls, ls->token, em); 170 lj_lex_error(ls, ls->tok, em);
169} 171}
170 172
171LJ_NORET LJ_NOINLINE static void err_token(LexState *ls, LexToken token) 173LJ_NORET LJ_NOINLINE static void err_token(LexState *ls, LexToken tok)
172{ 174{
173 lj_lex_error(ls, ls->token, LJ_ERR_XTOKEN, lj_lex_token2str(ls, token)); 175 lj_lex_error(ls, ls->tok, LJ_ERR_XTOKEN, lj_lex_token2str(ls, tok));
174} 176}
175 177
176LJ_NORET static void err_limit(FuncState *fs, uint32_t limit, const char *what) 178LJ_NORET static void err_limit(FuncState *fs, uint32_t limit, const char *what)
@@ -660,16 +662,16 @@ static void bcemit_method(FuncState *fs, ExpDesc *e, ExpDesc *key)
660 BCReg idx, func, obj = expr_toanyreg(fs, e); 662 BCReg idx, func, obj = expr_toanyreg(fs, e);
661 expr_free(fs, e); 663 expr_free(fs, e);
662 func = fs->freereg; 664 func = fs->freereg;
663 bcemit_AD(fs, BC_MOV, func+1, obj); /* Copy object to first argument. */ 665 bcemit_AD(fs, BC_MOV, func+1+LJ_FR2, obj); /* Copy object to 1st argument. */
664 lua_assert(expr_isstrk(key)); 666 lua_assert(expr_isstrk(key));
665 idx = const_str(fs, key); 667 idx = const_str(fs, key);
666 if (idx <= BCMAX_C) { 668 if (idx <= BCMAX_C) {
667 bcreg_reserve(fs, 2); 669 bcreg_reserve(fs, 2+LJ_FR2);
668 bcemit_ABC(fs, BC_TGETS, func, obj, idx); 670 bcemit_ABC(fs, BC_TGETS, func, obj, idx);
669 } else { 671 } else {
670 bcreg_reserve(fs, 3); 672 bcreg_reserve(fs, 3+LJ_FR2);
671 bcemit_AD(fs, BC_KSTR, func+2, idx); 673 bcemit_AD(fs, BC_KSTR, func+2+LJ_FR2, idx);
672 bcemit_ABC(fs, BC_TGETV, func, obj, func+2); 674 bcemit_ABC(fs, BC_TGETV, func, obj, func+2+LJ_FR2);
673 fs->freereg--; 675 fs->freereg--;
674 } 676 }
675 e->u.s.info = func; 677 e->u.s.info = func;
@@ -983,7 +985,7 @@ static void bcemit_unop(FuncState *fs, BCOp op, ExpDesc *e)
983/* Check and consume optional token. */ 985/* Check and consume optional token. */
984static int lex_opt(LexState *ls, LexToken tok) 986static int lex_opt(LexState *ls, LexToken tok)
985{ 987{
986 if (ls->token == tok) { 988 if (ls->tok == tok) {
987 lj_lex_next(ls); 989 lj_lex_next(ls);
988 return 1; 990 return 1;
989 } 991 }
@@ -993,7 +995,7 @@ static int lex_opt(LexState *ls, LexToken tok)
993/* Check and consume token. */ 995/* Check and consume token. */
994static void lex_check(LexState *ls, LexToken tok) 996static void lex_check(LexState *ls, LexToken tok)
995{ 997{
996 if (ls->token != tok) 998 if (ls->tok != tok)
997 err_token(ls, tok); 999 err_token(ls, tok);
998 lj_lex_next(ls); 1000 lj_lex_next(ls);
999} 1001}
@@ -1007,7 +1009,7 @@ static void lex_match(LexState *ls, LexToken what, LexToken who, BCLine line)
1007 } else { 1009 } else {
1008 const char *swhat = lj_lex_token2str(ls, what); 1010 const char *swhat = lj_lex_token2str(ls, what);
1009 const char *swho = lj_lex_token2str(ls, who); 1011 const char *swho = lj_lex_token2str(ls, who);
1010 lj_lex_error(ls, ls->token, LJ_ERR_XMATCH, swhat, swho, line); 1012 lj_lex_error(ls, ls->tok, LJ_ERR_XMATCH, swhat, swho, line);
1011 } 1013 }
1012 } 1014 }
1013} 1015}
@@ -1016,9 +1018,9 @@ static void lex_match(LexState *ls, LexToken what, LexToken who, BCLine line)
1016static GCstr *lex_str(LexState *ls) 1018static GCstr *lex_str(LexState *ls)
1017{ 1019{
1018 GCstr *s; 1020 GCstr *s;
1019 if (ls->token != TK_name && (LJ_52 || ls->token != TK_goto)) 1021 if (ls->tok != TK_name && (LJ_52 || ls->tok != TK_goto))
1020 err_token(ls, TK_name); 1022 err_token(ls, TK_name);
1021 s = strV(&ls->tokenval); 1023 s = strV(&ls->tokval);
1022 lj_lex_next(ls); 1024 lj_lex_next(ls);
1023 return s; 1025 return s;
1024} 1026}
@@ -1433,78 +1435,46 @@ static void fs_fixup_line(FuncState *fs, GCproto *pt,
1433 } 1435 }
1434} 1436}
1435 1437
1436/* Resize buffer if needed. */
1437static LJ_NOINLINE void fs_buf_resize(LexState *ls, MSize len)
1438{
1439 MSize sz = ls->sb.sz * 2;
1440 while (ls->sb.n + len > sz) sz = sz * 2;
1441 lj_str_resizebuf(ls->L, &ls->sb, sz);
1442}
1443
1444static LJ_AINLINE void fs_buf_need(LexState *ls, MSize len)
1445{
1446 if (LJ_UNLIKELY(ls->sb.n + len > ls->sb.sz))
1447 fs_buf_resize(ls, len);
1448}
1449
1450/* Add string to buffer. */
1451static void fs_buf_str(LexState *ls, const char *str, MSize len)
1452{
1453 char *p = ls->sb.buf + ls->sb.n;
1454 MSize i;
1455 ls->sb.n += len;
1456 for (i = 0; i < len; i++) p[i] = str[i];
1457}
1458
1459/* Add ULEB128 value to buffer. */
1460static void fs_buf_uleb128(LexState *ls, uint32_t v)
1461{
1462 MSize n = ls->sb.n;
1463 uint8_t *p = (uint8_t *)ls->sb.buf;
1464 for (; v >= 0x80; v >>= 7)
1465 p[n++] = (uint8_t)((v & 0x7f) | 0x80);
1466 p[n++] = (uint8_t)v;
1467 ls->sb.n = n;
1468}
1469
1470/* Prepare variable info for prototype. */ 1438/* Prepare variable info for prototype. */
1471static size_t fs_prep_var(LexState *ls, FuncState *fs, size_t *ofsvar) 1439static size_t fs_prep_var(LexState *ls, FuncState *fs, size_t *ofsvar)
1472{ 1440{
1473 VarInfo *vs =ls->vstack, *ve; 1441 VarInfo *vs =ls->vstack, *ve;
1474 MSize i, n; 1442 MSize i, n;
1475 BCPos lastpc; 1443 BCPos lastpc;
1476 lj_str_resetbuf(&ls->sb); /* Copy to temp. string buffer. */ 1444 lj_buf_reset(&ls->sb); /* Copy to temp. string buffer. */
1477 /* Store upvalue names. */ 1445 /* Store upvalue names. */
1478 for (i = 0, n = fs->nuv; i < n; i++) { 1446 for (i = 0, n = fs->nuv; i < n; i++) {
1479 GCstr *s = strref(vs[fs->uvmap[i]].name); 1447 GCstr *s = strref(vs[fs->uvmap[i]].name);
1480 MSize len = s->len+1; 1448 MSize len = s->len+1;
1481 fs_buf_need(ls, len); 1449 char *p = lj_buf_more(&ls->sb, len);
1482 fs_buf_str(ls, strdata(s), len); 1450 p = lj_buf_wmem(p, strdata(s), len);
1451 setsbufP(&ls->sb, p);
1483 } 1452 }
1484 *ofsvar = ls->sb.n; 1453 *ofsvar = sbuflen(&ls->sb);
1485 lastpc = 0; 1454 lastpc = 0;
1486 /* Store local variable names and compressed ranges. */ 1455 /* Store local variable names and compressed ranges. */
1487 for (ve = vs + ls->vtop, vs += fs->vbase; vs < ve; vs++) { 1456 for (ve = vs + ls->vtop, vs += fs->vbase; vs < ve; vs++) {
1488 if (!gola_isgotolabel(vs)) { 1457 if (!gola_isgotolabel(vs)) {
1489 GCstr *s = strref(vs->name); 1458 GCstr *s = strref(vs->name);
1490 BCPos startpc; 1459 BCPos startpc;
1460 char *p;
1491 if ((uintptr_t)s < VARNAME__MAX) { 1461 if ((uintptr_t)s < VARNAME__MAX) {
1492 fs_buf_need(ls, 1 + 2*5); 1462 p = lj_buf_more(&ls->sb, 1 + 2*5);
1493 ls->sb.buf[ls->sb.n++] = (uint8_t)(uintptr_t)s; 1463 *p++ = (char)(uintptr_t)s;
1494 } else { 1464 } else {
1495 MSize len = s->len+1; 1465 MSize len = s->len+1;
1496 fs_buf_need(ls, len + 2*5); 1466 p = lj_buf_more(&ls->sb, len + 2*5);
1497 fs_buf_str(ls, strdata(s), len); 1467 p = lj_buf_wmem(p, strdata(s), len);
1498 } 1468 }
1499 startpc = vs->startpc; 1469 startpc = vs->startpc;
1500 fs_buf_uleb128(ls, startpc-lastpc); 1470 p = lj_strfmt_wuleb128(p, startpc-lastpc);
1501 fs_buf_uleb128(ls, vs->endpc-startpc); 1471 p = lj_strfmt_wuleb128(p, vs->endpc-startpc);
1472 setsbufP(&ls->sb, p);
1502 lastpc = startpc; 1473 lastpc = startpc;
1503 } 1474 }
1504 } 1475 }
1505 fs_buf_need(ls, 1); 1476 lj_buf_putb(&ls->sb, '\0'); /* Terminator for varinfo. */
1506 ls->sb.buf[ls->sb.n++] = '\0'; /* Terminator for varinfo. */ 1477 return sbuflen(&ls->sb);
1507 return ls->sb.n;
1508} 1478}
1509 1479
1510/* Fixup variable info for prototype. */ 1480/* Fixup variable info for prototype. */
@@ -1512,7 +1482,7 @@ static void fs_fixup_var(LexState *ls, GCproto *pt, uint8_t *p, size_t ofsvar)
1512{ 1482{
1513 setmref(pt->uvinfo, p); 1483 setmref(pt->uvinfo, p);
1514 setmref(pt->varinfo, (char *)p + ofsvar); 1484 setmref(pt->varinfo, (char *)p + ofsvar);
1515 memcpy(p, ls->sb.buf, ls->sb.n); /* Copy from temp. string buffer. */ 1485 memcpy(p, sbufB(&ls->sb), sbuflen(&ls->sb)); /* Copy from temp. buffer. */
1516} 1486}
1517#else 1487#else
1518 1488
@@ -1621,7 +1591,7 @@ static GCproto *fs_finish(LexState *ls, BCLine line)
1621 L->top--; /* Pop table of constants. */ 1591 L->top--; /* Pop table of constants. */
1622 ls->vtop = fs->vbase; /* Reset variable stack. */ 1592 ls->vtop = fs->vbase; /* Reset variable stack. */
1623 ls->fs = fs->prev; 1593 ls->fs = fs->prev;
1624 lua_assert(ls->fs != NULL || ls->token == TK_eof); 1594 lua_assert(ls->fs != NULL || ls->tok == TK_eof);
1625 return pt; 1595 return pt;
1626} 1596}
1627 1597
@@ -1718,10 +1688,9 @@ static void expr_bracket(LexState *ls, ExpDesc *v)
1718static void expr_kvalue(TValue *v, ExpDesc *e) 1688static void expr_kvalue(TValue *v, ExpDesc *e)
1719{ 1689{
1720 if (e->k <= VKTRUE) { 1690 if (e->k <= VKTRUE) {
1721 setitype(v, ~(uint32_t)e->k); 1691 setpriV(v, ~(uint32_t)e->k);
1722 } else if (e->k == VKSTR) { 1692 } else if (e->k == VKSTR) {
1723 setgcref(v->gcr, obj2gco(e->u.sval)); 1693 setgcVraw(v, obj2gco(e->u.sval), LJ_TSTR);
1724 setitype(v, LJ_TSTR);
1725 } else { 1694 } else {
1726 lua_assert(tvisnumber(expr_numtv(e))); 1695 lua_assert(tvisnumber(expr_numtv(e)));
1727 *v = *expr_numtv(e); 1696 *v = *expr_numtv(e);
@@ -1743,15 +1712,15 @@ static void expr_table(LexState *ls, ExpDesc *e)
1743 bcreg_reserve(fs, 1); 1712 bcreg_reserve(fs, 1);
1744 freg++; 1713 freg++;
1745 lex_check(ls, '{'); 1714 lex_check(ls, '{');
1746 while (ls->token != '}') { 1715 while (ls->tok != '}') {
1747 ExpDesc key, val; 1716 ExpDesc key, val;
1748 vcall = 0; 1717 vcall = 0;
1749 if (ls->token == '[') { 1718 if (ls->tok == '[') {
1750 expr_bracket(ls, &key); /* Already calls expr_toval. */ 1719 expr_bracket(ls, &key); /* Already calls expr_toval. */
1751 if (!expr_isk(&key)) expr_index(fs, e, &key); 1720 if (!expr_isk(&key)) expr_index(fs, e, &key);
1752 if (expr_isnumk(&key) && expr_numiszero(&key)) needarr = 1; else nhash++; 1721 if (expr_isnumk(&key) && expr_numiszero(&key)) needarr = 1; else nhash++;
1753 lex_check(ls, '='); 1722 lex_check(ls, '=');
1754 } else if ((ls->token == TK_name || (!LJ_52 && ls->token == TK_goto)) && 1723 } else if ((ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) &&
1755 lj_lex_lookahead(ls) == '=') { 1724 lj_lex_lookahead(ls) == '=') {
1756 expr_str(ls, &key); 1725 expr_str(ls, &key);
1757 lex_check(ls, '='); 1726 lex_check(ls, '=');
@@ -1844,11 +1813,11 @@ static BCReg parse_params(LexState *ls, int needself)
1844 lex_check(ls, '('); 1813 lex_check(ls, '(');
1845 if (needself) 1814 if (needself)
1846 var_new_lit(ls, nparams++, "self"); 1815 var_new_lit(ls, nparams++, "self");
1847 if (ls->token != ')') { 1816 if (ls->tok != ')') {
1848 do { 1817 do {
1849 if (ls->token == TK_name || (!LJ_52 && ls->token == TK_goto)) { 1818 if (ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) {
1850 var_new(ls, nparams++, lex_str(ls)); 1819 var_new(ls, nparams++, lex_str(ls));
1851 } else if (ls->token == TK_dots) { 1820 } else if (ls->tok == TK_dots) {
1852 lj_lex_next(ls); 1821 lj_lex_next(ls);
1853 fs->flags |= PROTO_VARARG; 1822 fs->flags |= PROTO_VARARG;
1854 break; 1823 break;
@@ -1882,7 +1851,7 @@ static void parse_body(LexState *ls, ExpDesc *e, int needself, BCLine line)
1882 fs.bclim = pfs->bclim - pfs->pc; 1851 fs.bclim = pfs->bclim - pfs->pc;
1883 bcemit_AD(&fs, BC_FUNCF, 0, 0); /* Placeholder. */ 1852 bcemit_AD(&fs, BC_FUNCF, 0, 0); /* Placeholder. */
1884 parse_chunk(ls); 1853 parse_chunk(ls);
1885 if (ls->token != TK_end) lex_match(ls, TK_end, TK_function, line); 1854 if (ls->tok != TK_end) lex_match(ls, TK_end, TK_function, line);
1886 pt = fs_finish(ls, (ls->lastline = ls->linenumber)); 1855 pt = fs_finish(ls, (ls->lastline = ls->linenumber));
1887 pfs->bcbase = ls->bcstack + oldbase; /* May have been reallocated. */ 1856 pfs->bcbase = ls->bcstack + oldbase; /* May have been reallocated. */
1888 pfs->bclim = (BCPos)(ls->sizebcstack - oldbase); 1857 pfs->bclim = (BCPos)(ls->sizebcstack - oldbase);
@@ -1921,13 +1890,13 @@ static void parse_args(LexState *ls, ExpDesc *e)
1921 BCIns ins; 1890 BCIns ins;
1922 BCReg base; 1891 BCReg base;
1923 BCLine line = ls->linenumber; 1892 BCLine line = ls->linenumber;
1924 if (ls->token == '(') { 1893 if (ls->tok == '(') {
1925#if !LJ_52 1894#if !LJ_52
1926 if (line != ls->lastline) 1895 if (line != ls->lastline)
1927 err_syntax(ls, LJ_ERR_XAMBIG); 1896 err_syntax(ls, LJ_ERR_XAMBIG);
1928#endif 1897#endif
1929 lj_lex_next(ls); 1898 lj_lex_next(ls);
1930 if (ls->token == ')') { /* f(). */ 1899 if (ls->tok == ')') { /* f(). */
1931 args.k = VVOID; 1900 args.k = VVOID;
1932 } else { 1901 } else {
1933 expr_list(ls, &args); 1902 expr_list(ls, &args);
@@ -1935,11 +1904,11 @@ static void parse_args(LexState *ls, ExpDesc *e)
1935 setbc_b(bcptr(fs, &args), 0); /* Pass on multiple results. */ 1904 setbc_b(bcptr(fs, &args), 0); /* Pass on multiple results. */
1936 } 1905 }
1937 lex_match(ls, ')', '(', line); 1906 lex_match(ls, ')', '(', line);
1938 } else if (ls->token == '{') { 1907 } else if (ls->tok == '{') {
1939 expr_table(ls, &args); 1908 expr_table(ls, &args);
1940 } else if (ls->token == TK_string) { 1909 } else if (ls->tok == TK_string) {
1941 expr_init(&args, VKSTR, 0); 1910 expr_init(&args, VKSTR, 0);
1942 args.u.sval = strV(&ls->tokenval); 1911 args.u.sval = strV(&ls->tokval);
1943 lj_lex_next(ls); 1912 lj_lex_next(ls);
1944 } else { 1913 } else {
1945 err_syntax(ls, LJ_ERR_XFUNARG); 1914 err_syntax(ls, LJ_ERR_XFUNARG);
@@ -1948,11 +1917,11 @@ static void parse_args(LexState *ls, ExpDesc *e)
1948 lua_assert(e->k == VNONRELOC); 1917 lua_assert(e->k == VNONRELOC);
1949 base = e->u.s.info; /* Base register for call. */ 1918 base = e->u.s.info; /* Base register for call. */
1950 if (args.k == VCALL) { 1919 if (args.k == VCALL) {
1951 ins = BCINS_ABC(BC_CALLM, base, 2, args.u.s.aux - base - 1); 1920 ins = BCINS_ABC(BC_CALLM, base, 2, args.u.s.aux - base - 1 - LJ_FR2);
1952 } else { 1921 } else {
1953 if (args.k != VVOID) 1922 if (args.k != VVOID)
1954 expr_tonextreg(fs, &args); 1923 expr_tonextreg(fs, &args);
1955 ins = BCINS_ABC(BC_CALL, base, 2, fs->freereg - base); 1924 ins = BCINS_ABC(BC_CALL, base, 2, fs->freereg - base - LJ_FR2);
1956 } 1925 }
1957 expr_init(e, VCALL, bcemit_INS(fs, ins)); 1926 expr_init(e, VCALL, bcemit_INS(fs, ins));
1958 e->u.s.aux = base; 1927 e->u.s.aux = base;
@@ -1965,33 +1934,34 @@ static void expr_primary(LexState *ls, ExpDesc *v)
1965{ 1934{
1966 FuncState *fs = ls->fs; 1935 FuncState *fs = ls->fs;
1967 /* Parse prefix expression. */ 1936 /* Parse prefix expression. */
1968 if (ls->token == '(') { 1937 if (ls->tok == '(') {
1969 BCLine line = ls->linenumber; 1938 BCLine line = ls->linenumber;
1970 lj_lex_next(ls); 1939 lj_lex_next(ls);
1971 expr(ls, v); 1940 expr(ls, v);
1972 lex_match(ls, ')', '(', line); 1941 lex_match(ls, ')', '(', line);
1973 expr_discharge(ls->fs, v); 1942 expr_discharge(ls->fs, v);
1974 } else if (ls->token == TK_name || (!LJ_52 && ls->token == TK_goto)) { 1943 } else if (ls->tok == TK_name || (!LJ_52 && ls->tok == TK_goto)) {
1975 var_lookup(ls, v); 1944 var_lookup(ls, v);
1976 } else { 1945 } else {
1977 err_syntax(ls, LJ_ERR_XSYMBOL); 1946 err_syntax(ls, LJ_ERR_XSYMBOL);
1978 } 1947 }
1979 for (;;) { /* Parse multiple expression suffixes. */ 1948 for (;;) { /* Parse multiple expression suffixes. */
1980 if (ls->token == '.') { 1949 if (ls->tok == '.') {
1981 expr_field(ls, v); 1950 expr_field(ls, v);
1982 } else if (ls->token == '[') { 1951 } else if (ls->tok == '[') {
1983 ExpDesc key; 1952 ExpDesc key;
1984 expr_toanyreg(fs, v); 1953 expr_toanyreg(fs, v);
1985 expr_bracket(ls, &key); 1954 expr_bracket(ls, &key);
1986 expr_index(fs, v, &key); 1955 expr_index(fs, v, &key);
1987 } else if (ls->token == ':') { 1956 } else if (ls->tok == ':') {
1988 ExpDesc key; 1957 ExpDesc key;
1989 lj_lex_next(ls); 1958 lj_lex_next(ls);
1990 expr_str(ls, &key); 1959 expr_str(ls, &key);
1991 bcemit_method(fs, v, &key); 1960 bcemit_method(fs, v, &key);
1992 parse_args(ls, v); 1961 parse_args(ls, v);
1993 } else if (ls->token == '(' || ls->token == TK_string || ls->token == '{') { 1962 } else if (ls->tok == '(' || ls->tok == TK_string || ls->tok == '{') {
1994 expr_tonextreg(fs, v); 1963 expr_tonextreg(fs, v);
1964 if (LJ_FR2) bcreg_reserve(fs, 1);
1995 parse_args(ls, v); 1965 parse_args(ls, v);
1996 } else { 1966 } else {
1997 break; 1967 break;
@@ -2002,14 +1972,14 @@ static void expr_primary(LexState *ls, ExpDesc *v)
2002/* Parse simple expression. */ 1972/* Parse simple expression. */
2003static void expr_simple(LexState *ls, ExpDesc *v) 1973static void expr_simple(LexState *ls, ExpDesc *v)
2004{ 1974{
2005 switch (ls->token) { 1975 switch (ls->tok) {
2006 case TK_number: 1976 case TK_number:
2007 expr_init(v, (LJ_HASFFI && tviscdata(&ls->tokenval)) ? VKCDATA : VKNUM, 0); 1977 expr_init(v, (LJ_HASFFI && tviscdata(&ls->tokval)) ? VKCDATA : VKNUM, 0);
2008 copyTV(ls->L, &v->u.nval, &ls->tokenval); 1978 copyTV(ls->L, &v->u.nval, &ls->tokval);
2009 break; 1979 break;
2010 case TK_string: 1980 case TK_string:
2011 expr_init(v, VKSTR, 0); 1981 expr_init(v, VKSTR, 0);
2012 v->u.sval = strV(&ls->tokenval); 1982 v->u.sval = strV(&ls->tokval);
2013 break; 1983 break;
2014 case TK_nil: 1984 case TK_nil:
2015 expr_init(v, VKNIL, 0); 1985 expr_init(v, VKNIL, 0);
@@ -2097,11 +2067,11 @@ static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit);
2097static void expr_unop(LexState *ls, ExpDesc *v) 2067static void expr_unop(LexState *ls, ExpDesc *v)
2098{ 2068{
2099 BCOp op; 2069 BCOp op;
2100 if (ls->token == TK_not) { 2070 if (ls->tok == TK_not) {
2101 op = BC_NOT; 2071 op = BC_NOT;
2102 } else if (ls->token == '-') { 2072 } else if (ls->tok == '-') {
2103 op = BC_UNM; 2073 op = BC_UNM;
2104 } else if (ls->token == '#') { 2074 } else if (ls->tok == '#') {
2105 op = BC_LEN; 2075 op = BC_LEN;
2106 } else { 2076 } else {
2107 expr_simple(ls, v); 2077 expr_simple(ls, v);
@@ -2118,7 +2088,7 @@ static BinOpr expr_binop(LexState *ls, ExpDesc *v, uint32_t limit)
2118 BinOpr op; 2088 BinOpr op;
2119 synlevel_begin(ls); 2089 synlevel_begin(ls);
2120 expr_unop(ls, v); 2090 expr_unop(ls, v);
2121 op = token2binop(ls->token); 2091 op = token2binop(ls->tok);
2122 while (op != OPR_NOBINOPR && priority[op].left > limit) { 2092 while (op != OPR_NOBINOPR && priority[op].left > limit) {
2123 ExpDesc v2; 2093 ExpDesc v2;
2124 BinOpr nextop; 2094 BinOpr nextop;
@@ -2307,9 +2277,9 @@ static void parse_func(LexState *ls, BCLine line)
2307 lj_lex_next(ls); /* Skip 'function'. */ 2277 lj_lex_next(ls); /* Skip 'function'. */
2308 /* Parse function name. */ 2278 /* Parse function name. */
2309 var_lookup(ls, &v); 2279 var_lookup(ls, &v);
2310 while (ls->token == '.') /* Multiple dot-separated fields. */ 2280 while (ls->tok == '.') /* Multiple dot-separated fields. */
2311 expr_field(ls, &v); 2281 expr_field(ls, &v);
2312 if (ls->token == ':') { /* Optional colon to signify method call. */ 2282 if (ls->tok == ':') { /* Optional colon to signify method call. */
2313 needself = 1; 2283 needself = 1;
2314 expr_field(ls, &v); 2284 expr_field(ls, &v);
2315 } 2285 }
@@ -2322,9 +2292,9 @@ static void parse_func(LexState *ls, BCLine line)
2322/* -- Control transfer statements ----------------------------------------- */ 2292/* -- Control transfer statements ----------------------------------------- */
2323 2293
2324/* Check for end of block. */ 2294/* Check for end of block. */
2325static int endofblock(LexToken token) 2295static int parse_isend(LexToken tok)
2326{ 2296{
2327 switch (token) { 2297 switch (tok) {
2328 case TK_else: case TK_elseif: case TK_end: case TK_until: case TK_eof: 2298 case TK_else: case TK_elseif: case TK_end: case TK_until: case TK_eof:
2329 return 1; 2299 return 1;
2330 default: 2300 default:
@@ -2339,7 +2309,7 @@ static void parse_return(LexState *ls)
2339 FuncState *fs = ls->fs; 2309 FuncState *fs = ls->fs;
2340 lj_lex_next(ls); /* Skip 'return'. */ 2310 lj_lex_next(ls); /* Skip 'return'. */
2341 fs->flags |= PROTO_HAS_RETURN; 2311 fs->flags |= PROTO_HAS_RETURN;
2342 if (endofblock(ls->token) || ls->token == ';') { /* Bare return. */ 2312 if (parse_isend(ls->tok) || ls->tok == ';') { /* Bare return. */
2343 ins = BCINS_AD(BC_RET0, 0, 1); 2313 ins = BCINS_AD(BC_RET0, 0, 1);
2344 } else { /* Return with one or more values. */ 2314 } else { /* Return with one or more values. */
2345 ExpDesc e; /* Receives the _last_ expression in the list. */ 2315 ExpDesc e; /* Receives the _last_ expression in the list. */
@@ -2405,18 +2375,18 @@ static void parse_label(LexState *ls)
2405 lex_check(ls, TK_label); 2375 lex_check(ls, TK_label);
2406 /* Recursively parse trailing statements: labels and ';' (Lua 5.2 only). */ 2376 /* Recursively parse trailing statements: labels and ';' (Lua 5.2 only). */
2407 for (;;) { 2377 for (;;) {
2408 if (ls->token == TK_label) { 2378 if (ls->tok == TK_label) {
2409 synlevel_begin(ls); 2379 synlevel_begin(ls);
2410 parse_label(ls); 2380 parse_label(ls);
2411 synlevel_end(ls); 2381 synlevel_end(ls);
2412 } else if (LJ_52 && ls->token == ';') { 2382 } else if (LJ_52 && ls->tok == ';') {
2413 lj_lex_next(ls); 2383 lj_lex_next(ls);
2414 } else { 2384 } else {
2415 break; 2385 break;
2416 } 2386 }
2417 } 2387 }
2418 /* Trailing label is considered to be outside of scope. */ 2388 /* Trailing label is considered to be outside of scope. */
2419 if (endofblock(ls->token) && ls->token != TK_until) 2389 if (parse_isend(ls->tok) && ls->tok != TK_until)
2420 ls->vstack[idx].slot = fs->bl->nactvar; 2390 ls->vstack[idx].slot = fs->bl->nactvar;
2421 gola_resolve(ls, fs->bl, idx); 2391 gola_resolve(ls, fs->bl, idx);
2422} 2392}
@@ -2572,7 +2542,8 @@ static void parse_for_iter(LexState *ls, GCstr *indexname)
2572 lex_check(ls, TK_in); 2542 lex_check(ls, TK_in);
2573 line = ls->linenumber; 2543 line = ls->linenumber;
2574 assign_adjust(ls, 3, expr_list(ls, &e), &e); 2544 assign_adjust(ls, 3, expr_list(ls, &e), &e);
2575 bcreg_bump(fs, 3); /* The iterator needs another 3 slots (func + 2 args). */ 2545 /* The iterator needs another 3 [4] slots (func [pc] | state ctl). */
2546 bcreg_bump(fs, 3+LJ_FR2);
2576 isnext = (nvars <= 5 && predict_next(ls, fs, exprpc)); 2547 isnext = (nvars <= 5 && predict_next(ls, fs, exprpc));
2577 var_add(ls, 3); /* Hidden control variables. */ 2548 var_add(ls, 3); /* Hidden control variables. */
2578 lex_check(ls, TK_do); 2549 lex_check(ls, TK_do);
@@ -2600,9 +2571,9 @@ static void parse_for(LexState *ls, BCLine line)
2600 fscope_begin(fs, &bl, FSCOPE_LOOP); 2571 fscope_begin(fs, &bl, FSCOPE_LOOP);
2601 lj_lex_next(ls); /* Skip 'for'. */ 2572 lj_lex_next(ls); /* Skip 'for'. */
2602 varname = lex_str(ls); /* Get first variable name. */ 2573 varname = lex_str(ls); /* Get first variable name. */
2603 if (ls->token == '=') 2574 if (ls->tok == '=')
2604 parse_for_num(ls, varname, line); 2575 parse_for_num(ls, varname, line);
2605 else if (ls->token == ',' || ls->token == TK_in) 2576 else if (ls->tok == ',' || ls->tok == TK_in)
2606 parse_for_iter(ls, varname); 2577 parse_for_iter(ls, varname);
2607 else 2578 else
2608 err_syntax(ls, LJ_ERR_XFOR); 2579 err_syntax(ls, LJ_ERR_XFOR);
@@ -2628,12 +2599,12 @@ static void parse_if(LexState *ls, BCLine line)
2628 BCPos flist; 2599 BCPos flist;
2629 BCPos escapelist = NO_JMP; 2600 BCPos escapelist = NO_JMP;
2630 flist = parse_then(ls); 2601 flist = parse_then(ls);
2631 while (ls->token == TK_elseif) { /* Parse multiple 'elseif' blocks. */ 2602 while (ls->tok == TK_elseif) { /* Parse multiple 'elseif' blocks. */
2632 jmp_append(fs, &escapelist, bcemit_jmp(fs)); 2603 jmp_append(fs, &escapelist, bcemit_jmp(fs));
2633 jmp_tohere(fs, flist); 2604 jmp_tohere(fs, flist);
2634 flist = parse_then(ls); 2605 flist = parse_then(ls);
2635 } 2606 }
2636 if (ls->token == TK_else) { /* Parse optional 'else' block. */ 2607 if (ls->tok == TK_else) { /* Parse optional 'else' block. */
2637 jmp_append(fs, &escapelist, bcemit_jmp(fs)); 2608 jmp_append(fs, &escapelist, bcemit_jmp(fs));
2638 jmp_tohere(fs, flist); 2609 jmp_tohere(fs, flist);
2639 lj_lex_next(ls); /* Skip 'else'. */ 2610 lj_lex_next(ls); /* Skip 'else'. */
@@ -2651,7 +2622,7 @@ static void parse_if(LexState *ls, BCLine line)
2651static int parse_stmt(LexState *ls) 2622static int parse_stmt(LexState *ls)
2652{ 2623{
2653 BCLine line = ls->linenumber; 2624 BCLine line = ls->linenumber;
2654 switch (ls->token) { 2625 switch (ls->tok) {
2655 case TK_if: 2626 case TK_if:
2656 parse_if(ls, line); 2627 parse_if(ls, line);
2657 break; 2628 break;
@@ -2709,7 +2680,7 @@ static void parse_chunk(LexState *ls)
2709{ 2680{
2710 int islast = 0; 2681 int islast = 0;
2711 synlevel_begin(ls); 2682 synlevel_begin(ls);
2712 while (!islast && !endofblock(ls->token)) { 2683 while (!islast && !parse_isend(ls->tok)) {
2713 islast = parse_stmt(ls); 2684 islast = parse_stmt(ls);
2714 lex_opt(ls, ';'); 2685 lex_opt(ls, ';');
2715 lua_assert(ls->fs->framesize >= ls->fs->freereg && 2686 lua_assert(ls->fs->framesize >= ls->fs->freereg &&
@@ -2744,7 +2715,7 @@ GCproto *lj_parse(LexState *ls)
2744 bcemit_AD(&fs, BC_FUNCV, 0, 0); /* Placeholder. */ 2715 bcemit_AD(&fs, BC_FUNCV, 0, 0); /* Placeholder. */
2745 lj_lex_next(ls); /* Read-ahead first token. */ 2716 lj_lex_next(ls); /* Read-ahead first token. */
2746 parse_chunk(ls); 2717 parse_chunk(ls);
2747 if (ls->token != TK_eof) 2718 if (ls->tok != TK_eof)
2748 err_token(ls, TK_eof); 2719 err_token(ls, TK_eof);
2749 pt = fs_finish(ls, ls->linenumber); 2720 pt = fs_finish(ls, ls->linenumber);
2750 L->top--; /* Drop chunkname. */ 2721 L->top--; /* Drop chunkname. */
diff --git a/src/lj_profile.c b/src/lj_profile.c
new file mode 100644
index 00000000..116998e1
--- /dev/null
+++ b/src/lj_profile.c
@@ -0,0 +1,368 @@
1/*
2** Low-overhead profiling.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#define lj_profile_c
7#define LUA_CORE
8
9#include "lj_obj.h"
10
11#if LJ_HASPROFILE
12
13#include "lj_buf.h"
14#include "lj_frame.h"
15#include "lj_debug.h"
16#include "lj_dispatch.h"
17#if LJ_HASJIT
18#include "lj_jit.h"
19#include "lj_trace.h"
20#endif
21#include "lj_profile.h"
22
23#include "luajit.h"
24
25#if LJ_PROFILE_SIGPROF
26
27#include <sys/time.h>
28#include <signal.h>
29#define profile_lock(ps) UNUSED(ps)
30#define profile_unlock(ps) UNUSED(ps)
31
32#elif LJ_PROFILE_PTHREAD
33
34#include <pthread.h>
35#include <time.h>
36#if LJ_TARGET_PS3
37#include <sys/timer.h>
38#endif
39#define profile_lock(ps) pthread_mutex_lock(&ps->lock)
40#define profile_unlock(ps) pthread_mutex_unlock(&ps->lock)
41
42#elif LJ_PROFILE_WTHREAD
43
44#define WIN32_LEAN_AND_MEAN
45#if LJ_TARGET_XBOX360
46#include <xtl.h>
47#include <xbox.h>
48#else
49#include <windows.h>
50#endif
51typedef unsigned int (WINAPI *WMM_TPFUNC)(unsigned int);
52#define profile_lock(ps) EnterCriticalSection(&ps->lock)
53#define profile_unlock(ps) LeaveCriticalSection(&ps->lock)
54
55#endif
56
57/* Profiler state. */
58typedef struct ProfileState {
59 global_State *g; /* VM state that started the profiler. */
60 luaJIT_profile_callback cb; /* Profiler callback. */
61 void *data; /* Profiler callback data. */
62 SBuf sb; /* String buffer for stack dumps. */
63 int interval; /* Sample interval in milliseconds. */
64 int samples; /* Number of samples for next callback. */
65 int vmstate; /* VM state when profile timer triggered. */
66#if LJ_PROFILE_SIGPROF
67 struct sigaction oldsa; /* Previous SIGPROF state. */
68#elif LJ_PROFILE_PTHREAD
69 pthread_mutex_t lock; /* g->hookmask update lock. */
70 pthread_t thread; /* Timer thread. */
71 int abort; /* Abort timer thread. */
72#elif LJ_PROFILE_WTHREAD
73#if LJ_TARGET_WINDOWS
74 HINSTANCE wmm; /* WinMM library handle. */
75 WMM_TPFUNC wmm_tbp; /* WinMM timeBeginPeriod function. */
76 WMM_TPFUNC wmm_tep; /* WinMM timeEndPeriod function. */
77#endif
78 CRITICAL_SECTION lock; /* g->hookmask update lock. */
79 HANDLE thread; /* Timer thread. */
80 int abort; /* Abort timer thread. */
81#endif
82} ProfileState;
83
84/* Sadly, we have to use a static profiler state.
85**
86** The SIGPROF variant needs a static pointer to the global state, anyway.
87** And it would be hard to extend for multiple threads. You can still use
88** multiple VMs in multiple threads, but only profile one at a time.
89*/
90static ProfileState profile_state;
91
92/* Default sample interval in milliseconds. */
93#define LJ_PROFILE_INTERVAL_DEFAULT 10
94
95/* -- Profiler/hook interaction ------------------------------------------- */
96
97#if !LJ_PROFILE_SIGPROF
98void LJ_FASTCALL lj_profile_hook_enter(global_State *g)
99{
100 ProfileState *ps = &profile_state;
101 if (ps->g) {
102 profile_lock(ps);
103 hook_enter(g);
104 profile_unlock(ps);
105 } else {
106 hook_enter(g);
107 }
108}
109
110void LJ_FASTCALL lj_profile_hook_leave(global_State *g)
111{
112 ProfileState *ps = &profile_state;
113 if (ps->g) {
114 profile_lock(ps);
115 hook_leave(g);
116 profile_unlock(ps);
117 } else {
118 hook_leave(g);
119 }
120}
121#endif
122
123/* -- Profile callbacks --------------------------------------------------- */
124
125/* Callback from profile hook (HOOK_PROFILE already cleared). */
126void LJ_FASTCALL lj_profile_interpreter(lua_State *L)
127{
128 ProfileState *ps = &profile_state;
129 global_State *g = G(L);
130 uint8_t mask;
131 profile_lock(ps);
132 mask = (g->hookmask & ~HOOK_PROFILE);
133 if (!(mask & HOOK_VMEVENT)) {
134 int samples = ps->samples;
135 ps->samples = 0;
136 g->hookmask = HOOK_VMEVENT;
137 lj_dispatch_update(g);
138 profile_unlock(ps);
139 ps->cb(ps->data, L, samples, ps->vmstate); /* Invoke user callback. */
140 profile_lock(ps);
141 mask |= (g->hookmask & HOOK_PROFILE);
142 }
143 g->hookmask = mask;
144 lj_dispatch_update(g);
145 profile_unlock(ps);
146}
147
148/* Trigger profile hook. Asynchronous call from OS-specific profile timer. */
149static void profile_trigger(ProfileState *ps)
150{
151 global_State *g = ps->g;
152 uint8_t mask;
153 profile_lock(ps);
154 ps->samples++; /* Always increment number of samples. */
155 mask = g->hookmask;
156 if (!(mask & (HOOK_PROFILE|HOOK_VMEVENT))) { /* Set profile hook. */
157 int st = g->vmstate;
158 ps->vmstate = st >= 0 ? 'N' :
159 st == ~LJ_VMST_INTERP ? 'I' :
160 st == ~LJ_VMST_C ? 'C' :
161 st == ~LJ_VMST_GC ? 'G' : 'J';
162 g->hookmask = (mask | HOOK_PROFILE);
163 lj_dispatch_update(g);
164 }
165 profile_unlock(ps);
166}
167
168/* -- OS-specific profile timer handling ---------------------------------- */
169
170#if LJ_PROFILE_SIGPROF
171
172/* SIGPROF handler. */
173static void profile_signal(int sig)
174{
175 UNUSED(sig);
176 profile_trigger(&profile_state);
177}
178
179/* Start profiling timer. */
180static void profile_timer_start(ProfileState *ps)
181{
182 int interval = ps->interval;
183 struct itimerval tm;
184 struct sigaction sa;
185 tm.it_value.tv_sec = tm.it_interval.tv_sec = interval / 1000;
186 tm.it_value.tv_usec = tm.it_interval.tv_usec = (interval % 1000) * 1000;
187 setitimer(ITIMER_PROF, &tm, NULL);
188 sa.sa_flags = SA_RESTART;
189 sa.sa_handler = profile_signal;
190 sigemptyset(&sa.sa_mask);
191 sigaction(SIGPROF, &sa, &ps->oldsa);
192}
193
194/* Stop profiling timer. */
195static void profile_timer_stop(ProfileState *ps)
196{
197 struct itimerval tm;
198 tm.it_value.tv_sec = tm.it_interval.tv_sec = 0;
199 tm.it_value.tv_usec = tm.it_interval.tv_usec = 0;
200 setitimer(ITIMER_PROF, &tm, NULL);
201 sigaction(SIGPROF, &ps->oldsa, NULL);
202}
203
204#elif LJ_PROFILE_PTHREAD
205
206/* POSIX timer thread. */
207static void *profile_thread(ProfileState *ps)
208{
209 int interval = ps->interval;
210#if !LJ_TARGET_PS3
211 struct timespec ts;
212 ts.tv_sec = interval / 1000;
213 ts.tv_nsec = (interval % 1000) * 1000000;
214#endif
215 while (1) {
216#if LJ_TARGET_PS3
217 sys_timer_usleep(interval * 1000);
218#else
219 nanosleep(&ts, NULL);
220#endif
221 if (ps->abort) break;
222 profile_trigger(ps);
223 }
224 return NULL;
225}
226
227/* Start profiling timer thread. */
228static void profile_timer_start(ProfileState *ps)
229{
230 pthread_mutex_init(&ps->lock, 0);
231 ps->abort = 0;
232 pthread_create(&ps->thread, NULL, (void *(*)(void *))profile_thread, ps);
233}
234
235/* Stop profiling timer thread. */
236static void profile_timer_stop(ProfileState *ps)
237{
238 ps->abort = 1;
239 pthread_join(ps->thread, NULL);
240 pthread_mutex_destroy(&ps->lock);
241}
242
243#elif LJ_PROFILE_WTHREAD
244
245/* Windows timer thread. */
246static DWORD WINAPI profile_thread(void *psx)
247{
248 ProfileState *ps = (ProfileState *)psx;
249 int interval = ps->interval;
250#if LJ_TARGET_WINDOWS
251 ps->wmm_tbp(interval);
252#endif
253 while (1) {
254 Sleep(interval);
255 if (ps->abort) break;
256 profile_trigger(ps);
257 }
258#if LJ_TARGET_WINDOWS
259 ps->wmm_tep(interval);
260#endif
261 return 0;
262}
263
264/* Start profiling timer thread. */
265static void profile_timer_start(ProfileState *ps)
266{
267#if LJ_TARGET_WINDOWS
268 if (!ps->wmm) { /* Load WinMM library on-demand. */
269 ps->wmm = LoadLibraryExA("winmm.dll", NULL, 0);
270 if (ps->wmm) {
271 ps->wmm_tbp = (WMM_TPFUNC)GetProcAddress(ps->wmm, "timeBeginPeriod");
272 ps->wmm_tep = (WMM_TPFUNC)GetProcAddress(ps->wmm, "timeEndPeriod");
273 if (!ps->wmm_tbp || !ps->wmm_tep) {
274 ps->wmm = NULL;
275 return;
276 }
277 }
278 }
279#endif
280 InitializeCriticalSection(&ps->lock);
281 ps->abort = 0;
282 ps->thread = CreateThread(NULL, 0, profile_thread, ps, 0, NULL);
283}
284
285/* Stop profiling timer thread. */
286static void profile_timer_stop(ProfileState *ps)
287{
288 ps->abort = 1;
289 WaitForSingleObject(ps->thread, INFINITE);
290 DeleteCriticalSection(&ps->lock);
291}
292
293#endif
294
295/* -- Public profiling API ------------------------------------------------ */
296
297/* Start profiling. */
298LUA_API void luaJIT_profile_start(lua_State *L, const char *mode,
299 luaJIT_profile_callback cb, void *data)
300{
301 ProfileState *ps = &profile_state;
302 int interval = LJ_PROFILE_INTERVAL_DEFAULT;
303 while (*mode) {
304 int m = *mode++;
305 switch (m) {
306 case 'i':
307 interval = 0;
308 while (*mode >= '0' && *mode <= '9')
309 interval = interval * 10 + (*mode++ - '0');
310 if (interval <= 0) interval = 1;
311 break;
312#if LJ_HASJIT
313 case 'l': case 'f':
314 L2J(L)->prof_mode = m;
315 lj_trace_flushall(L);
316 break;
317#endif
318 default: /* Ignore unknown mode chars. */
319 break;
320 }
321 }
322 if (ps->g) {
323 luaJIT_profile_stop(L);
324 if (ps->g) return; /* Profiler in use by another VM. */
325 }
326 ps->g = G(L);
327 ps->interval = interval;
328 ps->cb = cb;
329 ps->data = data;
330 ps->samples = 0;
331 lj_buf_init(L, &ps->sb);
332 profile_timer_start(ps);
333}
334
335/* Stop profiling. */
336LUA_API void luaJIT_profile_stop(lua_State *L)
337{
338 ProfileState *ps = &profile_state;
339 global_State *g = ps->g;
340 if (G(L) == g) { /* Only stop profiler if started by this VM. */
341 profile_timer_stop(ps);
342 g->hookmask &= ~HOOK_PROFILE;
343 lj_dispatch_update(g);
344#if LJ_HASJIT
345 G2J(g)->prof_mode = 0;
346 lj_trace_flushall(L);
347#endif
348 lj_buf_free(g, &ps->sb);
349 setmref(ps->sb.b, NULL);
350 setmref(ps->sb.e, NULL);
351 ps->g = NULL;
352 }
353}
354
355/* Return a compact stack dump. */
356LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt,
357 int depth, size_t *len)
358{
359 ProfileState *ps = &profile_state;
360 SBuf *sb = &ps->sb;
361 setsbufL(sb, L);
362 lj_buf_reset(sb);
363 lj_debug_dumpstack(L, sb, fmt, depth);
364 *len = (size_t)sbuflen(sb);
365 return sbufB(sb);
366}
367
368#endif
diff --git a/src/lj_profile.h b/src/lj_profile.h
new file mode 100644
index 00000000..0cccfd78
--- /dev/null
+++ b/src/lj_profile.h
@@ -0,0 +1,21 @@
1/*
2** Low-overhead profiling.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_PROFILE_H
7#define _LJ_PROFILE_H
8
9#include "lj_obj.h"
10
11#if LJ_HASPROFILE
12
13LJ_FUNC void LJ_FASTCALL lj_profile_interpreter(lua_State *L);
14#if !LJ_PROFILE_SIGPROF
15LJ_FUNC void LJ_FASTCALL lj_profile_hook_enter(global_State *g);
16LJ_FUNC void LJ_FASTCALL lj_profile_hook_leave(global_State *g);
17#endif
18
19#endif
20
21#endif
diff --git a/src/lj_record.c b/src/lj_record.c
index 7b572764..9d0469c4 100644
--- a/src/lj_record.c
+++ b/src/lj_record.c
@@ -20,6 +20,9 @@
20#endif 20#endif
21#include "lj_bc.h" 21#include "lj_bc.h"
22#include "lj_ff.h" 22#include "lj_ff.h"
23#if LJ_HASPROFILE
24#include "lj_debug.h"
25#endif
23#include "lj_ir.h" 26#include "lj_ir.h"
24#include "lj_jit.h" 27#include "lj_jit.h"
25#include "lj_ircall.h" 28#include "lj_ircall.h"
@@ -48,7 +51,7 @@ static void rec_check_ir(jit_State *J)
48{ 51{
49 IRRef i, nins = J->cur.nins, nk = J->cur.nk; 52 IRRef i, nins = J->cur.nins, nk = J->cur.nk;
50 lua_assert(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536); 53 lua_assert(nk <= REF_BIAS && nins >= REF_BIAS && nins < 65536);
51 for (i = nins-1; i >= nk; i--) { 54 for (i = nk; i < nins; i++) {
52 IRIns *ir = IR(i); 55 IRIns *ir = IR(i);
53 uint32_t mode = lj_ir_mode[ir->o]; 56 uint32_t mode = lj_ir_mode[ir->o];
54 IRRef op1 = ir->op1; 57 IRRef op1 = ir->op1;
@@ -58,7 +61,10 @@ static void rec_check_ir(jit_State *J)
58 case IRMref: lua_assert(op1 >= nk); 61 case IRMref: lua_assert(op1 >= nk);
59 lua_assert(i >= REF_BIAS ? op1 < i : op1 > i); break; 62 lua_assert(i >= REF_BIAS ? op1 < i : op1 > i); break;
60 case IRMlit: break; 63 case IRMlit: break;
61 case IRMcst: lua_assert(i < REF_BIAS); continue; 64 case IRMcst: lua_assert(i < REF_BIAS);
65 if (irt_is64(ir->t) && ir->o != IR_KNULL)
66 i++;
67 continue;
62 } 68 }
63 switch (irm_op2(mode)) { 69 switch (irm_op2(mode)) {
64 case IRMnone: lua_assert(op2 == 0); break; 70 case IRMnone: lua_assert(op2 == 0); break;
@@ -81,30 +87,48 @@ static void rec_check_slots(jit_State *J)
81 BCReg s, nslots = J->baseslot + J->maxslot; 87 BCReg s, nslots = J->baseslot + J->maxslot;
82 int32_t depth = 0; 88 int32_t depth = 0;
83 cTValue *base = J->L->base - J->baseslot; 89 cTValue *base = J->L->base - J->baseslot;
84 lua_assert(J->baseslot >= 1 && J->baseslot < LJ_MAX_JSLOTS); 90 lua_assert(J->baseslot >= 1+LJ_FR2 && J->baseslot < LJ_MAX_JSLOTS);
85 lua_assert(J->baseslot == 1 || (J->slot[J->baseslot-1] & TREF_FRAME)); 91 lua_assert(J->baseslot == 1+LJ_FR2 || (J->slot[J->baseslot-1] & TREF_FRAME));
86 lua_assert(nslots < LJ_MAX_JSLOTS); 92 lua_assert(nslots < LJ_MAX_JSLOTS);
87 for (s = 0; s < nslots; s++) { 93 for (s = 0; s < nslots; s++) {
88 TRef tr = J->slot[s]; 94 TRef tr = J->slot[s];
89 if (tr) { 95 if (tr) {
90 cTValue *tv = &base[s]; 96 cTValue *tv = &base[s];
91 IRRef ref = tref_ref(tr); 97 IRRef ref = tref_ref(tr);
92 IRIns *ir; 98 IRIns *ir = NULL; /* Silence compiler. */
93 lua_assert(ref >= J->cur.nk && ref < J->cur.nins); 99 if (!LJ_FR2 || ref || !(tr & (TREF_FRAME | TREF_CONT))) {
94 ir = IR(ref); 100 lua_assert(ref >= J->cur.nk && ref < J->cur.nins);
95 lua_assert(irt_t(ir->t) == tref_t(tr)); 101 ir = IR(ref);
102 lua_assert(irt_t(ir->t) == tref_t(tr));
103 }
96 if (s == 0) { 104 if (s == 0) {
97 lua_assert(tref_isfunc(tr)); 105 lua_assert(tref_isfunc(tr));
106#if LJ_FR2
107 } else if (s == 1) {
108 lua_assert((tr & ~TREF_FRAME) == 0);
109#endif
98 } else if ((tr & TREF_FRAME)) { 110 } else if ((tr & TREF_FRAME)) {
99 GCfunc *fn = gco2func(frame_gc(tv)); 111 GCfunc *fn = gco2func(frame_gc(tv));
100 BCReg delta = (BCReg)(tv - frame_prev(tv)); 112 BCReg delta = (BCReg)(tv - frame_prev(tv));
113#if LJ_FR2
114 if (ref)
115 lua_assert(ir_knum(ir)->u64 == tv->u64);
116 tr = J->slot[s-1];
117 ir = IR(tref_ref(tr));
118#endif
101 lua_assert(tref_isfunc(tr)); 119 lua_assert(tref_isfunc(tr));
102 if (tref_isk(tr)) lua_assert(fn == ir_kfunc(ir)); 120 if (tref_isk(tr)) lua_assert(fn == ir_kfunc(ir));
103 lua_assert(s > delta ? (J->slot[s-delta] & TREF_FRAME) : (s == delta)); 121 lua_assert(s > delta + LJ_FR2 ? (J->slot[s-delta] & TREF_FRAME)
122 : (s == delta + LJ_FR2));
104 depth++; 123 depth++;
105 } else if ((tr & TREF_CONT)) { 124 } else if ((tr & TREF_CONT)) {
125#if LJ_FR2
126 if (ref)
127 lua_assert(ir_knum(ir)->u64 == tv->u64);
128#else
106 lua_assert(ir_kptr(ir) == gcrefp(tv->gcr, void)); 129 lua_assert(ir_kptr(ir) == gcrefp(tv->gcr, void));
107 lua_assert((J->slot[s+1] & TREF_FRAME)); 130#endif
131 lua_assert((J->slot[s+1+LJ_FR2] & TREF_FRAME));
108 depth++; 132 depth++;
109 } else { 133 } else {
110 if (tvisnumber(tv)) 134 if (tvisnumber(tv))
@@ -156,10 +180,10 @@ static TRef sload(jit_State *J, int32_t slot)
156/* Get TRef for current function. */ 180/* Get TRef for current function. */
157static TRef getcurrf(jit_State *J) 181static TRef getcurrf(jit_State *J)
158{ 182{
159 if (J->base[-1]) 183 if (J->base[-1-LJ_FR2])
160 return J->base[-1]; 184 return J->base[-1-LJ_FR2];
161 lua_assert(J->baseslot == 1); 185 lua_assert(J->baseslot == 1+LJ_FR2);
162 return sloadt(J, -1, IRT_FUNC, IRSLOAD_READONLY); 186 return sloadt(J, -1-LJ_FR2, IRT_FUNC, IRSLOAD_READONLY);
163} 187}
164 188
165/* Compare for raw object equality. 189/* Compare for raw object equality.
@@ -230,8 +254,12 @@ static void canonicalize_slots(jit_State *J)
230} 254}
231 255
232/* Stop recording. */ 256/* Stop recording. */
233static void rec_stop(jit_State *J, TraceLink linktype, TraceNo lnk) 257void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk)
234{ 258{
259#ifdef LUAJIT_ENABLE_TABLE_BUMP
260 if (J->retryrec)
261 lj_trace_err(J, LJ_TRERR_RETRY);
262#endif
235 lj_trace_end(J); 263 lj_trace_end(J);
236 J->cur.linktype = (uint8_t)linktype; 264 J->cur.linktype = (uint8_t)linktype;
237 J->cur.link = (uint16_t)lnk; 265 J->cur.link = (uint16_t)lnk;
@@ -499,8 +527,7 @@ static LoopEvent rec_for(jit_State *J, const BCIns *fori, int isforl)
499static LoopEvent rec_iterl(jit_State *J, const BCIns iterins) 527static LoopEvent rec_iterl(jit_State *J, const BCIns iterins)
500{ 528{
501 BCReg ra = bc_a(iterins); 529 BCReg ra = bc_a(iterins);
502 lua_assert(J->base[ra] != 0); 530 if (!tref_isnil(getslot(J, ra))) { /* Looping back? */
503 if (!tref_isnil(J->base[ra])) { /* Looping back? */
504 J->base[ra-1] = J->base[ra]; /* Copy result of ITERC to control var. */ 531 J->base[ra-1] = J->base[ra]; /* Copy result of ITERC to control var. */
505 J->maxslot = ra-1+bc_b(J->pc[-1]); 532 J->maxslot = ra-1+bc_b(J->pc[-1]);
506 J->pc += bc_j(iterins)+1; 533 J->pc += bc_j(iterins)+1;
@@ -538,12 +565,12 @@ static int innerloopleft(jit_State *J, const BCIns *pc)
538/* Handle the case when an interpreted loop op is hit. */ 565/* Handle the case when an interpreted loop op is hit. */
539static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev) 566static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
540{ 567{
541 if (J->parent == 0) { 568 if (J->parent == 0 && J->exitno == 0) {
542 if (pc == J->startpc && J->framedepth + J->retdepth == 0) { 569 if (pc == J->startpc && J->framedepth + J->retdepth == 0) {
543 /* Same loop? */ 570 /* Same loop? */
544 if (ev == LOOPEV_LEAVE) /* Must loop back to form a root trace. */ 571 if (ev == LOOPEV_LEAVE) /* Must loop back to form a root trace. */
545 lj_trace_err(J, LJ_TRERR_LLEAVE); 572 lj_trace_err(J, LJ_TRERR_LLEAVE);
546 rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping root trace. */ 573 lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Looping trace. */
547 } else if (ev != LOOPEV_LEAVE) { /* Entering inner loop? */ 574 } else if (ev != LOOPEV_LEAVE) { /* Entering inner loop? */
548 /* It's usually better to abort here and wait until the inner loop 575 /* It's usually better to abort here and wait until the inner loop
549 ** is traced. But if the inner loop repeatedly didn't loop back, 576 ** is traced. But if the inner loop repeatedly didn't loop back,
@@ -568,18 +595,64 @@ static void rec_loop_interp(jit_State *J, const BCIns *pc, LoopEvent ev)
568/* Handle the case when an already compiled loop op is hit. */ 595/* Handle the case when an already compiled loop op is hit. */
569static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev) 596static void rec_loop_jit(jit_State *J, TraceNo lnk, LoopEvent ev)
570{ 597{
571 if (J->parent == 0) { /* Root trace hit an inner loop. */ 598 if (J->parent == 0 && J->exitno == 0) { /* Root trace hit an inner loop. */
572 /* Better let the inner loop spawn a side trace back here. */ 599 /* Better let the inner loop spawn a side trace back here. */
573 lj_trace_err(J, LJ_TRERR_LINNER); 600 lj_trace_err(J, LJ_TRERR_LINNER);
574 } else if (ev != LOOPEV_LEAVE) { /* Side trace enters a compiled loop. */ 601 } else if (ev != LOOPEV_LEAVE) { /* Side trace enters a compiled loop. */
575 J->instunroll = 0; /* Cannot continue across a compiled loop op. */ 602 J->instunroll = 0; /* Cannot continue across a compiled loop op. */
576 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0) 603 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
577 rec_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Form an extra loop. */ 604 lj_record_stop(J, LJ_TRLINK_LOOP, J->cur.traceno); /* Form extra loop. */
578 else 605 else
579 rec_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the loop. */ 606 lj_record_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the loop. */
580 } /* Side trace continues across a loop that's left or not entered. */ 607 } /* Side trace continues across a loop that's left or not entered. */
581} 608}
582 609
610/* -- Record profiler hook checks ----------------------------------------- */
611
612#if LJ_HASPROFILE
613
614/* Need to insert profiler hook check? */
615static int rec_profile_need(jit_State *J, GCproto *pt, const BCIns *pc)
616{
617 GCproto *ppt;
618 lua_assert(J->prof_mode == 'f' || J->prof_mode == 'l');
619 if (!pt)
620 return 0;
621 ppt = J->prev_pt;
622 J->prev_pt = pt;
623 if (pt != ppt && ppt) {
624 J->prev_line = -1;
625 return 1;
626 }
627 if (J->prof_mode == 'l') {
628 BCLine line = lj_debug_line(pt, proto_bcpos(pt, pc));
629 BCLine pline = J->prev_line;
630 J->prev_line = line;
631 if (pline != line)
632 return 1;
633 }
634 return 0;
635}
636
637static void rec_profile_ins(jit_State *J, const BCIns *pc)
638{
639 if (J->prof_mode && rec_profile_need(J, J->pt, pc)) {
640 emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
641 lj_snap_add(J);
642 }
643}
644
645static void rec_profile_ret(jit_State *J)
646{
647 if (J->prof_mode == 'f') {
648 emitir(IRTG(IR_PROF, IRT_NIL), 0, 0);
649 J->prev_pt = NULL;
650 lj_snap_add(J);
651 }
652}
653
654#endif
655
583/* -- Record calls and returns -------------------------------------------- */ 656/* -- Record calls and returns -------------------------------------------- */
584 657
585/* Specialize to the runtime value of the called function or its prototype. */ 658/* Specialize to the runtime value of the called function or its prototype. */
@@ -590,11 +663,26 @@ static TRef rec_call_specialize(jit_State *J, GCfunc *fn, TRef tr)
590 GCproto *pt = funcproto(fn); 663 GCproto *pt = funcproto(fn);
591 /* Too many closures created? Probably not a monomorphic function. */ 664 /* Too many closures created? Probably not a monomorphic function. */
592 if (pt->flags >= PROTO_CLC_POLY) { /* Specialize to prototype instead. */ 665 if (pt->flags >= PROTO_CLC_POLY) { /* Specialize to prototype instead. */
593 TRef trpt = emitir(IRT(IR_FLOAD, IRT_P32), tr, IRFL_FUNC_PC); 666 TRef trpt = emitir(IRT(IR_FLOAD, IRT_PGC), tr, IRFL_FUNC_PC);
594 emitir(IRTG(IR_EQ, IRT_P32), trpt, lj_ir_kptr(J, proto_bc(pt))); 667 emitir(IRTG(IR_EQ, IRT_PGC), trpt, lj_ir_kptr(J, proto_bc(pt)));
595 (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); /* Prevent GC of proto. */ 668 (void)lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); /* Prevent GC of proto. */
596 return tr; 669 return tr;
597 } 670 }
671 } else {
672 /* Don't specialize to non-monomorphic builtins. */
673 switch (fn->c.ffid) {
674 case FF_coroutine_wrap_aux:
675 case FF_string_gmatch_aux:
676 /* NYI: io_file_iter doesn't have an ffid, yet. */
677 { /* Specialize to the ffid. */
678 TRef trid = emitir(IRT(IR_FLOAD, IRT_U8), tr, IRFL_FUNC_FFID);
679 emitir(IRTG(IR_EQ, IRT_INT), trid, lj_ir_kint(J, fn->c.ffid));
680 }
681 return tr;
682 default:
683 /* NYI: don't specialize to non-monomorphic C functions. */
684 break;
685 }
598 } 686 }
599 /* Otherwise specialize to the function (closure) value itself. */ 687 /* Otherwise specialize to the function (closure) value itself. */
600 kfunc = lj_ir_kfunc(J, fn); 688 kfunc = lj_ir_kfunc(J, fn);
@@ -607,21 +695,31 @@ static void rec_call_setup(jit_State *J, BCReg func, ptrdiff_t nargs)
607{ 695{
608 RecordIndex ix; 696 RecordIndex ix;
609 TValue *functv = &J->L->base[func]; 697 TValue *functv = &J->L->base[func];
610 TRef *fbase = &J->base[func]; 698 TRef kfunc, *fbase = &J->base[func];
611 ptrdiff_t i; 699 ptrdiff_t i;
612 for (i = 0; i <= nargs; i++) 700 (void)getslot(J, func); /* Ensure func has a reference. */
613 (void)getslot(J, func+i); /* Ensure func and all args have a reference. */ 701 for (i = 1; i <= nargs; i++)
702 (void)getslot(J, func+LJ_FR2+i); /* Ensure all args have a reference. */
614 if (!tref_isfunc(fbase[0])) { /* Resolve __call metamethod. */ 703 if (!tref_isfunc(fbase[0])) { /* Resolve __call metamethod. */
615 ix.tab = fbase[0]; 704 ix.tab = fbase[0];
616 copyTV(J->L, &ix.tabv, functv); 705 copyTV(J->L, &ix.tabv, functv);
617 if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj)) 706 if (!lj_record_mm_lookup(J, &ix, MM_call) || !tref_isfunc(ix.mobj))
618 lj_trace_err(J, LJ_TRERR_NOMM); 707 lj_trace_err(J, LJ_TRERR_NOMM);
619 for (i = ++nargs; i > 0; i--) /* Shift arguments up. */ 708 for (i = ++nargs; i > LJ_FR2; i--) /* Shift arguments up. */
620 fbase[i] = fbase[i-1]; 709 fbase[i+LJ_FR2] = fbase[i+LJ_FR2-1];
710#if LJ_FR2
711 fbase[2] = fbase[0];
712#endif
621 fbase[0] = ix.mobj; /* Replace function. */ 713 fbase[0] = ix.mobj; /* Replace function. */
622 functv = &ix.mobjv; 714 functv = &ix.mobjv;
623 } 715 }
624 fbase[0] = TREF_FRAME | rec_call_specialize(J, funcV(functv), fbase[0]); 716 kfunc = rec_call_specialize(J, funcV(functv), fbase[0]);
717#if LJ_FR2
718 fbase[0] = kfunc;
719 fbase[1] = TREF_FRAME;
720#else
721 fbase[0] = kfunc | TREF_FRAME;
722#endif
625 J->maxslot = (BCReg)nargs; 723 J->maxslot = (BCReg)nargs;
626} 724}
627 725
@@ -631,8 +729,8 @@ void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs)
631 rec_call_setup(J, func, nargs); 729 rec_call_setup(J, func, nargs);
632 /* Bump frame. */ 730 /* Bump frame. */
633 J->framedepth++; 731 J->framedepth++;
634 J->base += func+1; 732 J->base += func+1+LJ_FR2;
635 J->baseslot += func+1; 733 J->baseslot += func+1+LJ_FR2;
636} 734}
637 735
638/* Record tail call. */ 736/* Record tail call. */
@@ -648,7 +746,9 @@ void lj_record_tailcall(jit_State *J, BCReg func, ptrdiff_t nargs)
648 func += cbase; 746 func += cbase;
649 } 747 }
650 /* Move func + args down. */ 748 /* Move func + args down. */
651 memmove(&J->base[-1], &J->base[func], sizeof(TRef)*(J->maxslot+1)); 749 if (LJ_FR2 && J->baseslot == 2)
750 J->base[func+1] = TREF_FRAME;
751 memmove(&J->base[-1-LJ_FR2], &J->base[func], sizeof(TRef)*(J->maxslot+1+LJ_FR2));
652 /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */ 752 /* Note: the new TREF_FRAME is now at J->base[-1] (even for slot #0). */
653 /* Tailcalls can form a loop, so count towards the loop unroll limit. */ 753 /* Tailcalls can form a loop, so count towards the loop unroll limit. */
654 if (++J->tailcalled > J->loopunroll) 754 if (++J->tailcalled > J->loopunroll)
@@ -678,6 +778,8 @@ static int check_downrec_unroll(jit_State *J, GCproto *pt)
678 return 0; 778 return 0;
679} 779}
680 780
781static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot);
782
681/* Record return. */ 783/* Record return. */
682void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults) 784void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
683{ 785{
@@ -689,7 +791,7 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
689 BCReg cbase = (BCReg)frame_delta(frame); 791 BCReg cbase = (BCReg)frame_delta(frame);
690 if (--J->framedepth <= 0) 792 if (--J->framedepth <= 0)
691 lj_trace_err(J, LJ_TRERR_NYIRETL); 793 lj_trace_err(J, LJ_TRERR_NYIRETL);
692 lua_assert(J->baseslot > 1); 794 lua_assert(J->baseslot > 1+LJ_FR2);
693 gotresults++; 795 gotresults++;
694 rbase += cbase; 796 rbase += cbase;
695 J->baseslot -= (BCReg)cbase; 797 J->baseslot -= (BCReg)cbase;
@@ -700,19 +802,20 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
700 /* Return to lower frame via interpreter for unhandled cases. */ 802 /* Return to lower frame via interpreter for unhandled cases. */
701 if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) && 803 if (J->framedepth == 0 && J->pt && bc_isret(bc_op(*J->pc)) &&
702 (!frame_islua(frame) || 804 (!frame_islua(frame) ||
703 (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))))) { 805 (J->parent == 0 && J->exitno == 0 &&
806 !bc_isret(bc_op(J->cur.startins))))) {
704 /* NYI: specialize to frame type and return directly, not via RET*. */ 807 /* NYI: specialize to frame type and return directly, not via RET*. */
705 for (i = 0; i < (ptrdiff_t)rbase; i++) 808 for (i = 0; i < (ptrdiff_t)rbase; i++)
706 J->base[i] = 0; /* Purge dead slots. */ 809 J->base[i] = 0; /* Purge dead slots. */
707 J->maxslot = rbase + (BCReg)gotresults; 810 J->maxslot = rbase + (BCReg)gotresults;
708 rec_stop(J, LJ_TRLINK_RETURN, 0); /* Return to interpreter. */ 811 lj_record_stop(J, LJ_TRLINK_RETURN, 0); /* Return to interpreter. */
709 return; 812 return;
710 } 813 }
711 if (frame_isvarg(frame)) { 814 if (frame_isvarg(frame)) {
712 BCReg cbase = (BCReg)frame_delta(frame); 815 BCReg cbase = (BCReg)frame_delta(frame);
713 if (--J->framedepth < 0) /* NYI: return of vararg func to lower frame. */ 816 if (--J->framedepth < 0) /* NYI: return of vararg func to lower frame. */
714 lj_trace_err(J, LJ_TRERR_NYIRETL); 817 lj_trace_err(J, LJ_TRERR_NYIRETL);
715 lua_assert(J->baseslot > 1); 818 lua_assert(J->baseslot > 1+LJ_FR2);
716 rbase += cbase; 819 rbase += cbase;
717 J->baseslot -= (BCReg)cbase; 820 J->baseslot -= (BCReg)cbase;
718 J->base -= cbase; 821 J->base -= cbase;
@@ -722,27 +825,28 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
722 BCIns callins = *(frame_pc(frame)-1); 825 BCIns callins = *(frame_pc(frame)-1);
723 ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults; 826 ptrdiff_t nresults = bc_b(callins) ? (ptrdiff_t)bc_b(callins)-1 :gotresults;
724 BCReg cbase = bc_a(callins); 827 BCReg cbase = bc_a(callins);
725 GCproto *pt = funcproto(frame_func(frame - (cbase+1))); 828 GCproto *pt = funcproto(frame_func(frame - (cbase+1+LJ_FR2)));
726 if ((pt->flags & PROTO_NOJIT)) 829 if ((pt->flags & PROTO_NOJIT))
727 lj_trace_err(J, LJ_TRERR_CJITOFF); 830 lj_trace_err(J, LJ_TRERR_CJITOFF);
728 if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) { 831 if (J->framedepth == 0 && J->pt && frame == J->L->base - 1) {
729 if (check_downrec_unroll(J, pt)) { 832 if (check_downrec_unroll(J, pt)) {
730 J->maxslot = (BCReg)(rbase + gotresults); 833 J->maxslot = (BCReg)(rbase + gotresults);
731 lj_snap_purge(J); 834 lj_snap_purge(J);
732 rec_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno); /* Down-recursion. */ 835 lj_record_stop(J, LJ_TRLINK_DOWNREC, J->cur.traceno); /* Down-rec. */
733 return; 836 return;
734 } 837 }
735 lj_snap_add(J); 838 lj_snap_add(J);
736 } 839 }
737 for (i = 0; i < nresults; i++) /* Adjust results. */ 840 for (i = 0; i < nresults; i++) /* Adjust results. */
738 J->base[i-1] = i < gotresults ? J->base[rbase+i] : TREF_NIL; 841 J->base[i-1-LJ_FR2] = i < gotresults ? J->base[rbase+i] : TREF_NIL;
739 J->maxslot = cbase+(BCReg)nresults; 842 J->maxslot = cbase+(BCReg)nresults;
740 if (J->framedepth > 0) { /* Return to a frame that is part of the trace. */ 843 if (J->framedepth > 0) { /* Return to a frame that is part of the trace. */
741 J->framedepth--; 844 J->framedepth--;
742 lua_assert(J->baseslot > cbase+1); 845 lua_assert(J->baseslot > cbase+1+LJ_FR2);
743 J->baseslot -= cbase+1; 846 J->baseslot -= cbase+1+LJ_FR2;
744 J->base -= cbase+1; 847 J->base -= cbase+1+LJ_FR2;
745 } else if (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))) { 848 } else if (J->parent == 0 && J->exitno == 0 &&
849 !bc_isret(bc_op(J->cur.startins))) {
746 /* Return to lower frame would leave the loop in a root trace. */ 850 /* Return to lower frame would leave the loop in a root trace. */
747 lj_trace_err(J, LJ_TRERR_LLEAVE); 851 lj_trace_err(J, LJ_TRERR_LLEAVE);
748 } else if (J->needsnap) { /* Tailcalled to ff with side-effects. */ 852 } else if (J->needsnap) { /* Tailcalled to ff with side-effects. */
@@ -750,13 +854,13 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
750 } else { /* Return to lower frame. Guard for the target we return to. */ 854 } else { /* Return to lower frame. Guard for the target we return to. */
751 TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO); 855 TRef trpt = lj_ir_kgc(J, obj2gco(pt), IRT_PROTO);
752 TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame)); 856 TRef trpc = lj_ir_kptr(J, (void *)frame_pc(frame));
753 emitir(IRTG(IR_RETF, IRT_P32), trpt, trpc); 857 emitir(IRTG(IR_RETF, IRT_PGC), trpt, trpc);
754 J->retdepth++; 858 J->retdepth++;
755 J->needsnap = 1; 859 J->needsnap = 1;
756 lua_assert(J->baseslot == 1); 860 lua_assert(J->baseslot == 1+LJ_FR2);
757 /* Shift result slots up and clear the slots of the new frame below. */ 861 /* Shift result slots up and clear the slots of the new frame below. */
758 memmove(J->base + cbase, J->base-1, sizeof(TRef)*nresults); 862 memmove(J->base + cbase, J->base-1-LJ_FR2, sizeof(TRef)*nresults);
759 memset(J->base-1, 0, sizeof(TRef)*(cbase+1)); 863 memset(J->base-1-LJ_FR2, 0, sizeof(TRef)*(cbase+1+LJ_FR2));
760 } 864 }
761 } else if (frame_iscont(frame)) { /* Return to continuation frame. */ 865 } else if (frame_iscont(frame)) { /* Return to continuation frame. */
762 ASMFunction cont = frame_contf(frame); 866 ASMFunction cont = frame_contf(frame);
@@ -765,16 +869,40 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
765 lj_trace_err(J, LJ_TRERR_NYIRETL); 869 lj_trace_err(J, LJ_TRERR_NYIRETL);
766 J->baseslot -= (BCReg)cbase; 870 J->baseslot -= (BCReg)cbase;
767 J->base -= cbase; 871 J->base -= cbase;
768 J->maxslot = cbase-2; 872 J->maxslot = cbase-(2<<LJ_FR2);
769 if (cont == lj_cont_ra) { 873 if (cont == lj_cont_ra) {
770 /* Copy result to destination slot. */ 874 /* Copy result to destination slot. */
771 BCReg dst = bc_a(*(frame_contpc(frame)-1)); 875 BCReg dst = bc_a(*(frame_contpc(frame)-1));
772 J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL; 876 J->base[dst] = gotresults ? J->base[cbase+rbase] : TREF_NIL;
773 if (dst >= J->maxslot) J->maxslot = dst+1; 877 if (dst >= J->maxslot) {
878 J->maxslot = dst+1;
879 }
774 } else if (cont == lj_cont_nop) { 880 } else if (cont == lj_cont_nop) {
775 /* Nothing to do here. */ 881 /* Nothing to do here. */
776 } else if (cont == lj_cont_cat) { 882 } else if (cont == lj_cont_cat) {
777 lua_assert(0); 883 BCReg bslot = bc_b(*(frame_contpc(frame)-1));
884 TRef tr = gotresults ? J->base[cbase+rbase] : TREF_NIL;
885 if (bslot != J->maxslot) { /* Concatenate the remainder. */
886 TValue *b = J->L->base, save; /* Simulate lower frame and result. */
887 J->base[J->maxslot] = tr;
888 copyTV(J->L, &save, b-(2<<LJ_FR2));
889 if (gotresults)
890 copyTV(J->L, b-(2<<LJ_FR2), b+rbase);
891 else
892 setnilV(b-(2<<LJ_FR2));
893 J->L->base = b - cbase;
894 tr = rec_cat(J, bslot, cbase-(2<<LJ_FR2));
895 b = J->L->base + cbase; /* Undo. */
896 J->L->base = b;
897 copyTV(J->L, b-(2<<LJ_FR2), &save);
898 }
899 if (tr) { /* Store final result. */
900 BCReg dst = bc_a(*(frame_contpc(frame)-1));
901 J->base[dst] = tr;
902 if (dst >= J->maxslot) {
903 J->maxslot = dst+1;
904 }
905 } /* Otherwise continue with another __concat call. */
778 } else { 906 } else {
779 /* Result type already specialized. */ 907 /* Result type already specialized. */
780 lua_assert(cont == lj_cont_condf || cont == lj_cont_condt); 908 lua_assert(cont == lj_cont_condf || cont == lj_cont_condt);
@@ -782,7 +910,7 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
782 } else { 910 } else {
783 lj_trace_err(J, LJ_TRERR_NYIRETL); /* NYI: handle return to C frame. */ 911 lj_trace_err(J, LJ_TRERR_NYIRETL); /* NYI: handle return to C frame. */
784 } 912 }
785 lua_assert(J->baseslot >= 1); 913 lua_assert(J->baseslot >= 1+LJ_FR2);
786} 914}
787 915
788/* -- Metamethod handling ------------------------------------------------- */ 916/* -- Metamethod handling ------------------------------------------------- */
@@ -790,19 +918,17 @@ void lj_record_ret(jit_State *J, BCReg rbase, ptrdiff_t gotresults)
790/* Prepare to record call to metamethod. */ 918/* Prepare to record call to metamethod. */
791static BCReg rec_mm_prep(jit_State *J, ASMFunction cont) 919static BCReg rec_mm_prep(jit_State *J, ASMFunction cont)
792{ 920{
793 BCReg s, top = curr_proto(J->L)->framesize; 921 BCReg s, top = cont == lj_cont_cat ? J->maxslot : curr_proto(J->L)->framesize;
794 TRef trcont; 922#if LJ_FR2
795 setcont(&J->L->base[top], cont); 923 J->base[top] = lj_ir_k64(J, IR_KNUM, u64ptr(contptr(cont)));
796#if LJ_64 924 J->base[top+1] = TREF_CONT;
797 trcont = lj_ir_kptr(J, (void *)((int64_t)cont - (int64_t)lj_vm_asm_begin));
798#else 925#else
799 trcont = lj_ir_kptr(J, (void *)cont); 926 J->base[top] = lj_ir_kptr(J, contptr(cont)) | TREF_CONT;
800#endif 927#endif
801 J->base[top] = trcont | TREF_CONT;
802 J->framedepth++; 928 J->framedepth++;
803 for (s = J->maxslot; s < top; s++) 929 for (s = J->maxslot; s < top; s++)
804 J->base[s] = 0; /* Clear frame gap to avoid resurrecting previous refs. */ 930 J->base[s] = 0; /* Clear frame gap to avoid resurrecting previous refs. */
805 return top+1; 931 return top+1+LJ_FR2;
806} 932}
807 933
808/* Record metamethod lookup. */ 934/* Record metamethod lookup. */
@@ -821,7 +947,7 @@ int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
821 cTValue *mo; 947 cTValue *mo;
822 if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) { 948 if (LJ_HASFFI && udtype == UDTYPE_FFI_CLIB) {
823 /* Specialize to the C library namespace object. */ 949 /* Specialize to the C library namespace object. */
824 emitir(IRTG(IR_EQ, IRT_P32), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv))); 950 emitir(IRTG(IR_EQ, IRT_PGC), ix->tab, lj_ir_kptr(J, udataV(&ix->tabv)));
825 } else { 951 } else {
826 /* Specialize to the type of userdata. */ 952 /* Specialize to the type of userdata. */
827 TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE); 953 TRef tr = emitir(IRT(IR_FLOAD, IRT_U8), ix->tab, IRFL_UDATA_UDTYPE);
@@ -850,7 +976,13 @@ int lj_record_mm_lookup(jit_State *J, RecordIndex *ix, MMS mm)
850 } 976 }
851 /* The cdata metatable is treated as immutable. */ 977 /* The cdata metatable is treated as immutable. */
852 if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt; 978 if (LJ_HASFFI && tref_iscdata(ix->tab)) goto immutable_mt;
979#if LJ_GC64
980 /* TODO: fix ARM32 asm_fload(), so we can use this for all archs. */
981 ix->mt = mix.tab = lj_ir_ggfload(J, IRT_TAB,
982 GG_OFS(g.gcroot[GCROOT_BASEMT+itypemap(&ix->tabv)]));
983#else
853 ix->mt = mix.tab = lj_ir_ktab(J, mt); 984 ix->mt = mix.tab = lj_ir_ktab(J, mt);
985#endif
854 goto nocheck; 986 goto nocheck;
855 } 987 }
856 ix->mt = mt ? mix.tab : TREF_NIL; 988 ix->mt = mt ? mix.tab : TREF_NIL;
@@ -877,12 +1009,12 @@ nocheck:
877static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm) 1009static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
878{ 1010{
879 /* Set up metamethod call first to save ix->tab and ix->tabv. */ 1011 /* Set up metamethod call first to save ix->tab and ix->tabv. */
880 BCReg func = rec_mm_prep(J, lj_cont_ra); 1012 BCReg func = rec_mm_prep(J, mm == MM_concat ? lj_cont_cat : lj_cont_ra);
881 TRef *base = J->base + func; 1013 TRef *base = J->base + func;
882 TValue *basev = J->L->base + func; 1014 TValue *basev = J->L->base + func;
883 base[1] = ix->tab; base[2] = ix->key; 1015 base[1+LJ_FR2] = ix->tab; base[2+LJ_FR2] = ix->key;
884 copyTV(J->L, basev+1, &ix->tabv); 1016 copyTV(J->L, basev+1+LJ_FR2, &ix->tabv);
885 copyTV(J->L, basev+2, &ix->keyv); 1017 copyTV(J->L, basev+2+LJ_FR2, &ix->keyv);
886 if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */ 1018 if (!lj_record_mm_lookup(J, ix, mm)) { /* Lookup mm on 1st operand. */
887 if (mm != MM_unm) { 1019 if (mm != MM_unm) {
888 ix->tab = ix->key; 1020 ix->tab = ix->key;
@@ -894,6 +1026,9 @@ static TRef rec_mm_arith(jit_State *J, RecordIndex *ix, MMS mm)
894 } 1026 }
895ok: 1027ok:
896 base[0] = ix->mobj; 1028 base[0] = ix->mobj;
1029#if LJ_FR2
1030 base[1] = 0;
1031#endif
897 copyTV(J->L, basev+0, &ix->mobjv); 1032 copyTV(J->L, basev+0, &ix->mobjv);
898 lj_record_call(J, func, 2); 1033 lj_record_call(J, func, 2);
899 return 0; /* No result yet. */ 1034 return 0; /* No result yet. */
@@ -910,6 +1045,8 @@ static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
910 TRef *base = J->base + func; 1045 TRef *base = J->base + func;
911 TValue *basev = J->L->base + func; 1046 TValue *basev = J->L->base + func;
912 base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv); 1047 base[0] = ix.mobj; copyTV(J->L, basev+0, &ix.mobjv);
1048 base += LJ_FR2;
1049 basev += LJ_FR2;
913 base[1] = tr; copyTV(J->L, basev+1, tv); 1050 base[1] = tr; copyTV(J->L, basev+1, tv);
914#if LJ_52 1051#if LJ_52
915 base[2] = tr; copyTV(J->L, basev+2, tv); 1052 base[2] = tr; copyTV(J->L, basev+2, tv);
@@ -929,10 +1066,10 @@ static TRef rec_mm_len(jit_State *J, TRef tr, TValue *tv)
929static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op) 1066static void rec_mm_callcomp(jit_State *J, RecordIndex *ix, int op)
930{ 1067{
931 BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt); 1068 BCReg func = rec_mm_prep(J, (op&1) ? lj_cont_condf : lj_cont_condt);
932 TRef *base = J->base + func; 1069 TRef *base = J->base + func + LJ_FR2;
933 TValue *tv = J->L->base + func; 1070 TValue *tv = J->L->base + func + LJ_FR2;
934 base[0] = ix->mobj; base[1] = ix->val; base[2] = ix->key; 1071 base[-LJ_FR2] = ix->mobj; base[1] = ix->val; base[2] = ix->key;
935 copyTV(J->L, tv+0, &ix->mobjv); 1072 copyTV(J->L, tv-LJ_FR2, &ix->mobjv);
936 copyTV(J->L, tv+1, &ix->valv); 1073 copyTV(J->L, tv+1, &ix->valv);
937 copyTV(J->L, tv+2, &ix->keyv); 1074 copyTV(J->L, tv+2, &ix->keyv);
938 lj_record_call(J, func, 2); 1075 lj_record_call(J, func, 2);
@@ -1039,6 +1176,72 @@ static void rec_mm_comp_cdata(jit_State *J, RecordIndex *ix, int op, MMS mm)
1039 1176
1040/* -- Indexed access ------------------------------------------------------ */ 1177/* -- Indexed access ------------------------------------------------------ */
1041 1178
1179#ifdef LUAJIT_ENABLE_TABLE_BUMP
1180/* Bump table allocations in bytecode when they grow during recording. */
1181static void rec_idx_bump(jit_State *J, RecordIndex *ix)
1182{
1183 RBCHashEntry *rbc = &J->rbchash[(ix->tab & (RBCHASH_SLOTS-1))];
1184 if (tref_ref(ix->tab) == rbc->ref) {
1185 const BCIns *pc = mref(rbc->pc, const BCIns);
1186 GCtab *tb = tabV(&ix->tabv);
1187 uint32_t nhbits;
1188 IRIns *ir;
1189 if (!tvisnil(&ix->keyv))
1190 (void)lj_tab_set(J->L, tb, &ix->keyv); /* Grow table right now. */
1191 nhbits = tb->hmask > 0 ? lj_fls(tb->hmask)+1 : 0;
1192 ir = IR(tref_ref(ix->tab));
1193 if (ir->o == IR_TNEW) {
1194 uint32_t ah = bc_d(*pc);
1195 uint32_t asize = ah & 0x7ff, hbits = ah >> 11;
1196 if (nhbits > hbits) hbits = nhbits;
1197 if (tb->asize > asize) {
1198 asize = tb->asize <= 0x7ff ? tb->asize : 0x7ff;
1199 }
1200 if ((asize | (hbits<<11)) != ah) { /* Has the size changed? */
1201 /* Patch bytecode, but continue recording (for more patching). */
1202 setbc_d(pc, (asize | (hbits<<11)));
1203 /* Patching TNEW operands is only safe if the trace is aborted. */
1204 ir->op1 = asize; ir->op2 = hbits;
1205 J->retryrec = 1; /* Abort the trace at the end of recording. */
1206 }
1207 } else if (ir->o == IR_TDUP) {
1208 GCtab *tpl = gco2tab(proto_kgc(&gcref(rbc->pt)->pt, ~(ptrdiff_t)bc_d(*pc)));
1209 /* Grow template table, but preserve keys with nil values. */
1210 if ((tb->asize > tpl->asize && (1u << nhbits)-1 == tpl->hmask) ||
1211 (tb->asize == tpl->asize && (1u << nhbits)-1 > tpl->hmask)) {
1212 Node *node = noderef(tpl->node);
1213 uint32_t i, hmask = tpl->hmask, asize;
1214 TValue *array;
1215 for (i = 0; i <= hmask; i++) {
1216 if (!tvisnil(&node[i].key) && tvisnil(&node[i].val))
1217 settabV(J->L, &node[i].val, tpl);
1218 }
1219 if (!tvisnil(&ix->keyv) && tref_isk(ix->key)) {
1220 TValue *o = lj_tab_set(J->L, tpl, &ix->keyv);
1221 if (tvisnil(o)) settabV(J->L, o, tpl);
1222 }
1223 lj_tab_resize(J->L, tpl, tb->asize, nhbits);
1224 node = noderef(tpl->node);
1225 hmask = tpl->hmask;
1226 for (i = 0; i <= hmask; i++) {
1227 /* This is safe, since template tables only hold immutable values. */
1228 if (tvistab(&node[i].val))
1229 setnilV(&node[i].val);
1230 }
1231 /* The shape of the table may have changed. Clean up array part, too. */
1232 asize = tpl->asize;
1233 array = tvref(tpl->array);
1234 for (i = 0; i < asize; i++) {
1235 if (tvistab(&array[i]))
1236 setnilV(&array[i]);
1237 }
1238 J->retryrec = 1; /* Abort the trace at the end of recording. */
1239 }
1240 }
1241 }
1242}
1243#endif
1244
1042/* Record bounds-check. */ 1245/* Record bounds-check. */
1043static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize) 1246static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
1044{ 1247{
@@ -1078,11 +1281,14 @@ static void rec_idx_abc(jit_State *J, TRef asizeref, TRef ikey, uint32_t asize)
1078} 1281}
1079 1282
1080/* Record indexed key lookup. */ 1283/* Record indexed key lookup. */
1081static TRef rec_idx_key(jit_State *J, RecordIndex *ix) 1284static TRef rec_idx_key(jit_State *J, RecordIndex *ix, IRRef *rbref,
1285 IRType1 *rbguard)
1082{ 1286{
1083 TRef key; 1287 TRef key;
1084 GCtab *t = tabV(&ix->tabv); 1288 GCtab *t = tabV(&ix->tabv);
1085 ix->oldv = lj_tab_get(J->L, t, &ix->keyv); /* Lookup previous value. */ 1289 ix->oldv = lj_tab_get(J->L, t, &ix->keyv); /* Lookup previous value. */
1290 *rbref = 0;
1291 rbguard->irt = 0;
1086 1292
1087 /* Integer keys are looked up in the array part first. */ 1293 /* Integer keys are looked up in the array part first. */
1088 key = ix->key; 1294 key = ix->key;
@@ -1096,8 +1302,8 @@ static TRef rec_idx_key(jit_State *J, RecordIndex *ix)
1096 if ((MSize)k < t->asize) { /* Currently an array key? */ 1302 if ((MSize)k < t->asize) { /* Currently an array key? */
1097 TRef arrayref; 1303 TRef arrayref;
1098 rec_idx_abc(J, asizeref, ikey, t->asize); 1304 rec_idx_abc(J, asizeref, ikey, t->asize);
1099 arrayref = emitir(IRT(IR_FLOAD, IRT_P32), ix->tab, IRFL_TAB_ARRAY); 1305 arrayref = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_ARRAY);
1100 return emitir(IRT(IR_AREF, IRT_P32), arrayref, ikey); 1306 return emitir(IRT(IR_AREF, IRT_PGC), arrayref, ikey);
1101 } else { /* Currently not in array (may be an array extension)? */ 1307 } else { /* Currently not in array (may be an array extension)? */
1102 emitir(IRTGI(IR_ULE), asizeref, ikey); /* Inv. bounds check. */ 1308 emitir(IRTGI(IR_ULE), asizeref, ikey); /* Inv. bounds check. */
1103 if (k == 0 && tref_isk(key)) 1309 if (k == 0 && tref_isk(key))
@@ -1132,16 +1338,18 @@ static TRef rec_idx_key(jit_State *J, RecordIndex *ix)
1132 MSize hslot = (MSize)((char *)ix->oldv - (char *)&noderef(t->node)[0].val); 1338 MSize hslot = (MSize)((char *)ix->oldv - (char *)&noderef(t->node)[0].val);
1133 if (t->hmask > 0 && hslot <= t->hmask*(MSize)sizeof(Node) && 1339 if (t->hmask > 0 && hslot <= t->hmask*(MSize)sizeof(Node) &&
1134 hslot <= 65535*(MSize)sizeof(Node)) { 1340 hslot <= 65535*(MSize)sizeof(Node)) {
1135 TRef node, kslot; 1341 TRef node, kslot, hm;
1136 TRef hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK); 1342 *rbref = J->cur.nins; /* Mark possible rollback point. */
1343 *rbguard = J->guardemit;
1344 hm = emitir(IRTI(IR_FLOAD), ix->tab, IRFL_TAB_HMASK);
1137 emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask)); 1345 emitir(IRTGI(IR_EQ), hm, lj_ir_kint(J, (int32_t)t->hmask));
1138 node = emitir(IRT(IR_FLOAD, IRT_P32), ix->tab, IRFL_TAB_NODE); 1346 node = emitir(IRT(IR_FLOAD, IRT_PGC), ix->tab, IRFL_TAB_NODE);
1139 kslot = lj_ir_kslot(J, key, hslot / sizeof(Node)); 1347 kslot = lj_ir_kslot(J, key, hslot / sizeof(Node));
1140 return emitir(IRTG(IR_HREFK, IRT_P32), node, kslot); 1348 return emitir(IRTG(IR_HREFK, IRT_PGC), node, kslot);
1141 } 1349 }
1142 } 1350 }
1143 /* Fall back to a regular hash lookup. */ 1351 /* Fall back to a regular hash lookup. */
1144 return emitir(IRT(IR_HREF, IRT_P32), ix->tab, key); 1352 return emitir(IRT(IR_HREF, IRT_PGC), ix->tab, key);
1145} 1353}
1146 1354
1147/* Determine whether a key is NOT one of the fast metamethod names. */ 1355/* Determine whether a key is NOT one of the fast metamethod names. */
@@ -1166,6 +1374,8 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1166{ 1374{
1167 TRef xref; 1375 TRef xref;
1168 IROp xrefop, loadop; 1376 IROp xrefop, loadop;
1377 IRRef rbref;
1378 IRType1 rbguard;
1169 cTValue *oldv; 1379 cTValue *oldv;
1170 1380
1171 while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */ 1381 while (!tref_istab(ix->tab)) { /* Handle non-table lookup. */
@@ -1176,10 +1386,10 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1176 handlemm: 1386 handlemm:
1177 if (tref_isfunc(ix->mobj)) { /* Handle metamethod call. */ 1387 if (tref_isfunc(ix->mobj)) { /* Handle metamethod call. */
1178 BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra); 1388 BCReg func = rec_mm_prep(J, ix->val ? lj_cont_nop : lj_cont_ra);
1179 TRef *base = J->base + func; 1389 TRef *base = J->base + func + LJ_FR2;
1180 TValue *tv = J->L->base + func; 1390 TValue *tv = J->L->base + func + LJ_FR2;
1181 base[0] = ix->mobj; base[1] = ix->tab; base[2] = ix->key; 1391 base[-LJ_FR2] = ix->mobj; base[1] = ix->tab; base[2] = ix->key;
1182 setfuncV(J->L, tv+0, funcV(&ix->mobjv)); 1392 setfuncV(J->L, tv-LJ_FR2, funcV(&ix->mobjv));
1183 copyTV(J->L, tv+1, &ix->tabv); 1393 copyTV(J->L, tv+1, &ix->tabv);
1184 copyTV(J->L, tv+2, &ix->keyv); 1394 copyTV(J->L, tv+2, &ix->keyv);
1185 if (ix->val) { 1395 if (ix->val) {
@@ -1211,7 +1421,7 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1211 } 1421 }
1212 1422
1213 /* Record the key lookup. */ 1423 /* Record the key lookup. */
1214 xref = rec_idx_key(J, ix); 1424 xref = rec_idx_key(J, ix, &rbref, &rbguard);
1215 xrefop = IR(tref_ref(xref))->o; 1425 xrefop = IR(tref_ref(xref))->o;
1216 loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD; 1426 loadop = xrefop == IR_AREF ? IR_ALOAD : IR_HLOAD;
1217 /* The lj_meta_tset() inconsistency is gone, but better play safe. */ 1427 /* The lj_meta_tset() inconsistency is gone, but better play safe. */
@@ -1221,11 +1431,15 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1221 IRType t = itype2irt(oldv); 1431 IRType t = itype2irt(oldv);
1222 TRef res; 1432 TRef res;
1223 if (oldv == niltvg(J2G(J))) { 1433 if (oldv == niltvg(J2G(J))) {
1224 emitir(IRTG(IR_EQ, IRT_P32), xref, lj_ir_kkptr(J, niltvg(J2G(J)))); 1434 emitir(IRTG(IR_EQ, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1225 res = TREF_NIL; 1435 res = TREF_NIL;
1226 } else { 1436 } else {
1227 res = emitir(IRTG(loadop, t), xref, 0); 1437 res = emitir(IRTG(loadop, t), xref, 0);
1228 } 1438 }
1439 if (tref_ref(res) < rbref) { /* HREFK + load forwarded? */
1440 lj_ir_rollback(J, rbref); /* Rollback to eliminate hmask guard. */
1441 J->guardemit = rbguard;
1442 }
1229 if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index)) 1443 if (t == IRT_NIL && ix->idxchain && lj_record_mm_lookup(J, ix, MM_index))
1230 goto handlemm; 1444 goto handlemm;
1231 if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitives. */ 1445 if (irtype_ispri(t)) res = TREF_PRI(t); /* Canonicalize primitives. */
@@ -1233,6 +1447,10 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1233 } else { /* Indexed store. */ 1447 } else { /* Indexed store. */
1234 GCtab *mt = tabref(tabV(&ix->tabv)->metatable); 1448 GCtab *mt = tabref(tabV(&ix->tabv)->metatable);
1235 int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val); 1449 int keybarrier = tref_isgcv(ix->key) && !tref_isnil(ix->val);
1450 if (tref_ref(xref) < rbref) { /* HREFK forwarded? */
1451 lj_ir_rollback(J, rbref); /* Rollback to eliminate hmask guard. */
1452 J->guardemit = rbguard;
1453 }
1236 if (tvisnil(oldv)) { /* Previous value was nil? */ 1454 if (tvisnil(oldv)) { /* Previous value was nil? */
1237 /* Need to duplicate the hasmm check for the early guards. */ 1455 /* Need to duplicate the hasmm check for the early guards. */
1238 int hasmm = 0; 1456 int hasmm = 0;
@@ -1243,7 +1461,7 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1243 if (hasmm) 1461 if (hasmm)
1244 emitir(IRTG(loadop, IRT_NIL), xref, 0); /* Guard for nil value. */ 1462 emitir(IRTG(loadop, IRT_NIL), xref, 0); /* Guard for nil value. */
1245 else if (xrefop == IR_HREF) 1463 else if (xrefop == IR_HREF)
1246 emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_P32), 1464 emitir(IRTG(oldv == niltvg(J2G(J)) ? IR_EQ : IR_NE, IRT_PGC),
1247 xref, lj_ir_kkptr(J, niltvg(J2G(J)))); 1465 xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1248 if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) { 1466 if (ix->idxchain && lj_record_mm_lookup(J, ix, MM_newindex)) {
1249 lua_assert(hasmm); 1467 lua_assert(hasmm);
@@ -1254,13 +1472,17 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1254 TRef key = ix->key; 1472 TRef key = ix->key;
1255 if (tref_isinteger(key)) /* NEWREF needs a TValue as a key. */ 1473 if (tref_isinteger(key)) /* NEWREF needs a TValue as a key. */
1256 key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT); 1474 key = emitir(IRTN(IR_CONV), key, IRCONV_NUM_INT);
1257 xref = emitir(IRT(IR_NEWREF, IRT_P32), ix->tab, key); 1475 xref = emitir(IRT(IR_NEWREF, IRT_PGC), ix->tab, key);
1258 keybarrier = 0; /* NEWREF already takes care of the key barrier. */ 1476 keybarrier = 0; /* NEWREF already takes care of the key barrier. */
1477#ifdef LUAJIT_ENABLE_TABLE_BUMP
1478 if ((J->flags & JIT_F_OPT_SINK)) /* Avoid a separate flag. */
1479 rec_idx_bump(J, ix);
1480#endif
1259 } 1481 }
1260 } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) { 1482 } else if (!lj_opt_fwd_wasnonnil(J, loadop, tref_ref(xref))) {
1261 /* Cannot derive that the previous value was non-nil, must do checks. */ 1483 /* Cannot derive that the previous value was non-nil, must do checks. */
1262 if (xrefop == IR_HREF) /* Guard against store to niltv. */ 1484 if (xrefop == IR_HREF) /* Guard against store to niltv. */
1263 emitir(IRTG(IR_NE, IRT_P32), xref, lj_ir_kkptr(J, niltvg(J2G(J)))); 1485 emitir(IRTG(IR_NE, IRT_PGC), xref, lj_ir_kkptr(J, niltvg(J2G(J))));
1264 if (ix->idxchain) { /* Metamethod lookup required? */ 1486 if (ix->idxchain) { /* Metamethod lookup required? */
1265 /* A check for NULL metatable is cheaper (hoistable) than a load. */ 1487 /* A check for NULL metatable is cheaper (hoistable) than a load. */
1266 if (!mt) { 1488 if (!mt) {
@@ -1282,7 +1504,7 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1282 emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0); 1504 emitir(IRT(IR_TBAR, IRT_NIL), ix->tab, 0);
1283 /* Invalidate neg. metamethod cache for stores with certain string keys. */ 1505 /* Invalidate neg. metamethod cache for stores with certain string keys. */
1284 if (!nommstr(J, ix->key)) { 1506 if (!nommstr(J, ix->key)) {
1285 TRef fref = emitir(IRT(IR_FREF, IRT_P32), ix->tab, IRFL_TAB_NOMM); 1507 TRef fref = emitir(IRT(IR_FREF, IRT_PGC), ix->tab, IRFL_TAB_NOMM);
1286 emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0)); 1508 emitir(IRT(IR_FSTORE, IRT_U8), fref, lj_ir_kint(J, 0));
1287 } 1509 }
1288 J->needsnap = 1; 1510 J->needsnap = 1;
@@ -1290,6 +1512,31 @@ TRef lj_record_idx(jit_State *J, RecordIndex *ix)
1290 } 1512 }
1291} 1513}
1292 1514
1515static void rec_tsetm(jit_State *J, BCReg ra, BCReg rn, int32_t i)
1516{
1517 RecordIndex ix;
1518 cTValue *basev = J->L->base;
1519 GCtab *t = tabV(&basev[ra-1]);
1520 settabV(J->L, &ix.tabv, t);
1521 ix.tab = getslot(J, ra-1);
1522 ix.idxchain = 0;
1523#ifdef LUAJIT_ENABLE_TABLE_BUMP
1524 if ((J->flags & JIT_F_OPT_SINK)) {
1525 if (t->asize < i+rn-ra)
1526 lj_tab_reasize(J->L, t, i+rn-ra);
1527 setnilV(&ix.keyv);
1528 rec_idx_bump(J, &ix);
1529 }
1530#endif
1531 for (; ra < rn; i++, ra++) {
1532 setintV(&ix.keyv, i);
1533 ix.key = lj_ir_kint(J, i);
1534 copyTV(J->L, &ix.valv, &basev[ra]);
1535 ix.val = getslot(J, ra);
1536 lj_record_idx(J, &ix);
1537 }
1538}
1539
1293/* -- Upvalue access ------------------------------------------------------ */ 1540/* -- Upvalue access ------------------------------------------------------ */
1294 1541
1295/* Check whether upvalue is immutable and ok to constify. */ 1542/* Check whether upvalue is immutable and ok to constify. */
@@ -1332,7 +1579,11 @@ static TRef rec_upvalue(jit_State *J, uint32_t uv, TRef val)
1332 goto noconstify; 1579 goto noconstify;
1333 kfunc = lj_ir_kfunc(J, J->fn); 1580 kfunc = lj_ir_kfunc(J, J->fn);
1334 emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc); 1581 emitir(IRTG(IR_EQ, IRT_FUNC), fn, kfunc);
1335 J->base[-1] = TREF_FRAME | kfunc; 1582#if LJ_FR2
1583 J->base[-2] = kfunc;
1584#else
1585 J->base[-1] = kfunc | TREF_FRAME;
1586#endif
1336 fn = kfunc; 1587 fn = kfunc;
1337 } 1588 }
1338 tr = lj_record_constify(J, uvval(uvp)); 1589 tr = lj_record_constify(J, uvval(uvp));
@@ -1343,16 +1594,16 @@ noconstify:
1343 /* Note: this effectively limits LJ_MAX_UPVAL to 127. */ 1594 /* Note: this effectively limits LJ_MAX_UPVAL to 127. */
1344 uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff); 1595 uv = (uv << 8) | (hashrot(uvp->dhash, uvp->dhash + HASH_BIAS) & 0xff);
1345 if (!uvp->closed) { 1596 if (!uvp->closed) {
1346 uref = tref_ref(emitir(IRTG(IR_UREFO, IRT_P32), fn, uv)); 1597 uref = tref_ref(emitir(IRTG(IR_UREFO, IRT_PGC), fn, uv));
1347 /* In current stack? */ 1598 /* In current stack? */
1348 if (uvval(uvp) >= tvref(J->L->stack) && 1599 if (uvval(uvp) >= tvref(J->L->stack) &&
1349 uvval(uvp) < tvref(J->L->maxstack)) { 1600 uvval(uvp) < tvref(J->L->maxstack)) {
1350 int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot)); 1601 int32_t slot = (int32_t)(uvval(uvp) - (J->L->base - J->baseslot));
1351 if (slot >= 0) { /* Aliases an SSA slot? */ 1602 if (slot >= 0) { /* Aliases an SSA slot? */
1352 emitir(IRTG(IR_EQ, IRT_P32), 1603 emitir(IRTG(IR_EQ, IRT_PGC),
1353 REF_BASE, 1604 REF_BASE,
1354 emitir(IRT(IR_ADD, IRT_P32), uref, 1605 emitir(IRT(IR_ADD, IRT_PGC), uref,
1355 lj_ir_kint(J, (slot - 1) * -8))); 1606 lj_ir_kint(J, (slot - 1 - LJ_FR2) * -8)));
1356 slot -= (int32_t)J->baseslot; /* Note: slot number may be negative! */ 1607 slot -= (int32_t)J->baseslot; /* Note: slot number may be negative! */
1357 if (val == 0) { 1608 if (val == 0) {
1358 return getslot(J, slot); 1609 return getslot(J, slot);
@@ -1363,12 +1614,12 @@ noconstify:
1363 } 1614 }
1364 } 1615 }
1365 } 1616 }
1366 emitir(IRTG(IR_UGT, IRT_P32), 1617 emitir(IRTG(IR_UGT, IRT_PGC),
1367 emitir(IRT(IR_SUB, IRT_P32), uref, REF_BASE), 1618 emitir(IRT(IR_SUB, IRT_PGC), uref, REF_BASE),
1368 lj_ir_kint(J, (J->baseslot + J->maxslot) * 8)); 1619 lj_ir_kint(J, (J->baseslot + J->maxslot) * 8));
1369 } else { 1620 } else {
1370 needbarrier = 1; 1621 needbarrier = 1;
1371 uref = tref_ref(emitir(IRTG(IR_UREFC, IRT_P32), fn, uv)); 1622 uref = tref_ref(emitir(IRTG(IR_UREFC, IRT_PGC), fn, uv));
1372 } 1623 }
1373 if (val == 0) { /* Upvalue load */ 1624 if (val == 0) { /* Upvalue load */
1374 IRType t = itype2irt(uvval(uvp)); 1625 IRType t = itype2irt(uvval(uvp));
@@ -1407,9 +1658,9 @@ static void check_call_unroll(jit_State *J, TraceNo lnk)
1407 if (count + J->tailcalled > J->param[JIT_P_recunroll]) { 1658 if (count + J->tailcalled > J->param[JIT_P_recunroll]) {
1408 J->pc++; 1659 J->pc++;
1409 if (J->framedepth + J->retdepth == 0) 1660 if (J->framedepth + J->retdepth == 0)
1410 rec_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Tail-recursion. */ 1661 lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Tail-rec. */
1411 else 1662 else
1412 rec_stop(J, LJ_TRLINK_UPREC, J->cur.traceno); /* Up-recursion. */ 1663 lj_record_stop(J, LJ_TRLINK_UPREC, J->cur.traceno); /* Up-recursion. */
1413 } 1664 }
1414 } else { 1665 } else {
1415 if (count > J->param[JIT_P_callunroll]) { 1666 if (count > J->param[JIT_P_callunroll]) {
@@ -1443,11 +1694,14 @@ static void rec_func_setup(jit_State *J)
1443static void rec_func_vararg(jit_State *J) 1694static void rec_func_vararg(jit_State *J)
1444{ 1695{
1445 GCproto *pt = J->pt; 1696 GCproto *pt = J->pt;
1446 BCReg s, fixargs, vframe = J->maxslot+1; 1697 BCReg s, fixargs, vframe = J->maxslot+1+LJ_FR2;
1447 lua_assert((pt->flags & PROTO_VARARG)); 1698 lua_assert((pt->flags & PROTO_VARARG));
1448 if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS) 1699 if (J->baseslot + vframe + pt->framesize >= LJ_MAX_JSLOTS)
1449 lj_trace_err(J, LJ_TRERR_STACKOV); 1700 lj_trace_err(J, LJ_TRERR_STACKOV);
1450 J->base[vframe-1] = J->base[-1]; /* Copy function up. */ 1701 J->base[vframe-1-LJ_FR2] = J->base[-1-LJ_FR2]; /* Copy function up. */
1702#if LJ_FR2
1703 J->base[vframe-1] = TREF_FRAME;
1704#endif
1451 /* Copy fixarg slots up and set their original slots to nil. */ 1705 /* Copy fixarg slots up and set their original slots to nil. */
1452 fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot; 1706 fixargs = pt->numparams < J->maxslot ? pt->numparams : J->maxslot;
1453 for (s = 0; s < fixargs; s++) { 1707 for (s = 0; s < fixargs; s++) {
@@ -1483,9 +1737,9 @@ static void rec_func_jit(jit_State *J, TraceNo lnk)
1483 } 1737 }
1484 J->instunroll = 0; /* Cannot continue across a compiled function. */ 1738 J->instunroll = 0; /* Cannot continue across a compiled function. */
1485 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0) 1739 if (J->pc == J->startpc && J->framedepth + J->retdepth == 0)
1486 rec_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Extra tail-recursion. */ 1740 lj_record_stop(J, LJ_TRLINK_TAILREC, J->cur.traceno); /* Extra tail-rec. */
1487 else 1741 else
1488 rec_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the function. */ 1742 lj_record_stop(J, LJ_TRLINK_ROOT, lnk); /* Link to the function. */
1489} 1743}
1490 1744
1491/* -- Vararg handling ----------------------------------------------------- */ 1745/* -- Vararg handling ----------------------------------------------------- */
@@ -1509,8 +1763,10 @@ static int select_detect(jit_State *J)
1509static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults) 1763static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
1510{ 1764{
1511 int32_t numparams = J->pt->numparams; 1765 int32_t numparams = J->pt->numparams;
1512 ptrdiff_t nvararg = frame_delta(J->L->base-1) - numparams - 1; 1766 ptrdiff_t nvararg = frame_delta(J->L->base-1) - numparams - 1 - LJ_FR2;
1513 lua_assert(frame_isvarg(J->L->base-1)); 1767 lua_assert(frame_isvarg(J->L->base-1));
1768 if (LJ_FR2 && dst > J->maxslot)
1769 J->base[dst-1] = 0; /* Prevent resurrection of unrelated slot. */
1514 if (J->framedepth > 0) { /* Simple case: varargs defined on-trace. */ 1770 if (J->framedepth > 0) { /* Simple case: varargs defined on-trace. */
1515 ptrdiff_t i; 1771 ptrdiff_t i;
1516 if (nvararg < 0) nvararg = 0; 1772 if (nvararg < 0) nvararg = 0;
@@ -1521,10 +1777,10 @@ static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
1521 J->maxslot = dst + (BCReg)nresults; 1777 J->maxslot = dst + (BCReg)nresults;
1522 } 1778 }
1523 for (i = 0; i < nresults; i++) 1779 for (i = 0; i < nresults; i++)
1524 J->base[dst+i] = i < nvararg ? getslot(J, i - nvararg - 1) : TREF_NIL; 1780 J->base[dst+i] = i < nvararg ? getslot(J, i - nvararg - 1 - LJ_FR2) : TREF_NIL;
1525 } else { /* Unknown number of varargs passed to trace. */ 1781 } else { /* Unknown number of varargs passed to trace. */
1526 TRef fr = emitir(IRTI(IR_SLOAD), 0, IRSLOAD_READONLY|IRSLOAD_FRAME); 1782 TRef fr = emitir(IRTI(IR_SLOAD), LJ_FR2, IRSLOAD_READONLY|IRSLOAD_FRAME);
1527 int32_t frofs = 8*(1+numparams)+FRAME_VARG; 1783 int32_t frofs = 8*(1+LJ_FR2+numparams)+FRAME_VARG;
1528 if (nresults >= 0) { /* Known fixed number of results. */ 1784 if (nresults >= 0) { /* Known fixed number of results. */
1529 ptrdiff_t i; 1785 ptrdiff_t i;
1530 if (nvararg > 0) { 1786 if (nvararg > 0) {
@@ -1533,12 +1789,13 @@ static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
1533 if (nvararg >= nresults) 1789 if (nvararg >= nresults)
1534 emitir(IRTGI(IR_GE), fr, lj_ir_kint(J, frofs+8*(int32_t)nresults)); 1790 emitir(IRTGI(IR_GE), fr, lj_ir_kint(J, frofs+8*(int32_t)nresults));
1535 else 1791 else
1536 emitir(IRTGI(IR_EQ), fr, lj_ir_kint(J, frame_ftsz(J->L->base-1))); 1792 emitir(IRTGI(IR_EQ), fr,
1537 vbase = emitir(IRTI(IR_SUB), REF_BASE, fr); 1793 lj_ir_kint(J, (int32_t)frame_ftsz(J->L->base-1)));
1538 vbase = emitir(IRT(IR_ADD, IRT_P32), vbase, lj_ir_kint(J, frofs-8)); 1794 vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
1795 vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase, lj_ir_kint(J, frofs-8));
1539 for (i = 0; i < nload; i++) { 1796 for (i = 0; i < nload; i++) {
1540 IRType t = itype2irt(&J->L->base[i-1-nvararg]); 1797 IRType t = itype2irt(&J->L->base[i-1-LJ_FR2-nvararg]);
1541 TRef aref = emitir(IRT(IR_AREF, IRT_P32), 1798 TRef aref = emitir(IRT(IR_AREF, IRT_PGC),
1542 vbase, lj_ir_kint(J, (int32_t)i)); 1799 vbase, lj_ir_kint(J, (int32_t)i));
1543 TRef tr = emitir(IRTG(IR_VLOAD, t), aref, 0); 1800 TRef tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
1544 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */ 1801 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */
@@ -1584,15 +1841,16 @@ static void rec_varg(jit_State *J, BCReg dst, ptrdiff_t nresults)
1584 } 1841 }
1585 if (idx != 0 && idx <= nvararg) { 1842 if (idx != 0 && idx <= nvararg) {
1586 IRType t; 1843 IRType t;
1587 TRef aref, vbase = emitir(IRTI(IR_SUB), REF_BASE, fr); 1844 TRef aref, vbase = emitir(IRT(IR_SUB, IRT_IGC), REF_BASE, fr);
1588 vbase = emitir(IRT(IR_ADD, IRT_P32), vbase, lj_ir_kint(J, frofs-8)); 1845 vbase = emitir(IRT(IR_ADD, IRT_PGC), vbase,
1589 t = itype2irt(&J->L->base[idx-2-nvararg]); 1846 lj_ir_kint(J, frofs-(8<<LJ_FR2)));
1590 aref = emitir(IRT(IR_AREF, IRT_P32), vbase, tridx); 1847 t = itype2irt(&J->L->base[idx-2-LJ_FR2-nvararg]);
1848 aref = emitir(IRT(IR_AREF, IRT_PGC), vbase, tridx);
1591 tr = emitir(IRTG(IR_VLOAD, t), aref, 0); 1849 tr = emitir(IRTG(IR_VLOAD, t), aref, 0);
1592 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */ 1850 if (irtype_ispri(t)) tr = TREF_PRI(t); /* Canonicalize primitives. */
1593 } 1851 }
1594 J->base[dst-2] = tr; 1852 J->base[dst-2-LJ_FR2] = tr;
1595 J->maxslot = dst-1; 1853 J->maxslot = dst-1-LJ_FR2;
1596 J->bcskip = 2; /* Skip CALLM + select. */ 1854 J->bcskip = 2; /* Skip CALLM + select. */
1597 } else { 1855 } else {
1598 nyivarg: 1856 nyivarg:
@@ -1608,8 +1866,63 @@ static TRef rec_tnew(jit_State *J, uint32_t ah)
1608{ 1866{
1609 uint32_t asize = ah & 0x7ff; 1867 uint32_t asize = ah & 0x7ff;
1610 uint32_t hbits = ah >> 11; 1868 uint32_t hbits = ah >> 11;
1869 TRef tr;
1611 if (asize == 0x7ff) asize = 0x801; 1870 if (asize == 0x7ff) asize = 0x801;
1612 return emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits); 1871 tr = emitir(IRTG(IR_TNEW, IRT_TAB), asize, hbits);
1872#ifdef LUAJIT_ENABLE_TABLE_BUMP
1873 J->rbchash[(tr & (RBCHASH_SLOTS-1))].ref = tref_ref(tr);
1874 setmref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pc, J->pc);
1875 setgcref(J->rbchash[(tr & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
1876#endif
1877 return tr;
1878}
1879
1880/* -- Concatenation ------------------------------------------------------- */
1881
1882static TRef rec_cat(jit_State *J, BCReg baseslot, BCReg topslot)
1883{
1884 TRef *top = &J->base[topslot];
1885 TValue savetv[5];
1886 BCReg s;
1887 RecordIndex ix;
1888 lua_assert(baseslot < topslot);
1889 for (s = baseslot; s <= topslot; s++)
1890 (void)getslot(J, s); /* Ensure all arguments have a reference. */
1891 if (tref_isnumber_str(top[0]) && tref_isnumber_str(top[-1])) {
1892 TRef tr, hdr, *trp, *xbase, *base = &J->base[baseslot];
1893 /* First convert numbers to strings. */
1894 for (trp = top; trp >= base; trp--) {
1895 if (tref_isnumber(*trp))
1896 *trp = emitir(IRT(IR_TOSTR, IRT_STR), *trp,
1897 tref_isnum(*trp) ? IRTOSTR_NUM : IRTOSTR_INT);
1898 else if (!tref_isstr(*trp))
1899 break;
1900 }
1901 xbase = ++trp;
1902 tr = hdr = emitir(IRT(IR_BUFHDR, IRT_PGC),
1903 lj_ir_kptr(J, &J2G(J)->tmpbuf), IRBUFHDR_RESET);
1904 do {
1905 tr = emitir(IRT(IR_BUFPUT, IRT_PGC), tr, *trp++);
1906 } while (trp <= top);
1907 tr = emitir(IRT(IR_BUFSTR, IRT_STR), tr, hdr);
1908 J->maxslot = (BCReg)(xbase - J->base);
1909 if (xbase == base) return tr; /* Return simple concatenation result. */
1910 /* Pass partial result. */
1911 topslot = J->maxslot--;
1912 *xbase = tr;
1913 top = xbase;
1914 setstrV(J->L, &ix.keyv, &J2G(J)->strempty); /* Simulate string result. */
1915 } else {
1916 J->maxslot = topslot-1;
1917 copyTV(J->L, &ix.keyv, &J->L->base[topslot]);
1918 }
1919 copyTV(J->L, &ix.tabv, &J->L->base[topslot-1]);
1920 ix.tab = top[-1];
1921 ix.key = top[0];
1922 memcpy(savetv, &J->L->base[topslot-1], sizeof(savetv)); /* Save slots. */
1923 rec_mm_arith(J, &ix, MM_concat); /* Call __concat metamethod. */
1924 memcpy(&J->L->base[topslot-1], savetv, sizeof(savetv)); /* Restore slots. */
1925 return 0; /* No result yet. */
1613} 1926}
1614 1927
1615/* -- Record bytecode ops ------------------------------------------------- */ 1928/* -- Record bytecode ops ------------------------------------------------- */
@@ -1630,7 +1943,15 @@ static void rec_comp_fixup(jit_State *J, const BCIns *pc, int cond)
1630 const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0); 1943 const BCIns *npc = pc + 2 + (cond ? bc_j(jmpins) : 0);
1631 SnapShot *snap = &J->cur.snap[J->cur.nsnap-1]; 1944 SnapShot *snap = &J->cur.snap[J->cur.nsnap-1];
1632 /* Set PC to opposite target to avoid re-recording the comp. in side trace. */ 1945 /* Set PC to opposite target to avoid re-recording the comp. in side trace. */
1946#if LJ_FR2
1947 SnapEntry *flink = &J->cur.snapmap[snap->mapofs + snap->nent];
1948 uint64_t pcbase;
1949 memcpy(&pcbase, flink, sizeof(uint64_t));
1950 pcbase = (pcbase & 0xff) | (u64ptr(npc) << 8);
1951 memcpy(flink, &pcbase, sizeof(uint64_t));
1952#else
1633 J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc); 1953 J->cur.snapmap[snap->mapofs + snap->nent] = SNAP_MKPC(npc);
1954#endif
1634 J->needsnap = 1; 1955 J->needsnap = 1;
1635 if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins); 1956 if (bc_a(jmpins) < J->maxslot) J->maxslot = bc_a(jmpins);
1636 lj_snap_shrink(J); /* Shrink last snapshot if possible. */ 1957 lj_snap_shrink(J); /* Shrink last snapshot if possible. */
@@ -1650,7 +1971,7 @@ void lj_record_ins(jit_State *J)
1650 if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) { 1971 if (LJ_UNLIKELY(J->postproc != LJ_POST_NONE)) {
1651 switch (J->postproc) { 1972 switch (J->postproc) {
1652 case LJ_POST_FIXCOMP: /* Fixup comparison. */ 1973 case LJ_POST_FIXCOMP: /* Fixup comparison. */
1653 pc = frame_pc(&J2G(J)->tmptv); 1974 pc = (const BCIns *)(uintptr_t)J2G(J)->tmptv.u64;
1654 rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1))); 1975 rec_comp_fixup(J, pc, (!tvistruecond(&J2G(J)->tmptv2) ^ (bc_op(*pc)&1)));
1655 /* fallthrough */ 1976 /* fallthrough */
1656 case LJ_POST_FIXGUARD: /* Fixup and emit pending guard. */ 1977 case LJ_POST_FIXGUARD: /* Fixup and emit pending guard. */
@@ -1718,6 +2039,10 @@ void lj_record_ins(jit_State *J)
1718 rec_check_ir(J); 2039 rec_check_ir(J);
1719#endif 2040#endif
1720 2041
2042#if LJ_HASPROFILE
2043 rec_profile_ins(J, pc);
2044#endif
2045
1721 /* Keep a copy of the runtime values of var/num/str operands. */ 2046 /* Keep a copy of the runtime values of var/num/str operands. */
1722#define rav (&ix.valv) 2047#define rav (&ix.valv)
1723#define rbv (&ix.tabv) 2048#define rbv (&ix.tabv)
@@ -1744,7 +2069,7 @@ void lj_record_ins(jit_State *J)
1744 switch (bcmode_c(op)) { 2069 switch (bcmode_c(op)) {
1745 case BCMvar: 2070 case BCMvar:
1746 copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break; 2071 copyTV(J->L, rcv, &lbase[rc]); ix.key = rc = getslot(J, rc); break;
1747 case BCMpri: setitype(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break; 2072 case BCMpri: setpriV(rcv, ~rc); ix.key = rc = TREF_PRI(IRT_NIL+rc); break;
1748 case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc); 2073 case BCMnum: { cTValue *tv = proto_knumtv(J->pt, rc);
1749 copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) : 2074 copyTV(J->L, rcv, tv); ix.key = rc = tvisint(tv) ? lj_ir_kint(J, intV(tv)) :
1750 lj_ir_knumint(J, numV(tv)); } break; 2075 lj_ir_knumint(J, numV(tv)); } break;
@@ -1839,6 +2164,18 @@ void lj_record_ins(jit_State *J)
1839 J->maxslot = bc_a(pc[1]); /* Shrink used slots. */ 2164 J->maxslot = bc_a(pc[1]); /* Shrink used slots. */
1840 break; 2165 break;
1841 2166
2167 case BC_ISTYPE: case BC_ISNUM:
2168 /* These coercions need to correspond with lj_meta_istype(). */
2169 if (LJ_DUALNUM && rc == ~LJ_TNUMX+1)
2170 ra = lj_opt_narrow_toint(J, ra);
2171 else if (rc == ~LJ_TNUMX+2)
2172 ra = lj_ir_tonum(J, ra);
2173 else if (rc == ~LJ_TSTR+1)
2174 ra = lj_ir_tostr(J, ra);
2175 /* else: type specialization suffices. */
2176 J->base[bc_a(ins)] = ra;
2177 break;
2178
1842 /* -- Unary ops --------------------------------------------------------- */ 2179 /* -- Unary ops --------------------------------------------------------- */
1843 2180
1844 case BC_NOT: 2181 case BC_NOT:
@@ -1902,11 +2239,23 @@ void lj_record_ins(jit_State *J)
1902 rc = rec_mm_arith(J, &ix, MM_pow); 2239 rc = rec_mm_arith(J, &ix, MM_pow);
1903 break; 2240 break;
1904 2241
2242 /* -- Miscellaneous ops ------------------------------------------------- */
2243
2244 case BC_CAT:
2245 rc = rec_cat(J, rb, rc);
2246 break;
2247
1905 /* -- Constant and move ops --------------------------------------------- */ 2248 /* -- Constant and move ops --------------------------------------------- */
1906 2249
1907 case BC_MOV: 2250 case BC_MOV:
1908 /* Clear gap of method call to avoid resurrecting previous refs. */ 2251 /* Clear gap of method call to avoid resurrecting previous refs. */
1909 if (ra > J->maxslot) J->base[ra-1] = 0; 2252 if (ra > J->maxslot) {
2253#if LJ_FR2
2254 memset(J->base + J->maxslot, 0, (ra - J->maxslot) * sizeof(TRef));
2255#else
2256 J->base[ra-1] = 0;
2257#endif
2258 }
1910 break; 2259 break;
1911 case BC_KSTR: case BC_KNUM: case BC_KPRI: 2260 case BC_KSTR: case BC_KNUM: case BC_KPRI:
1912 break; 2261 break;
@@ -1914,6 +2263,8 @@ void lj_record_ins(jit_State *J)
1914 rc = lj_ir_kint(J, (int32_t)(int16_t)rc); 2263 rc = lj_ir_kint(J, (int32_t)(int16_t)rc);
1915 break; 2264 break;
1916 case BC_KNIL: 2265 case BC_KNIL:
2266 if (LJ_FR2 && ra > J->maxslot)
2267 J->base[ra-1] = 0;
1917 while (ra <= rc) 2268 while (ra <= rc)
1918 J->base[ra++] = TREF_NIL; 2269 J->base[ra++] = TREF_NIL;
1919 if (rc >= J->maxslot) J->maxslot = rc+1; 2270 if (rc >= J->maxslot) J->maxslot = rc+1;
@@ -1950,6 +2301,14 @@ void lj_record_ins(jit_State *J)
1950 ix.idxchain = LJ_MAX_IDXCHAIN; 2301 ix.idxchain = LJ_MAX_IDXCHAIN;
1951 rc = lj_record_idx(J, &ix); 2302 rc = lj_record_idx(J, &ix);
1952 break; 2303 break;
2304 case BC_TGETR: case BC_TSETR:
2305 ix.idxchain = 0;
2306 rc = lj_record_idx(J, &ix);
2307 break;
2308
2309 case BC_TSETM:
2310 rec_tsetm(J, ra, (BCReg)(J->L->top - J->L->base), (int32_t)rcv->u32.lo);
2311 break;
1953 2312
1954 case BC_TNEW: 2313 case BC_TNEW:
1955 rc = rec_tnew(J, rc); 2314 rc = rec_tnew(J, rc);
@@ -1957,33 +2316,38 @@ void lj_record_ins(jit_State *J)
1957 case BC_TDUP: 2316 case BC_TDUP:
1958 rc = emitir(IRTG(IR_TDUP, IRT_TAB), 2317 rc = emitir(IRTG(IR_TDUP, IRT_TAB),
1959 lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0); 2318 lj_ir_ktab(J, gco2tab(proto_kgc(J->pt, ~(ptrdiff_t)rc))), 0);
2319#ifdef LUAJIT_ENABLE_TABLE_BUMP
2320 J->rbchash[(rc & (RBCHASH_SLOTS-1))].ref = tref_ref(rc);
2321 setmref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pc, pc);
2322 setgcref(J->rbchash[(rc & (RBCHASH_SLOTS-1))].pt, obj2gco(J->pt));
2323#endif
1960 break; 2324 break;
1961 2325
1962 /* -- Calls and vararg handling ----------------------------------------- */ 2326 /* -- Calls and vararg handling ----------------------------------------- */
1963 2327
1964 case BC_ITERC: 2328 case BC_ITERC:
1965 J->base[ra] = getslot(J, ra-3); 2329 J->base[ra] = getslot(J, ra-3);
1966 J->base[ra+1] = getslot(J, ra-2); 2330 J->base[ra+1+LJ_FR2] = getslot(J, ra-2);
1967 J->base[ra+2] = getslot(J, ra-1); 2331 J->base[ra+2+LJ_FR2] = getslot(J, ra-1);
1968 { /* Do the actual copy now because lj_record_call needs the values. */ 2332 { /* Do the actual copy now because lj_record_call needs the values. */
1969 TValue *b = &J->L->base[ra]; 2333 TValue *b = &J->L->base[ra];
1970 copyTV(J->L, b, b-3); 2334 copyTV(J->L, b, b-3);
1971 copyTV(J->L, b+1, b-2); 2335 copyTV(J->L, b+1+LJ_FR2, b-2);
1972 copyTV(J->L, b+2, b-1); 2336 copyTV(J->L, b+2+LJ_FR2, b-1);
1973 } 2337 }
1974 lj_record_call(J, ra, (ptrdiff_t)rc-1); 2338 lj_record_call(J, ra, (ptrdiff_t)rc-1);
1975 break; 2339 break;
1976 2340
1977 /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */ 2341 /* L->top is set to L->base+ra+rc+NARGS-1+1. See lj_dispatch_ins(). */
1978 case BC_CALLM: 2342 case BC_CALLM:
1979 rc = (BCReg)(J->L->top - J->L->base) - ra; 2343 rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
1980 /* fallthrough */ 2344 /* fallthrough */
1981 case BC_CALL: 2345 case BC_CALL:
1982 lj_record_call(J, ra, (ptrdiff_t)rc-1); 2346 lj_record_call(J, ra, (ptrdiff_t)rc-1);
1983 break; 2347 break;
1984 2348
1985 case BC_CALLMT: 2349 case BC_CALLMT:
1986 rc = (BCReg)(J->L->top - J->L->base) - ra; 2350 rc = (BCReg)(J->L->top - J->L->base) - ra - LJ_FR2;
1987 /* fallthrough */ 2351 /* fallthrough */
1988 case BC_CALLT: 2352 case BC_CALLT:
1989 lj_record_tailcall(J, ra, (ptrdiff_t)rc-1); 2353 lj_record_tailcall(J, ra, (ptrdiff_t)rc-1);
@@ -2000,6 +2364,9 @@ void lj_record_ins(jit_State *J)
2000 rc = (BCReg)(J->L->top - J->L->base) - ra + 1; 2364 rc = (BCReg)(J->L->top - J->L->base) - ra + 1;
2001 /* fallthrough */ 2365 /* fallthrough */
2002 case BC_RET: case BC_RET0: case BC_RET1: 2366 case BC_RET: case BC_RET0: case BC_RET1:
2367#if LJ_HASPROFILE
2368 rec_profile_ret(J);
2369#endif
2003 lj_record_ret(J, ra, (ptrdiff_t)rc-1); 2370 lj_record_ret(J, ra, (ptrdiff_t)rc-1);
2004 break; 2371 break;
2005 2372
@@ -2012,7 +2379,7 @@ void lj_record_ins(jit_State *J)
2012 case BC_JFORI: 2379 case BC_JFORI:
2013 lua_assert(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL); 2380 lua_assert(bc_op(pc[(ptrdiff_t)rc-BCBIAS_J]) == BC_JFORL);
2014 if (rec_for(J, pc, 0) != LOOPEV_LEAVE) /* Link to existing loop. */ 2381 if (rec_for(J, pc, 0) != LOOPEV_LEAVE) /* Link to existing loop. */
2015 rec_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J])); 2382 lj_record_stop(J, LJ_TRLINK_ROOT, bc_d(pc[(ptrdiff_t)rc-BCBIAS_J]));
2016 /* Continue tracing if the loop is not entered. */ 2383 /* Continue tracing if the loop is not entered. */
2017 break; 2384 break;
2018 2385
@@ -2079,10 +2446,8 @@ void lj_record_ins(jit_State *J)
2079 /* fallthrough */ 2446 /* fallthrough */
2080 case BC_ITERN: 2447 case BC_ITERN:
2081 case BC_ISNEXT: 2448 case BC_ISNEXT:
2082 case BC_CAT:
2083 case BC_UCLO: 2449 case BC_UCLO:
2084 case BC_FNEW: 2450 case BC_FNEW:
2085 case BC_TSETM:
2086 setintV(&J->errinfo, (int32_t)op); 2451 setintV(&J->errinfo, (int32_t)op);
2087 lj_trace_err_info(J, LJ_TRERR_NYIBC); 2452 lj_trace_err_info(J, LJ_TRERR_NYIBC);
2088 break; 2453 break;
@@ -2091,7 +2456,12 @@ void lj_record_ins(jit_State *J)
2091 /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */ 2456 /* rc == 0 if we have no result yet, e.g. pending __index metamethod call. */
2092 if (bcmode_a(op) == BCMdst && rc) { 2457 if (bcmode_a(op) == BCMdst && rc) {
2093 J->base[ra] = rc; 2458 J->base[ra] = rc;
2094 if (ra >= J->maxslot) J->maxslot = ra+1; 2459 if (ra >= J->maxslot) {
2460#if LJ_FR2
2461 if (ra > J->maxslot) J->base[ra-1] = 0;
2462#endif
2463 J->maxslot = ra+1;
2464 }
2095 } 2465 }
2096 2466
2097#undef rav 2467#undef rav
@@ -2148,6 +2518,12 @@ static const BCIns *rec_setup_root(jit_State *J)
2148 J->maxslot = J->pt->numparams; 2518 J->maxslot = J->pt->numparams;
2149 pc++; 2519 pc++;
2150 break; 2520 break;
2521 case BC_CALLM:
2522 case BC_CALL:
2523 case BC_ITERC:
2524 /* No bytecode range check for stitched traces. */
2525 pc++;
2526 break;
2151 default: 2527 default:
2152 lua_assert(0); 2528 lua_assert(0);
2153 break; 2529 break;
@@ -2163,11 +2539,14 @@ void lj_record_setup(jit_State *J)
2163 /* Initialize state related to current trace. */ 2539 /* Initialize state related to current trace. */
2164 memset(J->slot, 0, sizeof(J->slot)); 2540 memset(J->slot, 0, sizeof(J->slot));
2165 memset(J->chain, 0, sizeof(J->chain)); 2541 memset(J->chain, 0, sizeof(J->chain));
2542#ifdef LUAJIT_ENABLE_TABLE_BUMP
2543 memset(J->rbchash, 0, sizeof(J->rbchash));
2544#endif
2166 memset(J->bpropcache, 0, sizeof(J->bpropcache)); 2545 memset(J->bpropcache, 0, sizeof(J->bpropcache));
2167 J->scev.idx = REF_NIL; 2546 J->scev.idx = REF_NIL;
2168 setmref(J->scev.pc, NULL); 2547 setmref(J->scev.pc, NULL);
2169 2548
2170 J->baseslot = 1; /* Invoking function is at base[-1]. */ 2549 J->baseslot = 1+LJ_FR2; /* Invoking function is at base[-1-LJ_FR2]. */
2171 J->base = J->slot + J->baseslot; 2550 J->base = J->slot + J->baseslot;
2172 J->maxslot = 0; 2551 J->maxslot = 0;
2173 J->framedepth = 0; 2552 J->framedepth = 0;
@@ -2182,7 +2561,7 @@ void lj_record_setup(jit_State *J)
2182 J->bc_extent = ~(MSize)0; 2561 J->bc_extent = ~(MSize)0;
2183 2562
2184 /* Emit instructions for fixed references. Also triggers initial IR alloc. */ 2563 /* Emit instructions for fixed references. Also triggers initial IR alloc. */
2185 emitir_raw(IRT(IR_BASE, IRT_P32), J->parent, J->exitno); 2564 emitir_raw(IRT(IR_BASE, IRT_PGC), J->parent, J->exitno);
2186 for (i = 0; i <= 2; i++) { 2565 for (i = 0; i <= 2; i++) {
2187 IRIns *ir = IR(REF_NIL-i); 2566 IRIns *ir = IR(REF_NIL-i);
2188 ir->i = 0; 2567 ir->i = 0;
@@ -2216,7 +2595,7 @@ void lj_record_setup(jit_State *J)
2216 if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] || 2595 if (traceref(J, J->cur.root)->nchild >= J->param[JIT_P_maxside] ||
2217 T->snap[J->exitno].count >= J->param[JIT_P_hotexit] + 2596 T->snap[J->exitno].count >= J->param[JIT_P_hotexit] +
2218 J->param[JIT_P_tryside]) { 2597 J->param[JIT_P_tryside]) {
2219 rec_stop(J, LJ_TRLINK_INTERP, 0); 2598 lj_record_stop(J, LJ_TRLINK_INTERP, 0);
2220 } 2599 }
2221 } else { /* Root trace. */ 2600 } else { /* Root trace. */
2222 J->cur.root = 0; 2601 J->cur.root = 0;
@@ -2228,9 +2607,15 @@ void lj_record_setup(jit_State *J)
2228 lj_snap_add(J); 2607 lj_snap_add(J);
2229 if (bc_op(J->cur.startins) == BC_FORL) 2608 if (bc_op(J->cur.startins) == BC_FORL)
2230 rec_for_loop(J, J->pc-1, &J->scev, 1); 2609 rec_for_loop(J, J->pc-1, &J->scev, 1);
2610 else if (bc_op(J->cur.startins) == BC_ITERC)
2611 J->startpc = NULL;
2231 if (1 + J->pt->framesize >= LJ_MAX_JSLOTS) 2612 if (1 + J->pt->framesize >= LJ_MAX_JSLOTS)
2232 lj_trace_err(J, LJ_TRERR_STACKOV); 2613 lj_trace_err(J, LJ_TRERR_STACKOV);
2233 } 2614 }
2615#if LJ_HASPROFILE
2616 J->prev_pt = NULL;
2617 J->prev_line = -1;
2618#endif
2234#ifdef LUAJIT_ENABLE_CHECKHOOK 2619#ifdef LUAJIT_ENABLE_CHECKHOOK
2235 /* Regularly check for instruction/line hooks from compiled code and 2620 /* Regularly check for instruction/line hooks from compiled code and
2236 ** exit to the interpreter if the hooks are set. 2621 ** exit to the interpreter if the hooks are set.
diff --git a/src/lj_record.h b/src/lj_record.h
index 2bbbde5b..93d374d2 100644
--- a/src/lj_record.h
+++ b/src/lj_record.h
@@ -28,6 +28,7 @@ typedef struct RecordIndex {
28 28
29LJ_FUNC int lj_record_objcmp(jit_State *J, TRef a, TRef b, 29LJ_FUNC int lj_record_objcmp(jit_State *J, TRef a, TRef b,
30 cTValue *av, cTValue *bv); 30 cTValue *av, cTValue *bv);
31LJ_FUNC void lj_record_stop(jit_State *J, TraceLink linktype, TraceNo lnk);
31LJ_FUNC TRef lj_record_constify(jit_State *J, cTValue *o); 32LJ_FUNC TRef lj_record_constify(jit_State *J, cTValue *o);
32 33
33LJ_FUNC void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs); 34LJ_FUNC void lj_record_call(jit_State *J, BCReg func, ptrdiff_t nargs);
diff --git a/src/lj_snap.c b/src/lj_snap.c
index e891f7a9..bb063c2b 100644
--- a/src/lj_snap.c
+++ b/src/lj_snap.c
@@ -68,10 +68,22 @@ static MSize snapshot_slots(jit_State *J, SnapEntry *map, BCReg nslots)
68 for (s = 0; s < nslots; s++) { 68 for (s = 0; s < nslots; s++) {
69 TRef tr = J->slot[s]; 69 TRef tr = J->slot[s];
70 IRRef ref = tref_ref(tr); 70 IRRef ref = tref_ref(tr);
71#if LJ_FR2
72 if (s == 1) { /* Ignore slot 1 in LJ_FR2 mode, except if tailcalled. */
73 if ((tr & TREF_FRAME))
74 map[n++] = SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL);
75 continue;
76 }
77 if ((tr & (TREF_FRAME | TREF_CONT)) && !ref) {
78 cTValue *base = J->L->base - J->baseslot;
79 tr = J->slot[s] = (tr & 0xff0000) | lj_ir_k64(J, IR_KNUM, base[s].u64);
80 ref = tref_ref(tr);
81 }
82#endif
71 if (ref) { 83 if (ref) {
72 SnapEntry sn = SNAP_TR(s, tr); 84 SnapEntry sn = SNAP_TR(s, tr);
73 IRIns *ir = &J->cur.ir[ref]; 85 IRIns *ir = &J->cur.ir[ref];
74 if (!(sn & (SNAP_CONT|SNAP_FRAME)) && 86 if ((LJ_FR2 || !(sn & (SNAP_CONT|SNAP_FRAME))) &&
75 ir->o == IR_SLOAD && ir->op1 == s && ref > retf) { 87 ir->o == IR_SLOAD && ir->op1 == s && ref > retf) {
76 /* No need to snapshot unmodified non-inherited slots. */ 88 /* No need to snapshot unmodified non-inherited slots. */
77 if (!(ir->op2 & IRSLOAD_INHERIT)) 89 if (!(ir->op2 & IRSLOAD_INHERIT))
@@ -90,32 +102,51 @@ static MSize snapshot_slots(jit_State *J, SnapEntry *map, BCReg nslots)
90} 102}
91 103
92/* Add frame links at the end of the snapshot. */ 104/* Add frame links at the end of the snapshot. */
93static BCReg snapshot_framelinks(jit_State *J, SnapEntry *map) 105static MSize snapshot_framelinks(jit_State *J, SnapEntry *map, uint8_t *topslot)
94{ 106{
95 cTValue *frame = J->L->base - 1; 107 cTValue *frame = J->L->base - 1;
96 cTValue *lim = J->L->base - J->baseslot; 108 cTValue *lim = J->L->base - J->baseslot + LJ_FR2;
97 cTValue *ftop = frame + funcproto(frame_func(frame))->framesize; 109 GCfunc *fn = frame_func(frame);
110 cTValue *ftop = isluafunc(fn) ? (frame+funcproto(fn)->framesize) : J->L->top;
111#if LJ_FR2
112 uint64_t pcbase = (u64ptr(J->pc) << 8) | (J->baseslot - 2);
113 lua_assert(2 <= J->baseslot && J->baseslot <= 257);
114 memcpy(map, &pcbase, sizeof(uint64_t));
115#else
98 MSize f = 0; 116 MSize f = 0;
99 map[f++] = SNAP_MKPC(J->pc); /* The current PC is always the first entry. */ 117 map[f++] = SNAP_MKPC(J->pc); /* The current PC is always the first entry. */
118#endif
100 while (frame > lim) { /* Backwards traversal of all frames above base. */ 119 while (frame > lim) { /* Backwards traversal of all frames above base. */
101 if (frame_islua(frame)) { 120 if (frame_islua(frame)) {
121#if !LJ_FR2
102 map[f++] = SNAP_MKPC(frame_pc(frame)); 122 map[f++] = SNAP_MKPC(frame_pc(frame));
123#endif
103 frame = frame_prevl(frame); 124 frame = frame_prevl(frame);
104 } else if (frame_iscont(frame)) { 125 } else if (frame_iscont(frame)) {
126#if !LJ_FR2
105 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame)); 127 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame));
106 map[f++] = SNAP_MKPC(frame_contpc(frame)); 128 map[f++] = SNAP_MKPC(frame_contpc(frame));
129#endif
107 frame = frame_prevd(frame); 130 frame = frame_prevd(frame);
108 } else { 131 } else {
109 lua_assert(!frame_isc(frame)); 132 lua_assert(!frame_isc(frame));
133#if !LJ_FR2
110 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame)); 134 map[f++] = SNAP_MKFTSZ(frame_ftsz(frame));
135#endif
111 frame = frame_prevd(frame); 136 frame = frame_prevd(frame);
112 continue; 137 continue;
113 } 138 }
114 if (frame + funcproto(frame_func(frame))->framesize > ftop) 139 if (frame + funcproto(frame_func(frame))->framesize > ftop)
115 ftop = frame + funcproto(frame_func(frame))->framesize; 140 ftop = frame + funcproto(frame_func(frame))->framesize;
116 } 141 }
142 *topslot = (uint8_t)(ftop - lim);
143#if LJ_FR2
144 lua_assert(sizeof(SnapEntry) * 2 == sizeof(uint64_t));
145 return 2;
146#else
117 lua_assert(f == (MSize)(1 + J->framedepth)); 147 lua_assert(f == (MSize)(1 + J->framedepth));
118 return (BCReg)(ftop - lim); 148 return f;
149#endif
119} 150}
120 151
121/* Take a snapshot of the current stack. */ 152/* Take a snapshot of the current stack. */
@@ -125,16 +156,16 @@ static void snapshot_stack(jit_State *J, SnapShot *snap, MSize nsnapmap)
125 MSize nent; 156 MSize nent;
126 SnapEntry *p; 157 SnapEntry *p;
127 /* Conservative estimate. */ 158 /* Conservative estimate. */
128 lj_snap_grow_map(J, nsnapmap + nslots + (MSize)J->framedepth+1); 159 lj_snap_grow_map(J, nsnapmap + nslots + (MSize)(LJ_FR2?2:J->framedepth+1));
129 p = &J->cur.snapmap[nsnapmap]; 160 p = &J->cur.snapmap[nsnapmap];
130 nent = snapshot_slots(J, p, nslots); 161 nent = snapshot_slots(J, p, nslots);
131 snap->topslot = (uint8_t)snapshot_framelinks(J, p + nent); 162 snap->nent = (uint8_t)nent;
163 nent += snapshot_framelinks(J, p + nent, &snap->topslot);
132 snap->mapofs = (uint16_t)nsnapmap; 164 snap->mapofs = (uint16_t)nsnapmap;
133 snap->ref = (IRRef1)J->cur.nins; 165 snap->ref = (IRRef1)J->cur.nins;
134 snap->nent = (uint8_t)nent;
135 snap->nslots = (uint8_t)nslots; 166 snap->nslots = (uint8_t)nslots;
136 snap->count = 0; 167 snap->count = 0;
137 J->cur.nsnapmap = (uint16_t)(nsnapmap + nent + 1 + J->framedepth); 168 J->cur.nsnapmap = (uint16_t)(nsnapmap + nent);
138} 169}
139 170
140/* Add or merge a snapshot. */ 171/* Add or merge a snapshot. */
@@ -143,8 +174,8 @@ void lj_snap_add(jit_State *J)
143 MSize nsnap = J->cur.nsnap; 174 MSize nsnap = J->cur.nsnap;
144 MSize nsnapmap = J->cur.nsnapmap; 175 MSize nsnapmap = J->cur.nsnapmap;
145 /* Merge if no ins. inbetween or if requested and no guard inbetween. */ 176 /* Merge if no ins. inbetween or if requested and no guard inbetween. */
146 if (J->mergesnap ? !irt_isguard(J->guardemit) : 177 if ((nsnap > 0 && J->cur.snap[nsnap-1].ref == J->cur.nins) ||
147 (nsnap > 0 && J->cur.snap[nsnap-1].ref == J->cur.nins)) { 178 (J->mergesnap && !irt_isguard(J->guardemit))) {
148 if (nsnap == 1) { /* But preserve snap #0 PC. */ 179 if (nsnap == 1) { /* But preserve snap #0 PC. */
149 emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0); 180 emitir_raw(IRT(IR_NOP, IRT_NIL), 0, 0);
150 goto nomerge; 181 goto nomerge;
@@ -237,7 +268,8 @@ static BCReg snap_usedef(jit_State *J, uint8_t *udf,
237 case BCMbase: 268 case BCMbase:
238 if (op >= BC_CALLM && op <= BC_VARG) { 269 if (op >= BC_CALLM && op <= BC_VARG) {
239 BCReg top = (op == BC_CALLM || op == BC_CALLMT || bc_c(ins) == 0) ? 270 BCReg top = (op == BC_CALLM || op == BC_CALLMT || bc_c(ins) == 0) ?
240 maxslot : (bc_a(ins) + bc_c(ins)); 271 maxslot : (bc_a(ins) + bc_c(ins)+LJ_FR2);
272 if (LJ_FR2) DEF_SLOT(bc_a(ins)+1);
241 s = bc_a(ins) - ((op == BC_ITERC || op == BC_ITERN) ? 3 : 0); 273 s = bc_a(ins) - ((op == BC_ITERC || op == BC_ITERN) ? 3 : 0);
242 for (; s < top; s++) USE_SLOT(s); 274 for (; s < top; s++) USE_SLOT(s);
243 for (; s < maxslot; s++) DEF_SLOT(s); 275 for (; s < maxslot; s++) DEF_SLOT(s);
@@ -281,8 +313,8 @@ void lj_snap_shrink(jit_State *J)
281 MSize n, m, nlim, nent = snap->nent; 313 MSize n, m, nlim, nent = snap->nent;
282 uint8_t udf[SNAP_USEDEF_SLOTS]; 314 uint8_t udf[SNAP_USEDEF_SLOTS];
283 BCReg maxslot = J->maxslot; 315 BCReg maxslot = J->maxslot;
284 BCReg minslot = snap_usedef(J, udf, snap_pc(map[nent]), maxslot);
285 BCReg baseslot = J->baseslot; 316 BCReg baseslot = J->baseslot;
317 BCReg minslot = snap_usedef(J, udf, snap_pc(&map[nent]), maxslot);
286 maxslot += baseslot; 318 maxslot += baseslot;
287 minslot += baseslot; 319 minslot += baseslot;
288 snap->nslots = (uint8_t)maxslot; 320 snap->nslots = (uint8_t)maxslot;
@@ -368,8 +400,8 @@ static TRef snap_replay_const(jit_State *J, IRIns *ir)
368 case IR_KPRI: return TREF_PRI(irt_type(ir->t)); 400 case IR_KPRI: return TREF_PRI(irt_type(ir->t));
369 case IR_KINT: return lj_ir_kint(J, ir->i); 401 case IR_KINT: return lj_ir_kint(J, ir->i);
370 case IR_KGC: return lj_ir_kgc(J, ir_kgc(ir), irt_t(ir->t)); 402 case IR_KGC: return lj_ir_kgc(J, ir_kgc(ir), irt_t(ir->t));
371 case IR_KNUM: return lj_ir_k64(J, IR_KNUM, ir_knum(ir)); 403 case IR_KNUM: case IR_KINT64:
372 case IR_KINT64: return lj_ir_k64(J, IR_KINT64, ir_kint64(ir)); 404 return lj_ir_k64(J, (IROp)ir->o, ir_k64(ir)->u64);
373 case IR_KPTR: return lj_ir_kptr(J, ir_kptr(ir)); /* Continuation. */ 405 case IR_KPTR: return lj_ir_kptr(J, ir_kptr(ir)); /* Continuation. */
374 default: lua_assert(0); return TREF_NIL; break; 406 default: lua_assert(0); return TREF_NIL; break;
375 } 407 }
@@ -442,7 +474,11 @@ void lj_snap_replay(jit_State *J, GCtrace *T)
442 goto setslot; 474 goto setslot;
443 bloomset(seen, ref); 475 bloomset(seen, ref);
444 if (irref_isk(ref)) { 476 if (irref_isk(ref)) {
445 tr = snap_replay_const(J, ir); 477 /* See special treatment of LJ_FR2 slot 1 in snapshot_slots() above. */
478 if (LJ_FR2 && (sn == SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL)))
479 tr = 0;
480 else
481 tr = snap_replay_const(J, ir);
446 } else if (!regsp_used(ir->prev)) { 482 } else if (!regsp_used(ir->prev)) {
447 pass23 = 1; 483 pass23 = 1;
448 lua_assert(s != 0); 484 lua_assert(s != 0);
@@ -456,7 +492,7 @@ void lj_snap_replay(jit_State *J, GCtrace *T)
456 } 492 }
457 setslot: 493 setslot:
458 J->slot[s] = tr | (sn&(SNAP_CONT|SNAP_FRAME)); /* Same as TREF_* flags. */ 494 J->slot[s] = tr | (sn&(SNAP_CONT|SNAP_FRAME)); /* Same as TREF_* flags. */
459 J->framedepth += ((sn & (SNAP_CONT|SNAP_FRAME)) && s); 495 J->framedepth += ((sn & (SNAP_CONT|SNAP_FRAME)) && (s != LJ_FR2));
460 if ((sn & SNAP_FRAME)) 496 if ((sn & SNAP_FRAME))
461 J->baseslot = s+1; 497 J->baseslot = s+1;
462 } 498 }
@@ -552,8 +588,7 @@ void lj_snap_replay(jit_State *J, GCtrace *T)
552 if (irref_isk(irs->op2) && irref_isk((irs+1)->op2)) { 588 if (irref_isk(irs->op2) && irref_isk((irs+1)->op2)) {
553 uint64_t k = (uint32_t)T->ir[irs->op2].i + 589 uint64_t k = (uint32_t)T->ir[irs->op2].i +
554 ((uint64_t)T->ir[(irs+1)->op2].i << 32); 590 ((uint64_t)T->ir[(irs+1)->op2].i << 32);
555 val = lj_ir_k64(J, t == IRT_I64 ? IR_KINT64 : IR_KNUM, 591 val = lj_ir_k64(J, t == IRT_I64 ? IR_KINT64 : IR_KNUM, k);
556 lj_ir_k64_find(J, k));
557 } else { 592 } else {
558 val = emitir_raw(IRT(IR_HIOP, t), val, 593 val = emitir_raw(IRT(IR_HIOP, t), val,
559 snap_pref(J, T, map, nent, seen, (irs+1)->op2)); 594 snap_pref(J, T, map, nent, seen, (irs+1)->op2));
@@ -604,13 +639,14 @@ static void snap_restoreval(jit_State *J, GCtrace *T, ExitState *ex,
604 } else if (irt_isnum(t)) { 639 } else if (irt_isnum(t)) {
605 o->u64 = *(uint64_t *)sps; 640 o->u64 = *(uint64_t *)sps;
606#endif 641#endif
607 } else if (LJ_64 && irt_islightud(t)) { 642#if LJ_64 && !LJ_GC64
643 } else if (irt_islightud(t)) {
608 /* 64 bit lightuserdata which may escape already has the tag bits. */ 644 /* 64 bit lightuserdata which may escape already has the tag bits. */
609 o->u64 = *(uint64_t *)sps; 645 o->u64 = *(uint64_t *)sps;
646#endif
610 } else { 647 } else {
611 lua_assert(!irt_ispri(t)); /* PRI refs never have a spill slot. */ 648 lua_assert(!irt_ispri(t)); /* PRI refs never have a spill slot. */
612 setgcrefi(o->gcr, *sps); 649 setgcV(J->L, o, (GCobj *)(uintptr_t)*(GCSize *)sps, irt_toitype(t));
613 setitype(o, irt_toitype(t));
614 } 650 }
615 } else { /* Restore from register. */ 651 } else { /* Restore from register. */
616 Reg r = regsp_reg(rs); 652 Reg r = regsp_reg(rs);
@@ -625,13 +661,15 @@ static void snap_restoreval(jit_State *J, GCtrace *T, ExitState *ex,
625 } else if (irt_isnum(t)) { 661 } else if (irt_isnum(t)) {
626 setnumV(o, ex->fpr[r-RID_MIN_FPR]); 662 setnumV(o, ex->fpr[r-RID_MIN_FPR]);
627#endif 663#endif
628 } else if (LJ_64 && irt_islightud(t)) { 664#if LJ_64 && !LJ_GC64
629 /* 64 bit lightuserdata which may escape already has the tag bits. */ 665 } else if (irt_is64(t)) {
666 /* 64 bit values that already have the tag bits. */
630 o->u64 = ex->gpr[r-RID_MIN_GPR]; 667 o->u64 = ex->gpr[r-RID_MIN_GPR];
668#endif
669 } else if (irt_ispri(t)) {
670 setpriV(o, irt_toitype(t));
631 } else { 671 } else {
632 if (!irt_ispri(t)) 672 setgcV(J->L, o, (GCobj *)ex->gpr[r-RID_MIN_GPR], irt_toitype(t));
633 setgcrefi(o->gcr, ex->gpr[r-RID_MIN_GPR]);
634 setitype(o, irt_toitype(t));
635 } 673 }
636 } 674 }
637} 675}
@@ -648,7 +686,7 @@ static void snap_restoredata(GCtrace *T, ExitState *ex,
648 uint64_t tmp; 686 uint64_t tmp;
649 if (irref_isk(ref)) { 687 if (irref_isk(ref)) {
650 if (ir->o == IR_KNUM || ir->o == IR_KINT64) { 688 if (ir->o == IR_KNUM || ir->o == IR_KINT64) {
651 src = mref(ir->ptr, int32_t); 689 src = (int32_t *)&ir[1];
652 } else if (sz == 8) { 690 } else if (sz == 8) {
653 tmp = (uint64_t)(uint32_t)ir->i; 691 tmp = (uint64_t)(uint32_t)ir->i;
654 src = (int32_t *)&tmp; 692 src = (int32_t *)&tmp;
@@ -685,8 +723,9 @@ static void snap_restoredata(GCtrace *T, ExitState *ex,
685#else 723#else
686 if (LJ_BE && sz == 4) src++; 724 if (LJ_BE && sz == 4) src++;
687#endif 725#endif
688 } 726 } else
689#endif 727#endif
728 if (LJ_64 && LJ_BE && sz == 4) src++;
690 } 729 }
691 } 730 }
692 lua_assert(sz == 1 || sz == 2 || sz == 4 || sz == 8); 731 lua_assert(sz == 1 || sz == 2 || sz == 4 || sz == 8);
@@ -708,8 +747,9 @@ static void snap_unsink(jit_State *J, GCtrace *T, ExitState *ex,
708 if (ir->o == IR_CNEW || ir->o == IR_CNEWI) { 747 if (ir->o == IR_CNEW || ir->o == IR_CNEWI) {
709 CTState *cts = ctype_cts(J->L); 748 CTState *cts = ctype_cts(J->L);
710 CTypeID id = (CTypeID)T->ir[ir->op1].i; 749 CTypeID id = (CTypeID)T->ir[ir->op1].i;
711 CTSize sz = lj_ctype_size(cts, id); 750 CTSize sz;
712 GCcdata *cd = lj_cdata_new(cts, id, sz); 751 CTInfo info = lj_ctype_info(cts, id, &sz);
752 GCcdata *cd = lj_cdata_newx(cts, id, sz, info);
713 setcdataV(J->L, o, cd); 753 setcdataV(J->L, o, cd);
714 if (ir->o == IR_CNEWI) { 754 if (ir->o == IR_CNEWI) {
715 uint8_t *p = (uint8_t *)cdataptr(cd); 755 uint8_t *p = (uint8_t *)cdataptr(cd);
@@ -791,11 +831,15 @@ const BCIns *lj_snap_restore(jit_State *J, void *exptr)
791 SnapShot *snap = &T->snap[snapno]; 831 SnapShot *snap = &T->snap[snapno];
792 MSize n, nent = snap->nent; 832 MSize n, nent = snap->nent;
793 SnapEntry *map = &T->snapmap[snap->mapofs]; 833 SnapEntry *map = &T->snapmap[snap->mapofs];
794 SnapEntry *flinks = &T->snapmap[snap_nextofs(T, snap)-1]; 834#if !LJ_FR2 || defined(LUA_USE_ASSERT)
795 int32_t ftsz0; 835 SnapEntry *flinks = &T->snapmap[snap_nextofs(T, snap)-1-LJ_FR2];
836#endif
837#if !LJ_FR2
838 ptrdiff_t ftsz0;
839#endif
796 TValue *frame; 840 TValue *frame;
797 BloomFilter rfilt = snap_renamefilter(T, snapno); 841 BloomFilter rfilt = snap_renamefilter(T, snapno);
798 const BCIns *pc = snap_pc(map[nent]); 842 const BCIns *pc = snap_pc(&map[nent]);
799 lua_State *L = J->L; 843 lua_State *L = J->L;
800 844
801 /* Set interpreter PC to the next PC to get correct error messages. */ 845 /* Set interpreter PC to the next PC to get correct error messages. */
@@ -808,8 +852,10 @@ const BCIns *lj_snap_restore(jit_State *J, void *exptr)
808 } 852 }
809 853
810 /* Fill stack slots with data from the registers and spill slots. */ 854 /* Fill stack slots with data from the registers and spill slots. */
811 frame = L->base-1; 855 frame = L->base-1-LJ_FR2;
856#if !LJ_FR2
812 ftsz0 = frame_ftsz(frame); /* Preserve link to previous frame in slot #0. */ 857 ftsz0 = frame_ftsz(frame); /* Preserve link to previous frame in slot #0. */
858#endif
813 for (n = 0; n < nent; n++) { 859 for (n = 0; n < nent; n++) {
814 SnapEntry sn = map[n]; 860 SnapEntry sn = map[n];
815 if (!(sn & SNAP_NORESTORE)) { 861 if (!(sn & SNAP_NORESTORE)) {
@@ -832,13 +878,18 @@ const BCIns *lj_snap_restore(jit_State *J, void *exptr)
832 TValue tmp; 878 TValue tmp;
833 snap_restoreval(J, T, ex, snapno, rfilt, ref+1, &tmp); 879 snap_restoreval(J, T, ex, snapno, rfilt, ref+1, &tmp);
834 o->u32.hi = tmp.u32.lo; 880 o->u32.hi = tmp.u32.lo;
881#if !LJ_FR2
835 } else if ((sn & (SNAP_CONT|SNAP_FRAME))) { 882 } else if ((sn & (SNAP_CONT|SNAP_FRAME))) {
836 /* Overwrite tag with frame link. */ 883 /* Overwrite tag with frame link. */
837 o->fr.tp.ftsz = snap_slot(sn) != 0 ? (int32_t)*flinks-- : ftsz0; 884 setframe_ftsz(o, snap_slot(sn) != 0 ? (int32_t)*flinks-- : ftsz0);
838 L->base = o+1; 885 L->base = o+1;
886#endif
839 } 887 }
840 } 888 }
841 } 889 }
890#if LJ_FR2
891 L->base += (map[nent+LJ_BE] & 0xff);
892#endif
842 lua_assert(map + nent == flinks); 893 lua_assert(map + nent == flinks);
843 894
844 /* Compute current stack top. */ 895 /* Compute current stack top. */
diff --git a/src/lj_state.c b/src/lj_state.c
index f8913519..3cc0fea5 100644
--- a/src/lj_state.c
+++ b/src/lj_state.c
@@ -12,6 +12,7 @@
12#include "lj_obj.h" 12#include "lj_obj.h"
13#include "lj_gc.h" 13#include "lj_gc.h"
14#include "lj_err.h" 14#include "lj_err.h"
15#include "lj_buf.h"
15#include "lj_str.h" 16#include "lj_str.h"
16#include "lj_tab.h" 17#include "lj_tab.h"
17#include "lj_func.h" 18#include "lj_func.h"
@@ -26,6 +27,7 @@
26#include "lj_vm.h" 27#include "lj_vm.h"
27#include "lj_lex.h" 28#include "lj_lex.h"
28#include "lj_alloc.h" 29#include "lj_alloc.h"
30#include "luajit.h"
29 31
30/* -- Stack handling ------------------------------------------------------ */ 32/* -- Stack handling ------------------------------------------------------ */
31 33
@@ -47,6 +49,7 @@
47** one extra slot if mobj is not a function. Only lj_meta_tset needs 5 49** one extra slot if mobj is not a function. Only lj_meta_tset needs 5
48** slots above top, but then mobj is always a function. So we can get by 50** slots above top, but then mobj is always a function. So we can get by
49** with 5 extra slots. 51** with 5 extra slots.
52** LJ_FR2: We need 2 more slots for the frame PC and the continuation PC.
50*/ 53*/
51 54
52/* Resize stack slots and adjust pointers in state. */ 55/* Resize stack slots and adjust pointers in state. */
@@ -59,7 +62,7 @@ static void resizestack(lua_State *L, MSize n)
59 GCobj *up; 62 GCobj *up;
60 lua_assert((MSize)(tvref(L->maxstack)-oldst)==L->stacksize-LJ_STACK_EXTRA-1); 63 lua_assert((MSize)(tvref(L->maxstack)-oldst)==L->stacksize-LJ_STACK_EXTRA-1);
61 st = (TValue *)lj_mem_realloc(L, tvref(L->stack), 64 st = (TValue *)lj_mem_realloc(L, tvref(L->stack),
62 (MSize)(L->stacksize*sizeof(TValue)), 65 (MSize)(oldsize*sizeof(TValue)),
63 (MSize)(realsize*sizeof(TValue))); 66 (MSize)(realsize*sizeof(TValue)));
64 setmref(L->stack, st); 67 setmref(L->stack, st);
65 delta = (char *)st - (char *)oldst; 68 delta = (char *)st - (char *)oldst;
@@ -67,12 +70,12 @@ static void resizestack(lua_State *L, MSize n)
67 while (oldsize < realsize) /* Clear new slots. */ 70 while (oldsize < realsize) /* Clear new slots. */
68 setnilV(st + oldsize++); 71 setnilV(st + oldsize++);
69 L->stacksize = realsize; 72 L->stacksize = realsize;
73 if ((size_t)(mref(G(L)->jit_base, char) - (char *)oldst) < oldsize)
74 setmref(G(L)->jit_base, mref(G(L)->jit_base, char) + delta);
70 L->base = (TValue *)((char *)L->base + delta); 75 L->base = (TValue *)((char *)L->base + delta);
71 L->top = (TValue *)((char *)L->top + delta); 76 L->top = (TValue *)((char *)L->top + delta);
72 for (up = gcref(L->openupval); up != NULL; up = gcnext(up)) 77 for (up = gcref(L->openupval); up != NULL; up = gcnext(up))
73 setmref(gco2uv(up)->v, (TValue *)((char *)uvval(gco2uv(up)) + delta)); 78 setmref(gco2uv(up)->v, (TValue *)((char *)uvval(gco2uv(up)) + delta));
74 if (obj2gco(L) == gcref(G(L)->jit_L))
75 setmref(G(L)->jit_base, mref(G(L)->jit_base, char) + delta);
76} 79}
77 80
78/* Relimit stack after error, in case the limit was overdrawn. */ 81/* Relimit stack after error, in case the limit was overdrawn. */
@@ -89,7 +92,8 @@ void lj_state_shrinkstack(lua_State *L, MSize used)
89 return; /* Avoid stack shrinking while handling stack overflow. */ 92 return; /* Avoid stack shrinking while handling stack overflow. */
90 if (4*used < L->stacksize && 93 if (4*used < L->stacksize &&
91 2*(LJ_STACK_START+LJ_STACK_EXTRA) < L->stacksize && 94 2*(LJ_STACK_START+LJ_STACK_EXTRA) < L->stacksize &&
92 obj2gco(L) != gcref(G(L)->jit_L)) /* Don't shrink stack of live trace. */ 95 /* Don't shrink stack of live trace. */
96 (tvref(G(L)->jit_base) == NULL || obj2gco(L) != gcref(G(L)->cur_L)))
93 resizestack(L, L->stacksize >> 1); 97 resizestack(L, L->stacksize >> 1);
94} 98}
95 99
@@ -125,8 +129,9 @@ static void stack_init(lua_State *L1, lua_State *L)
125 L1->stacksize = LJ_STACK_START + LJ_STACK_EXTRA; 129 L1->stacksize = LJ_STACK_START + LJ_STACK_EXTRA;
126 stend = st + L1->stacksize; 130 stend = st + L1->stacksize;
127 setmref(L1->maxstack, stend - LJ_STACK_EXTRA - 1); 131 setmref(L1->maxstack, stend - LJ_STACK_EXTRA - 1);
128 L1->base = L1->top = st+1; 132 setthreadV(L1, st++, L1); /* Needed for curr_funcisL() on empty stack. */
129 setthreadV(L1, st, L1); /* Needed for curr_funcisL() on empty stack. */ 133 if (LJ_FR2) setnilV(st++);
134 L1->base = L1->top = st;
130 while (st < stend) /* Clear new slots. */ 135 while (st < stend) /* Clear new slots. */
131 setnilV(st++); 136 setnilV(st++);
132} 137}
@@ -164,7 +169,7 @@ static void close_state(lua_State *L)
164 lj_ctype_freestate(g); 169 lj_ctype_freestate(g);
165#endif 170#endif
166 lj_mem_freevec(g, g->strhash, g->strmask+1, GCRef); 171 lj_mem_freevec(g, g->strhash, g->strmask+1, GCRef);
167 lj_str_freebuf(g, &g->tmpbuf); 172 lj_buf_free(g, &g->tmpbuf);
168 lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue); 173 lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue);
169 lua_assert(g->gc.total == sizeof(GG_State)); 174 lua_assert(g->gc.total == sizeof(GG_State));
170#ifndef LUAJIT_USE_SYSMALLOC 175#ifndef LUAJIT_USE_SYSMALLOC
@@ -175,7 +180,7 @@ static void close_state(lua_State *L)
175 g->allocf(g->allocd, G2GG(g), sizeof(GG_State), 0); 180 g->allocf(g->allocd, G2GG(g), sizeof(GG_State), 0);
176} 181}
177 182
178#if LJ_64 && !(defined(LUAJIT_USE_VALGRIND) && defined(LUAJIT_USE_SYSMALLOC)) 183#if LJ_64 && !LJ_GC64 && !(defined(LUAJIT_USE_VALGRIND) && defined(LUAJIT_USE_SYSMALLOC))
179lua_State *lj_state_newstate(lua_Alloc f, void *ud) 184lua_State *lj_state_newstate(lua_Alloc f, void *ud)
180#else 185#else
181LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud) 186LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud)
@@ -184,7 +189,7 @@ LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud)
184 GG_State *GG = (GG_State *)f(ud, NULL, 0, sizeof(GG_State)); 189 GG_State *GG = (GG_State *)f(ud, NULL, 0, sizeof(GG_State));
185 lua_State *L = &GG->L; 190 lua_State *L = &GG->L;
186 global_State *g = &GG->g; 191 global_State *g = &GG->g;
187 if (GG == NULL || !checkptr32(GG)) return NULL; 192 if (GG == NULL || !checkptrGC(GG)) return NULL;
188 memset(GG, 0, sizeof(GG_State)); 193 memset(GG, 0, sizeof(GG_State));
189 L->gct = ~LJ_TTHREAD; 194 L->gct = ~LJ_TTHREAD;
190 L->marked = LJ_GC_WHITE0 | LJ_GC_FIXED | LJ_GC_SFIXED; /* Prevent free. */ 195 L->marked = LJ_GC_WHITE0 | LJ_GC_FIXED | LJ_GC_SFIXED; /* Prevent free. */
@@ -202,8 +207,10 @@ LUA_API lua_State *lua_newstate(lua_Alloc f, void *ud)
202 setnilV(registry(L)); 207 setnilV(registry(L));
203 setnilV(&g->nilnode.val); 208 setnilV(&g->nilnode.val);
204 setnilV(&g->nilnode.key); 209 setnilV(&g->nilnode.key);
210#if !LJ_GC64
205 setmref(g->nilnode.freetop, &g->nilnode); 211 setmref(g->nilnode.freetop, &g->nilnode);
206 lj_str_initbuf(&g->tmpbuf); 212#endif
213 lj_buf_init(NULL, &g->tmpbuf);
207 g->gc.state = GCSpause; 214 g->gc.state = GCSpause;
208 setgcref(g->gc.root, obj2gco(L)); 215 setgcref(g->gc.root, obj2gco(L));
209 setmref(g->gc.sweep, &g->gc.root); 216 setmref(g->gc.sweep, &g->gc.root);
@@ -236,6 +243,10 @@ LUA_API void lua_close(lua_State *L)
236 global_State *g = G(L); 243 global_State *g = G(L);
237 int i; 244 int i;
238 L = mainthread(g); /* Only the main thread can be closed. */ 245 L = mainthread(g); /* Only the main thread can be closed. */
246#if LJ_HASPROFILE
247 luaJIT_profile_stop(L);
248#endif
249 setgcrefnull(g->cur_L);
239 lj_func_closeuv(L, tvref(L->stack)); 250 lj_func_closeuv(L, tvref(L->stack));
240 lj_gc_separateudata(g, 1); /* Separate udata which have GC metamethods. */ 251 lj_gc_separateudata(g, 1); /* Separate udata which have GC metamethods. */
241#if LJ_HASJIT 252#if LJ_HASJIT
@@ -246,8 +257,8 @@ LUA_API void lua_close(lua_State *L)
246 for (i = 0;;) { 257 for (i = 0;;) {
247 hook_enter(g); 258 hook_enter(g);
248 L->status = 0; 259 L->status = 0;
260 L->base = L->top = tvref(L->stack) + 1 + LJ_FR2;
249 L->cframe = NULL; 261 L->cframe = NULL;
250 L->base = L->top = tvref(L->stack) + 1;
251 if (lj_vm_cpcall(L, NULL, NULL, cpfinalize) == 0) { 262 if (lj_vm_cpcall(L, NULL, NULL, cpfinalize) == 0) {
252 if (++i >= 10) break; 263 if (++i >= 10) break;
253 lj_gc_separateudata(g, 1); /* Separate udata again. */ 264 lj_gc_separateudata(g, 1); /* Separate udata again. */
@@ -279,6 +290,8 @@ lua_State *lj_state_new(lua_State *L)
279void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L) 290void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L)
280{ 291{
281 lua_assert(L != mainthread(g)); 292 lua_assert(L != mainthread(g));
293 if (obj2gco(L) == gcref(g->cur_L))
294 setgcrefnull(g->cur_L);
282 lj_func_closeuv(L, tvref(L->stack)); 295 lj_func_closeuv(L, tvref(L->stack));
283 lua_assert(gcref(L->openupval) == NULL); 296 lua_assert(gcref(L->openupval) == NULL);
284 lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue); 297 lj_mem_freevec(g, tvref(L->stack), L->stacksize, TValue);
diff --git a/src/lj_state.h b/src/lj_state.h
index d5b476b2..02a0eafa 100644
--- a/src/lj_state.h
+++ b/src/lj_state.h
@@ -28,7 +28,7 @@ static LJ_AINLINE void lj_state_checkstack(lua_State *L, MSize need)
28 28
29LJ_FUNC lua_State *lj_state_new(lua_State *L); 29LJ_FUNC lua_State *lj_state_new(lua_State *L);
30LJ_FUNC void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L); 30LJ_FUNC void LJ_FASTCALL lj_state_free(global_State *g, lua_State *L);
31#if LJ_64 31#if LJ_64 && !LJ_GC64 && !(defined(LUAJIT_USE_VALGRIND) && defined(LUAJIT_USE_SYSMALLOC))
32LJ_FUNC lua_State *lj_state_newstate(lua_Alloc f, void *ud); 32LJ_FUNC lua_State *lj_state_newstate(lua_Alloc f, void *ud);
33#endif 33#endif
34 34
diff --git a/src/lj_str.c b/src/lj_str.c
index aae6ec5b..264dedc1 100644
--- a/src/lj_str.c
+++ b/src/lj_str.c
@@ -1,13 +1,8 @@
1/* 1/*
2** String handling. 2** String handling.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h 3** Copyright (C) 2005-2017 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*/ 4*/
8 5
9#include <stdio.h>
10
11#define lj_str_c 6#define lj_str_c
12#define LUA_CORE 7#define LUA_CORE
13 8
@@ -15,10 +10,9 @@
15#include "lj_gc.h" 10#include "lj_gc.h"
16#include "lj_err.h" 11#include "lj_err.h"
17#include "lj_str.h" 12#include "lj_str.h"
18#include "lj_state.h"
19#include "lj_char.h" 13#include "lj_char.h"
20 14
21/* -- String interning ---------------------------------------------------- */ 15/* -- String helpers ------------------------------------------------------ */
22 16
23/* Ordered compare of strings. Assumes string data is 4-byte aligned. */ 17/* Ordered compare of strings. Assumes string data is 4-byte aligned. */
24int32_t LJ_FASTCALL lj_str_cmp(GCstr *a, GCstr *b) 18int32_t LJ_FASTCALL lj_str_cmp(GCstr *a, GCstr *b)
@@ -64,6 +58,40 @@ static LJ_AINLINE int str_fastcmp(const char *a, const char *b, MSize len)
64 return 0; 58 return 0;
65} 59}
66 60
61/* Find fixed string p inside string s. */
62const char *lj_str_find(const char *s, const char *p, MSize slen, MSize plen)
63{
64 if (plen <= slen) {
65 if (plen == 0) {
66 return s;
67 } else {
68 int c = *(const uint8_t *)p++;
69 plen--; slen -= plen;
70 while (slen) {
71 const char *q = (const char *)memchr(s, c, slen);
72 if (!q) break;
73 if (memcmp(q+1, p, plen) == 0) return q;
74 q++; slen -= (MSize)(q-s); s = q;
75 }
76 }
77 }
78 return NULL;
79}
80
81/* Check whether a string has a pattern matching character. */
82int lj_str_haspattern(GCstr *s)
83{
84 const char *p = strdata(s), *q = p + s->len;
85 while (p < q) {
86 int c = *(const uint8_t *)p++;
87 if (lj_char_ispunct(c) && strchr("^$*+?.([%-", c))
88 return 1; /* Found a pattern matching char. */
89 }
90 return 0; /* No pattern matching chars found. */
91}
92
93/* -- String interning ---------------------------------------------------- */
94
67/* Resize the string hash table (grow and shrink). */ 95/* Resize the string hash table (grow and shrink). */
68void lj_str_resize(lua_State *L, MSize newmask) 96void lj_str_resize(lua_State *L, MSize newmask)
69{ 97{
@@ -167,173 +195,3 @@ void LJ_FASTCALL lj_str_free(global_State *g, GCstr *s)
167 lj_mem_free(g, s, sizestring(s)); 195 lj_mem_free(g, s, sizestring(s));
168} 196}
169 197
170/* -- Type conversions ---------------------------------------------------- */
171
172/* Print number to buffer. Canonicalizes non-finite values. */
173size_t LJ_FASTCALL lj_str_bufnum(char *s, cTValue *o)
174{
175 if (LJ_LIKELY((o->u32.hi << 1) < 0xffe00000)) { /* Finite? */
176 lua_Number n = o->n;
177#if __BIONIC__
178 if (tvismzero(o)) { s[0] = '-'; s[1] = '0'; return 2; }
179#endif
180 return (size_t)lua_number2str(s, n);
181 } else if (((o->u32.hi & 0x000fffff) | o->u32.lo) != 0) {
182 s[0] = 'n'; s[1] = 'a'; s[2] = 'n'; return 3;
183 } else if ((o->u32.hi & 0x80000000) == 0) {
184 s[0] = 'i'; s[1] = 'n'; s[2] = 'f'; return 3;
185 } else {
186 s[0] = '-'; s[1] = 'i'; s[2] = 'n'; s[3] = 'f'; return 4;
187 }
188}
189
190/* Print integer to buffer. Returns pointer to start. */
191char * LJ_FASTCALL lj_str_bufint(char *p, int32_t k)
192{
193 uint32_t u = (uint32_t)(k < 0 ? -k : k);
194 p += 1+10;
195 do { *--p = (char)('0' + u % 10); } while (u /= 10);
196 if (k < 0) *--p = '-';
197 return p;
198}
199
200/* Convert number to string. */
201GCstr * LJ_FASTCALL lj_str_fromnum(lua_State *L, const lua_Number *np)
202{
203 char buf[LJ_STR_NUMBUF];
204 size_t len = lj_str_bufnum(buf, (TValue *)np);
205 return lj_str_new(L, buf, len);
206}
207
208/* Convert integer to string. */
209GCstr * LJ_FASTCALL lj_str_fromint(lua_State *L, int32_t k)
210{
211 char s[1+10];
212 char *p = lj_str_bufint(s, k);
213 return lj_str_new(L, p, (size_t)(s+sizeof(s)-p));
214}
215
216GCstr * LJ_FASTCALL lj_str_fromnumber(lua_State *L, cTValue *o)
217{
218 return tvisint(o) ? lj_str_fromint(L, intV(o)) : lj_str_fromnum(L, &o->n);
219}
220
221/* -- String formatting --------------------------------------------------- */
222
223static void addstr(lua_State *L, SBuf *sb, const char *str, MSize len)
224{
225 char *p;
226 MSize i;
227 if (sb->n + len > sb->sz) {
228 MSize sz = sb->sz * 2;
229 while (sb->n + len > sz) sz = sz * 2;
230 lj_str_resizebuf(L, sb, sz);
231 }
232 p = sb->buf + sb->n;
233 sb->n += len;
234 for (i = 0; i < len; i++) p[i] = str[i];
235}
236
237static void addchar(lua_State *L, SBuf *sb, int c)
238{
239 if (sb->n + 1 > sb->sz) {
240 MSize sz = sb->sz * 2;
241 lj_str_resizebuf(L, sb, sz);
242 }
243 sb->buf[sb->n++] = (char)c;
244}
245
246/* Push formatted message as a string object to Lua stack. va_list variant. */
247const char *lj_str_pushvf(lua_State *L, const char *fmt, va_list argp)
248{
249 SBuf *sb = &G(L)->tmpbuf;
250 lj_str_needbuf(L, sb, (MSize)strlen(fmt));
251 lj_str_resetbuf(sb);
252 for (;;) {
253 const char *e = strchr(fmt, '%');
254 if (e == NULL) break;
255 addstr(L, sb, fmt, (MSize)(e-fmt));
256 /* This function only handles %s, %c, %d, %f and %p formats. */
257 switch (e[1]) {
258 case 's': {
259 const char *s = va_arg(argp, char *);
260 if (s == NULL) s = "(null)";
261 addstr(L, sb, s, (MSize)strlen(s));
262 break;
263 }
264 case 'c':
265 addchar(L, sb, va_arg(argp, int));
266 break;
267 case 'd': {
268 char buf[LJ_STR_INTBUF];
269 char *p = lj_str_bufint(buf, va_arg(argp, int32_t));
270 addstr(L, sb, p, (MSize)(buf+LJ_STR_INTBUF-p));
271 break;
272 }
273 case 'f': {
274 char buf[LJ_STR_NUMBUF];
275 TValue tv;
276 MSize len;
277 tv.n = (lua_Number)(va_arg(argp, LUAI_UACNUMBER));
278 len = (MSize)lj_str_bufnum(buf, &tv);
279 addstr(L, sb, buf, len);
280 break;
281 }
282 case 'p': {
283#define FMTP_CHARS (2*sizeof(ptrdiff_t))
284 char buf[2+FMTP_CHARS];
285 ptrdiff_t p = (ptrdiff_t)(va_arg(argp, void *));
286 ptrdiff_t i, lasti = 2+FMTP_CHARS;
287 if (p == 0) {
288 addstr(L, sb, "NULL", 4);
289 break;
290 }
291#if LJ_64
292 /* Shorten output for 64 bit pointers. */
293 lasti = 2+2*4+((p >> 32) ? 2+2*(lj_fls((uint32_t)(p >> 32))>>3) : 0);
294#endif
295 buf[0] = '0';
296 buf[1] = 'x';
297 for (i = lasti-1; i >= 2; i--, p >>= 4)
298 buf[i] = "0123456789abcdef"[(p & 15)];
299 addstr(L, sb, buf, (MSize)lasti);
300 break;
301 }
302 case '%':
303 addchar(L, sb, '%');
304 break;
305 default:
306 addchar(L, sb, '%');
307 addchar(L, sb, e[1]);
308 break;
309 }
310 fmt = e+2;
311 }
312 addstr(L, sb, fmt, (MSize)strlen(fmt));
313 setstrV(L, L->top, lj_str_new(L, sb->buf, sb->n));
314 incr_top(L);
315 return strVdata(L->top - 1);
316}
317
318/* Push formatted message as a string object to Lua stack. Vararg variant. */
319const char *lj_str_pushf(lua_State *L, const char *fmt, ...)
320{
321 const char *msg;
322 va_list argp;
323 va_start(argp, fmt);
324 msg = lj_str_pushvf(L, fmt, argp);
325 va_end(argp);
326 return msg;
327}
328
329/* -- Buffer handling ----------------------------------------------------- */
330
331char *lj_str_needbuf(lua_State *L, SBuf *sb, MSize sz)
332{
333 if (sz > sb->sz) {
334 if (sz < LJ_MIN_SBUF) sz = LJ_MIN_SBUF;
335 lj_str_resizebuf(L, sb, sz);
336 }
337 return sb->buf;
338}
339
diff --git a/src/lj_str.h b/src/lj_str.h
index be04a975..85c1e405 100644
--- a/src/lj_str.h
+++ b/src/lj_str.h
@@ -10,8 +10,13 @@
10 10
11#include "lj_obj.h" 11#include "lj_obj.h"
12 12
13/* String interning. */ 13/* String helpers. */
14LJ_FUNC int32_t LJ_FASTCALL lj_str_cmp(GCstr *a, GCstr *b); 14LJ_FUNC int32_t LJ_FASTCALL lj_str_cmp(GCstr *a, GCstr *b);
15LJ_FUNC const char *lj_str_find(const char *s, const char *f,
16 MSize slen, MSize flen);
17LJ_FUNC int lj_str_haspattern(GCstr *s);
18
19/* String interning. */
15LJ_FUNC void lj_str_resize(lua_State *L, MSize newmask); 20LJ_FUNC void lj_str_resize(lua_State *L, MSize newmask);
16LJ_FUNCA GCstr *lj_str_new(lua_State *L, const char *str, size_t len); 21LJ_FUNCA GCstr *lj_str_new(lua_State *L, const char *str, size_t len);
17LJ_FUNC void LJ_FASTCALL lj_str_free(global_State *g, GCstr *s); 22LJ_FUNC void LJ_FASTCALL lj_str_free(global_State *g, GCstr *s);
@@ -19,32 +24,4 @@ LJ_FUNC void LJ_FASTCALL lj_str_free(global_State *g, GCstr *s);
19#define lj_str_newz(L, s) (lj_str_new(L, s, strlen(s))) 24#define lj_str_newz(L, s) (lj_str_new(L, s, strlen(s)))
20#define lj_str_newlit(L, s) (lj_str_new(L, "" s, sizeof(s)-1)) 25#define lj_str_newlit(L, s) (lj_str_new(L, "" s, sizeof(s)-1))
21 26
22/* Type conversions. */
23LJ_FUNC size_t LJ_FASTCALL lj_str_bufnum(char *s, cTValue *o);
24LJ_FUNC char * LJ_FASTCALL lj_str_bufint(char *p, int32_t k);
25LJ_FUNCA GCstr * LJ_FASTCALL lj_str_fromnum(lua_State *L, const lua_Number *np);
26LJ_FUNC GCstr * LJ_FASTCALL lj_str_fromint(lua_State *L, int32_t k);
27LJ_FUNCA GCstr * LJ_FASTCALL lj_str_fromnumber(lua_State *L, cTValue *o);
28
29#define LJ_STR_INTBUF (1+10)
30#define LJ_STR_NUMBUF LUAI_MAXNUMBER2STR
31
32/* String formatting. */
33LJ_FUNC const char *lj_str_pushvf(lua_State *L, const char *fmt, va_list argp);
34LJ_FUNC const char *lj_str_pushf(lua_State *L, const char *fmt, ...)
35#if defined(__GNUC__)
36 __attribute__ ((format (printf, 2, 3)))
37#endif
38 ;
39
40/* Resizable string buffers. Struct definition in lj_obj.h. */
41LJ_FUNC char *lj_str_needbuf(lua_State *L, SBuf *sb, MSize sz);
42
43#define lj_str_initbuf(sb) ((sb)->buf = NULL, (sb)->sz = 0)
44#define lj_str_resetbuf(sb) ((sb)->n = 0)
45#define lj_str_resizebuf(L, sb, size) \
46 ((sb)->buf = (char *)lj_mem_realloc(L, (sb)->buf, (sb)->sz, (size)), \
47 (sb)->sz = (size))
48#define lj_str_freebuf(g, sb) lj_mem_free(g, (void *)(sb)->buf, (sb)->sz)
49
50#endif 27#endif
diff --git a/src/lj_strfmt.c b/src/lj_strfmt.c
new file mode 100644
index 00000000..d7893ce9
--- /dev/null
+++ b/src/lj_strfmt.c
@@ -0,0 +1,472 @@
1/*
2** String formatting.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#include <stdio.h>
7
8#define lj_strfmt_c
9#define LUA_CORE
10
11#include "lj_obj.h"
12#include "lj_buf.h"
13#include "lj_str.h"
14#include "lj_state.h"
15#include "lj_char.h"
16#include "lj_strfmt.h"
17
18/* -- Format parser ------------------------------------------------------- */
19
20static const uint8_t strfmt_map[('x'-'A')+1] = {
21 STRFMT_A,0,0,0,STRFMT_E,STRFMT_F,STRFMT_G,0,0,0,0,0,0,
22 0,0,0,0,0,0,0,0,0,0,STRFMT_X,0,0,
23 0,0,0,0,0,0,
24 STRFMT_A,0,STRFMT_C,STRFMT_D,STRFMT_E,STRFMT_F,STRFMT_G,0,STRFMT_I,0,0,0,0,
25 0,STRFMT_O,STRFMT_P,STRFMT_Q,0,STRFMT_S,0,STRFMT_U,0,0,STRFMT_X
26};
27
28SFormat LJ_FASTCALL lj_strfmt_parse(FormatState *fs)
29{
30 const uint8_t *p = fs->p, *e = fs->e;
31 fs->str = (const char *)p;
32 for (; p < e; p++) {
33 if (*p == '%') { /* Escape char? */
34 if (p[1] == '%') { /* '%%'? */
35 fs->p = ++p+1;
36 goto retlit;
37 } else {
38 SFormat sf = 0;
39 uint32_t c;
40 if (p != (const uint8_t *)fs->str)
41 break;
42 for (p++; (uint32_t)*p - ' ' <= (uint32_t)('0' - ' '); p++) {
43 /* Parse flags. */
44 if (*p == '-') sf |= STRFMT_F_LEFT;
45 else if (*p == '+') sf |= STRFMT_F_PLUS;
46 else if (*p == '0') sf |= STRFMT_F_ZERO;
47 else if (*p == ' ') sf |= STRFMT_F_SPACE;
48 else if (*p == '#') sf |= STRFMT_F_ALT;
49 else break;
50 }
51 if ((uint32_t)*p - '0' < 10) { /* Parse width. */
52 uint32_t width = (uint32_t)*p++ - '0';
53 if ((uint32_t)*p - '0' < 10)
54 width = (uint32_t)*p++ - '0' + width*10;
55 sf |= (width << STRFMT_SH_WIDTH);
56 }
57 if (*p == '.') { /* Parse precision. */
58 uint32_t prec = 0;
59 p++;
60 if ((uint32_t)*p - '0' < 10) {
61 prec = (uint32_t)*p++ - '0';
62 if ((uint32_t)*p - '0' < 10)
63 prec = (uint32_t)*p++ - '0' + prec*10;
64 }
65 sf |= ((prec+1) << STRFMT_SH_PREC);
66 }
67 /* Parse conversion. */
68 c = (uint32_t)*p - 'A';
69 if (LJ_LIKELY(c <= (uint32_t)('x' - 'A'))) {
70 uint32_t sx = strfmt_map[c];
71 if (sx) {
72 fs->p = p+1;
73 return (sf | sx | ((c & 0x20) ? 0 : STRFMT_F_UPPER));
74 }
75 }
76 /* Return error location. */
77 if (*p >= 32) p++;
78 fs->len = (MSize)(p - (const uint8_t *)fs->str);
79 fs->p = fs->e;
80 return STRFMT_ERR;
81 }
82 }
83 }
84 fs->p = p;
85retlit:
86 fs->len = (MSize)(p - (const uint8_t *)fs->str);
87 return fs->len ? STRFMT_LIT : STRFMT_EOF;
88}
89
90/* -- Raw conversions ----------------------------------------------------- */
91
92#define WINT_R(x, sh, sc) \
93 { uint32_t d = (x*(((1<<sh)+sc-1)/sc))>>sh; x -= d*sc; *p++ = (char)('0'+d); }
94
95/* Write integer to buffer. */
96char * LJ_FASTCALL lj_strfmt_wint(char *p, int32_t k)
97{
98 uint32_t u = (uint32_t)k;
99 if (k < 0) { u = (uint32_t)-k; *p++ = '-'; }
100 if (u < 10000) {
101 if (u < 10) goto dig1;
102 if (u < 100) goto dig2;
103 if (u < 1000) goto dig3;
104 } else {
105 uint32_t v = u / 10000; u -= v * 10000;
106 if (v < 10000) {
107 if (v < 10) goto dig5;
108 if (v < 100) goto dig6;
109 if (v < 1000) goto dig7;
110 } else {
111 uint32_t w = v / 10000; v -= w * 10000;
112 if (w >= 10) WINT_R(w, 10, 10)
113 *p++ = (char)('0'+w);
114 }
115 WINT_R(v, 23, 1000)
116 dig7: WINT_R(v, 12, 100)
117 dig6: WINT_R(v, 10, 10)
118 dig5: *p++ = (char)('0'+v);
119 }
120 WINT_R(u, 23, 1000)
121 dig3: WINT_R(u, 12, 100)
122 dig2: WINT_R(u, 10, 10)
123 dig1: *p++ = (char)('0'+u);
124 return p;
125}
126#undef WINT_R
127
128/* Write pointer to buffer. */
129char * LJ_FASTCALL lj_strfmt_wptr(char *p, const void *v)
130{
131 ptrdiff_t x = (ptrdiff_t)v;
132 MSize i, n = STRFMT_MAXBUF_PTR;
133 if (x == 0) {
134 *p++ = 'N'; *p++ = 'U'; *p++ = 'L'; *p++ = 'L';
135 return p;
136 }
137#if LJ_64
138 /* Shorten output for 64 bit pointers. */
139 n = 2+2*4+((x >> 32) ? 2+2*(lj_fls((uint32_t)(x >> 32))>>3) : 0);
140#endif
141 p[0] = '0';
142 p[1] = 'x';
143 for (i = n-1; i >= 2; i--, x >>= 4)
144 p[i] = "0123456789abcdef"[(x & 15)];
145 return p+n;
146}
147
148/* Write ULEB128 to buffer. */
149char * LJ_FASTCALL lj_strfmt_wuleb128(char *p, uint32_t v)
150{
151 for (; v >= 0x80; v >>= 7)
152 *p++ = (char)((v & 0x7f) | 0x80);
153 *p++ = (char)v;
154 return p;
155}
156
157/* Return string or write number to tmp buffer and return pointer to start. */
158const char *lj_strfmt_wstrnum(lua_State *L, cTValue *o, MSize *lenp)
159{
160 SBuf *sb;
161 if (tvisstr(o)) {
162 *lenp = strV(o)->len;
163 return strVdata(o);
164 } else if (tvisint(o)) {
165 sb = lj_strfmt_putint(lj_buf_tmp_(L), intV(o));
166 } else if (tvisnum(o)) {
167 sb = lj_strfmt_putfnum(lj_buf_tmp_(L), STRFMT_G14, o->n);
168 } else {
169 return NULL;
170 }
171 *lenp = sbuflen(sb);
172 return sbufB(sb);
173}
174
175/* -- Unformatted conversions to buffer ----------------------------------- */
176
177/* Add integer to buffer. */
178SBuf * LJ_FASTCALL lj_strfmt_putint(SBuf *sb, int32_t k)
179{
180 setsbufP(sb, lj_strfmt_wint(lj_buf_more(sb, STRFMT_MAXBUF_INT), k));
181 return sb;
182}
183
184#if LJ_HASJIT
185/* Add number to buffer. */
186SBuf * LJ_FASTCALL lj_strfmt_putnum(SBuf *sb, cTValue *o)
187{
188 return lj_strfmt_putfnum(sb, STRFMT_G14, o->n);
189}
190#endif
191
192SBuf * LJ_FASTCALL lj_strfmt_putptr(SBuf *sb, const void *v)
193{
194 setsbufP(sb, lj_strfmt_wptr(lj_buf_more(sb, STRFMT_MAXBUF_PTR), v));
195 return sb;
196}
197
198/* Add quoted string to buffer. */
199SBuf * LJ_FASTCALL lj_strfmt_putquoted(SBuf *sb, GCstr *str)
200{
201 const char *s = strdata(str);
202 MSize len = str->len;
203 lj_buf_putb(sb, '"');
204 while (len--) {
205 uint32_t c = (uint32_t)(uint8_t)*s++;
206 char *p = lj_buf_more(sb, 4);
207 if (c == '"' || c == '\\' || c == '\n') {
208 *p++ = '\\';
209 } else if (lj_char_iscntrl(c)) { /* This can only be 0-31 or 127. */
210 uint32_t d;
211 *p++ = '\\';
212 if (c >= 100 || lj_char_isdigit((uint8_t)*s)) {
213 *p++ = (char)('0'+(c >= 100)); if (c >= 100) c -= 100;
214 goto tens;
215 } else if (c >= 10) {
216 tens:
217 d = (c * 205) >> 11; c -= d * 10; *p++ = (char)('0'+d);
218 }
219 c += '0';
220 }
221 *p++ = (char)c;
222 setsbufP(sb, p);
223 }
224 lj_buf_putb(sb, '"');
225 return sb;
226}
227
228/* -- Formatted conversions to buffer ------------------------------------- */
229
230/* Add formatted char to buffer. */
231SBuf *lj_strfmt_putfchar(SBuf *sb, SFormat sf, int32_t c)
232{
233 MSize width = STRFMT_WIDTH(sf);
234 char *p = lj_buf_more(sb, width > 1 ? width : 1);
235 if ((sf & STRFMT_F_LEFT)) *p++ = (char)c;
236 while (width-- > 1) *p++ = ' ';
237 if (!(sf & STRFMT_F_LEFT)) *p++ = (char)c;
238 setsbufP(sb, p);
239 return sb;
240}
241
242/* Add formatted string to buffer. */
243SBuf *lj_strfmt_putfstr(SBuf *sb, SFormat sf, GCstr *str)
244{
245 MSize len = str->len <= STRFMT_PREC(sf) ? str->len : STRFMT_PREC(sf);
246 MSize width = STRFMT_WIDTH(sf);
247 char *p = lj_buf_more(sb, width > len ? width : len);
248 if ((sf & STRFMT_F_LEFT)) p = lj_buf_wmem(p, strdata(str), len);
249 while (width-- > len) *p++ = ' ';
250 if (!(sf & STRFMT_F_LEFT)) p = lj_buf_wmem(p, strdata(str), len);
251 setsbufP(sb, p);
252 return sb;
253}
254
255/* Add formatted signed/unsigned integer to buffer. */
256SBuf *lj_strfmt_putfxint(SBuf *sb, SFormat sf, uint64_t k)
257{
258 char buf[STRFMT_MAXBUF_XINT], *q = buf + sizeof(buf), *p;
259#ifdef LUA_USE_ASSERT
260 char *ps;
261#endif
262 MSize prefix = 0, len, prec, pprec, width, need;
263
264 /* Figure out signed prefixes. */
265 if (STRFMT_TYPE(sf) == STRFMT_INT) {
266 if ((int64_t)k < 0) {
267 k = (uint64_t)-(int64_t)k;
268 prefix = 256 + '-';
269 } else if ((sf & STRFMT_F_PLUS)) {
270 prefix = 256 + '+';
271 } else if ((sf & STRFMT_F_SPACE)) {
272 prefix = 256 + ' ';
273 }
274 }
275
276 /* Convert number and store to fixed-size buffer in reverse order. */
277 prec = STRFMT_PREC(sf);
278 if ((int32_t)prec >= 0) sf &= ~STRFMT_F_ZERO;
279 if (k == 0) { /* Special-case zero argument. */
280 if (prec != 0 ||
281 (sf & (STRFMT_T_OCT|STRFMT_F_ALT)) == (STRFMT_T_OCT|STRFMT_F_ALT))
282 *--q = '0';
283 } else if (!(sf & (STRFMT_T_HEX|STRFMT_T_OCT))) { /* Decimal. */
284 uint32_t k2;
285 while ((k >> 32)) { *--q = (char)('0' + k % 10); k /= 10; }
286 k2 = (uint32_t)k;
287 do { *--q = (char)('0' + k2 % 10); k2 /= 10; } while (k2);
288 } else if ((sf & STRFMT_T_HEX)) { /* Hex. */
289 const char *hexdig = (sf & STRFMT_F_UPPER) ? "0123456789ABCDEF" :
290 "0123456789abcdef";
291 do { *--q = hexdig[(k & 15)]; k >>= 4; } while (k);
292 if ((sf & STRFMT_F_ALT)) prefix = 512 + ((sf & STRFMT_F_UPPER) ? 'X' : 'x');
293 } else { /* Octal. */
294 do { *--q = (char)('0' + (uint32_t)(k & 7)); k >>= 3; } while (k);
295 if ((sf & STRFMT_F_ALT)) *--q = '0';
296 }
297
298 /* Calculate sizes. */
299 len = (MSize)(buf + sizeof(buf) - q);
300 if ((int32_t)len >= (int32_t)prec) prec = len;
301 width = STRFMT_WIDTH(sf);
302 pprec = prec + (prefix >> 8);
303 need = width > pprec ? width : pprec;
304 p = lj_buf_more(sb, need);
305#ifdef LUA_USE_ASSERT
306 ps = p;
307#endif
308
309 /* Format number with leading/trailing whitespace and zeros. */
310 if ((sf & (STRFMT_F_LEFT|STRFMT_F_ZERO)) == 0)
311 while (width-- > pprec) *p++ = ' ';
312 if (prefix) {
313 if ((char)prefix >= 'X') *p++ = '0';
314 *p++ = (char)prefix;
315 }
316 if ((sf & (STRFMT_F_LEFT|STRFMT_F_ZERO)) == STRFMT_F_ZERO)
317 while (width-- > pprec) *p++ = '0';
318 while (prec-- > len) *p++ = '0';
319 while (q < buf + sizeof(buf)) *p++ = *q++; /* Add number itself. */
320 if ((sf & STRFMT_F_LEFT))
321 while (width-- > pprec) *p++ = ' ';
322
323 lua_assert(need == (MSize)(p - ps));
324 setsbufP(sb, p);
325 return sb;
326}
327
328/* Add number formatted as signed integer to buffer. */
329SBuf *lj_strfmt_putfnum_int(SBuf *sb, SFormat sf, lua_Number n)
330{
331 int64_t k = (int64_t)n;
332 if (checki32(k) && sf == STRFMT_INT)
333 return lj_strfmt_putint(sb, (int32_t)k); /* Shortcut for plain %d. */
334 else
335 return lj_strfmt_putfxint(sb, sf, (uint64_t)k);
336}
337
338/* Add number formatted as unsigned integer to buffer. */
339SBuf *lj_strfmt_putfnum_uint(SBuf *sb, SFormat sf, lua_Number n)
340{
341 int64_t k;
342 if (n >= 9223372036854775808.0)
343 k = (int64_t)(n - 18446744073709551616.0);
344 else
345 k = (int64_t)n;
346 return lj_strfmt_putfxint(sb, sf, (uint64_t)k);
347}
348
349/* -- Conversions to strings ---------------------------------------------- */
350
351/* Convert integer to string. */
352GCstr * LJ_FASTCALL lj_strfmt_int(lua_State *L, int32_t k)
353{
354 char buf[STRFMT_MAXBUF_INT];
355 MSize len = (MSize)(lj_strfmt_wint(buf, k) - buf);
356 return lj_str_new(L, buf, len);
357}
358
359/* Convert integer or number to string. */
360GCstr * LJ_FASTCALL lj_strfmt_number(lua_State *L, cTValue *o)
361{
362 return tvisint(o) ? lj_strfmt_int(L, intV(o)) : lj_strfmt_num(L, o);
363}
364
365#if LJ_HASJIT
366/* Convert char value to string. */
367GCstr * LJ_FASTCALL lj_strfmt_char(lua_State *L, int c)
368{
369 char buf[1];
370 buf[0] = c;
371 return lj_str_new(L, buf, 1);
372}
373#endif
374
375/* Raw conversion of object to string. */
376GCstr * LJ_FASTCALL lj_strfmt_obj(lua_State *L, cTValue *o)
377{
378 if (tvisstr(o)) {
379 return strV(o);
380 } else if (tvisnumber(o)) {
381 return lj_strfmt_number(L, o);
382 } else if (tvisnil(o)) {
383 return lj_str_newlit(L, "nil");
384 } else if (tvisfalse(o)) {
385 return lj_str_newlit(L, "false");
386 } else if (tvistrue(o)) {
387 return lj_str_newlit(L, "true");
388 } else {
389 char buf[8+2+2+16], *p = buf;
390 p = lj_buf_wmem(p, lj_typename(o), (MSize)strlen(lj_typename(o)));
391 *p++ = ':'; *p++ = ' ';
392 if (tvisfunc(o) && isffunc(funcV(o))) {
393 p = lj_buf_wmem(p, "builtin#", 8);
394 p = lj_strfmt_wint(p, funcV(o)->c.ffid);
395 } else {
396 p = lj_strfmt_wptr(p, lj_obj_ptr(o));
397 }
398 return lj_str_new(L, buf, (size_t)(p - buf));
399 }
400}
401
402/* -- Internal string formatting ------------------------------------------ */
403
404/*
405** These functions are only used for lua_pushfstring(), lua_pushvfstring()
406** and for internal string formatting (e.g. error messages). Caveat: unlike
407** string.format(), only a limited subset of formats and flags are supported!
408**
409** LuaJIT has support for a couple more formats than Lua 5.1/5.2:
410** - %d %u %o %x with full formatting, 32 bit integers only.
411** - %f and other FP formats are really %.14g.
412** - %s %c %p without formatting.
413*/
414
415/* Push formatted message as a string object to Lua stack. va_list variant. */
416const char *lj_strfmt_pushvf(lua_State *L, const char *fmt, va_list argp)
417{
418 SBuf *sb = lj_buf_tmp_(L);
419 FormatState fs;
420 SFormat sf;
421 GCstr *str;
422 lj_strfmt_init(&fs, fmt, (MSize)strlen(fmt));
423 while ((sf = lj_strfmt_parse(&fs)) != STRFMT_EOF) {
424 switch (STRFMT_TYPE(sf)) {
425 case STRFMT_LIT:
426 lj_buf_putmem(sb, fs.str, fs.len);
427 break;
428 case STRFMT_INT:
429 lj_strfmt_putfxint(sb, sf, va_arg(argp, int32_t));
430 break;
431 case STRFMT_UINT:
432 lj_strfmt_putfxint(sb, sf, va_arg(argp, uint32_t));
433 break;
434 case STRFMT_NUM:
435 lj_strfmt_putfnum(sb, STRFMT_G14, va_arg(argp, lua_Number));
436 break;
437 case STRFMT_STR: {
438 const char *s = va_arg(argp, char *);
439 if (s == NULL) s = "(null)";
440 lj_buf_putmem(sb, s, (MSize)strlen(s));
441 break;
442 }
443 case STRFMT_CHAR:
444 lj_buf_putb(sb, va_arg(argp, int));
445 break;
446 case STRFMT_PTR:
447 lj_strfmt_putptr(sb, va_arg(argp, void *));
448 break;
449 case STRFMT_ERR:
450 default:
451 lj_buf_putb(sb, '?');
452 lua_assert(0);
453 break;
454 }
455 }
456 str = lj_buf_str(L, sb);
457 setstrV(L, L->top, str);
458 incr_top(L);
459 return strdata(str);
460}
461
462/* Push formatted message as a string object to Lua stack. Vararg variant. */
463const char *lj_strfmt_pushf(lua_State *L, const char *fmt, ...)
464{
465 const char *msg;
466 va_list argp;
467 va_start(argp, fmt);
468 msg = lj_strfmt_pushvf(L, fmt, argp);
469 va_end(argp);
470 return msg;
471}
472
diff --git a/src/lj_strfmt.h b/src/lj_strfmt.h
new file mode 100644
index 00000000..6e1d9017
--- /dev/null
+++ b/src/lj_strfmt.h
@@ -0,0 +1,125 @@
1/*
2** String formatting.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_STRFMT_H
7#define _LJ_STRFMT_H
8
9#include "lj_obj.h"
10
11typedef uint32_t SFormat; /* Format indicator. */
12
13/* Format parser state. */
14typedef struct FormatState {
15 const uint8_t *p; /* Current format string pointer. */
16 const uint8_t *e; /* End of format string. */
17 const char *str; /* Returned literal string. */
18 MSize len; /* Size of literal string. */
19} FormatState;
20
21/* Format types (max. 16). */
22typedef enum FormatType {
23 STRFMT_EOF, STRFMT_ERR, STRFMT_LIT,
24 STRFMT_INT, STRFMT_UINT, STRFMT_NUM, STRFMT_STR, STRFMT_CHAR, STRFMT_PTR
25} FormatType;
26
27/* Format subtypes (bits are reused). */
28#define STRFMT_T_HEX 0x0010 /* STRFMT_UINT */
29#define STRFMT_T_OCT 0x0020 /* STRFMT_UINT */
30#define STRFMT_T_FP_A 0x0000 /* STRFMT_NUM */
31#define STRFMT_T_FP_E 0x0010 /* STRFMT_NUM */
32#define STRFMT_T_FP_F 0x0020 /* STRFMT_NUM */
33#define STRFMT_T_FP_G 0x0030 /* STRFMT_NUM */
34#define STRFMT_T_QUOTED 0x0010 /* STRFMT_STR */
35
36/* Format flags. */
37#define STRFMT_F_LEFT 0x0100
38#define STRFMT_F_PLUS 0x0200
39#define STRFMT_F_ZERO 0x0400
40#define STRFMT_F_SPACE 0x0800
41#define STRFMT_F_ALT 0x1000
42#define STRFMT_F_UPPER 0x2000
43
44/* Format indicator fields. */
45#define STRFMT_SH_WIDTH 16
46#define STRFMT_SH_PREC 24
47
48#define STRFMT_TYPE(sf) ((FormatType)((sf) & 15))
49#define STRFMT_WIDTH(sf) (((sf) >> STRFMT_SH_WIDTH) & 255u)
50#define STRFMT_PREC(sf) ((((sf) >> STRFMT_SH_PREC) & 255u) - 1u)
51#define STRFMT_FP(sf) (((sf) >> 4) & 3)
52
53/* Formats for conversion characters. */
54#define STRFMT_A (STRFMT_NUM|STRFMT_T_FP_A)
55#define STRFMT_C (STRFMT_CHAR)
56#define STRFMT_D (STRFMT_INT)
57#define STRFMT_E (STRFMT_NUM|STRFMT_T_FP_E)
58#define STRFMT_F (STRFMT_NUM|STRFMT_T_FP_F)
59#define STRFMT_G (STRFMT_NUM|STRFMT_T_FP_G)
60#define STRFMT_I STRFMT_D
61#define STRFMT_O (STRFMT_UINT|STRFMT_T_OCT)
62#define STRFMT_P (STRFMT_PTR)
63#define STRFMT_Q (STRFMT_STR|STRFMT_T_QUOTED)
64#define STRFMT_S (STRFMT_STR)
65#define STRFMT_U (STRFMT_UINT)
66#define STRFMT_X (STRFMT_UINT|STRFMT_T_HEX)
67#define STRFMT_G14 (STRFMT_G | ((14+1) << STRFMT_SH_PREC))
68
69/* Maximum buffer sizes for conversions. */
70#define STRFMT_MAXBUF_XINT (1+22) /* '0' prefix + uint64_t in octal. */
71#define STRFMT_MAXBUF_INT (1+10) /* Sign + int32_t in decimal. */
72#define STRFMT_MAXBUF_NUM 32 /* Must correspond with STRFMT_G14. */
73#define STRFMT_MAXBUF_PTR (2+2*sizeof(ptrdiff_t)) /* "0x" + hex ptr. */
74
75/* Format parser. */
76LJ_FUNC SFormat LJ_FASTCALL lj_strfmt_parse(FormatState *fs);
77
78static LJ_AINLINE void lj_strfmt_init(FormatState *fs, const char *p, MSize len)
79{
80 fs->p = (const uint8_t *)p;
81 fs->e = (const uint8_t *)p + len;
82 lua_assert(*fs->e == 0); /* Must be NUL-terminated (may have NULs inside). */
83}
84
85/* Raw conversions. */
86LJ_FUNC char * LJ_FASTCALL lj_strfmt_wint(char *p, int32_t k);
87LJ_FUNC char * LJ_FASTCALL lj_strfmt_wptr(char *p, const void *v);
88LJ_FUNC char * LJ_FASTCALL lj_strfmt_wuleb128(char *p, uint32_t v);
89LJ_FUNC const char *lj_strfmt_wstrnum(lua_State *L, cTValue *o, MSize *lenp);
90
91/* Unformatted conversions to buffer. */
92LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putint(SBuf *sb, int32_t k);
93#if LJ_HASJIT
94LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putnum(SBuf *sb, cTValue *o);
95#endif
96LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putptr(SBuf *sb, const void *v);
97LJ_FUNC SBuf * LJ_FASTCALL lj_strfmt_putquoted(SBuf *sb, GCstr *str);
98
99/* Formatted conversions to buffer. */
100LJ_FUNC SBuf *lj_strfmt_putfxint(SBuf *sb, SFormat sf, uint64_t k);
101LJ_FUNC SBuf *lj_strfmt_putfnum_int(SBuf *sb, SFormat sf, lua_Number n);
102LJ_FUNC SBuf *lj_strfmt_putfnum_uint(SBuf *sb, SFormat sf, lua_Number n);
103LJ_FUNC SBuf *lj_strfmt_putfnum(SBuf *sb, SFormat, lua_Number n);
104LJ_FUNC SBuf *lj_strfmt_putfchar(SBuf *sb, SFormat, int32_t c);
105LJ_FUNC SBuf *lj_strfmt_putfstr(SBuf *sb, SFormat, GCstr *str);
106
107/* Conversions to strings. */
108LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_int(lua_State *L, int32_t k);
109LJ_FUNCA GCstr * LJ_FASTCALL lj_strfmt_num(lua_State *L, cTValue *o);
110LJ_FUNCA GCstr * LJ_FASTCALL lj_strfmt_number(lua_State *L, cTValue *o);
111#if LJ_HASJIT
112LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_char(lua_State *L, int c);
113#endif
114LJ_FUNC GCstr * LJ_FASTCALL lj_strfmt_obj(lua_State *L, cTValue *o);
115
116/* Internal string formatting. */
117LJ_FUNC const char *lj_strfmt_pushvf(lua_State *L, const char *fmt,
118 va_list argp);
119LJ_FUNC const char *lj_strfmt_pushf(lua_State *L, const char *fmt, ...)
120#ifdef __GNUC__
121 __attribute__ ((format (printf, 2, 3)))
122#endif
123 ;
124
125#endif
diff --git a/src/lj_strfmt_num.c b/src/lj_strfmt_num.c
new file mode 100644
index 00000000..9271f68a
--- /dev/null
+++ b/src/lj_strfmt_num.c
@@ -0,0 +1,592 @@
1/*
2** String formatting for floating-point numbers.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4** Contributed by Peter Cawley.
5*/
6
7#include <stdio.h>
8
9#define lj_strfmt_num_c
10#define LUA_CORE
11
12#include "lj_obj.h"
13#include "lj_buf.h"
14#include "lj_str.h"
15#include "lj_strfmt.h"
16
17/* -- Precomputed tables -------------------------------------------------- */
18
19/* Rescale factors to push the exponent of a number towards zero. */
20#define RESCALE_EXPONENTS(P, N) \
21 P(308), P(289), P(270), P(250), P(231), P(212), P(193), P(173), P(154), \
22 P(135), P(115), P(96), P(77), P(58), P(38), P(0), P(0), P(0), N(39), N(58), \
23 N(77), N(96), N(116), N(135), N(154), N(174), N(193), N(212), N(231), \
24 N(251), N(270), N(289)
25
26#define ONE_E_P(X) 1e+0 ## X
27#define ONE_E_N(X) 1e-0 ## X
28static const int16_t rescale_e[] = { RESCALE_EXPONENTS(-, +) };
29static const double rescale_n[] = { RESCALE_EXPONENTS(ONE_E_P, ONE_E_N) };
30#undef ONE_E_N
31#undef ONE_E_P
32
33/*
34** For p in range -70 through 57, this table encodes pairs (m, e) such that
35** 4*2^p <= (uint8_t)m*10^e, and is the smallest value for which this holds.
36*/
37static const int8_t four_ulp_m_e[] = {
38 34, -21, 68, -21, 14, -20, 28, -20, 55, -20, 2, -19, 3, -19, 5, -19, 9, -19,
39 -82, -18, 35, -18, 7, -17, -117, -17, 28, -17, 56, -17, 112, -16, -33, -16,
40 45, -16, 89, -16, -78, -15, 36, -15, 72, -15, -113, -14, 29, -14, 57, -14,
41 114, -13, -28, -13, 46, -13, 91, -12, -74, -12, 37, -12, 73, -12, 15, -11, 3,
42 -11, 59, -11, 2, -10, 3, -10, 5, -10, 1, -9, -69, -9, 38, -9, 75, -9, 15, -7,
43 3, -7, 6, -7, 12, -6, -17, -7, 48, -7, 96, -7, -65, -6, 39, -6, 77, -6, -103,
44 -5, 31, -5, 62, -5, 123, -4, -11, -4, 49, -4, 98, -4, -60, -3, 4, -2, 79, -3,
45 16, -2, 32, -2, 63, -2, 2, -1, 25, 0, 5, 1, 1, 2, 2, 2, 4, 2, 8, 2, 16, 2,
46 32, 2, 64, 2, -128, 2, 26, 2, 52, 2, 103, 3, -51, 3, 41, 4, 82, 4, -92, 4,
47 33, 4, 66, 4, -124, 5, 27, 5, 53, 5, 105, 6, 21, 6, 42, 6, 84, 6, 17, 7, 34,
48 7, 68, 7, 2, 8, 3, 8, 6, 8, 108, 9, -41, 9, 43, 10, 86, 9, -84, 10, 35, 10,
49 69, 10, -118, 11, 28, 11, 55, 12, 11, 13, 22, 13, 44, 13, 88, 13, -80, 13,
50 36, 13, 71, 13, -115, 14, 29, 14, 57, 14, 113, 15, -30, 15, 46, 15, 91, 15,
51 19, 16, 37, 16, 73, 16, 2, 17, 3, 17, 6, 17
52};
53
54/* min(2^32-1, 10^e-1) for e in range 0 through 10 */
55static uint32_t ndigits_dec_threshold[] = {
56 0, 9U, 99U, 999U, 9999U, 99999U, 999999U,
57 9999999U, 99999999U, 999999999U, 0xffffffffU
58};
59
60/* -- Helper functions ---------------------------------------------------- */
61
62/* Compute the number of digits in the decimal representation of x. */
63static MSize ndigits_dec(uint32_t x)
64{
65 MSize t = ((lj_fls(x | 1) * 77) >> 8) + 1; /* 2^8/77 is roughly log2(10) */
66 return t + (x > ndigits_dec_threshold[t]);
67}
68
69#define WINT_R(x, sh, sc) \
70 { uint32_t d = (x*(((1<<sh)+sc-1)/sc))>>sh; x -= d*sc; *p++ = (char)('0'+d); }
71
72/* Write 9-digit unsigned integer to buffer. */
73static char *lj_strfmt_wuint9(char *p, uint32_t u)
74{
75 uint32_t v = u / 10000, w;
76 u -= v * 10000;
77 w = v / 10000;
78 v -= w * 10000;
79 *p++ = (char)('0'+w);
80 WINT_R(v, 23, 1000)
81 WINT_R(v, 12, 100)
82 WINT_R(v, 10, 10)
83 *p++ = (char)('0'+v);
84 WINT_R(u, 23, 1000)
85 WINT_R(u, 12, 100)
86 WINT_R(u, 10, 10)
87 *p++ = (char)('0'+u);
88 return p;
89}
90#undef WINT_R
91
92/* -- Extended precision arithmetic --------------------------------------- */
93
94/*
95** The "nd" format is a fixed-precision decimal representation for numbers. It
96** consists of up to 64 uint32_t values, with each uint32_t storing a value
97** in the range [0, 1e9). A number in "nd" format consists of three variables:
98**
99** uint32_t nd[64];
100** uint32_t ndlo;
101** uint32_t ndhi;
102**
103** The integral part of the number is stored in nd[0 ... ndhi], the value of
104** which is sum{i in [0, ndhi] | nd[i] * 10^(9*i)}. If the fractional part of
105** the number is zero, ndlo is zero. Otherwise, the fractional part is stored
106** in nd[ndlo ... 63], the value of which is taken to be
107** sum{i in [ndlo, 63] | nd[i] * 10^(9*(i-64))}.
108**
109** If the array part had 128 elements rather than 64, then every double would
110** have an exact representation in "nd" format. With 64 elements, all integral
111** doubles have an exact representation, and all non-integral doubles have
112** enough digits to make both %.99e and %.99f do the right thing.
113*/
114
115#if LJ_64
116#define ND_MUL2K_MAX_SHIFT 29
117#define ND_MUL2K_DIV1E9(val) ((uint32_t)((val) / 1000000000))
118#else
119#define ND_MUL2K_MAX_SHIFT 11
120#define ND_MUL2K_DIV1E9(val) ((uint32_t)((val) >> 9) / 1953125)
121#endif
122
123/* Multiply nd by 2^k and add carry_in (ndlo is assumed to be zero). */
124static uint32_t nd_mul2k(uint32_t* nd, uint32_t ndhi, uint32_t k,
125 uint32_t carry_in, SFormat sf)
126{
127 uint32_t i, ndlo = 0, start = 1;
128 /* Performance hacks. */
129 if (k > ND_MUL2K_MAX_SHIFT*2 && STRFMT_FP(sf) != STRFMT_FP(STRFMT_T_FP_F)) {
130 start = ndhi - (STRFMT_PREC(sf) + 17) / 8;
131 }
132 /* Real logic. */
133 while (k >= ND_MUL2K_MAX_SHIFT) {
134 for (i = ndlo; i <= ndhi; i++) {
135 uint64_t val = ((uint64_t)nd[i] << ND_MUL2K_MAX_SHIFT) | carry_in;
136 carry_in = ND_MUL2K_DIV1E9(val);
137 nd[i] = (uint32_t)val - carry_in * 1000000000;
138 }
139 if (carry_in) {
140 nd[++ndhi] = carry_in; carry_in = 0;
141 if (start++ == ndlo) ++ndlo;
142 }
143 k -= ND_MUL2K_MAX_SHIFT;
144 }
145 if (k) {
146 for (i = ndlo; i <= ndhi; i++) {
147 uint64_t val = ((uint64_t)nd[i] << k) | carry_in;
148 carry_in = ND_MUL2K_DIV1E9(val);
149 nd[i] = (uint32_t)val - carry_in * 1000000000;
150 }
151 if (carry_in) nd[++ndhi] = carry_in;
152 }
153 return ndhi;
154}
155
156/* Divide nd by 2^k (ndlo is assumed to be zero). */
157static uint32_t nd_div2k(uint32_t* nd, uint32_t ndhi, uint32_t k, SFormat sf)
158{
159 uint32_t ndlo = 0, stop1 = ~0, stop2 = ~0;
160 /* Performance hacks. */
161 if (!ndhi) {
162 if (!nd[0]) {
163 return 0;
164 } else {
165 uint32_t s = lj_ffs(nd[0]);
166 if (s >= k) { nd[0] >>= k; return 0; }
167 nd[0] >>= s; k -= s;
168 }
169 }
170 if (k > 18) {
171 if (STRFMT_FP(sf) == STRFMT_FP(STRFMT_T_FP_F)) {
172 stop1 = 63 - (int32_t)STRFMT_PREC(sf) / 9;
173 } else {
174 int32_t floorlog2 = ndhi * 29 + lj_fls(nd[ndhi]) - k;
175 int32_t floorlog10 = (int32_t)(floorlog2 * 0.30102999566398114);
176 stop1 = 62 + (floorlog10 - (int32_t)STRFMT_PREC(sf)) / 9;
177 stop2 = 61 + ndhi - (int32_t)STRFMT_PREC(sf) / 8;
178 }
179 }
180 /* Real logic. */
181 while (k >= 9) {
182 uint32_t i = ndhi, carry = 0;
183 for (;;) {
184 uint32_t val = nd[i];
185 nd[i] = (val >> 9) + carry;
186 carry = (val & 0x1ff) * 1953125;
187 if (i == ndlo) break;
188 i = (i - 1) & 0x3f;
189 }
190 if (ndlo != stop1 && ndlo != stop2) {
191 if (carry) { ndlo = (ndlo - 1) & 0x3f; nd[ndlo] = carry; }
192 if (!nd[ndhi]) { ndhi = (ndhi - 1) & 0x3f; stop2--; }
193 } else if (!nd[ndhi]) {
194 if (ndhi != ndlo) { ndhi = (ndhi - 1) & 0x3f; stop2--; }
195 else return ndlo;
196 }
197 k -= 9;
198 }
199 if (k) {
200 uint32_t mask = (1U << k) - 1, mul = 1000000000 >> k, i = ndhi, carry = 0;
201 for (;;) {
202 uint32_t val = nd[i];
203 nd[i] = (val >> k) + carry;
204 carry = (val & mask) * mul;
205 if (i == ndlo) break;
206 i = (i - 1) & 0x3f;
207 }
208 if (carry) { ndlo = (ndlo - 1) & 0x3f; nd[ndlo] = carry; }
209 }
210 return ndlo;
211}
212
213/* Add m*10^e to nd (assumes ndlo <= e/9 <= ndhi and 0 <= m <= 9). */
214static uint32_t nd_add_m10e(uint32_t* nd, uint32_t ndhi, uint8_t m, int32_t e)
215{
216 uint32_t i, carry;
217 if (e >= 0) {
218 i = (uint32_t)e/9;
219 carry = m * (ndigits_dec_threshold[e - (int32_t)i*9] + 1);
220 } else {
221 int32_t f = (e-8)/9;
222 i = (uint32_t)(64 + f);
223 carry = m * (ndigits_dec_threshold[e - f*9] + 1);
224 }
225 for (;;) {
226 uint32_t val = nd[i] + carry;
227 if (LJ_UNLIKELY(val >= 1000000000)) {
228 val -= 1000000000;
229 nd[i] = val;
230 if (LJ_UNLIKELY(i == ndhi)) {
231 ndhi = (ndhi + 1) & 0x3f;
232 nd[ndhi] = 1;
233 break;
234 }
235 carry = 1;
236 i = (i + 1) & 0x3f;
237 } else {
238 nd[i] = val;
239 break;
240 }
241 }
242 return ndhi;
243}
244
245/* Test whether two "nd" values are equal in their most significant digits. */
246static int nd_similar(uint32_t* nd, uint32_t ndhi, uint32_t* ref, MSize hilen,
247 MSize prec)
248{
249 char nd9[9], ref9[9];
250 if (hilen <= prec) {
251 if (LJ_UNLIKELY(nd[ndhi] != *ref)) return 0;
252 prec -= hilen; ref--; ndhi = (ndhi - 1) & 0x3f;
253 if (prec >= 9) {
254 if (LJ_UNLIKELY(nd[ndhi] != *ref)) return 0;
255 prec -= 9; ref--; ndhi = (ndhi - 1) & 0x3f;
256 }
257 } else {
258 prec -= hilen - 9;
259 }
260 lua_assert(prec < 9);
261 lj_strfmt_wuint9(nd9, nd[ndhi]);
262 lj_strfmt_wuint9(ref9, *ref);
263 return !memcmp(nd9, ref9, prec) && (nd9[prec] < '5') == (ref9[prec] < '5');
264}
265
266/* -- Formatted conversions to buffer ------------------------------------- */
267
268/* Write formatted floating-point number to either sb or p. */
269static char *lj_strfmt_wfnum(SBuf *sb, SFormat sf, lua_Number n, char *p)
270{
271 MSize width = STRFMT_WIDTH(sf), prec = STRFMT_PREC(sf), len;
272 TValue t;
273 t.n = n;
274 if (LJ_UNLIKELY((t.u32.hi << 1) >= 0xffe00000)) {
275 /* Handle non-finite values uniformly for %a, %e, %f, %g. */
276 int prefix = 0, ch = (sf & STRFMT_F_UPPER) ? 0x202020 : 0;
277 if (((t.u32.hi & 0x000fffff) | t.u32.lo) != 0) {
278 ch ^= ('n' << 16) | ('a' << 8) | 'n';
279 if ((sf & STRFMT_F_SPACE)) prefix = ' ';
280 } else {
281 ch ^= ('i' << 16) | ('n' << 8) | 'f';
282 if ((t.u32.hi & 0x80000000)) prefix = '-';
283 else if ((sf & STRFMT_F_PLUS)) prefix = '+';
284 else if ((sf & STRFMT_F_SPACE)) prefix = ' ';
285 }
286 len = 3 + (prefix != 0);
287 if (!p) p = lj_buf_more(sb, width > len ? width : len);
288 if (!(sf & STRFMT_F_LEFT)) while (width-- > len) *p++ = ' ';
289 if (prefix) *p++ = prefix;
290 *p++ = (char)(ch >> 16); *p++ = (char)(ch >> 8); *p++ = (char)ch;
291 } else if (STRFMT_FP(sf) == STRFMT_FP(STRFMT_T_FP_A)) {
292 /* %a */
293 const char *hexdig = (sf & STRFMT_F_UPPER) ? "0123456789ABCDEFPX"
294 : "0123456789abcdefpx";
295 int32_t e = (t.u32.hi >> 20) & 0x7ff;
296 char prefix = 0, eprefix = '+';
297 if (t.u32.hi & 0x80000000) prefix = '-';
298 else if ((sf & STRFMT_F_PLUS)) prefix = '+';
299 else if ((sf & STRFMT_F_SPACE)) prefix = ' ';
300 t.u32.hi &= 0xfffff;
301 if (e) {
302 t.u32.hi |= 0x100000;
303 e -= 1023;
304 } else if (t.u32.lo | t.u32.hi) {
305 /* Non-zero denormal - normalise it. */
306 uint32_t shift = t.u32.hi ? 20-lj_fls(t.u32.hi) : 52-lj_fls(t.u32.lo);
307 e = -1022 - shift;
308 t.u64 <<= shift;
309 }
310 /* abs(n) == t.u64 * 2^(e - 52) */
311 /* If n != 0, bit 52 of t.u64 is set, and is the highest set bit. */
312 if ((int32_t)prec < 0) {
313 /* Default precision: use smallest precision giving exact result. */
314 prec = t.u32.lo ? 13-lj_ffs(t.u32.lo)/4 : 5-lj_ffs(t.u32.hi|0x100000)/4;
315 } else if (prec < 13) {
316 /* Precision is sufficiently low as to maybe require rounding. */
317 t.u64 += (((uint64_t)1) << (51 - prec*4));
318 }
319 if (e < 0) {
320 eprefix = '-';
321 e = -e;
322 }
323 len = 5 + ndigits_dec((uint32_t)e) + prec + (prefix != 0)
324 + ((prec | (sf & STRFMT_F_ALT)) != 0);
325 if (!p) p = lj_buf_more(sb, width > len ? width : len);
326 if (!(sf & (STRFMT_F_LEFT | STRFMT_F_ZERO))) {
327 while (width-- > len) *p++ = ' ';
328 }
329 if (prefix) *p++ = prefix;
330 *p++ = '0';
331 *p++ = hexdig[17]; /* x or X */
332 if ((sf & (STRFMT_F_LEFT | STRFMT_F_ZERO)) == STRFMT_F_ZERO) {
333 while (width-- > len) *p++ = '0';
334 }
335 *p++ = '0' + (t.u32.hi >> 20); /* Usually '1', sometimes '0' or '2'. */
336 if ((prec | (sf & STRFMT_F_ALT))) {
337 /* Emit fractional part. */
338 char *q = p + 1 + prec;
339 *p = '.';
340 if (prec < 13) t.u64 >>= (52 - prec*4);
341 else while (prec > 13) p[prec--] = '0';
342 while (prec) { p[prec--] = hexdig[t.u64 & 15]; t.u64 >>= 4; }
343 p = q;
344 }
345 *p++ = hexdig[16]; /* p or P */
346 *p++ = eprefix; /* + or - */
347 p = lj_strfmt_wint(p, e);
348 } else {
349 /* %e or %f or %g - begin by converting n to "nd" format. */
350 uint32_t nd[64];
351 uint32_t ndhi = 0, ndlo, i;
352 int32_t e = (t.u32.hi >> 20) & 0x7ff, ndebias = 0;
353 char prefix = 0, *q;
354 if (t.u32.hi & 0x80000000) prefix = '-';
355 else if ((sf & STRFMT_F_PLUS)) prefix = '+';
356 else if ((sf & STRFMT_F_SPACE)) prefix = ' ';
357 prec += ((int32_t)prec >> 31) & 7; /* Default precision is 6. */
358 if (STRFMT_FP(sf) == STRFMT_FP(STRFMT_T_FP_G)) {
359 /* %g - decrement precision if non-zero (to make it like %e). */
360 prec--;
361 prec ^= (uint32_t)((int32_t)prec >> 31);
362 }
363 if ((sf & STRFMT_T_FP_E) && prec < 14 && n != 0) {
364 /* Precision is sufficiently low that rescaling will probably work. */
365 if ((ndebias = rescale_e[e >> 6])) {
366 t.n = n * rescale_n[e >> 6];
367 if (LJ_UNLIKELY(!e)) t.n *= 1e10, ndebias -= 10;
368 t.u64 -= 2; /* Convert 2ulp below (later we convert 2ulp above). */
369 nd[0] = 0x100000 | (t.u32.hi & 0xfffff);
370 e = ((t.u32.hi >> 20) & 0x7ff) - 1075 - (ND_MUL2K_MAX_SHIFT < 29);
371 goto load_t_lo; rescale_failed:
372 t.n = n;
373 e = (t.u32.hi >> 20) & 0x7ff;
374 ndebias = ndhi = 0;
375 }
376 }
377 nd[0] = t.u32.hi & 0xfffff;
378 if (e == 0) e++; else nd[0] |= 0x100000;
379 e -= 1043;
380 if (t.u32.lo) {
381 e -= 32 + (ND_MUL2K_MAX_SHIFT < 29); load_t_lo:
382#if ND_MUL2K_MAX_SHIFT >= 29
383 nd[0] = (nd[0] << 3) | (t.u32.lo >> 29);
384 ndhi = nd_mul2k(nd, ndhi, 29, t.u32.lo & 0x1fffffff, sf);
385#elif ND_MUL2K_MAX_SHIFT >= 11
386 ndhi = nd_mul2k(nd, ndhi, 11, t.u32.lo >> 21, sf);
387 ndhi = nd_mul2k(nd, ndhi, 11, (t.u32.lo >> 10) & 0x7ff, sf);
388 ndhi = nd_mul2k(nd, ndhi, 11, (t.u32.lo << 1) & 0x7ff, sf);
389#else
390#error "ND_MUL2K_MAX_SHIFT too small"
391#endif
392 }
393 if (e >= 0) {
394 ndhi = nd_mul2k(nd, ndhi, (uint32_t)e, 0, sf);
395 ndlo = 0;
396 } else {
397 ndlo = nd_div2k(nd, ndhi, (uint32_t)-e, sf);
398 if (ndhi && !nd[ndhi]) ndhi--;
399 }
400 /* abs(n) == nd * 10^ndebias (for slightly loose interpretation of ==) */
401 if ((sf & STRFMT_T_FP_E)) {
402 /* %e or %g - assume %e and start by calculating nd's exponent (nde). */
403 char eprefix = '+';
404 int32_t nde = -1;
405 MSize hilen;
406 if (ndlo && !nd[ndhi]) {
407 ndhi = 64; do {} while (!nd[--ndhi]);
408 nde -= 64 * 9;
409 }
410 hilen = ndigits_dec(nd[ndhi]);
411 nde += ndhi * 9 + hilen;
412 if (ndebias) {
413 /*
414 ** Rescaling was performed, but this introduced some error, and might
415 ** have pushed us across a rounding boundary. We check whether this
416 ** error affected the result by introducing even more error (2ulp in
417 ** either direction), and seeing whether a roundary boundary was
418 ** crossed. Having already converted the -2ulp case, we save off its
419 ** most significant digits, convert the +2ulp case, and compare them.
420 */
421 int32_t eidx = e + 70 + (ND_MUL2K_MAX_SHIFT < 29)
422 + (t.u32.lo >= 0xfffffffe && !(~t.u32.hi << 12));
423 const int8_t *m_e = four_ulp_m_e + eidx * 2;
424 lua_assert(0 <= eidx && eidx < 128);
425 nd[33] = nd[ndhi];
426 nd[32] = nd[(ndhi - 1) & 0x3f];
427 nd[31] = nd[(ndhi - 2) & 0x3f];
428 nd_add_m10e(nd, ndhi, (uint8_t)*m_e, m_e[1]);
429 if (LJ_UNLIKELY(!nd_similar(nd, ndhi, nd + 33, hilen, prec + 1))) {
430 goto rescale_failed;
431 }
432 }
433 if ((int32_t)(prec - nde) < (0x3f & -(int32_t)ndlo) * 9) {
434 /* Precision is sufficiently low as to maybe require rounding. */
435 ndhi = nd_add_m10e(nd, ndhi, 5, nde - prec - 1);
436 nde += (hilen != ndigits_dec(nd[ndhi]));
437 }
438 nde += ndebias;
439 if ((sf & STRFMT_T_FP_F)) {
440 /* %g */
441 if ((int32_t)prec >= nde && nde >= -4) {
442 if (nde < 0) ndhi = 0;
443 prec -= nde;
444 goto g_format_like_f;
445 } else if (!(sf & STRFMT_F_ALT) && prec && width > 5) {
446 /* Decrease precision in order to strip trailing zeroes. */
447 char tail[9];
448 uint32_t maxprec = hilen - 1 + ((ndhi - ndlo) & 0x3f) * 9;
449 if (prec >= maxprec) prec = maxprec;
450 else ndlo = (ndhi - (((int32_t)(prec - hilen) + 9) / 9)) & 0x3f;
451 i = prec - hilen - (((ndhi - ndlo) & 0x3f) * 9) + 10;
452 lj_strfmt_wuint9(tail, nd[ndlo]);
453 while (prec && tail[--i] == '0') {
454 prec--;
455 if (!i) {
456 if (ndlo == ndhi) { prec = 0; break; }
457 lj_strfmt_wuint9(tail, nd[++ndlo]);
458 i = 9;
459 }
460 }
461 }
462 }
463 if (nde < 0) {
464 /* Make nde non-negative. */
465 eprefix = '-';
466 nde = -nde;
467 }
468 len = 3 + prec + (prefix != 0) + ndigits_dec((uint32_t)nde) + (nde < 10)
469 + ((prec | (sf & STRFMT_F_ALT)) != 0);
470 if (!p) p = lj_buf_more(sb, (width > len ? width : len) + 5);
471 if (!(sf & (STRFMT_F_LEFT | STRFMT_F_ZERO))) {
472 while (width-- > len) *p++ = ' ';
473 }
474 if (prefix) *p++ = prefix;
475 if ((sf & (STRFMT_F_LEFT | STRFMT_F_ZERO)) == STRFMT_F_ZERO) {
476 while (width-- > len) *p++ = '0';
477 }
478 q = lj_strfmt_wint(p + 1, nd[ndhi]);
479 p[0] = p[1]; /* Put leading digit in the correct place. */
480 if ((prec | (sf & STRFMT_F_ALT))) {
481 /* Emit fractional part. */
482 p[1] = '.'; p += 2;
483 prec -= (MSize)(q - p); p = q; /* Account for digits already emitted. */
484 /* Then emit chunks of 9 digits (this may emit 8 digits too many). */
485 for (i = ndhi; (int32_t)prec > 0 && i != ndlo; prec -= 9) {
486 i = (i - 1) & 0x3f;
487 p = lj_strfmt_wuint9(p, nd[i]);
488 }
489 if ((sf & STRFMT_T_FP_F) && !(sf & STRFMT_F_ALT)) {
490 /* %g (and not %#g) - strip trailing zeroes. */
491 p += (int32_t)prec & ((int32_t)prec >> 31);
492 while (p[-1] == '0') p--;
493 if (p[-1] == '.') p--;
494 } else {
495 /* %e (or %#g) - emit trailing zeroes. */
496 while ((int32_t)prec > 0) { *p++ = '0'; prec--; }
497 p += (int32_t)prec;
498 }
499 } else {
500 p++;
501 }
502 *p++ = (sf & STRFMT_F_UPPER) ? 'E' : 'e';
503 *p++ = eprefix; /* + or - */
504 if (nde < 10) *p++ = '0'; /* Always at least two digits of exponent. */
505 p = lj_strfmt_wint(p, nde);
506 } else {
507 /* %f (or, shortly, %g in %f style) */
508 if (prec < (MSize)(0x3f & -(int32_t)ndlo) * 9) {
509 /* Precision is sufficiently low as to maybe require rounding. */
510 ndhi = nd_add_m10e(nd, ndhi, 5, 0 - prec - 1);
511 }
512 g_format_like_f:
513 if ((sf & STRFMT_T_FP_E) && !(sf & STRFMT_F_ALT) && prec && width) {
514 /* Decrease precision in order to strip trailing zeroes. */
515 if (ndlo) {
516 /* nd has a fractional part; we need to look at its digits. */
517 char tail[9];
518 uint32_t maxprec = (64 - ndlo) * 9;
519 if (prec >= maxprec) prec = maxprec;
520 else ndlo = 64 - (prec + 8) / 9;
521 i = prec - ((63 - ndlo) * 9);
522 lj_strfmt_wuint9(tail, nd[ndlo]);
523 while (prec && tail[--i] == '0') {
524 prec--;
525 if (!i) {
526 if (ndlo == 63) { prec = 0; break; }
527 lj_strfmt_wuint9(tail, nd[++ndlo]);
528 i = 9;
529 }
530 }
531 } else {
532 /* nd has no fractional part, so precision goes straight to zero. */
533 prec = 0;
534 }
535 }
536 len = ndhi * 9 + ndigits_dec(nd[ndhi]) + prec + (prefix != 0)
537 + ((prec | (sf & STRFMT_F_ALT)) != 0);
538 if (!p) p = lj_buf_more(sb, (width > len ? width : len) + 8);
539 if (!(sf & (STRFMT_F_LEFT | STRFMT_F_ZERO))) {
540 while (width-- > len) *p++ = ' ';
541 }
542 if (prefix) *p++ = prefix;
543 if ((sf & (STRFMT_F_LEFT | STRFMT_F_ZERO)) == STRFMT_F_ZERO) {
544 while (width-- > len) *p++ = '0';
545 }
546 /* Emit integer part. */
547 p = lj_strfmt_wint(p, nd[ndhi]);
548 i = ndhi;
549 while (i) p = lj_strfmt_wuint9(p, nd[--i]);
550 if ((prec | (sf & STRFMT_F_ALT))) {
551 /* Emit fractional part. */
552 *p++ = '.';
553 /* Emit chunks of 9 digits (this may emit 8 digits too many). */
554 while ((int32_t)prec > 0 && i != ndlo) {
555 i = (i - 1) & 0x3f;
556 p = lj_strfmt_wuint9(p, nd[i]);
557 prec -= 9;
558 }
559 if ((sf & STRFMT_T_FP_E) && !(sf & STRFMT_F_ALT)) {
560 /* %g (and not %#g) - strip trailing zeroes. */
561 p += (int32_t)prec & ((int32_t)prec >> 31);
562 while (p[-1] == '0') p--;
563 if (p[-1] == '.') p--;
564 } else {
565 /* %f (or %#g) - emit trailing zeroes. */
566 while ((int32_t)prec > 0) { *p++ = '0'; prec--; }
567 p += (int32_t)prec;
568 }
569 }
570 }
571 }
572 if ((sf & STRFMT_F_LEFT)) while (width-- > len) *p++ = ' ';
573 return p;
574}
575
576/* Add formatted floating-point number to buffer. */
577SBuf *lj_strfmt_putfnum(SBuf *sb, SFormat sf, lua_Number n)
578{
579 setsbufP(sb, lj_strfmt_wfnum(sb, sf, n, NULL));
580 return sb;
581}
582
583/* -- Conversions to strings ---------------------------------------------- */
584
585/* Convert number to string. */
586GCstr * LJ_FASTCALL lj_strfmt_num(lua_State *L, cTValue *o)
587{
588 char buf[STRFMT_MAXBUF_NUM];
589 MSize len = (MSize)(lj_strfmt_wfnum(NULL, STRFMT_G14, o->n, buf) - buf);
590 return lj_str_new(L, buf, len);
591}
592
diff --git a/src/lj_strscan.c b/src/lj_strscan.c
index f1e34a3d..f5f35c96 100644
--- a/src/lj_strscan.c
+++ b/src/lj_strscan.c
@@ -140,7 +140,7 @@ static StrScanFmt strscan_hex(const uint8_t *p, TValue *o,
140 break; 140 break;
141 } 141 }
142 142
143 /* Reduce range then convert to double. */ 143 /* Reduce range, then convert to double. */
144 if ((x & U64x(c0000000,0000000))) { x = (x >> 2) | (x & 3); ex2 += 2; } 144 if ((x & U64x(c0000000,0000000))) { x = (x >> 2) | (x & 3); ex2 += 2; }
145 strscan_double(x, o, ex2, neg); 145 strscan_double(x, o, ex2, neg);
146 return fmt; 146 return fmt;
@@ -326,6 +326,49 @@ static StrScanFmt strscan_dec(const uint8_t *p, TValue *o,
326 return fmt; 326 return fmt;
327} 327}
328 328
329/* Parse binary number. */
330static StrScanFmt strscan_bin(const uint8_t *p, TValue *o,
331 StrScanFmt fmt, uint32_t opt,
332 int32_t ex2, int32_t neg, uint32_t dig)
333{
334 uint64_t x = 0;
335 uint32_t i;
336
337 if (ex2 || dig > 64) return STRSCAN_ERROR;
338
339 /* Scan binary digits. */
340 for (i = dig; i; i--, p++) {
341 if ((*p & ~1) != '0') return STRSCAN_ERROR;
342 x = (x << 1) | (*p & 1);
343 }
344
345 /* Format-specific handling. */
346 switch (fmt) {
347 case STRSCAN_INT:
348 if (!(opt & STRSCAN_OPT_TONUM) && x < 0x80000000u+neg) {
349 o->i = neg ? -(int32_t)x : (int32_t)x;
350 return STRSCAN_INT; /* Fast path for 32 bit integers. */
351 }
352 if (!(opt & STRSCAN_OPT_C)) { fmt = STRSCAN_NUM; break; }
353 /* fallthrough */
354 case STRSCAN_U32:
355 if (dig > 32) return STRSCAN_ERROR;
356 o->i = neg ? -(int32_t)x : (int32_t)x;
357 return STRSCAN_U32;
358 case STRSCAN_I64:
359 case STRSCAN_U64:
360 o->u64 = neg ? (uint64_t)-(int64_t)x : x;
361 return fmt;
362 default:
363 break;
364 }
365
366 /* Reduce range, then convert to double. */
367 if ((x & U64x(c0000000,0000000))) { x = (x >> 2) | (x & 3); ex2 += 2; }
368 strscan_double(x, o, ex2, neg);
369 return fmt;
370}
371
329/* Scan string containing a number. Returns format. Returns value in o. */ 372/* Scan string containing a number. Returns format. Returns value in o. */
330StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt) 373StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt)
331{ 374{
@@ -364,8 +407,12 @@ StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt)
364 407
365 /* Determine base and skip leading zeros. */ 408 /* Determine base and skip leading zeros. */
366 if (LJ_UNLIKELY(*p <= '0')) { 409 if (LJ_UNLIKELY(*p <= '0')) {
367 if (*p == '0' && casecmp(p[1], 'x')) 410 if (*p == '0') {
368 base = 16, cmask = LJ_CHAR_XDIGIT, p += 2; 411 if (casecmp(p[1], 'x'))
412 base = 16, cmask = LJ_CHAR_XDIGIT, p += 2;
413 else if (casecmp(p[1], 'b'))
414 base = 2, cmask = LJ_CHAR_DIGIT, p += 2;
415 }
369 for ( ; ; p++) { 416 for ( ; ; p++) {
370 if (*p == '0') { 417 if (*p == '0') {
371 hasdig = 1; 418 hasdig = 1;
@@ -403,7 +450,7 @@ StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt)
403 } 450 }
404 451
405 /* Parse exponent. */ 452 /* Parse exponent. */
406 if (casecmp(*p, (uint32_t)(base == 16 ? 'p' : 'e'))) { 453 if (base >= 10 && casecmp(*p, (uint32_t)(base == 16 ? 'p' : 'e'))) {
407 uint32_t xx; 454 uint32_t xx;
408 int negx = 0; 455 int negx = 0;
409 fmt = STRSCAN_NUM; p++; 456 fmt = STRSCAN_NUM; p++;
@@ -460,6 +507,8 @@ StrScanFmt lj_strscan_scan(const uint8_t *p, TValue *o, uint32_t opt)
460 return strscan_oct(sp, o, fmt, neg, dig); 507 return strscan_oct(sp, o, fmt, neg, dig);
461 if (base == 16) 508 if (base == 16)
462 fmt = strscan_hex(sp, o, fmt, opt, ex, neg, dig); 509 fmt = strscan_hex(sp, o, fmt, opt, ex, neg, dig);
510 else if (base == 2)
511 fmt = strscan_bin(sp, o, fmt, opt, ex, neg, dig);
463 else 512 else
464 fmt = strscan_dec(sp, o, fmt, opt, ex, neg, dig); 513 fmt = strscan_dec(sp, o, fmt, opt, ex, neg, dig);
465 514
diff --git a/src/lj_tab.c b/src/lj_tab.c
index 50f447e8..47c0cfd3 100644
--- a/src/lj_tab.c
+++ b/src/lj_tab.c
@@ -28,8 +28,12 @@ static LJ_AINLINE Node *hashmask(const GCtab *t, uint32_t hash)
28 28
29#define hashlohi(t, lo, hi) hashmask((t), hashrot((lo), (hi))) 29#define hashlohi(t, lo, hi) hashmask((t), hashrot((lo), (hi)))
30#define hashnum(t, o) hashlohi((t), (o)->u32.lo, ((o)->u32.hi << 1)) 30#define hashnum(t, o) hashlohi((t), (o)->u32.lo, ((o)->u32.hi << 1))
31#define hashptr(t, p) hashlohi((t), u32ptr(p), u32ptr(p) + HASH_BIAS) 31#if LJ_GC64
32#define hashgcref(t, r) \
33 hashlohi((t), (uint32_t)gcrefu(r), (uint32_t)(gcrefu(r) >> 32))
34#else
32#define hashgcref(t, r) hashlohi((t), gcrefu(r), gcrefu(r) + HASH_BIAS) 35#define hashgcref(t, r) hashlohi((t), gcrefu(r), gcrefu(r) + HASH_BIAS)
36#endif
33 37
34/* Hash an arbitrary key and return its anchor position in the hash table. */ 38/* Hash an arbitrary key and return its anchor position in the hash table. */
35static Node *hashkey(const GCtab *t, cTValue *key) 39static Node *hashkey(const GCtab *t, cTValue *key)
@@ -58,8 +62,8 @@ static LJ_AINLINE void newhpart(lua_State *L, GCtab *t, uint32_t hbits)
58 lj_err_msg(L, LJ_ERR_TABOV); 62 lj_err_msg(L, LJ_ERR_TABOV);
59 hsize = 1u << hbits; 63 hsize = 1u << hbits;
60 node = lj_mem_newvec(L, hsize, Node); 64 node = lj_mem_newvec(L, hsize, Node);
61 setmref(node->freetop, &node[hsize]);
62 setmref(t->node, node); 65 setmref(t->node, node);
66 setfreetop(t, node, &node[hsize]);
63 t->hmask = hsize-1; 67 t->hmask = hsize-1;
64} 68}
65 69
@@ -98,6 +102,7 @@ static GCtab *newtab(lua_State *L, uint32_t asize, uint32_t hbits)
98 GCtab *t; 102 GCtab *t;
99 /* First try to colocate the array part. */ 103 /* First try to colocate the array part. */
100 if (LJ_MAX_COLOSIZE != 0 && asize > 0 && asize <= LJ_MAX_COLOSIZE) { 104 if (LJ_MAX_COLOSIZE != 0 && asize > 0 && asize <= LJ_MAX_COLOSIZE) {
105 Node *nilnode;
101 lua_assert((sizeof(GCtab) & 7) == 0); 106 lua_assert((sizeof(GCtab) & 7) == 0);
102 t = (GCtab *)lj_mem_newgco(L, sizetabcolo(asize)); 107 t = (GCtab *)lj_mem_newgco(L, sizetabcolo(asize));
103 t->gct = ~LJ_TTAB; 108 t->gct = ~LJ_TTAB;
@@ -107,8 +112,13 @@ static GCtab *newtab(lua_State *L, uint32_t asize, uint32_t hbits)
107 setgcrefnull(t->metatable); 112 setgcrefnull(t->metatable);
108 t->asize = asize; 113 t->asize = asize;
109 t->hmask = 0; 114 t->hmask = 0;
110 setmref(t->node, &G(L)->nilnode); 115 nilnode = &G(L)->nilnode;
116 setmref(t->node, nilnode);
117#if LJ_GC64
118 setmref(t->freetop, nilnode);
119#endif
111 } else { /* Otherwise separately allocate the array part. */ 120 } else { /* Otherwise separately allocate the array part. */
121 Node *nilnode;
112 t = lj_mem_newobj(L, GCtab); 122 t = lj_mem_newobj(L, GCtab);
113 t->gct = ~LJ_TTAB; 123 t->gct = ~LJ_TTAB;
114 t->nomm = (uint8_t)~0; 124 t->nomm = (uint8_t)~0;
@@ -117,7 +127,11 @@ static GCtab *newtab(lua_State *L, uint32_t asize, uint32_t hbits)
117 setgcrefnull(t->metatable); 127 setgcrefnull(t->metatable);
118 t->asize = 0; /* In case the array allocation fails. */ 128 t->asize = 0; /* In case the array allocation fails. */
119 t->hmask = 0; 129 t->hmask = 0;
120 setmref(t->node, &G(L)->nilnode); 130 nilnode = &G(L)->nilnode;
131 setmref(t->node, nilnode);
132#if LJ_GC64
133 setmref(t->freetop, nilnode);
134#endif
121 if (asize > 0) { 135 if (asize > 0) {
122 if (asize > LJ_MAX_ASIZE) 136 if (asize > LJ_MAX_ASIZE)
123 lj_err_msg(L, LJ_ERR_TABOV); 137 lj_err_msg(L, LJ_ERR_TABOV);
@@ -149,6 +163,12 @@ GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits)
149 return t; 163 return t;
150} 164}
151 165
166/* The API of this function conforms to lua_createtable(). */
167GCtab *lj_tab_new_ah(lua_State *L, int32_t a, int32_t h)
168{
169 return lj_tab_new(L, (uint32_t)(a > 0 ? a+1 : 0), hsize2hbits(h));
170}
171
152#if LJ_HASJIT 172#if LJ_HASJIT
153GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize) 173GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize)
154{ 174{
@@ -185,7 +205,7 @@ GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt)
185 Node *node = noderef(t->node); 205 Node *node = noderef(t->node);
186 Node *knode = noderef(kt->node); 206 Node *knode = noderef(kt->node);
187 ptrdiff_t d = (char *)node - (char *)knode; 207 ptrdiff_t d = (char *)node - (char *)knode;
188 setmref(node->freetop, (Node *)((char *)noderef(knode->freetop) + d)); 208 setfreetop(t, node, (Node *)((char *)getfreetop(kt, knode) + d));
189 for (i = 0; i <= hmask; i++) { 209 for (i = 0; i <= hmask; i++) {
190 Node *kn = &knode[i]; 210 Node *kn = &knode[i];
191 Node *n = &node[i]; 211 Node *n = &node[i];
@@ -198,6 +218,17 @@ GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt)
198 return t; 218 return t;
199} 219}
200 220
221/* Clear a table. */
222void LJ_FASTCALL lj_tab_clear(GCtab *t)
223{
224 clearapart(t);
225 if (t->hmask > 0) {
226 Node *node = noderef(t->node);
227 setfreetop(t, node, &node[t->hmask+1]);
228 clearhpart(t);
229 }
230}
231
201/* Free a table. */ 232/* Free a table. */
202void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t) 233void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t)
203{ 234{
@@ -214,7 +245,7 @@ void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t)
214/* -- Table resizing ------------------------------------------------------ */ 245/* -- Table resizing ------------------------------------------------------ */
215 246
216/* Resize a table to fit the new array/hash part sizes. */ 247/* Resize a table to fit the new array/hash part sizes. */
217static void resizetab(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits) 248void lj_tab_resize(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits)
218{ 249{
219 Node *oldnode = noderef(t->node); 250 Node *oldnode = noderef(t->node);
220 uint32_t oldasize = t->asize; 251 uint32_t oldasize = t->asize;
@@ -247,6 +278,9 @@ static void resizetab(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits)
247 } else { 278 } else {
248 global_State *g = G(L); 279 global_State *g = G(L);
249 setmref(t->node, &g->nilnode); 280 setmref(t->node, &g->nilnode);
281#if LJ_GC64
282 setmref(t->freetop, &g->nilnode);
283#endif
250 t->hmask = 0; 284 t->hmask = 0;
251 } 285 }
252 if (asize < oldasize) { /* Array part shrinks? */ 286 if (asize < oldasize) { /* Array part shrinks? */
@@ -348,7 +382,7 @@ static void rehashtab(lua_State *L, GCtab *t, cTValue *ek)
348 asize += countint(ek, bins); 382 asize += countint(ek, bins);
349 na = bestasize(bins, &asize); 383 na = bestasize(bins, &asize);
350 total -= na; 384 total -= na;
351 resizetab(L, t, asize, hsize2hbits(total)); 385 lj_tab_resize(L, t, asize, hsize2hbits(total));
352} 386}
353 387
354#if LJ_HASFFI 388#if LJ_HASFFI
@@ -360,7 +394,7 @@ void lj_tab_rehash(lua_State *L, GCtab *t)
360 394
361void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize) 395void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize)
362{ 396{
363 resizetab(L, t, nasize+1, t->hmask > 0 ? lj_fls(t->hmask)+1 : 0); 397 lj_tab_resize(L, t, nasize+1, t->hmask > 0 ? lj_fls(t->hmask)+1 : 0);
364} 398}
365 399
366/* -- Table getters ------------------------------------------------------- */ 400/* -- Table getters ------------------------------------------------------- */
@@ -428,7 +462,7 @@ TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key)
428 Node *n = hashkey(t, key); 462 Node *n = hashkey(t, key);
429 if (!tvisnil(&n->val) || t->hmask == 0) { 463 if (!tvisnil(&n->val) || t->hmask == 0) {
430 Node *nodebase = noderef(t->node); 464 Node *nodebase = noderef(t->node);
431 Node *collide, *freenode = noderef(nodebase->freetop); 465 Node *collide, *freenode = getfreetop(t, nodebase);
432 lua_assert(freenode >= nodebase && freenode <= nodebase+t->hmask+1); 466 lua_assert(freenode >= nodebase && freenode <= nodebase+t->hmask+1);
433 do { 467 do {
434 if (freenode == nodebase) { /* No free node found? */ 468 if (freenode == nodebase) { /* No free node found? */
@@ -436,7 +470,7 @@ TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key)
436 return lj_tab_set(L, t, key); /* Retry key insertion. */ 470 return lj_tab_set(L, t, key); /* Retry key insertion. */
437 } 471 }
438 } while (!tvisnil(&(--freenode)->key)); 472 } while (!tvisnil(&(--freenode)->key));
439 setmref(nodebase->freetop, freenode); 473 setfreetop(t, nodebase, freenode);
440 lua_assert(freenode != &G(L)->nilnode); 474 lua_assert(freenode != &G(L)->nilnode);
441 collide = hashkey(t, &n->key); 475 collide = hashkey(t, &n->key);
442 if (collide != n) { /* Colliding node not the main node? */ 476 if (collide != n) { /* Colliding node not the main node? */
diff --git a/src/lj_tab.h b/src/lj_tab.h
index 36ce7cdd..71e34945 100644
--- a/src/lj_tab.h
+++ b/src/lj_tab.h
@@ -34,14 +34,17 @@ static LJ_AINLINE uint32_t hashrot(uint32_t lo, uint32_t hi)
34#define hsize2hbits(s) ((s) ? ((s)==1 ? 1 : 1+lj_fls((uint32_t)((s)-1))) : 0) 34#define hsize2hbits(s) ((s) ? ((s)==1 ? 1 : 1+lj_fls((uint32_t)((s)-1))) : 0)
35 35
36LJ_FUNCA GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits); 36LJ_FUNCA GCtab *lj_tab_new(lua_State *L, uint32_t asize, uint32_t hbits);
37LJ_FUNC GCtab *lj_tab_new_ah(lua_State *L, int32_t a, int32_t h);
37#if LJ_HASJIT 38#if LJ_HASJIT
38LJ_FUNC GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize); 39LJ_FUNC GCtab * LJ_FASTCALL lj_tab_new1(lua_State *L, uint32_t ahsize);
39#endif 40#endif
40LJ_FUNCA GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt); 41LJ_FUNCA GCtab * LJ_FASTCALL lj_tab_dup(lua_State *L, const GCtab *kt);
42LJ_FUNC void LJ_FASTCALL lj_tab_clear(GCtab *t);
41LJ_FUNC void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t); 43LJ_FUNC void LJ_FASTCALL lj_tab_free(global_State *g, GCtab *t);
42#if LJ_HASFFI 44#if LJ_HASFFI
43LJ_FUNC void lj_tab_rehash(lua_State *L, GCtab *t); 45LJ_FUNC void lj_tab_rehash(lua_State *L, GCtab *t);
44#endif 46#endif
47LJ_FUNC void lj_tab_resize(lua_State *L, GCtab *t, uint32_t asize, uint32_t hbits);
45LJ_FUNCA void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize); 48LJ_FUNCA void lj_tab_reasize(lua_State *L, GCtab *t, uint32_t nasize);
46 49
47/* Caveat: all getters except lj_tab_get() can return NULL! */ 50/* Caveat: all getters except lj_tab_get() can return NULL! */
@@ -53,7 +56,7 @@ LJ_FUNCA cTValue *lj_tab_get(lua_State *L, GCtab *t, cTValue *key);
53/* Caveat: all setters require a write barrier for the stored value. */ 56/* Caveat: all setters require a write barrier for the stored value. */
54 57
55LJ_FUNCA TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key); 58LJ_FUNCA TValue *lj_tab_newkey(lua_State *L, GCtab *t, cTValue *key);
56LJ_FUNC TValue *lj_tab_setinth(lua_State *L, GCtab *t, int32_t key); 59LJ_FUNCA TValue *lj_tab_setinth(lua_State *L, GCtab *t, int32_t key);
57LJ_FUNC TValue *lj_tab_setstr(lua_State *L, GCtab *t, GCstr *key); 60LJ_FUNC TValue *lj_tab_setstr(lua_State *L, GCtab *t, GCstr *key);
58LJ_FUNC TValue *lj_tab_set(lua_State *L, GCtab *t, cTValue *key); 61LJ_FUNC TValue *lj_tab_set(lua_State *L, GCtab *t, cTValue *key);
59 62
diff --git a/src/lj_target.h b/src/lj_target.h
index 53bfa6bf..8dcae957 100644
--- a/src/lj_target.h
+++ b/src/lj_target.h
@@ -55,7 +55,7 @@ typedef uint32_t RegSP;
55/* Bitset for registers. 32 registers suffice for most architectures. 55/* Bitset for registers. 32 registers suffice for most architectures.
56** Note that one set holds bits for both GPRs and FPRs. 56** Note that one set holds bits for both GPRs and FPRs.
57*/ 57*/
58#if LJ_TARGET_PPC || LJ_TARGET_MIPS 58#if LJ_TARGET_PPC || LJ_TARGET_MIPS || LJ_TARGET_ARM64
59typedef uint64_t RegSet; 59typedef uint64_t RegSet;
60#else 60#else
61typedef uint32_t RegSet; 61typedef uint32_t RegSet;
@@ -69,7 +69,7 @@ typedef uint32_t RegSet;
69#define rset_set(rs, r) (rs |= RID2RSET(r)) 69#define rset_set(rs, r) (rs |= RID2RSET(r))
70#define rset_clear(rs, r) (rs &= ~RID2RSET(r)) 70#define rset_clear(rs, r) (rs &= ~RID2RSET(r))
71#define rset_exclude(rs, r) (rs & ~RID2RSET(r)) 71#define rset_exclude(rs, r) (rs & ~RID2RSET(r))
72#if LJ_TARGET_PPC || LJ_TARGET_MIPS 72#if LJ_TARGET_PPC || LJ_TARGET_MIPS || LJ_TARGET_ARM64
73#define rset_picktop(rs) ((Reg)(__builtin_clzll(rs)^63)) 73#define rset_picktop(rs) ((Reg)(__builtin_clzll(rs)^63))
74#define rset_pickbot(rs) ((Reg)__builtin_ctzll(rs)) 74#define rset_pickbot(rs) ((Reg)__builtin_ctzll(rs))
75#else 75#else
@@ -138,6 +138,8 @@ typedef uint32_t RegCost;
138#include "lj_target_x86.h" 138#include "lj_target_x86.h"
139#elif LJ_TARGET_ARM 139#elif LJ_TARGET_ARM
140#include "lj_target_arm.h" 140#include "lj_target_arm.h"
141#elif LJ_TARGET_ARM64
142#include "lj_target_arm64.h"
141#elif LJ_TARGET_PPC 143#elif LJ_TARGET_PPC
142#include "lj_target_ppc.h" 144#include "lj_target_ppc.h"
143#elif LJ_TARGET_MIPS 145#elif LJ_TARGET_MIPS
diff --git a/src/lj_target_arm.h b/src/lj_target_arm.h
index d02cbf86..5551b1f1 100644
--- a/src/lj_target_arm.h
+++ b/src/lj_target_arm.h
@@ -243,10 +243,6 @@ typedef enum ARMIns {
243 ARMI_VCVT_S32_F64 = 0xeebd0bc0, 243 ARMI_VCVT_S32_F64 = 0xeebd0bc0,
244 ARMI_VCVT_U32_F32 = 0xeebc0ac0, 244 ARMI_VCVT_U32_F32 = 0xeebc0ac0,
245 ARMI_VCVT_U32_F64 = 0xeebc0bc0, 245 ARMI_VCVT_U32_F64 = 0xeebc0bc0,
246 ARMI_VCVTR_S32_F32 = 0xeebd0a40,
247 ARMI_VCVTR_S32_F64 = 0xeebd0b40,
248 ARMI_VCVTR_U32_F32 = 0xeebc0a40,
249 ARMI_VCVTR_U32_F64 = 0xeebc0b40,
250 ARMI_VCVT_F32_S32 = 0xeeb80ac0, 246 ARMI_VCVT_F32_S32 = 0xeeb80ac0,
251 ARMI_VCVT_F64_S32 = 0xeeb80bc0, 247 ARMI_VCVT_F64_S32 = 0xeeb80bc0,
252 ARMI_VCVT_F32_U32 = 0xeeb80a40, 248 ARMI_VCVT_F32_U32 = 0xeeb80a40,
diff --git a/src/lj_target_arm64.h b/src/lj_target_arm64.h
new file mode 100644
index 00000000..3f6bb39b
--- /dev/null
+++ b/src/lj_target_arm64.h
@@ -0,0 +1,322 @@
1/*
2** Definitions for ARM64 CPUs.
3** Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_TARGET_ARM64_H
7#define _LJ_TARGET_ARM64_H
8
9/* -- Registers IDs ------------------------------------------------------- */
10
11#define GPRDEF(_) \
12 _(X0) _(X1) _(X2) _(X3) _(X4) _(X5) _(X6) _(X7) \
13 _(X8) _(X9) _(X10) _(X11) _(X12) _(X13) _(X14) _(X15) \
14 _(X16) _(X17) _(X18) _(X19) _(X20) _(X21) _(X22) _(X23) \
15 _(X24) _(X25) _(X26) _(X27) _(X28) _(FP) _(LR) _(SP)
16#define FPRDEF(_) \
17 _(D0) _(D1) _(D2) _(D3) _(D4) _(D5) _(D6) _(D7) \
18 _(D8) _(D9) _(D10) _(D11) _(D12) _(D13) _(D14) _(D15) \
19 _(D16) _(D17) _(D18) _(D19) _(D20) _(D21) _(D22) _(D23) \
20 _(D24) _(D25) _(D26) _(D27) _(D28) _(D29) _(D30) _(D31)
21#define VRIDDEF(_)
22
23#define RIDENUM(name) RID_##name,
24
25enum {
26 GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */
27 FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */
28 RID_MAX,
29 RID_TMP = RID_LR,
30 RID_ZERO = RID_SP,
31
32 /* Calling conventions. */
33 RID_RET = RID_X0,
34 RID_FPRET = RID_D0,
35
36 /* These definitions must match with the *.dasc file(s): */
37 RID_BASE = RID_X19, /* Interpreter BASE. */
38 RID_LPC = RID_X21, /* Interpreter PC. */
39 RID_GL = RID_X22, /* Interpreter GL. */
40 RID_LREG = RID_X23, /* Interpreter L. */
41
42 /* Register ranges [min, max) and number of registers. */
43 RID_MIN_GPR = RID_X0,
44 RID_MAX_GPR = RID_SP+1,
45 RID_MIN_FPR = RID_MAX_GPR,
46 RID_MAX_FPR = RID_D31+1,
47 RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR,
48 RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR
49};
50
51#define RID_NUM_KREF RID_NUM_GPR
52#define RID_MIN_KREF RID_X0
53
54/* -- Register sets ------------------------------------------------------- */
55
56/* Make use of all registers, except for x18, fp, lr and sp. */
57#define RSET_FIXED \
58 (RID2RSET(RID_X18)|RID2RSET(RID_FP)|RID2RSET(RID_LR)|RID2RSET(RID_SP)|\
59 RID2RSET(RID_GL))
60#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED)
61#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)
62#define RSET_ALL (RSET_GPR|RSET_FPR)
63#define RSET_INIT RSET_ALL
64
65/* lr is an implicit scratch register. */
66#define RSET_SCRATCH_GPR (RSET_RANGE(RID_X0, RID_X17+1))
67#define RSET_SCRATCH_FPR \
68 (RSET_RANGE(RID_D0, RID_D7+1)|RSET_RANGE(RID_D16, RID_D31+1))
69#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR)
70#define REGARG_FIRSTGPR RID_X0
71#define REGARG_LASTGPR RID_X7
72#define REGARG_NUMGPR 8
73#define REGARG_FIRSTFPR RID_D0
74#define REGARG_LASTFPR RID_D7
75#define REGARG_NUMFPR 8
76
77/* -- Spill slots --------------------------------------------------------- */
78
79/* Spill slots are 32 bit wide. An even/odd pair is used for FPRs.
80**
81** SPS_FIXED: Available fixed spill slots in interpreter frame.
82** This definition must match with the vm_arm64.dasc file.
83** Pre-allocate some slots to avoid sp adjust in every root trace.
84**
85** SPS_FIRST: First spill slot for general use. Reserve min. two 32 bit slots.
86*/
87#define SPS_FIXED 4
88#define SPS_FIRST 2
89
90#define SPOFS_TMP 0
91
92#define sps_scale(slot) (4 * (int32_t)(slot))
93#define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3)
94
95/* -- Exit state ---------------------------------------------------------- */
96
97/* This definition must match with the *.dasc file(s). */
98typedef struct {
99 lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */
100 intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */
101 int32_t spill[256]; /* Spill slots. */
102} ExitState;
103
104/* Highest exit + 1 indicates stack check. */
105#define EXITSTATE_CHECKEXIT 1
106
107/* Return the address of a per-trace exit stub. */
108static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p, uint32_t exitno)
109{
110 while (*p == 0xd503201f) p++; /* Skip A64I_NOP. */
111 return p + 3 + exitno;
112}
113/* Avoid dependence on lj_jit.h if only including lj_target.h. */
114#define exitstub_trace_addr(T, exitno) \
115 exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode), (exitno))
116
117/* -- Instructions -------------------------------------------------------- */
118
119/* Instruction fields. */
120#define A64F_D(r) (r)
121#define A64F_N(r) ((r) << 5)
122#define A64F_A(r) ((r) << 10)
123#define A64F_M(r) ((r) << 16)
124#define A64F_IMMS(x) ((x) << 10)
125#define A64F_IMMR(x) ((x) << 16)
126#define A64F_U16(x) ((x) << 5)
127#define A64F_U12(x) ((x) << 10)
128#define A64F_S26(x) (x)
129#define A64F_S19(x) (((uint32_t)(x) & 0x7ffffu) << 5)
130#define A64F_S14(x) ((x) << 5)
131#define A64F_S9(x) ((x) << 12)
132#define A64F_BIT(x) ((x) << 19)
133#define A64F_SH(sh, x) (((sh) << 22) | ((x) << 10))
134#define A64F_EX(ex) (A64I_EX | ((ex) << 13))
135#define A64F_EXSH(ex,x) (A64I_EX | ((ex) << 13) | ((x) << 10))
136#define A64F_FP8(x) ((x) << 13)
137#define A64F_CC(cc) ((cc) << 12)
138#define A64F_LSL16(x) (((x) / 16) << 21)
139#define A64F_BSH(sh) ((sh) << 10)
140
141typedef enum A64Ins {
142 A64I_S = 0x20000000,
143 A64I_X = 0x80000000,
144 A64I_EX = 0x00200000,
145 A64I_ON = 0x00200000,
146 A64I_K12 = 0x1a000000,
147 A64I_K13 = 0x18000000,
148 A64I_LS_U = 0x01000000,
149 A64I_LS_S = 0x00800000,
150 A64I_LS_R = 0x01200800,
151 A64I_LS_SH = 0x00001000,
152 A64I_LS_UXTWx = 0x00004000,
153 A64I_LS_SXTWx = 0x0000c000,
154 A64I_LS_SXTXx = 0x0000e000,
155 A64I_LS_LSLx = 0x00006000,
156
157 A64I_ADDw = 0x0b000000,
158 A64I_ADDx = 0x8b000000,
159 A64I_ADDSw = 0x2b000000,
160 A64I_ADDSx = 0xab000000,
161 A64I_NEGw = 0x4b0003e0,
162 A64I_NEGx = 0xcb0003e0,
163 A64I_SUBw = 0x4b000000,
164 A64I_SUBx = 0xcb000000,
165 A64I_SUBSw = 0x6b000000,
166 A64I_SUBSx = 0xeb000000,
167
168 A64I_MULw = 0x1b007c00,
169 A64I_MULx = 0x9b007c00,
170 A64I_SMULL = 0x9b207c00,
171
172 A64I_ANDw = 0x0a000000,
173 A64I_ANDx = 0x8a000000,
174 A64I_ANDSw = 0x6a000000,
175 A64I_ANDSx = 0xea000000,
176 A64I_EORw = 0x4a000000,
177 A64I_EORx = 0xca000000,
178 A64I_ORRw = 0x2a000000,
179 A64I_ORRx = 0xaa000000,
180 A64I_TSTw = 0x6a00001f,
181 A64I_TSTx = 0xea00001f,
182
183 A64I_CMPw = 0x6b00001f,
184 A64I_CMPx = 0xeb00001f,
185 A64I_CMNw = 0x2b00001f,
186 A64I_CMNx = 0xab00001f,
187 A64I_CCMPw = 0x7a400000,
188 A64I_CCMPx = 0xfa400000,
189 A64I_CSELw = 0x1a800000,
190 A64I_CSELx = 0x9a800000,
191
192 A64I_ASRw = 0x13007c00,
193 A64I_ASRx = 0x9340fc00,
194 A64I_LSLx = 0xd3400000,
195 A64I_LSRx = 0xd340fc00,
196 A64I_SHRw = 0x1ac02000,
197 A64I_SHRx = 0x9ac02000, /* lsl/lsr/asr/ror x0, x0, x0 */
198 A64I_REVw = 0x5ac00800,
199 A64I_REVx = 0xdac00c00,
200
201 A64I_EXTRw = 0x13800000,
202 A64I_EXTRx = 0x93c00000,
203 A64I_SBFMw = 0x13000000,
204 A64I_SBFMx = 0x93400000,
205 A64I_SXTBw = 0x13001c00,
206 A64I_SXTHw = 0x13003c00,
207 A64I_SXTW = 0x93407c00,
208 A64I_UBFMw = 0x53000000,
209 A64I_UBFMx = 0xd3400000,
210 A64I_UXTBw = 0x53001c00,
211 A64I_UXTHw = 0x53003c00,
212
213 A64I_MOVw = 0x2a0003e0,
214 A64I_MOVx = 0xaa0003e0,
215 A64I_MVNw = 0x2a2003e0,
216 A64I_MVNx = 0xaa2003e0,
217 A64I_MOVKw = 0x72800000,
218 A64I_MOVKx = 0xf2800000,
219 A64I_MOVZw = 0x52800000,
220 A64I_MOVZx = 0xd2800000,
221 A64I_MOVNw = 0x12800000,
222 A64I_MOVNx = 0x92800000,
223
224 A64I_LDRB = 0x39400000,
225 A64I_LDRH = 0x79400000,
226 A64I_LDRw = 0xb9400000,
227 A64I_LDRx = 0xf9400000,
228 A64I_LDRLw = 0x18000000,
229 A64I_LDRLx = 0x58000000,
230 A64I_STRB = 0x39000000,
231 A64I_STRH = 0x79000000,
232 A64I_STRw = 0xb9000000,
233 A64I_STRx = 0xf9000000,
234 A64I_STPw = 0x29000000,
235 A64I_STPx = 0xa9000000,
236 A64I_LDPw = 0x29400000,
237 A64I_LDPx = 0xa9400000,
238
239 A64I_B = 0x14000000,
240 A64I_BCC = 0x54000000,
241 A64I_BL = 0x94000000,
242 A64I_BR = 0xd61f0000,
243 A64I_BLR = 0xd63f0000,
244 A64I_TBZ = 0x36000000,
245 A64I_TBNZ = 0x37000000,
246 A64I_CBZ = 0x34000000,
247 A64I_CBNZ = 0x35000000,
248
249 A64I_NOP = 0xd503201f,
250
251 /* FP */
252 A64I_FADDd = 0x1e602800,
253 A64I_FSUBd = 0x1e603800,
254 A64I_FMADDd = 0x1f400000,
255 A64I_FMSUBd = 0x1f408000,
256 A64I_FNMADDd = 0x1f600000,
257 A64I_FNMSUBd = 0x1f608000,
258 A64I_FMULd = 0x1e600800,
259 A64I_FDIVd = 0x1e601800,
260 A64I_FNEGd = 0x1e614000,
261 A64I_FABS = 0x1e60c000,
262 A64I_FSQRTd = 0x1e61c000,
263 A64I_LDRs = 0xbd400000,
264 A64I_LDRd = 0xfd400000,
265 A64I_STRs = 0xbd000000,
266 A64I_STRd = 0xfd000000,
267 A64I_LDPs = 0x2d400000,
268 A64I_LDPd = 0x6d400000,
269 A64I_STPs = 0x2d000000,
270 A64I_STPd = 0x6d000000,
271 A64I_FCMPd = 0x1e602000,
272 A64I_FCMPZd = 0x1e602008,
273 A64I_FCSELd = 0x1e600c00,
274 A64I_FRINTMd = 0x1e654000,
275 A64I_FRINTPd = 0x1e64c000,
276 A64I_FRINTZd = 0x1e65c000,
277
278 A64I_FCVT_F32_F64 = 0x1e624000,
279 A64I_FCVT_F64_F32 = 0x1e22c000,
280 A64I_FCVT_F32_S32 = 0x1e220000,
281 A64I_FCVT_F64_S32 = 0x1e620000,
282 A64I_FCVT_F32_U32 = 0x1e230000,
283 A64I_FCVT_F64_U32 = 0x1e630000,
284 A64I_FCVT_F32_S64 = 0x9e220000,
285 A64I_FCVT_F64_S64 = 0x9e620000,
286 A64I_FCVT_F32_U64 = 0x9e230000,
287 A64I_FCVT_F64_U64 = 0x9e630000,
288 A64I_FCVT_S32_F64 = 0x1e780000,
289 A64I_FCVT_S32_F32 = 0x1e380000,
290 A64I_FCVT_U32_F64 = 0x1e790000,
291 A64I_FCVT_U32_F32 = 0x1e390000,
292 A64I_FCVT_S64_F64 = 0x9e780000,
293 A64I_FCVT_S64_F32 = 0x9e380000,
294 A64I_FCVT_U64_F64 = 0x9e790000,
295 A64I_FCVT_U64_F32 = 0x9e390000,
296
297 A64I_FMOV_S = 0x1e204000,
298 A64I_FMOV_D = 0x1e604000,
299 A64I_FMOV_R_S = 0x1e260000,
300 A64I_FMOV_S_R = 0x1e270000,
301 A64I_FMOV_R_D = 0x9e660000,
302 A64I_FMOV_D_R = 0x9e670000,
303 A64I_FMOV_DI = 0x1e601000,
304} A64Ins;
305
306typedef enum A64Shift {
307 A64SH_LSL, A64SH_LSR, A64SH_ASR, A64SH_ROR
308} A64Shift;
309
310typedef enum A64Extend {
311 A64EX_UXTB, A64EX_UXTH, A64EX_UXTW, A64EX_UXTX,
312 A64EX_SXTB, A64EX_SXTH, A64EX_SXTW, A64EX_SXTX,
313} A64Extend;
314
315/* ARM condition codes. */
316typedef enum A64CC {
317 CC_EQ, CC_NE, CC_CS, CC_CC, CC_MI, CC_PL, CC_VS, CC_VC,
318 CC_HI, CC_LS, CC_GE, CC_LT, CC_GT, CC_LE, CC_AL,
319 CC_HS = CC_CS, CC_LO = CC_CC
320} A64CC;
321
322#endif
diff --git a/src/lj_target_mips.h b/src/lj_target_mips.h
index bed174b8..740687b3 100644
--- a/src/lj_target_mips.h
+++ b/src/lj_target_mips.h
@@ -13,11 +13,15 @@
13 _(R8) _(R9) _(R10) _(R11) _(R12) _(R13) _(R14) _(R15) \ 13 _(R8) _(R9) _(R10) _(R11) _(R12) _(R13) _(R14) _(R15) \
14 _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \ 14 _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \
15 _(R24) _(R25) _(SYS1) _(SYS2) _(R28) _(SP) _(R30) _(RA) 15 _(R24) _(R25) _(SYS1) _(SYS2) _(R28) _(SP) _(R30) _(RA)
16#if LJ_SOFTFP
17#define FPRDEF(_)
18#else
16#define FPRDEF(_) \ 19#define FPRDEF(_) \
17 _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \ 20 _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \
18 _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \ 21 _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \
19 _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \ 22 _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \
20 _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31) 23 _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31)
24#endif
21#define VRIDDEF(_) 25#define VRIDDEF(_)
22 26
23#define RIDENUM(name) RID_##name, 27#define RIDENUM(name) RID_##name,
@@ -39,7 +43,11 @@ enum {
39 RID_RETHI = RID_R2, 43 RID_RETHI = RID_R2,
40 RID_RETLO = RID_R3, 44 RID_RETLO = RID_R3,
41#endif 45#endif
46#if LJ_SOFTFP
47 RID_FPRET = RID_R2,
48#else
42 RID_FPRET = RID_F0, 49 RID_FPRET = RID_F0,
50#endif
43 RID_CFUNCADDR = RID_R25, 51 RID_CFUNCADDR = RID_R25,
44 52
45 /* These definitions must match with the *.dasc file(s): */ 53 /* These definitions must match with the *.dasc file(s): */
@@ -52,8 +60,12 @@ enum {
52 /* Register ranges [min, max) and number of registers. */ 60 /* Register ranges [min, max) and number of registers. */
53 RID_MIN_GPR = RID_R0, 61 RID_MIN_GPR = RID_R0,
54 RID_MAX_GPR = RID_RA+1, 62 RID_MAX_GPR = RID_RA+1,
55 RID_MIN_FPR = RID_F0, 63 RID_MIN_FPR = RID_MAX_GPR,
64#if LJ_SOFTFP
65 RID_MAX_FPR = RID_MIN_FPR,
66#else
56 RID_MAX_FPR = RID_F31+1, 67 RID_MAX_FPR = RID_F31+1,
68#endif
57 RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, 69 RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR,
58 RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR /* Only even regs are used. */ 70 RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR /* Only even regs are used. */
59}; 71};
@@ -68,28 +80,60 @@ enum {
68 (RID2RSET(RID_ZERO)|RID2RSET(RID_TMP)|RID2RSET(RID_SP)|\ 80 (RID2RSET(RID_ZERO)|RID2RSET(RID_TMP)|RID2RSET(RID_SP)|\
69 RID2RSET(RID_SYS1)|RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)|RID2RSET(RID_GP)) 81 RID2RSET(RID_SYS1)|RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)|RID2RSET(RID_GP))
70#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) 82#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED)
83#if LJ_SOFTFP
84#define RSET_FPR 0
85#else
86#if LJ_32
71#define RSET_FPR \ 87#define RSET_FPR \
72 (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ 88 (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\
73 RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ 89 RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\
74 RID2RSET(RID_F16)|RID2RSET(RID_F18)|RID2RSET(RID_F20)|RID2RSET(RID_F22)|\ 90 RID2RSET(RID_F16)|RID2RSET(RID_F18)|RID2RSET(RID_F20)|RID2RSET(RID_F22)|\
75 RID2RSET(RID_F24)|RID2RSET(RID_F26)|RID2RSET(RID_F28)|RID2RSET(RID_F30)) 91 RID2RSET(RID_F24)|RID2RSET(RID_F26)|RID2RSET(RID_F28)|RID2RSET(RID_F30))
76#define RSET_ALL (RSET_GPR|RSET_FPR) 92#else
77#define RSET_INIT RSET_ALL 93#define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)
94#endif
95#endif
96#define RSET_ALL (RSET_GPR|RSET_FPR)
97#define RSET_INIT RSET_ALL
78 98
79#define RSET_SCRATCH_GPR \ 99#define RSET_SCRATCH_GPR \
80 (RSET_RANGE(RID_R1, RID_R15+1)|\ 100 (RSET_RANGE(RID_R1, RID_R15+1)|\
81 RID2RSET(RID_R24)|RID2RSET(RID_R25)) 101 RID2RSET(RID_R24)|RID2RSET(RID_R25))
102#if LJ_SOFTFP
103#define RSET_SCRATCH_FPR 0
104#else
105#if LJ_32
82#define RSET_SCRATCH_FPR \ 106#define RSET_SCRATCH_FPR \
83 (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\ 107 (RID2RSET(RID_F0)|RID2RSET(RID_F2)|RID2RSET(RID_F4)|RID2RSET(RID_F6)|\
84 RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\ 108 RID2RSET(RID_F8)|RID2RSET(RID_F10)|RID2RSET(RID_F12)|RID2RSET(RID_F14)|\
85 RID2RSET(RID_F16)|RID2RSET(RID_F18)) 109 RID2RSET(RID_F16)|RID2RSET(RID_F18))
110#else
111#define RSET_SCRATCH_FPR RSET_RANGE(RID_F0, RID_F24)
112#endif
113#endif
86#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) 114#define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR)
87#define REGARG_FIRSTGPR RID_R4 115#define REGARG_FIRSTGPR RID_R4
116#if LJ_32
88#define REGARG_LASTGPR RID_R7 117#define REGARG_LASTGPR RID_R7
89#define REGARG_NUMGPR 4 118#define REGARG_NUMGPR 4
119#else
120#define REGARG_LASTGPR RID_R11
121#define REGARG_NUMGPR 8
122#endif
123#if LJ_ABI_SOFTFP
124#define REGARG_FIRSTFPR 0
125#define REGARG_LASTFPR 0
126#define REGARG_NUMFPR 0
127#else
90#define REGARG_FIRSTFPR RID_F12 128#define REGARG_FIRSTFPR RID_F12
129#if LJ_32
91#define REGARG_LASTFPR RID_F14 130#define REGARG_LASTFPR RID_F14
92#define REGARG_NUMFPR 2 131#define REGARG_NUMFPR 2
132#else
133#define REGARG_LASTFPR RID_F19
134#define REGARG_NUMFPR 8
135#endif
136#endif
93 137
94/* -- Spill slots --------------------------------------------------------- */ 138/* -- Spill slots --------------------------------------------------------- */
95 139
@@ -100,7 +144,11 @@ enum {
100** 144**
101** SPS_FIRST: First spill slot for general use. 145** SPS_FIRST: First spill slot for general use.
102*/ 146*/
147#if LJ_32
103#define SPS_FIXED 5 148#define SPS_FIXED 5
149#else
150#define SPS_FIXED 4
151#endif
104#define SPS_FIRST 4 152#define SPS_FIRST 4
105 153
106#define SPOFS_TMP 0 154#define SPOFS_TMP 0
@@ -112,8 +160,10 @@ enum {
112 160
113/* This definition must match with the *.dasc file(s). */ 161/* This definition must match with the *.dasc file(s). */
114typedef struct { 162typedef struct {
163#if !LJ_SOFTFP
115 lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ 164 lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */
116 int32_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ 165#endif
166 intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */
117 int32_t spill[256]; /* Spill slots. */ 167 int32_t spill[256]; /* Spill slots. */
118} ExitState; 168} ExitState;
119 169
@@ -142,51 +192,68 @@ static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p)
142#define MIPSF_F(r) ((r) << 6) 192#define MIPSF_F(r) ((r) << 6)
143#define MIPSF_A(n) ((n) << 6) 193#define MIPSF_A(n) ((n) << 6)
144#define MIPSF_M(n) ((n) << 11) 194#define MIPSF_M(n) ((n) << 11)
195#define MIPSF_L(n) ((n) << 6)
145 196
146typedef enum MIPSIns { 197typedef enum MIPSIns {
198 MIPSI_D = 0x38,
199 MIPSI_DV = 0x10,
200 MIPSI_D32 = 0x3c,
147 /* Integer instructions. */ 201 /* Integer instructions. */
148 MIPSI_MOVE = 0x00000021, 202 MIPSI_MOVE = 0x00000025,
149 MIPSI_NOP = 0x00000000, 203 MIPSI_NOP = 0x00000000,
150 204
151 MIPSI_LI = 0x24000000, 205 MIPSI_LI = 0x24000000,
152 MIPSI_LU = 0x34000000, 206 MIPSI_LU = 0x34000000,
153 MIPSI_LUI = 0x3c000000, 207 MIPSI_LUI = 0x3c000000,
154 208
155 MIPSI_ADDIU = 0x24000000, 209 MIPSI_AND = 0x00000024,
156 MIPSI_ANDI = 0x30000000, 210 MIPSI_ANDI = 0x30000000,
211 MIPSI_OR = 0x00000025,
157 MIPSI_ORI = 0x34000000, 212 MIPSI_ORI = 0x34000000,
213 MIPSI_XOR = 0x00000026,
158 MIPSI_XORI = 0x38000000, 214 MIPSI_XORI = 0x38000000,
215 MIPSI_NOR = 0x00000027,
216
217 MIPSI_SLT = 0x0000002a,
218 MIPSI_SLTU = 0x0000002b,
159 MIPSI_SLTI = 0x28000000, 219 MIPSI_SLTI = 0x28000000,
160 MIPSI_SLTIU = 0x2c000000, 220 MIPSI_SLTIU = 0x2c000000,
161 221
162 MIPSI_ADDU = 0x00000021, 222 MIPSI_ADDU = 0x00000021,
223 MIPSI_ADDIU = 0x24000000,
224 MIPSI_SUB = 0x00000022,
163 MIPSI_SUBU = 0x00000023, 225 MIPSI_SUBU = 0x00000023,
164 MIPSI_MUL = 0x70000002, 226 MIPSI_MUL = 0x70000002,
165 MIPSI_AND = 0x00000024, 227 MIPSI_DIV = 0x0000001a,
166 MIPSI_OR = 0x00000025, 228 MIPSI_DIVU = 0x0000001b,
167 MIPSI_XOR = 0x00000026, 229
168 MIPSI_NOR = 0x00000027,
169 MIPSI_SLT = 0x0000002a,
170 MIPSI_SLTU = 0x0000002b,
171 MIPSI_MOVZ = 0x0000000a, 230 MIPSI_MOVZ = 0x0000000a,
172 MIPSI_MOVN = 0x0000000b, 231 MIPSI_MOVN = 0x0000000b,
232 MIPSI_MFHI = 0x00000010,
233 MIPSI_MFLO = 0x00000012,
234 MIPSI_MULT = 0x00000018,
173 235
174 MIPSI_SLL = 0x00000000, 236 MIPSI_SLL = 0x00000000,
175 MIPSI_SRL = 0x00000002, 237 MIPSI_SRL = 0x00000002,
176 MIPSI_SRA = 0x00000003, 238 MIPSI_SRA = 0x00000003,
177 MIPSI_ROTR = 0x00200002, /* MIPS32R2 */ 239 MIPSI_ROTR = 0x00200002, /* MIPSXXR2 */
240 MIPSI_DROTR = 0x0020003a,
241 MIPSI_DROTR32 = 0x0020003e,
178 MIPSI_SLLV = 0x00000004, 242 MIPSI_SLLV = 0x00000004,
179 MIPSI_SRLV = 0x00000006, 243 MIPSI_SRLV = 0x00000006,
180 MIPSI_SRAV = 0x00000007, 244 MIPSI_SRAV = 0x00000007,
181 MIPSI_ROTRV = 0x00000046, /* MIPS32R2 */ 245 MIPSI_ROTRV = 0x00000046, /* MIPSXXR2 */
246 MIPSI_DROTRV = 0x00000056,
182 247
183 MIPSI_SEB = 0x7c000420, /* MIPS32R2 */ 248 MIPSI_SEB = 0x7c000420, /* MIPSXXR2 */
184 MIPSI_SEH = 0x7c000620, /* MIPS32R2 */ 249 MIPSI_SEH = 0x7c000620, /* MIPSXXR2 */
185 MIPSI_WSBH = 0x7c0000a0, /* MIPS32R2 */ 250 MIPSI_WSBH = 0x7c0000a0, /* MIPSXXR2 */
251 MIPSI_DSBH = 0x7c0000a4,
186 252
187 MIPSI_B = 0x10000000, 253 MIPSI_B = 0x10000000,
188 MIPSI_J = 0x08000000, 254 MIPSI_J = 0x08000000,
189 MIPSI_JAL = 0x0c000000, 255 MIPSI_JAL = 0x0c000000,
256 MIPSI_JALX = 0x74000000,
190 MIPSI_JR = 0x00000008, 257 MIPSI_JR = 0x00000008,
191 MIPSI_JALR = 0x0000f809, 258 MIPSI_JALR = 0x0000f809,
192 259
@@ -199,7 +266,9 @@ typedef enum MIPSIns {
199 266
200 /* Load/store instructions. */ 267 /* Load/store instructions. */
201 MIPSI_LW = 0x8c000000, 268 MIPSI_LW = 0x8c000000,
269 MIPSI_LD = 0xdc000000,
202 MIPSI_SW = 0xac000000, 270 MIPSI_SW = 0xac000000,
271 MIPSI_SD = 0xfc000000,
203 MIPSI_LB = 0x80000000, 272 MIPSI_LB = 0x80000000,
204 MIPSI_SB = 0xa0000000, 273 MIPSI_SB = 0xa0000000,
205 MIPSI_LH = 0x84000000, 274 MIPSI_LH = 0x84000000,
@@ -211,6 +280,50 @@ typedef enum MIPSIns {
211 MIPSI_LDC1 = 0xd4000000, 280 MIPSI_LDC1 = 0xd4000000,
212 MIPSI_SDC1 = 0xf4000000, 281 MIPSI_SDC1 = 0xf4000000,
213 282
283 /* MIPS64 instructions. */
284 MIPSI_DADD = 0x0000002c,
285 MIPSI_DADDI = 0x60000000,
286 MIPSI_DADDU = 0x0000002d,
287 MIPSI_DADDIU = 0x64000000,
288 MIPSI_DSUB = 0x0000002e,
289 MIPSI_DSUBU = 0x0000002f,
290 MIPSI_DDIV = 0x0000001e,
291 MIPSI_DDIVU = 0x0000001f,
292 MIPSI_DMULT = 0x0000001c,
293 MIPSI_DMULTU = 0x0000001d,
294
295 MIPSI_DSLL = 0x00000038,
296 MIPSI_DSRL = 0x0000003a,
297 MIPSI_DSLLV = 0x00000014,
298 MIPSI_DSRLV = 0x00000016,
299 MIPSI_DSRA = 0x0000003b,
300 MIPSI_DSRAV = 0x00000017,
301 MIPSI_DSRA32 = 0x0000003f,
302 MIPSI_DSLL32 = 0x0000003c,
303 MIPSI_DSRL32 = 0x0000003e,
304 MIPSI_DSHD = 0x7c000164,
305
306 MIPSI_AADDU = LJ_32 ? MIPSI_ADDU : MIPSI_DADDU,
307 MIPSI_AADDIU = LJ_32 ? MIPSI_ADDIU : MIPSI_DADDIU,
308 MIPSI_ASUBU = LJ_32 ? MIPSI_SUBU : MIPSI_DSUBU,
309 MIPSI_AL = LJ_32 ? MIPSI_LW : MIPSI_LD,
310 MIPSI_AS = LJ_32 ? MIPSI_SW : MIPSI_SD,
311
312 /* Extract/insert instructions. */
313 MIPSI_DEXTM = 0x7c000001,
314 MIPSI_DEXTU = 0x7c000002,
315 MIPSI_DEXT = 0x7c000003,
316 MIPSI_DINSM = 0x7c000005,
317 MIPSI_DINSU = 0x7c000006,
318 MIPSI_DINS = 0x7c000007,
319
320 MIPSI_RINT_D = 0x4620001a,
321 MIPSI_RINT_S = 0x4600001a,
322 MIPSI_RINT = 0x4400001a,
323 MIPSI_FLOOR_D = 0x4620000b,
324 MIPSI_CEIL_D = 0x4620000a,
325 MIPSI_ROUND_D = 0x46200008,
326
214 /* FP instructions. */ 327 /* FP instructions. */
215 MIPSI_MOV_S = 0x46000006, 328 MIPSI_MOV_S = 0x46000006,
216 MIPSI_MOV_D = 0x46200006, 329 MIPSI_MOV_D = 0x46200006,
@@ -235,24 +348,30 @@ typedef enum MIPSIns {
235 MIPSI_CVT_W_D = 0x46200024, 348 MIPSI_CVT_W_D = 0x46200024,
236 MIPSI_CVT_S_W = 0x46800020, 349 MIPSI_CVT_S_W = 0x46800020,
237 MIPSI_CVT_D_W = 0x46800021, 350 MIPSI_CVT_D_W = 0x46800021,
351 MIPSI_CVT_S_L = 0x46a00020,
352 MIPSI_CVT_D_L = 0x46a00021,
238 353
239 MIPSI_TRUNC_W_S = 0x4600000d, 354 MIPSI_TRUNC_W_S = 0x4600000d,
240 MIPSI_TRUNC_W_D = 0x4620000d, 355 MIPSI_TRUNC_W_D = 0x4620000d,
356 MIPSI_TRUNC_L_S = 0x46000009,
357 MIPSI_TRUNC_L_D = 0x46200009,
241 MIPSI_FLOOR_W_S = 0x4600000f, 358 MIPSI_FLOOR_W_S = 0x4600000f,
242 MIPSI_FLOOR_W_D = 0x4620000f, 359 MIPSI_FLOOR_W_D = 0x4620000f,
243 360
244 MIPSI_MFC1 = 0x44000000, 361 MIPSI_MFC1 = 0x44000000,
245 MIPSI_MTC1 = 0x44800000, 362 MIPSI_MTC1 = 0x44800000,
363 MIPSI_DMTC1 = 0x44a00000,
364 MIPSI_DMFC1 = 0x44200000,
246 365
247 MIPSI_BC1F = 0x45000000, 366 MIPSI_BC1F = 0x45000000,
248 MIPSI_BC1T = 0x45010000, 367 MIPSI_BC1T = 0x45010000,
249 368
250 MIPSI_C_EQ_D = 0x46200032, 369 MIPSI_C_EQ_D = 0x46200032,
370 MIPSI_C_OLT_S = 0x46000034,
251 MIPSI_C_OLT_D = 0x46200034, 371 MIPSI_C_OLT_D = 0x46200034,
252 MIPSI_C_ULT_D = 0x46200035, 372 MIPSI_C_ULT_D = 0x46200035,
253 MIPSI_C_OLE_D = 0x46200036, 373 MIPSI_C_OLE_D = 0x46200036,
254 MIPSI_C_ULE_D = 0x46200037, 374 MIPSI_C_ULE_D = 0x46200037,
255
256} MIPSIns; 375} MIPSIns;
257 376
258#endif 377#endif
diff --git a/src/lj_target_ppc.h b/src/lj_target_ppc.h
index e57e27df..c5c991a3 100644
--- a/src/lj_target_ppc.h
+++ b/src/lj_target_ppc.h
@@ -104,7 +104,7 @@ enum {
104/* This definition must match with the *.dasc file(s). */ 104/* This definition must match with the *.dasc file(s). */
105typedef struct { 105typedef struct {
106 lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ 106 lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */
107 int32_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ 107 intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */
108 int32_t spill[256]; /* Spill slots. */ 108 int32_t spill[256]; /* Spill slots. */
109} ExitState; 109} ExitState;
110 110
diff --git a/src/lj_target_x86.h b/src/lj_target_x86.h
index 4426cc8c..356f7924 100644
--- a/src/lj_target_x86.h
+++ b/src/lj_target_x86.h
@@ -22,7 +22,7 @@
22 _(XMM0) _(XMM1) _(XMM2) _(XMM3) _(XMM4) _(XMM5) _(XMM6) _(XMM7) 22 _(XMM0) _(XMM1) _(XMM2) _(XMM3) _(XMM4) _(XMM5) _(XMM6) _(XMM7)
23#endif 23#endif
24#define VRIDDEF(_) \ 24#define VRIDDEF(_) \
25 _(MRM) 25 _(MRM) _(RIP)
26 26
27#define RIDENUM(name) RID_##name, 27#define RIDENUM(name) RID_##name,
28 28
@@ -31,8 +31,10 @@ enum {
31 FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ 31 FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */
32 RID_MAX, 32 RID_MAX,
33 RID_MRM = RID_MAX, /* Pseudo-id for ModRM operand. */ 33 RID_MRM = RID_MAX, /* Pseudo-id for ModRM operand. */
34 RID_RIP = RID_MAX+5, /* Pseudo-id for RIP (x64 only), rm bits = 5. */
34 35
35 /* Calling conventions. */ 36 /* Calling conventions. */
37 RID_SP = RID_ESP,
36 RID_RET = RID_EAX, 38 RID_RET = RID_EAX,
37#if LJ_64 39#if LJ_64
38 RID_FPRET = RID_XMM0, 40 RID_FPRET = RID_XMM0,
@@ -62,8 +64,10 @@ enum {
62 64
63/* -- Register sets ------------------------------------------------------- */ 65/* -- Register sets ------------------------------------------------------- */
64 66
65/* Make use of all registers, except the stack pointer. */ 67/* Make use of all registers, except the stack pointer (and maybe DISPATCH). */
66#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR)-RID2RSET(RID_ESP)) 68#define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) \
69 - RID2RSET(RID_ESP) \
70 - LJ_GC64*RID2RSET(RID_DISPATCH))
67#define RSET_FPR (RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR)) 71#define RSET_FPR (RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR))
68#define RSET_ALL (RSET_GPR|RSET_FPR) 72#define RSET_ALL (RSET_GPR|RSET_FPR)
69#define RSET_INIT RSET_ALL 73#define RSET_INIT RSET_ALL
@@ -131,7 +135,11 @@ enum {
131#define SPS_FIXED (4*2) 135#define SPS_FIXED (4*2)
132#define SPS_FIRST (4*2) /* Don't use callee register save area. */ 136#define SPS_FIRST (4*2) /* Don't use callee register save area. */
133#else 137#else
138#if LJ_GC64
139#define SPS_FIXED 2
140#else
134#define SPS_FIXED 4 141#define SPS_FIXED 4
142#endif
135#define SPS_FIRST 2 143#define SPS_FIRST 2
136#endif 144#endif
137#else 145#else
@@ -184,12 +192,18 @@ typedef struct {
184#define XO_f20f(o) ((uint32_t)(0x0ff2fc + (0x##o<<24))) 192#define XO_f20f(o) ((uint32_t)(0x0ff2fc + (0x##o<<24)))
185#define XO_f30f(o) ((uint32_t)(0x0ff3fc + (0x##o<<24))) 193#define XO_f30f(o) ((uint32_t)(0x0ff3fc + (0x##o<<24)))
186 194
195#define XV_660f38(o) ((uint32_t)(0x79e2c4 + (0x##o<<24)))
196#define XV_f20f38(o) ((uint32_t)(0x7be2c4 + (0x##o<<24)))
197#define XV_f20f3a(o) ((uint32_t)(0x7be3c4 + (0x##o<<24)))
198#define XV_f30f38(o) ((uint32_t)(0x7ae2c4 + (0x##o<<24)))
199
187/* This list of x86 opcodes is not intended to be complete. Opcodes are only 200/* This list of x86 opcodes is not intended to be complete. Opcodes are only
188** included when needed. Take a look at DynASM or jit.dis_x86 to see the 201** included when needed. Take a look at DynASM or jit.dis_x86 to see the
189** whole mess. 202** whole mess.
190*/ 203*/
191typedef enum { 204typedef enum {
192 /* Fixed length opcodes. XI_* prefix. */ 205 /* Fixed length opcodes. XI_* prefix. */
206 XI_O16 = 0x66,
193 XI_NOP = 0x90, 207 XI_NOP = 0x90,
194 XI_XCHGa = 0x90, 208 XI_XCHGa = 0x90,
195 XI_CALL = 0xe8, 209 XI_CALL = 0xe8,
@@ -207,6 +221,7 @@ typedef enum {
207 XI_PUSHi8 = 0x6a, 221 XI_PUSHi8 = 0x6a,
208 XI_TESTb = 0x84, 222 XI_TESTb = 0x84,
209 XI_TEST = 0x85, 223 XI_TEST = 0x85,
224 XI_INT3 = 0xcc,
210 XI_MOVmi = 0xc7, 225 XI_MOVmi = 0xc7,
211 XI_GROUP5 = 0xff, 226 XI_GROUP5 = 0xff,
212 227
@@ -226,7 +241,14 @@ typedef enum {
226 XI_FSCALE = 0xfdd9, 241 XI_FSCALE = 0xfdd9,
227 XI_FYL2X = 0xf1d9, 242 XI_FYL2X = 0xf1d9,
228 243
244 /* VEX-encoded instructions. XV_* prefix. */
245 XV_RORX = XV_f20f3a(f0),
246 XV_SARX = XV_f30f38(f7),
247 XV_SHLX = XV_660f38(f7),
248 XV_SHRX = XV_f20f38(f7),
249
229 /* Variable-length opcodes. XO_* prefix. */ 250 /* Variable-length opcodes. XO_* prefix. */
251 XO_OR = XO_(0b),
230 XO_MOV = XO_(8b), 252 XO_MOV = XO_(8b),
231 XO_MOVto = XO_(89), 253 XO_MOVto = XO_(89),
232 XO_MOVtow = XO_66(89), 254 XO_MOVtow = XO_66(89),
@@ -277,10 +299,8 @@ typedef enum {
277 XO_ROUNDSD = 0x0b3a0ffc, /* Really 66 0f 3a 0b. See asm_fpmath. */ 299 XO_ROUNDSD = 0x0b3a0ffc, /* Really 66 0f 3a 0b. See asm_fpmath. */
278 XO_UCOMISD = XO_660f(2e), 300 XO_UCOMISD = XO_660f(2e),
279 XO_CVTSI2SD = XO_f20f(2a), 301 XO_CVTSI2SD = XO_f20f(2a),
280 XO_CVTSD2SI = XO_f20f(2d),
281 XO_CVTTSD2SI= XO_f20f(2c), 302 XO_CVTTSD2SI= XO_f20f(2c),
282 XO_CVTSI2SS = XO_f30f(2a), 303 XO_CVTSI2SS = XO_f30f(2a),
283 XO_CVTSS2SI = XO_f30f(2d),
284 XO_CVTTSS2SI= XO_f30f(2c), 304 XO_CVTTSS2SI= XO_f30f(2c),
285 XO_CVTSS2SD = XO_f30f(5a), 305 XO_CVTSS2SD = XO_f30f(5a),
286 XO_CVTSD2SS = XO_f20f(5a), 306 XO_CVTSD2SS = XO_f20f(5a),
diff --git a/src/lj_trace.c b/src/lj_trace.c
index 6f8dc1a4..80a7f024 100644
--- a/src/lj_trace.c
+++ b/src/lj_trace.c
@@ -117,15 +117,26 @@ static void perftools_addtrace(GCtrace *T)
117} 117}
118#endif 118#endif
119 119
120/* Allocate space for copy of trace. */ 120/* Allocate space for copy of T. */
121static GCtrace *trace_save_alloc(jit_State *J) 121GCtrace * LJ_FASTCALL lj_trace_alloc(lua_State *L, GCtrace *T)
122{ 122{
123 size_t sztr = ((sizeof(GCtrace)+7)&~7); 123 size_t sztr = ((sizeof(GCtrace)+7)&~7);
124 size_t szins = (J->cur.nins-J->cur.nk)*sizeof(IRIns); 124 size_t szins = (T->nins-T->nk)*sizeof(IRIns);
125 size_t sz = sztr + szins + 125 size_t sz = sztr + szins +
126 J->cur.nsnap*sizeof(SnapShot) + 126 T->nsnap*sizeof(SnapShot) +
127 J->cur.nsnapmap*sizeof(SnapEntry); 127 T->nsnapmap*sizeof(SnapEntry);
128 return lj_mem_newt(J->L, (MSize)sz, GCtrace); 128 GCtrace *T2 = lj_mem_newt(L, (MSize)sz, GCtrace);
129 char *p = (char *)T2 + sztr;
130 T2->gct = ~LJ_TTRACE;
131 T2->marked = 0;
132 T2->traceno = 0;
133 T2->ir = (IRIns *)p - T->nk;
134 T2->nins = T->nins;
135 T2->nk = T->nk;
136 T2->nsnap = T->nsnap;
137 T2->nsnapmap = T->nsnapmap;
138 memcpy(p, T->ir + T->nk, szins);
139 return T2;
129} 140}
130 141
131/* Save current trace by copying and compacting it. */ 142/* Save current trace by copying and compacting it. */
@@ -139,12 +150,12 @@ static void trace_save(jit_State *J, GCtrace *T)
139 setgcrefp(J2G(J)->gc.root, T); 150 setgcrefp(J2G(J)->gc.root, T);
140 newwhite(J2G(J), T); 151 newwhite(J2G(J), T);
141 T->gct = ~LJ_TTRACE; 152 T->gct = ~LJ_TTRACE;
142 T->ir = (IRIns *)p - J->cur.nk; 153 T->ir = (IRIns *)p - J->cur.nk; /* The IR has already been copied above. */
143 memcpy(p, J->cur.ir+J->cur.nk, szins);
144 p += szins; 154 p += szins;
145 TRACE_APPENDVEC(snap, nsnap, SnapShot) 155 TRACE_APPENDVEC(snap, nsnap, SnapShot)
146 TRACE_APPENDVEC(snapmap, nsnapmap, SnapEntry) 156 TRACE_APPENDVEC(snapmap, nsnapmap, SnapEntry)
147 J->cur.traceno = 0; 157 J->cur.traceno = 0;
158 J->curfinal = NULL;
148 setgcrefp(J->trace[T->traceno], T); 159 setgcrefp(J->trace[T->traceno], T);
149 lj_gc_barriertrace(J2G(J), T->traceno); 160 lj_gc_barriertrace(J2G(J), T->traceno);
150 lj_gdbjit_addtrace(J, T); 161 lj_gdbjit_addtrace(J, T);
@@ -274,7 +285,7 @@ int lj_trace_flushall(lua_State *L)
274 if (T->root == 0) 285 if (T->root == 0)
275 trace_flushroot(J, T); 286 trace_flushroot(J, T);
276 lj_gdbjit_deltrace(J, T); 287 lj_gdbjit_deltrace(J, T);
277 T->traceno = 0; 288 T->traceno = T->link = 0; /* Blacklist the link for cont_stitch. */
278 setgcrefnull(J->trace[i]); 289 setgcrefnull(J->trace[i]);
279 } 290 }
280 } 291 }
@@ -296,13 +307,42 @@ void lj_trace_initstate(global_State *g)
296{ 307{
297 jit_State *J = G2J(g); 308 jit_State *J = G2J(g);
298 TValue *tv; 309 TValue *tv;
299 /* Initialize SIMD constants. */ 310
311 /* Initialize aligned SIMD constants. */
300 tv = LJ_KSIMD(J, LJ_KSIMD_ABS); 312 tv = LJ_KSIMD(J, LJ_KSIMD_ABS);
301 tv[0].u64 = U64x(7fffffff,ffffffff); 313 tv[0].u64 = U64x(7fffffff,ffffffff);
302 tv[1].u64 = U64x(7fffffff,ffffffff); 314 tv[1].u64 = U64x(7fffffff,ffffffff);
303 tv = LJ_KSIMD(J, LJ_KSIMD_NEG); 315 tv = LJ_KSIMD(J, LJ_KSIMD_NEG);
304 tv[0].u64 = U64x(80000000,00000000); 316 tv[0].u64 = U64x(80000000,00000000);
305 tv[1].u64 = U64x(80000000,00000000); 317 tv[1].u64 = U64x(80000000,00000000);
318
319 /* Initialize 32/64 bit constants. */
320#if LJ_TARGET_X86ORX64
321 J->k64[LJ_K64_TOBIT].u64 = U64x(43380000,00000000);
322#if LJ_32
323 J->k64[LJ_K64_M2P64_31].u64 = U64x(c1e00000,00000000);
324#endif
325 J->k64[LJ_K64_2P64].u64 = U64x(43f00000,00000000);
326 J->k32[LJ_K32_M2P64_31] = LJ_64 ? 0xdf800000 : 0xcf000000;
327#endif
328#if LJ_TARGET_X86ORX64 || LJ_TARGET_MIPS64
329 J->k64[LJ_K64_M2P64].u64 = U64x(c3f00000,00000000);
330#endif
331#if LJ_TARGET_PPC
332 J->k32[LJ_K32_2P52_2P31] = 0x59800004;
333 J->k32[LJ_K32_2P52] = 0x59800000;
334#endif
335#if LJ_TARGET_PPC || LJ_TARGET_MIPS
336 J->k32[LJ_K32_2P31] = 0x4f000000;
337#endif
338#if LJ_TARGET_MIPS
339 J->k64[LJ_K64_2P31].u64 = U64x(41e00000,00000000);
340#if LJ_64
341 J->k64[LJ_K64_2P63].u64 = U64x(43e00000,00000000);
342 J->k32[LJ_K32_2P63] = 0x5f000000;
343 J->k32[LJ_K32_M2P64] = 0xdf800000;
344#endif
345#endif
306} 346}
307 347
308/* Free everything associated with the JIT compiler state. */ 348/* Free everything associated with the JIT compiler state. */
@@ -317,7 +357,6 @@ void lj_trace_freestate(global_State *g)
317 } 357 }
318#endif 358#endif
319 lj_mcode_free(J); 359 lj_mcode_free(J);
320 lj_ir_k64_freeall(J);
321 lj_mem_freevec(g, J->snapmapbuf, J->sizesnapmap, SnapEntry); 360 lj_mem_freevec(g, J->snapmapbuf, J->sizesnapmap, SnapEntry);
322 lj_mem_freevec(g, J->snapbuf, J->sizesnap, SnapShot); 361 lj_mem_freevec(g, J->snapbuf, J->sizesnap, SnapShot);
323 lj_mem_freevec(g, J->irbuf + J->irbotlim, J->irtoplim - J->irbotlim, IRIns); 362 lj_mem_freevec(g, J->irbuf + J->irbotlim, J->irtoplim - J->irbotlim, IRIns);
@@ -367,7 +406,7 @@ static void trace_start(jit_State *J)
367 TraceNo traceno; 406 TraceNo traceno;
368 407
369 if ((J->pt->flags & PROTO_NOJIT)) { /* JIT disabled for this proto? */ 408 if ((J->pt->flags & PROTO_NOJIT)) { /* JIT disabled for this proto? */
370 if (J->parent == 0) { 409 if (J->parent == 0 && J->exitno == 0) {
371 /* Lazy bytecode patching to disable hotcount events. */ 410 /* Lazy bytecode patching to disable hotcount events. */
372 lua_assert(bc_op(*J->pc) == BC_FORL || bc_op(*J->pc) == BC_ITERL || 411 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); 412 bc_op(*J->pc) == BC_LOOP || bc_op(*J->pc) == BC_FUNCF);
@@ -401,6 +440,8 @@ static void trace_start(jit_State *J)
401 J->guardemit.irt = 0; 440 J->guardemit.irt = 0;
402 J->postproc = LJ_POST_NONE; 441 J->postproc = LJ_POST_NONE;
403 lj_resetsplit(J); 442 lj_resetsplit(J);
443 J->retryrec = 0;
444 J->ktrace = 0;
404 setgcref(J->cur.startpt, obj2gco(J->pt)); 445 setgcref(J->cur.startpt, obj2gco(J->pt));
405 446
406 L = J->L; 447 L = J->L;
@@ -412,6 +453,12 @@ static void trace_start(jit_State *J)
412 if (J->parent) { 453 if (J->parent) {
413 setintV(L->top++, J->parent); 454 setintV(L->top++, J->parent);
414 setintV(L->top++, J->exitno); 455 setintV(L->top++, J->exitno);
456 } else {
457 BCOp op = bc_op(*J->pc);
458 if (op == BC_CALLM || op == BC_CALL || op == BC_ITERC) {
459 setintV(L->top++, J->exitno); /* Parent of stitched trace. */
460 setintV(L->top++, -1);
461 }
415 } 462 }
416 ); 463 );
417 lj_record_setup(J); 464 lj_record_setup(J);
@@ -424,7 +471,7 @@ static void trace_stop(jit_State *J)
424 BCOp op = bc_op(J->cur.startins); 471 BCOp op = bc_op(J->cur.startins);
425 GCproto *pt = &gcref(J->cur.startpt)->pt; 472 GCproto *pt = &gcref(J->cur.startpt)->pt;
426 TraceNo traceno = J->cur.traceno; 473 TraceNo traceno = J->cur.traceno;
427 GCtrace *T = trace_save_alloc(J); /* Do this first. May throw OOM. */ 474 GCtrace *T = J->curfinal;
428 lua_State *L; 475 lua_State *L;
429 476
430 switch (op) { 477 switch (op) {
@@ -461,6 +508,12 @@ static void trace_stop(jit_State *J)
461 root->nextside = (TraceNo1)traceno; 508 root->nextside = (TraceNo1)traceno;
462 } 509 }
463 break; 510 break;
511 case BC_CALLM:
512 case BC_CALL:
513 case BC_ITERC:
514 /* Trace stitching: patch link of previous trace. */
515 traceref(J, J->exitno)->link = traceno;
516 break;
464 default: 517 default:
465 lua_assert(0); 518 lua_assert(0);
466 break; 519 break;
@@ -475,6 +528,7 @@ static void trace_stop(jit_State *J)
475 lj_vmevent_send(L, TRACE, 528 lj_vmevent_send(L, TRACE,
476 setstrV(L, L->top++, lj_str_newlit(L, "stop")); 529 setstrV(L, L->top++, lj_str_newlit(L, "stop"));
477 setintV(L->top++, traceno); 530 setintV(L->top++, traceno);
531 setfuncV(L, L->top++, J->fn);
478 ); 532 );
479} 533}
480 534
@@ -502,6 +556,10 @@ static int trace_abort(jit_State *J)
502 556
503 J->postproc = LJ_POST_NONE; 557 J->postproc = LJ_POST_NONE;
504 lj_mcode_abort(J); 558 lj_mcode_abort(J);
559 if (J->curfinal) {
560 lj_trace_free(J2G(J), J->curfinal);
561 J->curfinal = NULL;
562 }
505 if (tvisnumber(L->top-1)) 563 if (tvisnumber(L->top-1))
506 e = (TraceError)numberVint(L->top-1); 564 e = (TraceError)numberVint(L->top-1);
507 if (e == LJ_TRERR_MCODELM) { 565 if (e == LJ_TRERR_MCODELM) {
@@ -510,8 +568,17 @@ static int trace_abort(jit_State *J)
510 return 1; /* Retry ASM with new MCode area. */ 568 return 1; /* Retry ASM with new MCode area. */
511 } 569 }
512 /* Penalize or blacklist starting bytecode instruction. */ 570 /* Penalize or blacklist starting bytecode instruction. */
513 if (J->parent == 0 && !bc_isret(bc_op(J->cur.startins))) 571 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); 572 if (J->exitno == 0) {
573 BCIns *startpc = mref(J->cur.startpc, BCIns);
574 if (e == LJ_TRERR_RETRY)
575 hotcount_set(J2GG(J), startpc+1, 1); /* Immediate retry. */
576 else
577 penalty_pc(J, &gcref(J->cur.startpt)->pt, startpc, e);
578 } else {
579 traceref(J, J->exitno)->link = J->exitno; /* Self-link is blacklisted. */
580 }
581 }
515 582
516 /* Is there anything to abort? */ 583 /* Is there anything to abort? */
517 traceno = J->cur.traceno; 584 traceno = J->cur.traceno;
@@ -680,6 +747,7 @@ static void trace_hotside(jit_State *J, const BCIns *pc)
680{ 747{
681 SnapShot *snap = &traceref(J, J->parent)->snap[J->exitno]; 748 SnapShot *snap = &traceref(J, J->parent)->snap[J->exitno];
682 if (!(J2G(J)->hookmask & (HOOK_GC|HOOK_VMEVENT)) && 749 if (!(J2G(J)->hookmask & (HOOK_GC|HOOK_VMEVENT)) &&
750 isluafunc(curr_func(J->L)) &&
683 snap->count != SNAPCOUNT_DONE && 751 snap->count != SNAPCOUNT_DONE &&
684 ++snap->count >= J->param[JIT_P_hotexit]) { 752 ++snap->count >= J->param[JIT_P_hotexit]) {
685 lua_assert(J->state == LJ_TRACE_IDLE); 753 lua_assert(J->state == LJ_TRACE_IDLE);
@@ -689,6 +757,20 @@ static void trace_hotside(jit_State *J, const BCIns *pc)
689 } 757 }
690} 758}
691 759
760/* Stitch a new trace to the previous trace. */
761void LJ_FASTCALL lj_trace_stitch(jit_State *J, const BCIns *pc)
762{
763 /* Only start a new trace if not recording or inside __gc call or vmevent. */
764 if (J->state == LJ_TRACE_IDLE &&
765 !(J2G(J)->hookmask & (HOOK_GC|HOOK_VMEVENT))) {
766 J->parent = 0; /* Have to treat it like a root trace. */
767 /* J->exitno is set to the invoking trace. */
768 J->state = LJ_TRACE_START;
769 lj_trace_ins(J, pc);
770 }
771}
772
773
692/* Tiny struct to pass data to protected call. */ 774/* Tiny struct to pass data to protected call. */
693typedef struct ExitDataCP { 775typedef struct ExitDataCP {
694 jit_State *J; 776 jit_State *J;
@@ -775,17 +857,20 @@ int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr)
775 if (errcode) 857 if (errcode)
776 return -errcode; /* Return negated error code. */ 858 return -errcode; /* Return negated error code. */
777 859
778 lj_vmevent_send(L, TEXIT, 860 if (!(LJ_HASPROFILE && (G(L)->hookmask & HOOK_PROFILE)))
779 lj_state_checkstack(L, 4+RID_NUM_GPR+RID_NUM_FPR+LUA_MINSTACK); 861 lj_vmevent_send(L, TEXIT,
780 setintV(L->top++, J->parent); 862 lj_state_checkstack(L, 4+RID_NUM_GPR+RID_NUM_FPR+LUA_MINSTACK);
781 setintV(L->top++, J->exitno); 863 setintV(L->top++, J->parent);
782 trace_exit_regs(L, ex); 864 setintV(L->top++, J->exitno);
783 ); 865 trace_exit_regs(L, ex);
866 );
784 867
785 pc = exd.pc; 868 pc = exd.pc;
786 cf = cframe_raw(L->cframe); 869 cf = cframe_raw(L->cframe);
787 setcframe_pc(cf, pc); 870 setcframe_pc(cf, pc);
788 if (G(L)->gc.state == GCSatomic || G(L)->gc.state == GCSfinalize) { 871 if (LJ_HASPROFILE && (G(L)->hookmask & HOOK_PROFILE)) {
872 /* Just exit to interpreter. */
873 } else if (G(L)->gc.state == GCSatomic || G(L)->gc.state == GCSfinalize) {
789 if (!(G(L)->hookmask & HOOK_GC)) 874 if (!(G(L)->hookmask & HOOK_GC))
790 lj_gc_step(L); /* Exited because of GC: drive GC forward. */ 875 lj_gc_step(L); /* Exited because of GC: drive GC forward. */
791 } else { 876 } else {
@@ -809,7 +894,7 @@ int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr)
809 ERRNO_RESTORE 894 ERRNO_RESTORE
810 switch (bc_op(*pc)) { 895 switch (bc_op(*pc)) {
811 case BC_CALLM: case BC_CALLMT: 896 case BC_CALLM: case BC_CALLMT:
812 return (int)((BCReg)(L->top - L->base) - bc_a(*pc) - bc_c(*pc)); 897 return (int)((BCReg)(L->top - L->base) - bc_a(*pc) - bc_c(*pc) + LJ_FR2);
813 case BC_RETM: 898 case BC_RETM:
814 return (int)((BCReg)(L->top - L->base) + 1 - bc_a(*pc) - bc_d(*pc)); 899 return (int)((BCReg)(L->top - L->base) + 1 - bc_a(*pc) - bc_d(*pc));
815 case BC_TSETM: 900 case BC_TSETM:
diff --git a/src/lj_trace.h b/src/lj_trace.h
index edc7af0d..22cae741 100644
--- a/src/lj_trace.h
+++ b/src/lj_trace.h
@@ -23,6 +23,7 @@ LJ_FUNC_NORET void lj_trace_err(jit_State *J, TraceError e);
23LJ_FUNC_NORET void lj_trace_err_info(jit_State *J, TraceError e); 23LJ_FUNC_NORET void lj_trace_err_info(jit_State *J, TraceError e);
24 24
25/* Trace management. */ 25/* Trace management. */
26LJ_FUNC GCtrace * LJ_FASTCALL lj_trace_alloc(lua_State *L, GCtrace *T);
26LJ_FUNC void LJ_FASTCALL lj_trace_free(global_State *g, GCtrace *T); 27LJ_FUNC void LJ_FASTCALL lj_trace_free(global_State *g, GCtrace *T);
27LJ_FUNC void lj_trace_reenableproto(GCproto *pt); 28LJ_FUNC void lj_trace_reenableproto(GCproto *pt);
28LJ_FUNC void lj_trace_flushproto(global_State *g, GCproto *pt); 29LJ_FUNC void lj_trace_flushproto(global_State *g, GCproto *pt);
@@ -34,6 +35,7 @@ LJ_FUNC void lj_trace_freestate(global_State *g);
34/* Event handling. */ 35/* Event handling. */
35LJ_FUNC void lj_trace_ins(jit_State *J, const BCIns *pc); 36LJ_FUNC void lj_trace_ins(jit_State *J, const BCIns *pc);
36LJ_FUNCA void LJ_FASTCALL lj_trace_hot(jit_State *J, const BCIns *pc); 37LJ_FUNCA void LJ_FASTCALL lj_trace_hot(jit_State *J, const BCIns *pc);
38LJ_FUNCA void LJ_FASTCALL lj_trace_stitch(jit_State *J, const BCIns *pc);
37LJ_FUNCA int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr); 39LJ_FUNCA int LJ_FASTCALL lj_trace_exit(jit_State *J, void *exptr);
38 40
39/* Signal asynchronous abort of trace or end of trace. */ 41/* Signal asynchronous abort of trace or end of trace. */
diff --git a/src/lj_traceerr.h b/src/lj_traceerr.h
index f920e5ed..1363c4f3 100644
--- a/src/lj_traceerr.h
+++ b/src/lj_traceerr.h
@@ -7,10 +7,12 @@
7 7
8/* Recording. */ 8/* Recording. */
9TREDEF(RECERR, "error thrown or hook called during recording") 9TREDEF(RECERR, "error thrown or hook called during recording")
10TREDEF(TRACEUV, "trace too short")
10TREDEF(TRACEOV, "trace too long") 11TREDEF(TRACEOV, "trace too long")
11TREDEF(STACKOV, "trace too deep") 12TREDEF(STACKOV, "trace too deep")
12TREDEF(SNAPOV, "too many snapshots") 13TREDEF(SNAPOV, "too many snapshots")
13TREDEF(BLACKL, "blacklisted") 14TREDEF(BLACKL, "blacklisted")
15TREDEF(RETRY, "retry recording")
14TREDEF(NYIBC, "NYI: bytecode %d") 16TREDEF(NYIBC, "NYI: bytecode %d")
15 17
16/* Recording loop ops. */ 18/* Recording loop ops. */
@@ -23,8 +25,6 @@ TREDEF(BADTYPE, "bad argument type")
23TREDEF(CJITOFF, "JIT compilation disabled for function") 25TREDEF(CJITOFF, "JIT compilation disabled for function")
24TREDEF(CUNROLL, "call unroll limit reached") 26TREDEF(CUNROLL, "call unroll limit reached")
25TREDEF(DOWNREC, "down-recursion, restarting") 27TREDEF(DOWNREC, "down-recursion, restarting")
26TREDEF(NYICF, "NYI: C function %s")
27TREDEF(NYIFF, "NYI: FastFunc %s")
28TREDEF(NYIFFU, "NYI: unsupported variant of FastFunc %s") 28TREDEF(NYIFFU, "NYI: unsupported variant of FastFunc %s")
29TREDEF(NYIRETL, "NYI: return to lower frame") 29TREDEF(NYIRETL, "NYI: return to lower frame")
30 30
diff --git a/src/lj_vm.h b/src/lj_vm.h
index 3ffa76bf..1cc7eed7 100644
--- a/src/lj_vm.h
+++ b/src/lj_vm.h
@@ -17,6 +17,10 @@ LJ_ASMF int lj_vm_cpcall(lua_State *L, lua_CFunction func, void *ud,
17LJ_ASMF int lj_vm_resume(lua_State *L, TValue *base, int nres1, ptrdiff_t ef); 17LJ_ASMF int lj_vm_resume(lua_State *L, TValue *base, int nres1, ptrdiff_t ef);
18LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_c(void *cframe, int errcode); 18LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_c(void *cframe, int errcode);
19LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_ff(void *cframe); 19LJ_ASMF_NORET void LJ_FASTCALL lj_vm_unwind_ff(void *cframe);
20#if LJ_ABI_WIN && LJ_TARGET_X86
21LJ_ASMF_NORET void LJ_FASTCALL lj_vm_rtlunwind(void *cframe, void *excptrec,
22 void *unwinder, int errcode);
23#endif
20LJ_ASMF void lj_vm_unwind_c_eh(void); 24LJ_ASMF void lj_vm_unwind_c_eh(void);
21LJ_ASMF void lj_vm_unwind_ff_eh(void); 25LJ_ASMF void lj_vm_unwind_ff_eh(void);
22#if LJ_TARGET_X86ORX64 26#if LJ_TARGET_X86ORX64
@@ -43,13 +47,14 @@ LJ_ASMF void lj_vm_record(void);
43LJ_ASMF void lj_vm_inshook(void); 47LJ_ASMF void lj_vm_inshook(void);
44LJ_ASMF void lj_vm_rethook(void); 48LJ_ASMF void lj_vm_rethook(void);
45LJ_ASMF void lj_vm_callhook(void); 49LJ_ASMF void lj_vm_callhook(void);
50LJ_ASMF void lj_vm_profhook(void);
46 51
47/* Trace exit handling. */ 52/* Trace exit handling. */
48LJ_ASMF void lj_vm_exit_handler(void); 53LJ_ASMF void lj_vm_exit_handler(void);
49LJ_ASMF void lj_vm_exit_interp(void); 54LJ_ASMF void lj_vm_exit_interp(void);
50 55
51/* Internal math helper functions. */ 56/* Internal math helper functions. */
52#if LJ_TARGET_X86ORX64 || LJ_TARGET_PPC 57#if LJ_TARGET_PPC || LJ_TARGET_ARM64 || (LJ_TARGET_MIPS && LJ_ABI_SOFTFP)
53#define lj_vm_floor floor 58#define lj_vm_floor floor
54#define lj_vm_ceil ceil 59#define lj_vm_ceil ceil
55#else 60#else
@@ -60,23 +65,26 @@ LJ_ASMF double lj_vm_floor_sf(double);
60LJ_ASMF double lj_vm_ceil_sf(double); 65LJ_ASMF double lj_vm_ceil_sf(double);
61#endif 66#endif
62#endif 67#endif
63#if defined(LUAJIT_NO_LOG2) || LJ_TARGET_X86ORX64 68#ifdef LUAJIT_NO_LOG2
64LJ_ASMF double lj_vm_log2(double); 69LJ_ASMF double lj_vm_log2(double);
65#else 70#else
66#define lj_vm_log2 log2 71#define lj_vm_log2 log2
67#endif 72#endif
73#if !(defined(_LJ_DISPATCH_H) && LJ_TARGET_MIPS)
74LJ_ASMF int32_t LJ_FASTCALL lj_vm_modi(int32_t, int32_t);
75#endif
68 76
69#if LJ_HASJIT 77#if LJ_HASJIT
70#if LJ_TARGET_X86ORX64 78#if LJ_TARGET_X86ORX64
71LJ_ASMF void lj_vm_floor_sse(void); 79LJ_ASMF void lj_vm_floor_sse(void);
72LJ_ASMF void lj_vm_ceil_sse(void); 80LJ_ASMF void lj_vm_ceil_sse(void);
73LJ_ASMF void lj_vm_trunc_sse(void); 81LJ_ASMF void lj_vm_trunc_sse(void);
74LJ_ASMF void lj_vm_exp_x87(void);
75LJ_ASMF void lj_vm_exp2_x87(void);
76LJ_ASMF void lj_vm_pow_sse(void);
77LJ_ASMF void lj_vm_powi_sse(void); 82LJ_ASMF void lj_vm_powi_sse(void);
83#define lj_vm_powi NULL
78#else 84#else
79#if LJ_TARGET_PPC 85LJ_ASMF double lj_vm_powi(double, int32_t);
86#endif
87#if LJ_TARGET_PPC || LJ_TARGET_ARM64
80#define lj_vm_trunc trunc 88#define lj_vm_trunc trunc
81#else 89#else
82LJ_ASMF double lj_vm_trunc(double); 90LJ_ASMF double lj_vm_trunc(double);
@@ -84,14 +92,11 @@ LJ_ASMF double lj_vm_trunc(double);
84LJ_ASMF double lj_vm_trunc_sf(double); 92LJ_ASMF double lj_vm_trunc_sf(double);
85#endif 93#endif
86#endif 94#endif
87LJ_ASMF double lj_vm_powi(double, int32_t);
88#ifdef LUAJIT_NO_EXP2 95#ifdef LUAJIT_NO_EXP2
89LJ_ASMF double lj_vm_exp2(double); 96LJ_ASMF double lj_vm_exp2(double);
90#else 97#else
91#define lj_vm_exp2 exp2 98#define lj_vm_exp2 exp2
92#endif 99#endif
93#endif
94LJ_ASMF int32_t LJ_FASTCALL lj_vm_modi(int32_t, int32_t);
95#if LJ_HASFFI 100#if LJ_HASFFI
96LJ_ASMF int lj_vm_errno(void); 101LJ_ASMF int lj_vm_errno(void);
97#endif 102#endif
@@ -104,8 +109,7 @@ LJ_ASMF void lj_cont_nop(void); /* Do nothing, just continue execution. */
104LJ_ASMF void lj_cont_condt(void); /* Branch if result is true. */ 109LJ_ASMF void lj_cont_condt(void); /* Branch if result is true. */
105LJ_ASMF void lj_cont_condf(void); /* Branch if result is false. */ 110LJ_ASMF void lj_cont_condf(void); /* Branch if result is false. */
106LJ_ASMF void lj_cont_hook(void); /* Continue from hook yield. */ 111LJ_ASMF void lj_cont_hook(void); /* Continue from hook yield. */
107 112LJ_ASMF void lj_cont_stitch(void); /* Trace stitching. */
108enum { LJ_CONT_TAILCALL, LJ_CONT_FFI_CALLBACK }; /* Special continuations. */
109 113
110/* Start of the ASM code. */ 114/* Start of the ASM code. */
111LJ_ASMF char lj_vm_asm_begin[]; 115LJ_ASMF char lj_vm_asm_begin[];
diff --git a/src/lj_vmevent.c b/src/lj_vmevent.c
index 7b6d7bf3..86640804 100644
--- a/src/lj_vmevent.c
+++ b/src/lj_vmevent.c
@@ -27,6 +27,7 @@ ptrdiff_t lj_vmevent_prepare(lua_State *L, VMEvent ev)
27 if (tv && tvisfunc(tv)) { 27 if (tv && tvisfunc(tv)) {
28 lj_state_checkstack(L, LUA_MINSTACK); 28 lj_state_checkstack(L, LUA_MINSTACK);
29 setfuncV(L, L->top++, funcV(tv)); 29 setfuncV(L, L->top++, funcV(tv));
30 if (LJ_FR2) setnilV(L->top++);
30 return savestack(L, L->top); 31 return savestack(L, L->top);
31 } 32 }
32 } 33 }
diff --git a/src/lj_vmmath.c b/src/lj_vmmath.c
index 73fc667f..b231d3e8 100644
--- a/src/lj_vmmath.c
+++ b/src/lj_vmmath.c
@@ -13,16 +13,29 @@
13#include "lj_ir.h" 13#include "lj_ir.h"
14#include "lj_vm.h" 14#include "lj_vm.h"
15 15
16/* -- Helper functions for generated machine code ------------------------- */ 16/* -- Wrapper functions --------------------------------------------------- */
17 17
18#if LJ_TARGET_X86ORX64 18#if LJ_TARGET_X86 && __ELF__ && __PIC__
19/* Wrapper functions to avoid linker issues on OSX. */ 19/* Wrapper functions to deal with the ELF/x86 PIC disaster. */
20LJ_FUNCA double lj_vm_sinh(double x) { return sinh(x); } 20LJ_FUNCA double lj_wrap_log(double x) { return log(x); }
21LJ_FUNCA double lj_vm_cosh(double x) { return cosh(x); } 21LJ_FUNCA double lj_wrap_log10(double x) { return log10(x); }
22LJ_FUNCA double lj_vm_tanh(double x) { return tanh(x); } 22LJ_FUNCA double lj_wrap_exp(double x) { return exp(x); }
23LJ_FUNCA double lj_wrap_sin(double x) { return sin(x); }
24LJ_FUNCA double lj_wrap_cos(double x) { return cos(x); }
25LJ_FUNCA double lj_wrap_tan(double x) { return tan(x); }
26LJ_FUNCA double lj_wrap_asin(double x) { return asin(x); }
27LJ_FUNCA double lj_wrap_acos(double x) { return acos(x); }
28LJ_FUNCA double lj_wrap_atan(double x) { return atan(x); }
29LJ_FUNCA double lj_wrap_sinh(double x) { return sinh(x); }
30LJ_FUNCA double lj_wrap_cosh(double x) { return cosh(x); }
31LJ_FUNCA double lj_wrap_tanh(double x) { return tanh(x); }
32LJ_FUNCA double lj_wrap_atan2(double x, double y) { return atan2(x, y); }
33LJ_FUNCA double lj_wrap_pow(double x, double y) { return pow(x, y); }
34LJ_FUNCA double lj_wrap_fmod(double x, double y) { return fmod(x, y); }
23#endif 35#endif
24 36
25#if !LJ_TARGET_X86ORX64 37/* -- Helper functions for generated machine code ------------------------- */
38
26double lj_vm_foldarith(double x, double y, int op) 39double lj_vm_foldarith(double x, double y, int op)
27{ 40{
28 switch (op) { 41 switch (op) {
@@ -43,6 +56,19 @@ double lj_vm_foldarith(double x, double y, int op)
43 default: return x; 56 default: return x;
44 } 57 }
45} 58}
59
60#if (LJ_HASJIT && !(LJ_TARGET_ARM || LJ_TARGET_ARM64 || LJ_TARGET_PPC)) || LJ_TARGET_MIPS
61int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b)
62{
63 uint32_t y, ua, ub;
64 lua_assert(b != 0); /* This must be checked before using this function. */
65 ua = a < 0 ? (uint32_t)-a : (uint32_t)a;
66 ub = b < 0 ? (uint32_t)-b : (uint32_t)b;
67 y = ua % ub;
68 if (y != 0 && (a^b) < 0) y = y - ub;
69 if (((int32_t)y^b) < 0) y = (uint32_t)-(int32_t)y;
70 return (int32_t)y;
71}
46#endif 72#endif
47 73
48#if LJ_HASJIT 74#if LJ_HASJIT
@@ -61,20 +87,6 @@ double lj_vm_exp2(double a)
61} 87}
62#endif 88#endif
63 89
64#if !(LJ_TARGET_ARM || LJ_TARGET_PPC)
65int32_t LJ_FASTCALL lj_vm_modi(int32_t a, int32_t b)
66{
67 uint32_t y, ua, ub;
68 lua_assert(b != 0); /* This must be checked before using this function. */
69 ua = a < 0 ? (uint32_t)-a : (uint32_t)a;
70 ub = b < 0 ? (uint32_t)-b : (uint32_t)b;
71 y = ua % ub;
72 if (y != 0 && (a^b) < 0) y = y - ub;
73 if (((int32_t)y^b) < 0) y = (uint32_t)-(int32_t)y;
74 return (int32_t)y;
75}
76#endif
77
78#if !LJ_TARGET_X86ORX64 90#if !LJ_TARGET_X86ORX64
79/* Unsigned x^k. */ 91/* Unsigned x^k. */
80static double lj_vm_powui(double x, uint32_t k) 92static double lj_vm_powui(double x, uint32_t k)
@@ -107,6 +119,7 @@ double lj_vm_powi(double x, int32_t k)
107 else 119 else
108 return 1.0 / lj_vm_powui(x, (uint32_t)-k); 120 return 1.0 / lj_vm_powui(x, (uint32_t)-k);
109} 121}
122#endif
110 123
111/* Computes fpm(x) for extended math functions. */ 124/* Computes fpm(x) for extended math functions. */
112double lj_vm_foldfpm(double x, int fpm) 125double lj_vm_foldfpm(double x, int fpm)
@@ -128,7 +141,6 @@ double lj_vm_foldfpm(double x, int fpm)
128 } 141 }
129 return 0; 142 return 0;
130} 143}
131#endif
132 144
133#if LJ_HASFFI 145#if LJ_HASFFI
134int lj_vm_errno(void) 146int lj_vm_errno(void)
diff --git a/src/ljamalg.c b/src/ljamalg.c
index 654fe82f..f1f28623 100644
--- a/src/ljamalg.c
+++ b/src/ljamalg.c
@@ -33,6 +33,7 @@
33#include "lj_char.c" 33#include "lj_char.c"
34#include "lj_bc.c" 34#include "lj_bc.c"
35#include "lj_obj.c" 35#include "lj_obj.c"
36#include "lj_buf.c"
36#include "lj_str.c" 37#include "lj_str.c"
37#include "lj_tab.c" 38#include "lj_tab.c"
38#include "lj_func.c" 39#include "lj_func.c"
@@ -44,7 +45,10 @@
44#include "lj_vmevent.c" 45#include "lj_vmevent.c"
45#include "lj_vmmath.c" 46#include "lj_vmmath.c"
46#include "lj_strscan.c" 47#include "lj_strscan.c"
48#include "lj_strfmt.c"
49#include "lj_strfmt_num.c"
47#include "lj_api.c" 50#include "lj_api.c"
51#include "lj_profile.c"
48#include "lj_lex.c" 52#include "lj_lex.c"
49#include "lj_parse.c" 53#include "lj_parse.c"
50#include "lj_bcread.c" 54#include "lj_bcread.c"
diff --git a/src/lua.h b/src/lua.h
index c83fd3bb..352d29f3 100644
--- a/src/lua.h
+++ b/src/lua.h
@@ -226,6 +226,7 @@ LUA_API int (lua_status) (lua_State *L);
226#define LUA_GCSTEP 5 226#define LUA_GCSTEP 5
227#define LUA_GCSETPAUSE 6 227#define LUA_GCSETPAUSE 6
228#define LUA_GCSETSTEPMUL 7 228#define LUA_GCSETSTEPMUL 7
229#define LUA_GCISRUNNING 9
229 230
230LUA_API int (lua_gc) (lua_State *L, int what, int data); 231LUA_API int (lua_gc) (lua_State *L, int what, int data);
231 232
diff --git a/src/luaconf.h b/src/luaconf.h
index 73b80f11..87b052db 100644
--- a/src/luaconf.h
+++ b/src/luaconf.h
@@ -37,7 +37,7 @@
37#endif 37#endif
38#define LUA_LROOT "/usr/local" 38#define LUA_LROOT "/usr/local"
39#define LUA_LUADIR "/lua/5.1/" 39#define LUA_LUADIR "/lua/5.1/"
40#define LUA_LJDIR "/luajit-2.0.4/" 40#define LUA_LJDIR "/luajit-2.1.0-beta2/"
41 41
42#ifdef LUA_ROOT 42#ifdef LUA_ROOT
43#define LUA_JROOT LUA_ROOT 43#define LUA_JROOT LUA_ROOT
diff --git a/src/luajit.c b/src/luajit.c
index 9e15b26d..8c8cf9e6 100644
--- a/src/luajit.c
+++ b/src/luajit.c
@@ -61,8 +61,9 @@ static void laction(int i)
61 61
62static void print_usage(void) 62static void print_usage(void)
63{ 63{
64 fprintf(stderr, 64 fputs("usage: ", stderr);
65 "usage: %s [options]... [script [args]...].\n" 65 fputs(progname, stderr);
66 fputs(" [options]... [script [args]...].\n"
66 "Available options are:\n" 67 "Available options are:\n"
67 " -e chunk Execute string " LUA_QL("chunk") ".\n" 68 " -e chunk Execute string " LUA_QL("chunk") ".\n"
68 " -l name Require library " LUA_QL("name") ".\n" 69 " -l name Require library " LUA_QL("name") ".\n"
@@ -73,16 +74,14 @@ static void print_usage(void)
73 " -v Show version information.\n" 74 " -v Show version information.\n"
74 " -E Ignore environment variables.\n" 75 " -E Ignore environment variables.\n"
75 " -- Stop handling options.\n" 76 " -- Stop handling options.\n"
76 " - Execute stdin and stop handling options.\n" 77 " - Execute stdin and stop handling options.\n", stderr);
77 ,
78 progname);
79 fflush(stderr); 78 fflush(stderr);
80} 79}
81 80
82static void l_message(const char *pname, const char *msg) 81static void l_message(const char *pname, const char *msg)
83{ 82{
84 if (pname) fprintf(stderr, "%s: ", pname); 83 if (pname) { fputs(pname, stderr); fputc(':', stderr); fputc(' ', stderr); }
85 fprintf(stderr, "%s\n", msg); 84 fputs(msg, stderr); fputc('\n', stderr);
86 fflush(stderr); 85 fflush(stderr);
87} 86}
88 87
@@ -153,22 +152,15 @@ static void print_jit_status(lua_State *L)
153 putc('\n', stdout); 152 putc('\n', stdout);
154} 153}
155 154
156static int getargs(lua_State *L, char **argv, int n) 155static void createargtable(lua_State *L, char **argv, int argc, int argf)
157{ 156{
158 int narg;
159 int i; 157 int i;
160 int argc = 0; 158 lua_createtable(L, argc - argf, argf);
161 while (argv[argc]) argc++; /* count total number of arguments */
162 narg = argc - (n + 1); /* number of arguments to the script */
163 luaL_checkstack(L, narg + 3, "too many arguments to script");
164 for (i = n+1; i < argc; i++)
165 lua_pushstring(L, argv[i]);
166 lua_createtable(L, narg, n + 1);
167 for (i = 0; i < argc; i++) { 159 for (i = 0; i < argc; i++) {
168 lua_pushstring(L, argv[i]); 160 lua_pushstring(L, argv[i]);
169 lua_rawseti(L, -2, i - n); 161 lua_rawseti(L, -2, i - argf);
170 } 162 }
171 return narg; 163 lua_setglobal(L, "arg");
172} 164}
173 165
174static int dofile(lua_State *L, const char *name) 166static int dofile(lua_State *L, const char *name)
@@ -274,21 +266,30 @@ static void dotty(lua_State *L)
274 progname = oldprogname; 266 progname = oldprogname;
275} 267}
276 268
277static int handle_script(lua_State *L, char **argv, int n) 269static int handle_script(lua_State *L, char **argx)
278{ 270{
279 int status; 271 int status;
280 const char *fname; 272 const char *fname = argx[0];
281 int narg = getargs(L, argv, n); /* collect arguments */ 273 if (strcmp(fname, "-") == 0 && strcmp(argx[-1], "--") != 0)
282 lua_setglobal(L, "arg");
283 fname = argv[n];
284 if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
285 fname = NULL; /* stdin */ 274 fname = NULL; /* stdin */
286 status = luaL_loadfile(L, fname); 275 status = luaL_loadfile(L, fname);
287 lua_insert(L, -(narg+1)); 276 if (status == 0) {
288 if (status == 0) 277 /* Fetch args from arg table. LUA_INIT or -e might have changed them. */
278 int narg = 0;
279 lua_getglobal(L, "arg");
280 if (lua_istable(L, -1)) {
281 do {
282 narg++;
283 lua_rawgeti(L, -narg, narg);
284 } while (!lua_isnil(L, -1));
285 lua_pop(L, 1);
286 lua_remove(L, -narg);
287 narg--;
288 } else {
289 lua_pop(L, 1);
290 }
289 status = docall(L, narg, 0); 291 status = docall(L, narg, 0);
290 else 292 }
291 lua_pop(L, narg);
292 return report(L, status); 293 return report(L, status);
293} 294}
294 295
@@ -385,7 +386,8 @@ static int dobytecode(lua_State *L, char **argv)
385 } 386 }
386 for (argv++; *argv != NULL; narg++, argv++) 387 for (argv++; *argv != NULL; narg++, argv++)
387 lua_pushstring(L, *argv); 388 lua_pushstring(L, *argv);
388 return report(L, lua_pcall(L, narg, 0, 0)); 389 report(L, lua_pcall(L, narg, 0, 0));
390 return -1;
389} 391}
390 392
391/* check that argument has no extra characters at the end */ 393/* check that argument has no extra characters at the end */
@@ -406,7 +408,7 @@ static int collectargs(char **argv, int *flags)
406 switch (argv[i][1]) { /* Check option. */ 408 switch (argv[i][1]) { /* Check option. */
407 case '-': 409 case '-':
408 notail(argv[i]); 410 notail(argv[i]);
409 return (argv[i+1] != NULL ? i+1 : 0); 411 return i+1;
410 case '\0': 412 case '\0':
411 return i; 413 return i;
412 case 'i': 414 case 'i':
@@ -431,23 +433,23 @@ static int collectargs(char **argv, int *flags)
431 case 'b': /* LuaJIT extension */ 433 case 'b': /* LuaJIT extension */
432 if (*flags) return -1; 434 if (*flags) return -1;
433 *flags |= FLAGS_EXEC; 435 *flags |= FLAGS_EXEC;
434 return 0; 436 return i+1;
435 case 'E': 437 case 'E':
436 *flags |= FLAGS_NOENV; 438 *flags |= FLAGS_NOENV;
437 break; 439 break;
438 default: return -1; /* invalid option */ 440 default: return -1; /* invalid option */
439 } 441 }
440 } 442 }
441 return 0; 443 return i;
442} 444}
443 445
444static int runargs(lua_State *L, char **argv, int n) 446static int runargs(lua_State *L, char **argv, int argn)
445{ 447{
446 int i; 448 int i;
447 for (i = 1; i < n; i++) { 449 for (i = 1; i < argn; i++) {
448 if (argv[i] == NULL) continue; 450 if (argv[i] == NULL) continue;
449 lua_assert(argv[i][0] == '-'); 451 lua_assert(argv[i][0] == '-');
450 switch (argv[i][1]) { /* option */ 452 switch (argv[i][1]) {
451 case 'e': { 453 case 'e': {
452 const char *chunk = argv[i] + 2; 454 const char *chunk = argv[i] + 2;
453 if (*chunk == '\0') chunk = argv[++i]; 455 if (*chunk == '\0') chunk = argv[++i];
@@ -461,10 +463,10 @@ static int runargs(lua_State *L, char **argv, int n)
461 if (*filename == '\0') filename = argv[++i]; 463 if (*filename == '\0') filename = argv[++i];
462 lua_assert(filename != NULL); 464 lua_assert(filename != NULL);
463 if (dolibrary(L, filename)) 465 if (dolibrary(L, filename))
464 return 1; /* stop if file fails */ 466 return 1;
465 break; 467 break;
466 } 468 }
467 case 'j': { /* LuaJIT extension */ 469 case 'j': { /* LuaJIT extension. */
468 const char *cmd = argv[i] + 2; 470 const char *cmd = argv[i] + 2;
469 if (*cmd == '\0') cmd = argv[++i]; 471 if (*cmd == '\0') cmd = argv[++i];
470 lua_assert(cmd != NULL); 472 lua_assert(cmd != NULL);
@@ -472,11 +474,11 @@ static int runargs(lua_State *L, char **argv, int n)
472 return 1; 474 return 1;
473 break; 475 break;
474 } 476 }
475 case 'O': /* LuaJIT extension */ 477 case 'O': /* LuaJIT extension. */
476 if (dojitopt(L, argv[i] + 2)) 478 if (dojitopt(L, argv[i] + 2))
477 return 1; 479 return 1;
478 break; 480 break;
479 case 'b': /* LuaJIT extension */ 481 case 'b': /* LuaJIT extension. */
480 return dobytecode(L, argv+i); 482 return dobytecode(L, argv+i);
481 default: break; 483 default: break;
482 } 484 }
@@ -509,45 +511,57 @@ static int pmain(lua_State *L)
509{ 511{
510 struct Smain *s = &smain; 512 struct Smain *s = &smain;
511 char **argv = s->argv; 513 char **argv = s->argv;
512 int script; 514 int argn;
513 int flags = 0; 515 int flags = 0;
514 globalL = L; 516 globalL = L;
515 if (argv[0] && argv[0][0]) progname = argv[0]; 517 if (argv[0] && argv[0][0]) progname = argv[0];
516 LUAJIT_VERSION_SYM(); /* linker-enforced version check */ 518
517 script = collectargs(argv, &flags); 519 LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
518 if (script < 0) { /* invalid args? */ 520
521 argn = collectargs(argv, &flags);
522 if (argn < 0) { /* Invalid args? */
519 print_usage(); 523 print_usage();
520 s->status = 1; 524 s->status = 1;
521 return 0; 525 return 0;
522 } 526 }
527
523 if ((flags & FLAGS_NOENV)) { 528 if ((flags & FLAGS_NOENV)) {
524 lua_pushboolean(L, 1); 529 lua_pushboolean(L, 1);
525 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); 530 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
526 } 531 }
527 lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ 532
528 luaL_openlibs(L); /* open libraries */ 533 /* Stop collector during library initialization. */
534 lua_gc(L, LUA_GCSTOP, 0);
535 luaL_openlibs(L);
529 lua_gc(L, LUA_GCRESTART, -1); 536 lua_gc(L, LUA_GCRESTART, -1);
537
538 createargtable(L, argv, s->argc, argn);
539
530 if (!(flags & FLAGS_NOENV)) { 540 if (!(flags & FLAGS_NOENV)) {
531 s->status = handle_luainit(L); 541 s->status = handle_luainit(L);
532 if (s->status != 0) return 0; 542 if (s->status != 0) return 0;
533 } 543 }
544
534 if ((flags & FLAGS_VERSION)) print_version(); 545 if ((flags & FLAGS_VERSION)) print_version();
535 s->status = runargs(L, argv, (script > 0) ? script : s->argc); 546
547 s->status = runargs(L, argv, argn);
536 if (s->status != 0) return 0; 548 if (s->status != 0) return 0;
537 if (script) { 549
538 s->status = handle_script(L, argv, script); 550 if (s->argc > argn) {
551 s->status = handle_script(L, argv + argn);
539 if (s->status != 0) return 0; 552 if (s->status != 0) return 0;
540 } 553 }
554
541 if ((flags & FLAGS_INTERACTIVE)) { 555 if ((flags & FLAGS_INTERACTIVE)) {
542 print_jit_status(L); 556 print_jit_status(L);
543 dotty(L); 557 dotty(L);
544 } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) { 558 } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
545 if (lua_stdin_is_tty()) { 559 if (lua_stdin_is_tty()) {
546 print_version(); 560 print_version();
547 print_jit_status(L); 561 print_jit_status(L);
548 dotty(L); 562 dotty(L);
549 } else { 563 } else {
550 dofile(L, NULL); /* executes stdin as a file */ 564 dofile(L, NULL); /* Executes stdin as a file. */
551 } 565 }
552 } 566 }
553 return 0; 567 return 0;
@@ -556,7 +570,7 @@ static int pmain(lua_State *L)
556int main(int argc, char **argv) 570int main(int argc, char **argv)
557{ 571{
558 int status; 572 int status;
559 lua_State *L = lua_open(); /* create state */ 573 lua_State *L = lua_open();
560 if (L == NULL) { 574 if (L == NULL) {
561 l_message(argv[0], "cannot create state: not enough memory"); 575 l_message(argv[0], "cannot create state: not enough memory");
562 return EXIT_FAILURE; 576 return EXIT_FAILURE;
@@ -566,6 +580,6 @@ int main(int argc, char **argv)
566 status = lua_cpcall(L, pmain, NULL); 580 status = lua_cpcall(L, pmain, NULL);
567 report(L, status); 581 report(L, status);
568 lua_close(L); 582 lua_close(L);
569 return (status || smain.status) ? EXIT_FAILURE : EXIT_SUCCESS; 583 return (status || smain.status > 0) ? EXIT_FAILURE : EXIT_SUCCESS;
570} 584}
571 585
diff --git a/src/luajit.h b/src/luajit.h
index 1709ca26..c1c801c9 100644
--- a/src/luajit.h
+++ b/src/luajit.h
@@ -30,9 +30,9 @@
30 30
31#include "lua.h" 31#include "lua.h"
32 32
33#define LUAJIT_VERSION "LuaJIT 2.0.4" 33#define LUAJIT_VERSION "LuaJIT 2.1.0-beta2"
34#define LUAJIT_VERSION_NUM 20004 /* Version 2.0.4 = 02.00.04. */ 34#define LUAJIT_VERSION_NUM 20100 /* Version 2.1.0 = 02.01.00. */
35#define LUAJIT_VERSION_SYM luaJIT_version_2_0_4 35#define LUAJIT_VERSION_SYM luaJIT_version_2_1_0_beta2
36#define LUAJIT_COPYRIGHT "Copyright (C) 2005-2017 Mike Pall" 36#define LUAJIT_COPYRIGHT "Copyright (C) 2005-2017 Mike Pall"
37#define LUAJIT_URL "http://luajit.org/" 37#define LUAJIT_URL "http://luajit.org/"
38 38
@@ -64,6 +64,15 @@ enum {
64/* Control the JIT engine. */ 64/* Control the JIT engine. */
65LUA_API int luaJIT_setmode(lua_State *L, int idx, int mode); 65LUA_API int luaJIT_setmode(lua_State *L, int idx, int mode);
66 66
67/* Low-overhead profiling API. */
68typedef void (*luaJIT_profile_callback)(void *data, lua_State *L,
69 int samples, int vmstate);
70LUA_API void luaJIT_profile_start(lua_State *L, const char *mode,
71 luaJIT_profile_callback cb, void *data);
72LUA_API void luaJIT_profile_stop(lua_State *L);
73LUA_API const char *luaJIT_profile_dumpstack(lua_State *L, const char *fmt,
74 int depth, size_t *len);
75
67/* Enforce (dynamic) linker error for version mismatches. Call from main. */ 76/* Enforce (dynamic) linker error for version mismatches. Call from main. */
68LUA_API void LUAJIT_VERSION_SYM(void); 77LUA_API void LUAJIT_VERSION_SYM(void);
69 78
diff --git a/src/msvcbuild.bat b/src/msvcbuild.bat
index fc4b8943..5648a899 100644
--- a/src/msvcbuild.bat
+++ b/src/msvcbuild.bat
@@ -20,6 +20,7 @@
20@set LJLIB=lib /nologo /nodefaultlib 20@set LJLIB=lib /nologo /nodefaultlib
21@set DASMDIR=..\dynasm 21@set DASMDIR=..\dynasm
22@set DASM=%DASMDIR%\dynasm.lua 22@set DASM=%DASMDIR%\dynasm.lua
23@set DASC=vm_x86.dasc
23@set LJDLLNAME=lua51.dll 24@set LJDLLNAME=lua51.dll
24@set LJLIBNAME=lua51.lib 25@set LJLIBNAME=lua51.lib
25@set ALL_LIB=lib_base.c lib_math.c lib_bit.c lib_string.c lib_table.c lib_io.c lib_os.c lib_package.c lib_debug.c lib_jit.c lib_ffi.c 26@set ALL_LIB=lib_base.c lib_math.c lib_bit.c lib_string.c lib_table.c lib_io.c lib_os.c lib_package.c lib_debug.c lib_jit.c lib_ffi.c
@@ -37,8 +38,14 @@ if exist minilua.exe.manifest^
37@if errorlevel 8 goto :X64 38@if errorlevel 8 goto :X64
38@set DASMFLAGS=-D WIN -D JIT -D FFI 39@set DASMFLAGS=-D WIN -D JIT -D FFI
39@set LJARCH=x86 40@set LJARCH=x86
41@set LJCOMPILE=%LJCOMPILE% /arch:SSE2
40:X64 42:X64
41minilua %DASM% -LN %DASMFLAGS% -o host\buildvm_arch.h vm_x86.dasc 43@if "%1" neq "gc64" goto :NOGC64
44@shift
45@set DASC=vm_x64.dasc
46@set LJCOMPILE=%LJCOMPILE% /DLUAJIT_ENABLE_GC64
47:NOGC64
48minilua %DASM% -LN %DASMFLAGS% -o host\buildvm_arch.h %DASC%
42@if errorlevel 1 goto :BAD 49@if errorlevel 1 goto :BAD
43 50
44%LJCOMPILE% /I "." /I %DASMDIR% host\buildvm*.c 51%LJCOMPILE% /I "." /I %DASMDIR% host\buildvm*.c
@@ -66,7 +73,7 @@ buildvm -m folddef -o lj_folddef.h lj_opt_fold.c
66@if "%1" neq "debug" goto :NODEBUG 73@if "%1" neq "debug" goto :NODEBUG
67@shift 74@shift
68@set LJCOMPILE=%LJCOMPILE% /Zi 75@set LJCOMPILE=%LJCOMPILE% /Zi
69@set LJLINK=%LJLINK% /debug 76@set LJLINK=%LJLINK% /debug /opt:ref /opt:icf /incremental:no
70:NODEBUG 77:NODEBUG
71@if "%1"=="amalg" goto :AMALGDLL 78@if "%1"=="amalg" goto :AMALGDLL
72@if "%1"=="static" goto :STATIC 79@if "%1"=="static" goto :STATIC
diff --git a/src/ps4build.bat b/src/ps4build.bat
index 337a44fa..e4a7defe 100644
--- a/src/ps4build.bat
+++ b/src/ps4build.bat
@@ -2,7 +2,19 @@
2@rem Donated to the public domain. 2@rem Donated to the public domain.
3@rem 3@rem
4@rem Open a "Visual Studio .NET Command Prompt" (64 bit host compiler) 4@rem Open a "Visual Studio .NET Command Prompt" (64 bit host compiler)
5@rem or "VS2015 x64 Native Tools Command Prompt".
6@rem
5@rem Then cd to this directory and run this script. 7@rem Then cd to this directory and run this script.
8@rem
9@rem Recommended invocation:
10@rem
11@rem ps4build release build, amalgamated, 64-bit GC
12@rem ps4build debug debug build, amalgamated, 64-bit GC
13@rem
14@rem Additional command-line options (not generally recommended):
15@rem
16@rem gc32 (before debug) 32-bit GC
17@rem noamalg (after debug) non-amalgamated build
6 18
7@if not defined INCLUDE goto :FAIL 19@if not defined INCLUDE goto :FAIL
8@if not defined SCE_ORBIS_SDK_DIR goto :FAIL 20@if not defined SCE_ORBIS_SDK_DIR goto :FAIL
@@ -15,6 +27,14 @@
15@set DASMDIR=..\dynasm 27@set DASMDIR=..\dynasm
16@set DASM=%DASMDIR%\dynasm.lua 28@set DASM=%DASMDIR%\dynasm.lua
17@set ALL_LIB=lib_base.c lib_math.c lib_bit.c lib_string.c lib_table.c lib_io.c lib_os.c lib_package.c lib_debug.c lib_jit.c lib_ffi.c 29@set ALL_LIB=lib_base.c lib_math.c lib_bit.c lib_string.c lib_table.c lib_io.c lib_os.c lib_package.c lib_debug.c lib_jit.c lib_ffi.c
30@set GC64=-DLUAJIT_ENABLE_GC64
31@set DASC=vm_x64.dasc
32
33@if "%1" neq "gc32" goto :NOGC32
34@shift
35@set GC64=
36@set DASC=vm_x86.dasc
37:NOGC32
18 38
19%LJCOMPILE% host\minilua.c 39%LJCOMPILE% host\minilua.c
20@if errorlevel 1 goto :BAD 40@if errorlevel 1 goto :BAD
@@ -28,10 +48,10 @@ if exist minilua.exe.manifest^
28@if not errorlevel 8 goto :FAIL 48@if not errorlevel 8 goto :FAIL
29 49
30@set DASMFLAGS=-D P64 -D NO_UNWIND 50@set DASMFLAGS=-D P64 -D NO_UNWIND
31minilua %DASM% -LN %DASMFLAGS% -o host\buildvm_arch.h vm_x86.dasc 51minilua %DASM% -LN %DASMFLAGS% -o host\buildvm_arch.h %DASC%
32@if errorlevel 1 goto :BAD 52@if errorlevel 1 goto :BAD
33 53
34%LJCOMPILE% /I "." /I %DASMDIR% -DLUAJIT_TARGET=LUAJIT_ARCH_X64 -DLUAJIT_OS=LUAJIT_OS_OTHER -DLUAJIT_DISABLE_JIT -DLUAJIT_DISABLE_FFI -DLUAJIT_NO_UNWIND host\buildvm*.c 54%LJCOMPILE% /I "." /I %DASMDIR% %GC64% -DLUAJIT_TARGET=LUAJIT_ARCH_X64 -DLUAJIT_OS=LUAJIT_OS_OTHER -DLUAJIT_DISABLE_JIT -DLUAJIT_DISABLE_FFI -DLUAJIT_NO_UNWIND host\buildvm*.c
35@if errorlevel 1 goto :BAD 55@if errorlevel 1 goto :BAD
36%LJLINK% /out:buildvm.exe buildvm*.obj 56%LJLINK% /out:buildvm.exe buildvm*.obj
37@if errorlevel 1 goto :BAD 57@if errorlevel 1 goto :BAD
@@ -54,7 +74,7 @@ buildvm -m folddef -o lj_folddef.h lj_opt_fold.c
54@if errorlevel 1 goto :BAD 74@if errorlevel 1 goto :BAD
55 75
56@rem ---- Cross compiler ---- 76@rem ---- Cross compiler ----
57@set LJCOMPILE="%SCE_ORBIS_SDK_DIR%\host_tools\bin\orbis-clang" -c -Wall -DLUAJIT_DISABLE_FFI 77@set LJCOMPILE="%SCE_ORBIS_SDK_DIR%\host_tools\bin\orbis-clang" -c -Wall -DLUAJIT_DISABLE_FFI %GC64%
58@set LJLIB="%SCE_ORBIS_SDK_DIR%\host_tools\bin\orbis-ar" rcus 78@set LJLIB="%SCE_ORBIS_SDK_DIR%\host_tools\bin\orbis-ar" rcus
59@set INCLUDE="" 79@set INCLUDE=""
60 80
@@ -63,14 +83,14 @@ orbis-as -o lj_vm.o lj_vm.s
63@if "%1" neq "debug" goto :NODEBUG 83@if "%1" neq "debug" goto :NODEBUG
64@shift 84@shift
65@set LJCOMPILE=%LJCOMPILE% -g -O0 85@set LJCOMPILE=%LJCOMPILE% -g -O0
66@set TARGETLIB=libluajitD.a 86@set TARGETLIB=libluajitD_ps4.a
67goto :BUILD 87goto :BUILD
68:NODEBUG 88:NODEBUG
69@set LJCOMPILE=%LJCOMPILE% -O2 89@set LJCOMPILE=%LJCOMPILE% -O2
70@set TARGETLIB=libluajit.a 90@set TARGETLIB=libluajit_ps4.a
71:BUILD 91:BUILD
72del %TARGETLIB% 92del %TARGETLIB%
73@if "%1"=="amalg" goto :AMALG 93@if "%1" neq "noamalg" goto :AMALG
74for %%f in (lj_*.c lib_*.c) do ( 94for %%f in (lj_*.c lib_*.c) do (
75 %LJCOMPILE% %%f 95 %LJCOMPILE% %%f
76 @if errorlevel 1 goto :BAD 96 @if errorlevel 1 goto :BAD
diff --git a/src/vm_arm.dasc b/src/vm_arm.dasc
index be5540ce..780cc16e 100644
--- a/src/vm_arm.dasc
+++ b/src/vm_arm.dasc
@@ -99,6 +99,7 @@
99|.type NODE, Node 99|.type NODE, Node
100|.type NARGS8, int 100|.type NARGS8, int
101|.type TRACE, GCtrace 101|.type TRACE, GCtrace
102|.type SBUF, SBuf
102| 103|
103|//----------------------------------------------------------------------- 104|//-----------------------------------------------------------------------
104| 105|
@@ -372,6 +373,17 @@ static void build_subroutines(BuildCtx *ctx)
372 | st_vmstate CARG2 373 | st_vmstate CARG2
373 | b ->vm_returnc 374 | b ->vm_returnc
374 | 375 |
376 |->vm_unwind_ext: // Complete external unwind.
377#if !LJ_NO_UNWIND
378 | push {r0, r1, r2, lr}
379 | bl extern _Unwind_Complete
380 | ldr r0, [sp]
381 | bl extern _Unwind_DeleteException
382 | pop {r0, r1, r2, lr}
383 | mov r0, r1
384 | bx r2
385#endif
386 |
375 |//----------------------------------------------------------------------- 387 |//-----------------------------------------------------------------------
376 |//-- Grow stack for calls ----------------------------------------------- 388 |//-- Grow stack for calls -----------------------------------------------
377 |//----------------------------------------------------------------------- 389 |//-----------------------------------------------------------------------
@@ -418,13 +430,14 @@ static void build_subroutines(BuildCtx *ctx)
418 | add CARG2, sp, #CFRAME_RESUME 430 | add CARG2, sp, #CFRAME_RESUME
419 | ldrb CARG1, L->status 431 | ldrb CARG1, L->status
420 | str CARG3, SAVE_ERRF 432 | str CARG3, SAVE_ERRF
421 | str CARG2, L->cframe 433 | str L, SAVE_PC // Any value outside of bytecode is ok.
422 | str CARG3, SAVE_CFRAME 434 | str CARG3, SAVE_CFRAME
423 | cmp CARG1, #0 435 | cmp CARG1, #0
424 | str L, SAVE_PC // Any value outside of bytecode is ok. 436 | str CARG2, L->cframe
425 | beq >3 437 | beq >3
426 | 438 |
427 | // Resume after yield (like a return). 439 | // Resume after yield (like a return).
440 | str L, [DISPATCH, #DISPATCH_GL(cur_L)]
428 | mov RA, BASE 441 | mov RA, BASE
429 | ldr BASE, L->base 442 | ldr BASE, L->base
430 | ldr CARG1, L->top 443 | ldr CARG1, L->top
@@ -458,14 +471,15 @@ static void build_subroutines(BuildCtx *ctx)
458 | str CARG3, SAVE_NRES 471 | str CARG3, SAVE_NRES
459 | mov L, CARG1 472 | mov L, CARG1
460 | str CARG1, SAVE_L 473 | str CARG1, SAVE_L
461 | mov BASE, CARG2
462 | str sp, L->cframe // Add our C frame to cframe chain.
463 | ldr DISPATCH, L->glref // Setup pointer to dispatch table. 474 | ldr DISPATCH, L->glref // Setup pointer to dispatch table.
475 | mov BASE, CARG2
464 | str CARG1, SAVE_PC // Any value outside of bytecode is ok. 476 | str CARG1, SAVE_PC // Any value outside of bytecode is ok.
465 | str RC, SAVE_CFRAME 477 | str RC, SAVE_CFRAME
466 | add DISPATCH, DISPATCH, #GG_G2DISP 478 | add DISPATCH, DISPATCH, #GG_G2DISP
479 | str sp, L->cframe // Add our C frame to cframe chain.
467 | 480 |
468 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype). 481 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
482 | str L, [DISPATCH, #DISPATCH_GL(cur_L)]
469 | ldr RB, L->base // RB = old base (for vmeta_call). 483 | ldr RB, L->base // RB = old base (for vmeta_call).
470 | ldr CARG1, L->top 484 | ldr CARG1, L->top
471 | mov MASKR8, #255 485 | mov MASKR8, #255
@@ -491,20 +505,21 @@ static void build_subroutines(BuildCtx *ctx)
491 | mov L, CARG1 505 | mov L, CARG1
492 | ldr RA, L:CARG1->stack 506 | ldr RA, L:CARG1->stack
493 | str CARG1, SAVE_L 507 | str CARG1, SAVE_L
508 | ldr DISPATCH, L->glref // Setup pointer to dispatch table.
494 | ldr RB, L->top 509 | ldr RB, L->top
495 | str CARG1, SAVE_PC // Any value outside of bytecode is ok. 510 | str CARG1, SAVE_PC // Any value outside of bytecode is ok.
496 | ldr RC, L->cframe 511 | ldr RC, L->cframe
512 | add DISPATCH, DISPATCH, #GG_G2DISP
497 | sub RA, RA, RB // Compute -savestack(L, L->top). 513 | sub RA, RA, RB // Compute -savestack(L, L->top).
498 | str sp, L->cframe // Add our C frame to cframe chain.
499 | mov RB, #0 514 | mov RB, #0
500 | str RA, SAVE_NRES // Neg. delta means cframe w/o frame. 515 | str RA, SAVE_NRES // Neg. delta means cframe w/o frame.
501 | str RB, SAVE_ERRF // No error function. 516 | str RB, SAVE_ERRF // No error function.
502 | str RC, SAVE_CFRAME 517 | str RC, SAVE_CFRAME
518 | str sp, L->cframe // Add our C frame to cframe chain.
519 | str L, [DISPATCH, #DISPATCH_GL(cur_L)]
503 | blx CARG4 // (lua_State *L, lua_CFunction func, void *ud) 520 | blx CARG4 // (lua_State *L, lua_CFunction func, void *ud)
504 | ldr DISPATCH, L->glref // Setup pointer to dispatch table.
505 | movs BASE, CRET1 521 | movs BASE, CRET1
506 | mov PC, #FRAME_CP 522 | mov PC, #FRAME_CP
507 | add DISPATCH, DISPATCH, #GG_G2DISP
508 | bne <3 // Else continue with the call. 523 | bne <3 // Else continue with the call.
509 | b ->vm_leave_cp // No base? Just remove C frame. 524 | b ->vm_leave_cp // No base? Just remove C frame.
510 | 525 |
@@ -614,6 +629,16 @@ static void build_subroutines(BuildCtx *ctx)
614 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here. 629 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here.
615 | b ->vm_call_dispatch_f 630 | b ->vm_call_dispatch_f
616 | 631 |
632 |->vmeta_tgetr:
633 | .IOS mov RC, BASE
634 | bl extern lj_tab_getinth // (GCtab *t, int32_t key)
635 | // Returns cTValue * or NULL.
636 | .IOS mov BASE, RC
637 | cmp CRET1, #0
638 | ldrdne CARG12, [CRET1]
639 | mvneq CARG2, #~LJ_TNIL
640 | b ->BC_TGETR_Z
641 |
617 |//----------------------------------------------------------------------- 642 |//-----------------------------------------------------------------------
618 | 643 |
619 |->vmeta_tsets1: 644 |->vmeta_tsets1:
@@ -671,6 +696,15 @@ static void build_subroutines(BuildCtx *ctx)
671 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here. 696 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here.
672 | b ->vm_call_dispatch_f 697 | b ->vm_call_dispatch_f
673 | 698 |
699 |->vmeta_tsetr:
700 | str BASE, L->base
701 | .IOS mov RC, BASE
702 | str PC, SAVE_PC
703 | bl extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
704 | // Returns TValue *.
705 | .IOS mov BASE, RC
706 | b ->BC_TSETR_Z
707 |
674 |//-- Comparison metamethods --------------------------------------------- 708 |//-- Comparison metamethods ---------------------------------------------
675 | 709 |
676 |->vmeta_comp: 710 |->vmeta_comp:
@@ -735,6 +769,17 @@ static void build_subroutines(BuildCtx *ctx)
735 | b <3 769 | b <3
736 |.endif 770 |.endif
737 | 771 |
772 |->vmeta_istype:
773 | sub PC, PC, #4
774 | str BASE, L->base
775 | mov CARG1, L
776 | lsr CARG2, RA, #3
777 | mov CARG3, RC
778 | str PC, SAVE_PC
779 | bl extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
780 | .IOS ldr BASE, L->base
781 | b ->cont_nop
782 |
738 |//-- Arithmetic metamethods --------------------------------------------- 783 |//-- Arithmetic metamethods ---------------------------------------------
739 | 784 |
740 |->vmeta_arith_vn: 785 |->vmeta_arith_vn:
@@ -1052,7 +1097,7 @@ static void build_subroutines(BuildCtx *ctx)
1052 | ffgccheck 1097 | ffgccheck
1053 | mov CARG1, L 1098 | mov CARG1, L
1054 | mov CARG2, BASE 1099 | mov CARG2, BASE
1055 | bl extern lj_str_fromnumber // (lua_State *L, cTValue *o) 1100 | bl extern lj_strfmt_number // (lua_State *L, cTValue *o)
1056 | // Returns GCstr *. 1101 | // Returns GCstr *.
1057 | ldr BASE, L->base 1102 | ldr BASE, L->base
1058 | mvn CARG2, #~LJ_TSTR 1103 | mvn CARG2, #~LJ_TSTR
@@ -1230,9 +1275,10 @@ static void build_subroutines(BuildCtx *ctx)
1230 | ldr CARG3, L:RA->base 1275 | ldr CARG3, L:RA->base
1231 | mv_vmstate CARG2, INTERP 1276 | mv_vmstate CARG2, INTERP
1232 | ldr CARG4, L:RA->top 1277 | ldr CARG4, L:RA->top
1233 | st_vmstate CARG2
1234 | cmp CRET1, #LUA_YIELD 1278 | cmp CRET1, #LUA_YIELD
1235 | ldr BASE, L->base 1279 | ldr BASE, L->base
1280 | str L, [DISPATCH, #DISPATCH_GL(cur_L)]
1281 | st_vmstate CARG2
1236 | bhi >8 1282 | bhi >8
1237 | subs RC, CARG4, CARG3 1283 | subs RC, CARG4, CARG3
1238 | ldr CARG1, L->maxstack 1284 | ldr CARG1, L->maxstack
@@ -1500,19 +1546,6 @@ static void build_subroutines(BuildCtx *ctx)
1500 | math_extern2 atan2 1546 | math_extern2 atan2
1501 | math_extern2 fmod 1547 | math_extern2 fmod
1502 | 1548 |
1503 |->ff_math_deg:
1504 |.if FPU
1505 | .ffunc_d math_rad
1506 | vldr d1, CFUNC:CARG3->upvalue[0]
1507 | vmul.f64 d0, d0, d1
1508 | b ->fff_resd
1509 |.else
1510 | .ffunc_n math_rad
1511 | ldrd CARG34, CFUNC:CARG3->upvalue[0]
1512 | bl extern __aeabi_dmul
1513 | b ->fff_restv
1514 |.endif
1515 |
1516 |.if HFABI 1549 |.if HFABI
1517 | .ffunc math_ldexp 1550 | .ffunc math_ldexp
1518 | ldr CARG4, [BASE, #4] 1551 | ldr CARG4, [BASE, #4]
@@ -1687,12 +1720,6 @@ static void build_subroutines(BuildCtx *ctx)
1687 | 1720 |
1688 |//-- String library ----------------------------------------------------- 1721 |//-- String library -----------------------------------------------------
1689 | 1722 |
1690 |.ffunc_1 string_len
1691 | checkstr CARG2, ->fff_fallback
1692 | ldr CARG1, STR:CARG1->len
1693 | mvn CARG2, #~LJ_TISNUM
1694 | b ->fff_restv
1695 |
1696 |.ffunc string_byte // Only handle the 1-arg case here. 1723 |.ffunc string_byte // Only handle the 1-arg case here.
1697 | ldrd CARG12, [BASE] 1724 | ldrd CARG12, [BASE]
1698 | ldr PC, [BASE, FRAME_PC] 1725 | ldr PC, [BASE, FRAME_PC]
@@ -1725,6 +1752,7 @@ static void build_subroutines(BuildCtx *ctx)
1725 | mov CARG1, L 1752 | mov CARG1, L
1726 | str PC, SAVE_PC 1753 | str PC, SAVE_PC
1727 | bl extern lj_str_new // (lua_State *L, char *str, size_t l) 1754 | bl extern lj_str_new // (lua_State *L, char *str, size_t l)
1755 |->fff_resstr:
1728 | // Returns GCstr *. 1756 | // Returns GCstr *.
1729 | ldr BASE, L->base 1757 | ldr BASE, L->base
1730 | mvn CARG2, #~LJ_TSTR 1758 | mvn CARG2, #~LJ_TSTR
@@ -1768,91 +1796,28 @@ static void build_subroutines(BuildCtx *ctx)
1768 | mvn CARG2, #~LJ_TSTR 1796 | mvn CARG2, #~LJ_TSTR
1769 | b ->fff_restv 1797 | b ->fff_restv
1770 | 1798 |
1771 |.ffunc string_rep // Only handle the 1-char case inline. 1799 |.macro ffstring_op, name
1772 | ffgccheck 1800 | .ffunc string_ .. name
1773 | ldrd CARG12, [BASE]
1774 | ldrd CARG34, [BASE, #8]
1775 | cmp NARGS8:RC, #16
1776 | bne ->fff_fallback // Exactly 2 arguments
1777 | checktp CARG2, LJ_TSTR
1778 | checktpeq CARG4, LJ_TISNUM
1779 | bne ->fff_fallback
1780 | subs CARG4, CARG3, #1
1781 | ldr CARG2, STR:CARG1->len
1782 | blt ->fff_emptystr // Count <= 0?
1783 | cmp CARG2, #1
1784 | blo ->fff_emptystr // Zero-length string?
1785 | bne ->fff_fallback // Fallback for > 1-char strings.
1786 | ldr RB, [DISPATCH, #DISPATCH_GL(tmpbuf.sz)]
1787 | ldr CARG2, [DISPATCH, #DISPATCH_GL(tmpbuf.buf)]
1788 | ldr CARG1, STR:CARG1[1]
1789 | cmp RB, CARG3
1790 | blo ->fff_fallback
1791 |1: // Fill buffer with char.
1792 | strb CARG1, [CARG2, CARG4]
1793 | subs CARG4, CARG4, #1
1794 | bge <1
1795 | b ->fff_newstr
1796 |
1797 |.ffunc string_reverse
1798 | ffgccheck 1801 | ffgccheck
1799 | ldrd CARG12, [BASE] 1802 | ldr CARG3, [BASE, #4]
1800 | cmp NARGS8:RC, #8 1803 | cmp NARGS8:RC, #8
1804 | ldr STR:CARG2, [BASE]
1801 | blo ->fff_fallback 1805 | blo ->fff_fallback
1802 | checkstr CARG2, ->fff_fallback 1806 | sub SBUF:CARG1, DISPATCH, #-DISPATCH_GL(tmpbuf)
1803 | ldr CARG3, STR:CARG1->len 1807 | checkstr CARG3, ->fff_fallback
1804 | ldr RB, [DISPATCH, #DISPATCH_GL(tmpbuf.sz)] 1808 | ldr CARG4, SBUF:CARG1->b
1805 | ldr CARG2, [DISPATCH, #DISPATCH_GL(tmpbuf.buf)] 1809 | str BASE, L->base
1806 | mov CARG4, CARG3 1810 | str PC, SAVE_PC
1807 | add CARG1, STR:CARG1, #sizeof(GCstr) 1811 | str L, SBUF:CARG1->L
1808 | cmp RB, CARG3 1812 | str CARG4, SBUF:CARG1->p
1809 | blo ->fff_fallback 1813 | bl extern lj_buf_putstr_ .. name
1810 |1: // Reverse string copy. 1814 | bl extern lj_buf_tostr
1811 | ldrb RB, [CARG1], #1 1815 | b ->fff_resstr
1812 | subs CARG4, CARG4, #1
1813 | blt ->fff_newstr
1814 | strb RB, [CARG2, CARG4]
1815 | b <1
1816 |
1817 |.macro ffstring_case, name, lo
1818 | .ffunc name
1819 | ffgccheck
1820 | ldrd CARG12, [BASE]
1821 | cmp NARGS8:RC, #8
1822 | blo ->fff_fallback
1823 | checkstr CARG2, ->fff_fallback
1824 | ldr CARG3, STR:CARG1->len
1825 | ldr RB, [DISPATCH, #DISPATCH_GL(tmpbuf.sz)]
1826 | ldr CARG2, [DISPATCH, #DISPATCH_GL(tmpbuf.buf)]
1827 | mov CARG4, #0
1828 | add CARG1, STR:CARG1, #sizeof(GCstr)
1829 | cmp RB, CARG3
1830 | blo ->fff_fallback
1831 |1: // ASCII case conversion.
1832 | ldrb RB, [CARG1, CARG4]
1833 | cmp CARG4, CARG3
1834 | bhs ->fff_newstr
1835 | sub RC, RB, #lo
1836 | cmp RC, #26
1837 | eorlo RB, RB, #0x20
1838 | strb RB, [CARG2, CARG4]
1839 | add CARG4, CARG4, #1
1840 | b <1
1841 |.endmacro 1816 |.endmacro
1842 | 1817 |
1843 |ffstring_case string_lower, 65 1818 |ffstring_op reverse
1844 |ffstring_case string_upper, 97 1819 |ffstring_op lower
1845 | 1820 |ffstring_op upper
1846 |//-- Table library ------------------------------------------------------
1847 |
1848 |.ffunc_1 table_getn
1849 | checktab CARG2, ->fff_fallback
1850 | .IOS mov RA, BASE
1851 | bl extern lj_tab_len // (GCtab *t)
1852 | // Returns uint32_t (but less than 2^31).
1853 | .IOS mov BASE, RA
1854 | mvn CARG2, #~LJ_TISNUM
1855 | b ->fff_restv
1856 | 1821 |
1857 |//-- Bit library -------------------------------------------------------- 1822 |//-- Bit library --------------------------------------------------------
1858 | 1823 |
@@ -2127,6 +2092,66 @@ static void build_subroutines(BuildCtx *ctx)
2127 | ldr INS, [PC, #-4] 2092 | ldr INS, [PC, #-4]
2128 | bx CRET1 2093 | bx CRET1
2129 | 2094 |
2095 |->cont_stitch: // Trace stitching.
2096 |.if JIT
2097 | // RA = resultptr, CARG4 = meta base
2098 | ldr RB, SAVE_MULTRES
2099 | ldr INS, [PC, #-4]
2100 | ldr TRACE:CARG3, [CARG4, #-24] // Save previous trace.
2101 | subs RB, RB, #8
2102 | decode_RA8 RC, INS // Call base.
2103 | beq >2
2104 |1: // Move results down.
2105 | ldrd CARG12, [RA]
2106 | add RA, RA, #8
2107 | subs RB, RB, #8
2108 | strd CARG12, [BASE, RC]
2109 | add RC, RC, #8
2110 | bne <1
2111 |2:
2112 | decode_RA8 RA, INS
2113 | decode_RB8 RB, INS
2114 | add RA, RA, RB
2115 |3:
2116 | cmp RA, RC
2117 | mvn CARG2, #~LJ_TNIL
2118 | bhi >9 // More results wanted?
2119 |
2120 | ldrh RA, TRACE:CARG3->traceno
2121 | ldrh RC, TRACE:CARG3->link
2122 | cmp RC, RA
2123 | beq ->cont_nop // Blacklisted.
2124 | cmp RC, #0
2125 | bne =>BC_JLOOP // Jump to stitched trace.
2126 |
2127 | // Stitch a new trace to the previous trace.
2128 | str RA, [DISPATCH, #DISPATCH_J(exitno)]
2129 | str L, [DISPATCH, #DISPATCH_J(L)]
2130 | str BASE, L->base
2131 | sub CARG1, DISPATCH, #-GG_DISP2J
2132 | mov CARG2, PC
2133 | bl extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
2134 | ldr BASE, L->base
2135 | b ->cont_nop
2136 |
2137 |9: // Fill up results with nil.
2138 | strd CARG12, [BASE, RC]
2139 | add RC, RC, #8
2140 | b <3
2141 |.endif
2142 |
2143 |->vm_profhook: // Dispatch target for profiler hook.
2144#if LJ_HASPROFILE
2145 | mov CARG1, L
2146 | str BASE, L->base
2147 | mov CARG2, PC
2148 | bl extern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
2149 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2150 | ldr BASE, L->base
2151 | sub PC, PC, #4
2152 | b ->cont_nop
2153#endif
2154 |
2130 |//----------------------------------------------------------------------- 2155 |//-----------------------------------------------------------------------
2131 |//-- Trace exit handler ------------------------------------------------- 2156 |//-- Trace exit handler -------------------------------------------------
2132 |//----------------------------------------------------------------------- 2157 |//-----------------------------------------------------------------------
@@ -2151,14 +2176,14 @@ static void build_subroutines(BuildCtx *ctx)
2151 | add CARG1, CARG1, CARG2, asr #6 2176 | add CARG1, CARG1, CARG2, asr #6
2152 | ldr CARG2, [lr, #4] // Load exit stub group offset. 2177 | ldr CARG2, [lr, #4] // Load exit stub group offset.
2153 | sub CARG1, CARG1, lr 2178 | sub CARG1, CARG1, lr
2154 | ldr L, [DISPATCH, #DISPATCH_GL(jit_L)] 2179 | ldr L, [DISPATCH, #DISPATCH_GL(cur_L)]
2155 | add CARG1, CARG2, CARG1, lsr #2 // Compute exit number. 2180 | add CARG1, CARG2, CARG1, lsr #2 // Compute exit number.
2156 | ldr BASE, [DISPATCH, #DISPATCH_GL(jit_base)] 2181 | ldr BASE, [DISPATCH, #DISPATCH_GL(jit_base)]
2157 | str CARG1, [DISPATCH, #DISPATCH_J(exitno)] 2182 | str CARG1, [DISPATCH, #DISPATCH_J(exitno)]
2158 | mov CARG4, #0 2183 | mov CARG4, #0
2159 | str L, [DISPATCH, #DISPATCH_J(L)]
2160 | str BASE, L->base 2184 | str BASE, L->base
2161 | str CARG4, [DISPATCH, #DISPATCH_GL(jit_L)] 2185 | str L, [DISPATCH, #DISPATCH_J(L)]
2186 | str CARG4, [DISPATCH, #DISPATCH_GL(jit_base)]
2162 | sub CARG1, DISPATCH, #-GG_DISP2J 2187 | sub CARG1, DISPATCH, #-GG_DISP2J
2163 | mov CARG2, sp 2188 | mov CARG2, sp
2164 | bl extern lj_trace_exit // (jit_State *J, ExitState *ex) 2189 | bl extern lj_trace_exit // (jit_State *J, ExitState *ex)
@@ -2177,13 +2202,14 @@ static void build_subroutines(BuildCtx *ctx)
2177 | ldr L, SAVE_L 2202 | ldr L, SAVE_L
2178 |1: 2203 |1:
2179 | cmp CARG1, #0 2204 | cmp CARG1, #0
2180 | blt >3 // Check for error from exit. 2205 | blt >9 // Check for error from exit.
2181 | lsl RC, CARG1, #3 2206 | lsl RC, CARG1, #3
2182 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC] 2207 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2183 | str RC, SAVE_MULTRES 2208 | str RC, SAVE_MULTRES
2184 | mov CARG3, #0 2209 | mov CARG3, #0
2210 | str BASE, L->base
2185 | ldr CARG2, LFUNC:CARG2->field_pc 2211 | ldr CARG2, LFUNC:CARG2->field_pc
2186 | str CARG3, [DISPATCH, #DISPATCH_GL(jit_L)] 2212 | str CARG3, [DISPATCH, #DISPATCH_GL(jit_base)]
2187 | mv_vmstate CARG4, INTERP 2213 | mv_vmstate CARG4, INTERP
2188 | ldr KBASE, [CARG2, #PC2PROTO(k)] 2214 | ldr KBASE, [CARG2, #PC2PROTO(k)]
2189 | // Modified copy of ins_next which handles function header dispatch, too. 2215 | // Modified copy of ins_next which handles function header dispatch, too.
@@ -2192,15 +2218,32 @@ static void build_subroutines(BuildCtx *ctx)
2192 | ldr INS, [PC], #4 2218 | ldr INS, [PC], #4
2193 | lsl MASKR8, MASKR8, #3 // MASKR8 = 255*8. 2219 | lsl MASKR8, MASKR8, #3 // MASKR8 = 255*8.
2194 | st_vmstate CARG4 2220 | st_vmstate CARG4
2221 | cmp OP, #BC_FUNCC+2 // Fast function?
2222 | bhs >4
2223 |2:
2195 | cmp OP, #BC_FUNCF // Function header? 2224 | cmp OP, #BC_FUNCF // Function header?
2196 | ldr OP, [DISPATCH, OP, lsl #2] 2225 | ldr OP, [DISPATCH, OP, lsl #2]
2197 | decode_RA8 RA, INS 2226 | decode_RA8 RA, INS
2198 | lsrlo RC, INS, #16 // No: Decode operands A*8 and D. 2227 | lsrlo RC, INS, #16 // No: Decode operands A*8 and D.
2199 | subhs RC, RC, #8 2228 | subhs RC, RC, #8
2200 | addhs RA, RA, BASE // Yes: RA = BASE+framesize*8, RC = nargs*8 2229 | addhs RA, RA, BASE // Yes: RA = BASE+framesize*8, RC = nargs*8
2230 | ldrhs CARG3, [BASE, FRAME_FUNC]
2201 | bx OP 2231 | bx OP
2202 | 2232 |
2203 |3: // Rethrow error from the right C frame. 2233 |4: // Check frame below fast function.
2234 | ldr CARG1, [BASE, FRAME_PC]
2235 | ands CARG2, CARG1, #FRAME_TYPE
2236 | bne <2 // Trace stitching continuation?
2237 | // Otherwise set KBASE for Lua function below fast function.
2238 | ldr CARG3, [CARG1, #-4]
2239 | decode_RA8 CARG1, CARG3
2240 | sub CARG2, BASE, CARG1
2241 | ldr LFUNC:CARG3, [CARG2, #-16]
2242 | ldr CARG3, LFUNC:CARG3->field_pc
2243 | ldr KBASE, [CARG3, #PC2PROTO(k)]
2244 | b <2
2245 |
2246 |9: // Rethrow error from the right C frame.
2204 | rsb CARG2, CARG1, #0 2247 | rsb CARG2, CARG1, #0
2205 | mov CARG1, L 2248 | mov CARG1, L
2206 | bl extern lj_err_throw // (lua_State *L, int errcode) 2249 | bl extern lj_err_throw // (lua_State *L, int errcode)
@@ -2833,6 +2876,25 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2833 | ins_next 2876 | ins_next
2834 break; 2877 break;
2835 2878
2879 case BC_ISTYPE:
2880 | // RA = src*8, RC = -type
2881 | ldrd CARG12, [BASE, RA]
2882 | ins_next1
2883 | cmn CARG2, RC
2884 | ins_next2
2885 | bne ->vmeta_istype
2886 | ins_next3
2887 break;
2888 case BC_ISNUM:
2889 | // RA = src*8, RC = -(TISNUM-1)
2890 | ldrd CARG12, [BASE, RA]
2891 | ins_next1
2892 | checktp CARG2, LJ_TISNUM
2893 | ins_next2
2894 | bhs ->vmeta_istype
2895 | ins_next3
2896 break;
2897
2836 /* -- Unary ops --------------------------------------------------------- */ 2898 /* -- Unary ops --------------------------------------------------------- */
2837 2899
2838 case BC_MOV: 2900 case BC_MOV:
@@ -3503,6 +3565,24 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3503 | bne <1 // 'no __index' flag set: done. 3565 | bne <1 // 'no __index' flag set: done.
3504 | b ->vmeta_tgetb 3566 | b ->vmeta_tgetb
3505 break; 3567 break;
3568 case BC_TGETR:
3569 | decode_RB8 RB, INS
3570 | decode_RC8 RC, INS
3571 | // RA = dst*8, RB = table*8, RC = key*8
3572 | ldr TAB:CARG1, [BASE, RB]
3573 | ldr CARG2, [BASE, RC]
3574 | ldr CARG4, TAB:CARG1->array
3575 | ldr CARG3, TAB:CARG1->asize
3576 | add CARG4, CARG4, CARG2, lsl #3
3577 | cmp CARG2, CARG3 // In array part?
3578 | bhs ->vmeta_tgetr
3579 | ldrd CARG12, [CARG4]
3580 |->BC_TGETR_Z:
3581 | ins_next1
3582 | ins_next2
3583 | strd CARG12, [BASE, RA]
3584 | ins_next3
3585 break;
3506 3586
3507 case BC_TSETV: 3587 case BC_TSETV:
3508 | decode_RB8 RB, INS 3588 | decode_RB8 RB, INS
@@ -3673,6 +3753,32 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3673 | barrierback TAB:CARG1, INS, CARG3 3753 | barrierback TAB:CARG1, INS, CARG3
3674 | b <2 3754 | b <2
3675 break; 3755 break;
3756 case BC_TSETR:
3757 | decode_RB8 RB, INS
3758 | decode_RC8 RC, INS
3759 | // RA = src*8, RB = table*8, RC = key*8
3760 | ldr TAB:CARG2, [BASE, RB]
3761 | ldr CARG3, [BASE, RC]
3762 | ldrb INS, TAB:CARG2->marked
3763 | ldr CARG1, TAB:CARG2->array
3764 | ldr CARG4, TAB:CARG2->asize
3765 | tst INS, #LJ_GC_BLACK // isblack(table)
3766 | add CARG1, CARG1, CARG3, lsl #3
3767 | bne >7
3768 |2:
3769 | cmp CARG3, CARG4 // In array part?
3770 | bhs ->vmeta_tsetr
3771 |->BC_TSETR_Z:
3772 | ldrd CARG34, [BASE, RA]
3773 | ins_next1
3774 | ins_next2
3775 | strd CARG34, [CARG1]
3776 | ins_next3
3777 |
3778 |7: // Possible table write barrier for the value. Skip valiswhite check.
3779 | barrierback TAB:CARG2, INS, RB
3780 | b <2
3781 break;
3676 3782
3677 case BC_TSETM: 3783 case BC_TSETM:
3678 | // RA = base*8 (table at base-1), RC = num_const (start index) 3784 | // RA = base*8 (table at base-1), RC = num_const (start index)
@@ -4270,7 +4376,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4270 | st_vmstate CARG2 4376 | st_vmstate CARG2
4271 | ldr RA, TRACE:RC->mcode 4377 | ldr RA, TRACE:RC->mcode
4272 | str BASE, [DISPATCH, #DISPATCH_GL(jit_base)] 4378 | str BASE, [DISPATCH, #DISPATCH_GL(jit_base)]
4273 | str L, [DISPATCH, #DISPATCH_GL(jit_L)] 4379 | str L, [DISPATCH, #DISPATCH_GL(tmpbuf.L)]
4274 | bx RA 4380 | bx RA
4275 |.endif 4381 |.endif
4276 break; 4382 break;
@@ -4388,6 +4494,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4388 | ldr BASE, L->base 4494 | ldr BASE, L->base
4389 | mv_vmstate CARG3, INTERP 4495 | mv_vmstate CARG3, INTERP
4390 | ldr CRET2, L->top 4496 | ldr CRET2, L->top
4497 | str L, [DISPATCH, #DISPATCH_GL(cur_L)]
4391 | lsl RC, CRET1, #3 4498 | lsl RC, CRET1, #3
4392 | st_vmstate CARG3 4499 | st_vmstate CARG3
4393 | ldr PC, [BASE, FRAME_PC] 4500 | ldr PC, [BASE, FRAME_PC]
diff --git a/src/vm_arm64.dasc b/src/vm_arm64.dasc
new file mode 100644
index 00000000..bb2496ab
--- /dev/null
+++ b/src/vm_arm64.dasc
@@ -0,0 +1,3964 @@
1|// Low-level VM code for ARM64 CPUs.
2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4|
5|.arch arm64
6|.section code_op, code_sub
7|
8|.actionlist build_actionlist
9|.globals GLOB_
10|.globalnames globnames
11|.externnames extnames
12|
13|// Note: The ragged indentation of the instructions is intentional.
14|// The starting columns indicate data dependencies.
15|
16|//-----------------------------------------------------------------------
17|
18|// ARM64 registers and the AAPCS64 ABI 1.0 at a glance:
19|//
20|// x0-x17 temp, x19-x28 callee-saved, x29 fp, x30 lr
21|// x18 is reserved on most platforms. Don't use it, save it or restore it.
22|// x31 doesn't exist. Register number 31 either means xzr/wzr (zero) or sp,
23|// depending on the instruction.
24|// v0-v7 temp, v8-v15 callee-saved (only d8-d15 preserved), v16-v31 temp
25|//
26|// x0-x7/v0-v7 hold parameters and results.
27|
28|// Fixed register assignments for the interpreter.
29|
30|// The following must be C callee-save.
31|.define BASE, x19 // Base of current Lua stack frame.
32|.define KBASE, x20 // Constants of current Lua function.
33|.define PC, x21 // Next PC.
34|.define GLREG, x22 // Global state.
35|.define LREG, x23 // Register holding lua_State (also in SAVE_L).
36|.define TISNUM, x24 // Constant LJ_TISNUM << 47.
37|.define TISNUMhi, x25 // Constant LJ_TISNUM << 15.
38|.define TISNIL, x26 // Constant -1LL.
39|.define fp, x29 // Yes, we have to maintain a frame pointer.
40|
41|.define ST_INTERP, w26 // Constant -1.
42|
43|// The following temporaries are not saved across C calls, except for RA/RC.
44|.define RA, x27
45|.define RC, x28
46|.define RB, x17
47|.define RAw, w27
48|.define RCw, w28
49|.define RBw, w17
50|.define INS, x16
51|.define INSw, w16
52|.define ITYPE, x15
53|.define TMP0, x8
54|.define TMP1, x9
55|.define TMP2, x10
56|.define TMP3, x11
57|.define TMP0w, w8
58|.define TMP1w, w9
59|.define TMP2w, w10
60|.define TMP3w, w11
61|
62|// Calling conventions. Also used as temporaries.
63|.define CARG1, x0
64|.define CARG2, x1
65|.define CARG3, x2
66|.define CARG4, x3
67|.define CARG5, x4
68|.define CARG1w, w0
69|.define CARG2w, w1
70|.define CARG3w, w2
71|.define CARG4w, w3
72|.define CARG5w, w4
73|
74|.define FARG1, d0
75|.define FARG2, d1
76|
77|.define CRET1, x0
78|.define CRET1w, w0
79|
80|// Stack layout while in interpreter. Must match with lj_frame.h.
81|
82|.define CFRAME_SPACE, 208
83|//----- 16 byte aligned, <-- sp entering interpreter
84|// Unused [sp, #204] // 32 bit values
85|.define SAVE_NRES, [sp, #200]
86|.define SAVE_ERRF, [sp, #196]
87|.define SAVE_MULTRES, [sp, #192]
88|.define TMPD, [sp, #184] // 64 bit values
89|.define SAVE_L, [sp, #176]
90|.define SAVE_PC, [sp, #168]
91|.define SAVE_CFRAME, [sp, #160]
92|.define SAVE_FPR_, 96 // 96+8*8: 64 bit FPR saves
93|.define SAVE_GPR_, 16 // 16+10*8: 64 bit GPR saves
94|.define SAVE_LR, [sp, #8]
95|.define SAVE_FP, [sp]
96|//----- 16 byte aligned, <-- sp while in interpreter.
97|
98|.define TMPDofs, #184
99|
100|.macro save_, gpr1, gpr2, fpr1, fpr2
101| stp d..fpr1, d..fpr2, [sp, # SAVE_FPR_+(fpr1-8)*8]
102| stp x..gpr1, x..gpr2, [sp, # SAVE_GPR_+(gpr1-19)*8]
103|.endmacro
104|.macro rest_, gpr1, gpr2, fpr1, fpr2
105| ldp d..fpr1, d..fpr2, [sp, # SAVE_FPR_+(fpr1-8)*8]
106| ldp x..gpr1, x..gpr2, [sp, # SAVE_GPR_+(gpr1-19)*8]
107|.endmacro
108|
109|.macro saveregs
110| stp fp, lr, [sp, #-CFRAME_SPACE]!
111| add fp, sp, #0
112| stp x19, x20, [sp, # SAVE_GPR_]
113| save_ 21, 22, 8, 9
114| save_ 23, 24, 10, 11
115| save_ 25, 26, 12, 13
116| save_ 27, 28, 14, 15
117|.endmacro
118|.macro restoreregs
119| ldp x19, x20, [sp, # SAVE_GPR_]
120| rest_ 21, 22, 8, 9
121| rest_ 23, 24, 10, 11
122| rest_ 25, 26, 12, 13
123| rest_ 27, 28, 14, 15
124| ldp fp, lr, [sp], # CFRAME_SPACE
125|.endmacro
126|
127|// Type definitions. Some of these are only used for documentation.
128|.type L, lua_State, LREG
129|.type GL, global_State, GLREG
130|.type TVALUE, TValue
131|.type GCOBJ, GCobj
132|.type STR, GCstr
133|.type TAB, GCtab
134|.type LFUNC, GCfuncL
135|.type CFUNC, GCfuncC
136|.type PROTO, GCproto
137|.type UPVAL, GCupval
138|.type NODE, Node
139|.type NARGS8, int
140|.type TRACE, GCtrace
141|.type SBUF, SBuf
142|
143|//-----------------------------------------------------------------------
144|
145|// Trap for not-yet-implemented parts.
146|.macro NYI; brk; .endmacro
147|
148|//-----------------------------------------------------------------------
149|
150|// Access to frame relative to BASE.
151|.define FRAME_FUNC, #-16
152|.define FRAME_PC, #-8
153|
154|.macro decode_RA, dst, ins; ubfx dst, ins, #8, #8; .endmacro
155|.macro decode_RB, dst, ins; ubfx dst, ins, #24, #8; .endmacro
156|.macro decode_RC, dst, ins; ubfx dst, ins, #16, #8; .endmacro
157|.macro decode_RD, dst, ins; ubfx dst, ins, #16, #16; .endmacro
158|.macro decode_RC8RD, dst, src; ubfiz dst, src, #3, #8; .endmacro
159|
160|// Instruction decode+dispatch.
161|.macro ins_NEXT
162| ldr INSw, [PC], #4
163| add TMP1, GL, INS, uxtb #3
164| decode_RA RA, INS
165| ldr TMP0, [TMP1, #GG_G2DISP]
166| decode_RD RC, INS
167| br TMP0
168|.endmacro
169|
170|// Instruction footer.
171|.if 1
172| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
173| .define ins_next, ins_NEXT
174| .define ins_next_, ins_NEXT
175|.else
176| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
177| // Affects only certain kinds of benchmarks (and only with -j off).
178| .macro ins_next
179| b ->ins_next
180| .endmacro
181| .macro ins_next_
182| ->ins_next:
183| ins_NEXT
184| .endmacro
185|.endif
186|
187|// Call decode and dispatch.
188|.macro ins_callt
189| // BASE = new base, CARG3 = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
190| ldr PC, LFUNC:CARG3->pc
191| ldr INSw, [PC], #4
192| add TMP1, GL, INS, uxtb #3
193| decode_RA RA, INS
194| ldr TMP0, [TMP1, #GG_G2DISP]
195| add RA, BASE, RA, lsl #3
196| br TMP0
197|.endmacro
198|
199|.macro ins_call
200| // BASE = new base, CARG3 = LFUNC/CFUNC, RC = nargs*8, PC = caller PC
201| str PC, [BASE, FRAME_PC]
202| ins_callt
203|.endmacro
204|
205|//-----------------------------------------------------------------------
206|
207|// Macros to check the TValue type and extract the GCobj. Branch on failure.
208|.macro checktp, reg, tp, target
209| asr ITYPE, reg, #47
210| cmn ITYPE, #-tp
211| and reg, reg, #LJ_GCVMASK
212| bne target
213|.endmacro
214|.macro checktp, dst, reg, tp, target
215| asr ITYPE, reg, #47
216| cmn ITYPE, #-tp
217| and dst, reg, #LJ_GCVMASK
218| bne target
219|.endmacro
220|.macro checkstr, reg, target; checktp reg, LJ_TSTR, target; .endmacro
221|.macro checktab, reg, target; checktp reg, LJ_TTAB, target; .endmacro
222|.macro checkfunc, reg, target; checktp reg, LJ_TFUNC, target; .endmacro
223|.macro checkint, reg, target
224| cmp TISNUMhi, reg, lsr #32
225| bne target
226|.endmacro
227|.macro checknum, reg, target
228| cmp TISNUMhi, reg, lsr #32
229| bls target
230|.endmacro
231|.macro checknumber, reg, target
232| cmp TISNUMhi, reg, lsr #32
233| blo target
234|.endmacro
235|
236|.macro mov_false, reg; movn reg, #0x8000, lsl #32; .endmacro
237|.macro mov_true, reg; movn reg, #0x0001, lsl #48; .endmacro
238|
239#define GL_J(field) (GG_G2J + (int)offsetof(jit_State, field))
240|
241#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
242|
243|.macro hotcheck, delta
244| lsr CARG1, PC, #1
245| and CARG1, CARG1, #126
246| add CARG1, CARG1, #GG_G2DISP+GG_DISP2HOT
247| ldrh CARG2w, [GL, CARG1]
248| subs CARG2, CARG2, #delta
249| strh CARG2w, [GL, CARG1]
250|.endmacro
251|
252|.macro hotloop
253| hotcheck HOTCOUNT_LOOP
254| blo ->vm_hotloop
255|.endmacro
256|
257|.macro hotcall
258| hotcheck HOTCOUNT_CALL
259| blo ->vm_hotcall
260|.endmacro
261|
262|// Set current VM state.
263|.macro mv_vmstate, reg, st; movn reg, #LJ_VMST_..st; .endmacro
264|.macro st_vmstate, reg; str reg, GL->vmstate; .endmacro
265|
266|// Move table write barrier back. Overwrites mark and tmp.
267|.macro barrierback, tab, mark, tmp
268| ldr tmp, GL->gc.grayagain
269| and mark, mark, #~LJ_GC_BLACK // black2gray(tab)
270| str tab, GL->gc.grayagain
271| strb mark, tab->marked
272| str tmp, tab->gclist
273|.endmacro
274|
275|//-----------------------------------------------------------------------
276
277#if !LJ_DUALNUM
278#error "Only dual-number mode supported for ARM64 target"
279#endif
280
281/* Generate subroutines used by opcodes and other parts of the VM. */
282/* The .code_sub section should be last to help static branch prediction. */
283static void build_subroutines(BuildCtx *ctx)
284{
285 |.code_sub
286 |
287 |//-----------------------------------------------------------------------
288 |//-- Return handling ----------------------------------------------------
289 |//-----------------------------------------------------------------------
290 |
291 |->vm_returnp:
292 | // See vm_return. Also: RB = previous base.
293 | tbz PC, #2, ->cont_dispatch // (PC & FRAME_P) == 0?
294 |
295 | // Return from pcall or xpcall fast func.
296 | ldr PC, [RB, FRAME_PC] // Fetch PC of previous frame.
297 | mov_true TMP0
298 | mov BASE, RB
299 | // Prepending may overwrite the pcall frame, so do it at the end.
300 | str TMP0, [RA, #-8]! // Prepend true to results.
301 |
302 |->vm_returnc:
303 | adds RC, RC, #8 // RC = (nresults+1)*8.
304 | mov CRET1, #LUA_YIELD
305 | beq ->vm_unwind_c_eh
306 | str RCw, SAVE_MULTRES
307 | ands CARG1, PC, #FRAME_TYPE
308 | beq ->BC_RET_Z // Handle regular return to Lua.
309 |
310 |->vm_return:
311 | // BASE = base, RA = resultptr, RC/MULTRES = (nresults+1)*8, PC = return
312 | // CARG1 = PC & FRAME_TYPE
313 | and RB, PC, #~FRAME_TYPEP
314 | cmp CARG1, #FRAME_C
315 | sub RB, BASE, RB // RB = previous base.
316 | bne ->vm_returnp
317 |
318 | str RB, L->base
319 | ldrsw CARG2, SAVE_NRES // CARG2 = nresults+1.
320 | mv_vmstate TMP0w, C
321 | sub BASE, BASE, #16
322 | subs TMP2, RC, #8
323 | st_vmstate TMP0w
324 | beq >2
325 |1:
326 | subs TMP2, TMP2, #8
327 | ldr TMP0, [RA], #8
328 | str TMP0, [BASE], #8
329 | bne <1
330 |2:
331 | cmp RC, CARG2, lsl #3 // More/less results wanted?
332 | bne >6
333 |3:
334 | str BASE, L->top // Store new top.
335 |
336 |->vm_leave_cp:
337 | ldr RC, SAVE_CFRAME // Restore previous C frame.
338 | mov CRET1, #0 // Ok return status for vm_pcall.
339 | str RC, L->cframe
340 |
341 |->vm_leave_unw:
342 | restoreregs
343 | ret
344 |
345 |6:
346 | bgt >7 // Less results wanted?
347 | // More results wanted. Check stack size and fill up results with nil.
348 | ldr CARG3, L->maxstack
349 | cmp BASE, CARG3
350 | bhs >8
351 | str TISNIL, [BASE], #8
352 | add RC, RC, #8
353 | b <2
354 |
355 |7: // Less results wanted.
356 | cbz CARG2, <3 // LUA_MULTRET+1 case?
357 | sub CARG1, RC, CARG2, lsl #3
358 | sub BASE, BASE, CARG1 // Shrink top.
359 | b <3
360 |
361 |8: // Corner case: need to grow stack for filling up results.
362 | // This can happen if:
363 | // - A C function grows the stack (a lot).
364 | // - The GC shrinks the stack in between.
365 | // - A return back from a lua_call() with (high) nresults adjustment.
366 | str BASE, L->top // Save current top held in BASE (yes).
367 | mov CARG1, L
368 | bl extern lj_state_growstack // (lua_State *L, int n)
369 | ldr BASE, L->top // Need the (realloced) L->top in BASE.
370 | ldrsw CARG2, SAVE_NRES
371 | b <2
372 |
373 |->vm_unwind_c: // Unwind C stack, return from vm_pcall.
374 | // (void *cframe, int errcode)
375 | mov sp, CARG1
376 | mov CRET1, CARG2
377 |->vm_unwind_c_eh: // Landing pad for external unwinder.
378 | ldr L, SAVE_L
379 | mv_vmstate TMP0w, C
380 | ldr GL, L->glref
381 | st_vmstate TMP0w
382 | b ->vm_leave_unw
383 |
384 |->vm_unwind_ff: // Unwind C stack, return from ff pcall.
385 | // (void *cframe)
386 | and sp, CARG1, #CFRAME_RAWMASK
387 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
388 | ldr L, SAVE_L
389 | movz TISNUM, #(LJ_TISNUM>>1)&0xffff, lsl #48
390 | movz TISNUMhi, #(LJ_TISNUM>>1)&0xffff, lsl #16
391 | movn TISNIL, #0
392 | mov RC, #16 // 2 results: false + error message.
393 | ldr BASE, L->base
394 | ldr GL, L->glref // Setup pointer to global state.
395 | mov_false TMP0
396 | sub RA, BASE, #8 // Results start at BASE-8.
397 | ldr PC, [BASE, FRAME_PC] // Fetch PC of previous frame.
398 | str TMP0, [BASE, #-8] // Prepend false to error message.
399 | st_vmstate ST_INTERP
400 | b ->vm_returnc
401 |
402 |//-----------------------------------------------------------------------
403 |//-- Grow stack for calls -----------------------------------------------
404 |//-----------------------------------------------------------------------
405 |
406 |->vm_growstack_c: // Grow stack for C function.
407 | // CARG1 = L
408 | mov CARG2, #LUA_MINSTACK
409 | b >2
410 |
411 |->vm_growstack_l: // Grow stack for Lua function.
412 | // BASE = new base, RA = BASE+framesize*8, RC = nargs*8, PC = first PC
413 | add RC, BASE, RC
414 | sub RA, RA, BASE
415 | mov CARG1, L
416 | stp BASE, RC, L->base
417 | add PC, PC, #4 // Must point after first instruction.
418 | lsr CARG2, RA, #3
419 |2:
420 | // L->base = new base, L->top = top
421 | str PC, SAVE_PC
422 | bl extern lj_state_growstack // (lua_State *L, int n)
423 | ldp BASE, RC, L->base
424 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC]
425 | sub NARGS8:RC, RC, BASE
426 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
427 | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
428 | ins_callt // Just retry the call.
429 |
430 |//-----------------------------------------------------------------------
431 |//-- Entry points into the assembler VM ---------------------------------
432 |//-----------------------------------------------------------------------
433 |
434 |->vm_resume: // Setup C frame and resume thread.
435 | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
436 | saveregs
437 | mov L, CARG1
438 | ldr GL, L->glref // Setup pointer to global state.
439 | mov BASE, CARG2
440 | str L, SAVE_L
441 | mov PC, #FRAME_CP
442 | str wzr, SAVE_NRES
443 | add TMP0, sp, #CFRAME_RESUME
444 | ldrb TMP1w, L->status
445 | str wzr, SAVE_ERRF
446 | str L, SAVE_PC // Any value outside of bytecode is ok.
447 | str xzr, SAVE_CFRAME
448 | str TMP0, L->cframe
449 | cbz TMP1w, >3
450 |
451 | // Resume after yield (like a return).
452 | str L, GL->cur_L
453 | mov RA, BASE
454 | ldp BASE, CARG1, L->base
455 | movz TISNUM, #(LJ_TISNUM>>1)&0xffff, lsl #48
456 | movz TISNUMhi, #(LJ_TISNUM>>1)&0xffff, lsl #16
457 | ldr PC, [BASE, FRAME_PC]
458 | strb wzr, L->status
459 | movn TISNIL, #0
460 | sub RC, CARG1, BASE
461 | ands CARG1, PC, #FRAME_TYPE
462 | add RC, RC, #8
463 | st_vmstate ST_INTERP
464 | str RCw, SAVE_MULTRES
465 | beq ->BC_RET_Z
466 | b ->vm_return
467 |
468 |->vm_pcall: // Setup protected C frame and enter VM.
469 | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
470 | saveregs
471 | mov PC, #FRAME_CP
472 | str CARG4w, SAVE_ERRF
473 | b >1
474 |
475 |->vm_call: // Setup C frame and enter VM.
476 | // (lua_State *L, TValue *base, int nres1)
477 | saveregs
478 | mov PC, #FRAME_C
479 |
480 |1: // Entry point for vm_pcall above (PC = ftype).
481 | ldr RC, L:CARG1->cframe
482 | str CARG3w, SAVE_NRES
483 | mov L, CARG1
484 | str CARG1, SAVE_L
485 | ldr GL, L->glref // Setup pointer to global state.
486 | mov BASE, CARG2
487 | str CARG1, SAVE_PC // Any value outside of bytecode is ok.
488 | str RC, SAVE_CFRAME
489 | str fp, L->cframe // Add our C frame to cframe chain.
490 |
491 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
492 | str L, GL->cur_L
493 | ldp RB, CARG1, L->base // RB = old base (for vmeta_call).
494 | movz TISNUM, #(LJ_TISNUM>>1)&0xffff, lsl #48
495 | movz TISNUMhi, #(LJ_TISNUM>>1)&0xffff, lsl #16
496 | add PC, PC, BASE
497 | movn TISNIL, #0
498 | sub PC, PC, RB // PC = frame delta + frame type
499 | sub NARGS8:RC, CARG1, BASE
500 | st_vmstate ST_INTERP
501 |
502 |->vm_call_dispatch:
503 | // RB = old base, BASE = new base, RC = nargs*8, PC = caller PC
504 | ldr CARG3, [BASE, FRAME_FUNC]
505 | checkfunc CARG3, ->vmeta_call
506 |
507 |->vm_call_dispatch_f:
508 | ins_call
509 | // BASE = new base, CARG3 = func, RC = nargs*8, PC = caller PC
510 |
511 |->vm_cpcall: // Setup protected C frame, call C.
512 | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
513 | saveregs
514 | mov L, CARG1
515 | ldr RA, L:CARG1->stack
516 | str CARG1, SAVE_L
517 | ldr GL, L->glref // Setup pointer to global state.
518 | ldr RB, L->top
519 | str CARG1, SAVE_PC // Any value outside of bytecode is ok.
520 | ldr RC, L->cframe
521 | sub RA, RA, RB // Compute -savestack(L, L->top).
522 | str RAw, SAVE_NRES // Neg. delta means cframe w/o frame.
523 | str wzr, SAVE_ERRF // No error function.
524 | str RC, SAVE_CFRAME
525 | str fp, L->cframe // Add our C frame to cframe chain.
526 | str L, GL->cur_L
527 | blr CARG4 // (lua_State *L, lua_CFunction func, void *ud)
528 | mov BASE, CRET1
529 | mov PC, #FRAME_CP
530 | cbnz BASE, <3 // Else continue with the call.
531 | b ->vm_leave_cp // No base? Just remove C frame.
532 |
533 |//-----------------------------------------------------------------------
534 |//-- Metamethod handling ------------------------------------------------
535 |//-----------------------------------------------------------------------
536 |
537 |//-- Continuation dispatch ----------------------------------------------
538 |
539 |->cont_dispatch:
540 | // BASE = meta base, RA = resultptr, RC = (nresults+1)*8
541 | ldr LFUNC:CARG3, [RB, FRAME_FUNC]
542 | ldr CARG1, [BASE, #-32] // Get continuation.
543 | mov CARG4, BASE
544 | mov BASE, RB // Restore caller BASE.
545 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
546 |.if FFI
547 | cmp CARG1, #1
548 |.endif
549 | ldr PC, [CARG4, #-24] // Restore PC from [cont|PC].
550 | ldr CARG3, LFUNC:CARG3->pc
551 | add TMP0, RA, RC
552 | str TISNIL, [TMP0, #-8] // Ensure one valid arg.
553 |.if FFI
554 | bls >1
555 |.endif
556 | ldr KBASE, [CARG3, #PC2PROTO(k)]
557 | // BASE = base, RA = resultptr, CARG4 = meta base
558 | br CARG1
559 |
560 |.if FFI
561 |1:
562 | beq ->cont_ffi_callback // cont = 1: return from FFI callback.
563 | // cont = 0: tailcall from C function.
564 | sub CARG4, CARG4, #32
565 | sub RC, CARG4, BASE
566 | b ->vm_call_tail
567 |.endif
568 |
569 |->cont_cat: // RA = resultptr, CARG4 = meta base
570 | ldr INSw, [PC, #-4]
571 | sub CARG2, CARG4, #32
572 | ldr TMP0, [RA]
573 | str BASE, L->base
574 | decode_RB RB, INS
575 | decode_RA RA, INS
576 | add TMP1, BASE, RB, lsl #3
577 | subs TMP1, CARG2, TMP1
578 | beq >1
579 | str TMP0, [CARG2]
580 | lsr CARG3, TMP1, #3
581 | b ->BC_CAT_Z
582 |
583 |1:
584 | str TMP0, [BASE, RA, lsl #3]
585 | b ->cont_nop
586 |
587 |//-- Table indexing metamethods -----------------------------------------
588 |
589 |->vmeta_tgets1:
590 | movn CARG4, #~LJ_TSTR
591 | add CARG2, BASE, RB, lsl #3
592 | add CARG4, STR:RC, CARG4, lsl #47
593 | b >2
594 |
595 |->vmeta_tgets:
596 | movk CARG2, #(LJ_TTAB>>1)&0xffff, lsl #48
597 | str CARG2, GL->tmptv
598 | add CARG2, GL, #offsetof(global_State, tmptv)
599 |2:
600 | add CARG3, sp, TMPDofs
601 | str CARG4, TMPD
602 | b >1
603 |
604 |->vmeta_tgetb: // RB = table, RC = index
605 | add RC, RC, TISNUM
606 | add CARG2, BASE, RB, lsl #3
607 | add CARG3, sp, TMPDofs
608 | str RC, TMPD
609 | b >1
610 |
611 |->vmeta_tgetv: // RB = table, RC = key
612 | add CARG2, BASE, RB, lsl #3
613 | add CARG3, BASE, RC, lsl #3
614 |1:
615 | str BASE, L->base
616 | mov CARG1, L
617 | str PC, SAVE_PC
618 | bl extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
619 | // Returns TValue * (finished) or NULL (metamethod).
620 | cbz CRET1, >3
621 | ldr TMP0, [CRET1]
622 | str TMP0, [BASE, RA, lsl #3]
623 | ins_next
624 |
625 |3: // Call __index metamethod.
626 | // BASE = base, L->top = new base, stack = cont/func/t/k
627 | sub TMP1, BASE, #FRAME_CONT
628 | ldr BASE, L->top
629 | mov NARGS8:RC, #16 // 2 args for func(t, k).
630 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here.
631 | str PC, [BASE, #-24] // [cont|PC]
632 | sub PC, BASE, TMP1
633 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
634 | b ->vm_call_dispatch_f
635 |
636 |->vmeta_tgetr:
637 | sxtw CARG2, TMP1w
638 | bl extern lj_tab_getinth // (GCtab *t, int32_t key)
639 | // Returns cTValue * or NULL.
640 | mov TMP0, TISNIL
641 | cbz CRET1, ->BC_TGETR_Z
642 | ldr TMP0, [CRET1]
643 | b ->BC_TGETR_Z
644 |
645 |//-----------------------------------------------------------------------
646 |
647 |->vmeta_tsets1:
648 | movn CARG4, #~LJ_TSTR
649 | add CARG2, BASE, RB, lsl #3
650 | add CARG4, STR:RC, CARG4, lsl #47
651 | b >2
652 |
653 |->vmeta_tsets:
654 | movk CARG2, #(LJ_TTAB>>1)&0xffff, lsl #48
655 | str CARG2, GL->tmptv
656 | add CARG2, GL, #offsetof(global_State, tmptv)
657 |2:
658 | add CARG3, sp, TMPDofs
659 | str CARG4, TMPD
660 | b >1
661 |
662 |->vmeta_tsetb: // RB = table, RC = index
663 | add RC, RC, TISNUM
664 | add CARG2, BASE, RB, lsl #3
665 | add CARG3, sp, TMPDofs
666 | str RC, TMPD
667 | b >1
668 |
669 |->vmeta_tsetv:
670 | add CARG2, BASE, RB, lsl #3
671 | add CARG3, BASE, RC, lsl #3
672 |1:
673 | str BASE, L->base
674 | mov CARG1, L
675 | str PC, SAVE_PC
676 | bl extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
677 | // Returns TValue * (finished) or NULL (metamethod).
678 | ldr TMP0, [BASE, RA, lsl #3]
679 | cbz CRET1, >3
680 | // NOBARRIER: lj_meta_tset ensures the table is not black.
681 | str TMP0, [CRET1]
682 | ins_next
683 |
684 |3: // Call __newindex metamethod.
685 | // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
686 | sub TMP1, BASE, #FRAME_CONT
687 | ldr BASE, L->top
688 | mov NARGS8:RC, #24 // 3 args for func(t, k, v).
689 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here.
690 | str TMP0, [BASE, #16] // Copy value to third argument.
691 | str PC, [BASE, #-24] // [cont|PC]
692 | sub PC, BASE, TMP1
693 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
694 | b ->vm_call_dispatch_f
695 |
696 |->vmeta_tsetr:
697 | sxtw CARG3, TMP1w
698 | str BASE, L->base
699 | str PC, SAVE_PC
700 | bl extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
701 | // Returns TValue *.
702 | b ->BC_TSETR_Z
703 |
704 |//-- Comparison metamethods ---------------------------------------------
705 |
706 |->vmeta_comp:
707 | add CARG2, BASE, RA, lsl #3
708 | sub PC, PC, #4
709 | add CARG3, BASE, RC, lsl #3
710 | str BASE, L->base
711 | mov CARG1, L
712 | str PC, SAVE_PC
713 | uxtb CARG4w, INSw
714 | bl extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
715 | // Returns 0/1 or TValue * (metamethod).
716 |3:
717 | cmp CRET1, #1
718 | bhi ->vmeta_binop
719 |4:
720 | ldrh RBw, [PC, #2]
721 | add PC, PC, #4
722 | add RB, PC, RB, lsl #2
723 | sub RB, RB, #0x20000
724 | csel PC, PC, RB, lo
725 |->cont_nop:
726 | ins_next
727 |
728 |->cont_ra: // RA = resultptr
729 | ldr INSw, [PC, #-4]
730 | ldr TMP0, [RA]
731 | decode_RA TMP1, INS
732 | str TMP0, [BASE, TMP1, lsl #3]
733 | b ->cont_nop
734 |
735 |->cont_condt: // RA = resultptr
736 | ldr TMP0, [RA]
737 | mov_true TMP1
738 | cmp TMP1, TMP0 // Branch if result is true.
739 | b <4
740 |
741 |->cont_condf: // RA = resultptr
742 | ldr TMP0, [RA]
743 | mov_false TMP1
744 | cmp TMP0, TMP1 // Branch if result is false.
745 | b <4
746 |
747 |->vmeta_equal:
748 | // CARG2, CARG3, CARG4 are already set by BC_ISEQV/BC_ISNEV.
749 | and TAB:CARG3, CARG3, #LJ_GCVMASK
750 | sub PC, PC, #4
751 | str BASE, L->base
752 | mov CARG1, L
753 | str PC, SAVE_PC
754 | bl extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
755 | // Returns 0/1 or TValue * (metamethod).
756 | b <3
757 |
758 |->vmeta_equal_cd:
759 |.if FFI
760 | sub PC, PC, #4
761 | str BASE, L->base
762 | mov CARG1, L
763 | mov CARG2, INS
764 | str PC, SAVE_PC
765 | bl extern lj_meta_equal_cd // (lua_State *L, BCIns op)
766 | // Returns 0/1 or TValue * (metamethod).
767 | b <3
768 |.endif
769 |
770 |->vmeta_istype:
771 | sub PC, PC, #4
772 | str BASE, L->base
773 | mov CARG1, L
774 | mov CARG2, RA
775 | mov CARG3, RC
776 | str PC, SAVE_PC
777 | bl extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
778 | b ->cont_nop
779 |
780 |//-- Arithmetic metamethods ---------------------------------------------
781 |
782 |->vmeta_arith_vn:
783 | add CARG3, BASE, RB, lsl #3
784 | add CARG4, KBASE, RC, lsl #3
785 | b >1
786 |
787 |->vmeta_arith_nv:
788 | add CARG4, BASE, RB, lsl #3
789 | add CARG3, KBASE, RC, lsl #3
790 | b >1
791 |
792 |->vmeta_unm:
793 | add CARG3, BASE, RC, lsl #3
794 | mov CARG4, CARG3
795 | b >1
796 |
797 |->vmeta_arith_vv:
798 | add CARG3, BASE, RB, lsl #3
799 | add CARG4, BASE, RC, lsl #3
800 |1:
801 | uxtb CARG5w, INSw
802 | add CARG2, BASE, RA, lsl #3
803 | str BASE, L->base
804 | mov CARG1, L
805 | str PC, SAVE_PC
806 | bl extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
807 | // Returns NULL (finished) or TValue * (metamethod).
808 | cbz CRET1, ->cont_nop
809 |
810 | // Call metamethod for binary op.
811 |->vmeta_binop:
812 | // BASE = old base, CRET1 = new base, stack = cont/func/o1/o2
813 | sub TMP1, CRET1, BASE
814 | str PC, [CRET1, #-24] // [cont|PC]
815 | add PC, TMP1, #FRAME_CONT
816 | mov BASE, CRET1
817 | mov NARGS8:RC, #16 // 2 args for func(o1, o2).
818 | b ->vm_call_dispatch
819 |
820 |->vmeta_len:
821 | add CARG2, BASE, RC, lsl #3
822#if LJ_52
823 | mov TAB:RC, TAB:CARG1 // Save table (ignored for other types).
824#endif
825 | str BASE, L->base
826 | mov CARG1, L
827 | str PC, SAVE_PC
828 | bl extern lj_meta_len // (lua_State *L, TValue *o)
829 | // Returns NULL (retry) or TValue * (metamethod base).
830#if LJ_52
831 | cbnz CRET1, ->vmeta_binop // Binop call for compatibility.
832 | mov TAB:CARG1, TAB:RC
833 | b ->BC_LEN_Z
834#else
835 | b ->vmeta_binop // Binop call for compatibility.
836#endif
837 |
838 |//-- Call metamethod ----------------------------------------------------
839 |
840 |->vmeta_call: // Resolve and call __call metamethod.
841 | // RB = old base, BASE = new base, RC = nargs*8
842 | mov CARG1, L
843 | str RB, L->base // This is the callers base!
844 | sub CARG2, BASE, #16
845 | str PC, SAVE_PC
846 | add CARG3, BASE, NARGS8:RC
847 | bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
848 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Guaranteed to be a function here.
849 | add NARGS8:RC, NARGS8:RC, #8 // Got one more argument now.
850 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
851 | ins_call
852 |
853 |->vmeta_callt: // Resolve __call for BC_CALLT.
854 | // BASE = old base, RA = new base, RC = nargs*8
855 | mov CARG1, L
856 | str BASE, L->base
857 | sub CARG2, RA, #16
858 | str PC, SAVE_PC
859 | add CARG3, RA, NARGS8:RC
860 | bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
861 | ldr TMP1, [RA, FRAME_FUNC] // Guaranteed to be a function here.
862 | ldr PC, [BASE, FRAME_PC]
863 | add NARGS8:RC, NARGS8:RC, #8 // Got one more argument now.
864 | and LFUNC:CARG3, TMP1, #LJ_GCVMASK
865 | b ->BC_CALLT2_Z
866 |
867 |//-- Argument coercion for 'for' statement ------------------------------
868 |
869 |->vmeta_for:
870 | mov CARG1, L
871 | str BASE, L->base
872 | mov CARG2, RA
873 | str PC, SAVE_PC
874 | bl extern lj_meta_for // (lua_State *L, TValue *base)
875 | ldr INSw, [PC, #-4]
876 |.if JIT
877 | uxtb TMP0w, INSw
878 |.endif
879 | decode_RA RA, INS
880 | decode_RD RC, INS
881 |.if JIT
882 | cmp TMP0, #BC_JFORI
883 | beq =>BC_JFORI
884 |.endif
885 | b =>BC_FORI
886 |
887 |//-----------------------------------------------------------------------
888 |//-- Fast functions -----------------------------------------------------
889 |//-----------------------------------------------------------------------
890 |
891 |.macro .ffunc, name
892 |->ff_ .. name:
893 |.endmacro
894 |
895 |.macro .ffunc_1, name
896 |->ff_ .. name:
897 | ldr CARG1, [BASE]
898 | cmp NARGS8:RC, #8
899 | blo ->fff_fallback
900 |.endmacro
901 |
902 |.macro .ffunc_2, name
903 |->ff_ .. name:
904 | ldp CARG1, CARG2, [BASE]
905 | cmp NARGS8:RC, #16
906 | blo ->fff_fallback
907 |.endmacro
908 |
909 |.macro .ffunc_n, name
910 | .ffunc name
911 | ldr CARG1, [BASE]
912 | cmp NARGS8:RC, #8
913 | ldr FARG1, [BASE]
914 | blo ->fff_fallback
915 | checknum CARG1, ->fff_fallback
916 |.endmacro
917 |
918 |.macro .ffunc_nn, name
919 | .ffunc name
920 | ldp CARG1, CARG2, [BASE]
921 | cmp NARGS8:RC, #16
922 | ldp FARG1, FARG2, [BASE]
923 | blo ->fff_fallback
924 | checknum CARG1, ->fff_fallback
925 | checknum CARG2, ->fff_fallback
926 |.endmacro
927 |
928 |// Inlined GC threshold check. Caveat: uses CARG1 and CARG2.
929 |.macro ffgccheck
930 | ldp CARG1, CARG2, GL->gc.total // Assumes threshold follows total.
931 | cmp CARG1, CARG2
932 | blt >1
933 | bl ->fff_gcstep
934 |1:
935 |.endmacro
936 |
937 |//-- Base library: checks -----------------------------------------------
938 |
939 |.ffunc_1 assert
940 | ldr PC, [BASE, FRAME_PC]
941 | mov_false TMP1
942 | cmp CARG1, TMP1
943 | bhs ->fff_fallback
944 | str CARG1, [BASE, #-16]
945 | sub RB, BASE, #8
946 | subs RA, NARGS8:RC, #8
947 | add RC, NARGS8:RC, #8 // Compute (nresults+1)*8.
948 | cbz RA, ->fff_res // Done if exactly 1 argument.
949 |1:
950 | ldr CARG1, [RB, #16]
951 | sub RA, RA, #8
952 | str CARG1, [RB], #8
953 | cbnz RA, <1
954 | b ->fff_res
955 |
956 |.ffunc_1 type
957 | mov TMP0, #~LJ_TISNUM
958 | asr ITYPE, CARG1, #47
959 | cmn ITYPE, #~LJ_TISNUM
960 | csinv TMP1, TMP0, ITYPE, lo
961 | add TMP1, TMP1, #offsetof(GCfuncC, upvalue)/8
962 | ldr CARG1, [CFUNC:CARG3, TMP1, lsl #3]
963 | b ->fff_restv
964 |
965 |//-- Base library: getters and setters ---------------------------------
966 |
967 |.ffunc_1 getmetatable
968 | asr ITYPE, CARG1, #47
969 | cmn ITYPE, #-LJ_TTAB
970 | ccmn ITYPE, #-LJ_TUDATA, #4, ne
971 | and TAB:CARG1, CARG1, #LJ_GCVMASK
972 | bne >6
973 |1: // Field metatable must be at same offset for GCtab and GCudata!
974 | ldr TAB:RB, TAB:CARG1->metatable
975 |2:
976 | mov CARG1, TISNIL
977 | ldr STR:RC, GL->gcroot[GCROOT_MMNAME+MM_metatable]
978 | cbz TAB:RB, ->fff_restv
979 | ldr TMP1w, TAB:RB->hmask
980 | ldr TMP2w, STR:RC->hash
981 | ldr NODE:CARG3, TAB:RB->node
982 | and TMP1w, TMP1w, TMP2w // idx = str->hash & tab->hmask
983 | add TMP1, TMP1, TMP1, lsl #1
984 | movn CARG4, #~LJ_TSTR
985 | add NODE:CARG3, NODE:CARG3, TMP1, lsl #3 // node = tab->node + idx*3*8
986 | add CARG4, STR:RC, CARG4, lsl #47 // Tagged key to look for.
987 |3: // Rearranged logic, because we expect _not_ to find the key.
988 | ldp CARG1, TMP0, NODE:CARG3->val
989 | ldr NODE:CARG3, NODE:CARG3->next
990 | cmp TMP0, CARG4
991 | beq >5
992 | cbnz NODE:CARG3, <3
993 |4:
994 | mov CARG1, RB // Use metatable as default result.
995 | movk CARG1, #(LJ_TTAB>>1)&0xffff, lsl #48
996 | b ->fff_restv
997 |5:
998 | cmp TMP0, TISNIL
999 | bne ->fff_restv
1000 | b <4
1001 |
1002 |6:
1003 | movn TMP0, #~LJ_TISNUM
1004 | cmp ITYPE, TMP0
1005 | csel ITYPE, ITYPE, TMP0, hs
1006 | sub TMP1, GL, ITYPE, lsl #3
1007 | ldr TAB:RB, [TMP1, #offsetof(global_State, gcroot[GCROOT_BASEMT])-8]
1008 | b <2
1009 |
1010 |.ffunc_2 setmetatable
1011 | // Fast path: no mt for table yet and not clearing the mt.
1012 | checktp TMP1, CARG1, LJ_TTAB, ->fff_fallback
1013 | ldr TAB:TMP0, TAB:TMP1->metatable
1014 | asr ITYPE, CARG2, #47
1015 | ldrb TMP2w, TAB:TMP1->marked
1016 | cmn ITYPE, #-LJ_TTAB
1017 | and TAB:CARG2, CARG2, #LJ_GCVMASK
1018 | ccmp TAB:TMP0, #0, #0, eq
1019 | bne ->fff_fallback
1020 | str TAB:CARG2, TAB:TMP1->metatable
1021 | tbz TMP2w, #2, ->fff_restv // isblack(table)
1022 | barrierback TAB:TMP1, TMP2w, TMP0
1023 | b ->fff_restv
1024 |
1025 |.ffunc rawget
1026 | ldr CARG2, [BASE]
1027 | cmp NARGS8:RC, #16
1028 | blo ->fff_fallback
1029 | checktab CARG2, ->fff_fallback
1030 | mov CARG1, L
1031 | add CARG3, BASE, #8
1032 | bl extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
1033 | // Returns cTValue *.
1034 | ldr CARG1, [CRET1]
1035 | b ->fff_restv
1036 |
1037 |//-- Base library: conversions ------------------------------------------
1038 |
1039 |.ffunc tonumber
1040 | // Only handles the number case inline (without a base argument).
1041 | ldr CARG1, [BASE]
1042 | cmp NARGS8:RC, #8
1043 | bne ->fff_fallback
1044 | checknumber CARG1, ->fff_fallback
1045 | b ->fff_restv
1046 |
1047 |.ffunc_1 tostring
1048 | // Only handles the string or number case inline.
1049 | asr ITYPE, CARG1, #47
1050 | cmn ITYPE, #-LJ_TSTR
1051 | // A __tostring method in the string base metatable is ignored.
1052 | beq ->fff_restv
1053 | // Handle numbers inline, unless a number base metatable is present.
1054 | ldr TMP1, GL->gcroot[GCROOT_BASEMT_NUM]
1055 | str BASE, L->base
1056 | cmn ITYPE, #-LJ_TISNUM
1057 | ccmp TMP1, #0, #0, ls
1058 | str PC, SAVE_PC // Redundant (but a defined value).
1059 | bne ->fff_fallback
1060 | ffgccheck
1061 | mov CARG1, L
1062 | mov CARG2, BASE
1063 | bl extern lj_strfmt_number // (lua_State *L, cTValue *o)
1064 | // Returns GCstr *.
1065 | movn TMP1, #~LJ_TSTR
1066 | ldr BASE, L->base
1067 | add CARG1, CARG1, TMP1, lsl #47
1068 | b ->fff_restv
1069 |
1070 |//-- Base library: iterators -------------------------------------------
1071 |
1072 |.ffunc_1 next
1073 | checktp CARG2, CARG1, LJ_TTAB, ->fff_fallback
1074 | str TISNIL, [BASE, NARGS8:RC] // Set missing 2nd arg to nil.
1075 | ldr PC, [BASE, FRAME_PC]
1076 | stp BASE, BASE, L->base // Add frame since C call can throw.
1077 | mov CARG1, L
1078 | add CARG3, BASE, #8
1079 | str PC, SAVE_PC
1080 | bl extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key)
1081 | // Returns 0 at end of traversal.
1082 | str TISNIL, [BASE, #-16]
1083 | cbz CRET1, ->fff_res1 // End of traversal: return nil.
1084 | ldp CARG1, CARG2, [BASE, #8] // Copy key and value to results.
1085 | mov RC, #(2+1)*8
1086 | stp CARG1, CARG2, [BASE, #-16]
1087 | b ->fff_res
1088 |
1089 |.ffunc_1 pairs
1090 | checktp TMP1, CARG1, LJ_TTAB, ->fff_fallback
1091#if LJ_52
1092 | ldr TAB:CARG2, TAB:TMP1->metatable
1093#endif
1094 | ldr CFUNC:CARG4, CFUNC:CARG3->upvalue[0]
1095 | ldr PC, [BASE, FRAME_PC]
1096#if LJ_52
1097 | cbnz TAB:CARG2, ->fff_fallback
1098#endif
1099 | mov RC, #(3+1)*8
1100 | stp CARG1, TISNIL, [BASE, #-8]
1101 | str CFUNC:CARG4, [BASE, #-16]
1102 | b ->fff_res
1103 |
1104 |.ffunc_2 ipairs_aux
1105 | checktab CARG1, ->fff_fallback
1106 | checkint CARG2, ->fff_fallback
1107 | ldr TMP1w, TAB:CARG1->asize
1108 | ldr CARG3, TAB:CARG1->array
1109 | ldr TMP0w, TAB:CARG1->hmask
1110 | add CARG2w, CARG2w, #1
1111 | cmp CARG2w, TMP1w
1112 | ldr PC, [BASE, FRAME_PC]
1113 | add TMP2, CARG2, TISNUM
1114 | mov RC, #(0+1)*8
1115 | str TMP2, [BASE, #-16]
1116 | bhs >2 // Not in array part?
1117 | ldr TMP0, [CARG3, CARG2, lsl #3]
1118 |1:
1119 | mov TMP1, #(2+1)*8
1120 | cmp TMP0, TISNIL
1121 | str TMP0, [BASE, #-8]
1122 | csel RC, RC, TMP1, eq
1123 | b ->fff_res
1124 |2: // Check for empty hash part first. Otherwise call C function.
1125 | cbz TMP0w, ->fff_res
1126 | bl extern lj_tab_getinth // (GCtab *t, int32_t key)
1127 | // Returns cTValue * or NULL.
1128 | cbz CRET1, ->fff_res
1129 | ldr TMP0, [CRET1]
1130 | b <1
1131 |
1132 |.ffunc_1 ipairs
1133 | checktp TMP1, CARG1, LJ_TTAB, ->fff_fallback
1134#if LJ_52
1135 | ldr TAB:CARG2, TAB:TMP1->metatable
1136#endif
1137 | ldr CFUNC:CARG4, CFUNC:CARG3->upvalue[0]
1138 | ldr PC, [BASE, FRAME_PC]
1139#if LJ_52
1140 | cbnz TAB:CARG2, ->fff_fallback
1141#endif
1142 | mov RC, #(3+1)*8
1143 | stp CARG1, TISNUM, [BASE, #-8]
1144 | str CFUNC:CARG4, [BASE, #-16]
1145 | b ->fff_res
1146 |
1147 |//-- Base library: catch errors ----------------------------------------
1148 |
1149 |.ffunc pcall
1150 | ldrb TMP0w, GL->hookmask
1151 | subs NARGS8:RC, NARGS8:RC, #8
1152 | blo ->fff_fallback
1153 | mov RB, BASE
1154 | add BASE, BASE, #16
1155 | ubfx TMP0w, TMP0w, #HOOK_ACTIVE_SHIFT, #1
1156 | add PC, TMP0, #16+FRAME_PCALL
1157 | beq ->vm_call_dispatch
1158 |1:
1159 | add TMP2, BASE, NARGS8:RC
1160 |2:
1161 | ldr TMP0, [TMP2, #-16]
1162 | str TMP0, [TMP2, #-8]!
1163 | cmp TMP2, BASE
1164 | bne <2
1165 | b ->vm_call_dispatch
1166 |
1167 |.ffunc xpcall
1168 | ldp CARG1, CARG2, [BASE]
1169 | ldrb TMP0w, GL->hookmask
1170 | subs NARGS8:RC, NARGS8:RC, #16
1171 | blo ->fff_fallback
1172 | mov RB, BASE
1173 | add BASE, BASE, #24
1174 | asr ITYPE, CARG2, #47
1175 | ubfx TMP0w, TMP0w, #HOOK_ACTIVE_SHIFT, #1
1176 | cmn ITYPE, #-LJ_TFUNC
1177 | add PC, TMP0, #24+FRAME_PCALL
1178 | bne ->fff_fallback // Traceback must be a function.
1179 | stp CARG2, CARG1, [RB] // Swap function and traceback.
1180 | cbz NARGS8:RC, ->vm_call_dispatch
1181 | b <1
1182 |
1183 |//-- Coroutine library --------------------------------------------------
1184 |
1185 |.macro coroutine_resume_wrap, resume
1186 |.if resume
1187 |.ffunc_1 coroutine_resume
1188 | checktp CARG1, LJ_TTHREAD, ->fff_fallback
1189 |.else
1190 |.ffunc coroutine_wrap_aux
1191 | ldr L:CARG1, CFUNC:CARG3->upvalue[0].gcr
1192 | and L:CARG1, CARG1, #LJ_GCVMASK
1193 |.endif
1194 | ldr PC, [BASE, FRAME_PC]
1195 | str BASE, L->base
1196 | ldp RB, CARG2, L:CARG1->base
1197 | ldrb TMP1w, L:CARG1->status
1198 | add TMP0, CARG2, TMP1
1199 | str PC, SAVE_PC
1200 | cmp TMP0, RB
1201 | beq ->fff_fallback
1202 | cmp TMP1, #LUA_YIELD
1203 | add TMP0, CARG2, #8
1204 | csel CARG2, CARG2, TMP0, hs
1205 | ldr CARG4, L:CARG1->maxstack
1206 | add CARG3, CARG2, NARGS8:RC
1207 | ldr RB, L:CARG1->cframe
1208 | ccmp CARG3, CARG4, #2, ls
1209 | ccmp RB, #0, #2, ls
1210 | bhi ->fff_fallback
1211 |.if resume
1212 | sub CARG3, CARG3, #8 // Keep resumed thread in stack for GC.
1213 | add BASE, BASE, #8
1214 | sub NARGS8:RC, NARGS8:RC, #8
1215 |.endif
1216 | str CARG3, L:CARG1->top
1217 | str BASE, L->top
1218 | cbz NARGS8:RC, >3
1219 |2: // Move args to coroutine.
1220 | ldr TMP0, [BASE, RB]
1221 | cmp RB, NARGS8:RC
1222 | str TMP0, [CARG2, RB]
1223 | add RB, RB, #8
1224 | bne <2
1225 |3:
1226 | mov CARG3, #0
1227 | mov L:RA, L:CARG1
1228 | mov CARG4, #0
1229 | bl ->vm_resume // (lua_State *L, TValue *base, 0, 0)
1230 | // Returns thread status.
1231 |4:
1232 | ldp CARG3, CARG4, L:RA->base
1233 | cmp CRET1, #LUA_YIELD
1234 | ldr BASE, L->base
1235 | str L, GL->cur_L
1236 | st_vmstate ST_INTERP
1237 | bhi >8
1238 | sub RC, CARG4, CARG3
1239 | ldr CARG1, L->maxstack
1240 | add CARG2, BASE, RC
1241 | cbz RC, >6 // No results?
1242 | cmp CARG2, CARG1
1243 | mov RB, #0
1244 | bhi >9 // Need to grow stack?
1245 |
1246 | sub CARG4, RC, #8
1247 | str CARG3, L:RA->top // Clear coroutine stack.
1248 |5: // Move results from coroutine.
1249 | ldr TMP0, [CARG3, RB]
1250 | cmp RB, CARG4
1251 | str TMP0, [BASE, RB]
1252 | add RB, RB, #8
1253 | bne <5
1254 |6:
1255 |.if resume
1256 | mov_true TMP1
1257 | add RC, RC, #16
1258 |7:
1259 | str TMP1, [BASE, #-8] // Prepend true/false to results.
1260 | sub RA, BASE, #8
1261 |.else
1262 | mov RA, BASE
1263 | add RC, RC, #8
1264 |.endif
1265 | ands CARG1, PC, #FRAME_TYPE
1266 | str PC, SAVE_PC
1267 | str RCw, SAVE_MULTRES
1268 | beq ->BC_RET_Z
1269 | b ->vm_return
1270 |
1271 |8: // Coroutine returned with error (at co->top-1).
1272 |.if resume
1273 | ldr TMP0, [CARG4, #-8]!
1274 | mov_false TMP1
1275 | mov RC, #(2+1)*8
1276 | str CARG4, L:RA->top // Remove error from coroutine stack.
1277 | str TMP0, [BASE] // Copy error message.
1278 | b <7
1279 |.else
1280 | mov CARG1, L
1281 | mov CARG2, L:RA
1282 | bl extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co)
1283 | // Never returns.
1284 |.endif
1285 |
1286 |9: // Handle stack expansion on return from yield.
1287 | mov CARG1, L
1288 | lsr CARG2, RC, #3
1289 | bl extern lj_state_growstack // (lua_State *L, int n)
1290 | mov CRET1, #0
1291 | b <4
1292 |.endmacro
1293 |
1294 | coroutine_resume_wrap 1 // coroutine.resume
1295 | coroutine_resume_wrap 0 // coroutine.wrap
1296 |
1297 |.ffunc coroutine_yield
1298 | ldr TMP0, L->cframe
1299 | add TMP1, BASE, NARGS8:RC
1300 | mov CRET1, #LUA_YIELD
1301 | stp BASE, TMP1, L->base
1302 | tbz TMP0, #0, ->fff_fallback
1303 | str xzr, L->cframe
1304 | strb CRET1w, L->status
1305 | b ->vm_leave_unw
1306 |
1307 |//-- Math library -------------------------------------------------------
1308 |
1309 |.macro math_round, func, round
1310 | .ffunc math_ .. func
1311 | ldr CARG1, [BASE]
1312 | cmp NARGS8:RC, #8
1313 | ldr d0, [BASE]
1314 | blo ->fff_fallback
1315 | cmp TISNUMhi, CARG1, lsr #32
1316 | beq ->fff_restv
1317 | blo ->fff_fallback
1318 | round d0, d0
1319 | b ->fff_resn
1320 |.endmacro
1321 |
1322 | math_round floor, frintm
1323 | math_round ceil, frintp
1324 |
1325 |.ffunc_1 math_abs
1326 | checknumber CARG1, ->fff_fallback
1327 | and CARG1, CARG1, #U64x(7fffffff,ffffffff)
1328 | bne ->fff_restv
1329 | eor CARG2w, CARG1w, CARG1w, asr #31
1330 | movz CARG3, #0x41e0, lsl #48 // 2^31.
1331 | subs CARG1w, CARG2w, CARG1w, asr #31
1332 | add CARG1, CARG1, TISNUM
1333 | csel CARG1, CARG1, CARG3, pl
1334 | // Fallthrough.
1335 |
1336 |->fff_restv:
1337 | // CARG1 = TValue result.
1338 | ldr PC, [BASE, FRAME_PC]
1339 | str CARG1, [BASE, #-16]
1340 |->fff_res1:
1341 | // PC = return.
1342 | mov RC, #(1+1)*8
1343 |->fff_res:
1344 | // RC = (nresults+1)*8, PC = return.
1345 | ands CARG1, PC, #FRAME_TYPE
1346 | str RCw, SAVE_MULTRES
1347 | sub RA, BASE, #16
1348 | bne ->vm_return
1349 | ldr INSw, [PC, #-4]
1350 | decode_RB RB, INS
1351 |5:
1352 | cmp RC, RB, lsl #3 // More results expected?
1353 | blo >6
1354 | decode_RA TMP1, INS
1355 | // Adjust BASE. KBASE is assumed to be set for the calling frame.
1356 | sub BASE, RA, TMP1, lsl #3
1357 | ins_next
1358 |
1359 |6: // Fill up results with nil.
1360 | add TMP1, RA, RC
1361 | add RC, RC, #8
1362 | str TISNIL, [TMP1, #-8]
1363 | b <5
1364 |
1365 |.macro math_extern, func
1366 | .ffunc_n math_ .. func
1367 | bl extern func
1368 | b ->fff_resn
1369 |.endmacro
1370 |
1371 |.macro math_extern2, func
1372 | .ffunc_nn math_ .. func
1373 | bl extern func
1374 | b ->fff_resn
1375 |.endmacro
1376 |
1377 |.ffunc_n math_sqrt
1378 | fsqrt d0, d0
1379 |->fff_resn:
1380 | ldr PC, [BASE, FRAME_PC]
1381 | str d0, [BASE, #-16]
1382 | b ->fff_res1
1383 |
1384 |.ffunc math_log
1385 | ldr CARG1, [BASE]
1386 | cmp NARGS8:RC, #8
1387 | ldr FARG1, [BASE]
1388 | bne ->fff_fallback // Need exactly 1 argument.
1389 | checknum CARG1, ->fff_fallback
1390 | bl extern log
1391 | b ->fff_resn
1392 |
1393 | math_extern log10
1394 | math_extern exp
1395 | math_extern sin
1396 | math_extern cos
1397 | math_extern tan
1398 | math_extern asin
1399 | math_extern acos
1400 | math_extern atan
1401 | math_extern sinh
1402 | math_extern cosh
1403 | math_extern tanh
1404 | math_extern2 pow
1405 | math_extern2 atan2
1406 | math_extern2 fmod
1407 |
1408 |.ffunc_2 math_ldexp
1409 | ldr FARG1, [BASE]
1410 | checknum CARG1, ->fff_fallback
1411 | checkint CARG2, ->fff_fallback
1412 | sxtw CARG1, CARG2w
1413 | bl extern ldexp // (double x, int exp)
1414 | b ->fff_resn
1415 |
1416 |.ffunc_n math_frexp
1417 | add CARG1, sp, TMPDofs
1418 | bl extern frexp
1419 | ldr CARG2w, TMPD
1420 | ldr PC, [BASE, FRAME_PC]
1421 | str d0, [BASE, #-16]
1422 | mov RC, #(2+1)*8
1423 | add CARG2, CARG2, TISNUM
1424 | str CARG2, [BASE, #-8]
1425 | b ->fff_res
1426 |
1427 |.ffunc_n math_modf
1428 | sub CARG1, BASE, #16
1429 | ldr PC, [BASE, FRAME_PC]
1430 | bl extern modf
1431 | mov RC, #(2+1)*8
1432 | str d0, [BASE, #-8]
1433 | b ->fff_res
1434 |
1435 |.macro math_minmax, name, cond, fcond
1436 | .ffunc_1 name
1437 | add RB, BASE, RC
1438 | add RA, BASE, #8
1439 | checkint CARG1, >4
1440 |1: // Handle integers.
1441 | ldr CARG2, [RA]
1442 | cmp RA, RB
1443 | bhs ->fff_restv
1444 | checkint CARG2, >3
1445 | cmp CARG1w, CARG2w
1446 | add RA, RA, #8
1447 | csel CARG1, CARG2, CARG1, cond
1448 | b <1
1449 |3: // Convert intermediate result to number and continue below.
1450 | scvtf d0, CARG1w
1451 | blo ->fff_fallback
1452 | ldr d1, [RA]
1453 | b >6
1454 |
1455 |4:
1456 | ldr d0, [BASE]
1457 | blo ->fff_fallback
1458 |5: // Handle numbers.
1459 | ldr CARG2, [RA]
1460 | ldr d1, [RA]
1461 | cmp RA, RB
1462 | bhs ->fff_resn
1463 | checknum CARG2, >7
1464 |6:
1465 | fcmp d0, d1
1466 | add RA, RA, #8
1467 | fcsel d0, d1, d0, fcond
1468 | b <5
1469 |7: // Convert integer to number and continue above.
1470 | scvtf d1, CARG2w
1471 | blo ->fff_fallback
1472 | b <6
1473 |.endmacro
1474 |
1475 | math_minmax math_min, gt, hi
1476 | math_minmax math_max, lt, lo
1477 |
1478 |//-- String library -----------------------------------------------------
1479 |
1480 |.ffunc string_byte // Only handle the 1-arg case here.
1481 | ldp PC, CARG1, [BASE, FRAME_PC]
1482 | cmp NARGS8:RC, #8
1483 | asr ITYPE, CARG1, #47
1484 | ccmn ITYPE, #-LJ_TSTR, #0, eq
1485 | and STR:CARG1, CARG1, #LJ_GCVMASK
1486 | bne ->fff_fallback
1487 | ldrb TMP0w, STR:CARG1[1] // Access is always ok (NUL at end).
1488 | ldr CARG3w, STR:CARG1->len
1489 | add TMP0, TMP0, TISNUM
1490 | str TMP0, [BASE, #-16]
1491 | mov RC, #(0+1)*8
1492 | cbz CARG3, ->fff_res
1493 | b ->fff_res1
1494 |
1495 |.ffunc string_char // Only handle the 1-arg case here.
1496 | ffgccheck
1497 | ldp PC, CARG1, [BASE, FRAME_PC]
1498 | cmp CARG1w, #255
1499 | ccmp NARGS8:RC, #8, #0, ls // Need exactly 1 argument.
1500 | bne ->fff_fallback
1501 | checkint CARG1, ->fff_fallback
1502 | mov CARG3, #1
1503 | mov CARG2, BASE // Points to stack. Little-endian.
1504 |->fff_newstr:
1505 | // CARG2 = str, CARG3 = len.
1506 | str BASE, L->base
1507 | mov CARG1, L
1508 | str PC, SAVE_PC
1509 | bl extern lj_str_new // (lua_State *L, char *str, size_t l)
1510 |->fff_resstr:
1511 | // Returns GCstr *.
1512 | ldr BASE, L->base
1513 | movn TMP1, #~LJ_TSTR
1514 | add CARG1, CARG1, TMP1, lsl #47
1515 | b ->fff_restv
1516 |
1517 |.ffunc string_sub
1518 | ffgccheck
1519 | ldr CARG1, [BASE]
1520 | ldr CARG3, [BASE, #16]
1521 | cmp NARGS8:RC, #16
1522 | movn RB, #0
1523 | beq >1
1524 | blo ->fff_fallback
1525 | checkint CARG3, ->fff_fallback
1526 | sxtw RB, CARG3w
1527 |1:
1528 | ldr CARG2, [BASE, #8]
1529 | checkstr CARG1, ->fff_fallback
1530 | ldr TMP1w, STR:CARG1->len
1531 | checkint CARG2, ->fff_fallback
1532 | sxtw CARG2, CARG2w
1533 | // CARG1 = str, TMP1 = str->len, CARG2 = start, RB = end
1534 | add TMP2, RB, TMP1
1535 | cmp RB, #0
1536 | add TMP0, CARG2, TMP1
1537 | csinc RB, RB, TMP2, ge // if (end < 0) end += len+1
1538 | cmp CARG2, #0
1539 | csinc CARG2, CARG2, TMP0, ge // if (start < 0) start += len+1
1540 | cmp RB, #0
1541 | csel RB, RB, xzr, ge // if (end < 0) end = 0
1542 | cmp CARG2, #1
1543 | csinc CARG2, CARG2, xzr, ge // if (start < 1) start = 1
1544 | cmp RB, TMP1
1545 | csel RB, RB, TMP1, le // if (end > len) end = len
1546 | add CARG1, STR:CARG1, #sizeof(GCstr)-1
1547 | subs CARG3, RB, CARG2 // len = end - start
1548 | add CARG2, CARG1, CARG2
1549 | add CARG3, CARG3, #1 // len += 1
1550 | bge ->fff_newstr
1551 | add STR:CARG1, GL, #offsetof(global_State, strempty)
1552 | movn TMP1, #~LJ_TSTR
1553 | add CARG1, CARG1, TMP1, lsl #47
1554 | b ->fff_restv
1555 |
1556 |.macro ffstring_op, name
1557 | .ffunc string_ .. name
1558 | ffgccheck
1559 | ldr CARG2, [BASE]
1560 | cmp NARGS8:RC, #8
1561 | asr ITYPE, CARG2, #47
1562 | ccmn ITYPE, #-LJ_TSTR, #0, hs
1563 | and STR:CARG2, CARG2, #LJ_GCVMASK
1564 | bne ->fff_fallback
1565 | ldr TMP0, GL->tmpbuf.b
1566 | add SBUF:CARG1, GL, #offsetof(global_State, tmpbuf)
1567 | str BASE, L->base
1568 | str PC, SAVE_PC
1569 | str L, GL->tmpbuf.L
1570 | str TMP0, GL->tmpbuf.p
1571 | bl extern lj_buf_putstr_ .. name
1572 | bl extern lj_buf_tostr
1573 | b ->fff_resstr
1574 |.endmacro
1575 |
1576 |ffstring_op reverse
1577 |ffstring_op lower
1578 |ffstring_op upper
1579 |
1580 |//-- Bit library --------------------------------------------------------
1581 |
1582 |// FP number to bit conversion for soft-float. Clobbers CARG1-CARG3
1583 |->vm_tobit_fb:
1584 | bls ->fff_fallback
1585 | add CARG2, CARG1, CARG1
1586 | mov CARG3, #1076
1587 | sub CARG3, CARG3, CARG2, lsr #53
1588 | cmp CARG3, #53
1589 | bhi >1
1590 | and CARG2, CARG2, #U64x(001fffff,ffffffff)
1591 | orr CARG2, CARG2, #U64x(00200000,00000000)
1592 | cmp CARG1, #0
1593 | lsr CARG2, CARG2, CARG3
1594 | cneg CARG1w, CARG2w, mi
1595 | br lr
1596 |1:
1597 | mov CARG1w, #0
1598 | br lr
1599 |
1600 |.macro .ffunc_bit, name
1601 | .ffunc_1 bit_..name
1602 | adr lr, >1
1603 | checkint CARG1, ->vm_tobit_fb
1604 |1:
1605 |.endmacro
1606 |
1607 |.macro .ffunc_bit_op, name, ins
1608 | .ffunc_bit name
1609 | mov RA, #8
1610 | mov TMP0w, CARG1w
1611 | adr lr, >2
1612 |1:
1613 | ldr CARG1, [BASE, RA]
1614 | cmp RA, NARGS8:RC
1615 | add RA, RA, #8
1616 | bge >9
1617 | checkint CARG1, ->vm_tobit_fb
1618 |2:
1619 | ins TMP0w, TMP0w, CARG1w
1620 | b <1
1621 |.endmacro
1622 |
1623 |.ffunc_bit_op band, and
1624 |.ffunc_bit_op bor, orr
1625 |.ffunc_bit_op bxor, eor
1626 |
1627 |.ffunc_bit tobit
1628 | mov TMP0w, CARG1w
1629 |9: // Label reused by .ffunc_bit_op users.
1630 | add CARG1, TMP0, TISNUM
1631 | b ->fff_restv
1632 |
1633 |.ffunc_bit bswap
1634 | rev TMP0w, CARG1w
1635 | add CARG1, TMP0, TISNUM
1636 | b ->fff_restv
1637 |
1638 |.ffunc_bit bnot
1639 | mvn TMP0w, CARG1w
1640 | add CARG1, TMP0, TISNUM
1641 | b ->fff_restv
1642 |
1643 |.macro .ffunc_bit_sh, name, ins, shmod
1644 | .ffunc bit_..name
1645 | ldp TMP0, CARG1, [BASE]
1646 | cmp NARGS8:RC, #16
1647 | blo ->fff_fallback
1648 | adr lr, >1
1649 | checkint CARG1, ->vm_tobit_fb
1650 |1:
1651 |.if shmod == 0
1652 | mov TMP1, CARG1
1653 |.else
1654 | neg TMP1, CARG1
1655 |.endif
1656 | mov CARG1, TMP0
1657 | adr lr, >2
1658 | checkint CARG1, ->vm_tobit_fb
1659 |2:
1660 | ins TMP0w, CARG1w, TMP1w
1661 | add CARG1, TMP0, TISNUM
1662 | b ->fff_restv
1663 |.endmacro
1664 |
1665 |.ffunc_bit_sh lshift, lsl, 0
1666 |.ffunc_bit_sh rshift, lsr, 0
1667 |.ffunc_bit_sh arshift, asr, 0
1668 |.ffunc_bit_sh rol, ror, 1
1669 |.ffunc_bit_sh ror, ror, 0
1670 |
1671 |//-----------------------------------------------------------------------
1672 |
1673 |->fff_fallback: // Call fast function fallback handler.
1674 | // BASE = new base, RC = nargs*8
1675 | ldp CFUNC:CARG3, PC, [BASE, FRAME_FUNC] // Fallback may overwrite PC.
1676 | ldr TMP2, L->maxstack
1677 | add TMP1, BASE, NARGS8:RC
1678 | stp BASE, TMP1, L->base
1679 | and CFUNC:CARG3, CARG3, #LJ_GCVMASK
1680 | add TMP1, TMP1, #8*LUA_MINSTACK
1681 | ldr CARG3, CFUNC:CARG3->f
1682 | str PC, SAVE_PC // Redundant (but a defined value).
1683 | cmp TMP1, TMP2
1684 | mov CARG1, L
1685 | bhi >5 // Need to grow stack.
1686 | blr CARG3 // (lua_State *L)
1687 | // Either throws an error, or recovers and returns -1, 0 or nresults+1.
1688 | ldr BASE, L->base
1689 | cmp CRET1w, #0
1690 | lsl RC, CRET1, #3
1691 | sub RA, BASE, #16
1692 | bgt ->fff_res // Returned nresults+1?
1693 |1: // Returned 0 or -1: retry fast path.
1694 | ldr CARG1, L->top
1695 | ldr CFUNC:CARG3, [BASE, FRAME_FUNC]
1696 | sub NARGS8:RC, CARG1, BASE
1697 | bne ->vm_call_tail // Returned -1?
1698 | and CFUNC:CARG3, CARG3, #LJ_GCVMASK
1699 | ins_callt // Returned 0: retry fast path.
1700 |
1701 |// Reconstruct previous base for vmeta_call during tailcall.
1702 |->vm_call_tail:
1703 | ands TMP0, PC, #FRAME_TYPE
1704 | and TMP1, PC, #~FRAME_TYPEP
1705 | bne >3
1706 | ldrb RAw, [PC, #-3]
1707 | lsl RA, RA, #3
1708 | add TMP1, RA, #16
1709 |3:
1710 | sub RB, BASE, TMP1
1711 | b ->vm_call_dispatch // Resolve again for tailcall.
1712 |
1713 |5: // Grow stack for fallback handler.
1714 | mov CARG2, #LUA_MINSTACK
1715 | bl extern lj_state_growstack // (lua_State *L, int n)
1716 | ldr BASE, L->base
1717 | cmp CARG1, CARG1 // Set zero-flag to force retry.
1718 | b <1
1719 |
1720 |->fff_gcstep: // Call GC step function.
1721 | // BASE = new base, RC = nargs*8
1722 | add CARG2, BASE, NARGS8:RC // Calculate L->top.
1723 | mov RA, lr
1724 | stp BASE, CARG2, L->base
1725 | str PC, SAVE_PC // Redundant (but a defined value).
1726 | mov CARG1, L
1727 | bl extern lj_gc_step // (lua_State *L)
1728 | ldp BASE, CARG2, L->base
1729 | ldr CFUNC:CARG3, [BASE, FRAME_FUNC]
1730 | mov lr, RA // Help return address predictor.
1731 | sub NARGS8:RC, CARG2, BASE // Calculate nargs*8.
1732 | and CFUNC:CARG3, CARG3, #LJ_GCVMASK
1733 | ret
1734 |
1735 |//-----------------------------------------------------------------------
1736 |//-- Special dispatch targets -------------------------------------------
1737 |//-----------------------------------------------------------------------
1738 |
1739 |->vm_record: // Dispatch target for recording phase.
1740 |.if JIT
1741 | ldrb CARG1w, GL->hookmask
1742 | tst CARG1, #HOOK_VMEVENT // No recording while in vmevent.
1743 | bne >5
1744 | // Decrement the hookcount for consistency, but always do the call.
1745 | ldr CARG2w, GL->hookcount
1746 | tst CARG1, #HOOK_ACTIVE
1747 | bne >1
1748 | sub CARG2w, CARG2w, #1
1749 | tst CARG1, #LUA_MASKLINE|LUA_MASKCOUNT
1750 | beq >1
1751 | str CARG2w, GL->hookcount
1752 | b >1
1753 |.endif
1754 |
1755 |->vm_rethook: // Dispatch target for return hooks.
1756 | ldrb TMP2w, GL->hookmask
1757 | tbz TMP2w, #HOOK_ACTIVE_SHIFT, >1 // Hook already active?
1758 |5: // Re-dispatch to static ins.
1759 | ldr TMP0, [TMP1, #GG_G2DISP+GG_DISP2STATIC]
1760 | br TMP0
1761 |
1762 |->vm_inshook: // Dispatch target for instr/line hooks.
1763 | ldrb TMP2w, GL->hookmask
1764 | ldr TMP3w, GL->hookcount
1765 | tbnz TMP2w, #HOOK_ACTIVE_SHIFT, <5 // Hook already active?
1766 | tst TMP2w, #LUA_MASKLINE|LUA_MASKCOUNT
1767 | beq <5
1768 | sub TMP3w, TMP3w, #1
1769 | str TMP3w, GL->hookcount
1770 | cbz TMP3w, >1
1771 | tbz TMP2w, #LUA_HOOKLINE, <5
1772 |1:
1773 | mov CARG1, L
1774 | str BASE, L->base
1775 | mov CARG2, PC
1776 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
1777 | bl extern lj_dispatch_ins // (lua_State *L, const BCIns *pc)
1778 |3:
1779 | ldr BASE, L->base
1780 |4: // Re-dispatch to static ins.
1781 | ldr INSw, [PC, #-4]
1782 | add TMP1, GL, INS, uxtb #3
1783 | decode_RA RA, INS
1784 | ldr TMP0, [TMP1, #GG_G2DISP+GG_DISP2STATIC]
1785 | decode_RD RC, INS
1786 | br TMP0
1787 |
1788 |->cont_hook: // Continue from hook yield.
1789 | ldr CARG1, [CARG4, #-40]
1790 | add PC, PC, #4
1791 | str CARG1w, SAVE_MULTRES // Restore MULTRES for *M ins.
1792 | b <4
1793 |
1794 |->vm_hotloop: // Hot loop counter underflow.
1795 |.if JIT
1796 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC] // Same as curr_topL(L).
1797 | add CARG1, GL, #GG_G2DISP+GG_DISP2J
1798 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
1799 | str PC, SAVE_PC
1800 | ldr CARG3, LFUNC:CARG3->pc
1801 | mov CARG2, PC
1802 | str L, [GL, #GL_J(L)]
1803 | ldrb CARG3w, [CARG3, #PC2PROTO(framesize)]
1804 | str BASE, L->base
1805 | add CARG3, BASE, CARG3, lsl #3
1806 | str CARG3, L->top
1807 | bl extern lj_trace_hot // (jit_State *J, const BCIns *pc)
1808 | b <3
1809 |.endif
1810 |
1811 |->vm_callhook: // Dispatch target for call hooks.
1812 | mov CARG2, PC
1813 |.if JIT
1814 | b >1
1815 |.endif
1816 |
1817 |->vm_hotcall: // Hot call counter underflow.
1818 |.if JIT
1819 | orr CARG2, PC, #1
1820 |1:
1821 |.endif
1822 | add TMP1, BASE, NARGS8:RC
1823 | str PC, SAVE_PC
1824 | mov CARG1, L
1825 | sub RA, RA, BASE
1826 | stp BASE, TMP1, L->base
1827 | bl extern lj_dispatch_call // (lua_State *L, const BCIns *pc)
1828 | // Returns ASMFunction.
1829 | ldp BASE, TMP1, L->base
1830 | str xzr, SAVE_PC // Invalidate for subsequent line hook.
1831 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC]
1832 | add RA, BASE, RA
1833 | sub NARGS8:RC, TMP1, BASE
1834 | ldr INSw, [PC, #-4]
1835 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
1836 | br CRET1
1837 |
1838 |->cont_stitch: // Trace stitching.
1839 |.if JIT
1840 | // RA = resultptr, CARG4 = meta base
1841 | ldr RB, SAVE_MULTRES
1842 | ldr INSw, [PC, #-4]
1843 | ldr TRACE:CARG3, [CARG4, #-40] // Save previous trace.
1844 | subs RB, RB, #8
1845 | decode_RA RC, INS // Call base.
1846 | and CARG3, CARG3, #LJ_GCVMASK
1847 | beq >2
1848 |1: // Move results down.
1849 | ldr CARG1, [RA]
1850 | add RA, RA, #8
1851 | subs RB, RB, #8
1852 | str CARG1, [BASE, RC, lsl #3]
1853 | add RC, RC, #1
1854 | bne <1
1855 |2:
1856 | decode_RA RA, INS
1857 | decode_RB RB, INS
1858 | add RA, RA, RB
1859 |3:
1860 | cmp RA, RC
1861 | bhi >9 // More results wanted?
1862 |
1863 | ldrh RAw, TRACE:CARG3->traceno
1864 | ldrh RCw, TRACE:CARG3->link
1865 | cmp RCw, RAw
1866 | beq ->cont_nop // Blacklisted.
1867 | cmp RCw, #0
1868 | bne =>BC_JLOOP // Jump to stitched trace.
1869 |
1870 | // Stitch a new trace to the previous trace.
1871 | mov CARG1, #GL_J(exitno)
1872 | str RA, [GL, CARG1]
1873 | mov CARG1, #GL_J(L)
1874 | str L, [GL, CARG1]
1875 | str BASE, L->base
1876 | add CARG1, GL, #GG_G2J
1877 | mov CARG2, PC
1878 | bl extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
1879 | ldr BASE, L->base
1880 | b ->cont_nop
1881 |
1882 |9: // Fill up results with nil.
1883 | str TISNIL, [BASE, RC, lsl #3]
1884 | add RC, RC, #1
1885 | b <3
1886 |.endif
1887 |
1888 |->vm_profhook: // Dispatch target for profiler hook.
1889#if LJ_HASPROFILE
1890 | mov CARG1, L
1891 | str BASE, L->base
1892 | mov CARG2, PC
1893 | bl extern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
1894 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
1895 | ldr BASE, L->base
1896 | sub PC, PC, #4
1897 | b ->cont_nop
1898#endif
1899 |
1900 |//-----------------------------------------------------------------------
1901 |//-- Trace exit handler -------------------------------------------------
1902 |//-----------------------------------------------------------------------
1903 |
1904 |.macro savex_, a, b
1905 | stp d..a, d..b, [sp, #a*8]
1906 | stp x..a, x..b, [sp, #32*8+a*8]
1907 |.endmacro
1908 |
1909 |->vm_exit_handler:
1910 |.if JIT
1911 | sub sp, sp, #(64*8)
1912 | savex_, 0, 1
1913 | savex_, 2, 3
1914 | savex_, 4, 5
1915 | savex_, 6, 7
1916 | savex_, 8, 9
1917 | savex_, 10, 11
1918 | savex_, 12, 13
1919 | savex_, 14, 15
1920 | savex_, 16, 17
1921 | savex_, 18, 19
1922 | savex_, 20, 21
1923 | savex_, 22, 23
1924 | savex_, 24, 25
1925 | savex_, 26, 27
1926 | savex_, 28, 29
1927 | stp d30, d31, [sp, #30*8]
1928 | ldr CARG1, [sp, #64*8] // Load original value of lr.
1929 | add CARG3, sp, #64*8 // Recompute original value of sp.
1930 | mv_vmstate CARG4, EXIT
1931 | stp xzr, CARG3, [sp, #62*8] // Store 0/sp in RID_LR/RID_SP.
1932 | sub CARG1, CARG1, lr
1933 | ldr L, GL->cur_L
1934 | lsr CARG1, CARG1, #2
1935 | ldr BASE, GL->jit_base
1936 | sub CARG1, CARG1, #2
1937 | ldr CARG2w, [lr] // Load trace number.
1938 | st_vmstate CARG4
1939 | str BASE, L->base
1940 | ubfx CARG2w, CARG2w, #5, #16
1941 | str CARG1w, [GL, #GL_J(exitno)]
1942 | str CARG2w, [GL, #GL_J(parent)]
1943 | str L, [GL, #GL_J(L)]
1944 | str xzr, GL->jit_base
1945 | add CARG1, GL, #GG_G2J
1946 | mov CARG2, sp
1947 | bl extern lj_trace_exit // (jit_State *J, ExitState *ex)
1948 | // Returns MULTRES (unscaled) or negated error code.
1949 | ldr CARG2, L->cframe
1950 | ldr BASE, L->base
1951 | and sp, CARG2, #CFRAME_RAWMASK
1952 | ldr PC, SAVE_PC // Get SAVE_PC.
1953 | str L, SAVE_L // Set SAVE_L (on-trace resume/yield).
1954 | b >1
1955 |.endif
1956 |
1957 |->vm_exit_interp:
1958 | // CARG1 = MULTRES or negated error code, BASE, PC and GL set.
1959 |.if JIT
1960 | ldr L, SAVE_L
1961 |1:
1962 | cmp CARG1w, #0
1963 | blt >9 // Check for error from exit.
1964 | lsl RC, CARG1, #3
1965 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
1966 | movz TISNUM, #(LJ_TISNUM>>1)&0xffff, lsl #48
1967 | movz TISNUMhi, #(LJ_TISNUM>>1)&0xffff, lsl #16
1968 | movn TISNIL, #0
1969 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
1970 | str RC, SAVE_MULTRES
1971 | str BASE, L->base
1972 | ldr CARG2, LFUNC:CARG2->pc
1973 | str xzr, GL->jit_base
1974 | mv_vmstate CARG4, INTERP
1975 | ldr KBASE, [CARG2, #PC2PROTO(k)]
1976 | // Modified copy of ins_next which handles function header dispatch, too.
1977 | ldrb RBw, [PC]
1978 | ldr INSw, [PC], #4
1979 | st_vmstate CARG4
1980 | cmp RBw, #BC_FUNCC+2 // Fast function?
1981 | add TMP1, GL, INS, uxtb #3
1982 | bhs >4
1983 |2:
1984 | cmp RBw, #BC_FUNCF // Function header?
1985 | add TMP0, GL, RB, uxtb #3
1986 | ldr RB, [TMP0, #GG_G2DISP]
1987 | decode_RA RA, INS
1988 | lsr TMP0, INS, #16
1989 | csel RC, TMP0, RC, lo
1990 | blo >5
1991 | ldr CARG3, [BASE, FRAME_FUNC]
1992 | sub RC, RC, #8
1993 | add RA, BASE, RA, lsl #3 // Yes: RA = BASE+framesize*8, RC = nargs*8
1994 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
1995 |5:
1996 | br RB
1997 |
1998 |4: // Check frame below fast function.
1999 | ldr CARG1, [BASE, FRAME_PC]
2000 | ands CARG2, CARG1, #FRAME_TYPE
2001 | bne <2 // Trace stitching continuation?
2002 | // Otherwise set KBASE for Lua function below fast function.
2003 | ldr CARG3, [CARG1, #-4]
2004 | decode_RA CARG1, CARG3
2005 | sub CARG2, BASE, CARG1, lsl #3
2006 | ldr LFUNC:CARG3, [CARG2, #-32]
2007 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
2008 | ldr CARG3, LFUNC:CARG3->pc
2009 | ldr KBASE, [CARG3, #PC2PROTO(k)]
2010 | b <2
2011 |
2012 |9: // Rethrow error from the right C frame.
2013 | neg CARG2, CARG1
2014 | mov CARG1, L
2015 | bl extern lj_err_throw // (lua_State *L, int errcode)
2016 |.endif
2017 |
2018 |//-----------------------------------------------------------------------
2019 |//-- Math helper functions ----------------------------------------------
2020 |//-----------------------------------------------------------------------
2021 |
2022 | // int lj_vm_modi(int dividend, int divisor);
2023 |->vm_modi:
2024 | eor CARG4w, CARG1w, CARG2w
2025 | cmp CARG4w, #0
2026 | eor CARG3w, CARG1w, CARG1w, asr #31
2027 | eor CARG4w, CARG2w, CARG2w, asr #31
2028 | sub CARG3w, CARG3w, CARG1w, asr #31
2029 | sub CARG4w, CARG4w, CARG2w, asr #31
2030 | udiv CARG1w, CARG3w, CARG4w
2031 | msub CARG1w, CARG1w, CARG4w, CARG3w
2032 | ccmp CARG1w, #0, #4, mi
2033 | sub CARG3w, CARG1w, CARG4w
2034 | csel CARG1w, CARG1w, CARG3w, eq
2035 | eor CARG3w, CARG1w, CARG2w
2036 | cmp CARG3w, #0
2037 | cneg CARG1w, CARG1w, mi
2038 | ret
2039 |
2040 |//-----------------------------------------------------------------------
2041 |//-- Miscellaneous functions --------------------------------------------
2042 |//-----------------------------------------------------------------------
2043 |
2044 |//-----------------------------------------------------------------------
2045 |//-- FFI helper functions -----------------------------------------------
2046 |//-----------------------------------------------------------------------
2047 |
2048 |// Handler for callback functions.
2049 |// Saveregs already performed. Callback slot number in [sp], g in r12.
2050 |->vm_ffi_callback:
2051 |.if FFI
2052 |.type CTSTATE, CTState, PC
2053 | saveregs
2054 | ldr CTSTATE, GL:x10->ctype_state
2055 | mov GL, x10
2056 | add x10, sp, # CFRAME_SPACE
2057 | str w9, CTSTATE->cb.slot
2058 | stp x0, x1, CTSTATE->cb.gpr[0]
2059 | stp d0, d1, CTSTATE->cb.fpr[0]
2060 | stp x2, x3, CTSTATE->cb.gpr[2]
2061 | stp d2, d3, CTSTATE->cb.fpr[2]
2062 | stp x4, x5, CTSTATE->cb.gpr[4]
2063 | stp d4, d5, CTSTATE->cb.fpr[4]
2064 | stp x6, x7, CTSTATE->cb.gpr[6]
2065 | stp d6, d7, CTSTATE->cb.fpr[6]
2066 | str x10, CTSTATE->cb.stack
2067 | mov CARG1, CTSTATE
2068 | str CTSTATE, SAVE_PC // Any value outside of bytecode is ok.
2069 | mov CARG2, sp
2070 | bl extern lj_ccallback_enter // (CTState *cts, void *cf)
2071 | // Returns lua_State *.
2072 | ldp BASE, RC, L:CRET1->base
2073 | movz TISNUM, #(LJ_TISNUM>>1)&0xffff, lsl #48
2074 | movz TISNUMhi, #(LJ_TISNUM>>1)&0xffff, lsl #16
2075 | movn TISNIL, #0
2076 | mov L, CRET1
2077 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC]
2078 | sub RC, RC, BASE
2079 | st_vmstate ST_INTERP
2080 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
2081 | ins_callt
2082 |.endif
2083 |
2084 |->cont_ffi_callback: // Return from FFI callback.
2085 |.if FFI
2086 | ldr CTSTATE, GL->ctype_state
2087 | stp BASE, CARG4, L->base
2088 | str L, CTSTATE->L
2089 | mov CARG1, CTSTATE
2090 | mov CARG2, RA
2091 | bl extern lj_ccallback_leave // (CTState *cts, TValue *o)
2092 | ldp x0, x1, CTSTATE->cb.gpr[0]
2093 | ldp d0, d1, CTSTATE->cb.fpr[0]
2094 | b ->vm_leave_unw
2095 |.endif
2096 |
2097 |->vm_ffi_call: // Call C function via FFI.
2098 | // Caveat: needs special frame unwinding, see below.
2099 |.if FFI
2100 | .type CCSTATE, CCallState, x19
2101 | stp fp, lr, [sp, #-32]!
2102 | add fp, sp, #0
2103 | str CCSTATE, [sp, #16]
2104 | mov CCSTATE, x0
2105 | ldr TMP0w, CCSTATE:x0->spadj
2106 | ldrb TMP1w, CCSTATE->nsp
2107 | add TMP2, CCSTATE, #offsetof(CCallState, stack)
2108 | subs TMP1, TMP1, #1
2109 | ldr TMP3, CCSTATE->func
2110 | sub sp, fp, TMP0
2111 | bmi >2
2112 |1: // Copy stack slots
2113 | ldr TMP0, [TMP2, TMP1, lsl #3]
2114 | str TMP0, [sp, TMP1, lsl #3]
2115 | subs TMP1, TMP1, #1
2116 | bpl <1
2117 |2:
2118 | ldp x0, x1, CCSTATE->gpr[0]
2119 | ldp d0, d1, CCSTATE->fpr[0]
2120 | ldp x2, x3, CCSTATE->gpr[2]
2121 | ldp d2, d3, CCSTATE->fpr[2]
2122 | ldp x4, x5, CCSTATE->gpr[4]
2123 | ldp d4, d5, CCSTATE->fpr[4]
2124 | ldp x6, x7, CCSTATE->gpr[6]
2125 | ldp d6, d7, CCSTATE->fpr[6]
2126 | ldr x8, CCSTATE->retp
2127 | blr TMP3
2128 | mov sp, fp
2129 | stp x0, x1, CCSTATE->gpr[0]
2130 | stp d0, d1, CCSTATE->fpr[0]
2131 | stp d2, d3, CCSTATE->fpr[2]
2132 | ldr CCSTATE, [sp, #16]
2133 | ldp fp, lr, [sp], #32
2134 | ret
2135 |.endif
2136 |// Note: vm_ffi_call must be the last function in this object file!
2137 |
2138 |//-----------------------------------------------------------------------
2139}
2140
2141/* Generate the code for a single instruction. */
2142static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2143{
2144 int vk = 0;
2145 |=>defop:
2146
2147 switch (op) {
2148
2149 /* -- Comparison ops ---------------------------------------------------- */
2150
2151 /* Remember: all ops branch for a true comparison, fall through otherwise. */
2152
2153 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
2154 | // RA = src1, RC = src2, JMP with RC = target
2155 | ldr CARG1, [BASE, RA, lsl #3]
2156 | ldrh RBw, [PC, #2]
2157 | ldr CARG2, [BASE, RC, lsl #3]
2158 | add PC, PC, #4
2159 | add RB, PC, RB, lsl #2
2160 | sub RB, RB, #0x20000
2161 | checkint CARG1, >3
2162 | checkint CARG2, >4
2163 | cmp CARG1w, CARG2w
2164 if (op == BC_ISLT) {
2165 | csel PC, RB, PC, lt
2166 } else if (op == BC_ISGE) {
2167 | csel PC, RB, PC, ge
2168 } else if (op == BC_ISLE) {
2169 | csel PC, RB, PC, le
2170 } else {
2171 | csel PC, RB, PC, gt
2172 }
2173 |1:
2174 | ins_next
2175 |
2176 |3: // RA not int.
2177 | ldr FARG1, [BASE, RA, lsl #3]
2178 | blo ->vmeta_comp
2179 | ldr FARG2, [BASE, RC, lsl #3]
2180 | cmp TISNUMhi, CARG2, lsr #32
2181 | bhi >5
2182 | bne ->vmeta_comp
2183 | // RA number, RC int.
2184 | scvtf FARG2, CARG2w
2185 | b >5
2186 |
2187 |4: // RA int, RC not int
2188 | ldr FARG2, [BASE, RC, lsl #3]
2189 | blo ->vmeta_comp
2190 | // RA int, RC number.
2191 | scvtf FARG1, CARG1w
2192 |
2193 |5: // RA number, RC number
2194 | fcmp FARG1, FARG2
2195 | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't.
2196 if (op == BC_ISLT) {
2197 | csel PC, RB, PC, lo
2198 } else if (op == BC_ISGE) {
2199 | csel PC, RB, PC, hs
2200 } else if (op == BC_ISLE) {
2201 | csel PC, RB, PC, ls
2202 } else {
2203 | csel PC, RB, PC, hi
2204 }
2205 | b <1
2206 break;
2207
2208 case BC_ISEQV: case BC_ISNEV:
2209 vk = op == BC_ISEQV;
2210 | // RA = src1, RC = src2, JMP with RC = target
2211 | ldr CARG1, [BASE, RA, lsl #3]
2212 | add RC, BASE, RC, lsl #3
2213 | ldrh RBw, [PC, #2]
2214 | ldr CARG3, [RC]
2215 | add PC, PC, #4
2216 | add RB, PC, RB, lsl #2
2217 | sub RB, RB, #0x20000
2218 | asr ITYPE, CARG3, #47
2219 | cmn ITYPE, #-LJ_TISNUM
2220 if (vk) {
2221 | bls ->BC_ISEQN_Z
2222 } else {
2223 | bls ->BC_ISNEN_Z
2224 }
2225 | // RC is not a number.
2226 | asr TMP0, CARG1, #47
2227 |.if FFI
2228 | // Check if RC or RA is a cdata.
2229 | cmn ITYPE, #-LJ_TCDATA
2230 | ccmn TMP0, #-LJ_TCDATA, #4, ne
2231 | beq ->vmeta_equal_cd
2232 |.endif
2233 | cmp CARG1, CARG3
2234 | bne >2
2235 | // Tag and value are equal.
2236 if (vk) {
2237 |->BC_ISEQV_Z:
2238 | mov PC, RB // Perform branch.
2239 }
2240 |1:
2241 | ins_next
2242 |
2243 |2: // Check if the tags are the same and it's a table or userdata.
2244 | cmp ITYPE, TMP0
2245 | ccmn ITYPE, #-LJ_TISTABUD, #2, eq
2246 if (vk) {
2247 | bhi <1
2248 } else {
2249 | bhi ->BC_ISEQV_Z // Reuse code from opposite instruction.
2250 }
2251 | // Different tables or userdatas. Need to check __eq metamethod.
2252 | // Field metatable must be at same offset for GCtab and GCudata!
2253 | and TAB:CARG2, CARG1, #LJ_GCVMASK
2254 | ldr TAB:TMP2, TAB:CARG2->metatable
2255 if (vk) {
2256 | cbz TAB:TMP2, <1 // No metatable?
2257 | ldrb TMP1w, TAB:TMP2->nomm
2258 | mov CARG4, #0 // ne = 0
2259 | tbnz TMP1w, #MM_eq, <1 // 'no __eq' flag set: done.
2260 } else {
2261 | cbz TAB:TMP2, ->BC_ISEQV_Z // No metatable?
2262 | ldrb TMP1w, TAB:TMP2->nomm
2263 | mov CARG4, #1 // ne = 1.
2264 | tbnz TMP1w, #MM_eq, ->BC_ISEQV_Z // 'no __eq' flag set: done.
2265 }
2266 | b ->vmeta_equal
2267 break;
2268
2269 case BC_ISEQS: case BC_ISNES:
2270 vk = op == BC_ISEQS;
2271 | // RA = src, RC = str_const (~), JMP with RC = target
2272 | ldr CARG1, [BASE, RA, lsl #3]
2273 | mvn RC, RC
2274 | ldrh RBw, [PC, #2]
2275 | ldr CARG2, [KBASE, RC, lsl #3]
2276 | add PC, PC, #4
2277 | movn TMP0, #~LJ_TSTR
2278 |.if FFI
2279 | asr ITYPE, CARG1, #47
2280 |.endif
2281 | add RB, PC, RB, lsl #2
2282 | add CARG2, CARG2, TMP0, lsl #47
2283 | sub RB, RB, #0x20000
2284 |.if FFI
2285 | cmn ITYPE, #-LJ_TCDATA
2286 | beq ->vmeta_equal_cd
2287 |.endif
2288 | cmp CARG1, CARG2
2289 if (vk) {
2290 | csel PC, RB, PC, eq
2291 } else {
2292 | csel PC, RB, PC, ne
2293 }
2294 | ins_next
2295 break;
2296
2297 case BC_ISEQN: case BC_ISNEN:
2298 vk = op == BC_ISEQN;
2299 | // RA = src, RC = num_const (~), JMP with RC = target
2300 | ldr CARG1, [BASE, RA, lsl #3]
2301 | add RC, KBASE, RC, lsl #3
2302 | ldrh RBw, [PC, #2]
2303 | ldr CARG3, [RC]
2304 | add PC, PC, #4
2305 | add RB, PC, RB, lsl #2
2306 | sub RB, RB, #0x20000
2307 if (vk) {
2308 |->BC_ISEQN_Z:
2309 } else {
2310 |->BC_ISNEN_Z:
2311 }
2312 | checkint CARG1, >4
2313 | checkint CARG3, >6
2314 | cmp CARG1w, CARG3w
2315 |1:
2316 if (vk) {
2317 | csel PC, RB, PC, eq
2318 |2:
2319 } else {
2320 |2:
2321 | csel PC, RB, PC, ne
2322 }
2323 |3:
2324 | ins_next
2325 |
2326 |4: // RA not int.
2327 |.if FFI
2328 | blo >7
2329 |.else
2330 | blo <2
2331 |.endif
2332 | ldr FARG1, [BASE, RA, lsl #3]
2333 | ldr FARG2, [RC]
2334 | cmp TISNUMhi, CARG3, lsr #32
2335 | bne >5
2336 | // RA number, RC int.
2337 | scvtf FARG2, CARG3w
2338 |5:
2339 | // RA number, RC number.
2340 | fcmp FARG1, FARG2
2341 | b <1
2342 |
2343 |6: // RA int, RC number
2344 | ldr FARG2, [RC]
2345 | scvtf FARG1, CARG1w
2346 | fcmp FARG1, FARG2
2347 | b <1
2348 |
2349 |.if FFI
2350 |7:
2351 | asr ITYPE, CARG1, #47
2352 | cmn ITYPE, #-LJ_TCDATA
2353 | bne <2
2354 | b ->vmeta_equal_cd
2355 |.endif
2356 break;
2357
2358 case BC_ISEQP: case BC_ISNEP:
2359 vk = op == BC_ISEQP;
2360 | // RA = src, RC = primitive_type (~), JMP with RC = target
2361 | ldr TMP0, [BASE, RA, lsl #3]
2362 | ldrh RBw, [PC, #2]
2363 | add PC, PC, #4
2364 | add RC, RC, #1
2365 | add RB, PC, RB, lsl #2
2366 |.if FFI
2367 | asr ITYPE, TMP0, #47
2368 | cmn ITYPE, #-LJ_TCDATA
2369 | beq ->vmeta_equal_cd
2370 | cmn RC, ITYPE
2371 |.else
2372 | cmn RC, TMP0, asr #47
2373 |.endif
2374 | sub RB, RB, #0x20000
2375 if (vk) {
2376 | csel PC, RB, PC, eq
2377 } else {
2378 | csel PC, RB, PC, ne
2379 }
2380 | ins_next
2381 break;
2382
2383 /* -- Unary test and copy ops ------------------------------------------- */
2384
2385 case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
2386 | // RA = dst or unused, RC = src, JMP with RC = target
2387 | ldrh RBw, [PC, #2]
2388 | ldr TMP0, [BASE, RC, lsl #3]
2389 | add PC, PC, #4
2390 | mov_false TMP1
2391 | add RB, PC, RB, lsl #2
2392 | cmp TMP0, TMP1
2393 | sub RB, RB, #0x20000
2394 if (op == BC_ISTC || op == BC_IST) {
2395 if (op == BC_ISTC) {
2396 | csel RA, RA, RC, lo
2397 }
2398 | csel PC, RB, PC, lo
2399 } else {
2400 if (op == BC_ISFC) {
2401 | csel RA, RA, RC, hs
2402 }
2403 | csel PC, RB, PC, hs
2404 }
2405 if (op == BC_ISTC || op == BC_ISFC) {
2406 | str TMP0, [BASE, RA, lsl #3]
2407 }
2408 | ins_next
2409 break;
2410
2411 case BC_ISTYPE:
2412 | // RA = src, RC = -type
2413 | ldr TMP0, [BASE, RA, lsl #3]
2414 | cmn RC, TMP0, asr #47
2415 | bne ->vmeta_istype
2416 | ins_next
2417 break;
2418 case BC_ISNUM:
2419 | // RA = src, RC = -(TISNUM-1)
2420 | ldr TMP0, [BASE, RA]
2421 | checknum TMP0, ->vmeta_istype
2422 | ins_next
2423 break;
2424
2425 /* -- Unary ops --------------------------------------------------------- */
2426
2427 case BC_MOV:
2428 | // RA = dst, RC = src
2429 | ldr TMP0, [BASE, RC, lsl #3]
2430 | str TMP0, [BASE, RA, lsl #3]
2431 | ins_next
2432 break;
2433 case BC_NOT:
2434 | // RA = dst, RC = src
2435 | ldr TMP0, [BASE, RC, lsl #3]
2436 | mov_false TMP1
2437 | mov_true TMP2
2438 | cmp TMP0, TMP1
2439 | csel TMP0, TMP1, TMP2, lo
2440 | str TMP0, [BASE, RA, lsl #3]
2441 | ins_next
2442 break;
2443 case BC_UNM:
2444 | // RA = dst, RC = src
2445 | ldr TMP0, [BASE, RC, lsl #3]
2446 | asr ITYPE, TMP0, #47
2447 | cmn ITYPE, #-LJ_TISNUM
2448 | bhi ->vmeta_unm
2449 | eor TMP0, TMP0, #U64x(80000000,00000000)
2450 | bne >5
2451 | negs TMP0w, TMP0w
2452 | movz CARG3, #0x41e0, lsl #48 // 2^31.
2453 | add TMP0, TMP0, TISNUM
2454 | csel TMP0, TMP0, CARG3, vc
2455 |5:
2456 | str TMP0, [BASE, RA, lsl #3]
2457 | ins_next
2458 break;
2459 case BC_LEN:
2460 | // RA = dst, RC = src
2461 | ldr CARG1, [BASE, RC, lsl #3]
2462 | asr ITYPE, CARG1, #47
2463 | cmn ITYPE, #-LJ_TSTR
2464 | and CARG1, CARG1, #LJ_GCVMASK
2465 | bne >2
2466 | ldr CARG1w, STR:CARG1->len
2467 |1:
2468 | add CARG1, CARG1, TISNUM
2469 | str CARG1, [BASE, RA, lsl #3]
2470 | ins_next
2471 |
2472 |2:
2473 | cmn ITYPE, #-LJ_TTAB
2474 | bne ->vmeta_len
2475#if LJ_52
2476 | ldr TAB:CARG2, TAB:CARG1->metatable
2477 | cbnz TAB:CARG2, >9
2478 |3:
2479#endif
2480 |->BC_LEN_Z:
2481 | bl extern lj_tab_len // (GCtab *t)
2482 | // Returns uint32_t (but less than 2^31).
2483 | b <1
2484 |
2485#if LJ_52
2486 |9:
2487 | ldrb TMP1w, TAB:CARG2->nomm
2488 | tbnz TMP1w, #MM_len, <3 // 'no __len' flag set: done.
2489 | b ->vmeta_len
2490#endif
2491 break;
2492
2493 /* -- Binary ops -------------------------------------------------------- */
2494
2495 |.macro ins_arithcheck_int, target
2496 | checkint CARG1, target
2497 | checkint CARG2, target
2498 |.endmacro
2499 |
2500 |.macro ins_arithcheck_num, target
2501 | checknum CARG1, target
2502 | checknum CARG2, target
2503 |.endmacro
2504 |
2505 |.macro ins_arithcheck_nzdiv, target
2506 | cbz CARG2w, target
2507 |.endmacro
2508 |
2509 |.macro ins_arithhead
2510 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
2511 ||if (vk == 1) {
2512 | and RC, RC, #255
2513 | decode_RB RB, INS
2514 ||} else {
2515 | decode_RB RB, INS
2516 | and RC, RC, #255
2517 ||}
2518 |.endmacro
2519 |
2520 |.macro ins_arithload, reg1, reg2
2521 | // RA = dst, RB = src1, RC = src2 | num_const
2522 ||switch (vk) {
2523 ||case 0:
2524 | ldr reg1, [BASE, RB, lsl #3]
2525 | ldr reg2, [KBASE, RC, lsl #3]
2526 || break;
2527 ||case 1:
2528 | ldr reg1, [KBASE, RC, lsl #3]
2529 | ldr reg2, [BASE, RB, lsl #3]
2530 || break;
2531 ||default:
2532 | ldr reg1, [BASE, RB, lsl #3]
2533 | ldr reg2, [BASE, RC, lsl #3]
2534 || break;
2535 ||}
2536 |.endmacro
2537 |
2538 |.macro ins_arithfallback, ins
2539 ||switch (vk) {
2540 ||case 0:
2541 | ins ->vmeta_arith_vn
2542 || break;
2543 ||case 1:
2544 | ins ->vmeta_arith_nv
2545 || break;
2546 ||default:
2547 | ins ->vmeta_arith_vv
2548 || break;
2549 ||}
2550 |.endmacro
2551 |
2552 |.macro ins_arithmod, res, reg1, reg2
2553 | fdiv d2, reg1, reg2
2554 | frintm d2, d2
2555 | fmsub res, d2, reg2, reg1
2556 |.endmacro
2557 |
2558 |.macro ins_arithdn, intins, fpins
2559 | ins_arithhead
2560 | ins_arithload CARG1, CARG2
2561 | ins_arithcheck_int >5
2562 |.if "intins" == "smull"
2563 | smull CARG1, CARG1w, CARG2w
2564 | cmp CARG1, CARG1, sxtw
2565 | mov CARG1w, CARG1w
2566 | ins_arithfallback bne
2567 |.elif "intins" == "ins_arithmodi"
2568 | ins_arithfallback ins_arithcheck_nzdiv
2569 | bl ->vm_modi
2570 |.else
2571 | intins CARG1w, CARG1w, CARG2w
2572 | ins_arithfallback bvs
2573 |.endif
2574 | add CARG1, CARG1, TISNUM
2575 | str CARG1, [BASE, RA, lsl #3]
2576 |4:
2577 | ins_next
2578 |
2579 |5: // FP variant.
2580 | ins_arithload FARG1, FARG2
2581 | ins_arithfallback ins_arithcheck_num
2582 | fpins FARG1, FARG1, FARG2
2583 | str FARG1, [BASE, RA, lsl #3]
2584 | b <4
2585 |.endmacro
2586 |
2587 |.macro ins_arithfp, fpins
2588 | ins_arithhead
2589 | ins_arithload CARG1, CARG2
2590 | ins_arithload FARG1, FARG2
2591 | ins_arithfallback ins_arithcheck_num
2592 |.if "fpins" == "fpow"
2593 | bl extern pow
2594 |.else
2595 | fpins FARG1, FARG1, FARG2
2596 |.endif
2597 | str FARG1, [BASE, RA, lsl #3]
2598 | ins_next
2599 |.endmacro
2600
2601 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
2602 | ins_arithdn adds, fadd
2603 break;
2604 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
2605 | ins_arithdn subs, fsub
2606 break;
2607 case BC_MULVN: case BC_MULNV: case BC_MULVV:
2608 | ins_arithdn smull, fmul
2609 break;
2610 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
2611 | ins_arithfp fdiv
2612 break;
2613 case BC_MODVN: case BC_MODNV: case BC_MODVV:
2614 | ins_arithdn ins_arithmodi, ins_arithmod
2615 break;
2616 case BC_POW:
2617 | // NYI: (partial) integer arithmetic.
2618 | ins_arithfp fpow
2619 break;
2620
2621 case BC_CAT:
2622 | decode_RB RB, INS
2623 | and RC, RC, #255
2624 | // RA = dst, RB = src_start, RC = src_end
2625 | str BASE, L->base
2626 | sub CARG3, RC, RB
2627 | add CARG2, BASE, RC, lsl #3
2628 |->BC_CAT_Z:
2629 | // RA = dst, CARG2 = top-1, CARG3 = left
2630 | mov CARG1, L
2631 | str PC, SAVE_PC
2632 | bl extern lj_meta_cat // (lua_State *L, TValue *top, int left)
2633 | // Returns NULL (finished) or TValue * (metamethod).
2634 | ldrb RBw, [PC, #-1]
2635 | ldr BASE, L->base
2636 | cbnz CRET1, ->vmeta_binop
2637 | ldr TMP0, [BASE, RB, lsl #3]
2638 | str TMP0, [BASE, RA, lsl #3] // Copy result to RA.
2639 | ins_next
2640 break;
2641
2642 /* -- Constant ops ------------------------------------------------------ */
2643
2644 case BC_KSTR:
2645 | // RA = dst, RC = str_const (~)
2646 | mvn RC, RC
2647 | ldr TMP0, [KBASE, RC, lsl #3]
2648 | movn TMP1, #~LJ_TSTR
2649 | add TMP0, TMP0, TMP1, lsl #47
2650 | str TMP0, [BASE, RA, lsl #3]
2651 | ins_next
2652 break;
2653 case BC_KCDATA:
2654 |.if FFI
2655 | // RA = dst, RC = cdata_const (~)
2656 | mvn RC, RC
2657 | ldr TMP0, [KBASE, RC, lsl #3]
2658 | movn TMP1, #~LJ_TCDATA
2659 | add TMP0, TMP0, TMP1, lsl #47
2660 | str TMP0, [BASE, RA, lsl #3]
2661 | ins_next
2662 |.endif
2663 break;
2664 case BC_KSHORT:
2665 | // RA = dst, RC = int16_literal
2666 | sxth RCw, RCw
2667 | add TMP0, RC, TISNUM
2668 | str TMP0, [BASE, RA, lsl #3]
2669 | ins_next
2670 break;
2671 case BC_KNUM:
2672 | // RA = dst, RC = num_const
2673 | ldr TMP0, [KBASE, RC, lsl #3]
2674 | str TMP0, [BASE, RA, lsl #3]
2675 | ins_next
2676 break;
2677 case BC_KPRI:
2678 | // RA = dst, RC = primitive_type (~)
2679 | mvn TMP0, RC, lsl #47
2680 | str TMP0, [BASE, RA, lsl #3]
2681 | ins_next
2682 break;
2683 case BC_KNIL:
2684 | // RA = base, RC = end
2685 | add RA, BASE, RA, lsl #3
2686 | add RC, BASE, RC, lsl #3
2687 | str TISNIL, [RA], #8
2688 |1:
2689 | cmp RA, RC
2690 | str TISNIL, [RA], #8
2691 | blt <1
2692 | ins_next_
2693 break;
2694
2695 /* -- Upvalue and function ops ------------------------------------------ */
2696
2697 case BC_UGET:
2698 | // RA = dst, RC = uvnum
2699 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2700 | add RC, RC, #offsetof(GCfuncL, uvptr)/8
2701 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
2702 | ldr UPVAL:CARG2, [LFUNC:CARG2, RC, lsl #3]
2703 | ldr CARG2, UPVAL:CARG2->v
2704 | ldr TMP0, [CARG2]
2705 | str TMP0, [BASE, RA, lsl #3]
2706 | ins_next
2707 break;
2708 case BC_USETV:
2709 | // RA = uvnum, RC = src
2710 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2711 | add RA, RA, #offsetof(GCfuncL, uvptr)/8
2712 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
2713 | ldr UPVAL:CARG1, [LFUNC:CARG2, RA, lsl #3]
2714 | ldr CARG3, [BASE, RC, lsl #3]
2715 | ldr CARG2, UPVAL:CARG1->v
2716 | ldrb TMP2w, UPVAL:CARG1->marked
2717 | ldrb TMP0w, UPVAL:CARG1->closed
2718 | asr ITYPE, CARG3, #47
2719 | str CARG3, [CARG2]
2720 | add ITYPE, ITYPE, #-LJ_TISGCV
2721 | tst TMP2w, #LJ_GC_BLACK // isblack(uv)
2722 | ccmp TMP0w, #0, #4, ne // && uv->closed
2723 | ccmn ITYPE, #-(LJ_TNUMX - LJ_TISGCV), #0, ne // && tvisgcv(v)
2724 | bhi >2
2725 |1:
2726 | ins_next
2727 |
2728 |2: // Check if new value is white.
2729 | and GCOBJ:CARG3, CARG3, #LJ_GCVMASK
2730 | ldrb TMP1w, GCOBJ:CARG3->gch.marked
2731 | tst TMP1w, #LJ_GC_WHITES // iswhite(str)
2732 | beq <1
2733 | // Crossed a write barrier. Move the barrier forward.
2734 | mov CARG1, GL
2735 | bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
2736 | b <1
2737 break;
2738 case BC_USETS:
2739 | // RA = uvnum, RC = str_const (~)
2740 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2741 | add RA, RA, #offsetof(GCfuncL, uvptr)/8
2742 | mvn RC, RC
2743 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
2744 | ldr UPVAL:CARG1, [LFUNC:CARG2, RA, lsl #3]
2745 | ldr STR:CARG3, [KBASE, RC, lsl #3]
2746 | movn TMP0, #~LJ_TSTR
2747 | ldr CARG2, UPVAL:CARG1->v
2748 | ldrb TMP2w, UPVAL:CARG1->marked
2749 | add TMP0, STR:CARG3, TMP0, lsl #47
2750 | ldrb TMP1w, STR:CARG3->marked
2751 | str TMP0, [CARG2]
2752 | tbnz TMP2w, #2, >2 // isblack(uv)
2753 |1:
2754 | ins_next
2755 |
2756 |2: // Check if string is white and ensure upvalue is closed.
2757 | ldrb TMP0w, UPVAL:CARG1->closed
2758 | tst TMP1w, #LJ_GC_WHITES // iswhite(str)
2759 | ccmp TMP0w, #0, #0, ne
2760 | beq <1
2761 | // Crossed a write barrier. Move the barrier forward.
2762 | mov CARG1, GL
2763 | bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
2764 | b <1
2765 break;
2766 case BC_USETN:
2767 | // RA = uvnum, RC = num_const
2768 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2769 | add RA, RA, #offsetof(GCfuncL, uvptr)/8
2770 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
2771 | ldr UPVAL:CARG2, [LFUNC:CARG2, RA, lsl #3]
2772 | ldr TMP0, [KBASE, RC, lsl #3]
2773 | ldr CARG2, UPVAL:CARG2->v
2774 | str TMP0, [CARG2]
2775 | ins_next
2776 break;
2777 case BC_USETP:
2778 | // RA = uvnum, RC = primitive_type (~)
2779 | ldr LFUNC:CARG2, [BASE, FRAME_FUNC]
2780 | add RA, RA, #offsetof(GCfuncL, uvptr)/8
2781 | and LFUNC:CARG2, CARG2, #LJ_GCVMASK
2782 | ldr UPVAL:CARG2, [LFUNC:CARG2, RA, lsl #3]
2783 | mvn TMP0, RC, lsl #47
2784 | ldr CARG2, UPVAL:CARG2->v
2785 | str TMP0, [CARG2]
2786 | ins_next
2787 break;
2788
2789 case BC_UCLO:
2790 | // RA = level, RC = target
2791 | ldr CARG3, L->openupval
2792 | add RC, PC, RC, lsl #2
2793 | str BASE, L->base
2794 | sub PC, RC, #0x20000
2795 | cbz CARG3, >1
2796 | mov CARG1, L
2797 | add CARG2, BASE, RA, lsl #3
2798 | bl extern lj_func_closeuv // (lua_State *L, TValue *level)
2799 | ldr BASE, L->base
2800 |1:
2801 | ins_next
2802 break;
2803
2804 case BC_FNEW:
2805 | // RA = dst, RC = proto_const (~) (holding function prototype)
2806 | mvn RC, RC
2807 | str BASE, L->base
2808 | ldr LFUNC:CARG3, [BASE, FRAME_FUNC]
2809 | str PC, SAVE_PC
2810 | ldr CARG2, [KBASE, RC, lsl #3]
2811 | mov CARG1, L
2812 | and LFUNC:CARG3, CARG3, #LJ_GCVMASK
2813 | // (lua_State *L, GCproto *pt, GCfuncL *parent)
2814 | bl extern lj_func_newL_gc
2815 | // Returns GCfuncL *.
2816 | ldr BASE, L->base
2817 | movn TMP0, #~LJ_TFUNC
2818 | add CRET1, CRET1, TMP0, lsl #47
2819 | str CRET1, [BASE, RA, lsl #3]
2820 | ins_next
2821 break;
2822
2823 /* -- Table ops --------------------------------------------------------- */
2824
2825 case BC_TNEW:
2826 case BC_TDUP:
2827 | // RA = dst, RC = (hbits|asize) | tab_const (~)
2828 | ldp CARG3, CARG4, GL->gc.total // Assumes threshold follows total.
2829 | str BASE, L->base
2830 | str PC, SAVE_PC
2831 | mov CARG1, L
2832 | cmp CARG3, CARG4
2833 | bhs >5
2834 |1:
2835 if (op == BC_TNEW) {
2836 | and CARG2, RC, #0x7ff
2837 | lsr CARG3, RC, #11
2838 | cmp CARG2, #0x7ff
2839 | mov TMP0, #0x801
2840 | csel CARG2, CARG2, TMP0, ne
2841 | bl extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits)
2842 | // Returns GCtab *.
2843 } else {
2844 | mvn RC, RC
2845 | ldr CARG2, [KBASE, RC, lsl #3]
2846 | bl extern lj_tab_dup // (lua_State *L, Table *kt)
2847 | // Returns GCtab *.
2848 }
2849 | ldr BASE, L->base
2850 | movk CRET1, #(LJ_TTAB>>1)&0xffff, lsl #48
2851 | str CRET1, [BASE, RA, lsl #3]
2852 | ins_next
2853 |
2854 |5:
2855 | bl extern lj_gc_step_fixtop // (lua_State *L)
2856 | mov CARG1, L
2857 | b <1
2858 break;
2859
2860 case BC_GGET:
2861 | // RA = dst, RC = str_const (~)
2862 case BC_GSET:
2863 | // RA = dst, RC = str_const (~)
2864 | ldr LFUNC:CARG1, [BASE, FRAME_FUNC]
2865 | mvn RC, RC
2866 | and LFUNC:CARG1, CARG1, #LJ_GCVMASK
2867 | ldr TAB:CARG2, LFUNC:CARG1->env
2868 | ldr STR:RC, [KBASE, RC, lsl #3]
2869 if (op == BC_GGET) {
2870 | b ->BC_TGETS_Z
2871 } else {
2872 | b ->BC_TSETS_Z
2873 }
2874 break;
2875
2876 case BC_TGETV:
2877 | decode_RB RB, INS
2878 | and RC, RC, #255
2879 | // RA = dst, RB = table, RC = key
2880 | ldr CARG2, [BASE, RB, lsl #3]
2881 | ldr TMP1, [BASE, RC, lsl #3]
2882 | checktab CARG2, ->vmeta_tgetv
2883 | checkint TMP1, >9 // Integer key?
2884 | ldr CARG3, TAB:CARG2->array
2885 | ldr CARG1w, TAB:CARG2->asize
2886 | add CARG3, CARG3, TMP1, uxtw #3
2887 | cmp TMP1w, CARG1w // In array part?
2888 | bhs ->vmeta_tgetv
2889 | ldr TMP0, [CARG3]
2890 | cmp TMP0, TISNIL
2891 | beq >5
2892 |1:
2893 | str TMP0, [BASE, RA, lsl #3]
2894 | ins_next
2895 |
2896 |5: // Check for __index if table value is nil.
2897 | ldr TAB:CARG1, TAB:CARG2->metatable
2898 | cbz TAB:CARG1, <1 // No metatable: done.
2899 | ldrb TMP1w, TAB:CARG1->nomm
2900 | tbnz TMP1w, #MM_index, <1 // 'no __index' flag set: done.
2901 | b ->vmeta_tgetv
2902 |
2903 |9:
2904 | asr ITYPE, TMP1, #47
2905 | cmn ITYPE, #-LJ_TSTR // String key?
2906 | bne ->vmeta_tgetv
2907 | and STR:RC, TMP1, #LJ_GCVMASK
2908 | b ->BC_TGETS_Z
2909 break;
2910 case BC_TGETS:
2911 | decode_RB RB, INS
2912 | and RC, RC, #255
2913 | // RA = dst, RB = table, RC = str_const (~)
2914 | ldr CARG2, [BASE, RB, lsl #3]
2915 | mvn RC, RC
2916 | ldr STR:RC, [KBASE, RC, lsl #3]
2917 | checktab CARG2, ->vmeta_tgets1
2918 |->BC_TGETS_Z:
2919 | // TAB:CARG2 = GCtab *, STR:RC = GCstr *, RA = dst
2920 | ldr TMP1w, TAB:CARG2->hmask
2921 | ldr TMP2w, STR:RC->hash
2922 | ldr NODE:CARG3, TAB:CARG2->node
2923 | and TMP1w, TMP1w, TMP2w // idx = str->hash & tab->hmask
2924 | add TMP1, TMP1, TMP1, lsl #1
2925 | movn CARG4, #~LJ_TSTR
2926 | add NODE:CARG3, NODE:CARG3, TMP1, lsl #3 // node = tab->node + idx*3*8
2927 | add CARG4, STR:RC, CARG4, lsl #47 // Tagged key to look for.
2928 |1:
2929 | ldp TMP0, CARG1, NODE:CARG3->val
2930 | ldr NODE:CARG3, NODE:CARG3->next
2931 | cmp CARG1, CARG4
2932 | bne >4
2933 | cmp TMP0, TISNIL
2934 | beq >5
2935 |3:
2936 | str TMP0, [BASE, RA, lsl #3]
2937 | ins_next
2938 |
2939 |4: // Follow hash chain.
2940 | cbnz NODE:CARG3, <1
2941 | // End of hash chain: key not found, nil result.
2942 | mov TMP0, TISNIL
2943 |
2944 |5: // Check for __index if table value is nil.
2945 | ldr TAB:CARG1, TAB:CARG2->metatable
2946 | cbz TAB:CARG1, <3 // No metatable: done.
2947 | ldrb TMP1w, TAB:CARG1->nomm
2948 | tbnz TMP1w, #MM_index, <3 // 'no __index' flag set: done.
2949 | b ->vmeta_tgets
2950 break;
2951 case BC_TGETB:
2952 | decode_RB RB, INS
2953 | and RC, RC, #255
2954 | // RA = dst, RB = table, RC = index
2955 | ldr CARG2, [BASE, RB, lsl #3]
2956 | checktab CARG2, ->vmeta_tgetb
2957 | ldr CARG3, TAB:CARG2->array
2958 | ldr CARG1w, TAB:CARG2->asize
2959 | add CARG3, CARG3, RC, lsl #3
2960 | cmp RCw, CARG1w // In array part?
2961 | bhs ->vmeta_tgetb
2962 | ldr TMP0, [CARG3]
2963 | cmp TMP0, TISNIL
2964 | beq >5
2965 |1:
2966 | str TMP0, [BASE, RA, lsl #3]
2967 | ins_next
2968 |
2969 |5: // Check for __index if table value is nil.
2970 | ldr TAB:CARG1, TAB:CARG2->metatable
2971 | cbz TAB:CARG1, <1 // No metatable: done.
2972 | ldrb TMP1w, TAB:CARG1->nomm
2973 | tbnz TMP1w, #MM_index, <1 // 'no __index' flag set: done.
2974 | b ->vmeta_tgetb
2975 break;
2976 case BC_TGETR:
2977 | decode_RB RB, INS
2978 | and RC, RC, #255
2979 | // RA = dst, RB = table, RC = key
2980 | ldr CARG1, [BASE, RB, lsl #3]
2981 | ldr TMP1, [BASE, RC, lsl #3]
2982 | and TAB:CARG1, CARG1, #LJ_GCVMASK
2983 | ldr CARG3, TAB:CARG1->array
2984 | ldr TMP2w, TAB:CARG1->asize
2985 | add CARG3, CARG3, TMP1w, uxtw #3
2986 | cmp TMP1w, TMP2w // In array part?
2987 | bhs ->vmeta_tgetr
2988 | ldr TMP0, [CARG3]
2989 |->BC_TGETR_Z:
2990 | str TMP0, [BASE, RA, lsl #3]
2991 | ins_next
2992 break;
2993
2994 case BC_TSETV:
2995 | decode_RB RB, INS
2996 | and RC, RC, #255
2997 | // RA = src, RB = table, RC = key
2998 | ldr CARG2, [BASE, RB, lsl #3]
2999 | ldr TMP1, [BASE, RC, lsl #3]
3000 | checktab CARG2, ->vmeta_tsetv
3001 | checkint TMP1, >9 // Integer key?
3002 | ldr CARG3, TAB:CARG2->array
3003 | ldr CARG1w, TAB:CARG2->asize
3004 | add CARG3, CARG3, TMP1, uxtw #3
3005 | cmp TMP1w, CARG1w // In array part?
3006 | bhs ->vmeta_tsetv
3007 | ldr TMP1, [CARG3]
3008 | ldr TMP0, [BASE, RA, lsl #3]
3009 | ldrb TMP2w, TAB:CARG2->marked
3010 | cmp TMP1, TISNIL // Previous value is nil?
3011 | beq >5
3012 |1:
3013 | str TMP0, [CARG3]
3014 | tbnz TMP2w, #2, >7 // isblack(table)
3015 |2:
3016 | ins_next
3017 |
3018 |5: // Check for __newindex if previous value is nil.
3019 | ldr TAB:CARG1, TAB:CARG2->metatable
3020 | cbz TAB:CARG1, <1 // No metatable: done.
3021 | ldrb TMP1w, TAB:CARG1->nomm
3022 | tbnz TMP1w, #MM_newindex, <1 // 'no __newindex' flag set: done.
3023 | b ->vmeta_tsetv
3024 |
3025 |7: // Possible table write barrier for the value. Skip valiswhite check.
3026 | barrierback TAB:CARG2, TMP2w, TMP1
3027 | b <2
3028 |
3029 |9:
3030 | asr ITYPE, TMP1, #47
3031 | cmn ITYPE, #-LJ_TSTR // String key?
3032 | bne ->vmeta_tsetv
3033 | and STR:RC, TMP1, #LJ_GCVMASK
3034 | b ->BC_TSETS_Z
3035 break;
3036 case BC_TSETS:
3037 | decode_RB RB, INS
3038 | and RC, RC, #255
3039 | // RA = dst, RB = table, RC = str_const (~)
3040 | ldr CARG2, [BASE, RB, lsl #3]
3041 | mvn RC, RC
3042 | ldr STR:RC, [KBASE, RC, lsl #3]
3043 | checktab CARG2, ->vmeta_tsets1
3044 |->BC_TSETS_Z:
3045 | // TAB:CARG2 = GCtab *, STR:RC = GCstr *, RA = src
3046 | ldr TMP1w, TAB:CARG2->hmask
3047 | ldr TMP2w, STR:RC->hash
3048 | ldr NODE:CARG3, TAB:CARG2->node
3049 | and TMP1w, TMP1w, TMP2w // idx = str->hash & tab->hmask
3050 | add TMP1, TMP1, TMP1, lsl #1
3051 | movn CARG4, #~LJ_TSTR
3052 | add NODE:CARG3, NODE:CARG3, TMP1, lsl #3 // node = tab->node + idx*3*8
3053 | add CARG4, STR:RC, CARG4, lsl #47 // Tagged key to look for.
3054 | strb wzr, TAB:CARG2->nomm // Clear metamethod cache.
3055 |1:
3056 | ldp TMP1, CARG1, NODE:CARG3->val
3057 | ldr NODE:TMP3, NODE:CARG3->next
3058 | ldrb TMP2w, TAB:CARG2->marked
3059 | cmp CARG1, CARG4
3060 | bne >5
3061 | ldr TMP0, [BASE, RA, lsl #3]
3062 | cmp TMP1, TISNIL // Previous value is nil?
3063 | beq >4
3064 |2:
3065 | str TMP0, NODE:CARG3->val
3066 | tbnz TMP2w, #2, >7 // isblack(table)
3067 |3:
3068 | ins_next
3069 |
3070 |4: // Check for __newindex if previous value is nil.
3071 | ldr TAB:CARG1, TAB:CARG2->metatable
3072 | cbz TAB:CARG1, <2 // No metatable: done.
3073 | ldrb TMP1w, TAB:CARG1->nomm
3074 | tbnz TMP1w, #MM_newindex, <2 // 'no __newindex' flag set: done.
3075 | b ->vmeta_tsets
3076 |
3077 |5: // Follow hash chain.
3078 | mov NODE:CARG3, NODE:TMP3
3079 | cbnz NODE:TMP3, <1
3080 | // End of hash chain: key not found, add a new one.
3081 |
3082 | // But check for __newindex first.
3083 | ldr TAB:CARG1, TAB:CARG2->metatable
3084 | cbz TAB:CARG1, >6 // No metatable: continue.
3085 | ldrb TMP1w, TAB:CARG1->nomm
3086 | // 'no __newindex' flag NOT set: check.
3087 | tbz TMP1w, #MM_newindex, ->vmeta_tsets
3088 |6:
3089 | movn TMP1, #~LJ_TSTR
3090 | str PC, SAVE_PC
3091 | add TMP0, STR:RC, TMP1, lsl #47
3092 | str BASE, L->base
3093 | mov CARG1, L
3094 | str TMP0, TMPD
3095 | add CARG3, sp, TMPDofs
3096 | bl extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k)
3097 | // Returns TValue *.
3098 | ldr BASE, L->base
3099 | ldr TMP0, [BASE, RA, lsl #3]
3100 | str TMP0, [CRET1]
3101 | b <3 // No 2nd write barrier needed.
3102 |
3103 |7: // Possible table write barrier for the value. Skip valiswhite check.
3104 | barrierback TAB:CARG2, TMP2w, TMP1
3105 | b <3
3106 break;
3107 case BC_TSETB:
3108 | decode_RB RB, INS
3109 | and RC, RC, #255
3110 | // RA = src, RB = table, RC = index
3111 | ldr CARG2, [BASE, RB, lsl #3]
3112 | checktab CARG2, ->vmeta_tsetb
3113 | ldr CARG3, TAB:CARG2->array
3114 | ldr CARG1w, TAB:CARG2->asize
3115 | add CARG3, CARG3, RC, lsl #3
3116 | cmp RCw, CARG1w // In array part?
3117 | bhs ->vmeta_tsetb
3118 | ldr TMP1, [CARG3]
3119 | ldr TMP0, [BASE, RA, lsl #3]
3120 | ldrb TMP2w, TAB:CARG2->marked
3121 | cmp TMP1, TISNIL // Previous value is nil?
3122 | beq >5
3123 |1:
3124 | str TMP0, [CARG3]
3125 | tbnz TMP2w, #2, >7 // isblack(table)
3126 |2:
3127 | ins_next
3128 |
3129 |5: // Check for __newindex if previous value is nil.
3130 | ldr TAB:CARG1, TAB:CARG2->metatable
3131 | cbz TAB:CARG1, <1 // No metatable: done.
3132 | ldrb TMP1w, TAB:CARG1->nomm
3133 | tbnz TMP1w, #MM_newindex, <1 // 'no __newindex' flag set: done.
3134 | b ->vmeta_tsetb
3135 |
3136 |7: // Possible table write barrier for the value. Skip valiswhite check.
3137 | barrierback TAB:CARG2, TMP2w, TMP1
3138 | b <2
3139 break;
3140 case BC_TSETR:
3141 | decode_RB RB, INS
3142 | and RC, RC, #255
3143 | // RA = src, RB = table, RC = key
3144 | ldr CARG2, [BASE, RB, lsl #3]
3145 | ldr TMP1, [BASE, RC, lsl #3]
3146 | and TAB:CARG2, CARG2, #LJ_GCVMASK
3147 | ldr CARG1, TAB:CARG2->array
3148 | ldrb TMP2w, TAB:CARG2->marked
3149 | ldr CARG4w, TAB:CARG2->asize
3150 | add CARG1, CARG1, TMP1, uxtw #3
3151 | tbnz TMP2w, #2, >7 // isblack(table)
3152 |2:
3153 | cmp TMP1w, CARG4w // In array part?
3154 | bhs ->vmeta_tsetr
3155 |->BC_TSETR_Z:
3156 | ldr TMP0, [BASE, RA, lsl #3]
3157 | str TMP0, [CARG1]
3158 | ins_next
3159 |
3160 |7: // Possible table write barrier for the value. Skip valiswhite check.
3161 | barrierback TAB:CARG2, TMP2w, TMP0
3162 | b <2
3163 break;
3164
3165 case BC_TSETM:
3166 | // RA = base (table at base-1), RC = num_const (start index)
3167 | add RA, BASE, RA, lsl #3
3168 |1:
3169 | ldr RBw, SAVE_MULTRES
3170 | ldr TAB:CARG2, [RA, #-8] // Guaranteed to be a table.
3171 | ldr TMP1, [KBASE, RC, lsl #3] // Integer constant is in lo-word.
3172 | sub RB, RB, #8
3173 | cbz RB, >4 // Nothing to copy?
3174 | and TAB:CARG2, CARG2, #LJ_GCVMASK
3175 | ldr CARG1w, TAB:CARG2->asize
3176 | add CARG3w, TMP1w, RBw, lsr #3
3177 | ldr CARG4, TAB:CARG2->array
3178 | cmp CARG3, CARG1
3179 | add RB, RA, RB
3180 | bhi >5
3181 | add TMP1, CARG4, TMP1w, uxtw #3
3182 | ldrb TMP2w, TAB:CARG2->marked
3183 |3: // Copy result slots to table.
3184 | ldr TMP0, [RA], #8
3185 | str TMP0, [TMP1], #8
3186 | cmp RA, RB
3187 | blo <3
3188 | tbnz TMP2w, #2, >7 // isblack(table)
3189 |4:
3190 | ins_next
3191 |
3192 |5: // Need to resize array part.
3193 | str BASE, L->base
3194 | mov CARG1, L
3195 | str PC, SAVE_PC
3196 | bl extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
3197 | // Must not reallocate the stack.
3198 | b <1
3199 |
3200 |7: // Possible table write barrier for any value. Skip valiswhite check.
3201 | barrierback TAB:CARG2, TMP2w, TMP1
3202 | b <4
3203 break;
3204
3205 /* -- Calls and vararg handling ----------------------------------------- */
3206
3207 case BC_CALLM:
3208 | // RA = base, (RB = nresults+1,) RC = extra_nargs
3209 | ldr TMP0w, SAVE_MULTRES
3210 | decode_RC8RD NARGS8:RC, RC
3211 | add NARGS8:RC, NARGS8:RC, TMP0
3212 | b ->BC_CALL_Z
3213 break;
3214 case BC_CALL:
3215 | decode_RC8RD NARGS8:RC, RC
3216 | // RA = base, (RB = nresults+1,) RC = (nargs+1)*8
3217 |->BC_CALL_Z:
3218 | mov RB, BASE // Save old BASE for vmeta_call.
3219 | add BASE, BASE, RA, lsl #3
3220 | ldr CARG3, [BASE]
3221 | sub NARGS8:RC, NARGS8:RC, #8
3222 | add BASE, BASE, #16
3223 | checkfunc CARG3, ->vmeta_call
3224 | ins_call
3225 break;
3226
3227 case BC_CALLMT:
3228 | // RA = base, (RB = 0,) RC = extra_nargs
3229 | ldr TMP0w, SAVE_MULTRES
3230 | add NARGS8:RC, TMP0, RC, lsl #3
3231 | b ->BC_CALLT1_Z
3232 break;
3233 case BC_CALLT:
3234 | lsl NARGS8:RC, RC, #3
3235 | // RA = base, (RB = 0,) RC = (nargs+1)*8
3236 |->BC_CALLT1_Z:
3237 | add RA, BASE, RA, lsl #3
3238 | ldr TMP1, [RA]
3239 | sub NARGS8:RC, NARGS8:RC, #8
3240 | add RA, RA, #16
3241 | checktp CARG3, TMP1, LJ_TFUNC, ->vmeta_callt
3242 | ldr PC, [BASE, FRAME_PC]
3243 |->BC_CALLT2_Z:
3244 | mov RB, #0
3245 | ldrb TMP2w, LFUNC:CARG3->ffid
3246 | tst PC, #FRAME_TYPE
3247 | bne >7
3248 |1:
3249 | str TMP1, [BASE, FRAME_FUNC] // Copy function down, but keep PC.
3250 | cbz NARGS8:RC, >3
3251 |2:
3252 | ldr TMP0, [RA, RB]
3253 | add TMP1, RB, #8
3254 | cmp TMP1, NARGS8:RC
3255 | str TMP0, [BASE, RB]
3256 | mov RB, TMP1
3257 | bne <2
3258 |3:
3259 | cmp TMP2, #1 // (> FF_C) Calling a fast function?
3260 | bhi >5
3261 |4:
3262 | ins_callt
3263 |
3264 |5: // Tailcall to a fast function with a Lua frame below.
3265 | ldrb RAw, [PC, #-3]
3266 | sub CARG1, BASE, RA, lsl #3
3267 | ldr LFUNC:CARG1, [CARG1, #-32]
3268 | and LFUNC:CARG1, CARG1, #LJ_GCVMASK
3269 | ldr CARG1, LFUNC:CARG1->pc
3270 | ldr KBASE, [CARG1, #PC2PROTO(k)]
3271 | b <4
3272 |
3273 |7: // Tailcall from a vararg function.
3274 | eor PC, PC, #FRAME_VARG
3275 | tst PC, #FRAME_TYPEP // Vararg frame below?
3276 | csel TMP2, RB, TMP2, ne // Clear ffid if no Lua function below.
3277 | bne <1
3278 | sub BASE, BASE, PC
3279 | ldr PC, [BASE, FRAME_PC]
3280 | tst PC, #FRAME_TYPE
3281 | csel TMP2, RB, TMP2, ne // Clear ffid if no Lua function below.
3282 | b <1
3283 break;
3284
3285 case BC_ITERC:
3286 | // RA = base, (RB = nresults+1, RC = nargs+1 (2+1))
3287 | add RA, BASE, RA, lsl #3
3288 | ldr CARG3, [RA, #-24]
3289 | mov RB, BASE // Save old BASE for vmeta_call.
3290 | ldp CARG1, CARG2, [RA, #-16]
3291 | add BASE, RA, #16
3292 | mov NARGS8:RC, #16 // Iterators get 2 arguments.
3293 | str CARG3, [RA] // Copy callable.
3294 | stp CARG1, CARG2, [RA, #16] // Copy state and control var.
3295 | checkfunc CARG3, ->vmeta_call
3296 | ins_call
3297 break;
3298
3299 case BC_ITERN:
3300 | // RA = base, (RB = nresults+1, RC = nargs+1 (2+1))
3301 |.if JIT
3302 | // NYI: add hotloop, record BC_ITERN.
3303 |.endif
3304 | add RA, BASE, RA, lsl #3
3305 | ldr TAB:RB, [RA, #-16]
3306 | ldrh TMP3w, [PC, #2]
3307 | ldr CARG1w, [RA, #-8] // Get index from control var.
3308 | add PC, PC, #4
3309 | add TMP3, PC, TMP3, lsl #2
3310 | and TAB:RB, RB, #LJ_GCVMASK
3311 | sub TMP3, TMP3, #0x20000
3312 | ldr TMP1w, TAB:RB->asize
3313 | ldr CARG2, TAB:RB->array
3314 |1: // Traverse array part.
3315 | subs RC, CARG1, TMP1
3316 | add CARG3, CARG2, CARG1, lsl #3
3317 | bhs >5 // Index points after array part?
3318 | ldr TMP0, [CARG3]
3319 | cmp TMP0, TISNIL
3320 | cinc CARG1, CARG1, eq // Skip holes in array part.
3321 | beq <1
3322 | add CARG1, CARG1, TISNUM
3323 | stp CARG1, TMP0, [RA]
3324 | add CARG1, CARG1, #1
3325 |3:
3326 | str CARG1w, [RA, #-8] // Update control var.
3327 | mov PC, TMP3
3328 |4:
3329 | ins_next
3330 |
3331 |5: // Traverse hash part.
3332 | ldr TMP2w, TAB:RB->hmask
3333 | ldr NODE:RB, TAB:RB->node
3334 |6:
3335 | add CARG1, RC, RC, lsl #1
3336 | cmp RC, TMP2 // End of iteration? Branch to ITERN+1.
3337 | add NODE:CARG3, NODE:RB, CARG1, lsl #3 // node = tab->node + idx*3*8
3338 | bhi <4
3339 | ldp TMP0, CARG1, NODE:CARG3->val
3340 | cmp TMP0, TISNIL
3341 | add RC, RC, #1
3342 | beq <6 // Skip holes in hash part.
3343 | stp CARG1, TMP0, [RA]
3344 | add CARG1, RC, TMP1
3345 | b <3
3346 break;
3347
3348 case BC_ISNEXT:
3349 | // RA = base, RC = target (points to ITERN)
3350 | add RA, BASE, RA, lsl #3
3351 | ldr CFUNC:CARG1, [RA, #-24]
3352 | add RC, PC, RC, lsl #2
3353 | ldp TAB:CARG3, CARG4, [RA, #-16]
3354 | sub RC, RC, #0x20000
3355 | checkfunc CFUNC:CARG1, >5
3356 | asr TMP0, TAB:CARG3, #47
3357 | ldrb TMP1w, CFUNC:CARG1->ffid
3358 | cmn TMP0, #-LJ_TTAB
3359 | ccmp CARG4, TISNIL, #0, eq
3360 | ccmp TMP1w, #FF_next_N, #0, eq
3361 | bne >5
3362 | mov TMP0w, #0xfffe7fff
3363 | lsl TMP0, TMP0, #32
3364 | str TMP0, [RA, #-8] // Initialize control var.
3365 |1:
3366 | mov PC, RC
3367 | ins_next
3368 |
3369 |5: // Despecialize bytecode if any of the checks fail.
3370 | mov TMP0, #BC_JMP
3371 | mov TMP1, #BC_ITERC
3372 | strb TMP0w, [PC, #-4]
3373 | strb TMP1w, [RC]
3374 | b <1
3375 break;
3376
3377 case BC_VARG:
3378 | decode_RB RB, INS
3379 | and RC, RC, #255
3380 | // RA = base, RB = (nresults+1), RC = numparams
3381 | ldr TMP1, [BASE, FRAME_PC]
3382 | add RC, BASE, RC, lsl #3
3383 | add RA, BASE, RA, lsl #3
3384 | add RC, RC, #FRAME_VARG
3385 | add TMP2, RA, RB, lsl #3
3386 | sub RC, RC, TMP1 // RC = vbase
3387 | // Note: RC may now be even _above_ BASE if nargs was < numparams.
3388 | sub TMP3, BASE, #16 // TMP3 = vtop
3389 | cbz RB, >5
3390 | sub TMP2, TMP2, #16
3391 |1: // Copy vararg slots to destination slots.
3392 | cmp RC, TMP3
3393 | ldr TMP0, [RC], #8
3394 | csel TMP0, TMP0, TISNIL, lo
3395 | cmp RA, TMP2
3396 | str TMP0, [RA], #8
3397 | blo <1
3398 |2:
3399 | ins_next
3400 |
3401 |5: // Copy all varargs.
3402 | ldr TMP0, L->maxstack
3403 | subs TMP2, TMP3, RC
3404 | csel RB, xzr, TMP2, le // MULTRES = (max(vtop-vbase,0)+1)*8
3405 | add RB, RB, #8
3406 | add TMP1, RA, TMP2
3407 | str RBw, SAVE_MULTRES
3408 | ble <2 // Nothing to copy.
3409 | cmp TMP1, TMP0
3410 | bhi >7
3411 |6:
3412 | ldr TMP0, [RC], #8
3413 | str TMP0, [RA], #8
3414 | cmp RC, TMP3
3415 | blo <6
3416 | b <2
3417 |
3418 |7: // Grow stack for varargs.
3419 | lsr CARG2, TMP2, #3
3420 | stp BASE, RA, L->base
3421 | mov CARG1, L
3422 | sub RC, RC, BASE // Need delta, because BASE may change.
3423 | str PC, SAVE_PC
3424 | bl extern lj_state_growstack // (lua_State *L, int n)
3425 | ldp BASE, RA, L->base
3426 | add RC, BASE, RC
3427 | sub TMP3, BASE, #16
3428 | b <6
3429 break;
3430
3431 /* -- Returns ----------------------------------------------------------- */
3432
3433 case BC_RETM:
3434 | // RA = results, RC = extra results
3435 | ldr TMP0w, SAVE_MULTRES
3436 | ldr PC, [BASE, FRAME_PC]
3437 | add RA, BASE, RA, lsl #3
3438 | add RC, TMP0, RC, lsl #3
3439 | b ->BC_RETM_Z
3440 break;
3441
3442 case BC_RET:
3443 | // RA = results, RC = nresults+1
3444 | ldr PC, [BASE, FRAME_PC]
3445 | lsl RC, RC, #3
3446 | add RA, BASE, RA, lsl #3
3447 |->BC_RETM_Z:
3448 | str RCw, SAVE_MULTRES
3449 |1:
3450 | ands CARG1, PC, #FRAME_TYPE
3451 | eor CARG2, PC, #FRAME_VARG
3452 | bne ->BC_RETV2_Z
3453 |
3454 |->BC_RET_Z:
3455 | // BASE = base, RA = resultptr, RC = (nresults+1)*8, PC = return
3456 | ldr INSw, [PC, #-4]
3457 | subs TMP1, RC, #8
3458 | sub CARG3, BASE, #16
3459 | beq >3
3460 |2:
3461 | ldr TMP0, [RA], #8
3462 | add BASE, BASE, #8
3463 | sub TMP1, TMP1, #8
3464 | str TMP0, [BASE, #-24]
3465 | cbnz TMP1, <2
3466 |3:
3467 | decode_RA RA, INS
3468 | sub CARG4, CARG3, RA, lsl #3
3469 | decode_RB RB, INS
3470 | ldr LFUNC:CARG1, [CARG4, FRAME_FUNC]
3471 |5:
3472 | cmp RC, RB, lsl #3 // More results expected?
3473 | blo >6
3474 | and LFUNC:CARG1, CARG1, #LJ_GCVMASK
3475 | mov BASE, CARG4
3476 | ldr CARG2, LFUNC:CARG1->pc
3477 | ldr KBASE, [CARG2, #PC2PROTO(k)]
3478 | ins_next
3479 |
3480 |6: // Fill up results with nil.
3481 | add BASE, BASE, #8
3482 | add RC, RC, #8
3483 | str TISNIL, [BASE, #-24]
3484 | b <5
3485 |
3486 |->BC_RETV1_Z: // Non-standard return case.
3487 | add RA, BASE, RA, lsl #3
3488 |->BC_RETV2_Z:
3489 | tst CARG2, #FRAME_TYPEP
3490 | bne ->vm_return
3491 | // Return from vararg function: relocate BASE down.
3492 | sub BASE, BASE, CARG2
3493 | ldr PC, [BASE, FRAME_PC]
3494 | b <1
3495 break;
3496
3497 case BC_RET0: case BC_RET1:
3498 | // RA = results, RC = nresults+1
3499 | ldr PC, [BASE, FRAME_PC]
3500 | lsl RC, RC, #3
3501 | str RCw, SAVE_MULTRES
3502 | ands CARG1, PC, #FRAME_TYPE
3503 | eor CARG2, PC, #FRAME_VARG
3504 | bne ->BC_RETV1_Z
3505 | ldr INSw, [PC, #-4]
3506 if (op == BC_RET1) {
3507 | ldr TMP0, [BASE, RA, lsl #3]
3508 }
3509 | sub CARG4, BASE, #16
3510 | decode_RA RA, INS
3511 | sub BASE, CARG4, RA, lsl #3
3512 if (op == BC_RET1) {
3513 | str TMP0, [CARG4], #8
3514 }
3515 | decode_RB RB, INS
3516 | ldr LFUNC:CARG1, [BASE, FRAME_FUNC]
3517 |5:
3518 | cmp RC, RB, lsl #3
3519 | blo >6
3520 | and LFUNC:CARG1, CARG1, #LJ_GCVMASK
3521 | ldr CARG2, LFUNC:CARG1->pc
3522 | ldr KBASE, [CARG2, #PC2PROTO(k)]
3523 | ins_next
3524 |
3525 |6: // Fill up results with nil.
3526 | add RC, RC, #8
3527 | str TISNIL, [CARG4], #8
3528 | b <5
3529 break;
3530
3531 /* -- Loops and branches ------------------------------------------------ */
3532
3533 |.define FOR_IDX, [RA]; .define FOR_TIDX, [RA, #4]
3534 |.define FOR_STOP, [RA, #8]; .define FOR_TSTOP, [RA, #12]
3535 |.define FOR_STEP, [RA, #16]; .define FOR_TSTEP, [RA, #20]
3536 |.define FOR_EXT, [RA, #24]; .define FOR_TEXT, [RA, #28]
3537
3538 case BC_FORL:
3539 |.if JIT
3540 | hotloop
3541 |.endif
3542 | // Fall through. Assumes BC_IFORL follows.
3543 break;
3544
3545 case BC_JFORI:
3546 case BC_JFORL:
3547#if !LJ_HASJIT
3548 break;
3549#endif
3550 case BC_FORI:
3551 case BC_IFORL:
3552 | // RA = base, RC = target (after end of loop or start of loop)
3553 vk = (op == BC_IFORL || op == BC_JFORL);
3554 | add RA, BASE, RA, lsl #3
3555 | ldp CARG1, CARG2, FOR_IDX // CARG1 = IDX, CARG2 = STOP
3556 | ldr CARG3, FOR_STEP // CARG3 = STEP
3557 if (op != BC_JFORL) {
3558 | add RC, PC, RC, lsl #2
3559 | sub RC, RC, #0x20000
3560 }
3561 | checkint CARG1, >5
3562 if (!vk) {
3563 | checkint CARG2, ->vmeta_for
3564 | checkint CARG3, ->vmeta_for
3565 | tbnz CARG3w, #31, >4
3566 | cmp CARG1w, CARG2w
3567 } else {
3568 | adds CARG1w, CARG1w, CARG3w
3569 | bvs >2
3570 | add TMP0, CARG1, TISNUM
3571 | tbnz CARG3w, #31, >4
3572 | cmp CARG1w, CARG2w
3573 }
3574 |1:
3575 if (op == BC_FORI) {
3576 | csel PC, RC, PC, gt
3577 } else if (op == BC_JFORI) {
3578 | mov PC, RC
3579 | ldrh RCw, [RC, #-2]
3580 } else if (op == BC_IFORL) {
3581 | csel PC, RC, PC, le
3582 }
3583 if (vk) {
3584 | str TMP0, FOR_IDX
3585 | str TMP0, FOR_EXT
3586 } else {
3587 | str CARG1, FOR_EXT
3588 }
3589 if (op == BC_JFORI || op == BC_JFORL) {
3590 | ble =>BC_JLOOP
3591 }
3592 |2:
3593 | ins_next
3594 |
3595 |4: // Invert check for negative step.
3596 | cmp CARG2w, CARG1w
3597 | b <1
3598 |
3599 |5: // FP loop.
3600 | ldp d0, d1, FOR_IDX
3601 | blo ->vmeta_for
3602 if (!vk) {
3603 | checknum CARG2, ->vmeta_for
3604 | checknum CARG3, ->vmeta_for
3605 | str d0, FOR_EXT
3606 } else {
3607 | ldr d2, FOR_STEP
3608 | fadd d0, d0, d2
3609 }
3610 | tbnz CARG3, #63, >7
3611 | fcmp d0, d1
3612 |6:
3613 if (vk) {
3614 | str d0, FOR_IDX
3615 | str d0, FOR_EXT
3616 }
3617 if (op == BC_FORI) {
3618 | csel PC, RC, PC, hi
3619 } else if (op == BC_JFORI) {
3620 | ldrh RCw, [RC, #-2]
3621 | bls =>BC_JLOOP
3622 } else if (op == BC_IFORL) {
3623 | csel PC, RC, PC, ls
3624 } else {
3625 | bls =>BC_JLOOP
3626 }
3627 | b <2
3628 |
3629 |7: // Invert check for negative step.
3630 | fcmp d1, d0
3631 | b <6
3632 break;
3633
3634 case BC_ITERL:
3635 |.if JIT
3636 | hotloop
3637 |.endif
3638 | // Fall through. Assumes BC_IITERL follows.
3639 break;
3640
3641 case BC_JITERL:
3642#if !LJ_HASJIT
3643 break;
3644#endif
3645 case BC_IITERL:
3646 | // RA = base, RC = target
3647 | ldr CARG1, [BASE, RA, lsl #3]
3648 | add TMP1, BASE, RA, lsl #3
3649 | cmp CARG1, TISNIL
3650 | beq >1 // Stop if iterator returned nil.
3651 if (op == BC_JITERL) {
3652 | str CARG1, [TMP1, #-8]
3653 | b =>BC_JLOOP
3654 } else {
3655 | add TMP0, PC, RC, lsl #2 // Otherwise save control var + branch.
3656 | sub PC, TMP0, #0x20000
3657 | str CARG1, [TMP1, #-8]
3658 }
3659 |1:
3660 | ins_next
3661 break;
3662
3663 case BC_LOOP:
3664 | // RA = base, RC = target (loop extent)
3665 | // Note: RA/RC is only used by trace recorder to determine scope/extent
3666 | // This opcode does NOT jump, it's only purpose is to detect a hot loop.
3667 |.if JIT
3668 | hotloop
3669 |.endif
3670 | // Fall through. Assumes BC_ILOOP follows.
3671 break;
3672
3673 case BC_ILOOP:
3674 | // RA = base, RC = target (loop extent)
3675 | ins_next
3676 break;
3677
3678 case BC_JLOOP:
3679 |.if JIT
3680 | // RA = base (ignored), RC = traceno
3681 | ldr CARG1, [GL, #GL_J(trace)]
3682 | mov CARG2, #0 // Traces on ARM64 don't store the trace #, so use 0.
3683 | ldr TRACE:RC, [CARG1, RC, lsl #3]
3684 | st_vmstate CARG2
3685 | ldr RA, TRACE:RC->mcode
3686 | str BASE, GL->jit_base
3687 | str L, GL->tmpbuf.L
3688 | sub sp, sp, #16 // See SPS_FIXED. Avoids sp adjust in every root trace.
3689 | br RA
3690 |.endif
3691 break;
3692
3693 case BC_JMP:
3694 | // RA = base (only used by trace recorder), RC = target
3695 | add RC, PC, RC, lsl #2
3696 | sub PC, RC, #0x20000
3697 | ins_next
3698 break;
3699
3700 /* -- Function headers -------------------------------------------------- */
3701
3702 case BC_FUNCF:
3703 |.if JIT
3704 | hotcall
3705 |.endif
3706 case BC_FUNCV: /* NYI: compiled vararg functions. */
3707 | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow.
3708 break;
3709
3710 case BC_JFUNCF:
3711#if !LJ_HASJIT
3712 break;
3713#endif
3714 case BC_IFUNCF:
3715 | // BASE = new base, RA = BASE+framesize*8, CARG3 = LFUNC, RC = nargs*8
3716 | ldr CARG1, L->maxstack
3717 | ldrb TMP1w, [PC, #-4+PC2PROTO(numparams)]
3718 | ldr KBASE, [PC, #-4+PC2PROTO(k)]
3719 | cmp RA, CARG1
3720 | bhi ->vm_growstack_l
3721 |2:
3722 | cmp NARGS8:RC, TMP1, lsl #3 // Check for missing parameters.
3723 | blo >3
3724 if (op == BC_JFUNCF) {
3725 | decode_RD RC, INS
3726 | b =>BC_JLOOP
3727 } else {
3728 | ins_next
3729 }
3730 |
3731 |3: // Clear missing parameters.
3732 | str TISNIL, [BASE, NARGS8:RC]
3733 | add NARGS8:RC, NARGS8:RC, #8
3734 | b <2
3735 break;
3736
3737 case BC_JFUNCV:
3738#if !LJ_HASJIT
3739 break;
3740#endif
3741 | NYI // NYI: compiled vararg functions
3742 break; /* NYI: compiled vararg functions. */
3743
3744 case BC_IFUNCV:
3745 | // BASE = new base, RA = BASE+framesize*8, CARG3 = LFUNC, RC = nargs*8
3746 | ldr CARG1, L->maxstack
3747 | movn TMP0, #~LJ_TFUNC
3748 | add TMP2, BASE, RC
3749 | add LFUNC:CARG3, CARG3, TMP0, lsl #47
3750 | add RA, RA, RC
3751 | add TMP0, RC, #16+FRAME_VARG
3752 | str LFUNC:CARG3, [TMP2], #8 // Store (tagged) copy of LFUNC.
3753 | ldr KBASE, [PC, #-4+PC2PROTO(k)]
3754 | cmp RA, CARG1
3755 | str TMP0, [TMP2], #8 // Store delta + FRAME_VARG.
3756 | bhs ->vm_growstack_l
3757 | sub RC, TMP2, #16
3758 | ldrb TMP1w, [PC, #-4+PC2PROTO(numparams)]
3759 | mov RA, BASE
3760 | mov BASE, TMP2
3761 | cbz TMP1, >2
3762 |1:
3763 | cmp RA, RC // Less args than parameters?
3764 | bhs >3
3765 | ldr TMP0, [RA]
3766 | sub TMP1, TMP1, #1
3767 | str TISNIL, [RA], #8 // Clear old fixarg slot (help the GC).
3768 | str TMP0, [TMP2], #8
3769 | cbnz TMP1, <1
3770 |2:
3771 | ins_next
3772 |
3773 |3:
3774 | sub TMP1, TMP1, #1
3775 | str TISNIL, [TMP2], #8
3776 | cbz TMP1, <2
3777 | b <3
3778 break;
3779
3780 case BC_FUNCC:
3781 case BC_FUNCCW:
3782 | // BASE = new base, RA = BASE+framesize*8, CARG3 = CFUNC, RC = nargs*8
3783 if (op == BC_FUNCC) {
3784 | ldr CARG4, CFUNC:CARG3->f
3785 } else {
3786 | ldr CARG4, GL->wrapf
3787 }
3788 | add CARG2, RA, NARGS8:RC
3789 | ldr CARG1, L->maxstack
3790 | add RC, BASE, NARGS8:RC
3791 | cmp CARG2, CARG1
3792 | stp BASE, RC, L->base
3793 if (op == BC_FUNCCW) {
3794 | ldr CARG2, CFUNC:CARG3->f
3795 }
3796 | mv_vmstate TMP0w, C
3797 | mov CARG1, L
3798 | bhi ->vm_growstack_c // Need to grow stack.
3799 | st_vmstate TMP0w
3800 | blr CARG4 // (lua_State *L [, lua_CFunction f])
3801 | // Returns nresults.
3802 | ldp BASE, TMP1, L->base
3803 | str L, GL->cur_L
3804 | sbfiz RC, CRET1, #3, #32
3805 | st_vmstate ST_INTERP
3806 | ldr PC, [BASE, FRAME_PC]
3807 | sub RA, TMP1, RC // RA = L->top - nresults*8
3808 | b ->vm_returnc
3809 break;
3810
3811 /* ---------------------------------------------------------------------- */
3812
3813 default:
3814 fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
3815 exit(2);
3816 break;
3817 }
3818}
3819
3820static int build_backend(BuildCtx *ctx)
3821{
3822 int op;
3823
3824 dasm_growpc(Dst, BC__MAX);
3825
3826 build_subroutines(ctx);
3827
3828 |.code_op
3829 for (op = 0; op < BC__MAX; op++)
3830 build_ins(ctx, (BCOp)op, op);
3831
3832 return BC__MAX;
3833}
3834
3835/* Emit pseudo frame-info for all assembler functions. */
3836static void emit_asm_debug(BuildCtx *ctx)
3837{
3838 int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code);
3839 int i, cf = CFRAME_SIZE >> 3;
3840 switch (ctx->mode) {
3841 case BUILD_elfasm:
3842 fprintf(ctx->fp, "\t.section .debug_frame,\"\",%%progbits\n");
3843 fprintf(ctx->fp,
3844 ".Lframe0:\n"
3845 "\t.long .LECIE0-.LSCIE0\n"
3846 ".LSCIE0:\n"
3847 "\t.long 0xffffffff\n"
3848 "\t.byte 0x1\n"
3849 "\t.string \"\"\n"
3850 "\t.uleb128 0x1\n"
3851 "\t.sleb128 -8\n"
3852 "\t.byte 30\n" /* Return address is in lr. */
3853 "\t.byte 0xc\n\t.uleb128 31\n\t.uleb128 0\n" /* def_cfa sp */
3854 "\t.align 3\n"
3855 ".LECIE0:\n\n");
3856 fprintf(ctx->fp,
3857 ".LSFDE0:\n"
3858 "\t.long .LEFDE0-.LASFDE0\n"
3859 ".LASFDE0:\n"
3860 "\t.long .Lframe0\n"
3861 "\t.quad .Lbegin\n"
3862 "\t.quad %d\n"
3863 "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
3864 "\t.byte 0x9d\n\t.uleb128 %d\n" /* offset fp */
3865 "\t.byte 0x9e\n\t.uleb128 %d\n", /* offset lr */
3866 fcofs, CFRAME_SIZE, cf, cf-1);
3867 for (i = 19; i <= 28; i++) /* offset x19-x28 */
3868 fprintf(ctx->fp, "\t.byte 0x%x\n\t.uleb128 %d\n", 0x80+i, cf-i+17);
3869 for (i = 8; i <= 15; i++) /* offset d8-d15 */
3870 fprintf(ctx->fp, "\t.byte 5\n\t.uleb128 0x%x\n\t.uleb128 %d\n",
3871 64+i, cf-i-4);
3872 fprintf(ctx->fp,
3873 "\t.align 3\n"
3874 ".LEFDE0:\n\n");
3875#if LJ_HASFFI
3876 fprintf(ctx->fp,
3877 ".LSFDE1:\n"
3878 "\t.long .LEFDE1-.LASFDE1\n"
3879 ".LASFDE1:\n"
3880 "\t.long .Lframe0\n"
3881 "\t.quad lj_vm_ffi_call\n"
3882 "\t.quad %d\n"
3883 "\t.byte 0xe\n\t.uleb128 32\n" /* def_cfa_offset */
3884 "\t.byte 0x9d\n\t.uleb128 4\n" /* offset fp */
3885 "\t.byte 0x9e\n\t.uleb128 3\n" /* offset lr */
3886 "\t.byte 0x93\n\t.uleb128 2\n" /* offset x19 */
3887 "\t.align 3\n"
3888 ".LEFDE1:\n\n", (int)ctx->codesz - fcofs);
3889#endif
3890 fprintf(ctx->fp, "\t.section .eh_frame,\"a\",%%progbits\n");
3891 fprintf(ctx->fp,
3892 ".Lframe1:\n"
3893 "\t.long .LECIE1-.LSCIE1\n"
3894 ".LSCIE1:\n"
3895 "\t.long 0\n"
3896 "\t.byte 0x1\n"
3897 "\t.string \"zPR\"\n"
3898 "\t.uleb128 0x1\n"
3899 "\t.sleb128 -8\n"
3900 "\t.byte 30\n" /* Return address is in lr. */
3901 "\t.uleb128 6\n" /* augmentation length */
3902 "\t.byte 0x1b\n" /* pcrel|sdata4 */
3903 "\t.long lj_err_unwind_dwarf-.\n"
3904 "\t.byte 0x1b\n" /* pcrel|sdata4 */
3905 "\t.byte 0xc\n\t.uleb128 31\n\t.uleb128 0\n" /* def_cfa sp */
3906 "\t.align 3\n"
3907 ".LECIE1:\n\n");
3908 fprintf(ctx->fp,
3909 ".LSFDE2:\n"
3910 "\t.long .LEFDE2-.LASFDE2\n"
3911 ".LASFDE2:\n"
3912 "\t.long .LASFDE2-.Lframe1\n"
3913 "\t.long .Lbegin-.\n"
3914 "\t.long %d\n"
3915 "\t.uleb128 0\n" /* augmentation length */
3916 "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
3917 "\t.byte 0x9d\n\t.uleb128 %d\n" /* offset fp */
3918 "\t.byte 0x9e\n\t.uleb128 %d\n", /* offset lr */
3919 fcofs, CFRAME_SIZE, cf, cf-1);
3920 for (i = 19; i <= 28; i++) /* offset x19-x28 */
3921 fprintf(ctx->fp, "\t.byte 0x%x\n\t.uleb128 %d\n", 0x80+i, cf-i+17);
3922 for (i = 8; i <= 15; i++) /* offset d8-d15 */
3923 fprintf(ctx->fp, "\t.byte 5\n\t.uleb128 0x%x\n\t.uleb128 %d\n",
3924 64+i, cf-i-4);
3925 fprintf(ctx->fp,
3926 "\t.align 3\n"
3927 ".LEFDE2:\n\n");
3928#if LJ_HASFFI
3929 fprintf(ctx->fp,
3930 ".Lframe2:\n"
3931 "\t.long .LECIE2-.LSCIE2\n"
3932 ".LSCIE2:\n"
3933 "\t.long 0\n"
3934 "\t.byte 0x1\n"
3935 "\t.string \"zR\"\n"
3936 "\t.uleb128 0x1\n"
3937 "\t.sleb128 -8\n"
3938 "\t.byte 30\n" /* Return address is in lr. */
3939 "\t.uleb128 1\n" /* augmentation length */
3940 "\t.byte 0x1b\n" /* pcrel|sdata4 */
3941 "\t.byte 0xc\n\t.uleb128 31\n\t.uleb128 0\n" /* def_cfa sp */
3942 "\t.align 3\n"
3943 ".LECIE2:\n\n");
3944 fprintf(ctx->fp,
3945 ".LSFDE3:\n"
3946 "\t.long .LEFDE3-.LASFDE3\n"
3947 ".LASFDE3:\n"
3948 "\t.long .LASFDE3-.Lframe2\n"
3949 "\t.long lj_vm_ffi_call-.\n"
3950 "\t.long %d\n"
3951 "\t.uleb128 0\n" /* augmentation length */
3952 "\t.byte 0xe\n\t.uleb128 32\n" /* def_cfa_offset */
3953 "\t.byte 0x9d\n\t.uleb128 4\n" /* offset fp */
3954 "\t.byte 0x9e\n\t.uleb128 3\n" /* offset lr */
3955 "\t.byte 0x93\n\t.uleb128 2\n" /* offset x19 */
3956 "\t.align 3\n"
3957 ".LEFDE3:\n\n", (int)ctx->codesz - fcofs);
3958#endif
3959 break;
3960 default:
3961 break;
3962 }
3963}
3964
diff --git a/src/vm_mips.dasc b/src/vm_mips.dasc
index 3f9c98c1..1afd6118 100644
--- a/src/vm_mips.dasc
+++ b/src/vm_mips.dasc
@@ -1,6 +1,9 @@
1|// Low-level VM code for MIPS CPUs. 1|// Low-level VM code for MIPS CPUs.
2|// Bytecode interpreter, fast functions and helper functions. 2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h 3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4|//
5|// MIPS soft-float support contributed by Djordje Kovacevic and
6|// Stefan Pejic from RT-RK.com, sponsored by Cisco Systems, Inc.
4| 7|
5|.arch mips 8|.arch mips
6|.section code_op, code_sub 9|.section code_op, code_sub
@@ -18,6 +21,12 @@
18|// Fixed register assignments for the interpreter. 21|// Fixed register assignments for the interpreter.
19|// Don't use: r0 = 0, r26/r27 = reserved, r28 = gp, r29 = sp, r31 = ra 22|// Don't use: r0 = 0, r26/r27 = reserved, r28 = gp, r29 = sp, r31 = ra
20| 23|
24|.macro .FPU, a, b
25|.if FPU
26| a, b
27|.endif
28|.endmacro
29|
21|// The following must be C callee-save (but BASE is often refetched). 30|// The following must be C callee-save (but BASE is often refetched).
22|.define BASE, r16 // Base of current Lua stack frame. 31|.define BASE, r16 // Base of current Lua stack frame.
23|.define KBASE, r17 // Constants of current Lua function. 32|.define KBASE, r17 // Constants of current Lua function.
@@ -25,13 +34,15 @@
25|.define DISPATCH, r19 // Opcode dispatch table. 34|.define DISPATCH, r19 // Opcode dispatch table.
26|.define LREG, r20 // Register holding lua_State (also in SAVE_L). 35|.define LREG, r20 // Register holding lua_State (also in SAVE_L).
27|.define MULTRES, r21 // Size of multi-result: (nresults+1)*8. 36|.define MULTRES, r21 // Size of multi-result: (nresults+1)*8.
28|// NYI: r22 currently unused.
29| 37|
30|.define JGL, r30 // On-trace: global_State + 32768. 38|.define JGL, r30 // On-trace: global_State + 32768.
31| 39|
32|// Constants for type-comparisons, stores and conversions. C callee-save. 40|// Constants for type-comparisons, stores and conversions. C callee-save.
41|.define TISNUM, r22
33|.define TISNIL, r30 42|.define TISNIL, r30
43|.if FPU
34|.define TOBIT, f30 // 2^52 + 2^51. 44|.define TOBIT, f30 // 2^52 + 2^51.
45|.endif
35| 46|
36|// The following temporaries are not saved across C calls, except for RA. 47|// The following temporaries are not saved across C calls, except for RA.
37|.define RA, r23 // Callee-save. 48|.define RA, r23 // Callee-save.
@@ -46,7 +57,7 @@
46|.define TMP2, r14 57|.define TMP2, r14
47|.define TMP3, r15 58|.define TMP3, r15
48| 59|
49|// Calling conventions. 60|// MIPS o32 calling convention.
50|.define CFUNCADDR, r25 61|.define CFUNCADDR, r25
51|.define CARG1, r4 62|.define CARG1, r4
52|.define CARG2, r5 63|.define CARG2, r5
@@ -56,13 +67,33 @@
56|.define CRET1, r2 67|.define CRET1, r2
57|.define CRET2, r3 68|.define CRET2, r3
58| 69|
70|.if ENDIAN_LE
71|.define SFRETLO, CRET1
72|.define SFRETHI, CRET2
73|.define SFARG1LO, CARG1
74|.define SFARG1HI, CARG2
75|.define SFARG2LO, CARG3
76|.define SFARG2HI, CARG4
77|.else
78|.define SFRETLO, CRET2
79|.define SFRETHI, CRET1
80|.define SFARG1LO, CARG2
81|.define SFARG1HI, CARG1
82|.define SFARG2LO, CARG4
83|.define SFARG2HI, CARG3
84|.endif
85|
86|.if FPU
59|.define FARG1, f12 87|.define FARG1, f12
60|.define FARG2, f14 88|.define FARG2, f14
61| 89|
62|.define FRET1, f0 90|.define FRET1, f0
63|.define FRET2, f2 91|.define FRET2, f2
92|.endif
64| 93|
65|// Stack layout while in interpreter. Must match with lj_frame.h. 94|// Stack layout while in interpreter. Must match with lj_frame.h.
95|.if FPU // MIPS32 hard-float.
96|
66|.define CFRAME_SPACE, 112 // Delta for sp. 97|.define CFRAME_SPACE, 112 // Delta for sp.
67| 98|
68|.define SAVE_ERRF, 124(sp) // 32 bit C frame info. 99|.define SAVE_ERRF, 124(sp) // 32 bit C frame info.
@@ -72,6 +103,20 @@
72|//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by interpreter. 103|//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by interpreter.
73|.define SAVE_GPR_, 72 // .. 72+10*4: 32 bit GPR saves. 104|.define SAVE_GPR_, 72 // .. 72+10*4: 32 bit GPR saves.
74|.define SAVE_FPR_, 24 // .. 24+6*8: 64 bit FPR saves. 105|.define SAVE_FPR_, 24 // .. 24+6*8: 64 bit FPR saves.
106|
107|.else // MIPS32 soft-float
108|
109|.define CFRAME_SPACE, 64 // Delta for sp.
110|
111|.define SAVE_ERRF, 76(sp) // 32 bit C frame info.
112|.define SAVE_NRES, 72(sp)
113|.define SAVE_CFRAME, 68(sp)
114|.define SAVE_L, 64(sp)
115|//----- 8 byte aligned, ^^^^ 16 byte register save area, owned by interpreter.
116|.define SAVE_GPR_, 24 // .. 24+10*4: 32 bit GPR saves.
117|
118|.endif
119|
75|.define SAVE_PC, 20(sp) 120|.define SAVE_PC, 20(sp)
76|.define ARG5, 16(sp) 121|.define ARG5, 16(sp)
77|.define CSAVE_4, 12(sp) 122|.define CSAVE_4, 12(sp)
@@ -83,43 +128,45 @@
83|.define ARG5_OFS, 16 128|.define ARG5_OFS, 16
84|.define SAVE_MULTRES, ARG5 129|.define SAVE_MULTRES, ARG5
85| 130|
131|//-----------------------------------------------------------------------
132|
86|.macro saveregs 133|.macro saveregs
87| addiu sp, sp, -CFRAME_SPACE 134| addiu sp, sp, -CFRAME_SPACE
88| sw ra, SAVE_GPR_+9*4(sp) 135| sw ra, SAVE_GPR_+9*4(sp)
89| sw r30, SAVE_GPR_+8*4(sp) 136| sw r30, SAVE_GPR_+8*4(sp)
90| sdc1 f30, SAVE_FPR_+5*8(sp) 137| .FPU sdc1 f30, SAVE_FPR_+5*8(sp)
91| sw r23, SAVE_GPR_+7*4(sp) 138| sw r23, SAVE_GPR_+7*4(sp)
92| sw r22, SAVE_GPR_+6*4(sp) 139| sw r22, SAVE_GPR_+6*4(sp)
93| sdc1 f28, SAVE_FPR_+4*8(sp) 140| .FPU sdc1 f28, SAVE_FPR_+4*8(sp)
94| sw r21, SAVE_GPR_+5*4(sp) 141| sw r21, SAVE_GPR_+5*4(sp)
95| sw r20, SAVE_GPR_+4*4(sp) 142| sw r20, SAVE_GPR_+4*4(sp)
96| sdc1 f26, SAVE_FPR_+3*8(sp) 143| .FPU sdc1 f26, SAVE_FPR_+3*8(sp)
97| sw r19, SAVE_GPR_+3*4(sp) 144| sw r19, SAVE_GPR_+3*4(sp)
98| sw r18, SAVE_GPR_+2*4(sp) 145| sw r18, SAVE_GPR_+2*4(sp)
99| sdc1 f24, SAVE_FPR_+2*8(sp) 146| .FPU sdc1 f24, SAVE_FPR_+2*8(sp)
100| sw r17, SAVE_GPR_+1*4(sp) 147| sw r17, SAVE_GPR_+1*4(sp)
101| sw r16, SAVE_GPR_+0*4(sp) 148| sw r16, SAVE_GPR_+0*4(sp)
102| sdc1 f22, SAVE_FPR_+1*8(sp) 149| .FPU sdc1 f22, SAVE_FPR_+1*8(sp)
103| sdc1 f20, SAVE_FPR_+0*8(sp) 150| .FPU sdc1 f20, SAVE_FPR_+0*8(sp)
104|.endmacro 151|.endmacro
105| 152|
106|.macro restoreregs_ret 153|.macro restoreregs_ret
107| lw ra, SAVE_GPR_+9*4(sp) 154| lw ra, SAVE_GPR_+9*4(sp)
108| lw r30, SAVE_GPR_+8*4(sp) 155| lw r30, SAVE_GPR_+8*4(sp)
109| ldc1 f30, SAVE_FPR_+5*8(sp) 156| .FPU ldc1 f30, SAVE_FPR_+5*8(sp)
110| lw r23, SAVE_GPR_+7*4(sp) 157| lw r23, SAVE_GPR_+7*4(sp)
111| lw r22, SAVE_GPR_+6*4(sp) 158| lw r22, SAVE_GPR_+6*4(sp)
112| ldc1 f28, SAVE_FPR_+4*8(sp) 159| .FPU ldc1 f28, SAVE_FPR_+4*8(sp)
113| lw r21, SAVE_GPR_+5*4(sp) 160| lw r21, SAVE_GPR_+5*4(sp)
114| lw r20, SAVE_GPR_+4*4(sp) 161| lw r20, SAVE_GPR_+4*4(sp)
115| ldc1 f26, SAVE_FPR_+3*8(sp) 162| .FPU ldc1 f26, SAVE_FPR_+3*8(sp)
116| lw r19, SAVE_GPR_+3*4(sp) 163| lw r19, SAVE_GPR_+3*4(sp)
117| lw r18, SAVE_GPR_+2*4(sp) 164| lw r18, SAVE_GPR_+2*4(sp)
118| ldc1 f24, SAVE_FPR_+2*8(sp) 165| .FPU ldc1 f24, SAVE_FPR_+2*8(sp)
119| lw r17, SAVE_GPR_+1*4(sp) 166| lw r17, SAVE_GPR_+1*4(sp)
120| lw r16, SAVE_GPR_+0*4(sp) 167| lw r16, SAVE_GPR_+0*4(sp)
121| ldc1 f22, SAVE_FPR_+1*8(sp) 168| .FPU ldc1 f22, SAVE_FPR_+1*8(sp)
122| ldc1 f20, SAVE_FPR_+0*8(sp) 169| .FPU ldc1 f20, SAVE_FPR_+0*8(sp)
123| jr ra 170| jr ra
124| addiu sp, sp, CFRAME_SPACE 171| addiu sp, sp, CFRAME_SPACE
125|.endmacro 172|.endmacro
@@ -138,6 +185,7 @@
138|.type NODE, Node 185|.type NODE, Node
139|.type NARGS8, int 186|.type NARGS8, int
140|.type TRACE, GCtrace 187|.type TRACE, GCtrace
188|.type SBUF, SBuf
141| 189|
142|//----------------------------------------------------------------------- 190|//-----------------------------------------------------------------------
143| 191|
@@ -152,13 +200,23 @@
152|//----------------------------------------------------------------------- 200|//-----------------------------------------------------------------------
153| 201|
154|// Endian-specific defines. 202|// Endian-specific defines.
155|.define FRAME_PC, LJ_ENDIAN_SELECT(-4,-8) 203|.if ENDIAN_LE
156|.define FRAME_FUNC, LJ_ENDIAN_SELECT(-8,-4) 204|.define FRAME_PC, -4
157|.define HI, LJ_ENDIAN_SELECT(4,0) 205|.define FRAME_FUNC, -8
158|.define LO, LJ_ENDIAN_SELECT(0,4) 206|.define HI, 4
159|.define OFS_RD, LJ_ENDIAN_SELECT(2,0) 207|.define LO, 0
160|.define OFS_RA, LJ_ENDIAN_SELECT(1,2) 208|.define OFS_RD, 2
161|.define OFS_OP, LJ_ENDIAN_SELECT(0,3) 209|.define OFS_RA, 1
210|.define OFS_OP, 0
211|.else
212|.define FRAME_PC, -8
213|.define FRAME_FUNC, -4
214|.define HI, 0
215|.define LO, 4
216|.define OFS_RD, 0
217|.define OFS_RA, 2
218|.define OFS_OP, 3
219|.endif
162| 220|
163|// Instruction decode. 221|// Instruction decode.
164|.macro decode_OP1, dst, ins; andi dst, ins, 0xff; .endmacro 222|.macro decode_OP1, dst, ins; andi dst, ins, 0xff; .endmacro
@@ -353,9 +411,11 @@ static void build_subroutines(BuildCtx *ctx)
353 |. sll TMP2, TMP2, 3 411 |. sll TMP2, TMP2, 3
354 |1: 412 |1:
355 | addiu TMP1, TMP1, -8 413 | addiu TMP1, TMP1, -8
356 | ldc1 f0, 0(RA) 414 | lw SFRETHI, HI(RA)
415 | lw SFRETLO, LO(RA)
357 | addiu RA, RA, 8 416 | addiu RA, RA, 8
358 | sdc1 f0, 0(BASE) 417 | sw SFRETHI, HI(BASE)
418 | sw SFRETLO, LO(BASE)
359 | bnez TMP1, <1 419 | bnez TMP1, <1
360 |. addiu BASE, BASE, 8 420 |. addiu BASE, BASE, 8
361 | 421 |
@@ -424,15 +484,16 @@ static void build_subroutines(BuildCtx *ctx)
424 | and sp, CARG1, AT 484 | and sp, CARG1, AT
425 |->vm_unwind_ff_eh: // Landing pad for external unwinder. 485 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
426 | lw L, SAVE_L 486 | lw L, SAVE_L
427 | lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). 487 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
488 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
428 | li TISNIL, LJ_TNIL 489 | li TISNIL, LJ_TNIL
429 | lw BASE, L->base 490 | lw BASE, L->base
430 | lw DISPATCH, L->glref // Setup pointer to dispatch table. 491 | lw DISPATCH, L->glref // Setup pointer to dispatch table.
431 | mtc1 TMP3, TOBIT 492 | .FPU mtc1 TMP3, TOBIT
432 | li TMP1, LJ_TFALSE 493 | li TMP1, LJ_TFALSE
433 | li_vmstate INTERP 494 | li_vmstate INTERP
434 | lw PC, FRAME_PC(BASE) // Fetch PC of previous frame. 495 | lw PC, FRAME_PC(BASE) // Fetch PC of previous frame.
435 | cvt.d.s TOBIT, TOBIT 496 | .FPU cvt.d.s TOBIT, TOBIT
436 | addiu RA, BASE, -8 // Results start at BASE-8. 497 | addiu RA, BASE, -8 // Results start at BASE-8.
437 | addiu DISPATCH, DISPATCH, GG_G2DISP 498 | addiu DISPATCH, DISPATCH, GG_G2DISP
438 | sw TMP1, HI(RA) // Prepend false to error message. 499 | sw TMP1, HI(RA) // Prepend false to error message.
@@ -486,21 +547,23 @@ static void build_subroutines(BuildCtx *ctx)
486 | addiu DISPATCH, DISPATCH, GG_G2DISP 547 | addiu DISPATCH, DISPATCH, GG_G2DISP
487 | sw r0, SAVE_NRES 548 | sw r0, SAVE_NRES
488 | sw r0, SAVE_ERRF 549 | sw r0, SAVE_ERRF
489 | sw TMP0, L->cframe 550 | sw CARG1, SAVE_PC // Any value outside of bytecode is ok.
490 | sw r0, SAVE_CFRAME 551 | sw r0, SAVE_CFRAME
491 | beqz TMP1, >3 552 | beqz TMP1, >3
492 |. sw CARG1, SAVE_PC // Any value outside of bytecode is ok. 553 |. sw TMP0, L->cframe
493 | 554 |
494 | // Resume after yield (like a return). 555 | // Resume after yield (like a return).
556 | sw L, DISPATCH_GL(cur_L)(DISPATCH)
495 | move RA, BASE 557 | move RA, BASE
496 | lw BASE, L->base 558 | lw BASE, L->base
559 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
497 | lw TMP1, L->top 560 | lw TMP1, L->top
498 | lw PC, FRAME_PC(BASE) 561 | lw PC, FRAME_PC(BASE)
499 | lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). 562 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
500 | subu RD, TMP1, BASE 563 | subu RD, TMP1, BASE
501 | mtc1 TMP3, TOBIT 564 | .FPU mtc1 TMP3, TOBIT
502 | sb r0, L->status 565 | sb r0, L->status
503 | cvt.d.s TOBIT, TOBIT 566 | .FPU cvt.d.s TOBIT, TOBIT
504 | li_vmstate INTERP 567 | li_vmstate INTERP
505 | addiu RD, RD, 8 568 | addiu RD, RD, 8
506 | st_vmstate 569 | st_vmstate
@@ -525,25 +588,27 @@ static void build_subroutines(BuildCtx *ctx)
525 | 588 |
526 |1: // Entry point for vm_pcall above (PC = ftype). 589 |1: // Entry point for vm_pcall above (PC = ftype).
527 | lw TMP1, L:CARG1->cframe 590 | lw TMP1, L:CARG1->cframe
528 | sw CARG3, SAVE_NRES
529 | move L, CARG1 591 | move L, CARG1
530 | sw CARG1, SAVE_L 592 | sw CARG3, SAVE_NRES
531 | move BASE, CARG2
532 | sw sp, L->cframe // Add our C frame to cframe chain.
533 | lw DISPATCH, L->glref // Setup pointer to dispatch table. 593 | lw DISPATCH, L->glref // Setup pointer to dispatch table.
594 | sw CARG1, SAVE_L
595 | move BASE, CARG2
596 | addiu DISPATCH, DISPATCH, GG_G2DISP
534 | sw CARG1, SAVE_PC // Any value outside of bytecode is ok. 597 | sw CARG1, SAVE_PC // Any value outside of bytecode is ok.
535 | sw TMP1, SAVE_CFRAME 598 | sw TMP1, SAVE_CFRAME
536 | addiu DISPATCH, DISPATCH, GG_G2DISP 599 | sw sp, L->cframe // Add our C frame to cframe chain.
537 | 600 |
538 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype). 601 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
602 | sw L, DISPATCH_GL(cur_L)(DISPATCH)
539 | lw TMP2, L->base // TMP2 = old base (used in vmeta_call). 603 | lw TMP2, L->base // TMP2 = old base (used in vmeta_call).
540 | lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). 604 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
605 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
541 | lw TMP1, L->top 606 | lw TMP1, L->top
542 | mtc1 TMP3, TOBIT 607 | .FPU mtc1 TMP3, TOBIT
543 | addu PC, PC, BASE 608 | addu PC, PC, BASE
544 | subu NARGS8:RC, TMP1, BASE 609 | subu NARGS8:RC, TMP1, BASE
545 | subu PC, PC, TMP2 // PC = frame delta + frame type 610 | subu PC, PC, TMP2 // PC = frame delta + frame type
546 | cvt.d.s TOBIT, TOBIT 611 | .FPU cvt.d.s TOBIT, TOBIT
547 | li_vmstate INTERP 612 | li_vmstate INTERP
548 | li TISNIL, LJ_TNIL 613 | li TISNIL, LJ_TNIL
549 | st_vmstate 614 | st_vmstate
@@ -566,20 +631,21 @@ static void build_subroutines(BuildCtx *ctx)
566 | lw TMP0, L:CARG1->stack 631 | lw TMP0, L:CARG1->stack
567 | sw CARG1, SAVE_L 632 | sw CARG1, SAVE_L
568 | lw TMP1, L->top 633 | lw TMP1, L->top
634 | lw DISPATCH, L->glref // Setup pointer to dispatch table.
569 | sw CARG1, SAVE_PC // Any value outside of bytecode is ok. 635 | sw CARG1, SAVE_PC // Any value outside of bytecode is ok.
570 | subu TMP0, TMP0, TMP1 // Compute -savestack(L, L->top). 636 | subu TMP0, TMP0, TMP1 // Compute -savestack(L, L->top).
571 | lw TMP1, L->cframe 637 | lw TMP1, L->cframe
572 | sw sp, L->cframe // Add our C frame to cframe chain. 638 | addiu DISPATCH, DISPATCH, GG_G2DISP
573 | sw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame. 639 | sw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame.
574 | sw r0, SAVE_ERRF // No error function. 640 | sw r0, SAVE_ERRF // No error function.
575 | move CFUNCADDR, CARG4 641 | sw TMP1, SAVE_CFRAME
642 | sw sp, L->cframe // Add our C frame to cframe chain.
643 | sw L, DISPATCH_GL(cur_L)(DISPATCH)
576 | jalr CARG4 // (lua_State *L, lua_CFunction func, void *ud) 644 | jalr CARG4 // (lua_State *L, lua_CFunction func, void *ud)
577 |. sw TMP1, SAVE_CFRAME 645 |. move CFUNCADDR, CARG4
578 | move BASE, CRET1 646 | move BASE, CRET1
579 | lw DISPATCH, L->glref // Setup pointer to dispatch table.
580 | li PC, FRAME_CP
581 | bnez CRET1, <3 // Else continue with the call. 647 | bnez CRET1, <3 // Else continue with the call.
582 |. addiu DISPATCH, DISPATCH, GG_G2DISP 648 |. li PC, FRAME_CP
583 | b ->vm_leave_cp // No base? Just remove C frame. 649 | b ->vm_leave_cp // No base? Just remove C frame.
584 |. nop 650 |. nop
585 | 651 |
@@ -624,7 +690,8 @@ static void build_subroutines(BuildCtx *ctx)
624 |->cont_cat: // RA = resultptr, RB = meta base 690 |->cont_cat: // RA = resultptr, RB = meta base
625 | lw INS, -4(PC) 691 | lw INS, -4(PC)
626 | addiu CARG2, RB, -16 692 | addiu CARG2, RB, -16
627 | ldc1 f0, 0(RA) 693 | lw SFRETHI, HI(RA)
694 | lw SFRETLO, LO(RA)
628 | decode_RB8a MULTRES, INS 695 | decode_RB8a MULTRES, INS
629 | decode_RA8a RA, INS 696 | decode_RA8a RA, INS
630 | decode_RB8b MULTRES 697 | decode_RB8b MULTRES
@@ -632,11 +699,13 @@ static void build_subroutines(BuildCtx *ctx)
632 | addu TMP1, BASE, MULTRES 699 | addu TMP1, BASE, MULTRES
633 | sw BASE, L->base 700 | sw BASE, L->base
634 | subu CARG3, CARG2, TMP1 701 | subu CARG3, CARG2, TMP1
702 | sw SFRETHI, HI(CARG2)
635 | bne TMP1, CARG2, ->BC_CAT_Z 703 | bne TMP1, CARG2, ->BC_CAT_Z
636 |. sdc1 f0, 0(CARG2) 704 |. sw SFRETLO, LO(CARG2)
637 | addu RA, BASE, RA 705 | addu RA, BASE, RA
706 | sw SFRETHI, HI(RA)
638 | b ->cont_nop 707 | b ->cont_nop
639 |. sdc1 f0, 0(RA) 708 |. sw SFRETLO, LO(RA)
640 | 709 |
641 |//-- Table indexing metamethods ----------------------------------------- 710 |//-- Table indexing metamethods -----------------------------------------
642 | 711 |
@@ -659,10 +728,9 @@ static void build_subroutines(BuildCtx *ctx)
659 |. sw TMP1, HI(CARG3) 728 |. sw TMP1, HI(CARG3)
660 | 729 |
661 |->vmeta_tgetb: // TMP0 = index 730 |->vmeta_tgetb: // TMP0 = index
662 | mtc1 TMP0, f0
663 | cvt.d.w f0, f0
664 | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) 731 | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
665 | sdc1 f0, 0(CARG3) 732 | sw TMP0, LO(CARG3)
733 | sw TISNUM, HI(CARG3)
666 | 734 |
667 |->vmeta_tgetv: 735 |->vmeta_tgetv:
668 |1: 736 |1:
@@ -674,9 +742,11 @@ static void build_subroutines(BuildCtx *ctx)
674 | // Returns TValue * (finished) or NULL (metamethod). 742 | // Returns TValue * (finished) or NULL (metamethod).
675 | beqz CRET1, >3 743 | beqz CRET1, >3
676 |. addiu TMP1, BASE, -FRAME_CONT 744 |. addiu TMP1, BASE, -FRAME_CONT
677 | ldc1 f0, 0(CRET1) 745 | lw SFARG1HI, HI(CRET1)
746 | lw SFARG2HI, LO(CRET1)
678 | ins_next1 747 | ins_next1
679 | sdc1 f0, 0(RA) 748 | sw SFARG1HI, HI(RA)
749 | sw SFARG2HI, LO(RA)
680 | ins_next2 750 | ins_next2
681 | 751 |
682 |3: // Call __index metamethod. 752 |3: // Call __index metamethod.
@@ -688,6 +758,17 @@ static void build_subroutines(BuildCtx *ctx)
688 | b ->vm_call_dispatch_f 758 | b ->vm_call_dispatch_f
689 |. li NARGS8:RC, 16 // 2 args for func(t, k). 759 |. li NARGS8:RC, 16 // 2 args for func(t, k).
690 | 760 |
761 |->vmeta_tgetr:
762 | load_got lj_tab_getinth
763 | call_intern lj_tab_getinth // (GCtab *t, int32_t key)
764 |. nop
765 | // Returns cTValue * or NULL.
766 | beqz CRET1, ->BC_TGETR_Z
767 |. move SFARG2HI, TISNIL
768 | lw SFARG2HI, HI(CRET1)
769 | b ->BC_TGETR_Z
770 |. lw SFARG2LO, LO(CRET1)
771 |
691 |//----------------------------------------------------------------------- 772 |//-----------------------------------------------------------------------
692 | 773 |
693 |->vmeta_tsets1: 774 |->vmeta_tsets1:
@@ -709,10 +790,9 @@ static void build_subroutines(BuildCtx *ctx)
709 |. sw TMP1, HI(CARG3) 790 |. sw TMP1, HI(CARG3)
710 | 791 |
711 |->vmeta_tsetb: // TMP0 = index 792 |->vmeta_tsetb: // TMP0 = index
712 | mtc1 TMP0, f0
713 | cvt.d.w f0, f0
714 | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) 793 | addiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
715 | sdc1 f0, 0(CARG3) 794 | sw TMP0, LO(CARG3)
795 | sw TISNUM, HI(CARG3)
716 | 796 |
717 |->vmeta_tsetv: 797 |->vmeta_tsetv:
718 |1: 798 |1:
@@ -722,11 +802,13 @@ static void build_subroutines(BuildCtx *ctx)
722 | call_intern lj_meta_tset // (lua_State *L, TValue *o, TValue *k) 802 | call_intern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
723 |. move CARG1, L 803 |. move CARG1, L
724 | // Returns TValue * (finished) or NULL (metamethod). 804 | // Returns TValue * (finished) or NULL (metamethod).
805 | lw SFARG1HI, HI(RA)
725 | beqz CRET1, >3 806 | beqz CRET1, >3
726 |. ldc1 f0, 0(RA) 807 |. lw SFARG1LO, LO(RA)
727 | // NOBARRIER: lj_meta_tset ensures the table is not black. 808 | // NOBARRIER: lj_meta_tset ensures the table is not black.
728 | ins_next1 809 | ins_next1
729 | sdc1 f0, 0(CRET1) 810 | sw SFARG1HI, HI(CRET1)
811 | sw SFARG1LO, LO(CRET1)
730 | ins_next2 812 | ins_next2
731 | 813 |
732 |3: // Call __newindex metamethod. 814 |3: // Call __newindex metamethod.
@@ -736,14 +818,27 @@ static void build_subroutines(BuildCtx *ctx)
736 | sw PC, -16+HI(BASE) // [cont|PC] 818 | sw PC, -16+HI(BASE) // [cont|PC]
737 | subu PC, BASE, TMP1 819 | subu PC, BASE, TMP1
738 | lw LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here. 820 | lw LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
739 | sdc1 f0, 16(BASE) // Copy value to third argument. 821 | sw SFARG1HI, 16+HI(BASE) // Copy value to third argument.
822 | sw SFARG1LO, 16+LO(BASE)
740 | b ->vm_call_dispatch_f 823 | b ->vm_call_dispatch_f
741 |. li NARGS8:RC, 24 // 3 args for func(t, k, v) 824 |. li NARGS8:RC, 24 // 3 args for func(t, k, v)
742 | 825 |
826 |->vmeta_tsetr:
827 | load_got lj_tab_setinth
828 | sw BASE, L->base
829 | sw PC, SAVE_PC
830 | call_intern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
831 |. move CARG1, L
832 | // Returns TValue *.
833 | b ->BC_TSETR_Z
834 |. nop
835 |
743 |//-- Comparison metamethods --------------------------------------------- 836 |//-- Comparison metamethods ---------------------------------------------
744 | 837 |
745 |->vmeta_comp: 838 |->vmeta_comp:
746 | // CARG2, CARG3 are already set by BC_ISLT/BC_ISGE/BC_ISLE/BC_ISGT. 839 | // RA/RD point to o1/o2.
840 | move CARG2, RA
841 | move CARG3, RD
747 | load_got lj_meta_comp 842 | load_got lj_meta_comp
748 | addiu PC, PC, -4 843 | addiu PC, PC, -4
749 | sw BASE, L->base 844 | sw BASE, L->base
@@ -769,11 +864,13 @@ static void build_subroutines(BuildCtx *ctx)
769 | 864 |
770 |->cont_ra: // RA = resultptr 865 |->cont_ra: // RA = resultptr
771 | lbu TMP1, -4+OFS_RA(PC) 866 | lbu TMP1, -4+OFS_RA(PC)
772 | ldc1 f0, 0(RA) 867 | lw SFRETHI, HI(RA)
868 | lw SFRETLO, LO(RA)
773 | sll TMP1, TMP1, 3 869 | sll TMP1, TMP1, 3
774 | addu TMP1, BASE, TMP1 870 | addu TMP1, BASE, TMP1
871 | sw SFRETHI, HI(TMP1)
775 | b ->cont_nop 872 | b ->cont_nop
776 |. sdc1 f0, 0(TMP1) 873 |. sw SFRETLO, LO(TMP1)
777 | 874 |
778 |->cont_condt: // RA = resultptr 875 |->cont_condt: // RA = resultptr
779 | lw TMP0, HI(RA) 876 | lw TMP0, HI(RA)
@@ -788,8 +885,11 @@ static void build_subroutines(BuildCtx *ctx)
788 |. addiu TMP2, AT, -1 // Branch if result is false. 885 |. addiu TMP2, AT, -1 // Branch if result is false.
789 | 886 |
790 |->vmeta_equal: 887 |->vmeta_equal:
791 | // CARG2, CARG3, CARG4 are already set by BC_ISEQV/BC_ISNEV. 888 | // SFARG1LO/SFARG2LO point to o1/o2. TMP0 is set to 0/1.
792 | load_got lj_meta_equal 889 | load_got lj_meta_equal
890 | move CARG2, SFARG1LO
891 | move CARG3, SFARG2LO
892 | move CARG4, TMP0
793 | addiu PC, PC, -4 893 | addiu PC, PC, -4
794 | sw BASE, L->base 894 | sw BASE, L->base
795 | sw PC, SAVE_PC 895 | sw PC, SAVE_PC
@@ -813,17 +913,31 @@ static void build_subroutines(BuildCtx *ctx)
813 |. nop 913 |. nop
814 |.endif 914 |.endif
815 | 915 |
916 |->vmeta_istype:
917 | load_got lj_meta_istype
918 | addiu PC, PC, -4
919 | sw BASE, L->base
920 | srl CARG2, RA, 3
921 | srl CARG3, RD, 3
922 | sw PC, SAVE_PC
923 | call_intern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
924 |. move CARG1, L
925 | b ->cont_nop
926 |. nop
927 |
816 |//-- Arithmetic metamethods --------------------------------------------- 928 |//-- Arithmetic metamethods ---------------------------------------------
817 | 929 |
818 |->vmeta_unm: 930 |->vmeta_unm:
819 | move CARG4, CARG3 931 | move RC, RB
820 | 932 |
821 |->vmeta_arith: 933 |->vmeta_arith:
822 | load_got lj_meta_arith 934 | load_got lj_meta_arith
823 | decode_OP1 TMP0, INS 935 | decode_OP1 TMP0, INS
824 | sw BASE, L->base 936 | sw BASE, L->base
825 | sw PC, SAVE_PC
826 | move CARG2, RA 937 | move CARG2, RA
938 | sw PC, SAVE_PC
939 | move CARG3, RB
940 | move CARG4, RC
827 | sw TMP0, ARG5 941 | sw TMP0, ARG5
828 | call_intern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op) 942 | call_intern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
829 |. move CARG1, L 943 |. move CARG1, L
@@ -931,40 +1045,52 @@ static void build_subroutines(BuildCtx *ctx)
931 | 1045 |
932 |.macro .ffunc_1, name 1046 |.macro .ffunc_1, name
933 |->ff_ .. name: 1047 |->ff_ .. name:
1048 | lw SFARG1HI, HI(BASE)
934 | beqz NARGS8:RC, ->fff_fallback 1049 | beqz NARGS8:RC, ->fff_fallback
935 |. lw CARG3, HI(BASE) 1050 |. lw SFARG1LO, LO(BASE)
936 | lw CARG1, LO(BASE)
937 |.endmacro 1051 |.endmacro
938 | 1052 |
939 |.macro .ffunc_2, name 1053 |.macro .ffunc_2, name
940 |->ff_ .. name: 1054 |->ff_ .. name:
941 | sltiu AT, NARGS8:RC, 16 1055 | sltiu AT, NARGS8:RC, 16
942 | lw CARG3, HI(BASE) 1056 | lw SFARG1HI, HI(BASE)
943 | bnez AT, ->fff_fallback 1057 | bnez AT, ->fff_fallback
944 |. lw CARG4, 8+HI(BASE) 1058 |. lw SFARG2HI, 8+HI(BASE)
945 | lw CARG1, LO(BASE) 1059 | lw SFARG1LO, LO(BASE)
946 | lw CARG2, 8+LO(BASE) 1060 | lw SFARG2LO, 8+LO(BASE)
947 |.endmacro 1061 |.endmacro
948 | 1062 |
949 |.macro .ffunc_n, name // Caveat: has delay slot! 1063 |.macro .ffunc_n, name // Caveat: has delay slot!
950 |->ff_ .. name: 1064 |->ff_ .. name:
951 | lw CARG3, HI(BASE) 1065 | lw SFARG1HI, HI(BASE)
1066 |.if FPU
1067 | ldc1 FARG1, 0(BASE)
1068 |.else
1069 | lw SFARG1LO, LO(BASE)
1070 |.endif
952 | beqz NARGS8:RC, ->fff_fallback 1071 | beqz NARGS8:RC, ->fff_fallback
953 |. ldc1 FARG1, 0(BASE) 1072 |. sltiu AT, SFARG1HI, LJ_TISNUM
954 | sltiu AT, CARG3, LJ_TISNUM
955 | beqz AT, ->fff_fallback 1073 | beqz AT, ->fff_fallback
956 |.endmacro 1074 |.endmacro
957 | 1075 |
958 |.macro .ffunc_nn, name // Caveat: has delay slot! 1076 |.macro .ffunc_nn, name // Caveat: has delay slot!
959 |->ff_ .. name: 1077 |->ff_ .. name:
960 | sltiu AT, NARGS8:RC, 16 1078 | sltiu AT, NARGS8:RC, 16
961 | lw CARG3, HI(BASE) 1079 | lw SFARG1HI, HI(BASE)
962 | bnez AT, ->fff_fallback 1080 | bnez AT, ->fff_fallback
963 |. lw CARG4, 8+HI(BASE) 1081 |. lw SFARG2HI, 8+HI(BASE)
964 | ldc1 FARG1, 0(BASE) 1082 | sltiu TMP0, SFARG1HI, LJ_TISNUM
965 | ldc1 FARG2, 8(BASE) 1083 |.if FPU
966 | sltiu TMP0, CARG3, LJ_TISNUM 1084 | ldc1 FARG1, 0(BASE)
967 | sltiu TMP1, CARG4, LJ_TISNUM 1085 |.else
1086 | lw SFARG1LO, LO(BASE)
1087 |.endif
1088 | sltiu TMP1, SFARG2HI, LJ_TISNUM
1089 |.if FPU
1090 | ldc1 FARG2, 8(BASE)
1091 |.else
1092 | lw SFARG2LO, 8+LO(BASE)
1093 |.endif
968 | and TMP0, TMP0, TMP1 1094 | and TMP0, TMP0, TMP1
969 | beqz TMP0, ->fff_fallback 1095 | beqz TMP0, ->fff_fallback
970 |.endmacro 1096 |.endmacro
@@ -980,52 +1106,54 @@ static void build_subroutines(BuildCtx *ctx)
980 |//-- Base library: checks ----------------------------------------------- 1106 |//-- Base library: checks -----------------------------------------------
981 | 1107 |
982 |.ffunc_1 assert 1108 |.ffunc_1 assert
983 | sltiu AT, CARG3, LJ_TISTRUECOND 1109 | sltiu AT, SFARG1HI, LJ_TISTRUECOND
984 | beqz AT, ->fff_fallback 1110 | beqz AT, ->fff_fallback
985 |. addiu RA, BASE, -8 1111 |. addiu RA, BASE, -8
986 | lw PC, FRAME_PC(BASE) 1112 | lw PC, FRAME_PC(BASE)
987 | addiu RD, NARGS8:RC, 8 // Compute (nresults+1)*8. 1113 | addiu RD, NARGS8:RC, 8 // Compute (nresults+1)*8.
988 | addu TMP2, RA, NARGS8:RC 1114 | addu TMP2, RA, NARGS8:RC
989 | sw CARG3, HI(RA) 1115 | sw SFARG1HI, HI(RA)
990 | addiu TMP1, BASE, 8 1116 | addiu TMP1, BASE, 8
991 | beq BASE, TMP2, ->fff_res // Done if exactly 1 argument. 1117 | beq BASE, TMP2, ->fff_res // Done if exactly 1 argument.
992 |. sw CARG1, LO(RA) 1118 |. sw SFARG1LO, LO(RA)
993 |1: 1119 |1:
994 | ldc1 f0, 0(TMP1) 1120 | lw SFRETHI, HI(TMP1)
995 | sdc1 f0, -8(TMP1) 1121 | lw SFRETLO, LO(TMP1)
1122 | sw SFRETHI, -8+HI(TMP1)
1123 | sw SFRETLO, -8+LO(TMP1)
996 | bne TMP1, TMP2, <1 1124 | bne TMP1, TMP2, <1
997 |. addiu TMP1, TMP1, 8 1125 |. addiu TMP1, TMP1, 8
998 | b ->fff_res 1126 | b ->fff_res
999 |. nop 1127 |. nop
1000 | 1128 |
1001 |.ffunc type 1129 |.ffunc type
1002 | lw CARG3, HI(BASE) 1130 | lw SFARG1HI, HI(BASE)
1003 | li TMP1, LJ_TISNUM
1004 | beqz NARGS8:RC, ->fff_fallback 1131 | beqz NARGS8:RC, ->fff_fallback
1005 |. sltiu TMP0, CARG3, LJ_TISNUM 1132 |. sltiu TMP0, SFARG1HI, LJ_TISNUM
1006 | movz TMP1, CARG3, TMP0 1133 | movn SFARG1HI, TISNUM, TMP0
1007 | not TMP1, TMP1 1134 | not TMP1, SFARG1HI
1008 | sll TMP1, TMP1, 3 1135 | sll TMP1, TMP1, 3
1009 | addu TMP1, CFUNC:RB, TMP1 1136 | addu TMP1, CFUNC:RB, TMP1
1010 | b ->fff_resn 1137 | lw SFARG1HI, CFUNC:TMP1->upvalue[0].u32.hi
1011 |. ldc1 FRET1, CFUNC:TMP1->upvalue 1138 | b ->fff_restv
1139 |. lw SFARG1LO, CFUNC:TMP1->upvalue[0].u32.lo
1012 | 1140 |
1013 |//-- Base library: getters and setters --------------------------------- 1141 |//-- Base library: getters and setters ---------------------------------
1014 | 1142 |
1015 |.ffunc_1 getmetatable 1143 |.ffunc_1 getmetatable
1016 | li AT, LJ_TTAB 1144 | li AT, LJ_TTAB
1017 | bne CARG3, AT, >6 1145 | bne SFARG1HI, AT, >6
1018 |. li AT, LJ_TUDATA 1146 |. li AT, LJ_TUDATA
1019 |1: // Field metatable must be at same offset for GCtab and GCudata! 1147 |1: // Field metatable must be at same offset for GCtab and GCudata!
1020 | lw TAB:CARG1, TAB:CARG1->metatable 1148 | lw TAB:SFARG1LO, TAB:SFARG1LO->metatable
1021 |2: 1149 |2:
1022 | lw STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH) 1150 | lw STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH)
1023 | beqz TAB:CARG1, ->fff_restv 1151 | beqz TAB:SFARG1LO, ->fff_restv
1024 |. li CARG3, LJ_TNIL 1152 |. li SFARG1HI, LJ_TNIL
1025 | lw TMP0, TAB:CARG1->hmask 1153 | lw TMP0, TAB:SFARG1LO->hmask
1026 | li CARG3, LJ_TTAB // Use metatable as default result. 1154 | li SFARG1HI, LJ_TTAB // Use metatable as default result.
1027 | lw TMP1, STR:RC->hash 1155 | lw TMP1, STR:RC->hash
1028 | lw NODE:TMP2, TAB:CARG1->node 1156 | lw NODE:TMP2, TAB:SFARG1LO->node
1029 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask 1157 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
1030 | sll TMP0, TMP1, 5 1158 | sll TMP0, TMP1, 5
1031 | sll TMP1, TMP1, 3 1159 | sll TMP1, TMP1, 3
@@ -1037,7 +1165,7 @@ static void build_subroutines(BuildCtx *ctx)
1037 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) 1165 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2)
1038 | lw NODE:TMP3, NODE:TMP2->next 1166 | lw NODE:TMP3, NODE:TMP2->next
1039 | bne CARG4, AT, >4 1167 | bne CARG4, AT, >4
1040 |. lw CARG2, offsetof(Node, val)+HI(NODE:TMP2) 1168 |. lw CARG3, offsetof(Node, val)+HI(NODE:TMP2)
1041 | beq TMP0, STR:RC, >5 1169 | beq TMP0, STR:RC, >5
1042 |. lw TMP1, offsetof(Node, val)+LO(NODE:TMP2) 1170 |. lw TMP1, offsetof(Node, val)+LO(NODE:TMP2)
1043 |4: 1171 |4:
@@ -1046,36 +1174,35 @@ static void build_subroutines(BuildCtx *ctx)
1046 | b <3 1174 | b <3
1047 |. nop 1175 |. nop
1048 |5: 1176 |5:
1049 | beq CARG2, TISNIL, ->fff_restv // Ditto for nil value. 1177 | beq CARG3, TISNIL, ->fff_restv // Ditto for nil value.
1050 |. nop 1178 |. nop
1051 | move CARG3, CARG2 // Return value of mt.__metatable. 1179 | move SFARG1HI, CARG3 // Return value of mt.__metatable.
1052 | b ->fff_restv 1180 | b ->fff_restv
1053 |. move CARG1, TMP1 1181 |. move SFARG1LO, TMP1
1054 | 1182 |
1055 |6: 1183 |6:
1056 | beq CARG3, AT, <1 1184 | beq SFARG1HI, AT, <1
1057 |. sltiu TMP0, CARG3, LJ_TISNUM 1185 |. sltu AT, TISNUM, SFARG1HI
1058 | li TMP1, LJ_TISNUM 1186 | movz SFARG1HI, TISNUM, AT
1059 | movz TMP1, CARG3, TMP0 1187 | not TMP1, SFARG1HI
1060 | not TMP1, TMP1
1061 | sll TMP1, TMP1, 2 1188 | sll TMP1, TMP1, 2
1062 | addu TMP1, DISPATCH, TMP1 1189 | addu TMP1, DISPATCH, TMP1
1063 | b <2 1190 | b <2
1064 |. lw TAB:CARG1, DISPATCH_GL(gcroot[GCROOT_BASEMT])(TMP1) 1191 |. lw TAB:SFARG1LO, DISPATCH_GL(gcroot[GCROOT_BASEMT])(TMP1)
1065 | 1192 |
1066 |.ffunc_2 setmetatable 1193 |.ffunc_2 setmetatable
1067 | // Fast path: no mt for table yet and not clearing the mt. 1194 | // Fast path: no mt for table yet and not clearing the mt.
1068 | li AT, LJ_TTAB 1195 | li AT, LJ_TTAB
1069 | bne CARG3, AT, ->fff_fallback 1196 | bne SFARG1HI, AT, ->fff_fallback
1070 |. addiu CARG4, CARG4, -LJ_TTAB 1197 |. addiu SFARG2HI, SFARG2HI, -LJ_TTAB
1071 | lw TAB:TMP1, TAB:CARG1->metatable 1198 | lw TAB:TMP1, TAB:SFARG1LO->metatable
1072 | lbu TMP3, TAB:CARG1->marked 1199 | lbu TMP3, TAB:SFARG1LO->marked
1073 | or AT, CARG4, TAB:TMP1 1200 | or AT, SFARG2HI, TAB:TMP1
1074 | bnez AT, ->fff_fallback 1201 | bnez AT, ->fff_fallback
1075 |. andi AT, TMP3, LJ_GC_BLACK // isblack(table) 1202 |. andi AT, TMP3, LJ_GC_BLACK // isblack(table)
1076 | beqz AT, ->fff_restv 1203 | beqz AT, ->fff_restv
1077 |. sw TAB:CARG2, TAB:CARG1->metatable 1204 |. sw TAB:SFARG2LO, TAB:SFARG1LO->metatable
1078 | barrierback TAB:CARG1, TMP3, TMP0, ->fff_restv 1205 | barrierback TAB:SFARG1LO, TMP3, TMP0, ->fff_restv
1079 | 1206 |
1080 |.ffunc rawget 1207 |.ffunc rawget
1081 | lw CARG4, HI(BASE) 1208 | lw CARG4, HI(BASE)
@@ -1089,44 +1216,44 @@ static void build_subroutines(BuildCtx *ctx)
1089 | call_intern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key) 1216 | call_intern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
1090 |. move CARG1, L 1217 |. move CARG1, L
1091 | // Returns cTValue *. 1218 | // Returns cTValue *.
1092 | b ->fff_resn 1219 | lw SFARG1HI, HI(CRET1)
1093 |. ldc1 FRET1, 0(CRET1) 1220 | b ->fff_restv
1221 |. lw SFARG1LO, LO(CRET1)
1094 | 1222 |
1095 |//-- Base library: conversions ------------------------------------------ 1223 |//-- Base library: conversions ------------------------------------------
1096 | 1224 |
1097 |.ffunc tonumber 1225 |.ffunc tonumber
1098 | // Only handles the number case inline (without a base argument). 1226 | // Only handles the number case inline (without a base argument).
1099 | lw CARG1, HI(BASE) 1227 | lw CARG1, HI(BASE)
1100 | xori AT, NARGS8:RC, 8 1228 | xori AT, NARGS8:RC, 8 // Exactly one number argument.
1101 | sltiu CARG1, CARG1, LJ_TISNUM 1229 | sltu TMP0, TISNUM, CARG1
1102 | movn CARG1, r0, AT 1230 | or AT, AT, TMP0
1103 | beqz CARG1, ->fff_fallback // Exactly one number argument. 1231 | bnez AT, ->fff_fallback
1104 |. ldc1 FRET1, 0(BASE) 1232 |. lw SFARG1HI, HI(BASE)
1105 | b ->fff_resn 1233 | b ->fff_restv
1106 |. nop 1234 |. lw SFARG1LO, LO(BASE)
1107 | 1235 |
1108 |.ffunc_1 tostring 1236 |.ffunc_1 tostring
1109 | // Only handles the string or number case inline. 1237 | // Only handles the string or number case inline.
1110 | li AT, LJ_TSTR 1238 | li AT, LJ_TSTR
1111 | // A __tostring method in the string base metatable is ignored. 1239 | // A __tostring method in the string base metatable is ignored.
1112 | beq CARG3, AT, ->fff_restv // String key? 1240 | beq SFARG1HI, AT, ->fff_restv // String key?
1113 | // Handle numbers inline, unless a number base metatable is present. 1241 | // Handle numbers inline, unless a number base metatable is present.
1114 |. lw TMP1, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH) 1242 |. lw TMP1, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH)
1115 | sltiu TMP0, CARG3, LJ_TISNUM 1243 | sltu TMP0, TISNUM, SFARG1HI
1116 | sltiu TMP1, TMP1, 1 1244 | or TMP0, TMP0, TMP1
1117 | and TMP0, TMP0, TMP1 1245 | bnez TMP0, ->fff_fallback
1118 | beqz TMP0, ->fff_fallback
1119 |. sw BASE, L->base // Add frame since C call can throw. 1246 |. sw BASE, L->base // Add frame since C call can throw.
1120 | ffgccheck 1247 | ffgccheck
1121 |. sw PC, SAVE_PC // Redundant (but a defined value). 1248 |. sw PC, SAVE_PC // Redundant (but a defined value).
1122 | load_got lj_str_fromnum 1249 | load_got lj_strfmt_number
1123 | move CARG1, L 1250 | move CARG1, L
1124 | call_intern lj_str_fromnum // (lua_State *L, lua_Number *np) 1251 | call_intern lj_strfmt_number // (lua_State *L, cTValue *o)
1125 |. move CARG2, BASE 1252 |. move CARG2, BASE
1126 | // Returns GCstr *. 1253 | // Returns GCstr *.
1127 | li CARG3, LJ_TSTR 1254 | li SFARG1HI, LJ_TSTR
1128 | b ->fff_restv 1255 | b ->fff_restv
1129 |. move CARG1, CRET1 1256 |. move SFARG1LO, CRET1
1130 | 1257 |
1131 |//-- Base library: iterators ------------------------------------------- 1258 |//-- Base library: iterators -------------------------------------------
1132 | 1259 |
@@ -1148,31 +1275,38 @@ static void build_subroutines(BuildCtx *ctx)
1148 |. move CARG1, L 1275 |. move CARG1, L
1149 | // Returns 0 at end of traversal. 1276 | // Returns 0 at end of traversal.
1150 | beqz CRET1, ->fff_restv // End of traversal: return nil. 1277 | beqz CRET1, ->fff_restv // End of traversal: return nil.
1151 |. li CARG3, LJ_TNIL 1278 |. li SFARG1HI, LJ_TNIL
1152 | ldc1 f0, 8(BASE) // Copy key and value to results. 1279 | lw TMP0, 8+HI(BASE)
1280 | lw TMP1, 8+LO(BASE)
1153 | addiu RA, BASE, -8 1281 | addiu RA, BASE, -8
1154 | ldc1 f2, 16(BASE) 1282 | lw TMP2, 16+HI(BASE)
1155 | li RD, (2+1)*8 1283 | lw TMP3, 16+LO(BASE)
1156 | sdc1 f0, 0(RA) 1284 | sw TMP0, HI(RA)
1285 | sw TMP1, LO(RA)
1286 | sw TMP2, 8+HI(RA)
1287 | sw TMP3, 8+LO(RA)
1157 | b ->fff_res 1288 | b ->fff_res
1158 |. sdc1 f2, 8(RA) 1289 |. li RD, (2+1)*8
1159 | 1290 |
1160 |.ffunc_1 pairs 1291 |.ffunc_1 pairs
1161 | li AT, LJ_TTAB 1292 | li AT, LJ_TTAB
1162 | bne CARG3, AT, ->fff_fallback 1293 | bne SFARG1HI, AT, ->fff_fallback
1163 |. lw PC, FRAME_PC(BASE) 1294 |. lw PC, FRAME_PC(BASE)
1164#if LJ_52 1295#if LJ_52
1165 | lw TAB:TMP2, TAB:CARG1->metatable 1296 | lw TAB:TMP2, TAB:SFARG1LO->metatable
1166 | ldc1 f0, CFUNC:RB->upvalue[0] 1297 | lw TMP0, CFUNC:RB->upvalue[0].u32.hi
1298 | lw TMP1, CFUNC:RB->upvalue[0].u32.lo
1167 | bnez TAB:TMP2, ->fff_fallback 1299 | bnez TAB:TMP2, ->fff_fallback
1168#else 1300#else
1169 | ldc1 f0, CFUNC:RB->upvalue[0] 1301 | lw TMP0, CFUNC:RB->upvalue[0].u32.hi
1302 | lw TMP1, CFUNC:RB->upvalue[0].u32.lo
1170#endif 1303#endif
1171 |. addiu RA, BASE, -8 1304 |. addiu RA, BASE, -8
1172 | sw TISNIL, 8+HI(BASE) 1305 | sw TISNIL, 8+HI(BASE)
1173 | li RD, (3+1)*8 1306 | sw TMP0, HI(RA)
1307 | sw TMP1, LO(RA)
1174 | b ->fff_res 1308 | b ->fff_res
1175 |. sdc1 f0, 0(RA) 1309 |. li RD, (3+1)*8
1176 | 1310 |
1177 |.ffunc ipairs_aux 1311 |.ffunc ipairs_aux
1178 | sltiu AT, NARGS8:RC, 16 1312 | sltiu AT, NARGS8:RC, 16
@@ -1180,35 +1314,32 @@ static void build_subroutines(BuildCtx *ctx)
1180 | lw TAB:CARG1, LO(BASE) 1314 | lw TAB:CARG1, LO(BASE)
1181 | lw CARG4, 8+HI(BASE) 1315 | lw CARG4, 8+HI(BASE)
1182 | bnez AT, ->fff_fallback 1316 | bnez AT, ->fff_fallback
1183 |. ldc1 FARG2, 8(BASE) 1317 |. addiu CARG3, CARG3, -LJ_TTAB
1184 | addiu CARG3, CARG3, -LJ_TTAB 1318 | xor CARG4, CARG4, TISNUM
1185 | sltiu AT, CARG4, LJ_TISNUM 1319 | and AT, CARG3, CARG4
1186 | li TMP0, 1 1320 | bnez AT, ->fff_fallback
1187 | movn AT, r0, CARG3
1188 | mtc1 TMP0, FARG1
1189 | beqz AT, ->fff_fallback
1190 |. lw PC, FRAME_PC(BASE) 1321 |. lw PC, FRAME_PC(BASE)
1191 | cvt.w.d FRET1, FARG2 1322 | lw TMP2, 8+LO(BASE)
1192 | cvt.d.w FARG1, FARG1
1193 | lw TMP0, TAB:CARG1->asize 1323 | lw TMP0, TAB:CARG1->asize
1194 | lw TMP1, TAB:CARG1->array 1324 | lw TMP1, TAB:CARG1->array
1195 | mfc1 TMP2, FRET1
1196 | addiu RA, BASE, -8
1197 | add.d FARG2, FARG2, FARG1
1198 | addiu TMP2, TMP2, 1 1325 | addiu TMP2, TMP2, 1
1326 | sw TISNUM, -8+HI(BASE)
1199 | sltu AT, TMP2, TMP0 1327 | sltu AT, TMP2, TMP0
1328 | sw TMP2, -8+LO(BASE)
1329 | beqz AT, >2 // Not in array part?
1330 |. addiu RA, BASE, -8
1200 | sll TMP3, TMP2, 3 1331 | sll TMP3, TMP2, 3
1201 | addu TMP3, TMP1, TMP3 1332 | addu TMP3, TMP1, TMP3
1202 | beqz AT, >2 // Not in array part? 1333 | lw TMP1, HI(TMP3)
1203 |. sdc1 FARG2, 0(RA) 1334 | lw TMP2, LO(TMP3)
1204 | lw TMP2, HI(TMP3)
1205 | ldc1 f0, 0(TMP3)
1206 |1: 1335 |1:
1207 | beq TMP2, TISNIL, ->fff_res // End of iteration, return 0 results. 1336 | beq TMP1, TISNIL, ->fff_res // End of iteration, return 0 results.
1208 |. li RD, (0+1)*8 1337 |. li RD, (0+1)*8
1209 | li RD, (2+1)*8 1338 | sw TMP1, 8+HI(RA)
1339 | sw TMP2, 8+LO(RA)
1210 | b ->fff_res 1340 | b ->fff_res
1211 |. sdc1 f0, 8(RA) 1341 |. li RD, (2+1)*8
1342 |
1212 |2: // Check for empty hash part first. Otherwise call C function. 1343 |2: // Check for empty hash part first. Otherwise call C function.
1213 | lw TMP0, TAB:CARG1->hmask 1344 | lw TMP0, TAB:CARG1->hmask
1214 | load_got lj_tab_getinth 1345 | load_got lj_tab_getinth
@@ -1219,27 +1350,30 @@ static void build_subroutines(BuildCtx *ctx)
1219 | // Returns cTValue * or NULL. 1350 | // Returns cTValue * or NULL.
1220 | beqz CRET1, ->fff_res 1351 | beqz CRET1, ->fff_res
1221 |. li RD, (0+1)*8 1352 |. li RD, (0+1)*8
1222 | lw TMP2, HI(CRET1) 1353 | lw TMP1, HI(CRET1)
1223 | b <1 1354 | b <1
1224 |. ldc1 f0, 0(CRET1) 1355 |. lw TMP2, LO(CRET1)
1225 | 1356 |
1226 |.ffunc_1 ipairs 1357 |.ffunc_1 ipairs
1227 | li AT, LJ_TTAB 1358 | li AT, LJ_TTAB
1228 | bne CARG3, AT, ->fff_fallback 1359 | bne SFARG1HI, AT, ->fff_fallback
1229 |. lw PC, FRAME_PC(BASE) 1360 |. lw PC, FRAME_PC(BASE)
1230#if LJ_52 1361#if LJ_52
1231 | lw TAB:TMP2, TAB:CARG1->metatable 1362 | lw TAB:TMP2, TAB:SFARG1LO->metatable
1232 | ldc1 f0, CFUNC:RB->upvalue[0] 1363 | lw TMP0, CFUNC:RB->upvalue[0].u32.hi
1364 | lw TMP1, CFUNC:RB->upvalue[0].u32.lo
1233 | bnez TAB:TMP2, ->fff_fallback 1365 | bnez TAB:TMP2, ->fff_fallback
1234#else 1366#else
1235 | ldc1 f0, CFUNC:RB->upvalue[0] 1367 | lw TMP0, CFUNC:RB->upvalue[0].u32.hi
1368 | lw TMP1, CFUNC:RB->upvalue[0].u32.lo
1236#endif 1369#endif
1237 |. addiu RA, BASE, -8 1370 |. addiu RA, BASE, -8
1238 | sw r0, 8+HI(BASE) 1371 | sw TISNUM, 8+HI(BASE)
1239 | sw r0, 8+LO(BASE) 1372 | sw r0, 8+LO(BASE)
1240 | li RD, (3+1)*8 1373 | sw TMP0, HI(RA)
1374 | sw TMP1, LO(RA)
1241 | b ->fff_res 1375 | b ->fff_res
1242 |. sdc1 f0, 0(RA) 1376 |. li RD, (3+1)*8
1243 | 1377 |
1244 |//-- Base library: catch errors ---------------------------------------- 1378 |//-- Base library: catch errors ----------------------------------------
1245 | 1379 |
@@ -1259,8 +1393,9 @@ static void build_subroutines(BuildCtx *ctx)
1259 | sltiu AT, NARGS8:RC, 16 1393 | sltiu AT, NARGS8:RC, 16
1260 | lw CARG4, 8+HI(BASE) 1394 | lw CARG4, 8+HI(BASE)
1261 | bnez AT, ->fff_fallback 1395 | bnez AT, ->fff_fallback
1262 |. ldc1 FARG2, 8(BASE) 1396 |. lw CARG3, 8+LO(BASE)
1263 | ldc1 FARG1, 0(BASE) 1397 | lw CARG1, LO(BASE)
1398 | lw CARG2, HI(BASE)
1264 | lbu TMP1, DISPATCH_GL(hookmask)(DISPATCH) 1399 | lbu TMP1, DISPATCH_GL(hookmask)(DISPATCH)
1265 | li AT, LJ_TFUNC 1400 | li AT, LJ_TFUNC
1266 | move TMP2, BASE 1401 | move TMP2, BASE
@@ -1268,9 +1403,11 @@ static void build_subroutines(BuildCtx *ctx)
1268 | addiu BASE, BASE, 16 1403 | addiu BASE, BASE, 16
1269 | // Remember active hook before pcall. 1404 | // Remember active hook before pcall.
1270 | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT 1405 | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT
1271 | sdc1 FARG2, 0(TMP2) // Swap function and traceback. 1406 | sw CARG3, LO(TMP2) // Swap function and traceback.
1407 | sw CARG4, HI(TMP2)
1272 | andi TMP3, TMP3, 1 1408 | andi TMP3, TMP3, 1
1273 | sdc1 FARG1, 8(TMP2) 1409 | sw CARG1, 8+LO(TMP2)
1410 | sw CARG2, 8+HI(TMP2)
1274 | addiu PC, TMP3, 16+FRAME_PCALL 1411 | addiu PC, TMP3, 16+FRAME_PCALL
1275 | b ->vm_call_dispatch 1412 | b ->vm_call_dispatch
1276 |. addiu NARGS8:RC, NARGS8:RC, -16 1413 |. addiu NARGS8:RC, NARGS8:RC, -16
@@ -1279,7 +1416,10 @@ static void build_subroutines(BuildCtx *ctx)
1279 | 1416 |
1280 |.macro coroutine_resume_wrap, resume 1417 |.macro coroutine_resume_wrap, resume
1281 |.if resume 1418 |.if resume
1282 |.ffunc_1 coroutine_resume 1419 |.ffunc coroutine_resume
1420 | lw CARG3, HI(BASE)
1421 | beqz NARGS8:RC, ->fff_fallback
1422 |. lw CARG1, LO(BASE)
1283 | li AT, LJ_TTHREAD 1423 | li AT, LJ_TTHREAD
1284 | bne CARG3, AT, ->fff_fallback 1424 | bne CARG3, AT, ->fff_fallback
1285 |.else 1425 |.else
@@ -1314,11 +1454,13 @@ static void build_subroutines(BuildCtx *ctx)
1314 | move CARG3, CARG2 1454 | move CARG3, CARG2
1315 | sw BASE, L->top 1455 | sw BASE, L->top
1316 |2: // Move args to coroutine. 1456 |2: // Move args to coroutine.
1317 | ldc1 f0, 0(BASE) 1457 | lw SFRETHI, HI(BASE)
1458 | lw SFRETLO, LO(BASE)
1318 | sltu AT, BASE, TMP1 1459 | sltu AT, BASE, TMP1
1319 | beqz AT, >3 1460 | beqz AT, >3
1320 |. addiu BASE, BASE, 8 1461 |. addiu BASE, BASE, 8
1321 | sdc1 f0, 0(CARG3) 1462 | sw SFRETHI, HI(CARG3)
1463 | sw SFRETLO, LO(CARG3)
1322 | b <2 1464 | b <2
1323 |. addiu CARG3, CARG3, 8 1465 |. addiu CARG3, CARG3, 8
1324 |3: 1466 |3:
@@ -1331,6 +1473,7 @@ static void build_subroutines(BuildCtx *ctx)
1331 | lw TMP3, L:RA->top 1473 | lw TMP3, L:RA->top
1332 | li_vmstate INTERP 1474 | li_vmstate INTERP
1333 | lw BASE, L->base 1475 | lw BASE, L->base
1476 | sw L, DISPATCH_GL(cur_L)(DISPATCH)
1334 | st_vmstate 1477 | st_vmstate
1335 | beqz AT, >8 1478 | beqz AT, >8
1336 |. subu RD, TMP3, TMP2 1479 |. subu RD, TMP3, TMP2
@@ -1343,10 +1486,12 @@ static void build_subroutines(BuildCtx *ctx)
1343 | sw TMP2, L:RA->top // Clear coroutine stack. 1486 | sw TMP2, L:RA->top // Clear coroutine stack.
1344 | move TMP1, BASE 1487 | move TMP1, BASE
1345 |5: // Move results from coroutine. 1488 |5: // Move results from coroutine.
1346 | ldc1 f0, 0(TMP2) 1489 | lw SFRETHI, HI(TMP2)
1490 | lw SFRETLO, LO(TMP2)
1347 | addiu TMP2, TMP2, 8 1491 | addiu TMP2, TMP2, 8
1348 | sltu AT, TMP2, TMP3 1492 | sltu AT, TMP2, TMP3
1349 | sdc1 f0, 0(TMP1) 1493 | sw SFRETHI, HI(TMP1)
1494 | sw SFRETLO, LO(TMP1)
1350 | bnez AT, <5 1495 | bnez AT, <5
1351 |. addiu TMP1, TMP1, 8 1496 |. addiu TMP1, TMP1, 8
1352 |6: 1497 |6:
@@ -1371,12 +1516,14 @@ static void build_subroutines(BuildCtx *ctx)
1371 |.if resume 1516 |.if resume
1372 | addiu TMP3, TMP3, -8 1517 | addiu TMP3, TMP3, -8
1373 | li TMP1, LJ_TFALSE 1518 | li TMP1, LJ_TFALSE
1374 | ldc1 f0, 0(TMP3) 1519 | lw SFRETHI, HI(TMP3)
1520 | lw SFRETLO, LO(TMP3)
1375 | sw TMP3, L:RA->top // Remove error from coroutine stack. 1521 | sw TMP3, L:RA->top // Remove error from coroutine stack.
1376 | li RD, (2+1)*8 1522 | li RD, (2+1)*8
1377 | sw TMP1, -8+HI(BASE) // Prepend false to results. 1523 | sw TMP1, -8+HI(BASE) // Prepend false to results.
1378 | addiu RA, BASE, -8 1524 | addiu RA, BASE, -8
1379 | sdc1 f0, 0(BASE) // Copy error message. 1525 | sw SFRETHI, HI(BASE) // Copy error message.
1526 | sw SFRETLO, LO(BASE)
1380 | b <7 1527 | b <7
1381 |. andi TMP0, PC, FRAME_TYPE 1528 |. andi TMP0, PC, FRAME_TYPE
1382 |.else 1529 |.else
@@ -1412,20 +1559,29 @@ static void build_subroutines(BuildCtx *ctx)
1412 | 1559 |
1413 |//-- Math library ------------------------------------------------------- 1560 |//-- Math library -------------------------------------------------------
1414 | 1561 |
1415 |.ffunc_n math_abs 1562 |.ffunc_1 math_abs
1416 |. abs.d FRET1, FARG1 1563 | bne SFARG1HI, TISNUM, >1
1417 |->fff_resn: 1564 |. sra TMP0, SFARG1LO, 31
1418 | lw PC, FRAME_PC(BASE) 1565 | xor TMP1, SFARG1LO, TMP0
1419 | addiu RA, BASE, -8 1566 | subu SFARG1LO, TMP1, TMP0
1420 | b ->fff_res1 1567 | bgez SFARG1LO, ->fff_restv
1421 |. sdc1 FRET1, -8(BASE) 1568 |. nop
1569 | lui SFARG1HI, 0x41e0 // 2^31 as a double.
1570 | b ->fff_restv
1571 |. li SFARG1LO, 0
1572 |1:
1573 | sltiu AT, SFARG1HI, LJ_TISNUM
1574 | beqz AT, ->fff_fallback
1575 |. sll SFARG1HI, SFARG1HI, 1
1576 | srl SFARG1HI, SFARG1HI, 1
1577 |// fallthrough
1422 | 1578 |
1423 |->fff_restv: 1579 |->fff_restv:
1424 | // CARG3/CARG1 = TValue result. 1580 | // SFARG1LO/SFARG1HI = TValue result.
1425 | lw PC, FRAME_PC(BASE) 1581 | lw PC, FRAME_PC(BASE)
1426 | sw CARG3, -8+HI(BASE) 1582 | sw SFARG1HI, -8+HI(BASE)
1427 | addiu RA, BASE, -8 1583 | addiu RA, BASE, -8
1428 | sw CARG1, -8+LO(BASE) 1584 | sw SFARG1LO, -8+LO(BASE)
1429 |->fff_res1: 1585 |->fff_res1:
1430 | // RA = results, PC = return. 1586 | // RA = results, PC = return.
1431 | li RD, (1+1)*8 1587 | li RD, (1+1)*8
@@ -1454,15 +1610,19 @@ static void build_subroutines(BuildCtx *ctx)
1454 |. sw TISNIL, -8+HI(TMP1) 1610 |. sw TISNIL, -8+HI(TMP1)
1455 | 1611 |
1456 |.macro math_extern, func 1612 |.macro math_extern, func
1457 |->ff_math_ .. func: 1613 | .ffunc math_ .. func
1458 | lw CARG3, HI(BASE) 1614 | lw SFARG1HI, HI(BASE)
1459 | beqz NARGS8:RC, ->fff_fallback 1615 | beqz NARGS8:RC, ->fff_fallback
1460 |. load_got func 1616 |. load_got func
1461 | sltiu AT, CARG3, LJ_TISNUM 1617 | sltiu AT, SFARG1HI, LJ_TISNUM
1462 | beqz AT, ->fff_fallback 1618 | beqz AT, ->fff_fallback
1463 |. nop 1619 |.if FPU
1464 | call_extern
1465 |. ldc1 FARG1, 0(BASE) 1620 |. ldc1 FARG1, 0(BASE)
1621 |.else
1622 |. lw SFARG1LO, LO(BASE)
1623 |.endif
1624 | call_extern
1625 |. nop
1466 | b ->fff_resn 1626 | b ->fff_resn
1467 |. nop 1627 |. nop
1468 |.endmacro 1628 |.endmacro
@@ -1476,10 +1636,22 @@ static void build_subroutines(BuildCtx *ctx)
1476 |. nop 1636 |. nop
1477 |.endmacro 1637 |.endmacro
1478 | 1638 |
1639 |// TODO: Return integer type if result is integer (own sf implementation).
1479 |.macro math_round, func 1640 |.macro math_round, func
1480 | .ffunc_n math_ .. func 1641 |->ff_math_ .. func:
1481 |. nop 1642 | lw SFARG1HI, HI(BASE)
1643 | beqz NARGS8:RC, ->fff_fallback
1644 |. lw SFARG1LO, LO(BASE)
1645 | beq SFARG1HI, TISNUM, ->fff_restv
1646 |. sltu AT, SFARG1HI, TISNUM
1647 | beqz AT, ->fff_fallback
1648 |.if FPU
1649 |. ldc1 FARG1, 0(BASE)
1482 | bal ->vm_ .. func 1650 | bal ->vm_ .. func
1651 |.else
1652 |. load_got func
1653 | call_extern
1654 |.endif
1483 |. nop 1655 |. nop
1484 | b ->fff_resn 1656 | b ->fff_resn
1485 |. nop 1657 |. nop
@@ -1489,15 +1661,19 @@ static void build_subroutines(BuildCtx *ctx)
1489 | math_round ceil 1661 | math_round ceil
1490 | 1662 |
1491 |.ffunc math_log 1663 |.ffunc math_log
1492 | lw CARG3, HI(BASE)
1493 | li AT, 8 1664 | li AT, 8
1494 | bne NARGS8:RC, AT, ->fff_fallback // Exactly 1 argument. 1665 | bne NARGS8:RC, AT, ->fff_fallback // Exactly 1 argument.
1495 |. load_got log 1666 |. lw SFARG1HI, HI(BASE)
1496 | sltiu AT, CARG3, LJ_TISNUM 1667 | sltiu AT, SFARG1HI, LJ_TISNUM
1497 | beqz AT, ->fff_fallback 1668 | beqz AT, ->fff_fallback
1498 |. nop 1669 |. load_got log
1670 |.if FPU
1499 | call_extern 1671 | call_extern
1500 |. ldc1 FARG1, 0(BASE) 1672 |. ldc1 FARG1, 0(BASE)
1673 |.else
1674 | call_extern
1675 |. lw SFARG1LO, LO(BASE)
1676 |.endif
1501 | b ->fff_resn 1677 | b ->fff_resn
1502 |. nop 1678 |. nop
1503 | 1679 |
@@ -1516,23 +1692,43 @@ static void build_subroutines(BuildCtx *ctx)
1516 | math_extern2 atan2 1692 | math_extern2 atan2
1517 | math_extern2 fmod 1693 | math_extern2 fmod
1518 | 1694 |
1695 |.if FPU
1519 |.ffunc_n math_sqrt 1696 |.ffunc_n math_sqrt
1520 |. sqrt.d FRET1, FARG1 1697 |. sqrt.d FRET1, FARG1
1521 | b ->fff_resn 1698 |// fallthrough to ->fff_resn
1522 |. nop 1699 |.else
1700 | math_extern sqrt
1701 |.endif
1702 |
1703 |->fff_resn:
1704 | lw PC, FRAME_PC(BASE)
1705 | addiu RA, BASE, -8
1706 |.if FPU
1707 | b ->fff_res1
1708 |. sdc1 FRET1, -8(BASE)
1709 |.else
1710 | sw SFRETHI, -8+HI(BASE)
1711 | b ->fff_res1
1712 |. sw SFRETLO, -8+LO(BASE)
1713 |.endif
1523 | 1714 |
1524 |->ff_math_deg:
1525 |.ffunc_n math_rad
1526 |. ldc1 FARG2, CFUNC:RB->upvalue[0]
1527 | b ->fff_resn
1528 |. mul.d FRET1, FARG1, FARG2
1529 | 1715 |
1530 |.ffunc_nn math_ldexp 1716 |.ffunc math_ldexp
1531 | cvt.w.d FARG2, FARG2 1717 | sltiu AT, NARGS8:RC, 16
1718 | lw SFARG1HI, HI(BASE)
1719 | bnez AT, ->fff_fallback
1720 |. lw CARG4, 8+HI(BASE)
1721 | bne CARG4, TISNUM, ->fff_fallback
1532 | load_got ldexp 1722 | load_got ldexp
1533 | mfc1 CARG3, FARG2 1723 |. sltu AT, SFARG1HI, TISNUM
1724 | beqz AT, ->fff_fallback
1725 |.if FPU
1726 |. ldc1 FARG1, 0(BASE)
1727 |.else
1728 |. lw SFARG1LO, LO(BASE)
1729 |.endif
1534 | call_extern 1730 | call_extern
1535 |. nop 1731 |. lw CARG3, 8+LO(BASE)
1536 | b ->fff_resn 1732 | b ->fff_resn
1537 |. nop 1733 |. nop
1538 | 1734 |
@@ -1543,10 +1739,17 @@ static void build_subroutines(BuildCtx *ctx)
1543 |. addiu CARG3, DISPATCH, DISPATCH_GL(tmptv) 1739 |. addiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
1544 | lw TMP1, DISPATCH_GL(tmptv)(DISPATCH) 1740 | lw TMP1, DISPATCH_GL(tmptv)(DISPATCH)
1545 | addiu RA, BASE, -8 1741 | addiu RA, BASE, -8
1742 |.if FPU
1546 | mtc1 TMP1, FARG2 1743 | mtc1 TMP1, FARG2
1547 | sdc1 FRET1, 0(RA) 1744 | sdc1 FRET1, 0(RA)
1548 | cvt.d.w FARG2, FARG2 1745 | cvt.d.w FARG2, FARG2
1549 | sdc1 FARG2, 8(RA) 1746 | sdc1 FARG2, 8(RA)
1747 |.else
1748 | sw SFRETLO, LO(RA)
1749 | sw SFRETHI, HI(RA)
1750 | sw TMP1, 8+LO(RA)
1751 | sw TISNUM, 8+HI(RA)
1752 |.endif
1550 | b ->fff_res 1753 | b ->fff_res
1551 |. li RD, (2+1)*8 1754 |. li RD, (2+1)*8
1552 | 1755 |
@@ -1556,49 +1759,101 @@ static void build_subroutines(BuildCtx *ctx)
1556 | call_extern 1759 | call_extern
1557 |. addiu CARG3, BASE, -8 1760 |. addiu CARG3, BASE, -8
1558 | addiu RA, BASE, -8 1761 | addiu RA, BASE, -8
1762 |.if FPU
1559 | sdc1 FRET1, 0(BASE) 1763 | sdc1 FRET1, 0(BASE)
1764 |.else
1765 | sw SFRETLO, LO(BASE)
1766 | sw SFRETHI, HI(BASE)
1767 |.endif
1560 | b ->fff_res 1768 | b ->fff_res
1561 |. li RD, (2+1)*8 1769 |. li RD, (2+1)*8
1562 | 1770 |
1563 |.macro math_minmax, name, ismax 1771 |.macro math_minmax, name, intins, fpins
1564 |->ff_ .. name: 1772 | .ffunc_1 name
1565 | lw CARG3, HI(BASE) 1773 | addu TMP3, BASE, NARGS8:RC
1566 | beqz NARGS8:RC, ->fff_fallback 1774 | bne SFARG1HI, TISNUM, >5
1567 |. ldc1 FRET1, 0(BASE) 1775 |. addiu TMP2, BASE, 8
1568 | sltiu AT, CARG3, LJ_TISNUM 1776 |1: // Handle integers.
1777 |. lw SFARG2HI, HI(TMP2)
1778 | beq TMP2, TMP3, ->fff_restv
1779 |. lw SFARG2LO, LO(TMP2)
1780 | bne SFARG2HI, TISNUM, >3
1781 |. slt AT, SFARG1LO, SFARG2LO
1782 | intins SFARG1LO, SFARG2LO, AT
1783 | b <1
1784 |. addiu TMP2, TMP2, 8
1785 |
1786 |3: // Convert intermediate result to number and continue with number loop.
1787 | sltiu AT, SFARG2HI, LJ_TISNUM
1569 | beqz AT, ->fff_fallback 1788 | beqz AT, ->fff_fallback
1570 |. addu TMP2, BASE, NARGS8:RC 1789 |.if FPU
1571 | addiu TMP1, BASE, 8 1790 |. mtc1 SFARG1LO, FRET1
1572 | beq TMP1, TMP2, ->fff_resn 1791 | cvt.d.w FRET1, FRET1
1573 |1: 1792 | b >7
1574 |. lw CARG3, HI(TMP1) 1793 |. ldc1 FARG1, 0(TMP2)
1575 | ldc1 FARG1, 0(TMP1) 1794 |.else
1576 | addiu TMP1, TMP1, 8 1795 |. nop
1577 | sltiu AT, CARG3, LJ_TISNUM 1796 | bal ->vm_sfi2d_1
1797 |. nop
1798 | b >7
1799 |. nop
1800 |.endif
1801 |
1802 |5:
1803 |. sltiu AT, SFARG1HI, LJ_TISNUM
1578 | beqz AT, ->fff_fallback 1804 | beqz AT, ->fff_fallback
1579 |.if ismax 1805 |.if FPU
1580 |. c.olt.d FARG1, FRET1 1806 |. ldc1 FRET1, 0(BASE)
1807 |.endif
1808 |
1809 |6: // Handle numbers.
1810 |. lw SFARG2HI, HI(TMP2)
1811 |.if FPU
1812 | beq TMP2, TMP3, ->fff_resn
1581 |.else 1813 |.else
1582 |. c.olt.d FRET1, FARG1 1814 | beq TMP2, TMP3, ->fff_restv
1583 |.endif 1815 |.endif
1584 | bne TMP1, TMP2, <1 1816 |. sltiu AT, SFARG2HI, LJ_TISNUM
1585 |. movf.d FRET1, FARG1 1817 | beqz AT, >8
1586 | b ->fff_resn 1818 |.if FPU
1819 |. ldc1 FARG1, 0(TMP2)
1820 |.else
1821 |. lw SFARG2LO, LO(TMP2)
1822 |.endif
1823 |7:
1824 |.if FPU
1825 | c.olt.d FRET1, FARG1
1826 | fpins FRET1, FARG1
1827 |.else
1828 | bal ->vm_sfcmpolt
1587 |. nop 1829 |. nop
1830 | intins SFARG1LO, SFARG2LO, CRET1
1831 | intins SFARG1HI, SFARG2HI, CRET1
1832 |.endif
1833 | b <6
1834 |. addiu TMP2, TMP2, 8
1835 |
1836 |8: // Convert integer to number and continue with number loop.
1837 | bne SFARG2HI, TISNUM, ->fff_fallback
1838 |.if FPU
1839 |. lwc1 FARG1, LO(TMP2)
1840 | b <7
1841 |. cvt.d.w FARG1, FARG1
1842 |.else
1843 |. nop
1844 | bal ->vm_sfi2d_2
1845 |. nop
1846 | b <7
1847 |. nop
1848 |.endif
1849 |
1588 |.endmacro 1850 |.endmacro
1589 | 1851 |
1590 | math_minmax math_min, 0 1852 | math_minmax math_min, movz, movf.d
1591 | math_minmax math_max, 1 1853 | math_minmax math_max, movn, movt.d
1592 | 1854 |
1593 |//-- String library ----------------------------------------------------- 1855 |//-- String library -----------------------------------------------------
1594 | 1856 |
1595 |.ffunc_1 string_len
1596 | li AT, LJ_TSTR
1597 | bne CARG3, AT, ->fff_fallback
1598 |. nop
1599 | b ->fff_resi
1600 |. lw CRET1, STR:CARG1->len
1601 |
1602 |.ffunc string_byte // Only handle the 1-arg case here. 1857 |.ffunc string_byte // Only handle the 1-arg case here.
1603 | lw CARG3, HI(BASE) 1858 | lw CARG3, HI(BASE)
1604 | lw STR:CARG1, LO(BASE) 1859 | lw STR:CARG1, LO(BASE)
@@ -1608,33 +1863,31 @@ static void build_subroutines(BuildCtx *ctx)
1608 | bnez AT, ->fff_fallback // Need exactly 1 string argument. 1863 | bnez AT, ->fff_fallback // Need exactly 1 string argument.
1609 |. nop 1864 |. nop
1610 | lw TMP0, STR:CARG1->len 1865 | lw TMP0, STR:CARG1->len
1611 | lbu TMP1, STR:CARG1[1] // Access is always ok (NUL at end).
1612 | addiu RA, BASE, -8 1866 | addiu RA, BASE, -8
1867 | lw PC, FRAME_PC(BASE)
1613 | sltu RD, r0, TMP0 1868 | sltu RD, r0, TMP0
1614 | mtc1 TMP1, f0 1869 | lbu TMP1, STR:CARG1[1] // Access is always ok (NUL at end).
1615 | addiu RD, RD, 1 1870 | addiu RD, RD, 1
1616 | cvt.d.w f0, f0
1617 | lw PC, FRAME_PC(BASE)
1618 | sll RD, RD, 3 // RD = ((str->len != 0)+1)*8 1871 | sll RD, RD, 3 // RD = ((str->len != 0)+1)*8
1872 | sw TISNUM, HI(RA)
1619 | b ->fff_res 1873 | b ->fff_res
1620 |. sdc1 f0, 0(RA) 1874 |. sw TMP1, LO(RA)
1621 | 1875 |
1622 |.ffunc string_char // Only handle the 1-arg case here. 1876 |.ffunc string_char // Only handle the 1-arg case here.
1623 | ffgccheck 1877 | ffgccheck
1624 |. nop 1878 |. nop
1625 | lw CARG3, HI(BASE) 1879 | lw CARG3, HI(BASE)
1626 | ldc1 FARG1, 0(BASE) 1880 | lw CARG1, LO(BASE)
1627 | li AT, 8 1881 | li TMP1, 255
1628 | bne NARGS8:RC, AT, ->fff_fallback // Exactly 1 argument. 1882 | xori AT, NARGS8:RC, 8 // Exactly 1 argument.
1629 |. sltiu AT, CARG3, LJ_TISNUM 1883 | xor TMP0, CARG3, TISNUM // Integer.
1630 | beqz AT, ->fff_fallback 1884 | sltu TMP1, TMP1, CARG1 // !(255 < n).
1885 | or AT, AT, TMP0
1886 | or AT, AT, TMP1
1887 | bnez AT, ->fff_fallback
1631 |. li CARG3, 1 1888 |. li CARG3, 1
1632 | cvt.w.d FARG1, FARG1
1633 | addiu CARG2, sp, ARG5_OFS 1889 | addiu CARG2, sp, ARG5_OFS
1634 | sltiu AT, TMP0, 256 1890 | sb CARG1, ARG5
1635 | mfc1 TMP0, FARG1
1636 | beqz AT, ->fff_fallback
1637 |. sw TMP0, ARG5
1638 |->fff_newstr: 1891 |->fff_newstr:
1639 | load_got lj_str_new 1892 | load_got lj_str_new
1640 | sw BASE, L->base 1893 | sw BASE, L->base
@@ -1643,35 +1896,30 @@ static void build_subroutines(BuildCtx *ctx)
1643 |. move CARG1, L 1896 |. move CARG1, L
1644 | // Returns GCstr *. 1897 | // Returns GCstr *.
1645 | lw BASE, L->base 1898 | lw BASE, L->base
1646 | move CARG1, CRET1 1899 |->fff_resstr:
1900 | move SFARG1LO, CRET1
1647 | b ->fff_restv 1901 | b ->fff_restv
1648 |. li CARG3, LJ_TSTR 1902 |. li SFARG1HI, LJ_TSTR
1649 | 1903 |
1650 |.ffunc string_sub 1904 |.ffunc string_sub
1651 | ffgccheck 1905 | ffgccheck
1652 |. nop 1906 |. nop
1653 | addiu AT, NARGS8:RC, -16 1907 | addiu AT, NARGS8:RC, -16
1654 | lw CARG3, 16+HI(BASE) 1908 | lw CARG3, 16+HI(BASE)
1655 | ldc1 f0, 16(BASE)
1656 | lw TMP0, HI(BASE) 1909 | lw TMP0, HI(BASE)
1657 | lw STR:CARG1, LO(BASE) 1910 | lw STR:CARG1, LO(BASE)
1658 | bltz AT, ->fff_fallback 1911 | bltz AT, ->fff_fallback
1659 | lw CARG2, 8+HI(BASE) 1912 |. lw CARG2, 8+HI(BASE)
1660 | ldc1 f2, 8(BASE)
1661 | beqz AT, >1 1913 | beqz AT, >1
1662 |. li CARG4, -1 1914 |. li CARG4, -1
1663 | cvt.w.d f0, f0 1915 | bne CARG3, TISNUM, ->fff_fallback
1664 | sltiu AT, CARG3, LJ_TISNUM 1916 |. lw CARG4, 16+LO(BASE)
1665 | beqz AT, ->fff_fallback
1666 |. mfc1 CARG4, f0
1667 |1: 1917 |1:
1668 | sltiu AT, CARG2, LJ_TISNUM 1918 | bne CARG2, TISNUM, ->fff_fallback
1669 | beqz AT, ->fff_fallback
1670 |. li AT, LJ_TSTR 1919 |. li AT, LJ_TSTR
1671 | cvt.w.d f2, f2
1672 | bne TMP0, AT, ->fff_fallback 1920 | bne TMP0, AT, ->fff_fallback
1673 |. lw CARG2, STR:CARG1->len 1921 |. lw CARG3, 8+LO(BASE)
1674 | mfc1 CARG3, f2 1922 | lw CARG2, STR:CARG1->len
1675 | // STR:CARG1 = str, CARG2 = str->len, CARG3 = start, CARG4 = end 1923 | // STR:CARG1 = str, CARG2 = str->len, CARG3 = start, CARG4 = end
1676 | slt AT, CARG4, r0 1924 | slt AT, CARG4, r0
1677 | addiu TMP0, CARG2, 1 1925 | addiu TMP0, CARG2, 1
@@ -1693,139 +1941,130 @@ static void build_subroutines(BuildCtx *ctx)
1693 | bgez CARG3, ->fff_newstr 1941 | bgez CARG3, ->fff_newstr
1694 |. addiu CARG3, CARG3, 1 // len++ 1942 |. addiu CARG3, CARG3, 1 // len++
1695 |->fff_emptystr: // Return empty string. 1943 |->fff_emptystr: // Return empty string.
1696 | addiu STR:CARG1, DISPATCH, DISPATCH_GL(strempty) 1944 | addiu STR:SFARG1LO, DISPATCH, DISPATCH_GL(strempty)
1697 | b ->fff_restv 1945 | b ->fff_restv
1698 |. li CARG3, LJ_TSTR 1946 |. li SFARG1HI, LJ_TSTR
1699 |
1700 |.ffunc string_rep // Only handle the 1-char case inline.
1701 | ffgccheck
1702 |. nop
1703 | lw TMP0, HI(BASE)
1704 | addiu AT, NARGS8:RC, -16 // Exactly 2 arguments.
1705 | lw CARG4, 8+HI(BASE)
1706 | lw STR:CARG1, LO(BASE)
1707 | addiu TMP0, TMP0, -LJ_TSTR
1708 | ldc1 f0, 8(BASE)
1709 | or AT, AT, TMP0
1710 | bnez AT, ->fff_fallback
1711 |. sltiu AT, CARG4, LJ_TISNUM
1712 | cvt.w.d f0, f0
1713 | beqz AT, ->fff_fallback
1714 |. lw TMP0, STR:CARG1->len
1715 | mfc1 CARG3, f0
1716 | lw TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
1717 | li AT, 1
1718 | blez CARG3, ->fff_emptystr // Count <= 0?
1719 |. sltu AT, AT, TMP0
1720 | beqz TMP0, ->fff_emptystr // Zero length string?
1721 |. sltu TMP0, TMP1, CARG3
1722 | or AT, AT, TMP0
1723 | lw CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
1724 | bnez AT, ->fff_fallback // Fallback for > 1-char strings.
1725 |. lbu TMP0, STR:CARG1[1]
1726 | addu TMP2, CARG2, CARG3
1727 |1: // Fill buffer with char. Yes, this is suboptimal code (do you care?).
1728 | addiu TMP2, TMP2, -1
1729 | sltu AT, CARG2, TMP2
1730 | bnez AT, <1
1731 |. sb TMP0, 0(TMP2)
1732 | b ->fff_newstr
1733 |. nop
1734 |
1735 |.ffunc string_reverse
1736 | ffgccheck
1737 |. nop
1738 | lw CARG3, HI(BASE)
1739 | lw STR:CARG1, LO(BASE)
1740 | beqz NARGS8:RC, ->fff_fallback
1741 |. li AT, LJ_TSTR
1742 | bne CARG3, AT, ->fff_fallback
1743 |. lw TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
1744 | lw CARG3, STR:CARG1->len
1745 | addiu CARG1, STR:CARG1, #STR
1746 | lw CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
1747 | sltu AT, TMP1, CARG3
1748 | bnez AT, ->fff_fallback
1749 |. addu TMP3, CARG1, CARG3
1750 | addu CARG4, CARG2, CARG3
1751 |1: // Reverse string copy.
1752 | lbu TMP1, 0(CARG1)
1753 | sltu AT, CARG1, TMP3
1754 | beqz AT, ->fff_newstr
1755 |. addiu CARG1, CARG1, 1
1756 | addiu CARG4, CARG4, -1
1757 | b <1
1758 | sb TMP1, 0(CARG4)
1759 | 1947 |
1760 |.macro ffstring_case, name, lo 1948 |.macro ffstring_op, name
1761 | .ffunc name 1949 | .ffunc string_ .. name
1762 | ffgccheck 1950 | ffgccheck
1763 |. nop 1951 |. nop
1764 | lw CARG3, HI(BASE) 1952 | lw CARG3, HI(BASE)
1765 | lw STR:CARG1, LO(BASE) 1953 | lw STR:CARG2, LO(BASE)
1766 | beqz NARGS8:RC, ->fff_fallback 1954 | beqz NARGS8:RC, ->fff_fallback
1767 |. li AT, LJ_TSTR 1955 |. li AT, LJ_TSTR
1768 | bne CARG3, AT, ->fff_fallback 1956 | bne CARG3, AT, ->fff_fallback
1769 |. lw TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH) 1957 |. addiu SBUF:CARG1, DISPATCH, DISPATCH_GL(tmpbuf)
1770 | lw CARG3, STR:CARG1->len 1958 | load_got lj_buf_putstr_ .. name
1771 | addiu CARG1, STR:CARG1, #STR 1959 | lw TMP0, SBUF:CARG1->b
1772 | lw CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH) 1960 | sw L, SBUF:CARG1->L
1773 | sltu AT, TMP1, CARG3 1961 | sw BASE, L->base
1774 | bnez AT, ->fff_fallback 1962 | sw TMP0, SBUF:CARG1->p
1775 |. addu TMP3, CARG1, CARG3 1963 | call_intern extern lj_buf_putstr_ .. name
1776 | move CARG4, CARG2 1964 |. sw PC, SAVE_PC
1777 |1: // ASCII case conversion. 1965 | load_got lj_buf_tostr
1778 | lbu TMP1, 0(CARG1) 1966 | call_intern lj_buf_tostr
1779 | sltu AT, CARG1, TMP3 1967 |. move SBUF:CARG1, SBUF:CRET1
1780 | beqz AT, ->fff_newstr 1968 | b ->fff_resstr
1781 |. addiu TMP0, TMP1, -lo 1969 |. lw BASE, L->base
1782 | xori TMP2, TMP1, 0x20
1783 | sltiu AT, TMP0, 26
1784 | movn TMP1, TMP2, AT
1785 | addiu CARG1, CARG1, 1
1786 | sb TMP1, 0(CARG4)
1787 | b <1
1788 |. addiu CARG4, CARG4, 1
1789 |.endmacro 1970 |.endmacro
1790 | 1971 |
1791 |ffstring_case string_lower, 65 1972 |ffstring_op reverse
1792 |ffstring_case string_upper, 97 1973 |ffstring_op lower
1974 |ffstring_op upper
1793 | 1975 |
1794 |//-- Table library ------------------------------------------------------ 1976 |//-- Bit library --------------------------------------------------------
1795 | 1977 |
1796 |.ffunc_1 table_getn 1978 |->vm_tobit_fb:
1797 | li AT, LJ_TTAB 1979 | beqz TMP1, ->fff_fallback
1798 | bne CARG3, AT, ->fff_fallback 1980 |.if FPU
1799 |. load_got lj_tab_len 1981 |. ldc1 FARG1, 0(BASE)
1800 | call_intern lj_tab_len // (GCtab *t) 1982 | add.d FARG1, FARG1, TOBIT
1801 |. nop 1983 | jr ra
1802 | // Returns uint32_t (but less than 2^31). 1984 |. mfc1 CRET1, FARG1
1803 | b ->fff_resi 1985 |.else
1986 |// FP number to bit conversion for soft-float.
1987 |->vm_tobit:
1988 | sll TMP0, SFARG1HI, 1
1989 | lui AT, 0x0020
1990 | addu TMP0, TMP0, AT
1991 | slt AT, TMP0, r0
1992 | movz SFARG1LO, r0, AT
1993 | beqz AT, >2
1994 |. li TMP1, 0x3e0
1995 | not TMP1, TMP1
1996 | sra TMP0, TMP0, 21
1997 | subu TMP0, TMP1, TMP0
1998 | slt AT, TMP0, r0
1999 | bnez AT, >1
2000 |. sll TMP1, SFARG1HI, 11
2001 | lui AT, 0x8000
2002 | or TMP1, TMP1, AT
2003 | srl AT, SFARG1LO, 21
2004 | or TMP1, TMP1, AT
2005 | slt AT, SFARG1HI, r0
2006 | beqz AT, >2
2007 |. srlv SFARG1LO, TMP1, TMP0
2008 | subu SFARG1LO, r0, SFARG1LO
2009 |2:
2010 | jr ra
2011 |. move CRET1, SFARG1LO
2012 |1:
2013 | addiu TMP0, TMP0, 21
2014 | srlv TMP1, SFARG1LO, TMP0
2015 | li AT, 20
2016 | subu TMP0, AT, TMP0
2017 | sll SFARG1LO, SFARG1HI, 12
2018 | sllv AT, SFARG1LO, TMP0
2019 | or SFARG1LO, TMP1, AT
2020 | slt AT, SFARG1HI, r0
2021 | beqz AT, <2
1804 |. nop 2022 |. nop
1805 | 2023 | jr ra
1806 |//-- Bit library -------------------------------------------------------- 2024 |. subu CRET1, r0, SFARG1LO
2025 |.endif
1807 | 2026 |
1808 |.macro .ffunc_bit, name 2027 |.macro .ffunc_bit, name
1809 | .ffunc_n bit_..name 2028 | .ffunc_1 bit_..name
1810 |. add.d FARG1, FARG1, TOBIT 2029 | beq SFARG1HI, TISNUM, >6
1811 | mfc1 CRET1, FARG1 2030 |. move CRET1, SFARG1LO
2031 | bal ->vm_tobit_fb
2032 |. sltu TMP1, SFARG1HI, TISNUM
2033 |6:
1812 |.endmacro 2034 |.endmacro
1813 | 2035 |
1814 |.macro .ffunc_bit_op, name, ins 2036 |.macro .ffunc_bit_op, name, ins
1815 | .ffunc_bit name 2037 | .ffunc_bit name
1816 | addiu TMP1, BASE, 8 2038 | addiu TMP2, BASE, 8
1817 | addu TMP2, BASE, NARGS8:RC 2039 | addu TMP3, BASE, NARGS8:RC
1818 |1: 2040 |1:
1819 | lw CARG4, HI(TMP1) 2041 | lw SFARG1HI, HI(TMP2)
1820 | beq TMP1, TMP2, ->fff_resi 2042 | beq TMP2, TMP3, ->fff_resi
1821 |. ldc1 FARG1, 0(TMP1) 2043 |. lw SFARG1LO, LO(TMP2)
1822 | sltiu AT, CARG4, LJ_TISNUM 2044 |.if FPU
1823 | beqz AT, ->fff_fallback 2045 | bne SFARG1HI, TISNUM, >2
1824 | add.d FARG1, FARG1, TOBIT 2046 |. addiu TMP2, TMP2, 8
1825 | mfc1 CARG2, FARG1
1826 | ins CRET1, CRET1, CARG2
1827 | b <1 2047 | b <1
1828 |. addiu TMP1, TMP1, 8 2048 |. ins CRET1, CRET1, SFARG1LO
2049 |2:
2050 | ldc1 FARG1, -8(TMP2)
2051 | sltu TMP1, SFARG1HI, TISNUM
2052 | beqz TMP1, ->fff_fallback
2053 |. add.d FARG1, FARG1, TOBIT
2054 | mfc1 SFARG1LO, FARG1
2055 | b <1
2056 |. ins CRET1, CRET1, SFARG1LO
2057 |.else
2058 | beq SFARG1HI, TISNUM, >2
2059 |. move CRET2, CRET1
2060 | bal ->vm_tobit_fb
2061 |. sltu TMP1, SFARG1HI, TISNUM
2062 | move SFARG1LO, CRET2
2063 |2:
2064 | ins CRET1, CRET1, SFARG1LO
2065 | b <1
2066 |. addiu TMP2, TMP2, 8
2067 |.endif
1829 |.endmacro 2068 |.endmacro
1830 | 2069 |
1831 |.ffunc_bit_op band, and 2070 |.ffunc_bit_op band, and
@@ -1849,24 +2088,28 @@ static void build_subroutines(BuildCtx *ctx)
1849 |. not CRET1, CRET1 2088 |. not CRET1, CRET1
1850 | 2089 |
1851 |.macro .ffunc_bit_sh, name, ins, shmod 2090 |.macro .ffunc_bit_sh, name, ins, shmod
1852 | .ffunc_nn bit_..name 2091 | .ffunc_2 bit_..name
1853 |. add.d FARG1, FARG1, TOBIT 2092 | beq SFARG1HI, TISNUM, >1
1854 | add.d FARG2, FARG2, TOBIT 2093 |. nop
1855 | mfc1 CARG1, FARG1 2094 | bal ->vm_tobit_fb
1856 | mfc1 CARG2, FARG2 2095 |. sltu TMP1, SFARG1HI, TISNUM
2096 | move SFARG1LO, CRET1
2097 |1:
2098 | bne SFARG2HI, TISNUM, ->fff_fallback
2099 |. nop
1857 |.if shmod == 1 2100 |.if shmod == 1
1858 | li AT, 32 2101 | li AT, 32
1859 | subu TMP0, AT, CARG2 2102 | subu TMP0, AT, SFARG2LO
1860 | sllv CARG2, CARG1, CARG2 2103 | sllv SFARG2LO, SFARG1LO, SFARG2LO
1861 | srlv CARG1, CARG1, TMP0 2104 | srlv SFARG1LO, SFARG1LO, TMP0
1862 |.elif shmod == 2 2105 |.elif shmod == 2
1863 | li AT, 32 2106 | li AT, 32
1864 | subu TMP0, AT, CARG2 2107 | subu TMP0, AT, SFARG2LO
1865 | srlv CARG2, CARG1, CARG2 2108 | srlv SFARG2LO, SFARG1LO, SFARG2LO
1866 | sllv CARG1, CARG1, TMP0 2109 | sllv SFARG1LO, SFARG1LO, TMP0
1867 |.endif 2110 |.endif
1868 | b ->fff_resi 2111 | b ->fff_resi
1869 |. ins CRET1, CARG1, CARG2 2112 |. ins CRET1, SFARG1LO, SFARG2LO
1870 |.endmacro 2113 |.endmacro
1871 | 2114 |
1872 |.ffunc_bit_sh lshift, sllv, 0 2115 |.ffunc_bit_sh lshift, sllv, 0
@@ -1878,9 +2121,11 @@ static void build_subroutines(BuildCtx *ctx)
1878 | 2121 |
1879 |.ffunc_bit tobit 2122 |.ffunc_bit tobit
1880 |->fff_resi: 2123 |->fff_resi:
1881 | mtc1 CRET1, FRET1 2124 | lw PC, FRAME_PC(BASE)
1882 | b ->fff_resn 2125 | addiu RA, BASE, -8
1883 |. cvt.d.w FRET1, FRET1 2126 | sw TISNUM, -8+HI(BASE)
2127 | b ->fff_res1
2128 |. sw CRET1, -8+LO(BASE)
1884 | 2129 |
1885 |//----------------------------------------------------------------------- 2130 |//-----------------------------------------------------------------------
1886 | 2131 |
@@ -2067,19 +2312,96 @@ static void build_subroutines(BuildCtx *ctx)
2067 | jr CRET1 2312 | jr CRET1
2068 |. lw INS, -4(PC) 2313 |. lw INS, -4(PC)
2069 | 2314 |
2315 |->cont_stitch: // Trace stitching.
2316 |.if JIT
2317 | // RA = resultptr, RB = meta base
2318 | lw INS, -4(PC)
2319 | lw TMP2, -24+LO(RB) // Save previous trace.
2320 | decode_RA8a RC, INS
2321 | addiu AT, MULTRES, -8
2322 | decode_RA8b RC
2323 | beqz AT, >2
2324 |. addu RC, BASE, RC // Call base.
2325 |1: // Move results down.
2326 | lw SFRETHI, HI(RA)
2327 | lw SFRETLO, LO(RA)
2328 | addiu AT, AT, -8
2329 | addiu RA, RA, 8
2330 | sw SFRETHI, HI(RC)
2331 | sw SFRETLO, LO(RC)
2332 | bnez AT, <1
2333 |. addiu RC, RC, 8
2334 |2:
2335 | decode_RA8a RA, INS
2336 | decode_RB8a RB, INS
2337 | decode_RA8b RA
2338 | decode_RB8b RB
2339 | addu RA, RA, RB
2340 | addu RA, BASE, RA
2341 |3:
2342 | sltu AT, RC, RA
2343 | bnez AT, >9 // More results wanted?
2344 |. nop
2345 |
2346 | lhu TMP3, TRACE:TMP2->traceno
2347 | lhu RD, TRACE:TMP2->link
2348 | beq RD, TMP3, ->cont_nop // Blacklisted.
2349 |. load_got lj_dispatch_stitch
2350 | bnez RD, =>BC_JLOOP // Jump to stitched trace.
2351 |. sll RD, RD, 3
2352 |
2353 | // Stitch a new trace to the previous trace.
2354 | sw TMP3, DISPATCH_J(exitno)(DISPATCH)
2355 | sw L, DISPATCH_J(L)(DISPATCH)
2356 | sw BASE, L->base
2357 | addiu CARG1, DISPATCH, GG_DISP2J
2358 | call_intern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
2359 |. move CARG2, PC
2360 | b ->cont_nop
2361 |. lw BASE, L->base
2362 |
2363 |9:
2364 | sw TISNIL, HI(RC)
2365 | b <3
2366 |. addiu RC, RC, 8
2367 |.endif
2368 |
2369 |->vm_profhook: // Dispatch target for profiler hook.
2370#if LJ_HASPROFILE
2371 | load_got lj_dispatch_profile
2372 | sw MULTRES, SAVE_MULTRES
2373 | move CARG2, PC
2374 | sw BASE, L->base
2375 | call_intern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
2376 |. move CARG1, L
2377 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2378 | addiu PC, PC, -4
2379 | b ->cont_nop
2380 |. lw BASE, L->base
2381#endif
2382 |
2070 |//----------------------------------------------------------------------- 2383 |//-----------------------------------------------------------------------
2071 |//-- Trace exit handler ------------------------------------------------- 2384 |//-- Trace exit handler -------------------------------------------------
2072 |//----------------------------------------------------------------------- 2385 |//-----------------------------------------------------------------------
2073 | 2386 |
2074 |.macro savex_, a, b 2387 |.macro savex_, a, b
2388 |.if FPU
2075 | sdc1 f..a, 16+a*8(sp) 2389 | sdc1 f..a, 16+a*8(sp)
2076 | sw r..a, 16+32*8+a*4(sp) 2390 | sw r..a, 16+32*8+a*4(sp)
2077 | sw r..b, 16+32*8+b*4(sp) 2391 | sw r..b, 16+32*8+b*4(sp)
2392 |.else
2393 | sw r..a, 16+a*4(sp)
2394 | sw r..b, 16+b*4(sp)
2395 |.endif
2078 |.endmacro 2396 |.endmacro
2079 | 2397 |
2080 |->vm_exit_handler: 2398 |->vm_exit_handler:
2081 |.if JIT 2399 |.if JIT
2400 |.if FPU
2082 | addiu sp, sp, -(16+32*8+32*4) 2401 | addiu sp, sp, -(16+32*8+32*4)
2402 |.else
2403 | addiu sp, sp, -(16+32*4)
2404 |.endif
2083 | savex_ 0, 1 2405 | savex_ 0, 1
2084 | savex_ 2, 3 2406 | savex_ 2, 3
2085 | savex_ 4, 5 2407 | savex_ 4, 5
@@ -2094,25 +2416,34 @@ static void build_subroutines(BuildCtx *ctx)
2094 | savex_ 22, 23 2416 | savex_ 22, 23
2095 | savex_ 24, 25 2417 | savex_ 24, 25
2096 | savex_ 26, 27 2418 | savex_ 26, 27
2419 |.if FPU
2097 | sdc1 f28, 16+28*8(sp) 2420 | sdc1 f28, 16+28*8(sp)
2098 | sw r28, 16+32*8+28*4(sp)
2099 | sdc1 f30, 16+30*8(sp) 2421 | sdc1 f30, 16+30*8(sp)
2422 | sw r28, 16+32*8+28*4(sp)
2100 | sw r30, 16+32*8+30*4(sp) 2423 | sw r30, 16+32*8+30*4(sp)
2101 | sw r0, 16+32*8+31*4(sp) // Clear RID_TMP. 2424 | sw r0, 16+32*8+31*4(sp) // Clear RID_TMP.
2425 | addiu TMP2, sp, 16+32*8+32*4 // Recompute original value of sp.
2426 | sw TMP2, 16+32*8+29*4(sp) // Store sp in RID_SP
2427 |.else
2428 | sw r28, 16+28*4(sp)
2429 | sw r30, 16+30*4(sp)
2430 | sw r0, 16+31*4(sp) // Clear RID_TMP.
2431 | addiu TMP2, sp, 16+32*4 // Recompute original value of sp.
2432 | sw TMP2, 16+29*4(sp) // Store sp in RID_SP
2433 |.endif
2102 | li_vmstate EXIT 2434 | li_vmstate EXIT
2103 | addiu TMP2, sp, 16+32*8+32*4 // Recompute original value of sp.
2104 | addiu DISPATCH, JGL, -GG_DISP2G-32768 2435 | addiu DISPATCH, JGL, -GG_DISP2G-32768
2105 | lw TMP1, 0(TMP2) // Load exit number. 2436 | lw TMP1, 0(TMP2) // Load exit number.
2106 | st_vmstate 2437 | st_vmstate
2107 | sw TMP2, 16+32*8+29*4(sp) // Store sp in RID_SP. 2438 | lw L, DISPATCH_GL(cur_L)(DISPATCH)
2108 | lw L, DISPATCH_GL(jit_L)(DISPATCH) 2439 | lw BASE, DISPATCH_GL(jit_base)(DISPATCH)
2109 | lw BASE, DISPATCH_GL(jit_base)(DISPATCH)
2110 | load_got lj_trace_exit 2440 | load_got lj_trace_exit
2111 | sw L, DISPATCH_J(L)(DISPATCH) 2441 | sw L, DISPATCH_J(L)(DISPATCH)
2112 | sw ra, DISPATCH_J(parent)(DISPATCH) // Store trace number. 2442 | sw ra, DISPATCH_J(parent)(DISPATCH) // Store trace number.
2443 | sw BASE, L->base
2113 | sw TMP1, DISPATCH_J(exitno)(DISPATCH) // Store exit number. 2444 | sw TMP1, DISPATCH_J(exitno)(DISPATCH) // Store exit number.
2114 | addiu CARG1, DISPATCH, GG_DISP2J 2445 | addiu CARG1, DISPATCH, GG_DISP2J
2115 | sw BASE, L->base 2446 | sw r0, DISPATCH_GL(jit_base)(DISPATCH)
2116 | call_intern lj_trace_exit // (jit_State *J, ExitState *ex) 2447 | call_intern lj_trace_exit // (jit_State *J, ExitState *ex)
2117 |. addiu CARG2, sp, 16 2448 |. addiu CARG2, sp, 16
2118 | // Returns MULTRES (unscaled) or negated error code. 2449 | // Returns MULTRES (unscaled) or negated error code.
@@ -2128,19 +2459,21 @@ static void build_subroutines(BuildCtx *ctx)
2128 |.if JIT 2459 |.if JIT
2129 | // CRET1 = MULTRES or negated error code, BASE, PC and JGL set. 2460 | // CRET1 = MULTRES or negated error code, BASE, PC and JGL set.
2130 | lw L, SAVE_L 2461 | lw L, SAVE_L
2131 | addiu DISPATCH, JGL, -GG_DISP2G-32768 2462 | addiu DISPATCH, JGL, -GG_DISP2G-32768
2463 | sw BASE, L->base
2132 |1: 2464 |1:
2133 | bltz CRET1, >3 // Check for error from exit. 2465 | bltz CRET1, >9 // Check for error from exit.
2134 |. lw LFUNC:TMP1, FRAME_FUNC(BASE) 2466 |. lw LFUNC:RB, FRAME_FUNC(BASE)
2135 | lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). 2467 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
2136 | sll MULTRES, CRET1, 3 2468 | sll MULTRES, CRET1, 3
2137 | li TISNIL, LJ_TNIL 2469 | li TISNIL, LJ_TNIL
2470 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
2138 | sw MULTRES, SAVE_MULTRES 2471 | sw MULTRES, SAVE_MULTRES
2139 | mtc1 TMP3, TOBIT 2472 | .FPU mtc1 TMP3, TOBIT
2140 | lw TMP1, LFUNC:TMP1->pc 2473 | lw TMP1, LFUNC:RB->pc
2141 | sw r0, DISPATCH_GL(jit_L)(DISPATCH) 2474 | sw r0, DISPATCH_GL(jit_base)(DISPATCH)
2142 | lw KBASE, PC2PROTO(k)(TMP1) 2475 | lw KBASE, PC2PROTO(k)(TMP1)
2143 | cvt.d.s TOBIT, TOBIT 2476 | .FPU cvt.d.s TOBIT, TOBIT
2144 | // Modified copy of ins_next which handles function header dispatch, too. 2477 | // Modified copy of ins_next which handles function header dispatch, too.
2145 | lw INS, 0(PC) 2478 | lw INS, 0(PC)
2146 | addiu PC, PC, 4 2479 | addiu PC, PC, 4
@@ -2148,7 +2481,7 @@ static void build_subroutines(BuildCtx *ctx)
2148 | sw TISNIL, DISPATCH_GL(vmstate)(DISPATCH) 2481 | sw TISNIL, DISPATCH_GL(vmstate)(DISPATCH)
2149 | decode_OP4a TMP1, INS 2482 | decode_OP4a TMP1, INS
2150 | decode_OP4b TMP1 2483 | decode_OP4b TMP1
2151 | sltiu TMP2, TMP1, BC_FUNCF*4 // Function header? 2484 | sltiu TMP2, TMP1, BC_FUNCF*4
2152 | addu TMP0, DISPATCH, TMP1 2485 | addu TMP0, DISPATCH, TMP1
2153 | decode_RD8a RD, INS 2486 | decode_RD8a RD, INS
2154 | lw AT, 0(TMP0) 2487 | lw AT, 0(TMP0)
@@ -2158,11 +2491,27 @@ static void build_subroutines(BuildCtx *ctx)
2158 | jr AT 2491 | jr AT
2159 |. decode_RD8b RD 2492 |. decode_RD8b RD
2160 |2: 2493 |2:
2494 | sltiu TMP2, TMP1, (BC_FUNCC+2)*4 // Fast function?
2495 | bnez TMP2, >3
2496 |. lw TMP1, FRAME_PC(BASE)
2497 | // Check frame below fast function.
2498 | andi TMP0, TMP1, FRAME_TYPE
2499 | bnez TMP0, >3 // Trace stitching continuation?
2500 |. nop
2501 | // Otherwise set KBASE for Lua function below fast function.
2502 | lw TMP2, -4(TMP1)
2503 | decode_RA8a TMP0, TMP2
2504 | decode_RA8b TMP0
2505 | subu TMP1, BASE, TMP0
2506 | lw LFUNC:TMP2, -8+FRAME_FUNC(TMP1)
2507 | lw TMP1, LFUNC:TMP2->pc
2508 | lw KBASE, PC2PROTO(k)(TMP1)
2509 |3:
2161 | addiu RC, MULTRES, -8 2510 | addiu RC, MULTRES, -8
2162 | jr AT 2511 | jr AT
2163 |. addu RA, RA, BASE 2512 |. addu RA, RA, BASE
2164 | 2513 |
2165 |3: // Rethrow error from the right C frame. 2514 |9: // Rethrow error from the right C frame.
2166 | load_got lj_err_throw 2515 | load_got lj_err_throw
2167 | negu CARG2, CRET1 2516 | negu CARG2, CRET1
2168 | call_intern lj_err_throw // (lua_State *L, int errcode) 2517 | call_intern lj_err_throw // (lua_State *L, int errcode)
@@ -2173,8 +2522,9 @@ static void build_subroutines(BuildCtx *ctx)
2173 |//-- Math helper functions ---------------------------------------------- 2522 |//-- Math helper functions ----------------------------------------------
2174 |//----------------------------------------------------------------------- 2523 |//-----------------------------------------------------------------------
2175 | 2524 |
2525 |// Hard-float round to integer.
2176 |// Modifies AT, TMP0, FRET1, FRET2, f4. Keeps all others incl. FARG1. 2526 |// Modifies AT, TMP0, FRET1, FRET2, f4. Keeps all others incl. FARG1.
2177 |.macro vm_round, func 2527 |.macro vm_round_hf, func
2178 | lui TMP0, 0x4330 // Hiword of 2^52 (double). 2528 | lui TMP0, 0x4330 // Hiword of 2^52 (double).
2179 | mtc1 r0, f4 2529 | mtc1 r0, f4
2180 | mtc1 TMP0, f5 2530 | mtc1 TMP0, f5
@@ -2216,6 +2566,12 @@ static void build_subroutines(BuildCtx *ctx)
2216 |. mov.d FRET1, FARG1 2566 |. mov.d FRET1, FARG1
2217 |.endmacro 2567 |.endmacro
2218 | 2568 |
2569 |.macro vm_round, func
2570 |.if FPU
2571 | vm_round_hf, func
2572 |.endif
2573 |.endmacro
2574 |
2219 |->vm_floor: 2575 |->vm_floor:
2220 | vm_round floor 2576 | vm_round floor
2221 |->vm_ceil: 2577 |->vm_ceil:
@@ -2225,6 +2581,178 @@ static void build_subroutines(BuildCtx *ctx)
2225 | vm_round trunc 2581 | vm_round trunc
2226 |.endif 2582 |.endif
2227 | 2583 |
2584 |// Soft-float integer to number conversion.
2585 |.macro sfi2d, AHI, ALO
2586 |.if not FPU
2587 | beqz ALO, >9 // Handle zero first.
2588 |. sra TMP0, ALO, 31
2589 | xor TMP1, ALO, TMP0
2590 | subu TMP1, TMP1, TMP0 // Absolute value in TMP1.
2591 | clz AHI, TMP1
2592 | andi TMP0, TMP0, 0x800 // Mask sign bit.
2593 | li AT, 0x3ff+31-1
2594 | sllv TMP1, TMP1, AHI // Align mantissa left with leading 1.
2595 | subu AHI, AT, AHI // Exponent - 1 in AHI.
2596 | sll ALO, TMP1, 21
2597 | or AHI, AHI, TMP0 // Sign | Exponent.
2598 | srl TMP1, TMP1, 11
2599 | sll AHI, AHI, 20 // Align left.
2600 | jr ra
2601 |. addu AHI, AHI, TMP1 // Add mantissa, increment exponent.
2602 |9:
2603 | jr ra
2604 |. li AHI, 0
2605 |.endif
2606 |.endmacro
2607 |
2608 |// Input SFARG1LO. Output: SFARG1*. Temporaries: AT, TMP0, TMP1.
2609 |->vm_sfi2d_1:
2610 | sfi2d SFARG1HI, SFARG1LO
2611 |
2612 |// Input SFARG2LO. Output: SFARG2*. Temporaries: AT, TMP0, TMP1.
2613 |->vm_sfi2d_2:
2614 | sfi2d SFARG2HI, SFARG2LO
2615 |
2616 |// Soft-float comparison. Equivalent to c.eq.d.
2617 |// Input: SFARG*. Output: CRET1. Temporaries: AT, TMP0, TMP1.
2618 |->vm_sfcmpeq:
2619 |.if not FPU
2620 | sll AT, SFARG1HI, 1
2621 | sll TMP0, SFARG2HI, 1
2622 | or CRET1, SFARG1LO, SFARG2LO
2623 | or TMP1, AT, TMP0
2624 | or TMP1, TMP1, CRET1
2625 | beqz TMP1, >8 // Both args +-0: return 1.
2626 |. sltu CRET1, r0, SFARG1LO
2627 | lui TMP1, 0xffe0
2628 | addu AT, AT, CRET1
2629 | sltu CRET1, r0, SFARG2LO
2630 | sltu AT, TMP1, AT
2631 | addu TMP0, TMP0, CRET1
2632 | sltu TMP0, TMP1, TMP0
2633 | or TMP1, AT, TMP0
2634 | bnez TMP1, >9 // Either arg is NaN: return 0;
2635 |. xor TMP0, SFARG1HI, SFARG2HI
2636 | xor TMP1, SFARG1LO, SFARG2LO
2637 | or AT, TMP0, TMP1
2638 | jr ra
2639 |. sltiu CRET1, AT, 1 // Same values: return 1.
2640 |8:
2641 | jr ra
2642 |. li CRET1, 1
2643 |9:
2644 | jr ra
2645 |. li CRET1, 0
2646 |.endif
2647 |
2648 |// Soft-float comparison. Equivalent to c.ult.d and c.olt.d.
2649 |// Input: SFARG*. Output: CRET1. Temporaries: AT, TMP0, TMP1, CRET2.
2650 |->vm_sfcmpult:
2651 |.if not FPU
2652 | b >1
2653 |. li CRET2, 1
2654 |.endif
2655 |
2656 |->vm_sfcmpolt:
2657 |.if not FPU
2658 | li CRET2, 0
2659 |1:
2660 | sll AT, SFARG1HI, 1
2661 | sll TMP0, SFARG2HI, 1
2662 | or CRET1, SFARG1LO, SFARG2LO
2663 | or TMP1, AT, TMP0
2664 | or TMP1, TMP1, CRET1
2665 | beqz TMP1, >8 // Both args +-0: return 0.
2666 |. sltu CRET1, r0, SFARG1LO
2667 | lui TMP1, 0xffe0
2668 | addu AT, AT, CRET1
2669 | sltu CRET1, r0, SFARG2LO
2670 | sltu AT, TMP1, AT
2671 | addu TMP0, TMP0, CRET1
2672 | sltu TMP0, TMP1, TMP0
2673 | or TMP1, AT, TMP0
2674 | bnez TMP1, >9 // Either arg is NaN: return 0 or 1;
2675 |. and AT, SFARG1HI, SFARG2HI
2676 | bltz AT, >5 // Both args negative?
2677 |. nop
2678 | beq SFARG1HI, SFARG2HI, >8
2679 |. sltu CRET1, SFARG1LO, SFARG2LO
2680 | jr ra
2681 |. slt CRET1, SFARG1HI, SFARG2HI
2682 |5: // Swap conditions if both operands are negative.
2683 | beq SFARG1HI, SFARG2HI, >8
2684 |. sltu CRET1, SFARG2LO, SFARG1LO
2685 | jr ra
2686 |. slt CRET1, SFARG2HI, SFARG1HI
2687 |8:
2688 | jr ra
2689 |. nop
2690 |9:
2691 | jr ra
2692 |. move CRET1, CRET2
2693 |.endif
2694 |
2695 |// Soft-float comparison. Equivalent to c.ole.d a, b or c.ole.d b, a.
2696 |// Input: SFARG*, TMP3. Output: CRET1. Temporaries: AT, TMP0, TMP1.
2697 |->vm_sfcmpolex:
2698 |.if not FPU
2699 | sll AT, SFARG1HI, 1
2700 | sll TMP0, SFARG2HI, 1
2701 | or CRET1, SFARG1LO, SFARG2LO
2702 | or TMP1, AT, TMP0
2703 | or TMP1, TMP1, CRET1
2704 | beqz TMP1, >8 // Both args +-0: return 1.
2705 |. sltu CRET1, r0, SFARG1LO
2706 | lui TMP1, 0xffe0
2707 | addu AT, AT, CRET1
2708 | sltu CRET1, r0, SFARG2LO
2709 | sltu AT, TMP1, AT
2710 | addu TMP0, TMP0, CRET1
2711 | sltu TMP0, TMP1, TMP0
2712 | or TMP1, AT, TMP0
2713 | bnez TMP1, >9 // Either arg is NaN: return 0;
2714 |. and AT, SFARG1HI, SFARG2HI
2715 | xor AT, AT, TMP3
2716 | bltz AT, >5 // Both args negative?
2717 |. nop
2718 | beq SFARG1HI, SFARG2HI, >6
2719 |. sltu CRET1, SFARG2LO, SFARG1LO
2720 | jr ra
2721 |. slt CRET1, SFARG2HI, SFARG1HI
2722 |5: // Swap conditions if both operands are negative.
2723 | beq SFARG1HI, SFARG2HI, >6
2724 |. sltu CRET1, SFARG1LO, SFARG2LO
2725 | slt CRET1, SFARG1HI, SFARG2HI
2726 |6:
2727 | jr ra
2728 |. nop
2729 |8:
2730 | jr ra
2731 |. li CRET1, 1
2732 |9:
2733 | jr ra
2734 |. li CRET1, 0
2735 |.endif
2736 |
2737 |.macro sfmin_max, name, intins
2738 |->vm_sf .. name:
2739 |.if JIT and not FPU
2740 | move TMP2, ra
2741 | bal ->vm_sfcmpolt
2742 |. nop
2743 | move TMP0, CRET1
2744 | move SFRETHI, SFARG1HI
2745 | move SFRETLO, SFARG1LO
2746 | move ra, TMP2
2747 | intins SFRETHI, SFARG2HI, TMP0
2748 | jr ra
2749 |. intins SFRETLO, SFARG2LO, TMP0
2750 |.endif
2751 |.endmacro
2752 |
2753 | sfmin_max min, movz
2754 | sfmin_max max, movn
2755 |
2228 |//----------------------------------------------------------------------- 2756 |//-----------------------------------------------------------------------
2229 |//-- Miscellaneous functions -------------------------------------------- 2757 |//-- Miscellaneous functions --------------------------------------------
2230 |//----------------------------------------------------------------------- 2758 |//-----------------------------------------------------------------------
@@ -2244,10 +2772,10 @@ static void build_subroutines(BuildCtx *ctx)
2244 | sw r1, CTSTATE->cb.slot 2772 | sw r1, CTSTATE->cb.slot
2245 | sw CARG1, CTSTATE->cb.gpr[0] 2773 | sw CARG1, CTSTATE->cb.gpr[0]
2246 | sw CARG2, CTSTATE->cb.gpr[1] 2774 | sw CARG2, CTSTATE->cb.gpr[1]
2247 | sdc1 FARG1, CTSTATE->cb.fpr[0] 2775 | .FPU sdc1 FARG1, CTSTATE->cb.fpr[0]
2248 | sw CARG3, CTSTATE->cb.gpr[2] 2776 | sw CARG3, CTSTATE->cb.gpr[2]
2249 | sw CARG4, CTSTATE->cb.gpr[3] 2777 | sw CARG4, CTSTATE->cb.gpr[3]
2250 | sdc1 FARG2, CTSTATE->cb.fpr[1] 2778 | .FPU sdc1 FARG2, CTSTATE->cb.fpr[1]
2251 | addiu TMP0, sp, CFRAME_SPACE+16 2779 | addiu TMP0, sp, CFRAME_SPACE+16
2252 | sw TMP0, CTSTATE->cb.stack 2780 | sw TMP0, CTSTATE->cb.stack
2253 | sw r0, SAVE_PC // Any value outside of bytecode is ok. 2781 | sw r0, SAVE_PC // Any value outside of bytecode is ok.
@@ -2257,15 +2785,16 @@ static void build_subroutines(BuildCtx *ctx)
2257 | // Returns lua_State *. 2785 | // Returns lua_State *.
2258 | lw BASE, L:CRET1->base 2786 | lw BASE, L:CRET1->base
2259 | lw RC, L:CRET1->top 2787 | lw RC, L:CRET1->top
2788 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
2260 | move L, CRET1 2789 | move L, CRET1
2261 | lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float). 2790 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
2262 | lw LFUNC:RB, FRAME_FUNC(BASE) 2791 | lw LFUNC:RB, FRAME_FUNC(BASE)
2263 | mtc1 TMP3, TOBIT 2792 | .FPU mtc1 TMP3, TOBIT
2264 | li_vmstate INTERP 2793 | li_vmstate INTERP
2265 | li TISNIL, LJ_TNIL 2794 | li TISNIL, LJ_TNIL
2266 | subu RC, RC, BASE 2795 | subu RC, RC, BASE
2267 | st_vmstate 2796 | st_vmstate
2268 | cvt.d.s TOBIT, TOBIT 2797 | .FPU cvt.d.s TOBIT, TOBIT
2269 | ins_callt 2798 | ins_callt
2270 |.endif 2799 |.endif
2271 | 2800 |
@@ -2279,11 +2808,11 @@ static void build_subroutines(BuildCtx *ctx)
2279 | move CARG2, RA 2808 | move CARG2, RA
2280 | call_intern lj_ccallback_leave // (CTState *cts, TValue *o) 2809 | call_intern lj_ccallback_leave // (CTState *cts, TValue *o)
2281 |. move CARG1, CTSTATE 2810 |. move CARG1, CTSTATE
2811 | .FPU ldc1 FRET1, CTSTATE->cb.fpr[0]
2282 | lw CRET1, CTSTATE->cb.gpr[0] 2812 | lw CRET1, CTSTATE->cb.gpr[0]
2283 | ldc1 FRET1, CTSTATE->cb.fpr[0] 2813 | .FPU ldc1 FRET2, CTSTATE->cb.fpr[1]
2284 | lw CRET2, CTSTATE->cb.gpr[1]
2285 | b ->vm_leave_unw 2814 | b ->vm_leave_unw
2286 |. ldc1 FRET2, CTSTATE->cb.fpr[1] 2815 |. lw CRET2, CTSTATE->cb.gpr[1]
2287 |.endif 2816 |.endif
2288 | 2817 |
2289 |->vm_ffi_call: // Call C function via FFI. 2818 |->vm_ffi_call: // Call C function via FFI.
@@ -2315,8 +2844,8 @@ static void build_subroutines(BuildCtx *ctx)
2315 | lw CARG2, CCSTATE->gpr[1] 2844 | lw CARG2, CCSTATE->gpr[1]
2316 | lw CARG3, CCSTATE->gpr[2] 2845 | lw CARG3, CCSTATE->gpr[2]
2317 | lw CARG4, CCSTATE->gpr[3] 2846 | lw CARG4, CCSTATE->gpr[3]
2318 | ldc1 FARG1, CCSTATE->fpr[0] 2847 | .FPU ldc1 FARG1, CCSTATE->fpr[0]
2319 | ldc1 FARG2, CCSTATE->fpr[1] 2848 | .FPU ldc1 FARG2, CCSTATE->fpr[1]
2320 | jalr CFUNCADDR 2849 | jalr CFUNCADDR
2321 |. lw CARG1, CCSTATE->gpr[0] // Do this last, since CCSTATE is CARG1. 2850 |. lw CARG1, CCSTATE->gpr[0] // Do this last, since CCSTATE is CARG1.
2322 | lw CCSTATE:TMP1, -12(r16) 2851 | lw CCSTATE:TMP1, -12(r16)
@@ -2324,8 +2853,13 @@ static void build_subroutines(BuildCtx *ctx)
2324 | lw ra, -4(r16) 2853 | lw ra, -4(r16)
2325 | sw CRET1, CCSTATE:TMP1->gpr[0] 2854 | sw CRET1, CCSTATE:TMP1->gpr[0]
2326 | sw CRET2, CCSTATE:TMP1->gpr[1] 2855 | sw CRET2, CCSTATE:TMP1->gpr[1]
2856 |.if FPU
2327 | sdc1 FRET1, CCSTATE:TMP1->fpr[0] 2857 | sdc1 FRET1, CCSTATE:TMP1->fpr[0]
2328 | sdc1 FRET2, CCSTATE:TMP1->fpr[1] 2858 | sdc1 FRET2, CCSTATE:TMP1->fpr[1]
2859 |.else
2860 | sw CARG1, CCSTATE:TMP1->gpr[2] // Soft-float: complex double .im part.
2861 | sw CARG2, CCSTATE:TMP1->gpr[3]
2862 |.endif
2329 | move sp, r16 2863 | move sp, r16
2330 | jr ra 2864 | jr ra
2331 |. move r16, TMP2 2865 |. move r16, TMP2
@@ -2349,82 +2883,143 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2349 2883
2350 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT: 2884 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
2351 | // RA = src1*8, RD = src2*8, JMP with RD = target 2885 | // RA = src1*8, RD = src2*8, JMP with RD = target
2352 | addu CARG2, BASE, RA 2886 |.macro bc_comp, FRA, FRD, RAHI, RALO, RDHI, RDLO, movop, fmovop, fcomp, sfcomp
2353 | addu CARG3, BASE, RD 2887 | addu RA, BASE, RA
2354 | lw TMP0, HI(CARG2) 2888 | addu RD, BASE, RD
2355 | lw TMP1, HI(CARG3) 2889 | lw RAHI, HI(RA)
2356 | ldc1 f0, 0(CARG2) 2890 | lw RDHI, HI(RD)
2357 | ldc1 f2, 0(CARG3)
2358 | sltiu TMP0, TMP0, LJ_TISNUM
2359 | sltiu TMP1, TMP1, LJ_TISNUM
2360 | lhu TMP2, OFS_RD(PC) 2891 | lhu TMP2, OFS_RD(PC)
2361 | and TMP0, TMP0, TMP1
2362 | addiu PC, PC, 4 2892 | addiu PC, PC, 4
2363 | beqz TMP0, ->vmeta_comp 2893 | bne RAHI, TISNUM, >2
2364 |. lui TMP1, (-(BCBIAS_J*4 >> 16) & 65535) 2894 |. lw RALO, LO(RA)
2365 | decode_RD4b TMP2 2895 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2366 | addu TMP2, TMP2, TMP1 2896 | lw RDLO, LO(RD)
2367 if (op == BC_ISLT || op == BC_ISGE) { 2897 | bne RDHI, TISNUM, >5
2368 | c.olt.d f0, f2 2898 |. decode_RD4b TMP2
2369 } else { 2899 | slt AT, SFARG1LO, SFARG2LO
2370 | c.ole.d f0, f2 2900 | addu TMP2, TMP2, TMP3
2371 } 2901 | movop TMP2, r0, AT
2372 if (op == BC_ISLT || op == BC_ISLE) {
2373 | movf TMP2, r0
2374 } else {
2375 | movt TMP2, r0
2376 }
2377 | addu PC, PC, TMP2
2378 |1: 2902 |1:
2903 | addu PC, PC, TMP2
2379 | ins_next 2904 | ins_next
2905 |
2906 |2: // RA is not an integer.
2907 | sltiu AT, RAHI, LJ_TISNUM
2908 | beqz AT, ->vmeta_comp
2909 |. lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2910 | sltiu AT, RDHI, LJ_TISNUM
2911 |.if FPU
2912 | ldc1 FRA, 0(RA)
2913 | ldc1 FRD, 0(RD)
2914 |.else
2915 | lw RDLO, LO(RD)
2916 |.endif
2917 | beqz AT, >4
2918 |. decode_RD4b TMP2
2919 |3: // RA and RD are both numbers.
2920 |.if FPU
2921 | fcomp f20, f22
2922 | addu TMP2, TMP2, TMP3
2923 | b <1
2924 |. fmovop TMP2, r0
2925 |.else
2926 | bal sfcomp
2927 |. addu TMP2, TMP2, TMP3
2928 | b <1
2929 |. movop TMP2, r0, CRET1
2930 |.endif
2931 |
2932 |4: // RA is a number, RD is not a number.
2933 | bne RDHI, TISNUM, ->vmeta_comp
2934 | // RA is a number, RD is an integer. Convert RD to a number.
2935 |.if FPU
2936 |. lwc1 FRD, LO(RD)
2937 | b <3
2938 |. cvt.d.w FRD, FRD
2939 |.else
2940 |. nop
2941 |.if "RDHI" == "SFARG1HI"
2942 | bal ->vm_sfi2d_1
2943 |.else
2944 | bal ->vm_sfi2d_2
2945 |.endif
2946 |. nop
2947 | b <3
2948 |. nop
2949 |.endif
2950 |
2951 |5: // RA is an integer, RD is not an integer
2952 | sltiu AT, RDHI, LJ_TISNUM
2953 | beqz AT, ->vmeta_comp
2954 | // RA is an integer, RD is a number. Convert RA to a number.
2955 |.if FPU
2956 |. mtc1 RALO, FRA
2957 | ldc1 FRD, 0(RD)
2958 | b <3
2959 | cvt.d.w FRA, FRA
2960 |.else
2961 |. nop
2962 |.if "RAHI" == "SFARG1HI"
2963 | bal ->vm_sfi2d_1
2964 |.else
2965 | bal ->vm_sfi2d_2
2966 |.endif
2967 |. nop
2968 | b <3
2969 |. nop
2970 |.endif
2971 |.endmacro
2972 |
2973 if (op == BC_ISLT) {
2974 | bc_comp f20, f22, SFARG1HI, SFARG1LO, SFARG2HI, SFARG2LO, movz, movf, c.olt.d, ->vm_sfcmpolt
2975 } else if (op == BC_ISGE) {
2976 | bc_comp f20, f22, SFARG1HI, SFARG1LO, SFARG2HI, SFARG2LO, movn, movt, c.olt.d, ->vm_sfcmpolt
2977 } else if (op == BC_ISLE) {
2978 | bc_comp f22, f20, SFARG2HI, SFARG2LO, SFARG1HI, SFARG1LO, movn, movt, c.ult.d, ->vm_sfcmpult
2979 } else {
2980 | bc_comp f22, f20, SFARG2HI, SFARG2LO, SFARG1HI, SFARG1LO, movz, movf, c.ult.d, ->vm_sfcmpult
2981 }
2380 break; 2982 break;
2381 2983
2382 case BC_ISEQV: case BC_ISNEV: 2984 case BC_ISEQV: case BC_ISNEV:
2383 vk = op == BC_ISEQV; 2985 vk = op == BC_ISEQV;
2384 | // RA = src1*8, RD = src2*8, JMP with RD = target 2986 | // RA = src1*8, RD = src2*8, JMP with RD = target
2385 | addu RA, BASE, RA 2987 | addu RA, BASE, RA
2386 | addiu PC, PC, 4 2988 | addiu PC, PC, 4
2387 | lw TMP0, HI(RA)
2388 | ldc1 f0, 0(RA)
2389 | addu RD, BASE, RD 2989 | addu RD, BASE, RD
2990 | lw SFARG1HI, HI(RA)
2390 | lhu TMP2, -4+OFS_RD(PC) 2991 | lhu TMP2, -4+OFS_RD(PC)
2391 | lw TMP1, HI(RD) 2992 | lw SFARG2HI, HI(RD)
2392 | ldc1 f2, 0(RD)
2393 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) 2993 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2394 | sltiu AT, TMP0, LJ_TISNUM 2994 | sltu AT, TISNUM, SFARG1HI
2395 | sltiu CARG1, TMP1, LJ_TISNUM 2995 | sltu TMP0, TISNUM, SFARG2HI
2396 | decode_RD4b TMP2 2996 | or AT, AT, TMP0
2397 | and AT, AT, CARG1
2398 | beqz AT, >5
2399 |. addu TMP2, TMP2, TMP3
2400 | c.eq.d f0, f2
2401 if (vk) { 2997 if (vk) {
2402 | movf TMP2, r0 2998 | beqz AT, ->BC_ISEQN_Z
2403 } else { 2999 } else {
2404 | movt TMP2, r0 3000 | beqz AT, ->BC_ISNEN_Z
2405 } 3001 }
2406 |1: 3002 |. decode_RD4b TMP2
2407 | addu PC, PC, TMP2 3003 | // Either or both types are not numbers.
2408 | ins_next 3004 | lw SFARG1LO, LO(RA)
2409 |5: // Either or both types are not numbers. 3005 | lw SFARG2LO, LO(RD)
2410 | lw CARG2, LO(RA) 3006 | addu TMP2, TMP2, TMP3
2411 | lw CARG3, LO(RD)
2412 |.if FFI 3007 |.if FFI
2413 | li TMP3, LJ_TCDATA 3008 | li TMP3, LJ_TCDATA
2414 | beq TMP0, TMP3, ->vmeta_equal_cd 3009 | beq SFARG1HI, TMP3, ->vmeta_equal_cd
2415 |.endif 3010 |.endif
2416 |. sltiu AT, TMP0, LJ_TISPRI // Not a primitive? 3011 |. sltiu AT, SFARG1HI, LJ_TISPRI // Not a primitive?
2417 |.if FFI 3012 |.if FFI
2418 | beq TMP1, TMP3, ->vmeta_equal_cd 3013 | beq SFARG2HI, TMP3, ->vmeta_equal_cd
2419 |.endif 3014 |.endif
2420 |. xor TMP3, CARG2, CARG3 // Same tv? 3015 |. xor TMP3, SFARG1LO, SFARG2LO // Same tv?
2421 | xor TMP1, TMP1, TMP0 // Same type? 3016 | xor SFARG2HI, SFARG2HI, SFARG1HI // Same type?
2422 | sltiu CARG1, TMP0, LJ_TISTABUD+1 // Table or userdata? 3017 | sltiu TMP0, SFARG1HI, LJ_TISTABUD+1 // Table or userdata?
2423 | movz TMP3, r0, AT // Ignore tv if primitive. 3018 | movz TMP3, r0, AT // Ignore tv if primitive.
2424 | movn CARG1, r0, TMP1 // Tab/ud and same type? 3019 | movn TMP0, r0, SFARG2HI // Tab/ud and same type?
2425 | or AT, TMP1, TMP3 // Same type && (pri||same tv). 3020 | or AT, SFARG2HI, TMP3 // Same type && (pri||same tv).
2426 | movz CARG1, r0, AT 3021 | movz TMP0, r0, AT
2427 | beqz CARG1, <1 // Done if not tab/ud or not same type or same tv. 3022 | beqz TMP0, >1 // Done if not tab/ud or not same type or same tv.
2428 if (vk) { 3023 if (vk) {
2429 |. movn TMP2, r0, AT 3024 |. movn TMP2, r0, AT
2430 } else { 3025 } else {
@@ -2432,15 +3027,18 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2432 } 3027 }
2433 | // Different tables or userdatas. Need to check __eq metamethod. 3028 | // Different tables or userdatas. Need to check __eq metamethod.
2434 | // Field metatable must be at same offset for GCtab and GCudata! 3029 | // Field metatable must be at same offset for GCtab and GCudata!
2435 | lw TAB:TMP1, TAB:CARG2->metatable 3030 | lw TAB:TMP1, TAB:SFARG1LO->metatable
2436 | beqz TAB:TMP1, <1 // No metatable? 3031 | beqz TAB:TMP1, >1 // No metatable?
2437 |. nop 3032 |. nop
2438 | lbu TMP1, TAB:TMP1->nomm 3033 | lbu TMP1, TAB:TMP1->nomm
2439 | andi TMP1, TMP1, 1<<MM_eq 3034 | andi TMP1, TMP1, 1<<MM_eq
2440 | bnez TMP1, <1 // Or 'no __eq' flag set? 3035 | bnez TMP1, >1 // Or 'no __eq' flag set?
2441 |. nop 3036 |. nop
2442 | b ->vmeta_equal // Handle __eq metamethod. 3037 | b ->vmeta_equal // Handle __eq metamethod.
2443 |. li CARG4, 1-vk // ne = 0 or 1. 3038 |. li TMP0, 1-vk // ne = 0 or 1.
3039 |1:
3040 | addu PC, PC, TMP2
3041 | ins_next
2444 break; 3042 break;
2445 3043
2446 case BC_ISEQS: case BC_ISNES: 3044 case BC_ISEQS: case BC_ISNES:
@@ -2477,38 +3075,124 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2477 vk = op == BC_ISEQN; 3075 vk = op == BC_ISEQN;
2478 | // RA = src*8, RD = num_const*8, JMP with RD = target 3076 | // RA = src*8, RD = num_const*8, JMP with RD = target
2479 | addu RA, BASE, RA 3077 | addu RA, BASE, RA
2480 | addiu PC, PC, 4 3078 | addu RD, KBASE, RD
2481 | lw TMP0, HI(RA) 3079 | lw SFARG1HI, HI(RA)
2482 | ldc1 f0, 0(RA) 3080 | lw SFARG2HI, HI(RD)
2483 | addu RD, KBASE, RD 3081 | lhu TMP2, OFS_RD(PC)
2484 | lhu TMP2, -4+OFS_RD(PC) 3082 | addiu PC, PC, 4
2485 | ldc1 f2, 0(RD)
2486 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) 3083 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2487 | sltiu AT, TMP0, LJ_TISNUM
2488 | decode_RD4b TMP2 3084 | decode_RD4b TMP2
2489 |.if FFI
2490 | beqz AT, >5
2491 |.else
2492 | beqz AT, >1
2493 |.endif
2494 |. addu TMP2, TMP2, TMP3
2495 | c.eq.d f0, f2
2496 if (vk) { 3085 if (vk) {
2497 | movf TMP2, r0 3086 |->BC_ISEQN_Z:
2498 | addu PC, PC, TMP2 3087 } else {
3088 |->BC_ISNEN_Z:
3089 }
3090 | bne SFARG1HI, TISNUM, >3
3091 |. lw SFARG1LO, LO(RA)
3092 | lw SFARG2LO, LO(RD)
3093 | addu TMP2, TMP2, TMP3
3094 | bne SFARG2HI, TISNUM, >6
3095 |. xor AT, SFARG1LO, SFARG2LO
3096 if (vk) {
3097 | movn TMP2, r0, AT
2499 |1: 3098 |1:
3099 | addu PC, PC, TMP2
3100 |2:
2500 } else { 3101 } else {
2501 | movt TMP2, r0 3102 | movz TMP2, r0, AT
2502 |1: 3103 |1:
3104 |2:
2503 | addu PC, PC, TMP2 3105 | addu PC, PC, TMP2
2504 } 3106 }
2505 | ins_next 3107 | ins_next
3108 |
3109 |3: // RA is not an integer.
3110 | sltiu AT, SFARG1HI, LJ_TISNUM
2506 |.if FFI 3111 |.if FFI
2507 |5: 3112 | beqz AT, >8
2508 | li AT, LJ_TCDATA 3113 |.else
2509 | beq TMP0, AT, ->vmeta_equal_cd 3114 | beqz AT, <2
3115 |.endif
3116 |. addu TMP2, TMP2, TMP3
3117 | sltiu AT, SFARG2HI, LJ_TISNUM
3118 |.if FPU
3119 | ldc1 f20, 0(RA)
3120 | ldc1 f22, 0(RD)
3121 |.endif
3122 | beqz AT, >5
3123 |. lw SFARG2LO, LO(RD)
3124 |4: // RA and RD are both numbers.
3125 |.if FPU
3126 | c.eq.d f20, f22
3127 | b <1
3128 if (vk) {
3129 |. movf TMP2, r0
3130 } else {
3131 |. movt TMP2, r0
3132 }
3133 |.else
3134 | bal ->vm_sfcmpeq
2510 |. nop 3135 |. nop
2511 | b <1 3136 | b <1
3137 if (vk) {
3138 |. movz TMP2, r0, CRET1
3139 } else {
3140 |. movn TMP2, r0, CRET1
3141 }
3142 |.endif
3143 |
3144 |5: // RA is a number, RD is not a number.
3145 |.if FFI
3146 | bne SFARG2HI, TISNUM, >9
3147 |.else
3148 | bne SFARG2HI, TISNUM, <2
3149 |.endif
3150 | // RA is a number, RD is an integer. Convert RD to a number.
3151 |.if FPU
3152 |. lwc1 f22, LO(RD)
3153 | b <4
3154 |. cvt.d.w f22, f22
3155 |.else
3156 |. nop
3157 | bal ->vm_sfi2d_2
3158 |. nop
3159 | b <4
3160 |. nop
3161 |.endif
3162 |
3163 |6: // RA is an integer, RD is not an integer
3164 | sltiu AT, SFARG2HI, LJ_TISNUM
3165 |.if FFI
3166 | beqz AT, >9
3167 |.else
3168 | beqz AT, <2
3169 |.endif
3170 | // RA is an integer, RD is a number. Convert RA to a number.
3171 |.if FPU
3172 |. mtc1 SFARG1LO, f20
3173 | ldc1 f22, 0(RD)
3174 | b <4
3175 | cvt.d.w f20, f20
3176 |.else
3177 |. nop
3178 | bal ->vm_sfi2d_1
3179 |. nop
3180 | b <4
3181 |. nop
3182 |.endif
3183 |
3184 |.if FFI
3185 |8:
3186 | li AT, LJ_TCDATA
3187 | bne SFARG1HI, AT, <2
3188 |. nop
3189 | b ->vmeta_equal_cd
3190 |. nop
3191 |9:
3192 | li AT, LJ_TCDATA
3193 | bne SFARG2HI, AT, <2
3194 |. nop
3195 | b ->vmeta_equal_cd
2512 |. nop 3196 |. nop
2513 |.endif 3197 |.endif
2514 break; 3198 break;
@@ -2560,7 +3244,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2560 | addu PC, PC, TMP2 3244 | addu PC, PC, TMP2
2561 } else { 3245 } else {
2562 | sltiu TMP0, TMP0, LJ_TISTRUECOND 3246 | sltiu TMP0, TMP0, LJ_TISTRUECOND
2563 | ldc1 f0, 0(RD) 3247 | lw SFRETHI, HI(RD)
3248 | lw SFRETLO, LO(RD)
2564 if (op == BC_ISTC) { 3249 if (op == BC_ISTC) {
2565 | beqz TMP0, >1 3250 | beqz TMP0, >1
2566 } else { 3251 } else {
@@ -2570,22 +3255,45 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2570 | decode_RD4b TMP2 3255 | decode_RD4b TMP2
2571 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) 3256 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2572 | addu TMP2, TMP2, TMP3 3257 | addu TMP2, TMP2, TMP3
2573 | sdc1 f0, 0(RA) 3258 | sw SFRETHI, HI(RA)
3259 | sw SFRETLO, LO(RA)
2574 | addu PC, PC, TMP2 3260 | addu PC, PC, TMP2
2575 |1: 3261 |1:
2576 } 3262 }
2577 | ins_next 3263 | ins_next
2578 break; 3264 break;
2579 3265
3266 case BC_ISTYPE:
3267 | // RA = src*8, RD = -type*8
3268 | addu TMP2, BASE, RA
3269 | srl TMP1, RD, 3
3270 | lw TMP0, HI(TMP2)
3271 | ins_next1
3272 | addu AT, TMP0, TMP1
3273 | bnez AT, ->vmeta_istype
3274 |. ins_next2
3275 break;
3276 case BC_ISNUM:
3277 | // RA = src*8, RD = -(TISNUM-1)*8
3278 | addu TMP2, BASE, RA
3279 | lw TMP0, HI(TMP2)
3280 | ins_next1
3281 | sltiu AT, TMP0, LJ_TISNUM
3282 | beqz AT, ->vmeta_istype
3283 |. ins_next2
3284 break;
3285
2580 /* -- Unary ops --------------------------------------------------------- */ 3286 /* -- Unary ops --------------------------------------------------------- */
2581 3287
2582 case BC_MOV: 3288 case BC_MOV:
2583 | // RA = dst*8, RD = src*8 3289 | // RA = dst*8, RD = src*8
2584 | addu RD, BASE, RD 3290 | addu RD, BASE, RD
2585 | addu RA, BASE, RA 3291 | addu RA, BASE, RA
2586 | ldc1 f0, 0(RD) 3292 | lw SFRETHI, HI(RD)
3293 | lw SFRETLO, LO(RD)
2587 | ins_next1 3294 | ins_next1
2588 | sdc1 f0, 0(RA) 3295 | sw SFRETHI, HI(RA)
3296 | sw SFRETLO, LO(RA)
2589 | ins_next2 3297 | ins_next2
2590 break; 3298 break;
2591 case BC_NOT: 3299 case BC_NOT:
@@ -2602,16 +3310,25 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2602 break; 3310 break;
2603 case BC_UNM: 3311 case BC_UNM:
2604 | // RA = dst*8, RD = src*8 3312 | // RA = dst*8, RD = src*8
2605 | addu CARG3, BASE, RD 3313 | addu RB, BASE, RD
3314 | lw SFARG1HI, HI(RB)
2606 | addu RA, BASE, RA 3315 | addu RA, BASE, RA
2607 | lw TMP0, HI(CARG3) 3316 | bne SFARG1HI, TISNUM, >2
2608 | ldc1 f0, 0(CARG3) 3317 |. lw SFARG1LO, LO(RB)
2609 | sltiu AT, TMP0, LJ_TISNUM 3318 | lui TMP1, 0x8000
2610 | beqz AT, ->vmeta_unm 3319 | beq SFARG1LO, TMP1, ->vmeta_unm // Meta handler deals with -2^31.
2611 |. neg.d f0, f0 3320 |. negu SFARG1LO, SFARG1LO
3321 |1:
2612 | ins_next1 3322 | ins_next1
2613 | sdc1 f0, 0(RA) 3323 | sw SFARG1HI, HI(RA)
3324 | sw SFARG1LO, LO(RA)
2614 | ins_next2 3325 | ins_next2
3326 |2:
3327 | sltiu AT, SFARG1HI, LJ_TISNUM
3328 | beqz AT, ->vmeta_unm
3329 |. lui TMP1, 0x8000
3330 | b <1
3331 |. xor SFARG1HI, SFARG1HI, TMP1
2615 break; 3332 break;
2616 case BC_LEN: 3333 case BC_LEN:
2617 | // RA = dst*8, RD = src*8 3334 | // RA = dst*8, RD = src*8
@@ -2622,12 +3339,11 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2622 | li AT, LJ_TSTR 3339 | li AT, LJ_TSTR
2623 | bne TMP0, AT, >2 3340 | bne TMP0, AT, >2
2624 |. li AT, LJ_TTAB 3341 |. li AT, LJ_TTAB
2625 | lw CRET1, STR:CARG1->len 3342 | lw CRET1, STR:CARG1->len
2626 |1: 3343 |1:
2627 | mtc1 CRET1, f0
2628 | cvt.d.w f0, f0
2629 | ins_next1 3344 | ins_next1
2630 | sdc1 f0, 0(RA) 3345 | sw TISNUM, HI(RA)
3346 | sw CRET1, LO(RA)
2631 | ins_next2 3347 | ins_next2
2632 |2: 3348 |2:
2633 | bne TMP0, AT, ->vmeta_len 3349 | bne TMP0, AT, ->vmeta_len
@@ -2658,104 +3374,232 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2658 3374
2659 /* -- Binary ops -------------------------------------------------------- */ 3375 /* -- Binary ops -------------------------------------------------------- */
2660 3376
2661 |.macro ins_arithpre 3377 |.macro fpmod, a, b, c
3378 | bal ->vm_floor // floor(b/c)
3379 |. div.d FARG1, b, c
3380 | mul.d a, FRET1, c
3381 | sub.d a, b, a // b - floor(b/c)*c
3382 |.endmacro
3383
3384 |.macro sfpmod
3385 | addiu sp, sp, -16
3386 |
3387 | load_got __divdf3
3388 | sw SFARG1HI, HI(sp)
3389 | sw SFARG1LO, LO(sp)
3390 | sw SFARG2HI, 8+HI(sp)
3391 | call_extern
3392 |. sw SFARG2LO, 8+LO(sp)
3393 |
3394 | load_got floor
3395 | move SFARG1HI, SFRETHI
3396 | call_extern
3397 |. move SFARG1LO, SFRETLO
3398 |
3399 | load_got __muldf3
3400 | move SFARG1HI, SFRETHI
3401 | move SFARG1LO, SFRETLO
3402 | lw SFARG2HI, 8+HI(sp)
3403 | call_extern
3404 |. lw SFARG2LO, 8+LO(sp)
3405 |
3406 | load_got __subdf3
3407 | lw SFARG1HI, HI(sp)
3408 | lw SFARG1LO, LO(sp)
3409 | move SFARG2HI, SFRETHI
3410 | call_extern
3411 |. move SFARG2LO, SFRETLO
3412 |
3413 | addiu sp, sp, 16
3414 |.endmacro
3415
3416 |.macro ins_arithpre, label
2662 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); 3417 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
2663 | decode_RB8a RB, INS
2664 | decode_RB8b RB
2665 | decode_RDtoRC8 RC, RD
2666 | // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8 3418 | // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8
2667 ||switch (vk) { 3419 ||switch (vk) {
2668 ||case 0: 3420 ||case 0:
2669 | addu CARG3, BASE, RB 3421 | decode_RB8a RB, INS
2670 | addu CARG4, KBASE, RC 3422 | decode_RB8b RB
2671 | lw TMP1, HI(CARG3) 3423 | decode_RDtoRC8 RC, RD
2672 | ldc1 f20, 0(CARG3) 3424 | // RA = dst*8, RB = src1*8, RC = num_const*8
2673 | ldc1 f22, 0(CARG4) 3425 | addu RB, BASE, RB
2674 | sltiu AT, TMP1, LJ_TISNUM 3426 |.if "label" ~= "none"
3427 | b label
3428 |.endif
3429 |. addu RC, KBASE, RC
2675 || break; 3430 || break;
2676 ||case 1: 3431 ||case 1:
2677 | addu CARG4, BASE, RB 3432 | decode_RB8a RC, INS
2678 | addu CARG3, KBASE, RC 3433 | decode_RB8b RC
2679 | lw TMP1, HI(CARG4) 3434 | decode_RDtoRC8 RB, RD
2680 | ldc1 f22, 0(CARG4) 3435 | // RA = dst*8, RB = num_const*8, RC = src1*8
2681 | ldc1 f20, 0(CARG3) 3436 | addu RC, BASE, RC
2682 | sltiu AT, TMP1, LJ_TISNUM 3437 |.if "label" ~= "none"
3438 | b label
3439 |.endif
3440 |. addu RB, KBASE, RB
2683 || break; 3441 || break;
2684 ||default: 3442 ||default:
2685 | addu CARG3, BASE, RB 3443 | decode_RB8a RB, INS
2686 | addu CARG4, BASE, RC 3444 | decode_RB8b RB
2687 | lw TMP1, HI(CARG3) 3445 | decode_RDtoRC8 RC, RD
2688 | lw TMP2, HI(CARG4) 3446 | // RA = dst*8, RB = src1*8, RC = src2*8
2689 | ldc1 f20, 0(CARG3) 3447 | addu RB, BASE, RB
2690 | ldc1 f22, 0(CARG4) 3448 |.if "label" ~= "none"
2691 | sltiu AT, TMP1, LJ_TISNUM 3449 | b label
2692 | sltiu TMP0, TMP2, LJ_TISNUM 3450 |.endif
2693 | and AT, AT, TMP0 3451 |. addu RC, BASE, RC
2694 || break; 3452 || break;
2695 ||} 3453 ||}
2696 | beqz AT, ->vmeta_arith
2697 |. addu RA, BASE, RA
2698 |.endmacro 3454 |.endmacro
2699 | 3455 |
2700 |.macro fpmod, a, b, c 3456 |.macro ins_arith, intins, fpins, fpcall, label
2701 |->BC_MODVN_Z: 3457 | ins_arithpre none
2702 | bal ->vm_floor // floor(b/c)
2703 |. div.d FARG1, b, c
2704 | mul.d a, FRET1, c
2705 | sub.d a, b, a // b - floor(b/c)*c
2706 |.endmacro
2707 | 3458 |
2708 |.macro ins_arith, ins 3459 |.if "label" ~= "none"
2709 | ins_arithpre 3460 |label:
2710 |.if "ins" == "fpmod_" 3461 |.endif
2711 | b ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway. 3462 |
2712 |. nop 3463 | lw SFARG1HI, HI(RB)
3464 | lw SFARG2HI, HI(RC)
3465 |
3466 |.if "intins" ~= "div"
3467 |
3468 | // Check for two integers.
3469 | lw SFARG1LO, LO(RB)
3470 | bne SFARG1HI, TISNUM, >5
3471 |. lw SFARG2LO, LO(RC)
3472 | bne SFARG2HI, TISNUM, >5
3473 |
3474 |.if "intins" == "addu"
3475 |. intins CRET1, SFARG1LO, SFARG2LO
3476 | xor TMP1, CRET1, SFARG1LO // ((y^a) & (y^b)) < 0: overflow.
3477 | xor TMP2, CRET1, SFARG2LO
3478 | and TMP1, TMP1, TMP2
3479 | bltz TMP1, ->vmeta_arith
3480 |. addu RA, BASE, RA
3481 |.elif "intins" == "subu"
3482 |. intins CRET1, SFARG1LO, SFARG2LO
3483 | xor TMP1, CRET1, SFARG1LO // ((y^a) & (a^b)) < 0: overflow.
3484 | xor TMP2, SFARG1LO, SFARG2LO
3485 | and TMP1, TMP1, TMP2
3486 | bltz TMP1, ->vmeta_arith
3487 |. addu RA, BASE, RA
3488 |.elif "intins" == "mult"
3489 |. intins SFARG1LO, SFARG2LO
3490 | mflo CRET1
3491 | mfhi TMP2
3492 | sra TMP1, CRET1, 31
3493 | bne TMP1, TMP2, ->vmeta_arith
3494 |. addu RA, BASE, RA
2713 |.else 3495 |.else
2714 | ins f0, f20, f22 3496 |. load_got lj_vm_modi
3497 | beqz SFARG2LO, ->vmeta_arith
3498 |. addu RA, BASE, RA
3499 |.if ENDIAN_BE
3500 | move CARG1, SFARG1LO
3501 |.endif
3502 | call_extern
3503 |. move CARG2, SFARG2LO
3504 |.endif
3505 |
3506 | ins_next1
3507 | sw TISNUM, HI(RA)
3508 | sw CRET1, LO(RA)
3509 |3:
3510 | ins_next2
3511 |
3512 |.elif not FPU
3513 |
3514 | lw SFARG1LO, LO(RB)
3515 | lw SFARG2LO, LO(RC)
3516 |
3517 |.endif
3518 |
3519 |5: // Check for two numbers.
3520 | .FPU ldc1 f20, 0(RB)
3521 | sltiu AT, SFARG1HI, LJ_TISNUM
3522 | sltiu TMP0, SFARG2HI, LJ_TISNUM
3523 | .FPU ldc1 f22, 0(RC)
3524 | and AT, AT, TMP0
3525 | beqz AT, ->vmeta_arith
3526 |. addu RA, BASE, RA
3527 |
3528 |.if FPU
3529 | fpins FRET1, f20, f22
3530 |.elif "fpcall" == "sfpmod"
3531 | sfpmod
3532 |.else
3533 | load_got fpcall
3534 | call_extern
3535 |. nop
3536 |.endif
3537 |
2715 | ins_next1 3538 | ins_next1
2716 | sdc1 f0, 0(RA) 3539 |.if not FPU
3540 | sw SFRETHI, HI(RA)
3541 |.endif
3542 |.if "intins" ~= "div"
3543 | b <3
3544 |.endif
3545 |.if FPU
3546 |. sdc1 FRET1, 0(RA)
3547 |.else
3548 |. sw SFRETLO, LO(RA)
3549 |.endif
3550 |.if "intins" == "div"
2717 | ins_next2 3551 | ins_next2
2718 |.endif 3552 |.endif
3553 |
2719 |.endmacro 3554 |.endmacro
2720 3555
2721 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV: 3556 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
2722 | ins_arith add.d 3557 | ins_arith addu, add.d, __adddf3, none
2723 break; 3558 break;
2724 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV: 3559 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
2725 | ins_arith sub.d 3560 | ins_arith subu, sub.d, __subdf3, none
2726 break; 3561 break;
2727 case BC_MULVN: case BC_MULNV: case BC_MULVV: 3562 case BC_MULVN: case BC_MULNV: case BC_MULVV:
2728 | ins_arith mul.d 3563 | ins_arith mult, mul.d, __muldf3, none
3564 break;
3565 case BC_DIVVN:
3566 | ins_arith div, div.d, __divdf3, ->BC_DIVVN_Z
2729 break; 3567 break;
2730 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV: 3568 case BC_DIVNV: case BC_DIVVV:
2731 | ins_arith div.d 3569 | ins_arithpre ->BC_DIVVN_Z
2732 break; 3570 break;
2733 case BC_MODVN: 3571 case BC_MODVN:
2734 | ins_arith fpmod 3572 | ins_arith modi, fpmod, sfpmod, ->BC_MODVN_Z
2735 break; 3573 break;
2736 case BC_MODNV: case BC_MODVV: 3574 case BC_MODNV: case BC_MODVV:
2737 | ins_arith fpmod_ 3575 | ins_arithpre ->BC_MODVN_Z
2738 break; 3576 break;
2739 case BC_POW: 3577 case BC_POW:
2740 | decode_RB8a RB, INS 3578 | ins_arithpre none
2741 | decode_RB8b RB 3579 | lw SFARG1HI, HI(RB)
2742 | decode_RDtoRC8 RC, RD 3580 | lw SFARG2HI, HI(RC)
2743 | addu CARG3, BASE, RB 3581 | sltiu AT, SFARG1HI, LJ_TISNUM
2744 | addu CARG4, BASE, RC 3582 | sltiu TMP0, SFARG2HI, LJ_TISNUM
2745 | lw TMP1, HI(CARG3)
2746 | lw TMP2, HI(CARG4)
2747 | ldc1 FARG1, 0(CARG3)
2748 | ldc1 FARG2, 0(CARG4)
2749 | sltiu AT, TMP1, LJ_TISNUM
2750 | sltiu TMP0, TMP2, LJ_TISNUM
2751 | and AT, AT, TMP0 3583 | and AT, AT, TMP0
2752 | load_got pow 3584 | load_got pow
2753 | beqz AT, ->vmeta_arith 3585 | beqz AT, ->vmeta_arith
2754 |. addu RA, BASE, RA 3586 |. addu RA, BASE, RA
3587 |.if FPU
3588 | ldc1 FARG1, 0(RB)
3589 | ldc1 FARG2, 0(RC)
3590 |.else
3591 | lw SFARG1LO, LO(RB)
3592 | lw SFARG2LO, LO(RC)
3593 |.endif
2755 | call_extern 3594 | call_extern
2756 |. nop 3595 |. nop
2757 | ins_next1 3596 | ins_next1
3597 |.if FPU
2758 | sdc1 FRET1, 0(RA) 3598 | sdc1 FRET1, 0(RA)
3599 |.else
3600 | sw SFRETHI, HI(RA)
3601 | sw SFRETLO, LO(RA)
3602 |.endif
2759 | ins_next2 3603 | ins_next2
2760 break; 3604 break;
2761 3605
@@ -2778,10 +3622,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2778 | bnez CRET1, ->vmeta_binop 3622 | bnez CRET1, ->vmeta_binop
2779 |. lw BASE, L->base 3623 |. lw BASE, L->base
2780 | addu RB, BASE, MULTRES 3624 | addu RB, BASE, MULTRES
2781 | ldc1 f0, 0(RB) 3625 | lw SFRETHI, HI(RB)
3626 | lw SFRETLO, LO(RB)
2782 | addu RA, BASE, RA 3627 | addu RA, BASE, RA
2783 | ins_next1 3628 | ins_next1
2784 | sdc1 f0, 0(RA) // Copy result from RB to RA. 3629 | sw SFRETHI, HI(RA)
3630 | sw SFRETLO, LO(RA)
2785 | ins_next2 3631 | ins_next2
2786 break; 3632 break;
2787 3633
@@ -2816,20 +3662,21 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2816 case BC_KSHORT: 3662 case BC_KSHORT:
2817 | // RA = dst*8, RD = int16_literal*8 3663 | // RA = dst*8, RD = int16_literal*8
2818 | sra RD, INS, 16 3664 | sra RD, INS, 16
2819 | mtc1 RD, f0
2820 | addu RA, BASE, RA 3665 | addu RA, BASE, RA
2821 | cvt.d.w f0, f0
2822 | ins_next1 3666 | ins_next1
2823 | sdc1 f0, 0(RA) 3667 | sw TISNUM, HI(RA)
3668 | sw RD, LO(RA)
2824 | ins_next2 3669 | ins_next2
2825 break; 3670 break;
2826 case BC_KNUM: 3671 case BC_KNUM:
2827 | // RA = dst*8, RD = num_const*8 3672 | // RA = dst*8, RD = num_const*8
2828 | addu RD, KBASE, RD 3673 | addu RD, KBASE, RD
2829 | addu RA, BASE, RA 3674 | addu RA, BASE, RA
2830 | ldc1 f0, 0(RD) 3675 | lw SFRETHI, HI(RD)
3676 | lw SFRETLO, LO(RD)
2831 | ins_next1 3677 | ins_next1
2832 | sdc1 f0, 0(RA) 3678 | sw SFRETHI, HI(RA)
3679 | sw SFRETLO, LO(RA)
2833 | ins_next2 3680 | ins_next2
2834 break; 3681 break;
2835 case BC_KPRI: 3682 case BC_KPRI:
@@ -2865,9 +3712,11 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2865 | lw UPVAL:RB, LFUNC:RD->uvptr 3712 | lw UPVAL:RB, LFUNC:RD->uvptr
2866 | ins_next1 3713 | ins_next1
2867 | lw TMP1, UPVAL:RB->v 3714 | lw TMP1, UPVAL:RB->v
2868 | ldc1 f0, 0(TMP1) 3715 | lw SFRETHI, HI(TMP1)
3716 | lw SFRETLO, LO(TMP1)
2869 | addu RA, BASE, RA 3717 | addu RA, BASE, RA
2870 | sdc1 f0, 0(RA) 3718 | sw SFRETHI, HI(RA)
3719 | sw SFRETLO, LO(RA)
2871 | ins_next2 3720 | ins_next2
2872 break; 3721 break;
2873 case BC_USETV: 3722 case BC_USETV:
@@ -2876,26 +3725,27 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2876 | srl RA, RA, 1 3725 | srl RA, RA, 1
2877 | addu RD, BASE, RD 3726 | addu RD, BASE, RD
2878 | addu RA, RA, LFUNC:RB 3727 | addu RA, RA, LFUNC:RB
2879 | ldc1 f0, 0(RD)
2880 | lw UPVAL:RB, LFUNC:RA->uvptr 3728 | lw UPVAL:RB, LFUNC:RA->uvptr
3729 | lw SFRETHI, HI(RD)
3730 | lw SFRETLO, LO(RD)
2881 | lbu TMP3, UPVAL:RB->marked 3731 | lbu TMP3, UPVAL:RB->marked
2882 | lw CARG2, UPVAL:RB->v 3732 | lw CARG2, UPVAL:RB->v
2883 | andi TMP3, TMP3, LJ_GC_BLACK // isblack(uv) 3733 | andi TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
2884 | lbu TMP0, UPVAL:RB->closed 3734 | lbu TMP0, UPVAL:RB->closed
2885 | lw TMP2, HI(RD) 3735 | sw SFRETHI, HI(CARG2)
2886 | sdc1 f0, 0(CARG2) 3736 | sw SFRETLO, LO(CARG2)
2887 | li AT, LJ_GC_BLACK|1 3737 | li AT, LJ_GC_BLACK|1
2888 | or TMP3, TMP3, TMP0 3738 | or TMP3, TMP3, TMP0
2889 | beq TMP3, AT, >2 // Upvalue is closed and black? 3739 | beq TMP3, AT, >2 // Upvalue is closed and black?
2890 |. addiu TMP2, TMP2, -(LJ_TNUMX+1) 3740 |. addiu TMP2, SFRETHI, -(LJ_TNUMX+1)
2891 |1: 3741 |1:
2892 | ins_next 3742 | ins_next
2893 | 3743 |
2894 |2: // Check if new value is collectable. 3744 |2: // Check if new value is collectable.
2895 | sltiu AT, TMP2, LJ_TISGCV - (LJ_TNUMX+1) 3745 | sltiu AT, TMP2, LJ_TISGCV - (LJ_TNUMX+1)
2896 | beqz AT, <1 // tvisgcv(v) 3746 | beqz AT, <1 // tvisgcv(v)
2897 |. lw TMP1, LO(RD) 3747 |. nop
2898 | lbu TMP3, GCOBJ:TMP1->gch.marked 3748 | lbu TMP3, GCOBJ:SFRETLO->gch.marked
2899 | andi TMP3, TMP3, LJ_GC_WHITES // iswhite(v) 3749 | andi TMP3, TMP3, LJ_GC_WHITES // iswhite(v)
2900 | beqz TMP3, <1 3750 | beqz TMP3, <1
2901 |. load_got lj_gc_barrieruv 3751 |. load_got lj_gc_barrieruv
@@ -2943,11 +3793,13 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2943 | srl RA, RA, 1 3793 | srl RA, RA, 1
2944 | addu RD, KBASE, RD 3794 | addu RD, KBASE, RD
2945 | addu RA, RA, LFUNC:RB 3795 | addu RA, RA, LFUNC:RB
2946 | ldc1 f0, 0(RD) 3796 | lw UPVAL:RB, LFUNC:RA->uvptr
2947 | lw UPVAL:RB, LFUNC:RA->uvptr 3797 | lw SFRETHI, HI(RD)
3798 | lw SFRETLO, LO(RD)
3799 | lw TMP1, UPVAL:RB->v
2948 | ins_next1 3800 | ins_next1
2949 | lw TMP1, UPVAL:RB->v 3801 | sw SFRETHI, HI(TMP1)
2950 | sdc1 f0, 0(TMP1) 3802 | sw SFRETLO, LO(TMP1)
2951 | ins_next2 3803 | ins_next2
2952 break; 3804 break;
2953 case BC_USETP: 3805 case BC_USETP:
@@ -2957,10 +3809,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2957 | srl TMP0, RD, 3 3809 | srl TMP0, RD, 3
2958 | addu RA, RA, LFUNC:RB 3810 | addu RA, RA, LFUNC:RB
2959 | not TMP0, TMP0 3811 | not TMP0, TMP0
2960 | lw UPVAL:RB, LFUNC:RA->uvptr 3812 | lw UPVAL:RB, LFUNC:RA->uvptr
2961 | ins_next1 3813 | ins_next1
2962 | lw TMP1, UPVAL:RB->v 3814 | lw TMP1, UPVAL:RB->v
2963 | sw TMP0, HI(TMP1) 3815 | sw TMP0, HI(TMP1)
2964 | ins_next2 3816 | ins_next2
2965 break; 3817 break;
2966 3818
@@ -2996,8 +3848,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2996 | li TMP0, LJ_TFUNC 3848 | li TMP0, LJ_TFUNC
2997 | ins_next1 3849 | ins_next1
2998 | addu RA, BASE, RA 3850 | addu RA, BASE, RA
2999 | sw TMP0, HI(RA)
3000 | sw LFUNC:CRET1, LO(RA) 3851 | sw LFUNC:CRET1, LO(RA)
3852 | sw TMP0, HI(RA)
3001 | ins_next2 3853 | ins_next2
3002 break; 3854 break;
3003 3855
@@ -3078,31 +3930,23 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3078 | lw TMP2, HI(CARG3) 3930 | lw TMP2, HI(CARG3)
3079 | lw TAB:RB, LO(CARG2) 3931 | lw TAB:RB, LO(CARG2)
3080 | li AT, LJ_TTAB 3932 | li AT, LJ_TTAB
3081 | ldc1 f0, 0(CARG3)
3082 | bne TMP1, AT, ->vmeta_tgetv 3933 | bne TMP1, AT, ->vmeta_tgetv
3083 |. addu RA, BASE, RA 3934 |. addu RA, BASE, RA
3084 | sltiu AT, TMP2, LJ_TISNUM 3935 | bne TMP2, TISNUM, >5
3085 | beqz AT, >5 3936 |. lw RC, LO(CARG3)
3086 |. li AT, LJ_TSTR 3937 | lw TMP0, TAB:RB->asize
3087 |
3088 | // Convert number key to integer, check for integerness and range.
3089 | cvt.w.d f2, f0
3090 | lw TMP0, TAB:RB->asize
3091 | mfc1 TMP2, f2
3092 | cvt.d.w f4, f2
3093 | lw TMP1, TAB:RB->array 3938 | lw TMP1, TAB:RB->array
3094 | c.eq.d f0, f4 3939 | sltu AT, RC, TMP0
3095 | sltu AT, TMP2, TMP0 3940 | sll TMP2, RC, 3
3096 | movf AT, r0
3097 | sll TMP2, TMP2, 3
3098 | beqz AT, ->vmeta_tgetv // Integer key and in array part? 3941 | beqz AT, ->vmeta_tgetv // Integer key and in array part?
3099 |. addu TMP2, TMP1, TMP2 3942 |. addu TMP2, TMP1, TMP2
3100 | lw TMP0, HI(TMP2) 3943 | lw SFRETHI, HI(TMP2)
3101 | beq TMP0, TISNIL, >2 3944 | beq SFRETHI, TISNIL, >2
3102 |. ldc1 f0, 0(TMP2) 3945 |. lw SFRETLO, LO(TMP2)
3103 |1: 3946 |1:
3104 | ins_next1 3947 | ins_next1
3105 | sdc1 f0, 0(RA) 3948 | sw SFRETHI, HI(RA)
3949 | sw SFRETLO, LO(RA)
3106 | ins_next2 3950 | ins_next2
3107 | 3951 |
3108 |2: // Check for __index if table value is nil. 3952 |2: // Check for __index if table value is nil.
@@ -3117,8 +3961,9 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3117 |. nop 3961 |. nop
3118 | 3962 |
3119 |5: 3963 |5:
3964 | li AT, LJ_TSTR
3120 | bne TMP2, AT, ->vmeta_tgetv 3965 | bne TMP2, AT, ->vmeta_tgetv
3121 |. lw STR:RC, LO(CARG3) 3966 |. nop
3122 | b ->BC_TGETS_Z // String key? 3967 | b ->BC_TGETS_Z // String key?
3123 |. nop 3968 |. nop
3124 break; 3969 break;
@@ -3150,18 +3995,18 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3150 | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2) 3995 | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2)
3151 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) 3996 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2)
3152 | lw NODE:TMP1, NODE:TMP2->next 3997 | lw NODE:TMP1, NODE:TMP2->next
3153 | lw CARG2, offsetof(Node, val)+HI(NODE:TMP2) 3998 | lw SFRETHI, offsetof(Node, val)+HI(NODE:TMP2)
3154 | addiu CARG1, CARG1, -LJ_TSTR 3999 | addiu CARG1, CARG1, -LJ_TSTR
3155 | xor TMP0, TMP0, STR:RC 4000 | xor TMP0, TMP0, STR:RC
3156 | or AT, CARG1, TMP0 4001 | or AT, CARG1, TMP0
3157 | bnez AT, >4 4002 | bnez AT, >4
3158 |. lw TAB:TMP3, TAB:RB->metatable 4003 |. lw TAB:TMP3, TAB:RB->metatable
3159 | beq CARG2, TISNIL, >5 // Key found, but nil value? 4004 | beq SFRETHI, TISNIL, >5 // Key found, but nil value?
3160 |. lw CARG1, offsetof(Node, val)+LO(NODE:TMP2) 4005 |. lw SFRETLO, offsetof(Node, val)+LO(NODE:TMP2)
3161 |3: 4006 |3:
3162 | ins_next1 4007 | ins_next1
3163 | sw CARG2, HI(RA) 4008 | sw SFRETHI, HI(RA)
3164 | sw CARG1, LO(RA) 4009 | sw SFRETLO, LO(RA)
3165 | ins_next2 4010 | ins_next2
3166 | 4011 |
3167 |4: // Follow hash chain. 4012 |4: // Follow hash chain.
@@ -3171,7 +4016,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3171 | 4016 |
3172 |5: // Check for __index if table value is nil. 4017 |5: // Check for __index if table value is nil.
3173 | beqz TAB:TMP3, <3 // No metatable: done. 4018 | beqz TAB:TMP3, <3 // No metatable: done.
3174 |. li CARG2, LJ_TNIL 4019 |. li SFRETHI, LJ_TNIL
3175 | lbu TMP0, TAB:TMP3->nomm 4020 | lbu TMP0, TAB:TMP3->nomm
3176 | andi TMP0, TMP0, 1<<MM_index 4021 | andi TMP0, TMP0, 1<<MM_index
3177 | bnez TMP0, <3 // 'no __index' flag set: done. 4022 | bnez TMP0, <3 // 'no __index' flag set: done.
@@ -3196,12 +4041,13 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3196 | sltu AT, TMP0, TMP1 4041 | sltu AT, TMP0, TMP1
3197 | beqz AT, ->vmeta_tgetb 4042 | beqz AT, ->vmeta_tgetb
3198 |. addu RC, TMP2, RC 4043 |. addu RC, TMP2, RC
3199 | lw TMP1, HI(RC) 4044 | lw SFRETHI, HI(RC)
3200 | beq TMP1, TISNIL, >5 4045 | beq SFRETHI, TISNIL, >5
3201 |. ldc1 f0, 0(RC) 4046 |. lw SFRETLO, LO(RC)
3202 |1: 4047 |1:
3203 | ins_next1 4048 | ins_next1
3204 | sdc1 f0, 0(RA) 4049 | sw SFRETHI, HI(RA)
4050 | sw SFRETLO, LO(RA)
3205 | ins_next2 4051 | ins_next2
3206 | 4052 |
3207 |5: // Check for __index if table value is nil. 4053 |5: // Check for __index if table value is nil.
@@ -3212,9 +4058,33 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3212 | andi TMP1, TMP1, 1<<MM_index 4058 | andi TMP1, TMP1, 1<<MM_index
3213 | bnez TMP1, <1 // 'no __index' flag set: done. 4059 | bnez TMP1, <1 // 'no __index' flag set: done.
3214 |. nop 4060 |. nop
3215 | b ->vmeta_tgetb // Caveat: preserve TMP0! 4061 | b ->vmeta_tgetb // Caveat: preserve TMP0 and CARG2!
3216 |. nop 4062 |. nop
3217 break; 4063 break;
4064 case BC_TGETR:
4065 | // RA = dst*8, RB = table*8, RC = key*8
4066 | decode_RB8a RB, INS
4067 | decode_RB8b RB
4068 | decode_RDtoRC8 RC, RD
4069 | addu RB, BASE, RB
4070 | addu RC, BASE, RC
4071 | lw TAB:CARG1, LO(RB)
4072 | lw CARG2, LO(RC)
4073 | addu RA, BASE, RA
4074 | lw TMP0, TAB:CARG1->asize
4075 | lw TMP1, TAB:CARG1->array
4076 | sltu AT, CARG2, TMP0
4077 | sll TMP2, CARG2, 3
4078 | beqz AT, ->vmeta_tgetr // In array part?
4079 |. addu CRET1, TMP1, TMP2
4080 | lw SFARG2HI, HI(CRET1)
4081 | lw SFARG2LO, LO(CRET1)
4082 |->BC_TGETR_Z:
4083 | ins_next1
4084 | sw SFARG2HI, HI(RA)
4085 | sw SFARG2LO, LO(RA)
4086 | ins_next2
4087 break;
3218 4088
3219 case BC_TSETV: 4089 case BC_TSETV:
3220 | // RA = src*8, RB = table*8, RC = key*8 4090 | // RA = src*8, RB = table*8, RC = key*8
@@ -3227,33 +4097,26 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3227 | lw TMP2, HI(CARG3) 4097 | lw TMP2, HI(CARG3)
3228 | lw TAB:RB, LO(CARG2) 4098 | lw TAB:RB, LO(CARG2)
3229 | li AT, LJ_TTAB 4099 | li AT, LJ_TTAB
3230 | ldc1 f0, 0(CARG3)
3231 | bne TMP1, AT, ->vmeta_tsetv 4100 | bne TMP1, AT, ->vmeta_tsetv
3232 |. addu RA, BASE, RA 4101 |. addu RA, BASE, RA
3233 | sltiu AT, TMP2, LJ_TISNUM 4102 | bne TMP2, TISNUM, >5
3234 | beqz AT, >5 4103 |. lw RC, LO(CARG3)
3235 |. li AT, LJ_TSTR 4104 | lw TMP0, TAB:RB->asize
3236 |
3237 | // Convert number key to integer, check for integerness and range.
3238 | cvt.w.d f2, f0
3239 | lw TMP0, TAB:RB->asize
3240 | mfc1 TMP2, f2
3241 | cvt.d.w f4, f2
3242 | lw TMP1, TAB:RB->array 4105 | lw TMP1, TAB:RB->array
3243 | c.eq.d f0, f4 4106 | sltu AT, RC, TMP0
3244 | sltu AT, TMP2, TMP0 4107 | sll TMP2, RC, 3
3245 | movf AT, r0
3246 | sll TMP2, TMP2, 3
3247 | beqz AT, ->vmeta_tsetv // Integer key and in array part? 4108 | beqz AT, ->vmeta_tsetv // Integer key and in array part?
3248 |. addu TMP1, TMP1, TMP2 4109 |. addu TMP1, TMP1, TMP2
3249 | lbu TMP3, TAB:RB->marked
3250 | lw TMP0, HI(TMP1) 4110 | lw TMP0, HI(TMP1)
4111 | lbu TMP3, TAB:RB->marked
4112 | lw SFRETHI, HI(RA)
3251 | beq TMP0, TISNIL, >3 4113 | beq TMP0, TISNIL, >3
3252 |. ldc1 f0, 0(RA) 4114 |. lw SFRETLO, LO(RA)
3253 |1: 4115 |1:
3254 | andi AT, TMP3, LJ_GC_BLACK // isblack(table) 4116 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
3255 | bnez AT, >7 4117 | sw SFRETHI, HI(TMP1)
3256 |. sdc1 f0, 0(TMP1) 4118 | bnez AT, >7
4119 |. sw SFRETLO, LO(TMP1)
3257 |2: 4120 |2:
3258 | ins_next 4121 | ins_next
3259 | 4122 |
@@ -3269,8 +4132,9 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3269 |. nop 4132 |. nop
3270 | 4133 |
3271 |5: 4134 |5:
4135 | li AT, LJ_TSTR
3272 | bne TMP2, AT, ->vmeta_tsetv 4136 | bne TMP2, AT, ->vmeta_tsetv
3273 |. lw STR:RC, LO(CARG3) 4137 |. nop
3274 | b ->BC_TSETS_Z // String key? 4138 | b ->BC_TSETS_Z // String key?
3275 |. nop 4139 |. nop
3276 | 4140 |
@@ -3302,7 +4166,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3302 | sll TMP1, TMP1, 3 4166 | sll TMP1, TMP1, 3
3303 | subu TMP1, TMP0, TMP1 4167 | subu TMP1, TMP0, TMP1
3304 | addu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8) 4168 | addu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
4169 |.if FPU
3305 | ldc1 f20, 0(RA) 4170 | ldc1 f20, 0(RA)
4171 |.else
4172 | lw SFRETHI, HI(RA)
4173 | lw SFRETLO, LO(RA)
4174 |.endif
3306 |1: 4175 |1:
3307 | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2) 4176 | lw CARG1, offsetof(Node, key)+HI(NODE:TMP2)
3308 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2) 4177 | lw TMP0, offsetof(Node, key)+LO(NODE:TMP2)
@@ -3316,8 +4185,14 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3316 |. lw TAB:TMP0, TAB:RB->metatable 4185 |. lw TAB:TMP0, TAB:RB->metatable
3317 |2: 4186 |2:
3318 | andi AT, TMP3, LJ_GC_BLACK // isblack(table) 4187 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4188 |.if FPU
3319 | bnez AT, >7 4189 | bnez AT, >7
3320 |. sdc1 f20, NODE:TMP2->val 4190 |. sdc1 f20, NODE:TMP2->val
4191 |.else
4192 | sw SFRETHI, NODE:TMP2->val.u32.hi
4193 | bnez AT, >7
4194 |. sw SFRETLO, NODE:TMP2->val.u32.lo
4195 |.endif
3321 |3: 4196 |3:
3322 | ins_next 4197 | ins_next
3323 | 4198 |
@@ -3355,8 +4230,16 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3355 |. move CARG1, L 4230 |. move CARG1, L
3356 | // Returns TValue *. 4231 | // Returns TValue *.
3357 | lw BASE, L->base 4232 | lw BASE, L->base
4233 |.if FPU
3358 | b <3 // No 2nd write barrier needed. 4234 | b <3 // No 2nd write barrier needed.
3359 |. sdc1 f20, 0(CRET1) 4235 |. sdc1 f20, 0(CRET1)
4236 |.else
4237 | lw SFARG1HI, HI(RA)
4238 | lw SFARG1LO, LO(RA)
4239 | sw SFARG1HI, HI(CRET1)
4240 | b <3 // No 2nd write barrier needed.
4241 |. sw SFARG1LO, LO(CRET1)
4242 |.endif
3360 | 4243 |
3361 |7: // Possible table write barrier for the value. Skip valiswhite check. 4244 |7: // Possible table write barrier for the value. Skip valiswhite check.
3362 | barrierback TAB:RB, TMP3, TMP0, <3 4245 | barrierback TAB:RB, TMP3, TMP0, <3
@@ -3381,11 +4264,13 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3381 | lw TMP1, HI(RC) 4264 | lw TMP1, HI(RC)
3382 | lbu TMP3, TAB:RB->marked 4265 | lbu TMP3, TAB:RB->marked
3383 | beq TMP1, TISNIL, >5 4266 | beq TMP1, TISNIL, >5
3384 |. ldc1 f0, 0(RA)
3385 |1: 4267 |1:
4268 |. lw SFRETHI, HI(RA)
4269 | lw SFRETLO, LO(RA)
3386 | andi AT, TMP3, LJ_GC_BLACK // isblack(table) 4270 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4271 | sw SFRETHI, HI(RC)
3387 | bnez AT, >7 4272 | bnez AT, >7
3388 |. sdc1 f0, 0(RC) 4273 |. sw SFRETLO, LO(RC)
3389 |2: 4274 |2:
3390 | ins_next 4275 | ins_next
3391 | 4276 |
@@ -3397,12 +4282,43 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3397 | andi TMP1, TMP1, 1<<MM_newindex 4282 | andi TMP1, TMP1, 1<<MM_newindex
3398 | bnez TMP1, <1 // 'no __newindex' flag set: done. 4283 | bnez TMP1, <1 // 'no __newindex' flag set: done.
3399 |. nop 4284 |. nop
3400 | b ->vmeta_tsetb // Caveat: preserve TMP0! 4285 | b ->vmeta_tsetb // Caveat: preserve TMP0 and CARG2!
3401 |. nop 4286 |. nop
3402 | 4287 |
3403 |7: // Possible table write barrier for the value. Skip valiswhite check. 4288 |7: // Possible table write barrier for the value. Skip valiswhite check.
3404 | barrierback TAB:RB, TMP3, TMP0, <2 4289 | barrierback TAB:RB, TMP3, TMP0, <2
3405 break; 4290 break;
4291 case BC_TSETR:
4292 | // RA = dst*8, RB = table*8, RC = key*8
4293 | decode_RB8a RB, INS
4294 | decode_RB8b RB
4295 | decode_RDtoRC8 RC, RD
4296 | addu CARG1, BASE, RB
4297 | addu CARG3, BASE, RC
4298 | lw TAB:CARG2, LO(CARG1)
4299 | lw CARG3, LO(CARG3)
4300 | lbu TMP3, TAB:CARG2->marked
4301 | lw TMP0, TAB:CARG2->asize
4302 | lw TMP1, TAB:CARG2->array
4303 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4304 | bnez AT, >7
4305 |. addu RA, BASE, RA
4306 |2:
4307 | sltu AT, CARG3, TMP0
4308 | sll TMP2, CARG3, 3
4309 | beqz AT, ->vmeta_tsetr // In array part?
4310 |. addu CRET1, TMP1, TMP2
4311 |->BC_TSETR_Z:
4312 | lw SFARG1HI, HI(RA)
4313 | lw SFARG1LO, LO(RA)
4314 | ins_next1
4315 | sw SFARG1HI, HI(CRET1)
4316 | sw SFARG1LO, LO(CRET1)
4317 | ins_next2
4318 |
4319 |7: // Possible table write barrier for the value. Skip valiswhite check.
4320 | barrierback TAB:CARG2, TMP3, TMP0, <2
4321 break;
3406 4322
3407 case BC_TSETM: 4323 case BC_TSETM:
3408 | // RA = base*8 (table at base-1), RD = num_const*8 (start index) 4324 | // RA = base*8 (table at base-1), RD = num_const*8 (start index)
@@ -3425,10 +4341,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3425 | addu TMP1, TMP1, CARG1 4341 | addu TMP1, TMP1, CARG1
3426 | andi TMP0, TMP3, LJ_GC_BLACK // isblack(table) 4342 | andi TMP0, TMP3, LJ_GC_BLACK // isblack(table)
3427 |3: // Copy result slots to table. 4343 |3: // Copy result slots to table.
3428 | ldc1 f0, 0(RA) 4344 | lw SFRETHI, HI(RA)
4345 | lw SFRETLO, LO(RA)
3429 | addiu RA, RA, 8 4346 | addiu RA, RA, 8
3430 | sltu AT, RA, TMP2 4347 | sltu AT, RA, TMP2
3431 | sdc1 f0, 0(TMP1) 4348 | sw SFRETHI, HI(TMP1)
4349 | sw SFRETLO, LO(TMP1)
3432 | bnez AT, <3 4350 | bnez AT, <3
3433 |. addiu TMP1, TMP1, 8 4351 |. addiu TMP1, TMP1, 8
3434 | bnez TMP0, >7 4352 | bnez TMP0, >7
@@ -3503,10 +4421,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3503 | beqz NARGS8:RC, >3 4421 | beqz NARGS8:RC, >3
3504 |. move TMP3, NARGS8:RC 4422 |. move TMP3, NARGS8:RC
3505 |2: 4423 |2:
3506 | ldc1 f0, 0(RA) 4424 | lw SFRETHI, HI(RA)
4425 | lw SFRETLO, LO(RA)
3507 | addiu RA, RA, 8 4426 | addiu RA, RA, 8
3508 | addiu TMP3, TMP3, -8 4427 | addiu TMP3, TMP3, -8
3509 | sdc1 f0, 0(TMP2) 4428 | sw SFRETHI, HI(TMP2)
4429 | sw SFRETLO, LO(TMP2)
3510 | bnez TMP3, <2 4430 | bnez TMP3, <2
3511 |. addiu TMP2, TMP2, 8 4431 |. addiu TMP2, TMP2, 8
3512 |3: 4432 |3:
@@ -3543,12 +4463,16 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3543 | li AT, LJ_TFUNC 4463 | li AT, LJ_TFUNC
3544 | lw TMP1, -24+HI(BASE) 4464 | lw TMP1, -24+HI(BASE)
3545 | lw LFUNC:RB, -24+LO(BASE) 4465 | lw LFUNC:RB, -24+LO(BASE)
3546 | ldc1 f2, -8(BASE) 4466 | lw SFARG1HI, -16+HI(BASE)
3547 | ldc1 f0, -16(BASE) 4467 | lw SFARG1LO, -16+LO(BASE)
4468 | lw SFARG2HI, -8+HI(BASE)
4469 | lw SFARG2LO, -8+LO(BASE)
3548 | sw TMP1, HI(BASE) // Copy callable. 4470 | sw TMP1, HI(BASE) // Copy callable.
3549 | sw LFUNC:RB, LO(BASE) 4471 | sw LFUNC:RB, LO(BASE)
3550 | sdc1 f2, 16(BASE) // Copy control var. 4472 | sw SFARG1HI, 8+HI(BASE) // Copy state.
3551 | sdc1 f0, 8(BASE) // Copy state. 4473 | sw SFARG1LO, 8+LO(BASE)
4474 | sw SFARG2HI, 16+HI(BASE) // Copy control var.
4475 | sw SFARG2LO, 16+LO(BASE)
3552 | addiu BASE, BASE, 8 4476 | addiu BASE, BASE, 8
3553 | bne TMP1, AT, ->vmeta_call 4477 | bne TMP1, AT, ->vmeta_call
3554 |. li NARGS8:RC, 16 // Iterators get 2 arguments. 4478 |. li NARGS8:RC, 16 // Iterators get 2 arguments.
@@ -3571,20 +4495,20 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3571 | beqz AT, >5 // Index points after array part? 4495 | beqz AT, >5 // Index points after array part?
3572 |. sll TMP3, RC, 3 4496 |. sll TMP3, RC, 3
3573 | addu TMP3, TMP1, TMP3 4497 | addu TMP3, TMP1, TMP3
3574 | lw TMP2, HI(TMP3) 4498 | lw SFARG1HI, HI(TMP3)
3575 | ldc1 f0, 0(TMP3) 4499 | lw SFARG1LO, LO(TMP3)
3576 | mtc1 RC, f2
3577 | lhu RD, -4+OFS_RD(PC) 4500 | lhu RD, -4+OFS_RD(PC)
3578 | beq TMP2, TISNIL, <1 // Skip holes in array part. 4501 | sw TISNUM, HI(RA)
4502 | sw RC, LO(RA)
4503 | beq SFARG1HI, TISNIL, <1 // Skip holes in array part.
3579 |. addiu RC, RC, 1 4504 |. addiu RC, RC, 1
3580 | cvt.d.w f2, f2 4505 | sw SFARG1HI, 8+HI(RA)
4506 | sw SFARG1LO, 8+LO(RA)
3581 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) 4507 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3582 | sdc1 f0, 8(RA)
3583 | decode_RD4b RD 4508 | decode_RD4b RD
3584 | addu RD, RD, TMP3 4509 | addu RD, RD, TMP3
3585 | sw RC, -8+LO(RA) // Update control var. 4510 | sw RC, -8+LO(RA) // Update control var.
3586 | addu PC, PC, RD 4511 | addu PC, PC, RD
3587 | sdc1 f2, 0(RA)
3588 |3: 4512 |3:
3589 | ins_next 4513 | ins_next
3590 | 4514 |
@@ -3599,18 +4523,21 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3599 | sll RB, RC, 3 4523 | sll RB, RC, 3
3600 | subu TMP3, TMP3, RB 4524 | subu TMP3, TMP3, RB
3601 | addu NODE:TMP3, TMP3, TMP2 4525 | addu NODE:TMP3, TMP3, TMP2
3602 | lw RB, HI(NODE:TMP3) 4526 | lw SFARG1HI, NODE:TMP3->val.u32.hi
3603 | ldc1 f0, 0(NODE:TMP3) 4527 | lw SFARG1LO, NODE:TMP3->val.u32.lo
3604 | lhu RD, -4+OFS_RD(PC) 4528 | lhu RD, -4+OFS_RD(PC)
3605 | beq RB, TISNIL, <6 // Skip holes in hash part. 4529 | beq SFARG1HI, TISNIL, <6 // Skip holes in hash part.
3606 |. addiu RC, RC, 1 4530 |. addiu RC, RC, 1
3607 | ldc1 f2, NODE:TMP3->key 4531 | lw SFARG2HI, NODE:TMP3->key.u32.hi
4532 | lw SFARG2LO, NODE:TMP3->key.u32.lo
3608 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535) 4533 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3609 | sdc1 f0, 8(RA) 4534 | sw SFARG1HI, 8+HI(RA)
4535 | sw SFARG1LO, 8+LO(RA)
3610 | addu RC, RC, TMP0 4536 | addu RC, RC, TMP0
3611 | decode_RD4b RD 4537 | decode_RD4b RD
3612 | addu RD, RD, TMP3 4538 | addu RD, RD, TMP3
3613 | sdc1 f2, 0(RA) 4539 | sw SFARG2HI, HI(RA)
4540 | sw SFARG2LO, LO(RA)
3614 | addu PC, PC, RD 4541 | addu PC, PC, RD
3615 | b <3 4542 | b <3
3616 |. sw RC, -8+LO(RA) // Update control var. 4543 |. sw RC, -8+LO(RA) // Update control var.
@@ -3690,9 +4617,11 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3690 | bnez AT, >7 4617 | bnez AT, >7
3691 |. addiu MULTRES, TMP1, 8 4618 |. addiu MULTRES, TMP1, 8
3692 |6: 4619 |6:
3693 | ldc1 f0, 0(RC) 4620 | lw SFRETHI, HI(RC)
4621 | lw SFRETLO, LO(RC)
3694 | addiu RC, RC, 8 4622 | addiu RC, RC, 8
3695 | sdc1 f0, 0(RA) 4623 | sw SFRETHI, HI(RA)
4624 | sw SFRETLO, LO(RA)
3696 | sltu AT, RC, TMP3 4625 | sltu AT, RC, TMP3
3697 | bnez AT, <6 // More vararg slots? 4626 | bnez AT, <6 // More vararg slots?
3698 |. addiu RA, RA, 8 4627 |. addiu RA, RA, 8
@@ -3748,10 +4677,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3748 | beqz RC, >3 4677 | beqz RC, >3
3749 |. subu BASE, TMP2, TMP0 4678 |. subu BASE, TMP2, TMP0
3750 |2: 4679 |2:
3751 | ldc1 f0, 0(RA) 4680 | lw SFRETHI, HI(RA)
4681 | lw SFRETLO, LO(RA)
3752 | addiu RA, RA, 8 4682 | addiu RA, RA, 8
3753 | addiu RC, RC, -8 4683 | addiu RC, RC, -8
3754 | sdc1 f0, 0(TMP2) 4684 | sw SFRETHI, HI(TMP2)
4685 | sw SFRETLO, LO(TMP2)
3755 | bnez RC, <2 4686 | bnez RC, <2
3756 |. addiu TMP2, TMP2, 8 4687 |. addiu TMP2, TMP2, 8
3757 |3: 4688 |3:
@@ -3792,14 +4723,16 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3792 | lw INS, -4(PC) 4723 | lw INS, -4(PC)
3793 | addiu TMP2, BASE, -8 4724 | addiu TMP2, BASE, -8
3794 if (op == BC_RET1) { 4725 if (op == BC_RET1) {
3795 | ldc1 f0, 0(RA) 4726 | lw SFRETHI, HI(RA)
4727 | lw SFRETLO, LO(RA)
3796 } 4728 }
3797 | decode_RB8a RB, INS 4729 | decode_RB8a RB, INS
3798 | decode_RA8a RA, INS 4730 | decode_RA8a RA, INS
3799 | decode_RB8b RB 4731 | decode_RB8b RB
3800 | decode_RA8b RA 4732 | decode_RA8b RA
3801 if (op == BC_RET1) { 4733 if (op == BC_RET1) {
3802 | sdc1 f0, 0(TMP2) 4734 | sw SFRETHI, HI(TMP2)
4735 | sw SFRETLO, LO(TMP2)
3803 } 4736 }
3804 | subu BASE, TMP2, RA 4737 | subu BASE, TMP2, RA
3805 |5: 4738 |5:
@@ -3841,69 +4774,147 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3841 | // RA = base*8, RD = target (after end of loop or start of loop) 4774 | // RA = base*8, RD = target (after end of loop or start of loop)
3842 vk = (op == BC_IFORL || op == BC_JFORL); 4775 vk = (op == BC_IFORL || op == BC_JFORL);
3843 | addu RA, BASE, RA 4776 | addu RA, BASE, RA
3844 if (vk) { 4777 | lw SFARG1HI, FORL_IDX*8+HI(RA)
3845 | ldc1 f0, FORL_IDX*8(RA) 4778 | lw SFARG1LO, FORL_IDX*8+LO(RA)
3846 | ldc1 f4, FORL_STEP*8(RA)
3847 | ldc1 f2, FORL_STOP*8(RA)
3848 | lw TMP3, FORL_STEP*8+HI(RA)
3849 | add.d f0, f0, f4
3850 | sdc1 f0, FORL_IDX*8(RA)
3851 } else {
3852 | lw TMP1, FORL_IDX*8+HI(RA)
3853 | lw TMP3, FORL_STEP*8+HI(RA)
3854 | lw TMP2, FORL_STOP*8+HI(RA)
3855 | sltiu TMP1, TMP1, LJ_TISNUM
3856 | sltiu TMP0, TMP3, LJ_TISNUM
3857 | sltiu TMP2, TMP2, LJ_TISNUM
3858 | and TMP1, TMP1, TMP0
3859 | and TMP1, TMP1, TMP2
3860 | ldc1 f0, FORL_IDX*8(RA)
3861 | beqz TMP1, ->vmeta_for
3862 |. ldc1 f2, FORL_STOP*8(RA)
3863 }
3864 if (op != BC_JFORL) { 4779 if (op != BC_JFORL) {
3865 | srl RD, RD, 1 4780 | srl RD, RD, 1
3866 | lui TMP0, (-(BCBIAS_J*4 >> 16) & 65535) 4781 | lui TMP2, (-(BCBIAS_J*4 >> 16) & 65535)
4782 | addu TMP2, RD, TMP2
4783 }
4784 if (!vk) {
4785 | lw SFARG2HI, FORL_STOP*8+HI(RA)
4786 | lw SFARG2LO, FORL_STOP*8+LO(RA)
4787 | bne SFARG1HI, TISNUM, >5
4788 |. lw SFRETHI, FORL_STEP*8+HI(RA)
4789 | xor AT, SFARG2HI, TISNUM
4790 | lw SFRETLO, FORL_STEP*8+LO(RA)
4791 | xor TMP0, SFRETHI, TISNUM
4792 | or AT, AT, TMP0
4793 | bnez AT, ->vmeta_for
4794 |. slt AT, SFRETLO, r0
4795 | slt CRET1, SFARG2LO, SFARG1LO
4796 | slt TMP1, SFARG1LO, SFARG2LO
4797 | movn CRET1, TMP1, AT
4798 } else {
4799 | bne SFARG1HI, TISNUM, >5
4800 |. lw SFARG2LO, FORL_STEP*8+LO(RA)
4801 | lw SFRETLO, FORL_STOP*8+LO(RA)
4802 | move TMP3, SFARG1LO
4803 | addu SFARG1LO, SFARG1LO, SFARG2LO
4804 | xor TMP0, SFARG1LO, TMP3
4805 | xor TMP1, SFARG1LO, SFARG2LO
4806 | and TMP0, TMP0, TMP1
4807 | slt TMP1, SFARG1LO, SFRETLO
4808 | slt CRET1, SFRETLO, SFARG1LO
4809 | slt AT, SFARG2LO, r0
4810 | slt TMP0, TMP0, r0 // ((y^a) & (y^b)) < 0: overflow.
4811 | movn CRET1, TMP1, AT
4812 | or CRET1, CRET1, TMP0
4813 }
4814 |1:
4815 if (op == BC_FORI) {
4816 | movz TMP2, r0, CRET1
4817 | addu PC, PC, TMP2
4818 } else if (op == BC_JFORI) {
4819 | addu PC, PC, TMP2
4820 | lhu RD, -4+OFS_RD(PC)
4821 } else if (op == BC_IFORL) {
4822 | movn TMP2, r0, CRET1
4823 | addu PC, PC, TMP2
3867 } 4824 }
3868 | c.le.d 0, f0, f2 4825 if (vk) {
3869 | c.le.d 1, f2, f0 4826 | sw SFARG1HI, FORL_IDX*8+HI(RA)
3870 | sdc1 f0, FORL_EXT*8(RA) 4827 | sw SFARG1LO, FORL_IDX*8+LO(RA)
4828 }
4829 | ins_next1
4830 | sw SFARG1HI, FORL_EXT*8+HI(RA)
4831 | sw SFARG1LO, FORL_EXT*8+LO(RA)
4832 |2:
3871 if (op == BC_JFORI) { 4833 if (op == BC_JFORI) {
3872 | li TMP1, 1 4834 | beqz CRET1, =>BC_JLOOP
3873 | li TMP2, 1
3874 | addu TMP0, RD, TMP0
3875 | slt TMP3, TMP3, r0
3876 | movf TMP1, r0, 0
3877 | addu PC, PC, TMP0
3878 | movf TMP2, r0, 1
3879 | lhu RD, -4+OFS_RD(PC)
3880 | movn TMP1, TMP2, TMP3
3881 | bnez TMP1, =>BC_JLOOP
3882 |. decode_RD8b RD 4835 |. decode_RD8b RD
3883 } else if (op == BC_JFORL) { 4836 } else if (op == BC_JFORL) {
3884 | li TMP1, 1 4837 | beqz CRET1, =>BC_JLOOP
3885 | li TMP2, 1 4838 }
3886 | slt TMP3, TMP3, r0 4839 | ins_next2
3887 | movf TMP1, r0, 0 4840 |
3888 | movf TMP2, r0, 1 4841 |5: // FP loop.
3889 | movn TMP1, TMP2, TMP3 4842 |.if FPU
3890 | bnez TMP1, =>BC_JLOOP 4843 if (!vk) {
4844 | ldc1 f0, FORL_IDX*8(RA)
4845 | ldc1 f2, FORL_STOP*8(RA)
4846 | sltiu TMP0, SFARG1HI, LJ_TISNUM
4847 | sltiu TMP1, SFARG2HI, LJ_TISNUM
4848 | sltiu AT, SFRETHI, LJ_TISNUM
4849 | and TMP0, TMP0, TMP1
4850 | and AT, AT, TMP0
4851 | beqz AT, ->vmeta_for
4852 |. slt TMP3, SFRETHI, r0
4853 | c.ole.d 0, f0, f2
4854 | c.ole.d 1, f2, f0
4855 | li CRET1, 1
4856 | movt CRET1, r0, 0
4857 | movt AT, r0, 1
4858 | b <1
4859 |. movn CRET1, AT, TMP3
4860 } else {
4861 | ldc1 f0, FORL_IDX*8(RA)
4862 | ldc1 f4, FORL_STEP*8(RA)
4863 | ldc1 f2, FORL_STOP*8(RA)
4864 | lw SFARG2HI, FORL_STEP*8+HI(RA)
4865 | add.d f0, f0, f4
4866 | c.ole.d 0, f0, f2
4867 | c.ole.d 1, f2, f0
4868 | slt TMP3, SFARG2HI, r0
4869 | li CRET1, 1
4870 | li AT, 1
4871 | movt CRET1, r0, 0
4872 | movt AT, r0, 1
4873 | movn CRET1, AT, TMP3
4874 if (op == BC_IFORL) {
4875 | movn TMP2, r0, CRET1
4876 | addu PC, PC, TMP2
4877 }
4878 | sdc1 f0, FORL_IDX*8(RA)
4879 | ins_next1
4880 | b <2
4881 |. sdc1 f0, FORL_EXT*8(RA)
4882 }
4883 |.else
4884 if (!vk) {
4885 | sltiu TMP0, SFARG1HI, LJ_TISNUM
4886 | sltiu TMP1, SFARG2HI, LJ_TISNUM
4887 | sltiu AT, SFRETHI, LJ_TISNUM
4888 | and TMP0, TMP0, TMP1
4889 | and AT, AT, TMP0
4890 | beqz AT, ->vmeta_for
4891 |. nop
4892 | bal ->vm_sfcmpolex
4893 |. move TMP3, SFRETHI
4894 | b <1
3891 |. nop 4895 |. nop
3892 } else { 4896 } else {
3893 | addu TMP1, RD, TMP0 4897 | lw SFARG2HI, FORL_STEP*8+HI(RA)
3894 | slt TMP3, TMP3, r0 4898 | load_got __adddf3
3895 | move TMP2, TMP1 4899 | call_extern
3896 if (op == BC_FORI) { 4900 |. sw TMP2, ARG5
3897 | movt TMP1, r0, 0 4901 | lw SFARG2HI, FORL_STOP*8+HI(RA)
3898 | movt TMP2, r0, 1 4902 | lw SFARG2LO, FORL_STOP*8+LO(RA)
4903 | move SFARG1HI, SFRETHI
4904 | move SFARG1LO, SFRETLO
4905 | bal ->vm_sfcmpolex
4906 |. lw TMP3, FORL_STEP*8+HI(RA)
4907 if ( op == BC_JFORL ) {
4908 | lhu RD, -4+OFS_RD(PC)
4909 | lw TMP2, ARG5
4910 | b <1
4911 |. decode_RD8b RD
3899 } else { 4912 } else {
3900 | movf TMP1, r0, 0 4913 | b <1
3901 | movf TMP2, r0, 1 4914 |. lw TMP2, ARG5
3902 } 4915 }
3903 | movn TMP1, TMP2, TMP3
3904 | addu PC, PC, TMP1
3905 } 4916 }
3906 | ins_next 4917 |.endif
3907 break; 4918 break;
3908 4919
3909 case BC_ITERL: 4920 case BC_ITERL:
@@ -3962,8 +4973,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3962 | sw AT, DISPATCH_GL(vmstate)(DISPATCH) 4973 | sw AT, DISPATCH_GL(vmstate)(DISPATCH)
3963 | lw TRACE:TMP2, 0(TMP1) 4974 | lw TRACE:TMP2, 0(TMP1)
3964 | sw BASE, DISPATCH_GL(jit_base)(DISPATCH) 4975 | sw BASE, DISPATCH_GL(jit_base)(DISPATCH)
3965 | sw L, DISPATCH_GL(jit_L)(DISPATCH)
3966 | lw TMP2, TRACE:TMP2->mcode 4976 | lw TMP2, TRACE:TMP2->mcode
4977 | sw L, DISPATCH_GL(tmpbuf.L)(DISPATCH)
3967 | jr TMP2 4978 | jr TMP2
3968 |. addiu JGL, DISPATCH, GG_DISP2G+32768 4979 |. addiu JGL, DISPATCH, GG_DISP2G+32768
3969 |.endif 4980 |.endif
@@ -4089,6 +5100,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4089 | li_vmstate INTERP 5100 | li_vmstate INTERP
4090 | lw PC, FRAME_PC(BASE) // Fetch PC of caller. 5101 | lw PC, FRAME_PC(BASE) // Fetch PC of caller.
4091 | subu RA, TMP1, RD // RA = L->top - nresults*8 5102 | subu RA, TMP1, RD // RA = L->top - nresults*8
5103 | sw L, DISPATCH_GL(cur_L)(DISPATCH)
4092 | b ->vm_returnc 5104 | b ->vm_returnc
4093 |. st_vmstate 5105 |. st_vmstate
4094 break; 5106 break;
@@ -4151,8 +5163,10 @@ static void emit_asm_debug(BuildCtx *ctx)
4151 fcofs, CFRAME_SIZE); 5163 fcofs, CFRAME_SIZE);
4152 for (i = 23; i >= 16; i--) 5164 for (i = 23; i >= 16; i--)
4153 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i); 5165 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i);
5166#if !LJ_SOFTFP
4154 for (i = 30; i >= 20; i -= 2) 5167 for (i = 30; i >= 20; i -= 2)
4155 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i); 5168 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i);
5169#endif
4156 fprintf(ctx->fp, 5170 fprintf(ctx->fp,
4157 "\t.align 2\n" 5171 "\t.align 2\n"
4158 ".LEFDE0:\n\n"); 5172 ".LEFDE0:\n\n");
@@ -4204,8 +5218,10 @@ static void emit_asm_debug(BuildCtx *ctx)
4204 fcofs, CFRAME_SIZE); 5218 fcofs, CFRAME_SIZE);
4205 for (i = 23; i >= 16; i--) 5219 for (i = 23; i >= 16; i--)
4206 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i); 5220 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 26-i);
5221#if !LJ_SOFTFP
4207 for (i = 30; i >= 20; i -= 2) 5222 for (i = 30; i >= 20; i -= 2)
4208 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i); 5223 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 42-i);
5224#endif
4209 fprintf(ctx->fp, 5225 fprintf(ctx->fp,
4210 "\t.align 2\n" 5226 "\t.align 2\n"
4211 ".LEFDE2:\n\n"); 5227 ".LEFDE2:\n\n");
diff --git a/src/vm_mips64.dasc b/src/vm_mips64.dasc
new file mode 100644
index 00000000..f0c22a74
--- /dev/null
+++ b/src/vm_mips64.dasc
@@ -0,0 +1,5062 @@
1|// Low-level VM code for MIPS64 CPUs.
2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4|//
5|// Contributed by Djordje Kovacevic and Stefan Pejic from RT-RK.com.
6|// Sponsored by Cisco Systems, Inc.
7|
8|.arch mips64
9|.section code_op, code_sub
10|
11|.actionlist build_actionlist
12|.globals GLOB_
13|.globalnames globnames
14|.externnames extnames
15|
16|// Note: The ragged indentation of the instructions is intentional.
17|// The starting columns indicate data dependencies.
18|
19|//-----------------------------------------------------------------------
20|
21|// Fixed register assignments for the interpreter.
22|// Don't use: r0 = 0, r26/r27 = reserved, r28 = gp, r29 = sp, r31 = ra
23|
24|.macro .FPU, a, b
25|.if FPU
26| a, b
27|.endif
28|.endmacro
29|
30|// The following must be C callee-save (but BASE is often refetched).
31|.define BASE, r16 // Base of current Lua stack frame.
32|.define KBASE, r17 // Constants of current Lua function.
33|.define PC, r18 // Next PC.
34|.define DISPATCH, r19 // Opcode dispatch table.
35|.define LREG, r20 // Register holding lua_State (also in SAVE_L).
36|.define MULTRES, r21 // Size of multi-result: (nresults+1)*8.
37|
38|.define JGL, r30 // On-trace: global_State + 32768.
39|
40|// Constants for type-comparisons, stores and conversions. C callee-save.
41|.define TISNIL, r30
42|.define TISNUM, r22
43|.if FPU
44|.define TOBIT, f30 // 2^52 + 2^51.
45|.endif
46|
47|// The following temporaries are not saved across C calls, except for RA.
48|.define RA, r23 // Callee-save.
49|.define RB, r8
50|.define RC, r9
51|.define RD, r10
52|.define INS, r11
53|
54|.define AT, r1 // Assembler temporary.
55|.define TMP0, r12
56|.define TMP1, r13
57|.define TMP2, r14
58|.define TMP3, r15
59|
60|// MIPS n64 calling convention.
61|.define CFUNCADDR, r25
62|.define CARG1, r4
63|.define CARG2, r5
64|.define CARG3, r6
65|.define CARG4, r7
66|.define CARG5, r8
67|.define CARG6, r9
68|.define CARG7, r10
69|.define CARG8, r11
70|
71|.define CRET1, r2
72|.define CRET2, r3
73|
74|.if FPU
75|.define FARG1, f12
76|.define FARG2, f13
77|.define FARG3, f14
78|.define FARG4, f15
79|.define FARG5, f16
80|.define FARG6, f17
81|.define FARG7, f18
82|.define FARG8, f19
83|
84|.define FRET1, f0
85|.define FRET2, f2
86|.endif
87|
88|// Stack layout while in interpreter. Must match with lj_frame.h.
89|.if FPU // MIPS64 hard-float.
90|
91|.define CFRAME_SPACE, 192 // Delta for sp.
92|
93|//----- 16 byte aligned, <-- sp entering interpreter
94|.define SAVE_ERRF, 188(sp) // 32 bit values.
95|.define SAVE_NRES, 184(sp)
96|.define SAVE_CFRAME, 176(sp) // 64 bit values.
97|.define SAVE_L, 168(sp)
98|.define SAVE_PC, 160(sp)
99|//----- 16 byte aligned
100|.define SAVE_GPR_, 80 // .. 80+10*8: 64 bit GPR saves.
101|.define SAVE_FPR_, 16 // .. 16+8*8: 64 bit FPR saves.
102|
103|.else // MIPS64 soft-float
104|
105|.define CFRAME_SPACE, 128 // Delta for sp.
106|
107|//----- 16 byte aligned, <-- sp entering interpreter
108|.define SAVE_ERRF, 124(sp) // 32 bit values.
109|.define SAVE_NRES, 120(sp)
110|.define SAVE_CFRAME, 112(sp) // 64 bit values.
111|.define SAVE_L, 104(sp)
112|.define SAVE_PC, 96(sp)
113|//----- 16 byte aligned
114|.define SAVE_GPR_, 16 // .. 16+10*8: 64 bit GPR saves.
115|
116|.endif
117|
118|.define TMPX, 8(sp) // Unused by interpreter, temp for JIT code.
119|.define TMPD, 0(sp)
120|//----- 16 byte aligned
121|
122|.define TMPD_OFS, 0
123|
124|.define SAVE_MULTRES, TMPD
125|
126|//-----------------------------------------------------------------------
127|
128|.macro saveregs
129| daddiu sp, sp, -CFRAME_SPACE
130| sd ra, SAVE_GPR_+9*8(sp)
131| sd r30, SAVE_GPR_+8*8(sp)
132| .FPU sdc1 f31, SAVE_FPR_+7*8(sp)
133| sd r23, SAVE_GPR_+7*8(sp)
134| .FPU sdc1 f30, SAVE_FPR_+6*8(sp)
135| sd r22, SAVE_GPR_+6*8(sp)
136| .FPU sdc1 f29, SAVE_FPR_+5*8(sp)
137| sd r21, SAVE_GPR_+5*8(sp)
138| .FPU sdc1 f28, SAVE_FPR_+4*8(sp)
139| sd r20, SAVE_GPR_+4*8(sp)
140| .FPU sdc1 f27, SAVE_FPR_+3*8(sp)
141| sd r19, SAVE_GPR_+3*8(sp)
142| .FPU sdc1 f26, SAVE_FPR_+2*8(sp)
143| sd r18, SAVE_GPR_+2*8(sp)
144| .FPU sdc1 f25, SAVE_FPR_+1*8(sp)
145| sd r17, SAVE_GPR_+1*8(sp)
146| .FPU sdc1 f24, SAVE_FPR_+0*8(sp)
147| sd r16, SAVE_GPR_+0*8(sp)
148|.endmacro
149|
150|.macro restoreregs_ret
151| ld ra, SAVE_GPR_+9*8(sp)
152| ld r30, SAVE_GPR_+8*8(sp)
153| ld r23, SAVE_GPR_+7*8(sp)
154| .FPU ldc1 f31, SAVE_FPR_+7*8(sp)
155| ld r22, SAVE_GPR_+6*8(sp)
156| .FPU ldc1 f30, SAVE_FPR_+6*8(sp)
157| ld r21, SAVE_GPR_+5*8(sp)
158| .FPU ldc1 f29, SAVE_FPR_+5*8(sp)
159| ld r20, SAVE_GPR_+4*8(sp)
160| .FPU ldc1 f28, SAVE_FPR_+4*8(sp)
161| ld r19, SAVE_GPR_+3*8(sp)
162| .FPU ldc1 f27, SAVE_FPR_+3*8(sp)
163| ld r18, SAVE_GPR_+2*8(sp)
164| .FPU ldc1 f26, SAVE_FPR_+2*8(sp)
165| ld r17, SAVE_GPR_+1*8(sp)
166| .FPU ldc1 f25, SAVE_FPR_+1*8(sp)
167| ld r16, SAVE_GPR_+0*8(sp)
168| .FPU ldc1 f24, SAVE_FPR_+0*8(sp)
169| jr ra
170| daddiu sp, sp, CFRAME_SPACE
171|.endmacro
172|
173|// Type definitions. Some of these are only used for documentation.
174|.type L, lua_State, LREG
175|.type GL, global_State
176|.type TVALUE, TValue
177|.type GCOBJ, GCobj
178|.type STR, GCstr
179|.type TAB, GCtab
180|.type LFUNC, GCfuncL
181|.type CFUNC, GCfuncC
182|.type PROTO, GCproto
183|.type UPVAL, GCupval
184|.type NODE, Node
185|.type NARGS8, int
186|.type TRACE, GCtrace
187|.type SBUF, SBuf
188|
189|//-----------------------------------------------------------------------
190|
191|// Trap for not-yet-implemented parts.
192|.macro NYI; .long 0xf0f0f0f0; .endmacro
193|
194|// Macros to mark delay slots.
195|.macro ., a; a; .endmacro
196|.macro ., a,b; a,b; .endmacro
197|.macro ., a,b,c; a,b,c; .endmacro
198|.macro ., a,b,c,d; a,b,c,d; .endmacro
199|
200|.define FRAME_PC, -8
201|.define FRAME_FUNC, -16
202|
203|//-----------------------------------------------------------------------
204|
205|// Endian-specific defines.
206|.if ENDIAN_LE
207|.define HI, 4
208|.define LO, 0
209|.define OFS_RD, 2
210|.define OFS_RA, 1
211|.define OFS_OP, 0
212|.else
213|.define HI, 0
214|.define LO, 4
215|.define OFS_RD, 0
216|.define OFS_RA, 2
217|.define OFS_OP, 3
218|.endif
219|
220|// Instruction decode.
221|.macro decode_OP1, dst, ins; andi dst, ins, 0xff; .endmacro
222|.macro decode_OP8a, dst, ins; andi dst, ins, 0xff; .endmacro
223|.macro decode_OP8b, dst; sll dst, dst, 3; .endmacro
224|.macro decode_RC8a, dst, ins; srl dst, ins, 13; .endmacro
225|.macro decode_RC8b, dst; andi dst, dst, 0x7f8; .endmacro
226|.macro decode_RD4b, dst; sll dst, dst, 2; .endmacro
227|.macro decode_RA8a, dst, ins; srl dst, ins, 5; .endmacro
228|.macro decode_RA8b, dst; andi dst, dst, 0x7f8; .endmacro
229|.macro decode_RB8a, dst, ins; srl dst, ins, 21; .endmacro
230|.macro decode_RB8b, dst; andi dst, dst, 0x7f8; .endmacro
231|.macro decode_RD8a, dst, ins; srl dst, ins, 16; .endmacro
232|.macro decode_RD8b, dst; sll dst, dst, 3; .endmacro
233|.macro decode_RDtoRC8, dst, src; andi dst, src, 0x7f8; .endmacro
234|
235|// Instruction fetch.
236|.macro ins_NEXT1
237| lw INS, 0(PC)
238| daddiu PC, PC, 4
239|.endmacro
240|// Instruction decode+dispatch.
241|.macro ins_NEXT2
242| decode_OP8a TMP1, INS
243| decode_OP8b TMP1
244| daddu TMP0, DISPATCH, TMP1
245| decode_RD8a RD, INS
246| ld AT, 0(TMP0)
247| decode_RA8a RA, INS
248| decode_RD8b RD
249| jr AT
250| decode_RA8b RA
251|.endmacro
252|.macro ins_NEXT
253| ins_NEXT1
254| ins_NEXT2
255|.endmacro
256|
257|// Instruction footer.
258|.if 1
259| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
260| .define ins_next, ins_NEXT
261| .define ins_next_, ins_NEXT
262| .define ins_next1, ins_NEXT1
263| .define ins_next2, ins_NEXT2
264|.else
265| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
266| // Affects only certain kinds of benchmarks (and only with -j off).
267| .macro ins_next
268| b ->ins_next
269| .endmacro
270| .macro ins_next1
271| .endmacro
272| .macro ins_next2
273| b ->ins_next
274| .endmacro
275| .macro ins_next_
276| ->ins_next:
277| ins_NEXT
278| .endmacro
279|.endif
280|
281|// Call decode and dispatch.
282|.macro ins_callt
283| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
284| ld PC, LFUNC:RB->pc
285| lw INS, 0(PC)
286| daddiu PC, PC, 4
287| decode_OP8a TMP1, INS
288| decode_RA8a RA, INS
289| decode_OP8b TMP1
290| decode_RA8b RA
291| daddu TMP0, DISPATCH, TMP1
292| ld TMP0, 0(TMP0)
293| jr TMP0
294| daddu RA, RA, BASE
295|.endmacro
296|
297|.macro ins_call
298| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, PC = caller PC
299| sd PC, FRAME_PC(BASE)
300| ins_callt
301|.endmacro
302|
303|//-----------------------------------------------------------------------
304|
305|.macro branch_RD
306| srl TMP0, RD, 1
307| lui AT, (-(BCBIAS_J*4 >> 16) & 65535)
308| addu TMP0, TMP0, AT
309| daddu PC, PC, TMP0
310|.endmacro
311|
312|// Assumes DISPATCH is relative to GL.
313#define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field))
314#define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field))
315#define GG_DISP2GOT (GG_OFS(got) - GG_OFS(dispatch))
316#define DISPATCH_GOT(name) (GG_DISP2GOT + sizeof(void*)*LJ_GOT_##name)
317|
318#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
319|
320|.macro load_got, func
321| ld CFUNCADDR, DISPATCH_GOT(func)(DISPATCH)
322|.endmacro
323|// Much faster. Sadly, there's no easy way to force the required code layout.
324|// .macro call_intern, func; bal extern func; .endmacro
325|.macro call_intern, func; jalr CFUNCADDR; .endmacro
326|.macro call_extern; jalr CFUNCADDR; .endmacro
327|.macro jmp_extern; jr CFUNCADDR; .endmacro
328|
329|.macro hotcheck, delta, target
330| dsrl TMP1, PC, 1
331| andi TMP1, TMP1, 126
332| daddu TMP1, TMP1, DISPATCH
333| lhu TMP2, GG_DISP2HOT(TMP1)
334| addiu TMP2, TMP2, -delta
335| bltz TMP2, target
336|. sh TMP2, GG_DISP2HOT(TMP1)
337|.endmacro
338|
339|.macro hotloop
340| hotcheck HOTCOUNT_LOOP, ->vm_hotloop
341|.endmacro
342|
343|.macro hotcall
344| hotcheck HOTCOUNT_CALL, ->vm_hotcall
345|.endmacro
346|
347|// Set current VM state. Uses TMP0.
348|.macro li_vmstate, st; li TMP0, ~LJ_VMST_..st; .endmacro
349|.macro st_vmstate; sw TMP0, DISPATCH_GL(vmstate)(DISPATCH); .endmacro
350|
351|// Move table write barrier back. Overwrites mark and tmp.
352|.macro barrierback, tab, mark, tmp, target
353| ld tmp, DISPATCH_GL(gc.grayagain)(DISPATCH)
354| andi mark, mark, ~LJ_GC_BLACK & 255 // black2gray(tab)
355| sd tab, DISPATCH_GL(gc.grayagain)(DISPATCH)
356| sb mark, tab->marked
357| b target
358|. sd tmp, tab->gclist
359|.endmacro
360|
361|// Clear type tag. Isolate lowest 14+32+1=47 bits of reg.
362|.macro cleartp, reg; dextm reg, reg, 0, 14; .endmacro
363|.macro cleartp, dst, reg; dextm dst, reg, 0, 14; .endmacro
364|
365|// Set type tag: Merge 17 type bits into bits [15+32=47, 31+32+1=64) of dst.
366|.macro settp, dst, tp; dinsu dst, tp, 15, 31; .endmacro
367|
368|// Extract (negative) type tag.
369|.macro gettp, dst, src; dsra dst, src, 47; .endmacro
370|
371|// Macros to check the TValue type and extract the GCobj. Branch on failure.
372|.macro checktp, reg, tp, target
373| gettp AT, reg
374| daddiu AT, AT, tp
375| bnez AT, target
376|. cleartp reg
377|.endmacro
378|.macro checktp, dst, reg, tp, target
379| gettp AT, reg
380| daddiu AT, AT, tp
381| bnez AT, target
382|. cleartp dst, reg
383|.endmacro
384|.macro checkstr, reg, target; checktp reg, -LJ_TSTR, target; .endmacro
385|.macro checktab, reg, target; checktp reg, -LJ_TTAB, target; .endmacro
386|.macro checkfunc, reg, target; checktp reg, -LJ_TFUNC, target; .endmacro
387|.macro checkint, reg, target // Caveat: has delay slot!
388| gettp AT, reg
389| bne AT, TISNUM, target
390|.endmacro
391|.macro checknum, reg, target // Caveat: has delay slot!
392| gettp AT, reg
393| sltiu AT, AT, LJ_TISNUM
394| beqz AT, target
395|.endmacro
396|
397|.macro mov_false, reg
398| lu reg, 0x8000
399| dsll reg, reg, 32
400| not reg, reg
401|.endmacro
402|.macro mov_true, reg
403| li reg, 0x0001
404| dsll reg, reg, 48
405| not reg, reg
406|.endmacro
407|
408|//-----------------------------------------------------------------------
409
410/* Generate subroutines used by opcodes and other parts of the VM. */
411/* The .code_sub section should be last to help static branch prediction. */
412static void build_subroutines(BuildCtx *ctx)
413{
414 |.code_sub
415 |
416 |//-----------------------------------------------------------------------
417 |//-- Return handling ----------------------------------------------------
418 |//-----------------------------------------------------------------------
419 |
420 |->vm_returnp:
421 | // See vm_return. Also: TMP2 = previous base.
422 | andi AT, PC, FRAME_P
423 | beqz AT, ->cont_dispatch
424 |
425 | // Return from pcall or xpcall fast func.
426 |. mov_true TMP1
427 | ld PC, FRAME_PC(TMP2) // Fetch PC of previous frame.
428 | move BASE, TMP2 // Restore caller base.
429 | // Prepending may overwrite the pcall frame, so do it at the end.
430 | sd TMP1, -8(RA) // Prepend true to results.
431 | daddiu RA, RA, -8
432 |
433 |->vm_returnc:
434 | addiu RD, RD, 8 // RD = (nresults+1)*8.
435 | andi TMP0, PC, FRAME_TYPE
436 | beqz RD, ->vm_unwind_c_eh
437 |. li CRET1, LUA_YIELD
438 | beqz TMP0, ->BC_RET_Z // Handle regular return to Lua.
439 |. move MULTRES, RD
440 |
441 |->vm_return:
442 | // BASE = base, RA = resultptr, RD/MULTRES = (nresults+1)*8, PC = return
443 | // TMP0 = PC & FRAME_TYPE
444 | li TMP2, -8
445 | xori AT, TMP0, FRAME_C
446 | and TMP2, PC, TMP2
447 | bnez AT, ->vm_returnp
448 | dsubu TMP2, BASE, TMP2 // TMP2 = previous base.
449 |
450 | addiu TMP1, RD, -8
451 | sd TMP2, L->base
452 | li_vmstate C
453 | lw TMP2, SAVE_NRES
454 | daddiu BASE, BASE, -16
455 | st_vmstate
456 | beqz TMP1, >2
457 |. sll TMP2, TMP2, 3
458 |1:
459 | addiu TMP1, TMP1, -8
460 | ld CRET1, 0(RA)
461 | daddiu RA, RA, 8
462 | sd CRET1, 0(BASE)
463 | bnez TMP1, <1
464 |. daddiu BASE, BASE, 8
465 |
466 |2:
467 | bne TMP2, RD, >6
468 |3:
469 |. sd BASE, L->top // Store new top.
470 |
471 |->vm_leave_cp:
472 | ld TMP0, SAVE_CFRAME // Restore previous C frame.
473 | move CRET1, r0 // Ok return status for vm_pcall.
474 | sd TMP0, L->cframe
475 |
476 |->vm_leave_unw:
477 | restoreregs_ret
478 |
479 |6:
480 | ld TMP1, L->maxstack
481 | slt AT, TMP2, RD
482 | bnez AT, >7 // Less results wanted?
483 | // More results wanted. Check stack size and fill up results with nil.
484 |. slt AT, BASE, TMP1
485 | beqz AT, >8
486 |. nop
487 | sd TISNIL, 0(BASE)
488 | addiu RD, RD, 8
489 | b <2
490 |. daddiu BASE, BASE, 8
491 |
492 |7: // Less results wanted.
493 | subu TMP0, RD, TMP2
494 | dsubu TMP0, BASE, TMP0 // Either keep top or shrink it.
495 | b <3
496 |. movn BASE, TMP0, TMP2 // LUA_MULTRET+1 case?
497 |
498 |8: // Corner case: need to grow stack for filling up results.
499 | // This can happen if:
500 | // - A C function grows the stack (a lot).
501 | // - The GC shrinks the stack in between.
502 | // - A return back from a lua_call() with (high) nresults adjustment.
503 | load_got lj_state_growstack
504 | move MULTRES, RD
505 | srl CARG2, TMP2, 3
506 | call_intern lj_state_growstack // (lua_State *L, int n)
507 |. move CARG1, L
508 | lw TMP2, SAVE_NRES
509 | ld BASE, L->top // Need the (realloced) L->top in BASE.
510 | move RD, MULTRES
511 | b <2
512 |. sll TMP2, TMP2, 3
513 |
514 |->vm_unwind_c: // Unwind C stack, return from vm_pcall.
515 | // (void *cframe, int errcode)
516 | move sp, CARG1
517 | move CRET1, CARG2
518 |->vm_unwind_c_eh: // Landing pad for external unwinder.
519 | ld L, SAVE_L
520 | li TMP0, ~LJ_VMST_C
521 | ld GL:TMP1, L->glref
522 | b ->vm_leave_unw
523 |. sw TMP0, GL:TMP1->vmstate
524 |
525 |->vm_unwind_ff: // Unwind C stack, return from ff pcall.
526 | // (void *cframe)
527 | li AT, -4
528 | and sp, CARG1, AT
529 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
530 | ld L, SAVE_L
531 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
532 | li TISNIL, LJ_TNIL
533 | li TISNUM, LJ_TISNUM
534 | ld BASE, L->base
535 | ld DISPATCH, L->glref // Setup pointer to dispatch table.
536 | .FPU mtc1 TMP3, TOBIT
537 | mov_false TMP1
538 | li_vmstate INTERP
539 | ld PC, FRAME_PC(BASE) // Fetch PC of previous frame.
540 | .FPU cvt.d.s TOBIT, TOBIT
541 | daddiu RA, BASE, -8 // Results start at BASE-8.
542 | daddiu DISPATCH, DISPATCH, GG_G2DISP
543 | sd TMP1, 0(RA) // Prepend false to error message.
544 | st_vmstate
545 | b ->vm_returnc
546 |. li RD, 16 // 2 results: false + error message.
547 |
548 |//-----------------------------------------------------------------------
549 |//-- Grow stack for calls -----------------------------------------------
550 |//-----------------------------------------------------------------------
551 |
552 |->vm_growstack_c: // Grow stack for C function.
553 | b >2
554 |. li CARG2, LUA_MINSTACK
555 |
556 |->vm_growstack_l: // Grow stack for Lua function.
557 | // BASE = new base, RA = BASE+framesize*8, RC = nargs*8, PC = first PC
558 | daddu RC, BASE, RC
559 | dsubu RA, RA, BASE
560 | sd BASE, L->base
561 | daddiu PC, PC, 4 // Must point after first instruction.
562 | sd RC, L->top
563 | srl CARG2, RA, 3
564 |2:
565 | // L->base = new base, L->top = top
566 | load_got lj_state_growstack
567 | sd PC, SAVE_PC
568 | call_intern lj_state_growstack // (lua_State *L, int n)
569 |. move CARG1, L
570 | ld BASE, L->base
571 | ld RC, L->top
572 | ld LFUNC:RB, FRAME_FUNC(BASE)
573 | dsubu RC, RC, BASE
574 | cleartp LFUNC:RB
575 | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
576 | ins_callt // Just retry the call.
577 |
578 |//-----------------------------------------------------------------------
579 |//-- Entry points into the assembler VM ---------------------------------
580 |//-----------------------------------------------------------------------
581 |
582 |->vm_resume: // Setup C frame and resume thread.
583 | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
584 | saveregs
585 | move L, CARG1
586 | ld DISPATCH, L->glref // Setup pointer to dispatch table.
587 | move BASE, CARG2
588 | lbu TMP1, L->status
589 | sd L, SAVE_L
590 | li PC, FRAME_CP
591 | daddiu TMP0, sp, CFRAME_RESUME
592 | daddiu DISPATCH, DISPATCH, GG_G2DISP
593 | sw r0, SAVE_NRES
594 | sw r0, SAVE_ERRF
595 | sd CARG1, SAVE_PC // Any value outside of bytecode is ok.
596 | sd r0, SAVE_CFRAME
597 | beqz TMP1, >3
598 |. sd TMP0, L->cframe
599 |
600 | // Resume after yield (like a return).
601 | sd L, DISPATCH_GL(cur_L)(DISPATCH)
602 | move RA, BASE
603 | ld BASE, L->base
604 | ld TMP1, L->top
605 | ld PC, FRAME_PC(BASE)
606 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
607 | dsubu RD, TMP1, BASE
608 | .FPU mtc1 TMP3, TOBIT
609 | sb r0, L->status
610 | .FPU cvt.d.s TOBIT, TOBIT
611 | li_vmstate INTERP
612 | daddiu RD, RD, 8
613 | st_vmstate
614 | move MULTRES, RD
615 | andi TMP0, PC, FRAME_TYPE
616 | li TISNIL, LJ_TNIL
617 | beqz TMP0, ->BC_RET_Z
618 |. li TISNUM, LJ_TISNUM
619 | b ->vm_return
620 |. nop
621 |
622 |->vm_pcall: // Setup protected C frame and enter VM.
623 | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
624 | saveregs
625 | sw CARG4, SAVE_ERRF
626 | b >1
627 |. li PC, FRAME_CP
628 |
629 |->vm_call: // Setup C frame and enter VM.
630 | // (lua_State *L, TValue *base, int nres1)
631 | saveregs
632 | li PC, FRAME_C
633 |
634 |1: // Entry point for vm_pcall above (PC = ftype).
635 | ld TMP1, L:CARG1->cframe
636 | move L, CARG1
637 | sw CARG3, SAVE_NRES
638 | ld DISPATCH, L->glref // Setup pointer to dispatch table.
639 | sd CARG1, SAVE_L
640 | move BASE, CARG2
641 | daddiu DISPATCH, DISPATCH, GG_G2DISP
642 | sd CARG1, SAVE_PC // Any value outside of bytecode is ok.
643 | sd TMP1, SAVE_CFRAME
644 | sd sp, L->cframe // Add our C frame to cframe chain.
645 |
646 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
647 | sd L, DISPATCH_GL(cur_L)(DISPATCH)
648 | ld TMP2, L->base // TMP2 = old base (used in vmeta_call).
649 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
650 | ld TMP1, L->top
651 | .FPU mtc1 TMP3, TOBIT
652 | daddu PC, PC, BASE
653 | dsubu NARGS8:RC, TMP1, BASE
654 | li TISNUM, LJ_TISNUM
655 | dsubu PC, PC, TMP2 // PC = frame delta + frame type
656 | .FPU cvt.d.s TOBIT, TOBIT
657 | li_vmstate INTERP
658 | li TISNIL, LJ_TNIL
659 | st_vmstate
660 |
661 |->vm_call_dispatch:
662 | // TMP2 = old base, BASE = new base, RC = nargs*8, PC = caller PC
663 | ld LFUNC:RB, FRAME_FUNC(BASE)
664 | checkfunc LFUNC:RB, ->vmeta_call
665 |
666 |->vm_call_dispatch_f:
667 | ins_call
668 | // BASE = new base, RB = func, RC = nargs*8, PC = caller PC
669 |
670 |->vm_cpcall: // Setup protected C frame, call C.
671 | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
672 | saveregs
673 | move L, CARG1
674 | ld TMP0, L:CARG1->stack
675 | sd CARG1, SAVE_L
676 | ld TMP1, L->top
677 | ld DISPATCH, L->glref // Setup pointer to dispatch table.
678 | sd CARG1, SAVE_PC // Any value outside of bytecode is ok.
679 | dsubu TMP0, TMP0, TMP1 // Compute -savestack(L, L->top).
680 | ld TMP1, L->cframe
681 | daddiu DISPATCH, DISPATCH, GG_G2DISP
682 | sw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame.
683 | sw r0, SAVE_ERRF // No error function.
684 | sd TMP1, SAVE_CFRAME
685 | sd sp, L->cframe // Add our C frame to cframe chain.
686 | sd L, DISPATCH_GL(cur_L)(DISPATCH)
687 | jalr CARG4 // (lua_State *L, lua_CFunction func, void *ud)
688 |. move CFUNCADDR, CARG4
689 | move BASE, CRET1
690 | bnez CRET1, <3 // Else continue with the call.
691 |. li PC, FRAME_CP
692 | b ->vm_leave_cp // No base? Just remove C frame.
693 |. nop
694 |
695 |//-----------------------------------------------------------------------
696 |//-- Metamethod handling ------------------------------------------------
697 |//-----------------------------------------------------------------------
698 |
699 |// The lj_meta_* functions (except for lj_meta_cat) don't reallocate the
700 |// stack, so BASE doesn't need to be reloaded across these calls.
701 |
702 |//-- Continuation dispatch ----------------------------------------------
703 |
704 |->cont_dispatch:
705 | // BASE = meta base, RA = resultptr, RD = (nresults+1)*8
706 | ld TMP0, -32(BASE) // Continuation.
707 | move RB, BASE
708 | move BASE, TMP2 // Restore caller BASE.
709 | ld LFUNC:TMP1, FRAME_FUNC(TMP2)
710 |.if FFI
711 | sltiu AT, TMP0, 2
712 |.endif
713 | ld PC, -24(RB) // Restore PC from [cont|PC].
714 | cleartp LFUNC:TMP1
715 | daddu TMP2, RA, RD
716 | ld TMP1, LFUNC:TMP1->pc
717 |.if FFI
718 | bnez AT, >1
719 |.endif
720 |. sd TISNIL, -8(TMP2) // Ensure one valid arg.
721 | // BASE = base, RA = resultptr, RB = meta base
722 | jr TMP0 // Jump to continuation.
723 |. ld KBASE, PC2PROTO(k)(TMP1)
724 |
725 |.if FFI
726 |1:
727 | bnez TMP0, ->cont_ffi_callback // cont = 1: return from FFI callback.
728 | // cont = 0: tailcall from C function.
729 |. daddiu TMP1, RB, -32
730 | b ->vm_call_tail
731 |. dsubu RC, TMP1, BASE
732 |.endif
733 |
734 |->cont_cat: // RA = resultptr, RB = meta base
735 | lw INS, -4(PC)
736 | daddiu CARG2, RB, -32
737 | ld CRET1, 0(RA)
738 | decode_RB8a MULTRES, INS
739 | decode_RA8a RA, INS
740 | decode_RB8b MULTRES
741 | decode_RA8b RA
742 | daddu TMP1, BASE, MULTRES
743 | sd BASE, L->base
744 | dsubu CARG3, CARG2, TMP1
745 | bne TMP1, CARG2, ->BC_CAT_Z
746 |. sd CRET1, 0(CARG2)
747 | daddu RA, BASE, RA
748 | b ->cont_nop
749 |. sd CRET1, 0(RA)
750 |
751 |//-- Table indexing metamethods -----------------------------------------
752 |
753 |->vmeta_tgets1:
754 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
755 | li TMP0, LJ_TSTR
756 | settp STR:RC, TMP0
757 | b >1
758 |. sd STR:RC, 0(CARG3)
759 |
760 |->vmeta_tgets:
761 | daddiu CARG2, DISPATCH, DISPATCH_GL(tmptv)
762 | li TMP0, LJ_TTAB
763 | li TMP1, LJ_TSTR
764 | settp TAB:RB, TMP0
765 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv2)
766 | sd TAB:RB, 0(CARG2)
767 | settp STR:RC, TMP1
768 | b >1
769 |. sd STR:RC, 0(CARG3)
770 |
771 |->vmeta_tgetb: // TMP0 = index
772 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
773 | settp TMP0, TISNUM
774 | sd TMP0, 0(CARG3)
775 |
776 |->vmeta_tgetv:
777 |1:
778 | load_got lj_meta_tget
779 | sd BASE, L->base
780 | sd PC, SAVE_PC
781 | call_intern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
782 |. move CARG1, L
783 | // Returns TValue * (finished) or NULL (metamethod).
784 | beqz CRET1, >3
785 |. daddiu TMP1, BASE, -FRAME_CONT
786 | ld CARG1, 0(CRET1)
787 | ins_next1
788 | sd CARG1, 0(RA)
789 | ins_next2
790 |
791 |3: // Call __index metamethod.
792 | // BASE = base, L->top = new base, stack = cont/func/t/k
793 | ld BASE, L->top
794 | sd PC, -24(BASE) // [cont|PC]
795 | dsubu PC, BASE, TMP1
796 | ld LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
797 | cleartp LFUNC:RB
798 | b ->vm_call_dispatch_f
799 |. li NARGS8:RC, 16 // 2 args for func(t, k).
800 |
801 |->vmeta_tgetr:
802 | load_got lj_tab_getinth
803 | call_intern lj_tab_getinth // (GCtab *t, int32_t key)
804 |. nop
805 | // Returns cTValue * or NULL.
806 | beqz CRET1, ->BC_TGETR_Z
807 |. move CARG2, TISNIL
808 | b ->BC_TGETR_Z
809 |. ld CARG2, 0(CRET1)
810 |
811 |//-----------------------------------------------------------------------
812 |
813 |->vmeta_tsets1:
814 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
815 | li TMP0, LJ_TSTR
816 | settp STR:RC, TMP0
817 | b >1
818 |. sd STR:RC, 0(CARG3)
819 |
820 |->vmeta_tsets:
821 | daddiu CARG2, DISPATCH, DISPATCH_GL(tmptv)
822 | li TMP0, LJ_TTAB
823 | li TMP1, LJ_TSTR
824 | settp TAB:RB, TMP0
825 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv2)
826 | sd TAB:RB, 0(CARG2)
827 | settp STR:RC, TMP1
828 | b >1
829 |. sd STR:RC, 0(CARG3)
830 |
831 |->vmeta_tsetb: // TMP0 = index
832 | daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
833 | settp TMP0, TISNUM
834 | sd TMP0, 0(CARG3)
835 |
836 |->vmeta_tsetv:
837 |1:
838 | load_got lj_meta_tset
839 | sd BASE, L->base
840 | sd PC, SAVE_PC
841 | call_intern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
842 |. move CARG1, L
843 | // Returns TValue * (finished) or NULL (metamethod).
844 | beqz CRET1, >3
845 |. ld CARG1, 0(RA)
846 | // NOBARRIER: lj_meta_tset ensures the table is not black.
847 | ins_next1
848 | sd CARG1, 0(CRET1)
849 | ins_next2
850 |
851 |3: // Call __newindex metamethod.
852 | // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
853 | daddiu TMP1, BASE, -FRAME_CONT
854 | ld BASE, L->top
855 | sd PC, -24(BASE) // [cont|PC]
856 | dsubu PC, BASE, TMP1
857 | ld LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
858 | cleartp LFUNC:RB
859 | sd CARG1, 16(BASE) // Copy value to third argument.
860 | b ->vm_call_dispatch_f
861 |. li NARGS8:RC, 24 // 3 args for func(t, k, v)
862 |
863 |->vmeta_tsetr:
864 | load_got lj_tab_setinth
865 | sd BASE, L->base
866 | sd PC, SAVE_PC
867 | call_intern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
868 |. move CARG1, L
869 | // Returns TValue *.
870 | b ->BC_TSETR_Z
871 |. nop
872 |
873 |//-- Comparison metamethods ---------------------------------------------
874 |
875 |->vmeta_comp:
876 | // RA/RD point to o1/o2.
877 | move CARG2, RA
878 | move CARG3, RD
879 | load_got lj_meta_comp
880 | daddiu PC, PC, -4
881 | sd BASE, L->base
882 | sd PC, SAVE_PC
883 | decode_OP1 CARG4, INS
884 | call_intern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
885 |. move CARG1, L
886 | // Returns 0/1 or TValue * (metamethod).
887 |3:
888 | sltiu AT, CRET1, 2
889 | beqz AT, ->vmeta_binop
890 | negu TMP2, CRET1
891 |4:
892 | lhu RD, OFS_RD(PC)
893 | daddiu PC, PC, 4
894 | lui TMP1, (-(BCBIAS_J*4 >> 16) & 65535)
895 | sll RD, RD, 2
896 | addu RD, RD, TMP1
897 | and RD, RD, TMP2
898 | daddu PC, PC, RD
899 |->cont_nop:
900 | ins_next
901 |
902 |->cont_ra: // RA = resultptr
903 | lbu TMP1, -4+OFS_RA(PC)
904 | ld CRET1, 0(RA)
905 | sll TMP1, TMP1, 3
906 | daddu TMP1, BASE, TMP1
907 | b ->cont_nop
908 |. sd CRET1, 0(TMP1)
909 |
910 |->cont_condt: // RA = resultptr
911 | ld TMP0, 0(RA)
912 | gettp TMP0, TMP0
913 | sltiu AT, TMP0, LJ_TISTRUECOND
914 | b <4
915 |. negu TMP2, AT // Branch if result is true.
916 |
917 |->cont_condf: // RA = resultptr
918 | ld TMP0, 0(RA)
919 | gettp TMP0, TMP0
920 | sltiu AT, TMP0, LJ_TISTRUECOND
921 | b <4
922 |. addiu TMP2, AT, -1 // Branch if result is false.
923 |
924 |->vmeta_equal:
925 | // CARG1/CARG2 point to o1/o2. TMP0 is set to 0/1.
926 | load_got lj_meta_equal
927 | cleartp LFUNC:CARG3, CARG2
928 | cleartp LFUNC:CARG2, CARG1
929 | move CARG4, TMP0
930 | daddiu PC, PC, -4
931 | sd BASE, L->base
932 | sd PC, SAVE_PC
933 | call_intern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
934 |. move CARG1, L
935 | // Returns 0/1 or TValue * (metamethod).
936 | b <3
937 |. nop
938 |
939 |->vmeta_equal_cd:
940 |.if FFI
941 | load_got lj_meta_equal_cd
942 | move CARG2, INS
943 | daddiu PC, PC, -4
944 | sd BASE, L->base
945 | sd PC, SAVE_PC
946 | call_intern lj_meta_equal_cd // (lua_State *L, BCIns op)
947 |. move CARG1, L
948 | // Returns 0/1 or TValue * (metamethod).
949 | b <3
950 |. nop
951 |.endif
952 |
953 |->vmeta_istype:
954 | load_got lj_meta_istype
955 | daddiu PC, PC, -4
956 | sd BASE, L->base
957 | srl CARG2, RA, 3
958 | srl CARG3, RD, 3
959 | sd PC, SAVE_PC
960 | call_intern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
961 |. move CARG1, L
962 | b ->cont_nop
963 |. nop
964 |
965 |//-- Arithmetic metamethods ---------------------------------------------
966 |
967 |->vmeta_unm:
968 | move RC, RB
969 |
970 |->vmeta_arith:
971 | load_got lj_meta_arith
972 | sd BASE, L->base
973 | move CARG2, RA
974 | sd PC, SAVE_PC
975 | move CARG3, RB
976 | move CARG4, RC
977 | decode_OP1 CARG5, INS // CARG5 == RB.
978 | call_intern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
979 |. move CARG1, L
980 | // Returns NULL (finished) or TValue * (metamethod).
981 | beqz CRET1, ->cont_nop
982 |. nop
983 |
984 | // Call metamethod for binary op.
985 |->vmeta_binop:
986 | // BASE = old base, CRET1 = new base, stack = cont/func/o1/o2
987 | dsubu TMP1, CRET1, BASE
988 | sd PC, -24(CRET1) // [cont|PC]
989 | move TMP2, BASE
990 | daddiu PC, TMP1, FRAME_CONT
991 | move BASE, CRET1
992 | b ->vm_call_dispatch
993 |. li NARGS8:RC, 16 // 2 args for func(o1, o2).
994 |
995 |->vmeta_len:
996 | // CARG2 already set by BC_LEN.
997#if LJ_52
998 | move MULTRES, CARG1
999#endif
1000 | load_got lj_meta_len
1001 | sd BASE, L->base
1002 | sd PC, SAVE_PC
1003 | call_intern lj_meta_len // (lua_State *L, TValue *o)
1004 |. move CARG1, L
1005 | // Returns NULL (retry) or TValue * (metamethod base).
1006#if LJ_52
1007 | bnez CRET1, ->vmeta_binop // Binop call for compatibility.
1008 |. nop
1009 | b ->BC_LEN_Z
1010 |. move CARG1, MULTRES
1011#else
1012 | b ->vmeta_binop // Binop call for compatibility.
1013 |. nop
1014#endif
1015 |
1016 |//-- Call metamethod ----------------------------------------------------
1017 |
1018 |->vmeta_call: // Resolve and call __call metamethod.
1019 | // TMP2 = old base, BASE = new base, RC = nargs*8
1020 | load_got lj_meta_call
1021 | sd TMP2, L->base // This is the callers base!
1022 | daddiu CARG2, BASE, -16
1023 | sd PC, SAVE_PC
1024 | daddu CARG3, BASE, RC
1025 | move MULTRES, NARGS8:RC
1026 | call_intern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
1027 |. move CARG1, L
1028 | ld LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
1029 | daddiu NARGS8:RC, MULTRES, 8 // Got one more argument now.
1030 | cleartp LFUNC:RB
1031 | ins_call
1032 |
1033 |->vmeta_callt: // Resolve __call for BC_CALLT.
1034 | // BASE = old base, RA = new base, RC = nargs*8
1035 | load_got lj_meta_call
1036 | sd BASE, L->base
1037 | daddiu CARG2, RA, -16
1038 | sd PC, SAVE_PC
1039 | daddu CARG3, RA, RC
1040 | move MULTRES, NARGS8:RC
1041 | call_intern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
1042 |. move CARG1, L
1043 | ld RB, FRAME_FUNC(RA) // Guaranteed to be a function here.
1044 | ld TMP1, FRAME_PC(BASE)
1045 | daddiu NARGS8:RC, MULTRES, 8 // Got one more argument now.
1046 | b ->BC_CALLT_Z
1047 |. cleartp LFUNC:CARG3, RB
1048 |
1049 |//-- Argument coercion for 'for' statement ------------------------------
1050 |
1051 |->vmeta_for:
1052 | load_got lj_meta_for
1053 | sd BASE, L->base
1054 | move CARG2, RA
1055 | sd PC, SAVE_PC
1056 | move MULTRES, INS
1057 | call_intern lj_meta_for // (lua_State *L, TValue *base)
1058 |. move CARG1, L
1059 |.if JIT
1060 | decode_OP1 TMP0, MULTRES
1061 | li AT, BC_JFORI
1062 |.endif
1063 | decode_RA8a RA, MULTRES
1064 | decode_RD8a RD, MULTRES
1065 | decode_RA8b RA
1066 |.if JIT
1067 | beq TMP0, AT, =>BC_JFORI
1068 |. decode_RD8b RD
1069 | b =>BC_FORI
1070 |. nop
1071 |.else
1072 | b =>BC_FORI
1073 |. decode_RD8b RD
1074 |.endif
1075 |
1076 |//-----------------------------------------------------------------------
1077 |//-- Fast functions -----------------------------------------------------
1078 |//-----------------------------------------------------------------------
1079 |
1080 |.macro .ffunc, name
1081 |->ff_ .. name:
1082 |.endmacro
1083 |
1084 |.macro .ffunc_1, name
1085 |->ff_ .. name:
1086 | beqz NARGS8:RC, ->fff_fallback
1087 |. ld CARG1, 0(BASE)
1088 |.endmacro
1089 |
1090 |.macro .ffunc_2, name
1091 |->ff_ .. name:
1092 | sltiu AT, NARGS8:RC, 16
1093 | ld CARG1, 0(BASE)
1094 | bnez AT, ->fff_fallback
1095 |. ld CARG2, 8(BASE)
1096 |.endmacro
1097 |
1098 |.macro .ffunc_n, name // Caveat: has delay slot!
1099 |->ff_ .. name:
1100 | ld CARG1, 0(BASE)
1101 | beqz NARGS8:RC, ->fff_fallback
1102 | // Either ldc1 or the 1st instruction of checknum is in the delay slot.
1103 | .FPU ldc1 FARG1, 0(BASE)
1104 | checknum CARG1, ->fff_fallback
1105 |.endmacro
1106 |
1107 |.macro .ffunc_nn, name // Caveat: has delay slot!
1108 |->ff_ .. name:
1109 | ld CARG1, 0(BASE)
1110 | sltiu AT, NARGS8:RC, 16
1111 | ld CARG2, 8(BASE)
1112 | bnez AT, ->fff_fallback
1113 |. gettp TMP0, CARG1
1114 | gettp TMP1, CARG2
1115 | sltiu TMP0, TMP0, LJ_TISNUM
1116 | sltiu TMP1, TMP1, LJ_TISNUM
1117 | .FPU ldc1 FARG1, 0(BASE)
1118 | and TMP0, TMP0, TMP1
1119 | .FPU ldc1 FARG2, 8(BASE)
1120 | beqz TMP0, ->fff_fallback
1121 |.endmacro
1122 |
1123 |// Inlined GC threshold check. Caveat: uses TMP0 and TMP1 and has delay slot!
1124 |.macro ffgccheck
1125 | ld TMP0, DISPATCH_GL(gc.total)(DISPATCH)
1126 | ld TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
1127 | dsubu AT, TMP0, TMP1
1128 | bgezal AT, ->fff_gcstep
1129 |.endmacro
1130 |
1131 |//-- Base library: checks -----------------------------------------------
1132 |.ffunc_1 assert
1133 | gettp AT, CARG1
1134 | sltiu AT, AT, LJ_TISTRUECOND
1135 | beqz AT, ->fff_fallback
1136 |. daddiu RA, BASE, -16
1137 | ld PC, FRAME_PC(BASE)
1138 | addiu RD, NARGS8:RC, 8 // Compute (nresults+1)*8.
1139 | daddu TMP2, RA, RD
1140 | daddiu TMP1, BASE, 8
1141 | beq BASE, TMP2, ->fff_res // Done if exactly 1 argument.
1142 |. sd CARG1, 0(RA)
1143 |1:
1144 | ld CRET1, 0(TMP1)
1145 | sd CRET1, -16(TMP1)
1146 | bne TMP1, TMP2, <1
1147 |. daddiu TMP1, TMP1, 8
1148 | b ->fff_res
1149 |. nop
1150 |
1151 |.ffunc_1 type
1152 | gettp TMP0, CARG1
1153 | sltu TMP1, TISNUM, TMP0
1154 | not TMP2, TMP0
1155 | li TMP3, ~LJ_TISNUM
1156 | movz TMP2, TMP3, TMP1
1157 | dsll TMP2, TMP2, 3
1158 | daddu TMP2, CFUNC:RB, TMP2
1159 | b ->fff_restv
1160 |. ld CARG1, CFUNC:TMP2->upvalue
1161 |
1162 |//-- Base library: getters and setters ---------------------------------
1163 |
1164 |.ffunc_1 getmetatable
1165 | gettp TMP2, CARG1
1166 | daddiu TMP0, TMP2, -LJ_TTAB
1167 | daddiu TMP1, TMP2, -LJ_TUDATA
1168 | movn TMP0, TMP1, TMP0
1169 | bnez TMP0, >6
1170 |. cleartp TAB:CARG1
1171 |1: // Field metatable must be at same offset for GCtab and GCudata!
1172 | ld TAB:RB, TAB:CARG1->metatable
1173 |2:
1174 | ld STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH)
1175 | beqz TAB:RB, ->fff_restv
1176 |. li CARG1, LJ_TNIL
1177 | lw TMP0, TAB:RB->hmask
1178 | lw TMP1, STR:RC->hash
1179 | ld NODE:TMP2, TAB:RB->node
1180 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
1181 | dsll TMP0, TMP1, 5
1182 | dsll TMP1, TMP1, 3
1183 | dsubu TMP1, TMP0, TMP1
1184 | daddu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
1185 | li CARG4, LJ_TSTR
1186 | settp STR:RC, CARG4 // Tagged key to look for.
1187 |3: // Rearranged logic, because we expect _not_ to find the key.
1188 | ld TMP0, NODE:TMP2->key
1189 | ld CARG1, NODE:TMP2->val
1190 | ld NODE:TMP2, NODE:TMP2->next
1191 | beq RC, TMP0, >5
1192 |. li AT, LJ_TTAB
1193 | bnez NODE:TMP2, <3
1194 |. nop
1195 |4:
1196 | move CARG1, RB
1197 | b ->fff_restv // Not found, keep default result.
1198 |. settp CARG1, AT
1199 |5:
1200 | bne CARG1, TISNIL, ->fff_restv
1201 |. nop
1202 | b <4 // Ditto for nil value.
1203 |. nop
1204 |
1205 |6:
1206 | sltiu AT, TMP2, LJ_TISNUM
1207 | movn TMP2, TISNUM, AT
1208 | dsll TMP2, TMP2, 3
1209 | dsubu TMP0, DISPATCH, TMP2
1210 | b <2
1211 |. ld TAB:RB, DISPATCH_GL(gcroot[GCROOT_BASEMT])-8(TMP0)
1212 |
1213 |.ffunc_2 setmetatable
1214 | // Fast path: no mt for table yet and not clearing the mt.
1215 | checktp TMP1, CARG1, -LJ_TTAB, ->fff_fallback
1216 | gettp TMP3, CARG2
1217 | ld TAB:TMP0, TAB:TMP1->metatable
1218 | lbu TMP2, TAB:TMP1->marked
1219 | daddiu AT, TMP3, -LJ_TTAB
1220 | cleartp TAB:CARG2
1221 | or AT, AT, TAB:TMP0
1222 | bnez AT, ->fff_fallback
1223 |. andi AT, TMP2, LJ_GC_BLACK // isblack(table)
1224 | beqz AT, ->fff_restv
1225 |. sd TAB:CARG2, TAB:TMP1->metatable
1226 | barrierback TAB:TMP1, TMP2, TMP0, ->fff_restv
1227 |
1228 |.ffunc rawget
1229 | ld CARG2, 0(BASE)
1230 | sltiu AT, NARGS8:RC, 16
1231 | load_got lj_tab_get
1232 | gettp TMP0, CARG2
1233 | cleartp CARG2
1234 | daddiu TMP0, TMP0, -LJ_TTAB
1235 | or AT, AT, TMP0
1236 | bnez AT, ->fff_fallback
1237 |. daddiu CARG3, BASE, 8
1238 | call_intern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
1239 |. move CARG1, L
1240 | b ->fff_restv
1241 |. ld CARG1, 0(CRET1)
1242 |
1243 |//-- Base library: conversions ------------------------------------------
1244 |
1245 |.ffunc tonumber
1246 | // Only handles the number case inline (without a base argument).
1247 | ld CARG1, 0(BASE)
1248 | xori AT, NARGS8:RC, 8 // Exactly one number argument.
1249 | gettp TMP1, CARG1
1250 | sltu TMP0, TISNUM, TMP1
1251 | or AT, AT, TMP0
1252 | bnez AT, ->fff_fallback
1253 |. nop
1254 | b ->fff_restv
1255 |. nop
1256 |
1257 |.ffunc_1 tostring
1258 | // Only handles the string or number case inline.
1259 | gettp TMP0, CARG1
1260 | daddiu AT, TMP0, -LJ_TSTR
1261 | // A __tostring method in the string base metatable is ignored.
1262 | beqz AT, ->fff_restv // String key?
1263 | // Handle numbers inline, unless a number base metatable is present.
1264 |. ld TMP1, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH)
1265 | sltu TMP0, TISNUM, TMP0
1266 | or TMP0, TMP0, TMP1
1267 | bnez TMP0, ->fff_fallback
1268 |. sd BASE, L->base // Add frame since C call can throw.
1269 | ffgccheck
1270 |. sd PC, SAVE_PC // Redundant (but a defined value).
1271 | load_got lj_strfmt_number
1272 | move CARG1, L
1273 | call_intern lj_strfmt_number // (lua_State *L, cTValue *o)
1274 |. move CARG2, BASE
1275 | // Returns GCstr *.
1276 | li AT, LJ_TSTR
1277 | settp CRET1, AT
1278 | b ->fff_restv
1279 |. move CARG1, CRET1
1280 |
1281 |//-- Base library: iterators -------------------------------------------
1282 |
1283 |.ffunc_1 next
1284 | checktp CARG2, CARG1, -LJ_TTAB, ->fff_fallback
1285 | daddu TMP2, BASE, NARGS8:RC
1286 | sd TISNIL, 0(TMP2) // Set missing 2nd arg to nil.
1287 | ld PC, FRAME_PC(BASE)
1288 | load_got lj_tab_next
1289 | sd BASE, L->base // Add frame since C call can throw.
1290 | sd BASE, L->top // Dummy frame length is ok.
1291 | daddiu CARG3, BASE, 8
1292 | sd PC, SAVE_PC
1293 | call_intern lj_tab_next // (lua_State *L, GCtab *t, TValue *key)
1294 |. move CARG1, L
1295 | // Returns 0 at end of traversal.
1296 | beqz CRET1, ->fff_restv // End of traversal: return nil.
1297 |. move CARG1, TISNIL
1298 | ld TMP0, 8(BASE)
1299 | daddiu RA, BASE, -16
1300 | ld TMP2, 16(BASE)
1301 | sd TMP0, 0(RA)
1302 | sd TMP2, 8(RA)
1303 | b ->fff_res
1304 |. li RD, (2+1)*8
1305 |
1306 |.ffunc_1 pairs
1307 | checktp TAB:TMP1, CARG1, -LJ_TTAB, ->fff_fallback
1308 | ld PC, FRAME_PC(BASE)
1309#if LJ_52
1310 | ld TAB:TMP2, TAB:TMP1->metatable
1311 | ld TMP0, CFUNC:RB->upvalue[0]
1312 | bnez TAB:TMP2, ->fff_fallback
1313#else
1314 | ld TMP0, CFUNC:RB->upvalue[0]
1315#endif
1316 |. daddiu RA, BASE, -16
1317 | sd TISNIL, 0(BASE)
1318 | sd CARG1, -8(BASE)
1319 | sd TMP0, 0(RA)
1320 | b ->fff_res
1321 |. li RD, (3+1)*8
1322 |
1323 |.ffunc_2 ipairs_aux
1324 | checktab CARG1, ->fff_fallback
1325 | checkint CARG2, ->fff_fallback
1326 |. lw TMP0, TAB:CARG1->asize
1327 | ld TMP1, TAB:CARG1->array
1328 | ld PC, FRAME_PC(BASE)
1329 | sextw TMP2, CARG2
1330 | addiu TMP2, TMP2, 1
1331 | sltu AT, TMP2, TMP0
1332 | daddiu RA, BASE, -16
1333 | zextw TMP0, TMP2
1334 | settp TMP0, TISNUM
1335 | beqz AT, >2 // Not in array part?
1336 |. sd TMP0, 0(RA)
1337 | dsll TMP3, TMP2, 3
1338 | daddu TMP3, TMP1, TMP3
1339 | ld TMP1, 0(TMP3)
1340 |1:
1341 | beq TMP1, TISNIL, ->fff_res // End of iteration, return 0 results.
1342 |. li RD, (0+1)*8
1343 | sd TMP1, -8(BASE)
1344 | b ->fff_res
1345 |. li RD, (2+1)*8
1346 |2: // Check for empty hash part first. Otherwise call C function.
1347 | lw TMP0, TAB:CARG1->hmask
1348 | load_got lj_tab_getinth
1349 | beqz TMP0, ->fff_res
1350 |. li RD, (0+1)*8
1351 | call_intern lj_tab_getinth // (GCtab *t, int32_t key)
1352 |. move CARG2, TMP2
1353 | // Returns cTValue * or NULL.
1354 | beqz CRET1, ->fff_res
1355 |. li RD, (0+1)*8
1356 | b <1
1357 |. ld TMP1, 0(CRET1)
1358 |
1359 |.ffunc_1 ipairs
1360 | checktp TAB:TMP1, CARG1, -LJ_TTAB, ->fff_fallback
1361 | ld PC, FRAME_PC(BASE)
1362#if LJ_52
1363 | ld TAB:TMP2, TAB:TMP1->metatable
1364 | ld CFUNC:TMP0, CFUNC:RB->upvalue[0]
1365 | bnez TAB:TMP2, ->fff_fallback
1366#else
1367 | ld TMP0, CFUNC:RB->upvalue[0]
1368#endif
1369 | daddiu RA, BASE, -16
1370 | dsll AT, TISNUM, 47
1371 | sd CARG1, -8(BASE)
1372 | sd AT, 0(BASE)
1373 | sd CFUNC:TMP0, 0(RA)
1374 | b ->fff_res
1375 |. li RD, (3+1)*8
1376 |
1377 |//-- Base library: catch errors ----------------------------------------
1378 |
1379 |.ffunc pcall
1380 | daddiu NARGS8:RC, NARGS8:RC, -8
1381 | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH)
1382 | bltz NARGS8:RC, ->fff_fallback
1383 |. move TMP2, BASE
1384 | daddiu BASE, BASE, 16
1385 | // Remember active hook before pcall.
1386 | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT
1387 | andi TMP3, TMP3, 1
1388 | daddiu PC, TMP3, 16+FRAME_PCALL
1389 | beqz NARGS8:RC, ->vm_call_dispatch
1390 |1:
1391 |. daddu TMP0, BASE, NARGS8:RC
1392 |2:
1393 | ld TMP1, -16(TMP0)
1394 | sd TMP1, -8(TMP0)
1395 | daddiu TMP0, TMP0, -8
1396 | bne TMP0, BASE, <2
1397 |. nop
1398 | b ->vm_call_dispatch
1399 |. nop
1400 |
1401 |.ffunc xpcall
1402 | daddiu NARGS8:RC, NARGS8:RC, -16
1403 | ld CARG1, 0(BASE)
1404 | ld CARG2, 8(BASE)
1405 | bltz NARGS8:RC, ->fff_fallback
1406 |. lbu TMP1, DISPATCH_GL(hookmask)(DISPATCH)
1407 | gettp AT, CARG2
1408 | daddiu AT, AT, -LJ_TFUNC
1409 | bnez AT, ->fff_fallback // Traceback must be a function.
1410 |. move TMP2, BASE
1411 | daddiu BASE, BASE, 24
1412 | // Remember active hook before pcall.
1413 | srl TMP3, TMP3, HOOK_ACTIVE_SHIFT
1414 | sd CARG2, 0(TMP2) // Swap function and traceback.
1415 | andi TMP3, TMP3, 1
1416 | sd CARG1, 8(TMP2)
1417 | beqz NARGS8:RC, ->vm_call_dispatch
1418 |. daddiu PC, TMP3, 24+FRAME_PCALL
1419 | b <1
1420 |. nop
1421 |
1422 |//-- Coroutine library --------------------------------------------------
1423 |
1424 |.macro coroutine_resume_wrap, resume
1425 |.if resume
1426 |.ffunc_1 coroutine_resume
1427 | checktp CARG1, CARG1, -LJ_TTHREAD, ->fff_fallback
1428 |.else
1429 |.ffunc coroutine_wrap_aux
1430 | ld L:CARG1, CFUNC:RB->upvalue[0].gcr
1431 | cleartp L:CARG1
1432 |.endif
1433 | lbu TMP0, L:CARG1->status
1434 | ld TMP1, L:CARG1->cframe
1435 | ld CARG2, L:CARG1->top
1436 | ld TMP2, L:CARG1->base
1437 | addiu AT, TMP0, -LUA_YIELD
1438 | daddu CARG3, CARG2, TMP0
1439 | daddiu TMP3, CARG2, 8
1440 | bgtz AT, ->fff_fallback // st > LUA_YIELD?
1441 |. movn CARG2, TMP3, AT
1442 | xor TMP2, TMP2, CARG3
1443 | bnez TMP1, ->fff_fallback // cframe != 0?
1444 |. or AT, TMP2, TMP0
1445 | ld TMP0, L:CARG1->maxstack
1446 | beqz AT, ->fff_fallback // base == top && st == 0?
1447 |. ld PC, FRAME_PC(BASE)
1448 | daddu TMP2, CARG2, NARGS8:RC
1449 | sltu AT, TMP0, TMP2
1450 | bnez AT, ->fff_fallback // Stack overflow?
1451 |. sd PC, SAVE_PC
1452 | sd BASE, L->base
1453 |1:
1454 |.if resume
1455 | daddiu BASE, BASE, 8 // Keep resumed thread in stack for GC.
1456 | daddiu NARGS8:RC, NARGS8:RC, -8
1457 | daddiu TMP2, TMP2, -8
1458 |.endif
1459 | sd TMP2, L:CARG1->top
1460 | daddu TMP1, BASE, NARGS8:RC
1461 | move CARG3, CARG2
1462 | sd BASE, L->top
1463 |2: // Move args to coroutine.
1464 | ld CRET1, 0(BASE)
1465 | sltu AT, BASE, TMP1
1466 | beqz AT, >3
1467 |. daddiu BASE, BASE, 8
1468 | sd CRET1, 0(CARG3)
1469 | b <2
1470 |. daddiu CARG3, CARG3, 8
1471 |3:
1472 | bal ->vm_resume // (lua_State *L, TValue *base, 0, 0)
1473 |. move L:RA, L:CARG1
1474 | // Returns thread status.
1475 |4:
1476 | ld TMP2, L:RA->base
1477 | sltiu AT, CRET1, LUA_YIELD+1
1478 | ld TMP3, L:RA->top
1479 | li_vmstate INTERP
1480 | ld BASE, L->base
1481 | sd L, DISPATCH_GL(cur_L)(DISPATCH)
1482 | st_vmstate
1483 | beqz AT, >8
1484 |. dsubu RD, TMP3, TMP2
1485 | ld TMP0, L->maxstack
1486 | beqz RD, >6 // No results?
1487 |. daddu TMP1, BASE, RD
1488 | sltu AT, TMP0, TMP1
1489 | bnez AT, >9 // Need to grow stack?
1490 |. daddu TMP3, TMP2, RD
1491 | sd TMP2, L:RA->top // Clear coroutine stack.
1492 | move TMP1, BASE
1493 |5: // Move results from coroutine.
1494 | ld CRET1, 0(TMP2)
1495 | daddiu TMP2, TMP2, 8
1496 | sltu AT, TMP2, TMP3
1497 | sd CRET1, 0(TMP1)
1498 | bnez AT, <5
1499 |. daddiu TMP1, TMP1, 8
1500 |6:
1501 | andi TMP0, PC, FRAME_TYPE
1502 |.if resume
1503 | mov_true TMP1
1504 | daddiu RA, BASE, -8
1505 | sd TMP1, -8(BASE) // Prepend true to results.
1506 | daddiu RD, RD, 16
1507 |.else
1508 | move RA, BASE
1509 | daddiu RD, RD, 8
1510 |.endif
1511 |7:
1512 | sd PC, SAVE_PC
1513 | beqz TMP0, ->BC_RET_Z
1514 |. move MULTRES, RD
1515 | b ->vm_return
1516 |. nop
1517 |
1518 |8: // Coroutine returned with error (at co->top-1).
1519 |.if resume
1520 | daddiu TMP3, TMP3, -8
1521 | mov_false TMP1
1522 | ld CRET1, 0(TMP3)
1523 | sd TMP3, L:RA->top // Remove error from coroutine stack.
1524 | li RD, (2+1)*8
1525 | sd TMP1, -8(BASE) // Prepend false to results.
1526 | daddiu RA, BASE, -8
1527 | sd CRET1, 0(BASE) // Copy error message.
1528 | b <7
1529 |. andi TMP0, PC, FRAME_TYPE
1530 |.else
1531 | load_got lj_ffh_coroutine_wrap_err
1532 | move CARG2, L:RA
1533 | call_intern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co)
1534 |. move CARG1, L
1535 |.endif
1536 |
1537 |9: // Handle stack expansion on return from yield.
1538 | load_got lj_state_growstack
1539 | srl CARG2, RD, 3
1540 | call_intern lj_state_growstack // (lua_State *L, int n)
1541 |. move CARG1, L
1542 | b <4
1543 |. li CRET1, 0
1544 |.endmacro
1545 |
1546 | coroutine_resume_wrap 1 // coroutine.resume
1547 | coroutine_resume_wrap 0 // coroutine.wrap
1548 |
1549 |.ffunc coroutine_yield
1550 | ld TMP0, L->cframe
1551 | daddu TMP1, BASE, NARGS8:RC
1552 | sd BASE, L->base
1553 | andi TMP0, TMP0, CFRAME_RESUME
1554 | sd TMP1, L->top
1555 | beqz TMP0, ->fff_fallback
1556 |. li CRET1, LUA_YIELD
1557 | sd r0, L->cframe
1558 | b ->vm_leave_unw
1559 |. sb CRET1, L->status
1560 |
1561 |//-- Math library -------------------------------------------------------
1562 |
1563 |.ffunc_1 math_abs
1564 | gettp CARG2, CARG1
1565 | daddiu AT, CARG2, -LJ_TISNUM
1566 | bnez AT, >1
1567 |. sextw TMP1, CARG1
1568 | sra TMP0, TMP1, 31 // Extract sign.
1569 | xor TMP1, TMP1, TMP0
1570 | dsubu CARG1, TMP1, TMP0
1571 | dsll TMP3, CARG1, 32
1572 | bgez TMP3, ->fff_restv
1573 |. settp CARG1, TISNUM
1574 | li CARG1, 0x41e0 // 2^31 as a double.
1575 | b ->fff_restv
1576 |. dsll CARG1, CARG1, 48
1577 |1:
1578 | sltiu AT, CARG2, LJ_TISNUM
1579 | beqz AT, ->fff_fallback
1580 |. dextm CARG1, CARG1, 0, 30
1581 |// fallthrough
1582 |
1583 |->fff_restv:
1584 | // CARG1 = TValue result.
1585 | ld PC, FRAME_PC(BASE)
1586 | daddiu RA, BASE, -16
1587 | sd CARG1, -16(BASE)
1588 |->fff_res1:
1589 | // RA = results, PC = return.
1590 | li RD, (1+1)*8
1591 |->fff_res:
1592 | // RA = results, RD = (nresults+1)*8, PC = return.
1593 | andi TMP0, PC, FRAME_TYPE
1594 | bnez TMP0, ->vm_return
1595 |. move MULTRES, RD
1596 | lw INS, -4(PC)
1597 | decode_RB8a RB, INS
1598 | decode_RB8b RB
1599 |5:
1600 | sltu AT, RD, RB
1601 | bnez AT, >6 // More results expected?
1602 |. decode_RA8a TMP0, INS
1603 | decode_RA8b TMP0
1604 | ins_next1
1605 | // Adjust BASE. KBASE is assumed to be set for the calling frame.
1606 | dsubu BASE, RA, TMP0
1607 | ins_next2
1608 |
1609 |6: // Fill up results with nil.
1610 | daddu TMP1, RA, RD
1611 | daddiu RD, RD, 8
1612 | b <5
1613 |. sd TISNIL, -8(TMP1)
1614 |
1615 |.macro math_extern, func
1616 | .ffunc_n math_ .. func
1617 | load_got func
1618 | call_extern
1619 |. nop
1620 | b ->fff_resn
1621 |. nop
1622 |.endmacro
1623 |
1624 |.macro math_extern2, func
1625 | .ffunc_nn math_ .. func
1626 |. load_got func
1627 | call_extern
1628 |. nop
1629 | b ->fff_resn
1630 |. nop
1631 |.endmacro
1632 |
1633 |// TODO: Return integer type if result is integer (own sf implementation).
1634 |.macro math_round, func
1635 |->ff_math_ .. func:
1636 | ld CARG1, 0(BASE)
1637 | beqz NARGS8:RC, ->fff_fallback
1638 |. gettp TMP0, CARG1
1639 | beq TMP0, TISNUM, ->fff_restv
1640 |. sltu AT, TMP0, TISNUM
1641 | beqz AT, ->fff_fallback
1642 |.if FPU
1643 |. ldc1 FARG1, 0(BASE)
1644 | bal ->vm_ .. func
1645 |. nop
1646 |.else
1647 |. load_got func
1648 | call_extern
1649 |. nop
1650 |.endif
1651 | b ->fff_resn
1652 |. nop
1653 |.endmacro
1654 |
1655 | math_round floor
1656 | math_round ceil
1657 |
1658 |.ffunc math_log
1659 | li AT, 8
1660 | bne NARGS8:RC, AT, ->fff_fallback // Exactly 1 argument.
1661 |. ld CARG1, 0(BASE)
1662 | checknum CARG1, ->fff_fallback
1663 |. load_got log
1664 |.if FPU
1665 | call_extern
1666 |. ldc1 FARG1, 0(BASE)
1667 |.else
1668 | call_extern
1669 |. nop
1670 |.endif
1671 | b ->fff_resn
1672 |. nop
1673 |
1674 | math_extern log10
1675 | math_extern exp
1676 | math_extern sin
1677 | math_extern cos
1678 | math_extern tan
1679 | math_extern asin
1680 | math_extern acos
1681 | math_extern atan
1682 | math_extern sinh
1683 | math_extern cosh
1684 | math_extern tanh
1685 | math_extern2 pow
1686 | math_extern2 atan2
1687 | math_extern2 fmod
1688 |
1689 |.if FPU
1690 |.ffunc_n math_sqrt
1691 |. sqrt.d FRET1, FARG1
1692 |// fallthrough to ->fff_resn
1693 |.else
1694 | math_extern sqrt
1695 |.endif
1696 |
1697 |->fff_resn:
1698 | ld PC, FRAME_PC(BASE)
1699 | daddiu RA, BASE, -16
1700 | b ->fff_res1
1701 |.if FPU
1702 |. sdc1 FRET1, 0(RA)
1703 |.else
1704 |. sd CRET1, 0(RA)
1705 |.endif
1706 |
1707 |
1708 |.ffunc_2 math_ldexp
1709 | checknum CARG1, ->fff_fallback
1710 | checkint CARG2, ->fff_fallback
1711 |. load_got ldexp
1712 | .FPU ldc1 FARG1, 0(BASE)
1713 | call_extern
1714 |. lw CARG2, 8+LO(BASE)
1715 | b ->fff_resn
1716 |. nop
1717 |
1718 |.ffunc_n math_frexp
1719 | load_got frexp
1720 | ld PC, FRAME_PC(BASE)
1721 | call_extern
1722 |. daddiu CARG2, DISPATCH, DISPATCH_GL(tmptv)
1723 | lw TMP1, DISPATCH_GL(tmptv)(DISPATCH)
1724 | daddiu RA, BASE, -16
1725 |.if FPU
1726 | mtc1 TMP1, FARG2
1727 | sdc1 FRET1, 0(RA)
1728 | cvt.d.w FARG2, FARG2
1729 | sdc1 FARG2, 8(RA)
1730 |.else
1731 | sd CRET1, 0(RA)
1732 | zextw TMP1, TMP1
1733 | settp TMP1, TISNUM
1734 | sd TMP1, 8(RA)
1735 |.endif
1736 | b ->fff_res
1737 |. li RD, (2+1)*8
1738 |
1739 |.ffunc_n math_modf
1740 | load_got modf
1741 | ld PC, FRAME_PC(BASE)
1742 | call_extern
1743 |. daddiu CARG2, BASE, -16
1744 | daddiu RA, BASE, -16
1745 |.if FPU
1746 | sdc1 FRET1, -8(BASE)
1747 |.else
1748 | sd CRET1, -8(BASE)
1749 |.endif
1750 | b ->fff_res
1751 |. li RD, (2+1)*8
1752 |
1753 |.macro math_minmax, name, intins, fpins
1754 | .ffunc_1 name
1755 | daddu TMP3, BASE, NARGS8:RC
1756 | checkint CARG1, >5
1757 |. daddiu TMP2, BASE, 8
1758 |1: // Handle integers.
1759 | beq TMP2, TMP3, ->fff_restv
1760 |. ld CARG2, 0(TMP2)
1761 | checkint CARG2, >3
1762 |. sextw CARG1, CARG1
1763 | lw CARG2, LO(TMP2)
1764 |. slt AT, CARG1, CARG2
1765 | intins CARG1, CARG2, AT
1766 | daddiu TMP2, TMP2, 8
1767 | zextw CARG1, CARG1
1768 | b <1
1769 |. settp CARG1, TISNUM
1770 |
1771 |3: // Convert intermediate result to number and continue with number loop.
1772 | checknum CARG2, ->fff_fallback
1773 |.if FPU
1774 |. mtc1 CARG1, FRET1
1775 | cvt.d.w FRET1, FRET1
1776 | b >7
1777 |. ldc1 FARG1, 0(TMP2)
1778 |.else
1779 |. nop
1780 | bal ->vm_sfi2d_1
1781 |. nop
1782 | b >7
1783 |. nop
1784 |.endif
1785 |
1786 |5:
1787 | .FPU ldc1 FRET1, 0(BASE)
1788 | checknum CARG1, ->fff_fallback
1789 |6: // Handle numbers.
1790 |. ld CARG2, 0(TMP2)
1791 | beq TMP2, TMP3, ->fff_resn
1792 |.if FPU
1793 | ldc1 FARG1, 0(TMP2)
1794 |.else
1795 | move CRET1, CARG1
1796 |.endif
1797 | checknum CARG2, >8
1798 |. nop
1799 |7:
1800 |.if FPU
1801 | c.olt.d FRET1, FARG1
1802 | fpins FRET1, FARG1
1803 |.else
1804 | bal ->vm_sfcmpolt
1805 |. nop
1806 | intins CARG1, CARG2, CRET1
1807 |.endif
1808 | b <6
1809 |. daddiu TMP2, TMP2, 8
1810 |
1811 |8: // Convert integer to number and continue with number loop.
1812 | checkint CARG2, ->fff_fallback
1813 |.if FPU
1814 |. lwc1 FARG1, LO(TMP2)
1815 | b <7
1816 |. cvt.d.w FARG1, FARG1
1817 |.else
1818 |. lw CARG2, LO(TMP2)
1819 | bal ->vm_sfi2d_2
1820 |. nop
1821 | b <7
1822 |. nop
1823 |.endif
1824 |
1825 |.endmacro
1826 |
1827 | math_minmax math_min, movz, movf.d
1828 | math_minmax math_max, movn, movt.d
1829 |
1830 |//-- String library -----------------------------------------------------
1831 |
1832 |.ffunc string_byte // Only handle the 1-arg case here.
1833 | ld CARG1, 0(BASE)
1834 | gettp TMP0, CARG1
1835 | xori AT, NARGS8:RC, 8
1836 | daddiu TMP0, TMP0, -LJ_TSTR
1837 | or AT, AT, TMP0
1838 | bnez AT, ->fff_fallback // Need exactly 1 string argument.
1839 |. cleartp STR:CARG1
1840 | lw TMP0, STR:CARG1->len
1841 | daddiu RA, BASE, -16
1842 | ld PC, FRAME_PC(BASE)
1843 | sltu RD, r0, TMP0
1844 | lbu TMP1, STR:CARG1[1] // Access is always ok (NUL at end).
1845 | addiu RD, RD, 1
1846 | sll RD, RD, 3 // RD = ((str->len != 0)+1)*8
1847 | settp TMP1, TISNUM
1848 | b ->fff_res
1849 |. sd TMP1, 0(RA)
1850 |
1851 |.ffunc string_char // Only handle the 1-arg case here.
1852 | ffgccheck
1853 |. nop
1854 | ld CARG1, 0(BASE)
1855 | gettp TMP0, CARG1
1856 | xori AT, NARGS8:RC, 8 // Exactly 1 argument.
1857 | daddiu TMP0, TMP0, -LJ_TISNUM // Integer.
1858 | li TMP1, 255
1859 | sextw CARG1, CARG1
1860 | or AT, AT, TMP0
1861 | sltu TMP1, TMP1, CARG1 // !(255 < n).
1862 | or AT, AT, TMP1
1863 | bnez AT, ->fff_fallback
1864 |. li CARG3, 1
1865 | daddiu CARG2, sp, TMPD_OFS
1866 | sb CARG1, TMPD
1867 |->fff_newstr:
1868 | load_got lj_str_new
1869 | sd BASE, L->base
1870 | sd PC, SAVE_PC
1871 | call_intern lj_str_new // (lua_State *L, char *str, size_t l)
1872 |. move CARG1, L
1873 | // Returns GCstr *.
1874 | ld BASE, L->base
1875 |->fff_resstr:
1876 | li AT, LJ_TSTR
1877 | settp CRET1, AT
1878 | b ->fff_restv
1879 |. move CARG1, CRET1
1880 |
1881 |.ffunc string_sub
1882 | ffgccheck
1883 |. nop
1884 | addiu AT, NARGS8:RC, -16
1885 | ld TMP0, 0(BASE)
1886 | bltz AT, ->fff_fallback
1887 |. gettp TMP3, TMP0
1888 | cleartp STR:CARG1, TMP0
1889 | ld CARG2, 8(BASE)
1890 | beqz AT, >1
1891 |. li CARG4, -1
1892 | ld CARG3, 16(BASE)
1893 | checkint CARG3, ->fff_fallback
1894 |. sextw CARG4, CARG3
1895 |1:
1896 | checkint CARG2, ->fff_fallback
1897 |. li AT, LJ_TSTR
1898 | bne TMP3, AT, ->fff_fallback
1899 |. sextw CARG3, CARG2
1900 | lw CARG2, STR:CARG1->len
1901 | // STR:CARG1 = str, CARG2 = str->len, CARG3 = start, CARG4 = end
1902 | slt AT, CARG4, r0
1903 | addiu TMP0, CARG2, 1
1904 | addu TMP1, CARG4, TMP0
1905 | slt TMP3, CARG3, r0
1906 | movn CARG4, TMP1, AT // if (end < 0) end += len+1
1907 | addu TMP1, CARG3, TMP0
1908 | movn CARG3, TMP1, TMP3 // if (start < 0) start += len+1
1909 | li TMP2, 1
1910 | slt AT, CARG4, r0
1911 | slt TMP3, r0, CARG3
1912 | movn CARG4, r0, AT // if (end < 0) end = 0
1913 | movz CARG3, TMP2, TMP3 // if (start < 1) start = 1
1914 | slt AT, CARG2, CARG4
1915 | movn CARG4, CARG2, AT // if (end > len) end = len
1916 | daddu CARG2, STR:CARG1, CARG3
1917 | subu CARG3, CARG4, CARG3 // len = end - start
1918 | daddiu CARG2, CARG2, sizeof(GCstr)-1
1919 | bgez CARG3, ->fff_newstr
1920 |. addiu CARG3, CARG3, 1 // len++
1921 |->fff_emptystr: // Return empty string.
1922 | li AT, LJ_TSTR
1923 | daddiu STR:CARG1, DISPATCH, DISPATCH_GL(strempty)
1924 | b ->fff_restv
1925 |. settp CARG1, AT
1926 |
1927 |.macro ffstring_op, name
1928 | .ffunc string_ .. name
1929 | ffgccheck
1930 |. nop
1931 | beqz NARGS8:RC, ->fff_fallback
1932 |. ld CARG2, 0(BASE)
1933 | checkstr STR:CARG2, ->fff_fallback
1934 | daddiu SBUF:CARG1, DISPATCH, DISPATCH_GL(tmpbuf)
1935 | load_got lj_buf_putstr_ .. name
1936 | ld TMP0, SBUF:CARG1->b
1937 | sd L, SBUF:CARG1->L
1938 | sd BASE, L->base
1939 | sd TMP0, SBUF:CARG1->p
1940 | call_intern extern lj_buf_putstr_ .. name
1941 |. sd PC, SAVE_PC
1942 | load_got lj_buf_tostr
1943 | call_intern lj_buf_tostr
1944 |. move SBUF:CARG1, SBUF:CRET1
1945 | b ->fff_resstr
1946 |. ld BASE, L->base
1947 |.endmacro
1948 |
1949 |ffstring_op reverse
1950 |ffstring_op lower
1951 |ffstring_op upper
1952 |
1953 |//-- Bit library --------------------------------------------------------
1954 |
1955 |->vm_tobit_fb:
1956 | beqz TMP1, ->fff_fallback
1957 |.if FPU
1958 |. ldc1 FARG1, 0(BASE)
1959 | add.d FARG1, FARG1, TOBIT
1960 | mfc1 CRET1, FARG1
1961 | jr ra
1962 |. zextw CRET1, CRET1
1963 |.else
1964 |// FP number to bit conversion for soft-float.
1965 |->vm_tobit:
1966 | dsll TMP0, CARG1, 1
1967 | li CARG3, 1076
1968 | dsrl AT, TMP0, 53
1969 | dsubu CARG3, CARG3, AT
1970 | sltiu AT, CARG3, 54
1971 | beqz AT, >1
1972 |. dextm TMP0, TMP0, 0, 20
1973 | dinsu TMP0, AT, 21, 21
1974 | slt AT, CARG1, r0
1975 | dsrlv CRET1, TMP0, CARG3
1976 | dsubu TMP0, r0, CRET1
1977 | movn CRET1, TMP0, AT
1978 | jr ra
1979 |. zextw CRET1, CRET1
1980 |1:
1981 | jr ra
1982 |. move CRET1, r0
1983 |.endif
1984 |
1985 |.macro .ffunc_bit, name
1986 | .ffunc_1 bit_..name
1987 | gettp TMP0, CARG1
1988 | beq TMP0, TISNUM, >6
1989 |. zextw CRET1, CARG1
1990 | bal ->vm_tobit_fb
1991 |. sltiu TMP1, TMP0, LJ_TISNUM
1992 |6:
1993 |.endmacro
1994 |
1995 |.macro .ffunc_bit_op, name, bins
1996 | .ffunc_bit name
1997 | daddiu TMP2, BASE, 8
1998 | daddu TMP3, BASE, NARGS8:RC
1999 |1:
2000 | beq TMP2, TMP3, ->fff_resi
2001 |. ld CARG1, 0(TMP2)
2002 | gettp TMP0, CARG1
2003 |.if FPU
2004 | bne TMP0, TISNUM, >2
2005 |. daddiu TMP2, TMP2, 8
2006 | zextw CARG1, CARG1
2007 | b <1
2008 |. bins CRET1, CRET1, CARG1
2009 |2:
2010 | ldc1 FARG1, -8(TMP2)
2011 | sltiu AT, TMP0, LJ_TISNUM
2012 | beqz AT, ->fff_fallback
2013 |. add.d FARG1, FARG1, TOBIT
2014 | mfc1 CARG1, FARG1
2015 | zextw CARG1, CARG1
2016 | b <1
2017 |. bins CRET1, CRET1, CARG1
2018 |.else
2019 | beq TMP0, TISNUM, >2
2020 |. move CRET2, CRET1
2021 | bal ->vm_tobit_fb
2022 |. sltiu TMP1, TMP0, LJ_TISNUM
2023 | move CARG1, CRET2
2024 |2:
2025 | zextw CARG1, CARG1
2026 | bins CRET1, CRET1, CARG1
2027 | b <1
2028 |. daddiu TMP2, TMP2, 8
2029 |.endif
2030 |.endmacro
2031 |
2032 |.ffunc_bit_op band, and
2033 |.ffunc_bit_op bor, or
2034 |.ffunc_bit_op bxor, xor
2035 |
2036 |.ffunc_bit bswap
2037 | dsrl TMP0, CRET1, 8
2038 | dsrl TMP1, CRET1, 24
2039 | andi TMP2, TMP0, 0xff00
2040 | dins TMP1, CRET1, 24, 31
2041 | dins TMP2, TMP0, 16, 23
2042 | b ->fff_resi
2043 |. or CRET1, TMP1, TMP2
2044 |
2045 |.ffunc_bit bnot
2046 | not CRET1, CRET1
2047 | b ->fff_resi
2048 |. zextw CRET1, CRET1
2049 |
2050 |.macro .ffunc_bit_sh, name, shins, shmod
2051 | .ffunc_2 bit_..name
2052 | gettp TMP0, CARG1
2053 | beq TMP0, TISNUM, >1
2054 |. nop
2055 | bal ->vm_tobit_fb
2056 |. sltiu TMP1, TMP0, LJ_TISNUM
2057 | move CARG1, CRET1
2058 |1:
2059 | gettp TMP0, CARG2
2060 | bne TMP0, TISNUM, ->fff_fallback
2061 |. zextw CARG2, CARG2
2062 | sextw CARG1, CARG1
2063 |.if shmod == 1
2064 | negu CARG2, CARG2
2065 |.endif
2066 | shins CRET1, CARG1, CARG2
2067 | b ->fff_resi
2068 |. zextw CRET1, CRET1
2069 |.endmacro
2070 |
2071 |.ffunc_bit_sh lshift, sllv, 0
2072 |.ffunc_bit_sh rshift, srlv, 0
2073 |.ffunc_bit_sh arshift, srav, 0
2074 |.ffunc_bit_sh rol, rotrv, 1
2075 |.ffunc_bit_sh ror, rotrv, 0
2076 |
2077 |.ffunc_bit tobit
2078 |->fff_resi:
2079 | ld PC, FRAME_PC(BASE)
2080 | daddiu RA, BASE, -16
2081 | settp CRET1, TISNUM
2082 | b ->fff_res1
2083 |. sd CRET1, -16(BASE)
2084 |
2085 |//-----------------------------------------------------------------------
2086 |->fff_fallback: // Call fast function fallback handler.
2087 | // BASE = new base, RB = CFUNC, RC = nargs*8
2088 | ld TMP3, CFUNC:RB->f
2089 | daddu TMP1, BASE, NARGS8:RC
2090 | ld PC, FRAME_PC(BASE) // Fallback may overwrite PC.
2091 | daddiu TMP0, TMP1, 8*LUA_MINSTACK
2092 | ld TMP2, L->maxstack
2093 | sd PC, SAVE_PC // Redundant (but a defined value).
2094 | sltu AT, TMP2, TMP0
2095 | sd BASE, L->base
2096 | sd TMP1, L->top
2097 | bnez AT, >5 // Need to grow stack.
2098 |. move CFUNCADDR, TMP3
2099 | jalr TMP3 // (lua_State *L)
2100 |. move CARG1, L
2101 | // Either throws an error, or recovers and returns -1, 0 or nresults+1.
2102 | ld BASE, L->base
2103 | sll RD, CRET1, 3
2104 | bgtz CRET1, ->fff_res // Returned nresults+1?
2105 |. daddiu RA, BASE, -16
2106 |1: // Returned 0 or -1: retry fast path.
2107 | ld LFUNC:RB, FRAME_FUNC(BASE)
2108 | ld TMP0, L->top
2109 | cleartp LFUNC:RB
2110 | bnez CRET1, ->vm_call_tail // Returned -1?
2111 |. dsubu NARGS8:RC, TMP0, BASE
2112 | ins_callt // Returned 0: retry fast path.
2113 |
2114 |// Reconstruct previous base for vmeta_call during tailcall.
2115 |->vm_call_tail:
2116 | andi TMP0, PC, FRAME_TYPE
2117 | li AT, -4
2118 | bnez TMP0, >3
2119 |. and TMP1, PC, AT
2120 | lbu TMP1, OFS_RA(PC)
2121 | sll TMP1, TMP1, 3
2122 | addiu TMP1, TMP1, 16
2123 |3:
2124 | b ->vm_call_dispatch // Resolve again for tailcall.
2125 |. dsubu TMP2, BASE, TMP1
2126 |
2127 |5: // Grow stack for fallback handler.
2128 | load_got lj_state_growstack
2129 | li CARG2, LUA_MINSTACK
2130 | call_intern lj_state_growstack // (lua_State *L, int n)
2131 |. move CARG1, L
2132 | ld BASE, L->base
2133 | b <1
2134 |. li CRET1, 0 // Force retry.
2135 |
2136 |->fff_gcstep: // Call GC step function.
2137 | // BASE = new base, RC = nargs*8
2138 | move MULTRES, ra
2139 | load_got lj_gc_step
2140 | sd BASE, L->base
2141 | daddu TMP0, BASE, NARGS8:RC
2142 | sd PC, SAVE_PC // Redundant (but a defined value).
2143 | sd TMP0, L->top
2144 | call_intern lj_gc_step // (lua_State *L)
2145 |. move CARG1, L
2146 | ld BASE, L->base
2147 | move ra, MULTRES
2148 | ld TMP0, L->top
2149 | ld CFUNC:RB, FRAME_FUNC(BASE)
2150 | cleartp CFUNC:RB
2151 | jr ra
2152 |. dsubu NARGS8:RC, TMP0, BASE
2153 |
2154 |//-----------------------------------------------------------------------
2155 |//-- Special dispatch targets -------------------------------------------
2156 |//-----------------------------------------------------------------------
2157 |
2158 |->vm_record: // Dispatch target for recording phase.
2159 |.if JIT
2160 | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH)
2161 | andi AT, TMP3, HOOK_VMEVENT // No recording while in vmevent.
2162 | bnez AT, >5
2163 | // Decrement the hookcount for consistency, but always do the call.
2164 |. lw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
2165 | andi AT, TMP3, HOOK_ACTIVE
2166 | bnez AT, >1
2167 |. addiu TMP2, TMP2, -1
2168 | andi AT, TMP3, LUA_MASKLINE|LUA_MASKCOUNT
2169 | beqz AT, >1
2170 |. nop
2171 | b >1
2172 |. sw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
2173 |.endif
2174 |
2175 |->vm_rethook: // Dispatch target for return hooks.
2176 | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH)
2177 | andi AT, TMP3, HOOK_ACTIVE // Hook already active?
2178 | beqz AT, >1
2179 |5: // Re-dispatch to static ins.
2180 |. ld AT, GG_DISP2STATIC(TMP0) // Assumes TMP0 holds DISPATCH+OP*4.
2181 | jr AT
2182 |. nop
2183 |
2184 |->vm_inshook: // Dispatch target for instr/line hooks.
2185 | lbu TMP3, DISPATCH_GL(hookmask)(DISPATCH)
2186 | lw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
2187 | andi AT, TMP3, HOOK_ACTIVE // Hook already active?
2188 | bnez AT, <5
2189 |. andi AT, TMP3, LUA_MASKLINE|LUA_MASKCOUNT
2190 | beqz AT, <5
2191 |. addiu TMP2, TMP2, -1
2192 | beqz TMP2, >1
2193 |. sw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
2194 | andi AT, TMP3, LUA_MASKLINE
2195 | beqz AT, <5
2196 |1:
2197 |. load_got lj_dispatch_ins
2198 | sw MULTRES, SAVE_MULTRES
2199 | move CARG2, PC
2200 | sd BASE, L->base
2201 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
2202 | call_intern lj_dispatch_ins // (lua_State *L, const BCIns *pc)
2203 |. move CARG1, L
2204 |3:
2205 | ld BASE, L->base
2206 |4: // Re-dispatch to static ins.
2207 | lw INS, -4(PC)
2208 | decode_OP8a TMP1, INS
2209 | decode_OP8b TMP1
2210 | daddu TMP0, DISPATCH, TMP1
2211 | decode_RD8a RD, INS
2212 | ld AT, GG_DISP2STATIC(TMP0)
2213 | decode_RA8a RA, INS
2214 | decode_RD8b RD
2215 | jr AT
2216 | decode_RA8b RA
2217 |
2218 |->cont_hook: // Continue from hook yield.
2219 | daddiu PC, PC, 4
2220 | b <4
2221 |. lw MULTRES, -24+LO(RB) // Restore MULTRES for *M ins.
2222 |
2223 |->vm_hotloop: // Hot loop counter underflow.
2224 |.if JIT
2225 | ld LFUNC:TMP1, FRAME_FUNC(BASE)
2226 | daddiu CARG1, DISPATCH, GG_DISP2J
2227 | cleartp LFUNC:TMP1
2228 | sd PC, SAVE_PC
2229 | ld TMP1, LFUNC:TMP1->pc
2230 | move CARG2, PC
2231 | sd L, DISPATCH_J(L)(DISPATCH)
2232 | lbu TMP1, PC2PROTO(framesize)(TMP1)
2233 | load_got lj_trace_hot
2234 | sd BASE, L->base
2235 | dsll TMP1, TMP1, 3
2236 | daddu TMP1, BASE, TMP1
2237 | call_intern lj_trace_hot // (jit_State *J, const BCIns *pc)
2238 |. sd TMP1, L->top
2239 | b <3
2240 |. nop
2241 |.endif
2242 |
2243 |
2244 |->vm_callhook: // Dispatch target for call hooks.
2245 |.if JIT
2246 | b >1
2247 |.endif
2248 |. move CARG2, PC
2249 |
2250 |->vm_hotcall: // Hot call counter underflow.
2251 |.if JIT
2252 | ori CARG2, PC, 1
2253 |1:
2254 |.endif
2255 | load_got lj_dispatch_call
2256 | daddu TMP0, BASE, RC
2257 | sd PC, SAVE_PC
2258 | sd BASE, L->base
2259 | dsubu RA, RA, BASE
2260 | sd TMP0, L->top
2261 | call_intern lj_dispatch_call // (lua_State *L, const BCIns *pc)
2262 |. move CARG1, L
2263 | // Returns ASMFunction.
2264 | ld BASE, L->base
2265 | ld TMP0, L->top
2266 | sd r0, SAVE_PC // Invalidate for subsequent line hook.
2267 | dsubu NARGS8:RC, TMP0, BASE
2268 | daddu RA, BASE, RA
2269 | ld LFUNC:RB, FRAME_FUNC(BASE)
2270 | cleartp LFUNC:RB
2271 | jr CRET1
2272 |. lw INS, -4(PC)
2273 |
2274 |->cont_stitch: // Trace stitching.
2275 |.if JIT
2276 | // RA = resultptr, RB = meta base
2277 | lw INS, -4(PC)
2278 | ld TRACE:TMP2, -40(RB) // Save previous trace.
2279 | decode_RA8a RC, INS
2280 | daddiu AT, MULTRES, -8
2281 | cleartp TRACE:TMP2
2282 | decode_RA8b RC
2283 | beqz AT, >2
2284 |. daddu RC, BASE, RC // Call base.
2285 |1: // Move results down.
2286 | ld CARG1, 0(RA)
2287 | daddiu AT, AT, -8
2288 | daddiu RA, RA, 8
2289 | sd CARG1, 0(RC)
2290 | bnez AT, <1
2291 |. daddiu RC, RC, 8
2292 |2:
2293 | decode_RA8a RA, INS
2294 | decode_RB8a RB, INS
2295 | decode_RA8b RA
2296 | decode_RB8b RB
2297 | daddu RA, RA, RB
2298 | daddu RA, BASE, RA
2299 |3:
2300 | sltu AT, RC, RA
2301 | bnez AT, >9 // More results wanted?
2302 |. nop
2303 |
2304 | lhu TMP3, TRACE:TMP2->traceno
2305 | lhu RD, TRACE:TMP2->link
2306 | beq RD, TMP3, ->cont_nop // Blacklisted.
2307 |. load_got lj_dispatch_stitch
2308 | bnez RD, =>BC_JLOOP // Jump to stitched trace.
2309 |. sll RD, RD, 3
2310 |
2311 | // Stitch a new trace to the previous trace.
2312 | sw TMP3, DISPATCH_J(exitno)(DISPATCH)
2313 | sd L, DISPATCH_J(L)(DISPATCH)
2314 | sd BASE, L->base
2315 | daddiu CARG1, DISPATCH, GG_DISP2J
2316 | call_intern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
2317 |. move CARG2, PC
2318 | b ->cont_nop
2319 |. ld BASE, L->base
2320 |
2321 |9:
2322 | sd TISNIL, 0(RC)
2323 | b <3
2324 |. daddiu RC, RC, 8
2325 |.endif
2326 |
2327 |->vm_profhook: // Dispatch target for profiler hook.
2328#if LJ_HASPROFILE
2329 | load_got lj_dispatch_profile
2330 | sd MULTRES, SAVE_MULTRES
2331 | move CARG2, PC
2332 | sd BASE, L->base
2333 | call_intern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
2334 |. move CARG1, L
2335 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2336 | daddiu PC, PC, -4
2337 | b ->cont_nop
2338 |. ld BASE, L->base
2339#endif
2340 |
2341 |//-----------------------------------------------------------------------
2342 |//-- Trace exit handler -------------------------------------------------
2343 |//-----------------------------------------------------------------------
2344 |
2345 |.macro savex_, a, b
2346 |.if FPU
2347 | sdc1 f..a, a*8(sp)
2348 | sdc1 f..b, b*8(sp)
2349 | sd r..a, 32*8+a*8(sp)
2350 | sd r..b, 32*8+b*8(sp)
2351 |.else
2352 | sd r..a, a*8(sp)
2353 | sd r..b, b*8(sp)
2354 |.endif
2355 |.endmacro
2356 |
2357 |->vm_exit_handler:
2358 |.if JIT
2359 |.if FPU
2360 | daddiu sp, sp, -(32*8+32*8)
2361 |.else
2362 | daddiu sp, sp, -(32*8)
2363 |.endif
2364 | savex_ 0, 1
2365 | savex_ 2, 3
2366 | savex_ 4, 5
2367 | savex_ 6, 7
2368 | savex_ 8, 9
2369 | savex_ 10, 11
2370 | savex_ 12, 13
2371 | savex_ 14, 15
2372 | savex_ 16, 17
2373 | savex_ 18, 19
2374 | savex_ 20, 21
2375 | savex_ 22, 23
2376 | savex_ 24, 25
2377 | savex_ 26, 27
2378 | savex_ 28, 30
2379 |.if FPU
2380 | sdc1 f29, 29*8(sp)
2381 | sdc1 f31, 31*8(sp)
2382 | sd r0, 32*8+31*8(sp) // Clear RID_TMP.
2383 | daddiu TMP2, sp, 32*8+32*8 // Recompute original value of sp.
2384 | sd TMP2, 32*8+29*8(sp) // Store sp in RID_SP
2385 |.else
2386 | sd r0, 31*8(sp) // Clear RID_TMP.
2387 | daddiu TMP2, sp, 32*8 // Recompute original value of sp.
2388 | sd TMP2, 29*8(sp) // Store sp in RID_SP
2389 |.endif
2390 | li_vmstate EXIT
2391 | daddiu DISPATCH, JGL, -GG_DISP2G-32768
2392 | lw TMP1, 0(TMP2) // Load exit number.
2393 | st_vmstate
2394 | ld L, DISPATCH_GL(cur_L)(DISPATCH)
2395 | ld BASE, DISPATCH_GL(jit_base)(DISPATCH)
2396 | load_got lj_trace_exit
2397 | sd L, DISPATCH_J(L)(DISPATCH)
2398 | sw ra, DISPATCH_J(parent)(DISPATCH) // Store trace number.
2399 | sd BASE, L->base
2400 | sw TMP1, DISPATCH_J(exitno)(DISPATCH) // Store exit number.
2401 | daddiu CARG1, DISPATCH, GG_DISP2J
2402 | sd r0, DISPATCH_GL(jit_base)(DISPATCH)
2403 | call_intern lj_trace_exit // (jit_State *J, ExitState *ex)
2404 |. move CARG2, sp
2405 | // Returns MULTRES (unscaled) or negated error code.
2406 | ld TMP1, L->cframe
2407 | li AT, -4
2408 | ld BASE, L->base
2409 | and sp, TMP1, AT
2410 | ld PC, SAVE_PC // Get SAVE_PC.
2411 | b >1
2412 |. sd L, SAVE_L // Set SAVE_L (on-trace resume/yield).
2413 |.endif
2414 |->vm_exit_interp:
2415 |.if JIT
2416 | // CRET1 = MULTRES or negated error code, BASE, PC and JGL set.
2417 | ld L, SAVE_L
2418 | daddiu DISPATCH, JGL, -GG_DISP2G-32768
2419 | sd BASE, L->base
2420 |1:
2421 | bltz CRET1, >9 // Check for error from exit.
2422 |. ld LFUNC:RB, FRAME_FUNC(BASE)
2423 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
2424 | dsll MULTRES, CRET1, 3
2425 | cleartp LFUNC:RB
2426 | sd MULTRES, SAVE_MULTRES
2427 | li TISNIL, LJ_TNIL
2428 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
2429 | .FPU mtc1 TMP3, TOBIT
2430 | ld TMP1, LFUNC:RB->pc
2431 | sd r0, DISPATCH_GL(jit_base)(DISPATCH)
2432 | ld KBASE, PC2PROTO(k)(TMP1)
2433 | .FPU cvt.d.s TOBIT, TOBIT
2434 | // Modified copy of ins_next which handles function header dispatch, too.
2435 | lw INS, 0(PC)
2436 | daddiu PC, PC, 4
2437 | // Assumes TISNIL == ~LJ_VMST_INTERP == -1
2438 | sw TISNIL, DISPATCH_GL(vmstate)(DISPATCH)
2439 | decode_OP8a TMP1, INS
2440 | decode_OP8b TMP1
2441 | sltiu TMP2, TMP1, BC_FUNCF*8
2442 | daddu TMP0, DISPATCH, TMP1
2443 | decode_RD8a RD, INS
2444 | ld AT, 0(TMP0)
2445 | decode_RA8a RA, INS
2446 | beqz TMP2, >2
2447 |. decode_RA8b RA
2448 | jr AT
2449 |. decode_RD8b RD
2450 |2:
2451 | sltiu TMP2, TMP1, (BC_FUNCC+2)*8 // Fast function?
2452 | bnez TMP2, >3
2453 |. ld TMP1, FRAME_PC(BASE)
2454 | // Check frame below fast function.
2455 | andi TMP0, TMP1, FRAME_TYPE
2456 | bnez TMP0, >3 // Trace stitching continuation?
2457 |. nop
2458 | // Otherwise set KBASE for Lua function below fast function.
2459 | lw TMP2, -4(TMP1)
2460 | decode_RA8a TMP0, TMP2
2461 | decode_RA8b TMP0
2462 | dsubu TMP1, BASE, TMP0
2463 | ld LFUNC:TMP2, -32(TMP1)
2464 | cleartp LFUNC:TMP2
2465 | ld TMP1, LFUNC:TMP2->pc
2466 | ld KBASE, PC2PROTO(k)(TMP1)
2467 |3:
2468 | daddiu RC, MULTRES, -8
2469 | jr AT
2470 |. daddu RA, RA, BASE
2471 |
2472 |9: // Rethrow error from the right C frame.
2473 | load_got lj_err_throw
2474 | negu CARG2, CRET1
2475 | call_intern lj_err_throw // (lua_State *L, int errcode)
2476 |. move CARG1, L
2477 |.endif
2478 |
2479 |//-----------------------------------------------------------------------
2480 |//-- Math helper functions ----------------------------------------------
2481 |//-----------------------------------------------------------------------
2482 |
2483 |// Hard-float round to integer.
2484 |// Modifies AT, TMP0, FRET1, FRET2, f4. Keeps all others incl. FARG1.
2485 |.macro vm_round_hf, func
2486 | lui TMP0, 0x4330 // Hiword of 2^52 (double).
2487 | dsll TMP0, TMP0, 32
2488 | dmtc1 TMP0, f4
2489 | abs.d FRET2, FARG1 // |x|
2490 | dmfc1 AT, FARG1
2491 | c.olt.d 0, FRET2, f4
2492 | add.d FRET1, FRET2, f4 // (|x| + 2^52) - 2^52
2493 | bc1f 0, >1 // Truncate only if |x| < 2^52.
2494 |. sub.d FRET1, FRET1, f4
2495 | slt AT, AT, r0
2496 |.if "func" == "ceil"
2497 | lui TMP0, 0xbff0 // Hiword of -1 (double). Preserves -0.
2498 |.else
2499 | lui TMP0, 0x3ff0 // Hiword of +1 (double).
2500 |.endif
2501 |.if "func" == "trunc"
2502 | dsll TMP0, TMP0, 32
2503 | dmtc1 TMP0, f4
2504 | c.olt.d 0, FRET2, FRET1 // |x| < result?
2505 | sub.d FRET2, FRET1, f4
2506 | movt.d FRET1, FRET2, 0 // If yes, subtract +1.
2507 | neg.d FRET2, FRET1
2508 | jr ra
2509 |. movn.d FRET1, FRET2, AT // Merge sign bit back in.
2510 |.else
2511 | neg.d FRET2, FRET1
2512 | dsll TMP0, TMP0, 32
2513 | dmtc1 TMP0, f4
2514 | movn.d FRET1, FRET2, AT // Merge sign bit back in.
2515 |.if "func" == "ceil"
2516 | c.olt.d 0, FRET1, FARG1 // x > result?
2517 |.else
2518 | c.olt.d 0, FARG1, FRET1 // x < result?
2519 |.endif
2520 | sub.d FRET2, FRET1, f4 // If yes, subtract +-1.
2521 | jr ra
2522 |. movt.d FRET1, FRET2, 0
2523 |.endif
2524 |1:
2525 | jr ra
2526 |. mov.d FRET1, FARG1
2527 |.endmacro
2528 |
2529 |.macro vm_round, func
2530 |.if FPU
2531 | vm_round_hf, func
2532 |.endif
2533 |.endmacro
2534 |
2535 |->vm_floor:
2536 | vm_round floor
2537 |->vm_ceil:
2538 | vm_round ceil
2539 |->vm_trunc:
2540 |.if JIT
2541 | vm_round trunc
2542 |.endif
2543 |
2544 |// Soft-float integer to number conversion.
2545 |.macro sfi2d, ARG
2546 |.if not FPU
2547 | beqz ARG, >9 // Handle zero first.
2548 |. sra TMP0, ARG, 31
2549 | xor TMP1, ARG, TMP0
2550 | dsubu TMP1, TMP1, TMP0 // Absolute value in TMP1.
2551 | dclz ARG, TMP1
2552 | addiu ARG, ARG, -11
2553 | li AT, 0x3ff+63-11-1
2554 | dsllv TMP1, TMP1, ARG // Align mantissa left with leading 1.
2555 | subu ARG, AT, ARG // Exponent - 1.
2556 | ins ARG, TMP0, 11, 11 // Sign | Exponent.
2557 | dsll ARG, ARG, 52 // Align left.
2558 | jr ra
2559 |. daddu ARG, ARG, TMP1 // Add mantissa, increment exponent.
2560 |9:
2561 | jr ra
2562 |. nop
2563 |.endif
2564 |.endmacro
2565 |
2566 |// Input CARG1. Output: CARG1. Temporaries: AT, TMP0, TMP1.
2567 |->vm_sfi2d_1:
2568 | sfi2d CARG1
2569 |
2570 |// Input CARG2. Output: CARG2. Temporaries: AT, TMP0, TMP1.
2571 |->vm_sfi2d_2:
2572 | sfi2d CARG2
2573 |
2574 |// Soft-float comparison. Equivalent to c.eq.d.
2575 |// Input: CARG*. Output: CRET1. Temporaries: AT, TMP0, TMP1.
2576 |->vm_sfcmpeq:
2577 |.if not FPU
2578 | dsll AT, CARG1, 1
2579 | dsll TMP0, CARG2, 1
2580 | or TMP1, AT, TMP0
2581 | beqz TMP1, >8 // Both args +-0: return 1.
2582 |. lui TMP1, 0xffe0
2583 | dsll TMP1, TMP1, 32
2584 | sltu AT, TMP1, AT
2585 | sltu TMP0, TMP1, TMP0
2586 | or TMP1, AT, TMP0
2587 | bnez TMP1, >9 // Either arg is NaN: return 0;
2588 |. xor AT, CARG1, CARG2
2589 | jr ra
2590 |. sltiu CRET1, AT, 1 // Same values: return 1.
2591 |8:
2592 | jr ra
2593 |. li CRET1, 1
2594 |9:
2595 | jr ra
2596 |. li CRET1, 0
2597 |.endif
2598 |
2599 |// Soft-float comparison. Equivalent to c.ult.d and c.olt.d.
2600 |// Input: CARG1, CARG2. Output: CRET1. Temporaries: AT, TMP0, TMP1, CRET2.
2601 |->vm_sfcmpult:
2602 |.if not FPU
2603 | b >1
2604 |. li CRET2, 1
2605 |.endif
2606 |
2607 |->vm_sfcmpolt:
2608 |.if not FPU
2609 | li CRET2, 0
2610 |1:
2611 | dsll AT, CARG1, 1
2612 | dsll TMP0, CARG2, 1
2613 | or TMP1, AT, TMP0
2614 | beqz TMP1, >8 // Both args +-0: return 0.
2615 |. lui TMP1, 0xffe0
2616 | dsll TMP1, TMP1, 32
2617 | sltu AT, TMP1, AT
2618 | sltu TMP0, TMP1, TMP0
2619 | or TMP1, AT, TMP0
2620 | bnez TMP1, >9 // Either arg is NaN: return 0 or 1;
2621 |. and AT, CARG1, CARG2
2622 | bltz AT, >5 // Both args negative?
2623 |. nop
2624 | jr ra
2625 |. slt CRET1, CARG1, CARG2
2626 |5: // Swap conditions if both operands are negative.
2627 | jr ra
2628 |. slt CRET1, CARG2, CARG1
2629 |8:
2630 | jr ra
2631 |. nop
2632 |9:
2633 | jr ra
2634 |. move CRET1, CRET2
2635 |.endif
2636 |
2637 |// Soft-float comparison. Equivalent to c.ole.d a, b or c.ole.d b, a.
2638 |// Input: CARG1, CARG2, TMP3. Output: CRET1. Temporaries: AT, TMP0, TMP1.
2639 |->vm_sfcmpolex:
2640 |.if not FPU
2641 | dsll AT, CARG1, 1
2642 | dsll TMP0, CARG2, 1
2643 | or TMP1, AT, TMP0
2644 | beqz TMP1, >8 // Both args +-0: return 1.
2645 |. lui TMP1, 0xffe0
2646 | dsll TMP1, TMP1, 32
2647 | sltu AT, TMP1, AT
2648 | sltu TMP0, TMP1, TMP0
2649 | or TMP1, AT, TMP0
2650 | bnez TMP1, >9 // Either arg is NaN: return 0;
2651 |. and AT, CARG1, CARG2
2652 | xor AT, AT, TMP3
2653 | bltz AT, >5 // Both args negative?
2654 |. nop
2655 | jr ra
2656 |. slt CRET1, CARG2, CARG1
2657 |5: // Swap conditions if both operands are negative.
2658 | jr ra
2659 |. slt CRET1, CARG1, CARG2
2660 |8:
2661 | jr ra
2662 |. li CRET1, 1
2663 |9:
2664 | jr ra
2665 |. li CRET1, 0
2666 |.endif
2667 |
2668 |//-----------------------------------------------------------------------
2669 |//-- Miscellaneous functions --------------------------------------------
2670 |//-----------------------------------------------------------------------
2671 |
2672 |//-----------------------------------------------------------------------
2673 |//-- FFI helper functions -----------------------------------------------
2674 |//-----------------------------------------------------------------------
2675 |
2676 |// Handler for callback functions. Callback slot number in r1, g in r2.
2677 |->vm_ffi_callback:
2678 |.if FFI
2679 |.type CTSTATE, CTState, PC
2680 | saveregs
2681 | ld CTSTATE, GL:r2->ctype_state
2682 | daddiu DISPATCH, r2, GG_G2DISP
2683 | load_got lj_ccallback_enter
2684 | sw r1, CTSTATE->cb.slot
2685 | sd CARG1, CTSTATE->cb.gpr[0]
2686 | .FPU sdc1 FARG1, CTSTATE->cb.fpr[0]
2687 | sd CARG2, CTSTATE->cb.gpr[1]
2688 | .FPU sdc1 FARG2, CTSTATE->cb.fpr[1]
2689 | sd CARG3, CTSTATE->cb.gpr[2]
2690 | .FPU sdc1 FARG3, CTSTATE->cb.fpr[2]
2691 | sd CARG4, CTSTATE->cb.gpr[3]
2692 | .FPU sdc1 FARG4, CTSTATE->cb.fpr[3]
2693 | sd CARG5, CTSTATE->cb.gpr[4]
2694 | .FPU sdc1 FARG5, CTSTATE->cb.fpr[4]
2695 | sd CARG6, CTSTATE->cb.gpr[5]
2696 | .FPU sdc1 FARG6, CTSTATE->cb.fpr[5]
2697 | sd CARG7, CTSTATE->cb.gpr[6]
2698 | .FPU sdc1 FARG7, CTSTATE->cb.fpr[6]
2699 | sd CARG8, CTSTATE->cb.gpr[7]
2700 | .FPU sdc1 FARG8, CTSTATE->cb.fpr[7]
2701 | daddiu TMP0, sp, CFRAME_SPACE
2702 | sd TMP0, CTSTATE->cb.stack
2703 | sd r0, SAVE_PC // Any value outside of bytecode is ok.
2704 | move CARG2, sp
2705 | call_intern lj_ccallback_enter // (CTState *cts, void *cf)
2706 |. move CARG1, CTSTATE
2707 | // Returns lua_State *.
2708 | ld BASE, L:CRET1->base
2709 | ld RC, L:CRET1->top
2710 | move L, CRET1
2711 | .FPU lui TMP3, 0x59c0 // TOBIT = 2^52 + 2^51 (float).
2712 | ld LFUNC:RB, FRAME_FUNC(BASE)
2713 | .FPU mtc1 TMP3, TOBIT
2714 | li TISNIL, LJ_TNIL
2715 | li TISNUM, LJ_TISNUM
2716 | li_vmstate INTERP
2717 | subu RC, RC, BASE
2718 | cleartp LFUNC:RB
2719 | st_vmstate
2720 | .FPU cvt.d.s TOBIT, TOBIT
2721 | ins_callt
2722 |.endif
2723 |
2724 |->cont_ffi_callback: // Return from FFI callback.
2725 |.if FFI
2726 | load_got lj_ccallback_leave
2727 | ld CTSTATE, DISPATCH_GL(ctype_state)(DISPATCH)
2728 | sd BASE, L->base
2729 | sd RB, L->top
2730 | sd L, CTSTATE->L
2731 | move CARG2, RA
2732 | call_intern lj_ccallback_leave // (CTState *cts, TValue *o)
2733 |. move CARG1, CTSTATE
2734 | .FPU ldc1 FRET1, CTSTATE->cb.fpr[0]
2735 | ld CRET1, CTSTATE->cb.gpr[0]
2736 | .FPU ldc1 FRET2, CTSTATE->cb.fpr[1]
2737 | b ->vm_leave_unw
2738 |. ld CRET2, CTSTATE->cb.gpr[1]
2739 |.endif
2740 |
2741 |->vm_ffi_call: // Call C function via FFI.
2742 | // Caveat: needs special frame unwinding, see below.
2743 |.if FFI
2744 | .type CCSTATE, CCallState, CARG1
2745 | lw TMP1, CCSTATE->spadj
2746 | lbu CARG2, CCSTATE->nsp
2747 | move TMP2, sp
2748 | dsubu sp, sp, TMP1
2749 | sd ra, -8(TMP2)
2750 | sll CARG2, CARG2, 3
2751 | sd r16, -16(TMP2)
2752 | sd CCSTATE, -24(TMP2)
2753 | move r16, TMP2
2754 | daddiu TMP1, CCSTATE, offsetof(CCallState, stack)
2755 | move TMP2, sp
2756 | beqz CARG2, >2
2757 |. daddu TMP3, TMP1, CARG2
2758 |1:
2759 | ld TMP0, 0(TMP1)
2760 | daddiu TMP1, TMP1, 8
2761 | sltu AT, TMP1, TMP3
2762 | sd TMP0, 0(TMP2)
2763 | bnez AT, <1
2764 |. daddiu TMP2, TMP2, 8
2765 |2:
2766 | ld CFUNCADDR, CCSTATE->func
2767 | .FPU ldc1 FARG1, CCSTATE->gpr[0]
2768 | ld CARG2, CCSTATE->gpr[1]
2769 | .FPU ldc1 FARG2, CCSTATE->gpr[1]
2770 | ld CARG3, CCSTATE->gpr[2]
2771 | .FPU ldc1 FARG3, CCSTATE->gpr[2]
2772 | ld CARG4, CCSTATE->gpr[3]
2773 | .FPU ldc1 FARG4, CCSTATE->gpr[3]
2774 | ld CARG5, CCSTATE->gpr[4]
2775 | .FPU ldc1 FARG5, CCSTATE->gpr[4]
2776 | ld CARG6, CCSTATE->gpr[5]
2777 | .FPU ldc1 FARG6, CCSTATE->gpr[5]
2778 | ld CARG7, CCSTATE->gpr[6]
2779 | .FPU ldc1 FARG7, CCSTATE->gpr[6]
2780 | ld CARG8, CCSTATE->gpr[7]
2781 | .FPU ldc1 FARG8, CCSTATE->gpr[7]
2782 | jalr CFUNCADDR
2783 |. ld CARG1, CCSTATE->gpr[0] // Do this last, since CCSTATE is CARG1.
2784 | ld CCSTATE:TMP1, -24(r16)
2785 | ld TMP2, -16(r16)
2786 | ld ra, -8(r16)
2787 | sd CRET1, CCSTATE:TMP1->gpr[0]
2788 | sd CRET2, CCSTATE:TMP1->gpr[1]
2789 |.if FPU
2790 | sdc1 FRET1, CCSTATE:TMP1->fpr[0]
2791 | sdc1 FRET2, CCSTATE:TMP1->fpr[1]
2792 |.else
2793 | sd CARG1, CCSTATE:TMP1->gpr[2] // 2nd FP struct field for soft-float.
2794 |.endif
2795 | move sp, r16
2796 | jr ra
2797 |. move r16, TMP2
2798 |.endif
2799 |// Note: vm_ffi_call must be the last function in this object file!
2800 |
2801 |//-----------------------------------------------------------------------
2802}
2803
2804/* Generate the code for a single instruction. */
2805static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2806{
2807 int vk = 0;
2808 |=>defop:
2809
2810 switch (op) {
2811
2812 /* -- Comparison ops ---------------------------------------------------- */
2813
2814 /* Remember: all ops branch for a true comparison, fall through otherwise. */
2815
2816 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
2817 | // RA = src1*8, RD = src2*8, JMP with RD = target
2818 |.macro bc_comp, FRA, FRD, ARGRA, ARGRD, movop, fmovop, fcomp, sfcomp
2819 | daddu RA, BASE, RA
2820 | daddu RD, BASE, RD
2821 | ld ARGRA, 0(RA)
2822 | ld ARGRD, 0(RD)
2823 | lhu TMP2, OFS_RD(PC)
2824 | gettp CARG3, ARGRA
2825 | gettp CARG4, ARGRD
2826 | bne CARG3, TISNUM, >2
2827 |. daddiu PC, PC, 4
2828 | bne CARG4, TISNUM, >5
2829 |. decode_RD4b TMP2
2830 | sextw ARGRA, ARGRA
2831 | sextw ARGRD, ARGRD
2832 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2833 | slt AT, CARG1, CARG2
2834 | addu TMP2, TMP2, TMP3
2835 | movop TMP2, r0, AT
2836 |1:
2837 | daddu PC, PC, TMP2
2838 | ins_next
2839 |
2840 |2: // RA is not an integer.
2841 | sltiu AT, CARG3, LJ_TISNUM
2842 | beqz AT, ->vmeta_comp
2843 |. lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2844 | sltiu AT, CARG4, LJ_TISNUM
2845 | beqz AT, >4
2846 |. decode_RD4b TMP2
2847 |.if FPU
2848 | ldc1 FRA, 0(RA)
2849 | ldc1 FRD, 0(RD)
2850 |.endif
2851 |3: // RA and RD are both numbers.
2852 |.if FPU
2853 | fcomp f20, f22
2854 | addu TMP2, TMP2, TMP3
2855 | b <1
2856 |. fmovop TMP2, r0
2857 |.else
2858 | bal sfcomp
2859 |. addu TMP2, TMP2, TMP3
2860 | b <1
2861 |. movop TMP2, r0, CRET1
2862 |.endif
2863 |
2864 |4: // RA is a number, RD is not a number.
2865 | bne CARG4, TISNUM, ->vmeta_comp
2866 | // RA is a number, RD is an integer. Convert RD to a number.
2867 |.if FPU
2868 |. lwc1 FRD, LO(RD)
2869 | ldc1 FRA, 0(RA)
2870 | b <3
2871 |. cvt.d.w FRD, FRD
2872 |.else
2873 |.if "ARGRD" == "CARG1"
2874 |. sextw CARG1, CARG1
2875 | bal ->vm_sfi2d_1
2876 |. nop
2877 |.else
2878 |. sextw CARG2, CARG2
2879 | bal ->vm_sfi2d_2
2880 |. nop
2881 |.endif
2882 | b <3
2883 |. nop
2884 |.endif
2885 |
2886 |5: // RA is an integer, RD is not an integer
2887 | sltiu AT, CARG4, LJ_TISNUM
2888 | beqz AT, ->vmeta_comp
2889 |. lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2890 | // RA is an integer, RD is a number. Convert RA to a number.
2891 |.if FPU
2892 | lwc1 FRA, LO(RA)
2893 | ldc1 FRD, 0(RD)
2894 | b <3
2895 | cvt.d.w FRA, FRA
2896 |.else
2897 |.if "ARGRA" == "CARG1"
2898 | bal ->vm_sfi2d_1
2899 |. sextw CARG1, CARG1
2900 |.else
2901 | bal ->vm_sfi2d_2
2902 |. sextw CARG2, CARG2
2903 |.endif
2904 | b <3
2905 |. nop
2906 |.endif
2907 |.endmacro
2908 |
2909 if (op == BC_ISLT) {
2910 | bc_comp f20, f22, CARG1, CARG2, movz, movf, c.olt.d, ->vm_sfcmpolt
2911 } else if (op == BC_ISGE) {
2912 | bc_comp f20, f22, CARG1, CARG2, movn, movt, c.olt.d, ->vm_sfcmpolt
2913 } else if (op == BC_ISLE) {
2914 | bc_comp f22, f20, CARG2, CARG1, movn, movt, c.ult.d, ->vm_sfcmpult
2915 } else {
2916 | bc_comp f22, f20, CARG2, CARG1, movz, movf, c.ult.d, ->vm_sfcmpult
2917 }
2918 break;
2919
2920 case BC_ISEQV: case BC_ISNEV:
2921 vk = op == BC_ISEQV;
2922 | // RA = src1*8, RD = src2*8, JMP with RD = target
2923 | daddu RA, BASE, RA
2924 | daddiu PC, PC, 4
2925 | daddu RD, BASE, RD
2926 | ld CARG1, 0(RA)
2927 | lhu TMP2, -4+OFS_RD(PC)
2928 | ld CARG2, 0(RD)
2929 | gettp CARG3, CARG1
2930 | gettp CARG4, CARG2
2931 | sltu AT, TISNUM, CARG3
2932 | sltu TMP1, TISNUM, CARG4
2933 | or AT, AT, TMP1
2934 if (vk) {
2935 | beqz AT, ->BC_ISEQN_Z
2936 } else {
2937 | beqz AT, ->BC_ISNEN_Z
2938 }
2939 | // Either or both types are not numbers.
2940 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
2941 |.if FFI
2942 |. li AT, LJ_TCDATA
2943 | beq CARG3, AT, ->vmeta_equal_cd
2944 |.endif
2945 | decode_RD4b TMP2
2946 |.if FFI
2947 | beq CARG4, AT, ->vmeta_equal_cd
2948 |. nop
2949 |.endif
2950 | bne CARG1, CARG2, >2
2951 |. addu TMP2, TMP2, TMP3
2952 | // Tag and value are equal.
2953 if (vk) {
2954 |->BC_ISEQV_Z:
2955 | daddu PC, PC, TMP2
2956 }
2957 |1:
2958 | ins_next
2959 |
2960 |2: // Check if the tags are the same and it's a table or userdata.
2961 | xor AT, CARG3, CARG4 // Same type?
2962 | sltiu TMP0, CARG3, LJ_TISTABUD+1 // Table or userdata?
2963 | movn TMP0, r0, AT
2964 if (vk) {
2965 | beqz TMP0, <1
2966 } else {
2967 | beqz TMP0, ->BC_ISEQV_Z // Reuse code from opposite instruction.
2968 }
2969 | // Different tables or userdatas. Need to check __eq metamethod.
2970 | // Field metatable must be at same offset for GCtab and GCudata!
2971 |. cleartp TAB:TMP1, CARG1
2972 | ld TAB:TMP3, TAB:TMP1->metatable
2973 if (vk) {
2974 | beqz TAB:TMP3, <1 // No metatable?
2975 |. nop
2976 | lbu TMP3, TAB:TMP3->nomm
2977 | andi TMP3, TMP3, 1<<MM_eq
2978 | bnez TMP3, >1 // Or 'no __eq' flag set?
2979 } else {
2980 | beqz TAB:TMP3,->BC_ISEQV_Z // No metatable?
2981 |. nop
2982 | lbu TMP3, TAB:TMP3->nomm
2983 | andi TMP3, TMP3, 1<<MM_eq
2984 | bnez TMP3, ->BC_ISEQV_Z // Or 'no __eq' flag set?
2985 }
2986 |. nop
2987 | b ->vmeta_equal // Handle __eq metamethod.
2988 |. li TMP0, 1-vk // ne = 0 or 1.
2989 break;
2990
2991 case BC_ISEQS: case BC_ISNES:
2992 vk = op == BC_ISEQS;
2993 | // RA = src*8, RD = str_const*8 (~), JMP with RD = target
2994 | daddu RA, BASE, RA
2995 | daddiu PC, PC, 4
2996 | ld CARG1, 0(RA)
2997 | dsubu RD, KBASE, RD
2998 | lhu TMP2, -4+OFS_RD(PC)
2999 | ld CARG2, -8(RD) // KBASE-8-str_const*8
3000 |.if FFI
3001 | gettp TMP0, CARG1
3002 | li AT, LJ_TCDATA
3003 |.endif
3004 | li TMP1, LJ_TSTR
3005 | decode_RD4b TMP2
3006 |.if FFI
3007 | beq TMP0, AT, ->vmeta_equal_cd
3008 |.endif
3009 |. settp CARG2, TMP1
3010 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3011 | xor TMP1, CARG1, CARG2
3012 | addu TMP2, TMP2, TMP3
3013 if (vk) {
3014 | movn TMP2, r0, TMP1
3015 } else {
3016 | movz TMP2, r0, TMP1
3017 }
3018 | daddu PC, PC, TMP2
3019 | ins_next
3020 break;
3021
3022 case BC_ISEQN: case BC_ISNEN:
3023 vk = op == BC_ISEQN;
3024 | // RA = src*8, RD = num_const*8, JMP with RD = target
3025 | daddu RA, BASE, RA
3026 | daddu RD, KBASE, RD
3027 | ld CARG1, 0(RA)
3028 | ld CARG2, 0(RD)
3029 | lhu TMP2, OFS_RD(PC)
3030 | gettp CARG3, CARG1
3031 | gettp CARG4, CARG2
3032 | daddiu PC, PC, 4
3033 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3034 if (vk) {
3035 |->BC_ISEQN_Z:
3036 } else {
3037 |->BC_ISNEN_Z:
3038 }
3039 | bne CARG3, TISNUM, >3
3040 |. decode_RD4b TMP2
3041 | bne CARG4, TISNUM, >6
3042 |. addu TMP2, TMP2, TMP3
3043 | xor AT, CARG1, CARG2
3044 if (vk) {
3045 | movn TMP2, r0, AT
3046 |1:
3047 | daddu PC, PC, TMP2
3048 |2:
3049 } else {
3050 | movz TMP2, r0, AT
3051 |1:
3052 |2:
3053 | daddu PC, PC, TMP2
3054 }
3055 | ins_next
3056 |
3057 |3: // RA is not an integer.
3058 | sltu AT, CARG3, TISNUM
3059 |.if FFI
3060 | beqz AT, >8
3061 |.else
3062 | beqz AT, <2
3063 |.endif
3064 |. addu TMP2, TMP2, TMP3
3065 | sltu AT, CARG4, TISNUM
3066 |.if FPU
3067 | ldc1 f20, 0(RA)
3068 | ldc1 f22, 0(RD)
3069 |.endif
3070 | beqz AT, >5
3071 |. nop
3072 |4: // RA and RD are both numbers.
3073 |.if FPU
3074 | c.eq.d f20, f22
3075 | b <1
3076 if (vk) {
3077 |. movf TMP2, r0
3078 } else {
3079 |. movt TMP2, r0
3080 }
3081 |.else
3082 | bal ->vm_sfcmpeq
3083 |. nop
3084 | b <1
3085 if (vk) {
3086 |. movz TMP2, r0, CRET1
3087 } else {
3088 |. movn TMP2, r0, CRET1
3089 }
3090 |.endif
3091 |
3092 |5: // RA is a number, RD is not a number.
3093 |.if FFI
3094 | bne CARG4, TISNUM, >9
3095 |.else
3096 | bne CARG4, TISNUM, <2
3097 |.endif
3098 | // RA is a number, RD is an integer. Convert RD to a number.
3099 |.if FPU
3100 |. lwc1 f22, LO(RD)
3101 | b <4
3102 |. cvt.d.w f22, f22
3103 |.else
3104 |. sextw CARG2, CARG2
3105 | bal ->vm_sfi2d_2
3106 |. nop
3107 | b <4
3108 |. nop
3109 |.endif
3110 |
3111 |6: // RA is an integer, RD is not an integer
3112 | sltu AT, CARG4, TISNUM
3113 |.if FFI
3114 | beqz AT, >9
3115 |.else
3116 | beqz AT, <2
3117 |.endif
3118 | // RA is an integer, RD is a number. Convert RA to a number.
3119 |.if FPU
3120 |. lwc1 f20, LO(RA)
3121 | ldc1 f22, 0(RD)
3122 | b <4
3123 | cvt.d.w f20, f20
3124 |.else
3125 |. sextw CARG1, CARG1
3126 | bal ->vm_sfi2d_1
3127 |. nop
3128 | b <4
3129 |. nop
3130 |.endif
3131 |
3132 |.if FFI
3133 |8:
3134 | li AT, LJ_TCDATA
3135 | bne CARG3, AT, <2
3136 |. nop
3137 | b ->vmeta_equal_cd
3138 |. nop
3139 |9:
3140 | li AT, LJ_TCDATA
3141 | bne CARG4, AT, <2
3142 |. nop
3143 | b ->vmeta_equal_cd
3144 |. nop
3145 |.endif
3146 break;
3147
3148 case BC_ISEQP: case BC_ISNEP:
3149 vk = op == BC_ISEQP;
3150 | // RA = src*8, RD = primitive_type*8 (~), JMP with RD = target
3151 | daddu RA, BASE, RA
3152 | srl TMP1, RD, 3
3153 | ld TMP0, 0(RA)
3154 | lhu TMP2, OFS_RD(PC)
3155 | not TMP1, TMP1
3156 | gettp TMP0, TMP0
3157 | daddiu PC, PC, 4
3158 |.if FFI
3159 | li AT, LJ_TCDATA
3160 | beq TMP0, AT, ->vmeta_equal_cd
3161 |.endif
3162 |. xor TMP0, TMP0, TMP1
3163 | decode_RD4b TMP2
3164 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3165 | addu TMP2, TMP2, TMP3
3166 if (vk) {
3167 | movn TMP2, r0, TMP0
3168 } else {
3169 | movz TMP2, r0, TMP0
3170 }
3171 | daddu PC, PC, TMP2
3172 | ins_next
3173 break;
3174
3175 /* -- Unary test and copy ops ------------------------------------------- */
3176
3177 case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
3178 | // RA = dst*8 or unused, RD = src*8, JMP with RD = target
3179 | daddu RD, BASE, RD
3180 | lhu TMP2, OFS_RD(PC)
3181 | ld TMP0, 0(RD)
3182 | daddiu PC, PC, 4
3183 | gettp TMP0, TMP0
3184 | sltiu TMP0, TMP0, LJ_TISTRUECOND
3185 if (op == BC_IST || op == BC_ISF) {
3186 | decode_RD4b TMP2
3187 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3188 | addu TMP2, TMP2, TMP3
3189 if (op == BC_IST) {
3190 | movz TMP2, r0, TMP0
3191 } else {
3192 | movn TMP2, r0, TMP0
3193 }
3194 | daddu PC, PC, TMP2
3195 } else {
3196 | ld CRET1, 0(RD)
3197 if (op == BC_ISTC) {
3198 | beqz TMP0, >1
3199 } else {
3200 | bnez TMP0, >1
3201 }
3202 |. daddu RA, BASE, RA
3203 | decode_RD4b TMP2
3204 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
3205 | addu TMP2, TMP2, TMP3
3206 | sd CRET1, 0(RA)
3207 | daddu PC, PC, TMP2
3208 |1:
3209 }
3210 | ins_next
3211 break;
3212
3213 case BC_ISTYPE:
3214 | // RA = src*8, RD = -type*8
3215 | daddu TMP2, BASE, RA
3216 | srl TMP1, RD, 3
3217 | ld TMP0, 0(TMP2)
3218 | ins_next1
3219 | gettp TMP0, TMP0
3220 | daddu AT, TMP0, TMP1
3221 | bnez AT, ->vmeta_istype
3222 |. ins_next2
3223 break;
3224 case BC_ISNUM:
3225 | // RA = src*8, RD = -(TISNUM-1)*8
3226 | daddu TMP2, BASE, RA
3227 | ld TMP0, 0(TMP2)
3228 | ins_next1
3229 | checknum TMP0, ->vmeta_istype
3230 |. ins_next2
3231 break;
3232
3233 /* -- Unary ops --------------------------------------------------------- */
3234
3235 case BC_MOV:
3236 | // RA = dst*8, RD = src*8
3237 | daddu RD, BASE, RD
3238 | daddu RA, BASE, RA
3239 | ld CRET1, 0(RD)
3240 | ins_next1
3241 | sd CRET1, 0(RA)
3242 | ins_next2
3243 break;
3244 case BC_NOT:
3245 | // RA = dst*8, RD = src*8
3246 | daddu RD, BASE, RD
3247 | daddu RA, BASE, RA
3248 | ld TMP0, 0(RD)
3249 | li AT, LJ_TTRUE
3250 | gettp TMP0, TMP0
3251 | sltu TMP0, AT, TMP0
3252 | addiu TMP0, TMP0, 1
3253 | dsll TMP0, TMP0, 47
3254 | not TMP0, TMP0
3255 | ins_next1
3256 | sd TMP0, 0(RA)
3257 | ins_next2
3258 break;
3259 case BC_UNM:
3260 | // RA = dst*8, RD = src*8
3261 | daddu RB, BASE, RD
3262 | ld CARG1, 0(RB)
3263 | daddu RA, BASE, RA
3264 | gettp CARG3, CARG1
3265 | bne CARG3, TISNUM, >2
3266 |. lui TMP1, 0x8000
3267 | sextw CARG1, CARG1
3268 | beq CARG1, TMP1, ->vmeta_unm // Meta handler deals with -2^31.
3269 |. negu CARG1, CARG1
3270 | zextw CARG1, CARG1
3271 | settp CARG1, TISNUM
3272 |1:
3273 | ins_next1
3274 | sd CARG1, 0(RA)
3275 | ins_next2
3276 |2:
3277 | sltiu AT, CARG3, LJ_TISNUM
3278 | beqz AT, ->vmeta_unm
3279 |. dsll TMP1, TMP1, 32
3280 | b <1
3281 |. xor CARG1, CARG1, TMP1
3282 break;
3283 case BC_LEN:
3284 | // RA = dst*8, RD = src*8
3285 | daddu CARG2, BASE, RD
3286 | daddu RA, BASE, RA
3287 | ld TMP0, 0(CARG2)
3288 | gettp TMP1, TMP0
3289 | daddiu AT, TMP1, -LJ_TSTR
3290 | bnez AT, >2
3291 |. cleartp STR:CARG1, TMP0
3292 | lw CRET1, STR:CARG1->len
3293 |1:
3294 | settp CRET1, TISNUM
3295 | ins_next1
3296 | sd CRET1, 0(RA)
3297 | ins_next2
3298 |2:
3299 | daddiu AT, TMP1, -LJ_TTAB
3300 | bnez AT, ->vmeta_len
3301 |. nop
3302#if LJ_52
3303 | ld TAB:TMP2, TAB:CARG1->metatable
3304 | bnez TAB:TMP2, >9
3305 |. nop
3306 |3:
3307#endif
3308 |->BC_LEN_Z:
3309 | load_got lj_tab_len
3310 | call_intern lj_tab_len // (GCtab *t)
3311 |. nop
3312 | // Returns uint32_t (but less than 2^31).
3313 | b <1
3314 |. nop
3315#if LJ_52
3316 |9:
3317 | lbu TMP0, TAB:TMP2->nomm
3318 | andi TMP0, TMP0, 1<<MM_len
3319 | bnez TMP0, <3 // 'no __len' flag set: done.
3320 |. nop
3321 | b ->vmeta_len
3322 |. nop
3323#endif
3324 break;
3325
3326 /* -- Binary ops -------------------------------------------------------- */
3327
3328 |.macro fpmod, a, b, c
3329 | bal ->vm_floor // floor(b/c)
3330 |. div.d FARG1, b, c
3331 | mul.d a, FRET1, c
3332 | sub.d a, b, a // b - floor(b/c)*c
3333 |.endmacro
3334
3335 |.macro sfpmod
3336 | daddiu sp, sp, -16
3337 |
3338 | load_got __divdf3
3339 | sd CARG1, 0(sp)
3340 | call_extern
3341 |. sd CARG2, 8(sp)
3342 |
3343 | load_got floor
3344 | call_extern
3345 |. move CARG1, CRET1
3346 |
3347 | load_got __muldf3
3348 | move CARG1, CRET1
3349 | call_extern
3350 |. ld CARG2, 8(sp)
3351 |
3352 | load_got __subdf3
3353 | ld CARG1, 0(sp)
3354 | call_extern
3355 |. move CARG2, CRET1
3356 |
3357 | daddiu sp, sp, 16
3358 |.endmacro
3359
3360 |.macro ins_arithpre, label
3361 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
3362 | // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8
3363 ||switch (vk) {
3364 ||case 0:
3365 | decode_RB8a RB, INS
3366 | decode_RB8b RB
3367 | decode_RDtoRC8 RC, RD
3368 | // RA = dst*8, RB = src1*8, RC = num_const*8
3369 | daddu RB, BASE, RB
3370 |.if "label" ~= "none"
3371 | b label
3372 |.endif
3373 |. daddu RC, KBASE, RC
3374 || break;
3375 ||case 1:
3376 | decode_RB8a RC, INS
3377 | decode_RB8b RC
3378 | decode_RDtoRC8 RB, RD
3379 | // RA = dst*8, RB = num_const*8, RC = src1*8
3380 | daddu RC, BASE, RC
3381 |.if "label" ~= "none"
3382 | b label
3383 |.endif
3384 |. daddu RB, KBASE, RB
3385 || break;
3386 ||default:
3387 | decode_RB8a RB, INS
3388 | decode_RB8b RB
3389 | decode_RDtoRC8 RC, RD
3390 | // RA = dst*8, RB = src1*8, RC = src2*8
3391 | daddu RB, BASE, RB
3392 |.if "label" ~= "none"
3393 | b label
3394 |.endif
3395 |. daddu RC, BASE, RC
3396 || break;
3397 ||}
3398 |.endmacro
3399 |
3400 |.macro ins_arith, intins, fpins, fpcall, label
3401 | ins_arithpre none
3402 |
3403 |.if "label" ~= "none"
3404 |label:
3405 |.endif
3406 |
3407 |// Used in 5.
3408 | ld CARG1, 0(RB)
3409 | ld CARG2, 0(RC)
3410 | gettp TMP0, CARG1
3411 | gettp TMP1, CARG2
3412 |
3413 |.if "intins" ~= "div"
3414 |
3415 | // Check for two integers.
3416 | sextw CARG3, CARG1
3417 | bne TMP0, TISNUM, >5
3418 |. sextw CARG4, CARG2
3419 | bne TMP1, TISNUM, >5
3420 |
3421 |.if "intins" == "addu"
3422 |. intins CRET1, CARG3, CARG4
3423 | xor TMP1, CRET1, CARG3 // ((y^a) & (y^b)) < 0: overflow.
3424 | xor TMP2, CRET1, CARG4
3425 | and TMP1, TMP1, TMP2
3426 | bltz TMP1, ->vmeta_arith
3427 |. daddu RA, BASE, RA
3428 |.elif "intins" == "subu"
3429 |. intins CRET1, CARG3, CARG4
3430 | xor TMP1, CRET1, CARG3 // ((y^a) & (a^b)) < 0: overflow.
3431 | xor TMP2, CARG3, CARG4
3432 | and TMP1, TMP1, TMP2
3433 | bltz TMP1, ->vmeta_arith
3434 |. daddu RA, BASE, RA
3435 |.elif "intins" == "mult"
3436 |. intins CARG3, CARG4
3437 | mflo CRET1
3438 | mfhi TMP2
3439 | sra TMP1, CRET1, 31
3440 | bne TMP1, TMP2, ->vmeta_arith
3441 |. daddu RA, BASE, RA
3442 |.else
3443 |. load_got lj_vm_modi
3444 | beqz CARG4, ->vmeta_arith
3445 |. daddu RA, BASE, RA
3446 | move CARG1, CARG3
3447 | call_extern
3448 |. move CARG2, CARG4
3449 |.endif
3450 |
3451 | zextw CRET1, CRET1
3452 | settp CRET1, TISNUM
3453 | ins_next1
3454 | sd CRET1, 0(RA)
3455 |3:
3456 | ins_next2
3457 |
3458 |.endif
3459 |
3460 |5: // Check for two numbers.
3461 | .FPU ldc1 f20, 0(RB)
3462 | sltu AT, TMP0, TISNUM
3463 | sltu TMP0, TMP1, TISNUM
3464 | .FPU ldc1 f22, 0(RC)
3465 | and AT, AT, TMP0
3466 | beqz AT, ->vmeta_arith
3467 |. daddu RA, BASE, RA
3468 |
3469 |.if FPU
3470 | fpins FRET1, f20, f22
3471 |.elif "fpcall" == "sfpmod"
3472 | sfpmod
3473 |.else
3474 | load_got fpcall
3475 | call_extern
3476 |. nop
3477 |.endif
3478 |
3479 | ins_next1
3480 |.if "intins" ~= "div"
3481 | b <3
3482 |.endif
3483 |.if FPU
3484 |. sdc1 FRET1, 0(RA)
3485 |.else
3486 |. sd CRET1, 0(RA)
3487 |.endif
3488 |.if "intins" == "div"
3489 | ins_next2
3490 |.endif
3491 |
3492 |.endmacro
3493
3494 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
3495 | ins_arith addu, add.d, __adddf3, none
3496 break;
3497 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
3498 | ins_arith subu, sub.d, __subdf3, none
3499 break;
3500 case BC_MULVN: case BC_MULNV: case BC_MULVV:
3501 | ins_arith mult, mul.d, __muldf3, none
3502 break;
3503 case BC_DIVVN:
3504 | ins_arith div, div.d, __divdf3, ->BC_DIVVN_Z
3505 break;
3506 case BC_DIVNV: case BC_DIVVV:
3507 | ins_arithpre ->BC_DIVVN_Z
3508 break;
3509 case BC_MODVN:
3510 | ins_arith modi, fpmod, sfpmod, ->BC_MODVN_Z
3511 break;
3512 case BC_MODNV: case BC_MODVV:
3513 | ins_arithpre ->BC_MODVN_Z
3514 break;
3515 case BC_POW:
3516 | ins_arithpre none
3517 | ld CARG1, 0(RB)
3518 | ld CARG2, 0(RC)
3519 | gettp TMP0, CARG1
3520 | gettp TMP1, CARG2
3521 | sltiu TMP0, TMP0, LJ_TISNUM
3522 | sltiu TMP1, TMP1, LJ_TISNUM
3523 | and AT, TMP0, TMP1
3524 | load_got pow
3525 | beqz AT, ->vmeta_arith
3526 |. daddu RA, BASE, RA
3527 |.if FPU
3528 | ldc1 FARG1, 0(RB)
3529 | ldc1 FARG2, 0(RC)
3530 |.endif
3531 | call_extern
3532 |. nop
3533 | ins_next1
3534 |.if FPU
3535 | sdc1 FRET1, 0(RA)
3536 |.else
3537 | sd CRET1, 0(RA)
3538 |.endif
3539 | ins_next2
3540 break;
3541
3542 case BC_CAT:
3543 | // RA = dst*8, RB = src_start*8, RC = src_end*8
3544 | decode_RB8a RB, INS
3545 | decode_RB8b RB
3546 | decode_RDtoRC8 RC, RD
3547 | dsubu CARG3, RC, RB
3548 | sd BASE, L->base
3549 | daddu CARG2, BASE, RC
3550 | move MULTRES, RB
3551 |->BC_CAT_Z:
3552 | load_got lj_meta_cat
3553 | srl CARG3, CARG3, 3
3554 | sd PC, SAVE_PC
3555 | call_intern lj_meta_cat // (lua_State *L, TValue *top, int left)
3556 |. move CARG1, L
3557 | // Returns NULL (finished) or TValue * (metamethod).
3558 | bnez CRET1, ->vmeta_binop
3559 |. ld BASE, L->base
3560 | daddu RB, BASE, MULTRES
3561 | ld CRET1, 0(RB)
3562 | daddu RA, BASE, RA
3563 | ins_next1
3564 | sd CRET1, 0(RA)
3565 | ins_next2
3566 break;
3567
3568 /* -- Constant ops ------------------------------------------------------ */
3569
3570 case BC_KSTR:
3571 | // RA = dst*8, RD = str_const*8 (~)
3572 | dsubu TMP1, KBASE, RD
3573 | ins_next1
3574 | li TMP2, LJ_TSTR
3575 | ld TMP0, -8(TMP1) // KBASE-8-str_const*8
3576 | daddu RA, BASE, RA
3577 | settp TMP0, TMP2
3578 | sd TMP0, 0(RA)
3579 | ins_next2
3580 break;
3581 case BC_KCDATA:
3582 |.if FFI
3583 | // RA = dst*8, RD = cdata_const*8 (~)
3584 | dsubu TMP1, KBASE, RD
3585 | ins_next1
3586 | ld TMP0, -8(TMP1) // KBASE-8-cdata_const*8
3587 | li TMP2, LJ_TCDATA
3588 | daddu RA, BASE, RA
3589 | settp TMP0, TMP2
3590 | sd TMP0, 0(RA)
3591 | ins_next2
3592 |.endif
3593 break;
3594 case BC_KSHORT:
3595 | // RA = dst*8, RD = int16_literal*8
3596 | sra RD, INS, 16
3597 | daddu RA, BASE, RA
3598 | zextw RD, RD
3599 | ins_next1
3600 | settp RD, TISNUM
3601 | sd RD, 0(RA)
3602 | ins_next2
3603 break;
3604 case BC_KNUM:
3605 | // RA = dst*8, RD = num_const*8
3606 | daddu RD, KBASE, RD
3607 | daddu RA, BASE, RA
3608 | ld CRET1, 0(RD)
3609 | ins_next1
3610 | sd CRET1, 0(RA)
3611 | ins_next2
3612 break;
3613 case BC_KPRI:
3614 | // RA = dst*8, RD = primitive_type*8 (~)
3615 | daddu RA, BASE, RA
3616 | dsll TMP0, RD, 44
3617 | not TMP0, TMP0
3618 | ins_next1
3619 | sd TMP0, 0(RA)
3620 | ins_next2
3621 break;
3622 case BC_KNIL:
3623 | // RA = base*8, RD = end*8
3624 | daddu RA, BASE, RA
3625 | sd TISNIL, 0(RA)
3626 | daddiu RA, RA, 8
3627 | daddu RD, BASE, RD
3628 |1:
3629 | sd TISNIL, 0(RA)
3630 | slt AT, RA, RD
3631 | bnez AT, <1
3632 |. daddiu RA, RA, 8
3633 | ins_next_
3634 break;
3635
3636 /* -- Upvalue and function ops ------------------------------------------ */
3637
3638 case BC_UGET:
3639 | // RA = dst*8, RD = uvnum*8
3640 | ld LFUNC:RB, FRAME_FUNC(BASE)
3641 | daddu RA, BASE, RA
3642 | cleartp LFUNC:RB
3643 | daddu RD, RD, LFUNC:RB
3644 | ld UPVAL:RB, LFUNC:RD->uvptr
3645 | ins_next1
3646 | ld TMP1, UPVAL:RB->v
3647 | ld CRET1, 0(TMP1)
3648 | sd CRET1, 0(RA)
3649 | ins_next2
3650 break;
3651 case BC_USETV:
3652 | // RA = uvnum*8, RD = src*8
3653 | ld LFUNC:RB, FRAME_FUNC(BASE)
3654 | daddu RD, BASE, RD
3655 | cleartp LFUNC:RB
3656 | daddu RA, RA, LFUNC:RB
3657 | ld UPVAL:RB, LFUNC:RA->uvptr
3658 | ld CRET1, 0(RD)
3659 | lbu TMP3, UPVAL:RB->marked
3660 | ld CARG2, UPVAL:RB->v
3661 | andi TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
3662 | lbu TMP0, UPVAL:RB->closed
3663 | gettp TMP2, RD
3664 | sd CRET1, 0(CARG2)
3665 | li AT, LJ_GC_BLACK|1
3666 | or TMP3, TMP3, TMP0
3667 | beq TMP3, AT, >2 // Upvalue is closed and black?
3668 |. daddiu TMP2, TMP2, -(LJ_TNUMX+1)
3669 |1:
3670 | ins_next
3671 |
3672 |2: // Check if new value is collectable.
3673 | sltiu AT, TMP2, LJ_TISGCV - (LJ_TNUMX+1)
3674 | beqz AT, <1 // tvisgcv(v)
3675 |. cleartp GCOBJ:TMP1, RB
3676 | lbu TMP3, GCOBJ:TMP1->gch.marked
3677 | andi TMP3, TMP3, LJ_GC_WHITES // iswhite(v)
3678 | beqz TMP3, <1
3679 |. load_got lj_gc_barrieruv
3680 | // Crossed a write barrier. Move the barrier forward.
3681 | call_intern lj_gc_barrieruv // (global_State *g, TValue *tv)
3682 |. daddiu CARG1, DISPATCH, GG_DISP2G
3683 | b <1
3684 |. nop
3685 break;
3686 case BC_USETS:
3687 | // RA = uvnum*8, RD = str_const*8 (~)
3688 | ld LFUNC:RB, FRAME_FUNC(BASE)
3689 | dsubu TMP1, KBASE, RD
3690 | cleartp LFUNC:RB
3691 | daddu RA, RA, LFUNC:RB
3692 | ld UPVAL:RB, LFUNC:RA->uvptr
3693 | ld STR:TMP1, -8(TMP1) // KBASE-8-str_const*8
3694 | lbu TMP2, UPVAL:RB->marked
3695 | ld CARG2, UPVAL:RB->v
3696 | lbu TMP3, STR:TMP1->marked
3697 | andi AT, TMP2, LJ_GC_BLACK // isblack(uv)
3698 | lbu TMP2, UPVAL:RB->closed
3699 | li TMP0, LJ_TSTR
3700 | settp TMP1, TMP0
3701 | bnez AT, >2
3702 |. sd TMP1, 0(CARG2)
3703 |1:
3704 | ins_next
3705 |
3706 |2: // Check if string is white and ensure upvalue is closed.
3707 | beqz TMP2, <1
3708 |. andi AT, TMP3, LJ_GC_WHITES // iswhite(str)
3709 | beqz AT, <1
3710 |. load_got lj_gc_barrieruv
3711 | // Crossed a write barrier. Move the barrier forward.
3712 | call_intern lj_gc_barrieruv // (global_State *g, TValue *tv)
3713 |. daddiu CARG1, DISPATCH, GG_DISP2G
3714 | b <1
3715 |. nop
3716 break;
3717 case BC_USETN:
3718 | // RA = uvnum*8, RD = num_const*8
3719 | ld LFUNC:RB, FRAME_FUNC(BASE)
3720 | daddu RD, KBASE, RD
3721 | cleartp LFUNC:RB
3722 | daddu RA, RA, LFUNC:RB
3723 | ld UPVAL:RB, LFUNC:RA->uvptr
3724 | ld CRET1, 0(RD)
3725 | ld TMP1, UPVAL:RB->v
3726 | ins_next1
3727 | sd CRET1, 0(TMP1)
3728 | ins_next2
3729 break;
3730 case BC_USETP:
3731 | // RA = uvnum*8, RD = primitive_type*8 (~)
3732 | ld LFUNC:RB, FRAME_FUNC(BASE)
3733 | dsll TMP0, RD, 44
3734 | cleartp LFUNC:RB
3735 | daddu RA, RA, LFUNC:RB
3736 | not TMP0, TMP0
3737 | ld UPVAL:RB, LFUNC:RA->uvptr
3738 | ins_next1
3739 | ld TMP1, UPVAL:RB->v
3740 | sd TMP0, 0(TMP1)
3741 | ins_next2
3742 break;
3743
3744 case BC_UCLO:
3745 | // RA = level*8, RD = target
3746 | ld TMP2, L->openupval
3747 | branch_RD // Do this first since RD is not saved.
3748 | load_got lj_func_closeuv
3749 | sd BASE, L->base
3750 | beqz TMP2, >1
3751 |. move CARG1, L
3752 | call_intern lj_func_closeuv // (lua_State *L, TValue *level)
3753 |. daddu CARG2, BASE, RA
3754 | ld BASE, L->base
3755 |1:
3756 | ins_next
3757 break;
3758
3759 case BC_FNEW:
3760 | // RA = dst*8, RD = proto_const*8 (~) (holding function prototype)
3761 | load_got lj_func_newL_gc
3762 | dsubu TMP1, KBASE, RD
3763 | ld CARG3, FRAME_FUNC(BASE)
3764 | ld CARG2, -8(TMP1) // KBASE-8-tab_const*8
3765 | sd BASE, L->base
3766 | sd PC, SAVE_PC
3767 | cleartp CARG3
3768 | // (lua_State *L, GCproto *pt, GCfuncL *parent)
3769 | call_intern lj_func_newL_gc
3770 |. move CARG1, L
3771 | // Returns GCfuncL *.
3772 | li TMP0, LJ_TFUNC
3773 | ld BASE, L->base
3774 | ins_next1
3775 | settp CRET1, TMP0
3776 | daddu RA, BASE, RA
3777 | sd CRET1, 0(RA)
3778 | ins_next2
3779 break;
3780
3781 /* -- Table ops --------------------------------------------------------- */
3782
3783 case BC_TNEW:
3784 case BC_TDUP:
3785 | // RA = dst*8, RD = (hbits|asize)*8 | tab_const*8 (~)
3786 | ld TMP0, DISPATCH_GL(gc.total)(DISPATCH)
3787 | ld TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
3788 | sd BASE, L->base
3789 | sd PC, SAVE_PC
3790 | sltu AT, TMP0, TMP1
3791 | beqz AT, >5
3792 |1:
3793 if (op == BC_TNEW) {
3794 | load_got lj_tab_new
3795 | srl CARG2, RD, 3
3796 | andi CARG2, CARG2, 0x7ff
3797 | li TMP0, 0x801
3798 | addiu AT, CARG2, -0x7ff
3799 | srl CARG3, RD, 14
3800 | movz CARG2, TMP0, AT
3801 | // (lua_State *L, int32_t asize, uint32_t hbits)
3802 | call_intern lj_tab_new
3803 |. move CARG1, L
3804 | // Returns Table *.
3805 } else {
3806 | load_got lj_tab_dup
3807 | dsubu TMP1, KBASE, RD
3808 | move CARG1, L
3809 | call_intern lj_tab_dup // (lua_State *L, Table *kt)
3810 |. ld CARG2, -8(TMP1) // KBASE-8-str_const*8
3811 | // Returns Table *.
3812 }
3813 | li TMP0, LJ_TTAB
3814 | ld BASE, L->base
3815 | ins_next1
3816 | daddu RA, BASE, RA
3817 | settp CRET1, TMP0
3818 | sd CRET1, 0(RA)
3819 | ins_next2
3820 |5:
3821 | load_got lj_gc_step_fixtop
3822 | move MULTRES, RD
3823 | call_intern lj_gc_step_fixtop // (lua_State *L)
3824 |. move CARG1, L
3825 | b <1
3826 |. move RD, MULTRES
3827 break;
3828
3829 case BC_GGET:
3830 | // RA = dst*8, RD = str_const*8 (~)
3831 case BC_GSET:
3832 | // RA = src*8, RD = str_const*8 (~)
3833 | ld LFUNC:TMP2, FRAME_FUNC(BASE)
3834 | dsubu TMP1, KBASE, RD
3835 | ld STR:RC, -8(TMP1) // KBASE-8-str_const*8
3836 | cleartp LFUNC:TMP2
3837 | ld TAB:RB, LFUNC:TMP2->env
3838 if (op == BC_GGET) {
3839 | b ->BC_TGETS_Z
3840 } else {
3841 | b ->BC_TSETS_Z
3842 }
3843 |. daddu RA, BASE, RA
3844 break;
3845
3846 case BC_TGETV:
3847 | // RA = dst*8, RB = table*8, RC = key*8
3848 | decode_RB8a RB, INS
3849 | decode_RB8b RB
3850 | decode_RDtoRC8 RC, RD
3851 | daddu CARG2, BASE, RB
3852 | daddu CARG3, BASE, RC
3853 | ld TAB:RB, 0(CARG2)
3854 | ld TMP2, 0(CARG3)
3855 | daddu RA, BASE, RA
3856 | checktab TAB:RB, ->vmeta_tgetv
3857 | gettp TMP3, TMP2
3858 | bne TMP3, TISNUM, >5 // Integer key?
3859 |. lw TMP0, TAB:RB->asize
3860 | sextw TMP2, TMP2
3861 | ld TMP1, TAB:RB->array
3862 | sltu AT, TMP2, TMP0
3863 | sll TMP2, TMP2, 3
3864 | beqz AT, ->vmeta_tgetv // Integer key and in array part?
3865 |. daddu TMP2, TMP1, TMP2
3866 | ld AT, 0(TMP2)
3867 | beq AT, TISNIL, >2
3868 |. ld CRET1, 0(TMP2)
3869 |1:
3870 | ins_next1
3871 | sd CRET1, 0(RA)
3872 | ins_next2
3873 |
3874 |2: // Check for __index if table value is nil.
3875 | ld TAB:TMP2, TAB:RB->metatable
3876 | beqz TAB:TMP2, <1 // No metatable: done.
3877 |. nop
3878 | lbu TMP0, TAB:TMP2->nomm
3879 | andi TMP0, TMP0, 1<<MM_index
3880 | bnez TMP0, <1 // 'no __index' flag set: done.
3881 |. nop
3882 | b ->vmeta_tgetv
3883 |. nop
3884 |
3885 |5:
3886 | li AT, LJ_TSTR
3887 | bne TMP3, AT, ->vmeta_tgetv
3888 |. cleartp RC, TMP2
3889 | b ->BC_TGETS_Z // String key?
3890 |. nop
3891 break;
3892 case BC_TGETS:
3893 | // RA = dst*8, RB = table*8, RC = str_const*8 (~)
3894 | decode_RB8a RB, INS
3895 | decode_RB8b RB
3896 | decode_RC8a RC, INS
3897 | daddu CARG2, BASE, RB
3898 | decode_RC8b RC
3899 | ld TAB:RB, 0(CARG2)
3900 | dsubu CARG3, KBASE, RC
3901 | daddu RA, BASE, RA
3902 | ld STR:RC, -8(CARG3) // KBASE-8-str_const*8
3903 | checktab TAB:RB, ->vmeta_tgets1
3904 |->BC_TGETS_Z:
3905 | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = dst*8
3906 | lw TMP0, TAB:RB->hmask
3907 | lw TMP1, STR:RC->hash
3908 | ld NODE:TMP2, TAB:RB->node
3909 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
3910 | sll TMP0, TMP1, 5
3911 | sll TMP1, TMP1, 3
3912 | subu TMP1, TMP0, TMP1
3913 | li TMP3, LJ_TSTR
3914 | daddu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
3915 | settp STR:RC, TMP3 // Tagged key to look for.
3916 |1:
3917 | ld CARG1, NODE:TMP2->key
3918 | ld CRET1, NODE:TMP2->val
3919 | ld NODE:TMP1, NODE:TMP2->next
3920 | bne CARG1, RC, >4
3921 |. ld TAB:TMP3, TAB:RB->metatable
3922 | beq CRET1, TISNIL, >5 // Key found, but nil value?
3923 |. nop
3924 |3:
3925 | ins_next1
3926 | sd CRET1, 0(RA)
3927 | ins_next2
3928 |
3929 |4: // Follow hash chain.
3930 | bnez NODE:TMP1, <1
3931 |. move NODE:TMP2, NODE:TMP1
3932 | // End of hash chain: key not found, nil result.
3933 |
3934 |5: // Check for __index if table value is nil.
3935 | beqz TAB:TMP3, <3 // No metatable: done.
3936 |. move CRET1, TISNIL
3937 | lbu TMP0, TAB:TMP3->nomm
3938 | andi TMP0, TMP0, 1<<MM_index
3939 | bnez TMP0, <3 // 'no __index' flag set: done.
3940 |. nop
3941 | b ->vmeta_tgets
3942 |. nop
3943 break;
3944 case BC_TGETB:
3945 | // RA = dst*8, RB = table*8, RC = index*8
3946 | decode_RB8a RB, INS
3947 | decode_RB8b RB
3948 | daddu CARG2, BASE, RB
3949 | decode_RDtoRC8 RC, RD
3950 | ld TAB:RB, 0(CARG2)
3951 | daddu RA, BASE, RA
3952 | srl TMP0, RC, 3
3953 | checktab TAB:RB, ->vmeta_tgetb
3954 | lw TMP1, TAB:RB->asize
3955 | ld TMP2, TAB:RB->array
3956 | sltu AT, TMP0, TMP1
3957 | beqz AT, ->vmeta_tgetb
3958 |. daddu RC, TMP2, RC
3959 | ld AT, 0(RC)
3960 | beq AT, TISNIL, >5
3961 |. ld CRET1, 0(RC)
3962 |1:
3963 | ins_next1
3964 | sd CRET1, 0(RA)
3965 | ins_next2
3966 |
3967 |5: // Check for __index if table value is nil.
3968 | ld TAB:TMP2, TAB:RB->metatable
3969 | beqz TAB:TMP2, <1 // No metatable: done.
3970 |. nop
3971 | lbu TMP1, TAB:TMP2->nomm
3972 | andi TMP1, TMP1, 1<<MM_index
3973 | bnez TMP1, <1 // 'no __index' flag set: done.
3974 |. nop
3975 | b ->vmeta_tgetb // Caveat: preserve TMP0 and CARG2!
3976 |. nop
3977 break;
3978 case BC_TGETR:
3979 | // RA = dst*8, RB = table*8, RC = key*8
3980 | decode_RB8a RB, INS
3981 | decode_RB8b RB
3982 | decode_RDtoRC8 RC, RD
3983 | daddu RB, BASE, RB
3984 | daddu RC, BASE, RC
3985 | ld TAB:CARG1, 0(RB)
3986 | lw CARG2, LO(RC)
3987 | daddu RA, BASE, RA
3988 | cleartp TAB:CARG1
3989 | lw TMP0, TAB:CARG1->asize
3990 | ld TMP1, TAB:CARG1->array
3991 | sltu AT, CARG2, TMP0
3992 | sll TMP2, CARG2, 3
3993 | beqz AT, ->vmeta_tgetr // In array part?
3994 |. daddu CRET1, TMP1, TMP2
3995 | ld CARG2, 0(CRET1)
3996 |->BC_TGETR_Z:
3997 | ins_next1
3998 | sd CARG2, 0(RA)
3999 | ins_next2
4000 break;
4001
4002 case BC_TSETV:
4003 | // RA = src*8, RB = table*8, RC = key*8
4004 | decode_RB8a RB, INS
4005 | decode_RB8b RB
4006 | decode_RDtoRC8 RC, RD
4007 | daddu CARG2, BASE, RB
4008 | daddu CARG3, BASE, RC
4009 | ld RB, 0(CARG2)
4010 | ld TMP2, 0(CARG3)
4011 | daddu RA, BASE, RA
4012 | checktab RB, ->vmeta_tsetv
4013 | checkint TMP2, >5
4014 |. sextw RC, TMP2
4015 | lw TMP0, TAB:RB->asize
4016 | ld TMP1, TAB:RB->array
4017 | sltu AT, RC, TMP0
4018 | sll TMP2, RC, 3
4019 | beqz AT, ->vmeta_tsetv // Integer key and in array part?
4020 |. daddu TMP1, TMP1, TMP2
4021 | ld TMP0, 0(TMP1)
4022 | lbu TMP3, TAB:RB->marked
4023 | beq TMP0, TISNIL, >3
4024 |. ld CRET1, 0(RA)
4025 |1:
4026 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4027 | bnez AT, >7
4028 |. sd CRET1, 0(TMP1)
4029 |2:
4030 | ins_next
4031 |
4032 |3: // Check for __newindex if previous value is nil.
4033 | ld TAB:TMP2, TAB:RB->metatable
4034 | beqz TAB:TMP2, <1 // No metatable: done.
4035 |. nop
4036 | lbu TMP2, TAB:TMP2->nomm
4037 | andi TMP2, TMP2, 1<<MM_newindex
4038 | bnez TMP2, <1 // 'no __newindex' flag set: done.
4039 |. nop
4040 | b ->vmeta_tsetv
4041 |. nop
4042 |
4043 |5:
4044 | gettp AT, TMP2
4045 | daddiu AT, AT, -LJ_TSTR
4046 | bnez AT, ->vmeta_tsetv
4047 |. nop
4048 | b ->BC_TSETS_Z // String key?
4049 |. cleartp STR:RC, TMP2
4050 |
4051 |7: // Possible table write barrier for the value. Skip valiswhite check.
4052 | barrierback TAB:RB, TMP3, TMP0, <2
4053 break;
4054 case BC_TSETS:
4055 | // RA = src*8, RB = table*8, RC = str_const*8 (~)
4056 | decode_RB8a RB, INS
4057 | decode_RB8b RB
4058 | daddu CARG2, BASE, RB
4059 | decode_RC8a RC, INS
4060 | ld TAB:RB, 0(CARG2)
4061 | decode_RC8b RC
4062 | dsubu CARG3, KBASE, RC
4063 | ld RC, -8(CARG3) // KBASE-8-str_const*8
4064 | daddu RA, BASE, RA
4065 | cleartp STR:RC
4066 | checktab TAB:RB, ->vmeta_tsets1
4067 |->BC_TSETS_Z:
4068 | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = BASE+src*8
4069 | lw TMP0, TAB:RB->hmask
4070 | lw TMP1, STR:RC->hash
4071 | ld NODE:TMP2, TAB:RB->node
4072 | sb r0, TAB:RB->nomm // Clear metamethod cache.
4073 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
4074 | sll TMP0, TMP1, 5
4075 | sll TMP1, TMP1, 3
4076 | subu TMP1, TMP0, TMP1
4077 | li TMP3, LJ_TSTR
4078 | daddu NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
4079 | settp STR:RC, TMP3 // Tagged key to look for.
4080 |.if FPU
4081 | ldc1 f20, 0(RA)
4082 |.else
4083 | ld CRET1, 0(RA)
4084 |.endif
4085 |1:
4086 | ld TMP0, NODE:TMP2->key
4087 | ld CARG2, NODE:TMP2->val
4088 | ld NODE:TMP1, NODE:TMP2->next
4089 | bne TMP0, RC, >5
4090 |. lbu TMP3, TAB:RB->marked
4091 | beq CARG2, TISNIL, >4 // Key found, but nil value?
4092 |. ld TAB:TMP0, TAB:RB->metatable
4093 |2:
4094 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4095 | bnez AT, >7
4096 |.if FPU
4097 |. sdc1 f20, NODE:TMP2->val
4098 |.else
4099 |. sd CRET1, NODE:TMP2->val
4100 |.endif
4101 |3:
4102 | ins_next
4103 |
4104 |4: // Check for __newindex if previous value is nil.
4105 | beqz TAB:TMP0, <2 // No metatable: done.
4106 |. nop
4107 | lbu TMP0, TAB:TMP0->nomm
4108 | andi TMP0, TMP0, 1<<MM_newindex
4109 | bnez TMP0, <2 // 'no __newindex' flag set: done.
4110 |. nop
4111 | b ->vmeta_tsets
4112 |. nop
4113 |
4114 |5: // Follow hash chain.
4115 | bnez NODE:TMP1, <1
4116 |. move NODE:TMP2, NODE:TMP1
4117 | // End of hash chain: key not found, add a new one
4118 |
4119 | // But check for __newindex first.
4120 | ld TAB:TMP2, TAB:RB->metatable
4121 | beqz TAB:TMP2, >6 // No metatable: continue.
4122 |. daddiu CARG3, DISPATCH, DISPATCH_GL(tmptv)
4123 | lbu TMP0, TAB:TMP2->nomm
4124 | andi TMP0, TMP0, 1<<MM_newindex
4125 | beqz TMP0, ->vmeta_tsets // 'no __newindex' flag NOT set: check.
4126 |6:
4127 | load_got lj_tab_newkey
4128 | sd RC, 0(CARG3)
4129 | sd BASE, L->base
4130 | move CARG2, TAB:RB
4131 | sd PC, SAVE_PC
4132 | call_intern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k
4133 |. move CARG1, L
4134 | // Returns TValue *.
4135 | ld BASE, L->base
4136 |.if FPU
4137 | b <3 // No 2nd write barrier needed.
4138 |. sdc1 f20, 0(CRET1)
4139 |.else
4140 | ld CARG1, 0(RA)
4141 | b <3 // No 2nd write barrier needed.
4142 |. sd CARG1, 0(CRET1)
4143 |.endif
4144 |
4145 |7: // Possible table write barrier for the value. Skip valiswhite check.
4146 | barrierback TAB:RB, TMP3, TMP0, <3
4147 break;
4148 case BC_TSETB:
4149 | // RA = src*8, RB = table*8, RC = index*8
4150 | decode_RB8a RB, INS
4151 | decode_RB8b RB
4152 | daddu CARG2, BASE, RB
4153 | decode_RDtoRC8 RC, RD
4154 | ld TAB:RB, 0(CARG2)
4155 | daddu RA, BASE, RA
4156 | srl TMP0, RC, 3
4157 | checktab RB, ->vmeta_tsetb
4158 | lw TMP1, TAB:RB->asize
4159 | ld TMP2, TAB:RB->array
4160 | sltu AT, TMP0, TMP1
4161 | beqz AT, ->vmeta_tsetb
4162 |. daddu RC, TMP2, RC
4163 | ld TMP1, 0(RC)
4164 | lbu TMP3, TAB:RB->marked
4165 | beq TMP1, TISNIL, >5
4166 |1:
4167 |. ld CRET1, 0(RA)
4168 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4169 | bnez AT, >7
4170 |. sd CRET1, 0(RC)
4171 |2:
4172 | ins_next
4173 |
4174 |5: // Check for __newindex if previous value is nil.
4175 | ld TAB:TMP2, TAB:RB->metatable
4176 | beqz TAB:TMP2, <1 // No metatable: done.
4177 |. nop
4178 | lbu TMP1, TAB:TMP2->nomm
4179 | andi TMP1, TMP1, 1<<MM_newindex
4180 | bnez TMP1, <1 // 'no __newindex' flag set: done.
4181 |. nop
4182 | b ->vmeta_tsetb // Caveat: preserve TMP0 and CARG2!
4183 |. nop
4184 |
4185 |7: // Possible table write barrier for the value. Skip valiswhite check.
4186 | barrierback TAB:RB, TMP3, TMP0, <2
4187 break;
4188 case BC_TSETR:
4189 | // RA = dst*8, RB = table*8, RC = key*8
4190 | decode_RB8a RB, INS
4191 | decode_RB8b RB
4192 | decode_RDtoRC8 RC, RD
4193 | daddu CARG1, BASE, RB
4194 | daddu CARG3, BASE, RC
4195 | ld TAB:CARG2, 0(CARG1)
4196 | lw CARG3, LO(CARG3)
4197 | cleartp TAB:CARG2
4198 | lbu TMP3, TAB:CARG2->marked
4199 | lw TMP0, TAB:CARG2->asize
4200 | ld TMP1, TAB:CARG2->array
4201 | andi AT, TMP3, LJ_GC_BLACK // isblack(table)
4202 | bnez AT, >7
4203 |. daddu RA, BASE, RA
4204 |2:
4205 | sltu AT, CARG3, TMP0
4206 | sll TMP2, CARG3, 3
4207 | beqz AT, ->vmeta_tsetr // In array part?
4208 |. daddu CRET1, TMP1, TMP2
4209 |->BC_TSETR_Z:
4210 | ld CARG1, 0(RA)
4211 | ins_next1
4212 | sd CARG1, 0(CRET1)
4213 | ins_next2
4214 |
4215 |7: // Possible table write barrier for the value. Skip valiswhite check.
4216 | barrierback TAB:CARG2, TMP3, TMP0, <2
4217 break;
4218
4219 case BC_TSETM:
4220 | // RA = base*8 (table at base-1), RD = num_const*8 (start index)
4221 | daddu RA, BASE, RA
4222 |1:
4223 | daddu TMP3, KBASE, RD
4224 | ld TAB:CARG2, -8(RA) // Guaranteed to be a table.
4225 | addiu TMP0, MULTRES, -8
4226 | lw TMP3, LO(TMP3) // Integer constant is in lo-word.
4227 | beqz TMP0, >4 // Nothing to copy?
4228 |. srl CARG3, TMP0, 3
4229 | cleartp CARG2
4230 | addu CARG3, CARG3, TMP3
4231 | lw TMP2, TAB:CARG2->asize
4232 | sll TMP1, TMP3, 3
4233 | lbu TMP3, TAB:CARG2->marked
4234 | ld CARG1, TAB:CARG2->array
4235 | sltu AT, TMP2, CARG3
4236 | bnez AT, >5
4237 |. daddu TMP2, RA, TMP0
4238 | daddu TMP1, TMP1, CARG1
4239 | andi TMP0, TMP3, LJ_GC_BLACK // isblack(table)
4240 |3: // Copy result slots to table.
4241 | ld CRET1, 0(RA)
4242 | daddiu RA, RA, 8
4243 | sltu AT, RA, TMP2
4244 | sd CRET1, 0(TMP1)
4245 | bnez AT, <3
4246 |. daddiu TMP1, TMP1, 8
4247 | bnez TMP0, >7
4248 |. nop
4249 |4:
4250 | ins_next
4251 |
4252 |5: // Need to resize array part.
4253 | load_got lj_tab_reasize
4254 | sd BASE, L->base
4255 | sd PC, SAVE_PC
4256 | move BASE, RD
4257 | call_intern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
4258 |. move CARG1, L
4259 | // Must not reallocate the stack.
4260 | move RD, BASE
4261 | b <1
4262 |. ld BASE, L->base // Reload BASE for lack of a saved register.
4263 |
4264 |7: // Possible table write barrier for any value. Skip valiswhite check.
4265 | barrierback TAB:CARG2, TMP3, TMP0, <4
4266 break;
4267
4268 /* -- Calls and vararg handling ----------------------------------------- */
4269
4270 case BC_CALLM:
4271 | // RA = base*8, (RB = (nresults+1)*8,) RC = extra_nargs*8
4272 | decode_RDtoRC8 NARGS8:RC, RD
4273 | b ->BC_CALL_Z
4274 |. addu NARGS8:RC, NARGS8:RC, MULTRES
4275 break;
4276 case BC_CALL:
4277 | // RA = base*8, (RB = (nresults+1)*8,) RC = (nargs+1)*8
4278 | decode_RDtoRC8 NARGS8:RC, RD
4279 |->BC_CALL_Z:
4280 | move TMP2, BASE
4281 | daddu BASE, BASE, RA
4282 | ld LFUNC:RB, 0(BASE)
4283 | daddiu BASE, BASE, 16
4284 | addiu NARGS8:RC, NARGS8:RC, -8
4285 | checkfunc RB, ->vmeta_call
4286 | ins_call
4287 break;
4288
4289 case BC_CALLMT:
4290 | // RA = base*8, (RB = 0,) RC = extra_nargs*8
4291 | addu NARGS8:RD, NARGS8:RD, MULTRES // BC_CALLT gets RC from RD.
4292 | // Fall through. Assumes BC_CALLT follows.
4293 break;
4294 case BC_CALLT:
4295 | // RA = base*8, (RB = 0,) RC = (nargs+1)*8
4296 | daddu RA, BASE, RA
4297 | ld RB, 0(RA)
4298 | move NARGS8:RC, RD
4299 | ld TMP1, FRAME_PC(BASE)
4300 | daddiu RA, RA, 16
4301 | addiu NARGS8:RC, NARGS8:RC, -8
4302 | checktp CARG3, RB, -LJ_TFUNC, ->vmeta_callt
4303 |->BC_CALLT_Z:
4304 | andi TMP0, TMP1, FRAME_TYPE // Caveat: preserve TMP0 until the 'or'.
4305 | lbu TMP3, LFUNC:CARG3->ffid
4306 | bnez TMP0, >7
4307 |. xori TMP2, TMP1, FRAME_VARG
4308 |1:
4309 | sd RB, FRAME_FUNC(BASE) // Copy function down, but keep PC.
4310 | sltiu AT, TMP3, 2 // (> FF_C) Calling a fast function?
4311 | move TMP2, BASE
4312 | move RB, CARG3
4313 | beqz NARGS8:RC, >3
4314 |. move TMP3, NARGS8:RC
4315 |2:
4316 | ld CRET1, 0(RA)
4317 | daddiu RA, RA, 8
4318 | addiu TMP3, TMP3, -8
4319 | sd CRET1, 0(TMP2)
4320 | bnez TMP3, <2
4321 |. daddiu TMP2, TMP2, 8
4322 |3:
4323 | or TMP0, TMP0, AT
4324 | beqz TMP0, >5
4325 |. nop
4326 |4:
4327 | ins_callt
4328 |
4329 |5: // Tailcall to a fast function with a Lua frame below.
4330 | lw INS, -4(TMP1)
4331 | decode_RA8a RA, INS
4332 | decode_RA8b RA
4333 | dsubu TMP1, BASE, RA
4334 | ld TMP1, -32(TMP1)
4335 | cleartp LFUNC:TMP1
4336 | ld TMP1, LFUNC:TMP1->pc
4337 | b <4
4338 |. ld KBASE, PC2PROTO(k)(TMP1) // Need to prepare KBASE.
4339 |
4340 |7: // Tailcall from a vararg function.
4341 | andi AT, TMP2, FRAME_TYPEP
4342 | bnez AT, <1 // Vararg frame below?
4343 |. dsubu TMP2, BASE, TMP2 // Relocate BASE down.
4344 | move BASE, TMP2
4345 | ld TMP1, FRAME_PC(TMP2)
4346 | b <1
4347 |. andi TMP0, TMP1, FRAME_TYPE
4348 break;
4349
4350 case BC_ITERC:
4351 | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 ((2+1)*8))
4352 | move TMP2, BASE // Save old BASE fir vmeta_call.
4353 | daddu BASE, BASE, RA
4354 | ld RB, -24(BASE)
4355 | ld CARG1, -16(BASE)
4356 | ld CARG2, -8(BASE)
4357 | li NARGS8:RC, 16 // Iterators get 2 arguments.
4358 | sd RB, 0(BASE) // Copy callable.
4359 | sd CARG1, 16(BASE) // Copy state.
4360 | sd CARG2, 24(BASE) // Copy control var.
4361 | daddiu BASE, BASE, 16
4362 | checkfunc RB, ->vmeta_call
4363 | ins_call
4364 break;
4365
4366 case BC_ITERN:
4367 | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 (2+1)*8)
4368 |.if JIT
4369 | // NYI: add hotloop, record BC_ITERN.
4370 |.endif
4371 | daddu RA, BASE, RA
4372 | ld TAB:RB, -16(RA)
4373 | lw RC, -8+LO(RA) // Get index from control var.
4374 | cleartp TAB:RB
4375 | daddiu PC, PC, 4
4376 | lw TMP0, TAB:RB->asize
4377 | ld TMP1, TAB:RB->array
4378 | dsll CARG3, TISNUM, 47
4379 |1: // Traverse array part.
4380 | sltu AT, RC, TMP0
4381 | beqz AT, >5 // Index points after array part?
4382 |. sll TMP3, RC, 3
4383 | daddu TMP3, TMP1, TMP3
4384 | ld CARG1, 0(TMP3)
4385 | lhu RD, -4+OFS_RD(PC)
4386 | or TMP2, RC, CARG3
4387 | beq CARG1, TISNIL, <1 // Skip holes in array part.
4388 |. addiu RC, RC, 1
4389 | sd TMP2, 0(RA)
4390 | sd CARG1, 8(RA)
4391 | or TMP0, RC, CARG3
4392 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
4393 | decode_RD4b RD
4394 | daddu RD, RD, TMP3
4395 | sw TMP0, -8+LO(RA) // Update control var.
4396 | daddu PC, PC, RD
4397 |3:
4398 | ins_next
4399 |
4400 |5: // Traverse hash part.
4401 | lw TMP1, TAB:RB->hmask
4402 | subu RC, RC, TMP0
4403 | ld TMP2, TAB:RB->node
4404 |6:
4405 | sltu AT, TMP1, RC // End of iteration? Branch to ITERL+1.
4406 | bnez AT, <3
4407 |. sll TMP3, RC, 5
4408 | sll RB, RC, 3
4409 | subu TMP3, TMP3, RB
4410 | daddu NODE:TMP3, TMP3, TMP2
4411 | ld CARG1, 0(NODE:TMP3)
4412 | lhu RD, -4+OFS_RD(PC)
4413 | beq CARG1, TISNIL, <6 // Skip holes in hash part.
4414 |. addiu RC, RC, 1
4415 | ld CARG2, NODE:TMP3->key
4416 | lui TMP3, (-(BCBIAS_J*4 >> 16) & 65535)
4417 | sd CARG1, 8(RA)
4418 | addu RC, RC, TMP0
4419 | decode_RD4b RD
4420 | addu RD, RD, TMP3
4421 | sd CARG2, 0(RA)
4422 | daddu PC, PC, RD
4423 | b <3
4424 |. sw RC, -8+LO(RA) // Update control var.
4425 break;
4426
4427 case BC_ISNEXT:
4428 | // RA = base*8, RD = target (points to ITERN)
4429 | daddu RA, BASE, RA
4430 | srl TMP0, RD, 1
4431 | ld CFUNC:CARG1, -24(RA)
4432 | daddu TMP0, PC, TMP0
4433 | ld CARG2, -16(RA)
4434 | ld CARG3, -8(RA)
4435 | lui TMP2, (-(BCBIAS_J*4 >> 16) & 65535)
4436 | checkfunc CFUNC:CARG1, >5
4437 | gettp CARG2, CARG2
4438 | daddiu CARG2, CARG2, -LJ_TTAB
4439 | lbu TMP1, CFUNC:CARG1->ffid
4440 | daddiu CARG3, CARG3, -LJ_TNIL
4441 | or AT, CARG2, CARG3
4442 | daddiu TMP1, TMP1, -FF_next_N
4443 | or AT, AT, TMP1
4444 | bnez AT, >5
4445 |. lui TMP1, 0xfffe
4446 | daddu PC, TMP0, TMP2
4447 | ori TMP1, TMP1, 0x7fff
4448 | dsll TMP1, TMP1, 32
4449 | sd TMP1, -8(RA)
4450 |1:
4451 | ins_next
4452 |5: // Despecialize bytecode if any of the checks fail.
4453 | li TMP3, BC_JMP
4454 | li TMP1, BC_ITERC
4455 | sb TMP3, -4+OFS_OP(PC)
4456 | daddu PC, TMP0, TMP2
4457 | b <1
4458 |. sb TMP1, OFS_OP(PC)
4459 break;
4460
4461 case BC_VARG:
4462 | // RA = base*8, RB = (nresults+1)*8, RC = numparams*8
4463 | ld TMP0, FRAME_PC(BASE)
4464 | decode_RDtoRC8 RC, RD
4465 | decode_RB8a RB, INS
4466 | daddu RC, BASE, RC
4467 | decode_RB8b RB
4468 | daddu RA, BASE, RA
4469 | daddiu RC, RC, FRAME_VARG
4470 | daddu TMP2, RA, RB
4471 | daddiu TMP3, BASE, -16 // TMP3 = vtop
4472 | dsubu RC, RC, TMP0 // RC = vbase
4473 | // Note: RC may now be even _above_ BASE if nargs was < numparams.
4474 | beqz RB, >5 // Copy all varargs?
4475 |. dsubu TMP1, TMP3, RC
4476 | daddiu TMP2, TMP2, -16
4477 |1: // Copy vararg slots to destination slots.
4478 | ld CARG1, 0(RC)
4479 | sltu AT, RC, TMP3
4480 | daddiu RC, RC, 8
4481 | movz CARG1, TISNIL, AT
4482 | sd CARG1, 0(RA)
4483 | sltu AT, RA, TMP2
4484 | bnez AT, <1
4485 |. daddiu RA, RA, 8
4486 |3:
4487 | ins_next
4488 |
4489 |5: // Copy all varargs.
4490 | ld TMP0, L->maxstack
4491 | blez TMP1, <3 // No vararg slots?
4492 |. li MULTRES, 8 // MULTRES = (0+1)*8
4493 | daddu TMP2, RA, TMP1
4494 | sltu AT, TMP0, TMP2
4495 | bnez AT, >7
4496 |. daddiu MULTRES, TMP1, 8
4497 |6:
4498 | ld CRET1, 0(RC)
4499 | daddiu RC, RC, 8
4500 | sd CRET1, 0(RA)
4501 | sltu AT, RC, TMP3
4502 | bnez AT, <6 // More vararg slots?
4503 |. daddiu RA, RA, 8
4504 | b <3
4505 |. nop
4506 |
4507 |7: // Grow stack for varargs.
4508 | load_got lj_state_growstack
4509 | sd RA, L->top
4510 | dsubu RA, RA, BASE
4511 | sd BASE, L->base
4512 | dsubu BASE, RC, BASE // Need delta, because BASE may change.
4513 | sd PC, SAVE_PC
4514 | srl CARG2, TMP1, 3
4515 | call_intern lj_state_growstack // (lua_State *L, int n)
4516 |. move CARG1, L
4517 | move RC, BASE
4518 | ld BASE, L->base
4519 | daddu RA, BASE, RA
4520 | daddu RC, BASE, RC
4521 | b <6
4522 |. daddiu TMP3, BASE, -16
4523 break;
4524
4525 /* -- Returns ----------------------------------------------------------- */
4526
4527 case BC_RETM:
4528 | // RA = results*8, RD = extra_nresults*8
4529 | addu RD, RD, MULTRES // MULTRES >= 8, so RD >= 8.
4530 | // Fall through. Assumes BC_RET follows.
4531 break;
4532
4533 case BC_RET:
4534 | // RA = results*8, RD = (nresults+1)*8
4535 | ld PC, FRAME_PC(BASE)
4536 | daddu RA, BASE, RA
4537 | move MULTRES, RD
4538 |1:
4539 | andi TMP0, PC, FRAME_TYPE
4540 | bnez TMP0, ->BC_RETV_Z
4541 |. xori TMP1, PC, FRAME_VARG
4542 |
4543 |->BC_RET_Z:
4544 | // BASE = base, RA = resultptr, RD = (nresults+1)*8, PC = return
4545 | lw INS, -4(PC)
4546 | daddiu TMP2, BASE, -16
4547 | daddiu RC, RD, -8
4548 | decode_RA8a TMP0, INS
4549 | decode_RB8a RB, INS
4550 | decode_RA8b TMP0
4551 | decode_RB8b RB
4552 | daddu TMP3, TMP2, RB
4553 | beqz RC, >3
4554 |. dsubu BASE, TMP2, TMP0
4555 |2:
4556 | ld CRET1, 0(RA)
4557 | daddiu RA, RA, 8
4558 | daddiu RC, RC, -8
4559 | sd CRET1, 0(TMP2)
4560 | bnez RC, <2
4561 |. daddiu TMP2, TMP2, 8
4562 |3:
4563 | daddiu TMP3, TMP3, -8
4564 |5:
4565 | sltu AT, TMP2, TMP3
4566 | bnez AT, >6
4567 |. ld LFUNC:TMP1, FRAME_FUNC(BASE)
4568 | ins_next1
4569 | cleartp LFUNC:TMP1
4570 | ld TMP1, LFUNC:TMP1->pc
4571 | ld KBASE, PC2PROTO(k)(TMP1)
4572 | ins_next2
4573 |
4574 |6: // Fill up results with nil.
4575 | sd TISNIL, 0(TMP2)
4576 | b <5
4577 |. daddiu TMP2, TMP2, 8
4578 |
4579 |->BC_RETV_Z: // Non-standard return case.
4580 | andi TMP2, TMP1, FRAME_TYPEP
4581 | bnez TMP2, ->vm_return
4582 |. nop
4583 | // Return from vararg function: relocate BASE down.
4584 | dsubu BASE, BASE, TMP1
4585 | b <1
4586 |. ld PC, FRAME_PC(BASE)
4587 break;
4588
4589 case BC_RET0: case BC_RET1:
4590 | // RA = results*8, RD = (nresults+1)*8
4591 | ld PC, FRAME_PC(BASE)
4592 | daddu RA, BASE, RA
4593 | move MULTRES, RD
4594 | andi TMP0, PC, FRAME_TYPE
4595 | bnez TMP0, ->BC_RETV_Z
4596 |. xori TMP1, PC, FRAME_VARG
4597 | lw INS, -4(PC)
4598 | daddiu TMP2, BASE, -16
4599 if (op == BC_RET1) {
4600 | ld CRET1, 0(RA)
4601 }
4602 | decode_RB8a RB, INS
4603 | decode_RA8a RA, INS
4604 | decode_RB8b RB
4605 | decode_RA8b RA
4606 | dsubu BASE, TMP2, RA
4607 if (op == BC_RET1) {
4608 | sd CRET1, 0(TMP2)
4609 }
4610 |5:
4611 | sltu AT, RD, RB
4612 | bnez AT, >6
4613 |. ld TMP1, FRAME_FUNC(BASE)
4614 | ins_next1
4615 | cleartp LFUNC:TMP1
4616 | ld TMP1, LFUNC:TMP1->pc
4617 | ld KBASE, PC2PROTO(k)(TMP1)
4618 | ins_next2
4619 |
4620 |6: // Fill up results with nil.
4621 | daddiu TMP2, TMP2, 8
4622 | daddiu RD, RD, 8
4623 | b <5
4624 if (op == BC_RET1) {
4625 |. sd TISNIL, 0(TMP2)
4626 } else {
4627 |. sd TISNIL, -8(TMP2)
4628 }
4629 break;
4630
4631 /* -- Loops and branches ------------------------------------------------ */
4632
4633 case BC_FORL:
4634 |.if JIT
4635 | hotloop
4636 |.endif
4637 | // Fall through. Assumes BC_IFORL follows.
4638 break;
4639
4640 case BC_JFORI:
4641 case BC_JFORL:
4642#if !LJ_HASJIT
4643 break;
4644#endif
4645 case BC_FORI:
4646 case BC_IFORL:
4647 | // RA = base*8, RD = target (after end of loop or start of loop)
4648 vk = (op == BC_IFORL || op == BC_JFORL);
4649 | daddu RA, BASE, RA
4650 | ld CARG1, FORL_IDX*8(RA) // IDX CARG1 - CARG3 type
4651 | gettp CARG3, CARG1
4652 if (op != BC_JFORL) {
4653 | srl RD, RD, 1
4654 | lui TMP2, (-(BCBIAS_J*4 >> 16) & 65535)
4655 | daddu TMP2, RD, TMP2
4656 }
4657 if (!vk) {
4658 | ld CARG2, FORL_STOP*8(RA) // STOP CARG2 - CARG4 type
4659 | ld CRET1, FORL_STEP*8(RA) // STEP CRET1 - CRET2 type
4660 | gettp CARG4, CARG2
4661 | bne CARG3, TISNUM, >5
4662 |. gettp CRET2, CRET1
4663 | bne CARG4, TISNUM, ->vmeta_for
4664 |. sextw CARG3, CARG1
4665 | bne CRET2, TISNUM, ->vmeta_for
4666 |. sextw CARG2, CARG2
4667 | dext AT, CRET1, 31, 0
4668 | slt CRET1, CARG2, CARG3
4669 | slt TMP1, CARG3, CARG2
4670 | movn CRET1, TMP1, AT
4671 } else {
4672 | bne CARG3, TISNUM, >5
4673 |. ld CARG2, FORL_STEP*8(RA) // STEP CARG2 - CARG4 type
4674 | ld CRET1, FORL_STOP*8(RA) // STOP CRET1 - CRET2 type
4675 | sextw TMP3, CARG1
4676 | sextw CARG2, CARG2
4677 | sextw CRET1, CRET1
4678 | addu CARG1, TMP3, CARG2
4679 | xor TMP0, CARG1, TMP3
4680 | xor TMP1, CARG1, CARG2
4681 | and TMP0, TMP0, TMP1
4682 | slt TMP1, CARG1, CRET1
4683 | slt CRET1, CRET1, CARG1
4684 | slt AT, CARG2, r0
4685 | slt TMP0, TMP0, r0 // ((y^a) & (y^b)) < 0: overflow.
4686 | movn CRET1, TMP1, AT
4687 | or CRET1, CRET1, TMP0
4688 | zextw CARG1, CARG1
4689 | settp CARG1, TISNUM
4690 }
4691 |1:
4692 if (op == BC_FORI) {
4693 | movz TMP2, r0, CRET1
4694 | daddu PC, PC, TMP2
4695 } else if (op == BC_JFORI) {
4696 | daddu PC, PC, TMP2
4697 | lhu RD, -4+OFS_RD(PC)
4698 } else if (op == BC_IFORL) {
4699 | movn TMP2, r0, CRET1
4700 | daddu PC, PC, TMP2
4701 }
4702 if (vk) {
4703 | sd CARG1, FORL_IDX*8(RA)
4704 }
4705 | ins_next1
4706 | sd CARG1, FORL_EXT*8(RA)
4707 |2:
4708 if (op == BC_JFORI) {
4709 | beqz CRET1, =>BC_JLOOP
4710 |. decode_RD8b RD
4711 } else if (op == BC_JFORL) {
4712 | beqz CRET1, =>BC_JLOOP
4713 }
4714 | ins_next2
4715 |
4716 |5: // FP loop.
4717 |.if FPU
4718 if (!vk) {
4719 | ldc1 f0, FORL_IDX*8(RA)
4720 | ldc1 f2, FORL_STOP*8(RA)
4721 | sltiu TMP0, CARG3, LJ_TISNUM
4722 | sltiu TMP1, CARG4, LJ_TISNUM
4723 | sltiu AT, CRET2, LJ_TISNUM
4724 | ld TMP3, FORL_STEP*8(RA)
4725 | and TMP0, TMP0, TMP1
4726 | and AT, AT, TMP0
4727 | beqz AT, ->vmeta_for
4728 |. slt TMP3, TMP3, r0
4729 | c.ole.d 0, f0, f2
4730 | c.ole.d 1, f2, f0
4731 | li CRET1, 1
4732 | movt CRET1, r0, 0
4733 | movt AT, r0, 1
4734 | b <1
4735 |. movn CRET1, AT, TMP3
4736 } else {
4737 | ldc1 f0, FORL_IDX*8(RA)
4738 | ldc1 f4, FORL_STEP*8(RA)
4739 | ldc1 f2, FORL_STOP*8(RA)
4740 | ld TMP3, FORL_STEP*8(RA)
4741 | add.d f0, f0, f4
4742 | c.ole.d 0, f0, f2
4743 | c.ole.d 1, f2, f0
4744 | slt TMP3, TMP3, r0
4745 | li CRET1, 1
4746 | li AT, 1
4747 | movt CRET1, r0, 0
4748 | movt AT, r0, 1
4749 | movn CRET1, AT, TMP3
4750 if (op == BC_IFORL) {
4751 | movn TMP2, r0, CRET1
4752 | daddu PC, PC, TMP2
4753 }
4754 | sdc1 f0, FORL_IDX*8(RA)
4755 | ins_next1
4756 | b <2
4757 |. sdc1 f0, FORL_EXT*8(RA)
4758 }
4759 |.else
4760 if (!vk) {
4761 | sltiu TMP0, CARG3, LJ_TISNUM
4762 | sltiu TMP1, CARG4, LJ_TISNUM
4763 | sltiu AT, CRET2, LJ_TISNUM
4764 | and TMP0, TMP0, TMP1
4765 | and AT, AT, TMP0
4766 | beqz AT, ->vmeta_for
4767 |. nop
4768 | bal ->vm_sfcmpolex
4769 |. lw TMP3, FORL_STEP*8+HI(RA)
4770 | b <1
4771 |. nop
4772 } else {
4773 | load_got __adddf3
4774 | call_extern
4775 |. sw TMP2, TMPD
4776 | ld CARG2, FORL_STOP*8(RA)
4777 | move CARG1, CRET1
4778 if ( op == BC_JFORL ) {
4779 | lhu RD, -4+OFS_RD(PC)
4780 | decode_RD8b RD
4781 }
4782 | bal ->vm_sfcmpolex
4783 |. lw TMP3, FORL_STEP*8+HI(RA)
4784 | b <1
4785 |. lw TMP2, TMPD
4786 }
4787 |.endif
4788 break;
4789
4790 case BC_ITERL:
4791 |.if JIT
4792 | hotloop
4793 |.endif
4794 | // Fall through. Assumes BC_IITERL follows.
4795 break;
4796
4797 case BC_JITERL:
4798#if !LJ_HASJIT
4799 break;
4800#endif
4801 case BC_IITERL:
4802 | // RA = base*8, RD = target
4803 | daddu RA, BASE, RA
4804 | ld TMP1, 0(RA)
4805 | beq TMP1, TISNIL, >1 // Stop if iterator returned nil.
4806 |. nop
4807 if (op == BC_JITERL) {
4808 | b =>BC_JLOOP
4809 |. sd TMP1, -8(RA)
4810 } else {
4811 | branch_RD // Otherwise save control var + branch.
4812 | sd TMP1, -8(RA)
4813 }
4814 |1:
4815 | ins_next
4816 break;
4817
4818 case BC_LOOP:
4819 | // RA = base*8, RD = target (loop extent)
4820 | // Note: RA/RD is only used by trace recorder to determine scope/extent
4821 | // This opcode does NOT jump, it's only purpose is to detect a hot loop.
4822 |.if JIT
4823 | hotloop
4824 |.endif
4825 | // Fall through. Assumes BC_ILOOP follows.
4826 break;
4827
4828 case BC_ILOOP:
4829 | // RA = base*8, RD = target (loop extent)
4830 | ins_next
4831 break;
4832
4833 case BC_JLOOP:
4834 |.if JIT
4835 | // RA = base*8 (ignored), RD = traceno*8
4836 | ld TMP1, DISPATCH_J(trace)(DISPATCH)
4837 | li AT, 0
4838 | daddu TMP1, TMP1, RD
4839 | // Traces on MIPS don't store the trace number, so use 0.
4840 | sd AT, DISPATCH_GL(vmstate)(DISPATCH)
4841 | ld TRACE:TMP2, 0(TMP1)
4842 | sd BASE, DISPATCH_GL(jit_base)(DISPATCH)
4843 | ld TMP2, TRACE:TMP2->mcode
4844 | sd L, DISPATCH_GL(tmpbuf.L)(DISPATCH)
4845 | jr TMP2
4846 |. daddiu JGL, DISPATCH, GG_DISP2G+32768
4847 |.endif
4848 break;
4849
4850 case BC_JMP:
4851 | // RA = base*8 (only used by trace recorder), RD = target
4852 | branch_RD
4853 | ins_next
4854 break;
4855
4856 /* -- Function headers -------------------------------------------------- */
4857
4858 case BC_FUNCF:
4859 |.if JIT
4860 | hotcall
4861 |.endif
4862 case BC_FUNCV: /* NYI: compiled vararg functions. */
4863 | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow.
4864 break;
4865
4866 case BC_JFUNCF:
4867#if !LJ_HASJIT
4868 break;
4869#endif
4870 case BC_IFUNCF:
4871 | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
4872 | ld TMP2, L->maxstack
4873 | lbu TMP1, -4+PC2PROTO(numparams)(PC)
4874 | ld KBASE, -4+PC2PROTO(k)(PC)
4875 | sltu AT, TMP2, RA
4876 | bnez AT, ->vm_growstack_l
4877 |. sll TMP1, TMP1, 3
4878 if (op != BC_JFUNCF) {
4879 | ins_next1
4880 }
4881 |2:
4882 | sltu AT, NARGS8:RC, TMP1 // Check for missing parameters.
4883 | bnez AT, >3
4884 |. daddu AT, BASE, NARGS8:RC
4885 if (op == BC_JFUNCF) {
4886 | decode_RD8a RD, INS
4887 | b =>BC_JLOOP
4888 |. decode_RD8b RD
4889 } else {
4890 | ins_next2
4891 }
4892 |
4893 |3: // Clear missing parameters.
4894 | sd TISNIL, 0(AT)
4895 | b <2
4896 |. addiu NARGS8:RC, NARGS8:RC, 8
4897 break;
4898
4899 case BC_JFUNCV:
4900#if !LJ_HASJIT
4901 break;
4902#endif
4903 | NYI // NYI: compiled vararg functions
4904 break; /* NYI: compiled vararg functions. */
4905
4906 case BC_IFUNCV:
4907 | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
4908 | li TMP0, LJ_TFUNC
4909 | daddu TMP1, BASE, RC
4910 | ld TMP2, L->maxstack
4911 | settp LFUNC:RB, TMP0
4912 | daddu TMP0, RA, RC
4913 | sd LFUNC:RB, 0(TMP1) // Store (tagged) copy of LFUNC.
4914 | daddiu TMP3, RC, 16+FRAME_VARG
4915 | sltu AT, TMP0, TMP2
4916 | ld KBASE, -4+PC2PROTO(k)(PC)
4917 | beqz AT, ->vm_growstack_l
4918 |. sd TMP3, 8(TMP1) // Store delta + FRAME_VARG.
4919 | lbu TMP2, -4+PC2PROTO(numparams)(PC)
4920 | move RA, BASE
4921 | move RC, TMP1
4922 | ins_next1
4923 | beqz TMP2, >3
4924 |. daddiu BASE, TMP1, 16
4925 |1:
4926 | ld TMP0, 0(RA)
4927 | sltu AT, RA, RC // Less args than parameters?
4928 | move CARG1, TMP0
4929 | movz TMP0, TISNIL, AT // Clear missing parameters.
4930 | movn CARG1, TISNIL, AT // Clear old fixarg slot (help the GC).
4931 | addiu TMP2, TMP2, -1
4932 | sd TMP0, 16(TMP1)
4933 | daddiu TMP1, TMP1, 8
4934 | sd CARG1, 0(RA)
4935 | bnez TMP2, <1
4936 |. daddiu RA, RA, 8
4937 |3:
4938 | ins_next2
4939 break;
4940
4941 case BC_FUNCC:
4942 case BC_FUNCCW:
4943 | // BASE = new base, RA = BASE+framesize*8, RB = CFUNC, RC = nargs*8
4944 if (op == BC_FUNCC) {
4945 | ld CFUNCADDR, CFUNC:RB->f
4946 } else {
4947 | ld CFUNCADDR, DISPATCH_GL(wrapf)(DISPATCH)
4948 }
4949 | daddu TMP1, RA, NARGS8:RC
4950 | ld TMP2, L->maxstack
4951 | daddu RC, BASE, NARGS8:RC
4952 | sd BASE, L->base
4953 | sltu AT, TMP2, TMP1
4954 | sd RC, L->top
4955 | li_vmstate C
4956 if (op == BC_FUNCCW) {
4957 | ld CARG2, CFUNC:RB->f
4958 }
4959 | bnez AT, ->vm_growstack_c // Need to grow stack.
4960 |. move CARG1, L
4961 | jalr CFUNCADDR // (lua_State *L [, lua_CFunction f])
4962 |. st_vmstate
4963 | // Returns nresults.
4964 | ld BASE, L->base
4965 | sll RD, CRET1, 3
4966 | ld TMP1, L->top
4967 | li_vmstate INTERP
4968 | ld PC, FRAME_PC(BASE) // Fetch PC of caller.
4969 | dsubu RA, TMP1, RD // RA = L->top - nresults*8
4970 | sd L, DISPATCH_GL(cur_L)(DISPATCH)
4971 | b ->vm_returnc
4972 |. st_vmstate
4973 break;
4974
4975 /* ---------------------------------------------------------------------- */
4976
4977 default:
4978 fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
4979 exit(2);
4980 break;
4981 }
4982}
4983
4984static int build_backend(BuildCtx *ctx)
4985{
4986 int op;
4987
4988 dasm_growpc(Dst, BC__MAX);
4989
4990 build_subroutines(ctx);
4991
4992 |.code_op
4993 for (op = 0; op < BC__MAX; op++)
4994 build_ins(ctx, (BCOp)op, op);
4995
4996 return BC__MAX;
4997}
4998
4999/* Emit pseudo frame-info for all assembler functions. */
5000static void emit_asm_debug(BuildCtx *ctx)
5001{
5002 int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code);
5003 int i;
5004 switch (ctx->mode) {
5005 case BUILD_elfasm:
5006 fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n");
5007 fprintf(ctx->fp,
5008 ".Lframe0:\n"
5009 "\t.4byte .LECIE0-.LSCIE0\n"
5010 ".LSCIE0:\n"
5011 "\t.4byte 0xffffffff\n"
5012 "\t.byte 0x1\n"
5013 "\t.string \"\"\n"
5014 "\t.uleb128 0x1\n"
5015 "\t.sleb128 -4\n"
5016 "\t.byte 31\n"
5017 "\t.byte 0xc\n\t.uleb128 29\n\t.uleb128 0\n"
5018 "\t.align 2\n"
5019 ".LECIE0:\n\n");
5020 fprintf(ctx->fp,
5021 ".LSFDE0:\n"
5022 "\t.4byte .LEFDE0-.LASFDE0\n"
5023 ".LASFDE0:\n"
5024 "\t.4byte .Lframe0\n"
5025 "\t.8byte .Lbegin\n"
5026 "\t.8byte %d\n"
5027 "\t.byte 0xe\n\t.uleb128 %d\n"
5028 "\t.byte 0x9f\n\t.sleb128 2*5\n"
5029 "\t.byte 0x9e\n\t.sleb128 2*6\n",
5030 fcofs, CFRAME_SIZE);
5031 for (i = 23; i >= 16; i--)
5032 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+i, 2*(30-i));
5033#if !LJ_SOFTFP
5034 for (i = 31; i >= 24; i--)
5035 fprintf(ctx->fp, "\t.byte %d\n\t.uleb128 %d\n", 0x80+32+i, 2*(46-i));
5036#endif
5037 fprintf(ctx->fp,
5038 "\t.align 2\n"
5039 ".LEFDE0:\n\n");
5040#if LJ_HASFFI
5041 fprintf(ctx->fp,
5042 ".LSFDE1:\n"
5043 "\t.4byte .LEFDE1-.LASFDE1\n"
5044 ".LASFDE1:\n"
5045 "\t.4byte .Lframe0\n"
5046 "\t.4byte lj_vm_ffi_call\n"
5047 "\t.4byte %d\n"
5048 "\t.byte 0x9f\n\t.uleb128 2*1\n"
5049 "\t.byte 0x90\n\t.uleb128 2*2\n"
5050 "\t.byte 0xd\n\t.uleb128 0x10\n"
5051 "\t.align 2\n"
5052 ".LEFDE1:\n\n", (int)ctx->codesz - fcofs);
5053#endif
5054#if !LJ_NO_UNWIND
5055 /* NYI */
5056#endif
5057 break;
5058 default:
5059 break;
5060 }
5061}
5062
diff --git a/src/vm_ppc.dasc b/src/vm_ppc.dasc
index 91f50037..b4260ebc 100644
--- a/src/vm_ppc.dasc
+++ b/src/vm_ppc.dasc
@@ -1,4 +1,4 @@
1|// Low-level VM code for PowerPC CPUs. 1|// Low-level VM code for PowerPC 32 bit or 32on64 bit mode.
2|// Bytecode interpreter, fast functions and helper functions. 2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h 3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4| 4|
@@ -18,7 +18,7 @@
18|// DynASM defines used by the PPC port: 18|// DynASM defines used by the PPC port:
19|// 19|//
20|// P64 64 bit pointers (only for GPR64 testing). 20|// P64 64 bit pointers (only for GPR64 testing).
21|// Note: a full PPC64 _LP64 port is not planned. 21|// Note: see vm_ppc64.dasc for a full PPC64 _LP64 port.
22|// GPR64 64 bit registers (but possibly 32 bit pointers, e.g. PS3). 22|// GPR64 64 bit registers (but possibly 32 bit pointers, e.g. PS3).
23|// Affects reg saves, stack layout, carry/overflow/dot flags etc. 23|// Affects reg saves, stack layout, carry/overflow/dot flags etc.
24|// FRAME32 Use 32 bit frame layout, even with GPR64 (Xbox 360). 24|// FRAME32 Use 32 bit frame layout, even with GPR64 (Xbox 360).
@@ -316,16 +316,10 @@
316|.type NODE, Node 316|.type NODE, Node
317|.type NARGS8, int 317|.type NARGS8, int
318|.type TRACE, GCtrace 318|.type TRACE, GCtrace
319|.type SBUF, SBuf
319| 320|
320|//----------------------------------------------------------------------- 321|//-----------------------------------------------------------------------
321| 322|
322|// These basic macros should really be part of DynASM.
323|.macro srwi, rx, ry, n; rlwinm rx, ry, 32-n, n, 31; .endmacro
324|.macro slwi, rx, ry, n; rlwinm rx, ry, n, 0, 31-n; .endmacro
325|.macro rotlwi, rx, ry, n; rlwinm rx, ry, n, 0, 31; .endmacro
326|.macro rotlw, rx, ry, rn; rlwnm rx, ry, rn, 0, 31; .endmacro
327|.macro subi, rx, ry, i; addi rx, ry, -i; .endmacro
328|
329|// Trap for not-yet-implemented parts. 323|// Trap for not-yet-implemented parts.
330|.macro NYI; tw 4, sp, sp; .endmacro 324|.macro NYI; tw 4, sp, sp; .endmacro
331| 325|
@@ -684,12 +678,13 @@ static void build_subroutines(BuildCtx *ctx)
684 | stw CARG3, SAVE_NRES 678 | stw CARG3, SAVE_NRES
685 | cmplwi TMP1, 0 679 | cmplwi TMP1, 0
686 | stw CARG3, SAVE_ERRF 680 | stw CARG3, SAVE_ERRF
687 | stp TMP0, L->cframe
688 | stp CARG3, SAVE_CFRAME 681 | stp CARG3, SAVE_CFRAME
689 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok. 682 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
683 | stp TMP0, L->cframe
690 | beq >3 684 | beq >3
691 | 685 |
692 | // Resume after yield (like a return). 686 | // Resume after yield (like a return).
687 | stw L, DISPATCH_GL(cur_L)(DISPATCH)
693 | mr RA, BASE 688 | mr RA, BASE
694 | lp BASE, L->base 689 | lp BASE, L->base
695 | li TISNUM, LJ_TISNUM // Setup type comparison constants. 690 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
@@ -729,17 +724,18 @@ static void build_subroutines(BuildCtx *ctx)
729 | 724 |
730 |1: // Entry point for vm_pcall above (PC = ftype). 725 |1: // Entry point for vm_pcall above (PC = ftype).
731 | lp TMP1, L:CARG1->cframe 726 | lp TMP1, L:CARG1->cframe
732 | stw CARG3, SAVE_NRES
733 | mr L, CARG1 727 | mr L, CARG1
734 | stw CARG1, SAVE_L 728 | stw CARG3, SAVE_NRES
735 | mr BASE, CARG2
736 | stp sp, L->cframe // Add our C frame to cframe chain.
737 | lwz DISPATCH, L->glref // Setup pointer to dispatch table. 729 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
730 | stw CARG1, SAVE_L
731 | mr BASE, CARG2
732 | addi DISPATCH, DISPATCH, GG_G2DISP
738 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok. 733 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
739 | stp TMP1, SAVE_CFRAME 734 | stp TMP1, SAVE_CFRAME
740 | addi DISPATCH, DISPATCH, GG_G2DISP 735 | stp sp, L->cframe // Add our C frame to cframe chain.
741 | 736 |
742 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype). 737 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
738 | stw L, DISPATCH_GL(cur_L)(DISPATCH)
743 | lp TMP2, L->base // TMP2 = old base (used in vmeta_call). 739 | lp TMP2, L->base // TMP2 = old base (used in vmeta_call).
744 | li TISNUM, LJ_TISNUM // Setup type comparison constants. 740 | li TISNUM, LJ_TISNUM // Setup type comparison constants.
745 | lp TMP1, L->top 741 | lp TMP1, L->top
@@ -776,15 +772,18 @@ static void build_subroutines(BuildCtx *ctx)
776 | lwz TMP0, L:CARG1->stack 772 | lwz TMP0, L:CARG1->stack
777 | stw CARG1, SAVE_L 773 | stw CARG1, SAVE_L
778 | lp TMP1, L->top 774 | lp TMP1, L->top
775 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
779 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok. 776 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
780 | sub TMP0, TMP0, TMP1 // Compute -savestack(L, L->top). 777 | sub TMP0, TMP0, TMP1 // Compute -savestack(L, L->top).
781 | lp TMP1, L->cframe 778 | lp TMP1, L->cframe
782 | stp sp, L->cframe // Add our C frame to cframe chain. 779 | addi DISPATCH, DISPATCH, GG_G2DISP
783 | .toc lp CARG4, 0(CARG4) 780 | .toc lp CARG4, 0(CARG4)
784 | li TMP2, 0 781 | li TMP2, 0
785 | stw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame. 782 | stw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame.
786 | stw TMP2, SAVE_ERRF // No error function. 783 | stw TMP2, SAVE_ERRF // No error function.
787 | stp TMP1, SAVE_CFRAME 784 | stp TMP1, SAVE_CFRAME
785 | stp sp, L->cframe // Add our C frame to cframe chain.
786 | stw L, DISPATCH_GL(cur_L)(DISPATCH)
788 | mtctr CARG4 787 | mtctr CARG4
789 | bctrl // (lua_State *L, lua_CFunction func, void *ud) 788 | bctrl // (lua_State *L, lua_CFunction func, void *ud)
790 |.if PPE 789 |.if PPE
@@ -793,9 +792,7 @@ static void build_subroutines(BuildCtx *ctx)
793 |.else 792 |.else
794 | mr. BASE, CRET1 793 | mr. BASE, CRET1
795 |.endif 794 |.endif
796 | lwz DISPATCH, L->glref // Setup pointer to dispatch table. 795 | li PC, FRAME_CP
797 | li PC, FRAME_CP
798 | addi DISPATCH, DISPATCH, GG_G2DISP
799 | bne <3 // Else continue with the call. 796 | bne <3 // Else continue with the call.
800 | b ->vm_leave_cp // No base? Just remove C frame. 797 | b ->vm_leave_cp // No base? Just remove C frame.
801 | 798 |
@@ -918,6 +915,17 @@ static void build_subroutines(BuildCtx *ctx)
918 | li NARGS8:RC, 16 // 2 args for func(t, k). 915 | li NARGS8:RC, 16 // 2 args for func(t, k).
919 | b ->vm_call_dispatch_f 916 | b ->vm_call_dispatch_f
920 | 917 |
918 |->vmeta_tgetr:
919 | bl extern lj_tab_getinth // (GCtab *t, int32_t key)
920 | // Returns cTValue * or NULL.
921 | cmplwi CRET1, 0
922 | beq >1
923 | lfd f14, 0(CRET1)
924 | b ->BC_TGETR_Z
925 |1:
926 | stwx TISNIL, BASE, RA
927 | b ->cont_nop
928 |
921 |//----------------------------------------------------------------------- 929 |//-----------------------------------------------------------------------
922 | 930 |
923 |->vmeta_tsets1: 931 |->vmeta_tsets1:
@@ -985,6 +993,14 @@ static void build_subroutines(BuildCtx *ctx)
985 | stfd f0, 16(BASE) // Copy value to third argument. 993 | stfd f0, 16(BASE) // Copy value to third argument.
986 | b ->vm_call_dispatch_f 994 | b ->vm_call_dispatch_f
987 | 995 |
996 |->vmeta_tsetr:
997 | stp BASE, L->base
998 | stw PC, SAVE_PC
999 | bl extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
1000 | // Returns TValue *.
1001 | stfd f14, 0(CRET1)
1002 | b ->cont_nop
1003 |
988 |//-- Comparison metamethods --------------------------------------------- 1004 |//-- Comparison metamethods ---------------------------------------------
989 | 1005 |
990 |->vmeta_comp: 1006 |->vmeta_comp:
@@ -1063,6 +1079,16 @@ static void build_subroutines(BuildCtx *ctx)
1063 | b <3 1079 | b <3
1064 |.endif 1080 |.endif
1065 | 1081 |
1082 |->vmeta_istype:
1083 | subi PC, PC, 4
1084 | stp BASE, L->base
1085 | srwi CARG2, RA, 3
1086 | mr CARG1, L
1087 | srwi CARG3, RD, 3
1088 | stw PC, SAVE_PC
1089 | bl extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
1090 | b ->cont_nop
1091 |
1066 |//-- Arithmetic metamethods --------------------------------------------- 1092 |//-- Arithmetic metamethods ---------------------------------------------
1067 | 1093 |
1068 |->vmeta_arith_nv: 1094 |->vmeta_arith_nv:
@@ -1387,9 +1413,9 @@ static void build_subroutines(BuildCtx *ctx)
1387 | mr CARG1, L 1413 | mr CARG1, L
1388 | mr CARG2, BASE 1414 | mr CARG2, BASE
1389 |.if DUALNUM 1415 |.if DUALNUM
1390 | bl extern lj_str_fromnumber // (lua_State *L, cTValue *o) 1416 | bl extern lj_strfmt_number // (lua_State *L, cTValue *o)
1391 |.else 1417 |.else
1392 | bl extern lj_str_fromnum // (lua_State *L, lua_Number *np) 1418 | bl extern lj_strfmt_num // (lua_State *L, lua_Number *np)
1393 |.endif 1419 |.endif
1394 | // Returns GCstr *. 1420 | // Returns GCstr *.
1395 | li CARG3, LJ_TSTR 1421 | li CARG3, LJ_TSTR
@@ -1622,6 +1648,7 @@ static void build_subroutines(BuildCtx *ctx)
1622 | lp TMP3, L:SAVE0->top 1648 | lp TMP3, L:SAVE0->top
1623 | li_vmstate INTERP 1649 | li_vmstate INTERP
1624 | lp BASE, L->base 1650 | lp BASE, L->base
1651 | stw L, DISPATCH_GL(cur_L)(DISPATCH)
1625 | st_vmstate 1652 | st_vmstate
1626 | bgt >8 1653 | bgt >8
1627 | sub RD, TMP3, TMP2 1654 | sub RD, TMP3, TMP2
@@ -1893,12 +1920,6 @@ static void build_subroutines(BuildCtx *ctx)
1893 | math_extern2 atan2 1920 | math_extern2 atan2
1894 | math_extern2 fmod 1921 | math_extern2 fmod
1895 | 1922 |
1896 |->ff_math_deg:
1897 |.ffunc_n math_rad
1898 | lfd FARG2, CFUNC:RB->upvalue[0]
1899 | fmul FARG1, FARG1, FARG2
1900 | b ->fff_resn
1901 |
1902 |.if DUALNUM 1923 |.if DUALNUM
1903 |.ffunc math_ldexp 1924 |.ffunc math_ldexp
1904 | cmplwi NARGS8:RC, 16 1925 | cmplwi NARGS8:RC, 16
@@ -2044,11 +2065,6 @@ static void build_subroutines(BuildCtx *ctx)
2044 | 2065 |
2045 |//-- String library ----------------------------------------------------- 2066 |//-- String library -----------------------------------------------------
2046 | 2067 |
2047 |.ffunc_1 string_len
2048 | checkstr CARG3; bne ->fff_fallback
2049 | lwz CRET1, STR:CARG1->len
2050 | b ->fff_resi
2051 |
2052 |.ffunc string_byte // Only handle the 1-arg case here. 2068 |.ffunc string_byte // Only handle the 1-arg case here.
2053 | cmplwi NARGS8:RC, 8 2069 | cmplwi NARGS8:RC, 8
2054 | lwz CARG3, 0(BASE) 2070 | lwz CARG3, 0(BASE)
@@ -2103,6 +2119,7 @@ static void build_subroutines(BuildCtx *ctx)
2103 | stp BASE, L->base 2119 | stp BASE, L->base
2104 | stw PC, SAVE_PC 2120 | stw PC, SAVE_PC
2105 | bl extern lj_str_new // (lua_State *L, char *str, size_t l) 2121 | bl extern lj_str_new // (lua_State *L, char *str, size_t l)
2122 |->fff_resstr:
2106 | // Returns GCstr *. 2123 | // Returns GCstr *.
2107 | lp BASE, L->base 2124 | lp BASE, L->base
2108 | li CARG3, LJ_TSTR 2125 | li CARG3, LJ_TSTR
@@ -2180,114 +2197,29 @@ static void build_subroutines(BuildCtx *ctx)
2180 | addi TMP1, TMP1, 1 // start = 1 + (start ? start+len : 0) 2197 | addi TMP1, TMP1, 1 // start = 1 + (start ? start+len : 0)
2181 | b <3 2198 | b <3
2182 | 2199 |
2183 |.ffunc string_rep // Only handle the 1-char case inline. 2200 |.macro ffstring_op, name
2184 | ffgccheck 2201 | .ffunc string_ .. name
2185 | cmplwi NARGS8:RC, 16
2186 | lwz TMP0, 0(BASE)
2187 | lwz STR:CARG1, 4(BASE)
2188 | lwz CARG4, 8(BASE)
2189 |.if DUALNUM
2190 | lwz CARG3, 12(BASE)
2191 |.else
2192 | lfd FARG2, 8(BASE)
2193 |.endif
2194 | bne ->fff_fallback // Exactly 2 arguments.
2195 | checkstr TMP0; bne ->fff_fallback
2196 |.if DUALNUM
2197 | checknum CARG4; bne ->fff_fallback
2198 |.else
2199 | checknum CARG4; bge ->fff_fallback
2200 | toint CARG3, FARG2
2201 |.endif
2202 | lwz TMP0, STR:CARG1->len
2203 | cmpwi CARG3, 0
2204 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
2205 | ble >2 // Count <= 0? (or non-int)
2206 | cmplwi TMP0, 1
2207 | subi TMP2, CARG3, 1
2208 | blt >2 // Zero length string?
2209 | cmplw cr1, TMP1, CARG3
2210 | bne ->fff_fallback // Fallback for > 1-char strings.
2211 | lbz TMP0, STR:CARG1[1]
2212 | lp CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
2213 | blt cr1, ->fff_fallback
2214 |1: // Fill buffer with char. Yes, this is suboptimal code (do you care?).
2215 | cmplwi TMP2, 0
2216 | stbx TMP0, CARG2, TMP2
2217 | subi TMP2, TMP2, 1
2218 | bne <1
2219 | b ->fff_newstr
2220 |2: // Return empty string.
2221 | la STR:CARG1, DISPATCH_GL(strempty)(DISPATCH)
2222 | li CARG3, LJ_TSTR
2223 | b ->fff_restv
2224 |
2225 |.ffunc string_reverse
2226 | ffgccheck 2202 | ffgccheck
2227 | cmplwi NARGS8:RC, 8 2203 | cmplwi NARGS8:RC, 8
2228 | lwz CARG3, 0(BASE) 2204 | lwz CARG3, 0(BASE)
2229 | lwz STR:CARG1, 4(BASE) 2205 | lwz STR:CARG2, 4(BASE)
2230 | blt ->fff_fallback 2206 | blt ->fff_fallback
2231 | checkstr CARG3 2207 | checkstr CARG3
2232 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH) 2208 | la SBUF:CARG1, DISPATCH_GL(tmpbuf)(DISPATCH)
2233 | bne ->fff_fallback 2209 | bne ->fff_fallback
2234 | lwz CARG3, STR:CARG1->len 2210 | lwz TMP0, SBUF:CARG1->b
2235 | la CARG1, #STR(STR:CARG1) 2211 | stw L, SBUF:CARG1->L
2236 | lp CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH) 2212 | stp BASE, L->base
2237 | li TMP2, 0 2213 | stw PC, SAVE_PC
2238 | cmplw TMP1, CARG3 2214 | stw TMP0, SBUF:CARG1->p
2239 | subi TMP3, CARG3, 1 2215 | bl extern lj_buf_putstr_ .. name
2240 | blt ->fff_fallback 2216 | bl extern lj_buf_tostr
2241 |1: // Reverse string copy. 2217 | b ->fff_resstr
2242 | cmpwi TMP3, 0
2243 | lbzx TMP1, CARG1, TMP2
2244 | blty ->fff_newstr
2245 | stbx TMP1, CARG2, TMP3
2246 | subi TMP3, TMP3, 1
2247 | addi TMP2, TMP2, 1
2248 | b <1
2249 |
2250 |.macro ffstring_case, name, lo
2251 | .ffunc name
2252 | ffgccheck
2253 | cmplwi NARGS8:RC, 8
2254 | lwz CARG3, 0(BASE)
2255 | lwz STR:CARG1, 4(BASE)
2256 | blt ->fff_fallback
2257 | checkstr CARG3
2258 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
2259 | bne ->fff_fallback
2260 | lwz CARG3, STR:CARG1->len
2261 | la CARG1, #STR(STR:CARG1)
2262 | lp CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
2263 | cmplw TMP1, CARG3
2264 | li TMP2, 0
2265 | blt ->fff_fallback
2266 |1: // ASCII case conversion.
2267 | cmplw TMP2, CARG3
2268 | lbzx TMP1, CARG1, TMP2
2269 | bgey ->fff_newstr
2270 | subi TMP0, TMP1, lo
2271 | xori TMP3, TMP1, 0x20
2272 | addic TMP0, TMP0, -26
2273 | subfe TMP3, TMP3, TMP3
2274 | rlwinm TMP3, TMP3, 0, 26, 26 // x &= 0x20.
2275 | xor TMP1, TMP1, TMP3
2276 | stbx TMP1, CARG2, TMP2
2277 | addi TMP2, TMP2, 1
2278 | b <1
2279 |.endmacro 2218 |.endmacro
2280 | 2219 |
2281 |ffstring_case string_lower, 65 2220 |ffstring_op reverse
2282 |ffstring_case string_upper, 97 2221 |ffstring_op lower
2283 | 2222 |ffstring_op upper
2284 |//-- Table library ------------------------------------------------------
2285 |
2286 |.ffunc_1 table_getn
2287 | checktab CARG3; bne ->fff_fallback
2288 | bl extern lj_tab_len // (GCtab *t)
2289 | // Returns uint32_t (but less than 2^31).
2290 | b ->fff_resi
2291 | 2223 |
2292 |//-- Bit library -------------------------------------------------------- 2224 |//-- Bit library --------------------------------------------------------
2293 | 2225 |
@@ -2589,6 +2521,66 @@ static void build_subroutines(BuildCtx *ctx)
2589 | mtctr CRET1 2521 | mtctr CRET1
2590 | bctr 2522 | bctr
2591 | 2523 |
2524 |->cont_stitch: // Trace stitching.
2525 |.if JIT
2526 | // RA = resultptr, RB = meta base
2527 | lwz INS, -4(PC)
2528 | lwz TRACE:TMP2, -20(RB) // Save previous trace.
2529 | addic. TMP1, MULTRES, -8
2530 | decode_RA8 RC, INS // Call base.
2531 | beq >2
2532 |1: // Move results down.
2533 | lfd f0, 0(RA)
2534 | addic. TMP1, TMP1, -8
2535 | addi RA, RA, 8
2536 | stfdx f0, BASE, RC
2537 | addi RC, RC, 8
2538 | bne <1
2539 |2:
2540 | decode_RA8 RA, INS
2541 | decode_RB8 RB, INS
2542 | add RA, RA, RB
2543 |3:
2544 | cmplw RA, RC
2545 | bgt >9 // More results wanted?
2546 |
2547 | lhz TMP3, TRACE:TMP2->traceno
2548 | lhz RD, TRACE:TMP2->link
2549 | cmpw RD, TMP3
2550 | cmpwi cr1, RD, 0
2551 | beq ->cont_nop // Blacklisted.
2552 | slwi RD, RD, 3
2553 | bne cr1, =>BC_JLOOP // Jump to stitched trace.
2554 |
2555 | // Stitch a new trace to the previous trace.
2556 | stw TMP3, DISPATCH_J(exitno)(DISPATCH)
2557 | stp L, DISPATCH_J(L)(DISPATCH)
2558 | stp BASE, L->base
2559 | addi CARG1, DISPATCH, GG_DISP2J
2560 | mr CARG2, PC
2561 | bl extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
2562 | lp BASE, L->base
2563 | b ->cont_nop
2564 |
2565 |9:
2566 | stwx TISNIL, BASE, RC
2567 | addi RC, RC, 8
2568 | b <3
2569 |.endif
2570 |
2571 |->vm_profhook: // Dispatch target for profiler hook.
2572#if LJ_HASPROFILE
2573 | mr CARG1, L
2574 | stw MULTRES, SAVE_MULTRES
2575 | mr CARG2, PC
2576 | stp BASE, L->base
2577 | bl extern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
2578 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2579 | lp BASE, L->base
2580 | subi PC, PC, 4
2581 | b ->cont_nop
2582#endif
2583 |
2592 |//----------------------------------------------------------------------- 2584 |//-----------------------------------------------------------------------
2593 |//-- Trace exit handler ------------------------------------------------- 2585 |//-- Trace exit handler -------------------------------------------------
2594 |//----------------------------------------------------------------------- 2586 |//-----------------------------------------------------------------------
@@ -2623,16 +2615,16 @@ static void build_subroutines(BuildCtx *ctx)
2623 | savex_ 20,21,22,23 2615 | savex_ 20,21,22,23
2624 | lhz CARG4, 2(CARG3) // Load trace number. 2616 | lhz CARG4, 2(CARG3) // Load trace number.
2625 | savex_ 24,25,26,27 2617 | savex_ 24,25,26,27
2626 | lwz L, DISPATCH_GL(jit_L)(DISPATCH) 2618 | lwz L, DISPATCH_GL(cur_L)(DISPATCH)
2627 | savex_ 28,29,30,31 2619 | savex_ 28,29,30,31
2628 | sub CARG3, TMP0, CARG3 // Compute exit number. 2620 | sub CARG3, TMP0, CARG3 // Compute exit number.
2629 | lp BASE, DISPATCH_GL(jit_base)(DISPATCH) 2621 | lp BASE, DISPATCH_GL(jit_base)(DISPATCH)
2630 | srwi CARG3, CARG3, 2 2622 | srwi CARG3, CARG3, 2
2631 | stw L, DISPATCH_J(L)(DISPATCH) 2623 | stp L, DISPATCH_J(L)(DISPATCH)
2632 | subi CARG3, CARG3, 2 2624 | subi CARG3, CARG3, 2
2633 | stw TMP1, DISPATCH_GL(jit_L)(DISPATCH)
2634 | stw CARG4, DISPATCH_J(parent)(DISPATCH)
2635 | stp BASE, L->base 2625 | stp BASE, L->base
2626 | stw CARG4, DISPATCH_J(parent)(DISPATCH)
2627 | stw TMP1, DISPATCH_GL(jit_base)(DISPATCH)
2636 | addi CARG1, DISPATCH, GG_DISP2J 2628 | addi CARG1, DISPATCH, GG_DISP2J
2637 | stw CARG3, DISPATCH_J(exitno)(DISPATCH) 2629 | stw CARG3, DISPATCH_J(exitno)(DISPATCH)
2638 | addi CARG2, sp, 16 2630 | addi CARG2, sp, 16
@@ -2656,15 +2648,16 @@ static void build_subroutines(BuildCtx *ctx)
2656 | // CARG1 = MULTRES or negated error code, BASE, PC and JGL set. 2648 | // CARG1 = MULTRES or negated error code, BASE, PC and JGL set.
2657 | lwz L, SAVE_L 2649 | lwz L, SAVE_L
2658 | addi DISPATCH, JGL, -GG_DISP2G-32768 2650 | addi DISPATCH, JGL, -GG_DISP2G-32768
2651 | stp BASE, L->base
2659 |1: 2652 |1:
2660 | cmpwi CARG1, 0 2653 | cmpwi CARG1, 0
2661 | blt >3 // Check for error from exit. 2654 | blt >9 // Check for error from exit.
2662 | lwz LFUNC:TMP1, FRAME_FUNC(BASE) 2655 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2663 | slwi MULTRES, CARG1, 3 2656 | slwi MULTRES, CARG1, 3
2664 | li TMP2, 0 2657 | li TMP2, 0
2665 | stw MULTRES, SAVE_MULTRES 2658 | stw MULTRES, SAVE_MULTRES
2666 | lwz TMP1, LFUNC:TMP1->pc 2659 | lwz TMP1, LFUNC:RB->pc
2667 | stw TMP2, DISPATCH_GL(jit_L)(DISPATCH) 2660 | stw TMP2, DISPATCH_GL(jit_base)(DISPATCH)
2668 | lwz KBASE, PC2PROTO(k)(TMP1) 2661 | lwz KBASE, PC2PROTO(k)(TMP1)
2669 | // Setup type comparison constants. 2662 | // Setup type comparison constants.
2670 | li TISNUM, LJ_TISNUM 2663 | li TISNUM, LJ_TISNUM
@@ -2694,11 +2687,25 @@ static void build_subroutines(BuildCtx *ctx)
2694 | decode_RC8 RC, INS 2687 | decode_RC8 RC, INS
2695 | bctr 2688 | bctr
2696 |2: 2689 |2:
2690 | cmplwi TMP1, (BC_FUNCC+2)*4 // Fast function?
2691 | blt >3
2692 | // Check frame below fast function.
2693 | lwz TMP1, FRAME_PC(BASE)
2694 | andix. TMP0, TMP1, FRAME_TYPE
2695 | bney >3 // Trace stitching continuation?
2696 | // Otherwise set KBASE for Lua function below fast function.
2697 | lwz TMP2, -4(TMP1)
2698 | decode_RA8 TMP0, TMP2
2699 | sub TMP1, BASE, TMP0
2700 | lwz LFUNC:TMP2, -12(TMP1)
2701 | lwz TMP1, LFUNC:TMP2->pc
2702 | lwz KBASE, PC2PROTO(k)(TMP1)
2703 |3:
2697 | subi RC, MULTRES, 8 2704 | subi RC, MULTRES, 8
2698 | add RA, RA, BASE 2705 | add RA, RA, BASE
2699 | bctr 2706 | bctr
2700 | 2707 |
2701 |3: // Rethrow error from the right C frame. 2708 |9: // Rethrow error from the right C frame.
2702 | neg CARG2, CARG1 2709 | neg CARG2, CARG1
2703 | mr CARG1, L 2710 | mr CARG1, L
2704 | bl extern lj_err_throw // (lua_State *L, int errcode) 2711 | bl extern lj_err_throw // (lua_State *L, int errcode)
@@ -3288,6 +3295,29 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3288 | ins_next 3295 | ins_next
3289 break; 3296 break;
3290 3297
3298 case BC_ISTYPE:
3299 | // RA = src*8, RD = -type*8
3300 | lwzx TMP0, BASE, RA
3301 | srwi TMP1, RD, 3
3302 | ins_next1
3303 |.if not PPE and not GPR64
3304 | add. TMP0, TMP0, TMP1
3305 |.else
3306 | neg TMP1, TMP1
3307 | cmpw TMP0, TMP1
3308 |.endif
3309 | bne ->vmeta_istype
3310 | ins_next2
3311 break;
3312 case BC_ISNUM:
3313 | // RA = src*8, RD = -(TISNUM-1)*8
3314 | lwzx TMP0, BASE, RA
3315 | ins_next1
3316 | checknum TMP0
3317 | bge ->vmeta_istype
3318 | ins_next2
3319 break;
3320
3291 /* -- Unary ops --------------------------------------------------------- */ 3321 /* -- Unary ops --------------------------------------------------------- */
3292 3322
3293 case BC_MOV: 3323 case BC_MOV:
@@ -4039,6 +4069,30 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4039 | bne <1 // 'no __index' flag set: done. 4069 | bne <1 // 'no __index' flag set: done.
4040 | b ->vmeta_tgetb // Caveat: preserve TMP0! 4070 | b ->vmeta_tgetb // Caveat: preserve TMP0!
4041 break; 4071 break;
4072 case BC_TGETR:
4073 | // RA = dst*8, RB = table*8, RC = key*8
4074 | add RB, BASE, RB
4075 | lwz TAB:CARG1, 4(RB)
4076 |.if DUALNUM
4077 | add RC, BASE, RC
4078 | lwz TMP0, TAB:CARG1->asize
4079 | lwz CARG2, 4(RC)
4080 | lwz TMP1, TAB:CARG1->array
4081 |.else
4082 | lfdx f0, BASE, RC
4083 | lwz TMP0, TAB:CARG1->asize
4084 | toint CARG2, f0
4085 | lwz TMP1, TAB:CARG1->array
4086 |.endif
4087 | cmplw TMP0, CARG2
4088 | slwi TMP2, CARG2, 3
4089 | ble ->vmeta_tgetr // In array part?
4090 | lfdx f14, TMP1, TMP2
4091 |->BC_TGETR_Z:
4092 | ins_next1
4093 | stfdx f14, BASE, RA
4094 | ins_next2
4095 break;
4042 4096
4043 case BC_TSETV: 4097 case BC_TSETV:
4044 | // RA = src*8, RB = table*8, RC = key*8 4098 | // RA = src*8, RB = table*8, RC = key*8
@@ -4218,6 +4272,39 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4218 | barrierback TAB:RB, TMP3, TMP0 4272 | barrierback TAB:RB, TMP3, TMP0
4219 | b <2 4273 | b <2
4220 break; 4274 break;
4275 case BC_TSETR:
4276 | // RA = dst*8, RB = table*8, RC = key*8
4277 | add RB, BASE, RB
4278 | lwz TAB:CARG2, 4(RB)
4279 |.if DUALNUM
4280 | add RC, BASE, RC
4281 | lbz TMP3, TAB:CARG2->marked
4282 | lwz TMP0, TAB:CARG2->asize
4283 | lwz CARG3, 4(RC)
4284 | lwz TMP1, TAB:CARG2->array
4285 |.else
4286 | lfdx f0, BASE, RC
4287 | lbz TMP3, TAB:CARG2->marked
4288 | lwz TMP0, TAB:CARG2->asize
4289 | toint CARG3, f0
4290 | lwz TMP1, TAB:CARG2->array
4291 |.endif
4292 | andix. TMP2, TMP3, LJ_GC_BLACK // isblack(table)
4293 | bne >7
4294 |2:
4295 | cmplw TMP0, CARG3
4296 | slwi TMP2, CARG3, 3
4297 | lfdx f14, BASE, RA
4298 | ble ->vmeta_tsetr // In array part?
4299 | ins_next1
4300 | stfdx f14, TMP1, TMP2
4301 | ins_next2
4302 |
4303 |7: // Possible table write barrier for the value. Skip valiswhite check.
4304 | barrierback TAB:CARG2, TMP3, TMP2
4305 | b <2
4306 break;
4307
4221 4308
4222 case BC_TSETM: 4309 case BC_TSETM:
4223 | // RA = base*8 (table at base-1), RD = num_const*8 (start index) 4310 | // RA = base*8 (table at base-1), RD = num_const*8 (start index)
@@ -4859,8 +4946,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4859 | lp TMP2, TRACE:TMP2->mcode 4946 | lp TMP2, TRACE:TMP2->mcode
4860 | stw BASE, DISPATCH_GL(jit_base)(DISPATCH) 4947 | stw BASE, DISPATCH_GL(jit_base)(DISPATCH)
4861 | mtctr TMP2 4948 | mtctr TMP2
4862 | stw L, DISPATCH_GL(jit_L)(DISPATCH)
4863 | addi JGL, DISPATCH, GG_DISP2G+32768 4949 | addi JGL, DISPATCH, GG_DISP2G+32768
4950 | stw L, DISPATCH_GL(tmpbuf.L)(DISPATCH)
4864 | bctr 4951 | bctr
4865 |.endif 4952 |.endif
4866 break; 4953 break;
@@ -4995,6 +5082,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4995 | lp TMP1, L->top 5082 | lp TMP1, L->top
4996 | li_vmstate INTERP 5083 | li_vmstate INTERP
4997 | lwz PC, FRAME_PC(BASE) // Fetch PC of caller. 5084 | lwz PC, FRAME_PC(BASE) // Fetch PC of caller.
5085 | stw L, DISPATCH_GL(cur_L)(DISPATCH)
4998 | sub RA, TMP1, RD // RA = L->top - nresults*8 5086 | sub RA, TMP1, RD // RA = L->top - nresults*8
4999 | st_vmstate 5087 | st_vmstate
5000 | b ->vm_returnc 5088 | b ->vm_returnc
diff --git a/src/vm_ppcspe.dasc b/src/vm_ppcspe.dasc
deleted file mode 100644
index 2a57a41f..00000000
--- a/src/vm_ppcspe.dasc
+++ /dev/null
@@ -1,3691 +0,0 @@
1|// Low-level VM code for PowerPC/e500 CPUs.
2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4|
5|.arch ppc
6|.section code_op, code_sub
7|
8|.actionlist build_actionlist
9|.globals GLOB_
10|.globalnames globnames
11|.externnames extnames
12|
13|// Note: The ragged indentation of the instructions is intentional.
14|// The starting columns indicate data dependencies.
15|
16|//-----------------------------------------------------------------------
17|
18|// Fixed register assignments for the interpreter.
19|// Don't use: r1 = sp, r2 and r13 = reserved and/or small data area ptr
20|
21|// The following must be C callee-save (but BASE is often refetched).
22|.define BASE, r14 // Base of current Lua stack frame.
23|.define KBASE, r15 // Constants of current Lua function.
24|.define PC, r16 // Next PC.
25|.define DISPATCH, r17 // Opcode dispatch table.
26|.define LREG, r18 // Register holding lua_State (also in SAVE_L).
27|.define MULTRES, r19 // Size of multi-result: (nresults+1)*8.
28|
29|// Constants for vectorized type-comparisons (hi+low GPR). C callee-save.
30|.define TISNUM, r22
31|.define TISSTR, r23
32|.define TISTAB, r24
33|.define TISFUNC, r25
34|.define TISNIL, r26
35|.define TOBIT, r27
36|.define ZERO, TOBIT // Zero in lo word.
37|
38|// The following temporaries are not saved across C calls, except for RA.
39|.define RA, r20 // Callee-save.
40|.define RB, r10
41|.define RC, r11
42|.define RD, r12
43|.define INS, r7 // Overlaps CARG5.
44|
45|.define TMP0, r0
46|.define TMP1, r8
47|.define TMP2, r9
48|.define TMP3, r6 // Overlaps CARG4.
49|
50|// Saved temporaries.
51|.define SAVE0, r21
52|
53|// Calling conventions.
54|.define CARG1, r3
55|.define CARG2, r4
56|.define CARG3, r5
57|.define CARG4, r6 // Overlaps TMP3.
58|.define CARG5, r7 // Overlaps INS.
59|
60|.define CRET1, r3
61|.define CRET2, r4
62|
63|// Stack layout while in interpreter. Must match with lj_frame.h.
64|.define SAVE_LR, 188(sp)
65|.define CFRAME_SPACE, 184 // Delta for sp.
66|// Back chain for sp: 184(sp) <-- sp entering interpreter
67|.define SAVE_r31, 176(sp) // 64 bit register saves.
68|.define SAVE_r30, 168(sp)
69|.define SAVE_r29, 160(sp)
70|.define SAVE_r28, 152(sp)
71|.define SAVE_r27, 144(sp)
72|.define SAVE_r26, 136(sp)
73|.define SAVE_r25, 128(sp)
74|.define SAVE_r24, 120(sp)
75|.define SAVE_r23, 112(sp)
76|.define SAVE_r22, 104(sp)
77|.define SAVE_r21, 96(sp)
78|.define SAVE_r20, 88(sp)
79|.define SAVE_r19, 80(sp)
80|.define SAVE_r18, 72(sp)
81|.define SAVE_r17, 64(sp)
82|.define SAVE_r16, 56(sp)
83|.define SAVE_r15, 48(sp)
84|.define SAVE_r14, 40(sp)
85|.define SAVE_CR, 36(sp)
86|.define UNUSED1, 32(sp)
87|.define SAVE_ERRF, 28(sp) // 32 bit C frame info.
88|.define SAVE_NRES, 24(sp)
89|.define SAVE_CFRAME, 20(sp)
90|.define SAVE_L, 16(sp)
91|.define SAVE_PC, 12(sp)
92|.define SAVE_MULTRES, 8(sp)
93|// Next frame lr: 4(sp)
94|// Back chain for sp: 0(sp) <-- sp while in interpreter
95|
96|.macro save_, reg; evstdd reg, SAVE_..reg; .endmacro
97|.macro rest_, reg; evldd reg, SAVE_..reg; .endmacro
98|
99|.macro saveregs
100| stwu sp, -CFRAME_SPACE(sp)
101| save_ r14; save_ r15; save_ r16; save_ r17; save_ r18; save_ r19
102| mflr r0; mfcr r12
103| save_ r20; save_ r21; save_ r22; save_ r23; save_ r24; save_ r25
104| stw r0, SAVE_LR; stw r12, SAVE_CR
105| save_ r26; save_ r27; save_ r28; save_ r29; save_ r30; save_ r31
106|.endmacro
107|
108|.macro restoreregs
109| lwz r0, SAVE_LR; lwz r12, SAVE_CR
110| rest_ r14; rest_ r15; rest_ r16; rest_ r17; rest_ r18; rest_ r19
111| mtlr r0; mtcrf 0x38, r12
112| rest_ r20; rest_ r21; rest_ r22; rest_ r23; rest_ r24; rest_ r25
113| rest_ r26; rest_ r27; rest_ r28; rest_ r29; rest_ r30; rest_ r31
114| addi sp, sp, CFRAME_SPACE
115|.endmacro
116|
117|// Type definitions. Some of these are only used for documentation.
118|.type L, lua_State, LREG
119|.type GL, global_State
120|.type TVALUE, TValue
121|.type GCOBJ, GCobj
122|.type STR, GCstr
123|.type TAB, GCtab
124|.type LFUNC, GCfuncL
125|.type CFUNC, GCfuncC
126|.type PROTO, GCproto
127|.type UPVAL, GCupval
128|.type NODE, Node
129|.type NARGS8, int
130|.type TRACE, GCtrace
131|
132|//-----------------------------------------------------------------------
133|
134|// These basic macros should really be part of DynASM.
135|.macro srwi, rx, ry, n; rlwinm rx, ry, 32-n, n, 31; .endmacro
136|.macro slwi, rx, ry, n; rlwinm rx, ry, n, 0, 31-n; .endmacro
137|.macro rotlwi, rx, ry, n; rlwinm rx, ry, n, 0, 31; .endmacro
138|.macro rotlw, rx, ry, rn; rlwnm rx, ry, rn, 0, 31; .endmacro
139|.macro subi, rx, ry, i; addi rx, ry, -i; .endmacro
140|
141|// Trap for not-yet-implemented parts.
142|.macro NYI; tw 4, sp, sp; .endmacro
143|
144|//-----------------------------------------------------------------------
145|
146|// Access to frame relative to BASE.
147|.define FRAME_PC, -8
148|.define FRAME_FUNC, -4
149|
150|// Instruction decode.
151|.macro decode_OP4, dst, ins; rlwinm dst, ins, 2, 22, 29; .endmacro
152|.macro decode_RA8, dst, ins; rlwinm dst, ins, 27, 21, 28; .endmacro
153|.macro decode_RB8, dst, ins; rlwinm dst, ins, 11, 21, 28; .endmacro
154|.macro decode_RC8, dst, ins; rlwinm dst, ins, 19, 21, 28; .endmacro
155|.macro decode_RD8, dst, ins; rlwinm dst, ins, 19, 13, 28; .endmacro
156|
157|.macro decode_OP1, dst, ins; rlwinm dst, ins, 0, 24, 31; .endmacro
158|.macro decode_RD4, dst, ins; rlwinm dst, ins, 18, 14, 29; .endmacro
159|
160|// Instruction fetch.
161|.macro ins_NEXT1
162| lwz INS, 0(PC)
163| addi PC, PC, 4
164|.endmacro
165|// Instruction decode+dispatch.
166|.macro ins_NEXT2
167| decode_OP4 TMP1, INS
168| decode_RB8 RB, INS
169| decode_RD8 RD, INS
170| lwzx TMP0, DISPATCH, TMP1
171| decode_RA8 RA, INS
172| decode_RC8 RC, INS
173| mtctr TMP0
174| bctr
175|.endmacro
176|.macro ins_NEXT
177| ins_NEXT1
178| ins_NEXT2
179|.endmacro
180|
181|// Instruction footer.
182|.if 1
183| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
184| .define ins_next, ins_NEXT
185| .define ins_next_, ins_NEXT
186| .define ins_next1, ins_NEXT1
187| .define ins_next2, ins_NEXT2
188|.else
189| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
190| // Affects only certain kinds of benchmarks (and only with -j off).
191| .macro ins_next
192| b ->ins_next
193| .endmacro
194| .macro ins_next1
195| .endmacro
196| .macro ins_next2
197| b ->ins_next
198| .endmacro
199| .macro ins_next_
200| ->ins_next:
201| ins_NEXT
202| .endmacro
203|.endif
204|
205|// Call decode and dispatch.
206|.macro ins_callt
207| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
208| lwz PC, LFUNC:RB->pc
209| lwz INS, 0(PC)
210| addi PC, PC, 4
211| decode_OP4 TMP1, INS
212| decode_RA8 RA, INS
213| lwzx TMP0, DISPATCH, TMP1
214| add RA, RA, BASE
215| mtctr TMP0
216| bctr
217|.endmacro
218|
219|.macro ins_call
220| // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, PC = caller PC
221| stw PC, FRAME_PC(BASE)
222| ins_callt
223|.endmacro
224|
225|//-----------------------------------------------------------------------
226|
227|// Macros to test operand types.
228|.macro checknum, reg; evcmpltu reg, TISNUM; .endmacro
229|.macro checkstr, reg; evcmpeq reg, TISSTR; .endmacro
230|.macro checktab, reg; evcmpeq reg, TISTAB; .endmacro
231|.macro checkfunc, reg; evcmpeq reg, TISFUNC; .endmacro
232|.macro checknil, reg; evcmpeq reg, TISNIL; .endmacro
233|.macro checkok, label; blt label; .endmacro
234|.macro checkfail, label; bge label; .endmacro
235|.macro checkanyfail, label; bns label; .endmacro
236|.macro checkallok, label; bso label; .endmacro
237|
238|.macro branch_RD
239| srwi TMP0, RD, 1
240| add PC, PC, TMP0
241| addis PC, PC, -(BCBIAS_J*4 >> 16)
242|.endmacro
243|
244|// Assumes DISPATCH is relative to GL.
245#define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field))
246#define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field))
247|
248#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
249|
250|.macro hotloop
251| NYI
252|.endmacro
253|
254|.macro hotcall
255| NYI
256|.endmacro
257|
258|// Set current VM state. Uses TMP0.
259|.macro li_vmstate, st; li TMP0, ~LJ_VMST_..st; .endmacro
260|.macro st_vmstate; stw TMP0, DISPATCH_GL(vmstate)(DISPATCH); .endmacro
261|
262|// Move table write barrier back. Overwrites mark and tmp.
263|.macro barrierback, tab, mark, tmp
264| lwz tmp, DISPATCH_GL(gc.grayagain)(DISPATCH)
265| // Assumes LJ_GC_BLACK is 0x04.
266| rlwinm mark, mark, 0, 30, 28 // black2gray(tab)
267| stw tab, DISPATCH_GL(gc.grayagain)(DISPATCH)
268| stb mark, tab->marked
269| stw tmp, tab->gclist
270|.endmacro
271|
272|//-----------------------------------------------------------------------
273
274/* Generate subroutines used by opcodes and other parts of the VM. */
275/* The .code_sub section should be last to help static branch prediction. */
276static void build_subroutines(BuildCtx *ctx)
277{
278 |.code_sub
279 |
280 |//-----------------------------------------------------------------------
281 |//-- Return handling ----------------------------------------------------
282 |//-----------------------------------------------------------------------
283 |
284 |->vm_returnp:
285 | // See vm_return. Also: TMP2 = previous base.
286 | andi. TMP0, PC, FRAME_P
287 | evsplati TMP1, LJ_TTRUE
288 | beq ->cont_dispatch
289 |
290 | // Return from pcall or xpcall fast func.
291 | lwz PC, FRAME_PC(TMP2) // Fetch PC of previous frame.
292 | mr BASE, TMP2 // Restore caller base.
293 | // Prepending may overwrite the pcall frame, so do it at the end.
294 | stwu TMP1, FRAME_PC(RA) // Prepend true to results.
295 |
296 |->vm_returnc:
297 | addi RD, RD, 8 // RD = (nresults+1)*8.
298 | andi. TMP0, PC, FRAME_TYPE
299 | cmpwi cr1, RD, 0
300 | li CRET1, LUA_YIELD
301 | beq cr1, ->vm_unwind_c_eh
302 | mr MULTRES, RD
303 | beq ->BC_RET_Z // Handle regular return to Lua.
304 |
305 |->vm_return:
306 | // BASE = base, RA = resultptr, RD/MULTRES = (nresults+1)*8, PC = return
307 | // TMP0 = PC & FRAME_TYPE
308 | cmpwi TMP0, FRAME_C
309 | rlwinm TMP2, PC, 0, 0, 28
310 | li_vmstate C
311 | sub TMP2, BASE, TMP2 // TMP2 = previous base.
312 | bne ->vm_returnp
313 |
314 | addic. TMP1, RD, -8
315 | stw TMP2, L->base
316 | lwz TMP2, SAVE_NRES
317 | subi BASE, BASE, 8
318 | st_vmstate
319 | slwi TMP2, TMP2, 3
320 | beq >2
321 |1:
322 | addic. TMP1, TMP1, -8
323 | evldd TMP0, 0(RA)
324 | addi RA, RA, 8
325 | evstdd TMP0, 0(BASE)
326 | addi BASE, BASE, 8
327 | bne <1
328 |
329 |2:
330 | cmpw TMP2, RD // More/less results wanted?
331 | bne >6
332 |3:
333 | stw BASE, L->top // Store new top.
334 |
335 |->vm_leave_cp:
336 | lwz TMP0, SAVE_CFRAME // Restore previous C frame.
337 | li CRET1, 0 // Ok return status for vm_pcall.
338 | stw TMP0, L->cframe
339 |
340 |->vm_leave_unw:
341 | restoreregs
342 | blr
343 |
344 |6:
345 | ble >7 // Less results wanted?
346 | // More results wanted. Check stack size and fill up results with nil.
347 | lwz TMP1, L->maxstack
348 | cmplw BASE, TMP1
349 | bge >8
350 | evstdd TISNIL, 0(BASE)
351 | addi RD, RD, 8
352 | addi BASE, BASE, 8
353 | b <2
354 |
355 |7: // Less results wanted.
356 | sub TMP0, RD, TMP2
357 | cmpwi TMP2, 0 // LUA_MULTRET+1 case?
358 | sub TMP0, BASE, TMP0 // Subtract the difference.
359 | iseleq BASE, BASE, TMP0 // Either keep top or shrink it.
360 | b <3
361 |
362 |8: // Corner case: need to grow stack for filling up results.
363 | // This can happen if:
364 | // - A C function grows the stack (a lot).
365 | // - The GC shrinks the stack in between.
366 | // - A return back from a lua_call() with (high) nresults adjustment.
367 | stw BASE, L->top // Save current top held in BASE (yes).
368 | mr SAVE0, RD
369 | mr CARG2, TMP2
370 | mr CARG1, L
371 | bl extern lj_state_growstack // (lua_State *L, int n)
372 | lwz TMP2, SAVE_NRES
373 | mr RD, SAVE0
374 | slwi TMP2, TMP2, 3
375 | lwz BASE, L->top // Need the (realloced) L->top in BASE.
376 | b <2
377 |
378 |->vm_unwind_c: // Unwind C stack, return from vm_pcall.
379 | // (void *cframe, int errcode)
380 | mr sp, CARG1
381 | mr CRET1, CARG2
382 |->vm_unwind_c_eh: // Landing pad for external unwinder.
383 | lwz L, SAVE_L
384 | li TMP0, ~LJ_VMST_C
385 | lwz GL:TMP1, L->glref
386 | stw TMP0, GL:TMP1->vmstate
387 | b ->vm_leave_unw
388 |
389 |->vm_unwind_ff: // Unwind C stack, return from ff pcall.
390 | // (void *cframe)
391 | rlwinm sp, CARG1, 0, 0, 29
392 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
393 | lwz L, SAVE_L
394 | evsplati TISNUM, LJ_TISNUM+1 // Setup type comparison constants.
395 | evsplati TISFUNC, LJ_TFUNC
396 | lus TOBIT, 0x4338
397 | evsplati TISTAB, LJ_TTAB
398 | li TMP0, 0
399 | lwz BASE, L->base
400 | evmergelo TOBIT, TOBIT, TMP0
401 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
402 | evsplati TISSTR, LJ_TSTR
403 | li TMP1, LJ_TFALSE
404 | evsplati TISNIL, LJ_TNIL
405 | li_vmstate INTERP
406 | lwz PC, FRAME_PC(BASE) // Fetch PC of previous frame.
407 | la RA, -8(BASE) // Results start at BASE-8.
408 | addi DISPATCH, DISPATCH, GG_G2DISP
409 | stw TMP1, 0(RA) // Prepend false to error message.
410 | li RD, 16 // 2 results: false + error message.
411 | st_vmstate
412 | b ->vm_returnc
413 |
414 |//-----------------------------------------------------------------------
415 |//-- Grow stack for calls -----------------------------------------------
416 |//-----------------------------------------------------------------------
417 |
418 |->vm_growstack_c: // Grow stack for C function.
419 | li CARG2, LUA_MINSTACK
420 | b >2
421 |
422 |->vm_growstack_l: // Grow stack for Lua function.
423 | // BASE = new base, RA = BASE+framesize*8, RC = nargs*8, PC = first PC
424 | add RC, BASE, RC
425 | sub RA, RA, BASE
426 | stw BASE, L->base
427 | addi PC, PC, 4 // Must point after first instruction.
428 | stw RC, L->top
429 | srwi CARG2, RA, 3
430 |2:
431 | // L->base = new base, L->top = top
432 | stw PC, SAVE_PC
433 | mr CARG1, L
434 | bl extern lj_state_growstack // (lua_State *L, int n)
435 | lwz BASE, L->base
436 | lwz RC, L->top
437 | lwz LFUNC:RB, FRAME_FUNC(BASE)
438 | sub RC, RC, BASE
439 | // BASE = new base, RB = LFUNC/CFUNC, RC = nargs*8, FRAME_PC(BASE) = PC
440 | ins_callt // Just retry the call.
441 |
442 |//-----------------------------------------------------------------------
443 |//-- Entry points into the assembler VM ---------------------------------
444 |//-----------------------------------------------------------------------
445 |
446 |->vm_resume: // Setup C frame and resume thread.
447 | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
448 | saveregs
449 | mr L, CARG1
450 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
451 | mr BASE, CARG2
452 | lbz TMP1, L->status
453 | stw L, SAVE_L
454 | li PC, FRAME_CP
455 | addi TMP0, sp, CFRAME_RESUME
456 | addi DISPATCH, DISPATCH, GG_G2DISP
457 | stw CARG3, SAVE_NRES
458 | cmplwi TMP1, 0
459 | stw CARG3, SAVE_ERRF
460 | stw TMP0, L->cframe
461 | stw CARG3, SAVE_CFRAME
462 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
463 | beq >3
464 |
465 | // Resume after yield (like a return).
466 | mr RA, BASE
467 | lwz BASE, L->base
468 | evsplati TISNUM, LJ_TISNUM+1 // Setup type comparison constants.
469 | lwz TMP1, L->top
470 | evsplati TISFUNC, LJ_TFUNC
471 | lus TOBIT, 0x4338
472 | evsplati TISTAB, LJ_TTAB
473 | lwz PC, FRAME_PC(BASE)
474 | li TMP2, 0
475 | evsplati TISSTR, LJ_TSTR
476 | sub RD, TMP1, BASE
477 | evmergelo TOBIT, TOBIT, TMP2
478 | stb CARG3, L->status
479 | andi. TMP0, PC, FRAME_TYPE
480 | li_vmstate INTERP
481 | addi RD, RD, 8
482 | evsplati TISNIL, LJ_TNIL
483 | mr MULTRES, RD
484 | st_vmstate
485 | beq ->BC_RET_Z
486 | b ->vm_return
487 |
488 |->vm_pcall: // Setup protected C frame and enter VM.
489 | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
490 | saveregs
491 | li PC, FRAME_CP
492 | stw CARG4, SAVE_ERRF
493 | b >1
494 |
495 |->vm_call: // Setup C frame and enter VM.
496 | // (lua_State *L, TValue *base, int nres1)
497 | saveregs
498 | li PC, FRAME_C
499 |
500 |1: // Entry point for vm_pcall above (PC = ftype).
501 | lwz TMP1, L:CARG1->cframe
502 | stw CARG3, SAVE_NRES
503 | mr L, CARG1
504 | stw CARG1, SAVE_L
505 | mr BASE, CARG2
506 | stw sp, L->cframe // Add our C frame to cframe chain.
507 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
508 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
509 | stw TMP1, SAVE_CFRAME
510 | addi DISPATCH, DISPATCH, GG_G2DISP
511 |
512 |3: // Entry point for vm_cpcall/vm_resume (BASE = base, PC = ftype).
513 | lwz TMP2, L->base // TMP2 = old base (used in vmeta_call).
514 | evsplati TISNUM, LJ_TISNUM+1 // Setup type comparison constants.
515 | lwz TMP1, L->top
516 | evsplati TISFUNC, LJ_TFUNC
517 | add PC, PC, BASE
518 | evsplati TISTAB, LJ_TTAB
519 | lus TOBIT, 0x4338
520 | li TMP0, 0
521 | sub PC, PC, TMP2 // PC = frame delta + frame type
522 | evsplati TISSTR, LJ_TSTR
523 | sub NARGS8:RC, TMP1, BASE
524 | evmergelo TOBIT, TOBIT, TMP0
525 | li_vmstate INTERP
526 | evsplati TISNIL, LJ_TNIL
527 | st_vmstate
528 |
529 |->vm_call_dispatch:
530 | // TMP2 = old base, BASE = new base, RC = nargs*8, PC = caller PC
531 | li TMP0, -8
532 | evlddx LFUNC:RB, BASE, TMP0
533 | checkfunc LFUNC:RB
534 | checkfail ->vmeta_call
535 |
536 |->vm_call_dispatch_f:
537 | ins_call
538 | // BASE = new base, RB = func, RC = nargs*8, PC = caller PC
539 |
540 |->vm_cpcall: // Setup protected C frame, call C.
541 | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
542 | saveregs
543 | mr L, CARG1
544 | lwz TMP0, L:CARG1->stack
545 | stw CARG1, SAVE_L
546 | lwz TMP1, L->top
547 | stw CARG1, SAVE_PC // Any value outside of bytecode is ok.
548 | sub TMP0, TMP0, TMP1 // Compute -savestack(L, L->top).
549 | lwz TMP1, L->cframe
550 | stw sp, L->cframe // Add our C frame to cframe chain.
551 | li TMP2, 0
552 | stw TMP0, SAVE_NRES // Neg. delta means cframe w/o frame.
553 | stw TMP2, SAVE_ERRF // No error function.
554 | stw TMP1, SAVE_CFRAME
555 | mtctr CARG4
556 | bctrl // (lua_State *L, lua_CFunction func, void *ud)
557 | mr. BASE, CRET1
558 | lwz DISPATCH, L->glref // Setup pointer to dispatch table.
559 | li PC, FRAME_CP
560 | addi DISPATCH, DISPATCH, GG_G2DISP
561 | bne <3 // Else continue with the call.
562 | b ->vm_leave_cp // No base? Just remove C frame.
563 |
564 |//-----------------------------------------------------------------------
565 |//-- Metamethod handling ------------------------------------------------
566 |//-----------------------------------------------------------------------
567 |
568 |// The lj_meta_* functions (except for lj_meta_cat) don't reallocate the
569 |// stack, so BASE doesn't need to be reloaded across these calls.
570 |
571 |//-- Continuation dispatch ----------------------------------------------
572 |
573 |->cont_dispatch:
574 | // BASE = meta base, RA = resultptr, RD = (nresults+1)*8
575 | lwz TMP0, -12(BASE) // Continuation.
576 | mr RB, BASE
577 | mr BASE, TMP2 // Restore caller BASE.
578 | lwz LFUNC:TMP1, FRAME_FUNC(TMP2)
579 | cmplwi TMP0, 0
580 | lwz PC, -16(RB) // Restore PC from [cont|PC].
581 | beq >1
582 | subi TMP2, RD, 8
583 | lwz TMP1, LFUNC:TMP1->pc
584 | evstddx TISNIL, RA, TMP2 // Ensure one valid arg.
585 | lwz KBASE, PC2PROTO(k)(TMP1)
586 | // BASE = base, RA = resultptr, RB = meta base
587 | mtctr TMP0
588 | bctr // Jump to continuation.
589 |
590 |1: // Tail call from C function.
591 | subi TMP1, RB, 16
592 | sub RC, TMP1, BASE
593 | b ->vm_call_tail
594 |
595 |->cont_cat: // RA = resultptr, RB = meta base
596 | lwz INS, -4(PC)
597 | subi CARG2, RB, 16
598 | decode_RB8 SAVE0, INS
599 | evldd TMP0, 0(RA)
600 | add TMP1, BASE, SAVE0
601 | stw BASE, L->base
602 | cmplw TMP1, CARG2
603 | sub CARG3, CARG2, TMP1
604 | decode_RA8 RA, INS
605 | evstdd TMP0, 0(CARG2)
606 | bne ->BC_CAT_Z
607 | evstddx TMP0, BASE, RA
608 | b ->cont_nop
609 |
610 |//-- Table indexing metamethods -----------------------------------------
611 |
612 |->vmeta_tgets1:
613 | evmergelo STR:RC, TISSTR, STR:RC
614 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
615 | decode_RB8 RB, INS
616 | evstdd STR:RC, 0(CARG3)
617 | add CARG2, BASE, RB
618 | b >1
619 |
620 |->vmeta_tgets:
621 | evmergelo TAB:RB, TISTAB, TAB:RB
622 | la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
623 | evmergelo STR:RC, TISSTR, STR:RC
624 | evstdd TAB:RB, 0(CARG2)
625 | la CARG3, DISPATCH_GL(tmptv2)(DISPATCH)
626 | evstdd STR:RC, 0(CARG3)
627 | b >1
628 |
629 |->vmeta_tgetb: // TMP0 = index
630 | efdcfsi TMP0, TMP0
631 | decode_RB8 RB, INS
632 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
633 | add CARG2, BASE, RB
634 | evstdd TMP0, 0(CARG3)
635 | b >1
636 |
637 |->vmeta_tgetv:
638 | decode_RB8 RB, INS
639 | decode_RC8 RC, INS
640 | add CARG2, BASE, RB
641 | add CARG3, BASE, RC
642 |1:
643 | stw BASE, L->base
644 | mr CARG1, L
645 | stw PC, SAVE_PC
646 | bl extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
647 | // Returns TValue * (finished) or NULL (metamethod).
648 | cmplwi CRET1, 0
649 | beq >3
650 | evldd TMP0, 0(CRET1)
651 | evstddx TMP0, BASE, RA
652 | ins_next
653 |
654 |3: // Call __index metamethod.
655 | // BASE = base, L->top = new base, stack = cont/func/t/k
656 | subfic TMP1, BASE, FRAME_CONT
657 | lwz BASE, L->top
658 | stw PC, -16(BASE) // [cont|PC]
659 | add PC, TMP1, BASE
660 | lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
661 | li NARGS8:RC, 16 // 2 args for func(t, k).
662 | b ->vm_call_dispatch_f
663 |
664 |//-----------------------------------------------------------------------
665 |
666 |->vmeta_tsets1:
667 | evmergelo STR:RC, TISSTR, STR:RC
668 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
669 | decode_RB8 RB, INS
670 | evstdd STR:RC, 0(CARG3)
671 | add CARG2, BASE, RB
672 | b >1
673 |
674 |->vmeta_tsets:
675 | evmergelo TAB:RB, TISTAB, TAB:RB
676 | la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
677 | evmergelo STR:RC, TISSTR, STR:RC
678 | evstdd TAB:RB, 0(CARG2)
679 | la CARG3, DISPATCH_GL(tmptv2)(DISPATCH)
680 | evstdd STR:RC, 0(CARG3)
681 | b >1
682 |
683 |->vmeta_tsetb: // TMP0 = index
684 | efdcfsi TMP0, TMP0
685 | decode_RB8 RB, INS
686 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
687 | add CARG2, BASE, RB
688 | evstdd TMP0, 0(CARG3)
689 | b >1
690 |
691 |->vmeta_tsetv:
692 | decode_RB8 RB, INS
693 | decode_RC8 RC, INS
694 | add CARG2, BASE, RB
695 | add CARG3, BASE, RC
696 |1:
697 | stw BASE, L->base
698 | mr CARG1, L
699 | stw PC, SAVE_PC
700 | bl extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
701 | // Returns TValue * (finished) or NULL (metamethod).
702 | cmplwi CRET1, 0
703 | evlddx TMP0, BASE, RA
704 | beq >3
705 | // NOBARRIER: lj_meta_tset ensures the table is not black.
706 | evstdd TMP0, 0(CRET1)
707 | ins_next
708 |
709 |3: // Call __newindex metamethod.
710 | // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
711 | subfic TMP1, BASE, FRAME_CONT
712 | lwz BASE, L->top
713 | stw PC, -16(BASE) // [cont|PC]
714 | add PC, TMP1, BASE
715 | lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
716 | li NARGS8:RC, 24 // 3 args for func(t, k, v)
717 | evstdd TMP0, 16(BASE) // Copy value to third argument.
718 | b ->vm_call_dispatch_f
719 |
720 |//-- Comparison metamethods ---------------------------------------------
721 |
722 |->vmeta_comp:
723 | mr CARG1, L
724 | subi PC, PC, 4
725 | add CARG2, BASE, RA
726 | stw PC, SAVE_PC
727 | add CARG3, BASE, RD
728 | stw BASE, L->base
729 | decode_OP1 CARG4, INS
730 | bl extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
731 | // Returns 0/1 or TValue * (metamethod).
732 |3:
733 | cmplwi CRET1, 1
734 | bgt ->vmeta_binop
735 |4:
736 | lwz INS, 0(PC)
737 | addi PC, PC, 4
738 | decode_RD4 TMP2, INS
739 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
740 | add TMP2, TMP2, TMP3
741 | isellt PC, PC, TMP2
742 |->cont_nop:
743 | ins_next
744 |
745 |->cont_ra: // RA = resultptr
746 | lwz INS, -4(PC)
747 | evldd TMP0, 0(RA)
748 | decode_RA8 TMP1, INS
749 | evstddx TMP0, BASE, TMP1
750 | b ->cont_nop
751 |
752 |->cont_condt: // RA = resultptr
753 | lwz TMP0, 0(RA)
754 | li TMP1, LJ_TTRUE
755 | cmplw TMP1, TMP0 // Branch if result is true.
756 | b <4
757 |
758 |->cont_condf: // RA = resultptr
759 | lwz TMP0, 0(RA)
760 | li TMP1, LJ_TFALSE
761 | cmplw TMP0, TMP1 // Branch if result is false.
762 | b <4
763 |
764 |->vmeta_equal:
765 | // CARG2, CARG3, CARG4 are already set by BC_ISEQV/BC_ISNEV.
766 | subi PC, PC, 4
767 | stw BASE, L->base
768 | mr CARG1, L
769 | stw PC, SAVE_PC
770 | bl extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
771 | // Returns 0/1 or TValue * (metamethod).
772 | b <3
773 |
774 |//-- Arithmetic metamethods ---------------------------------------------
775 |
776 |->vmeta_arith_vn:
777 | add CARG3, BASE, RB
778 | add CARG4, KBASE, RC
779 | b >1
780 |
781 |->vmeta_arith_nv:
782 | add CARG3, KBASE, RC
783 | add CARG4, BASE, RB
784 | b >1
785 |
786 |->vmeta_unm:
787 | add CARG3, BASE, RD
788 | mr CARG4, CARG3
789 | b >1
790 |
791 |->vmeta_arith_vv:
792 | add CARG3, BASE, RB
793 | add CARG4, BASE, RC
794 |1:
795 | add CARG2, BASE, RA
796 | stw BASE, L->base
797 | mr CARG1, L
798 | stw PC, SAVE_PC
799 | decode_OP1 CARG5, INS // Caveat: CARG5 overlaps INS.
800 | bl extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
801 | // Returns NULL (finished) or TValue * (metamethod).
802 | cmplwi CRET1, 0
803 | beq ->cont_nop
804 |
805 | // Call metamethod for binary op.
806 |->vmeta_binop:
807 | // BASE = old base, CRET1 = new base, stack = cont/func/o1/o2
808 | sub TMP1, CRET1, BASE
809 | stw PC, -16(CRET1) // [cont|PC]
810 | mr TMP2, BASE
811 | addi PC, TMP1, FRAME_CONT
812 | mr BASE, CRET1
813 | li NARGS8:RC, 16 // 2 args for func(o1, o2).
814 | b ->vm_call_dispatch
815 |
816 |->vmeta_len:
817#if LJ_52
818 | mr SAVE0, CARG1
819#endif
820 | add CARG2, BASE, RD
821 | stw BASE, L->base
822 | mr CARG1, L
823 | stw PC, SAVE_PC
824 | bl extern lj_meta_len // (lua_State *L, TValue *o)
825 | // Returns NULL (retry) or TValue * (metamethod base).
826#if LJ_52
827 | cmplwi CRET1, 0
828 | bne ->vmeta_binop // Binop call for compatibility.
829 | mr CARG1, SAVE0
830 | b ->BC_LEN_Z
831#else
832 | b ->vmeta_binop // Binop call for compatibility.
833#endif
834 |
835 |//-- Call metamethod ----------------------------------------------------
836 |
837 |->vmeta_call: // Resolve and call __call metamethod.
838 | // TMP2 = old base, BASE = new base, RC = nargs*8
839 | mr CARG1, L
840 | stw TMP2, L->base // This is the callers base!
841 | subi CARG2, BASE, 8
842 | stw PC, SAVE_PC
843 | add CARG3, BASE, RC
844 | mr SAVE0, NARGS8:RC
845 | bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
846 | lwz LFUNC:RB, FRAME_FUNC(BASE) // Guaranteed to be a function here.
847 | addi NARGS8:RC, SAVE0, 8 // Got one more argument now.
848 | ins_call
849 |
850 |->vmeta_callt: // Resolve __call for BC_CALLT.
851 | // BASE = old base, RA = new base, RC = nargs*8
852 | mr CARG1, L
853 | stw BASE, L->base
854 | subi CARG2, RA, 8
855 | stw PC, SAVE_PC
856 | add CARG3, RA, RC
857 | mr SAVE0, NARGS8:RC
858 | bl extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
859 | lwz TMP1, FRAME_PC(BASE)
860 | addi NARGS8:RC, SAVE0, 8 // Got one more argument now.
861 | lwz LFUNC:RB, FRAME_FUNC(RA) // Guaranteed to be a function here.
862 | b ->BC_CALLT_Z
863 |
864 |//-- Argument coercion for 'for' statement ------------------------------
865 |
866 |->vmeta_for:
867 | mr CARG1, L
868 | stw BASE, L->base
869 | mr CARG2, RA
870 | stw PC, SAVE_PC
871 | mr SAVE0, INS
872 | bl extern lj_meta_for // (lua_State *L, TValue *base)
873 |.if JIT
874 | decode_OP1 TMP0, SAVE0
875 |.endif
876 | decode_RA8 RA, SAVE0
877 |.if JIT
878 | cmpwi TMP0, BC_JFORI
879 |.endif
880 | decode_RD8 RD, SAVE0
881 |.if JIT
882 | beq =>BC_JFORI
883 |.endif
884 | b =>BC_FORI
885 |
886 |//-----------------------------------------------------------------------
887 |//-- Fast functions -----------------------------------------------------
888 |//-----------------------------------------------------------------------
889 |
890 |.macro .ffunc, name
891 |->ff_ .. name:
892 |.endmacro
893 |
894 |.macro .ffunc_1, name
895 |->ff_ .. name:
896 | cmplwi NARGS8:RC, 8
897 | evldd CARG1, 0(BASE)
898 | blt ->fff_fallback
899 |.endmacro
900 |
901 |.macro .ffunc_2, name
902 |->ff_ .. name:
903 | cmplwi NARGS8:RC, 16
904 | evldd CARG1, 0(BASE)
905 | evldd CARG2, 8(BASE)
906 | blt ->fff_fallback
907 |.endmacro
908 |
909 |.macro .ffunc_n, name
910 | .ffunc_1 name
911 | checknum CARG1
912 | checkfail ->fff_fallback
913 |.endmacro
914 |
915 |.macro .ffunc_nn, name
916 | .ffunc_2 name
917 | evmergehi TMP0, CARG1, CARG2
918 | checknum TMP0
919 | checkanyfail ->fff_fallback
920 |.endmacro
921 |
922 |// Inlined GC threshold check. Caveat: uses TMP0 and TMP1.
923 |.macro ffgccheck
924 | lwz TMP0, DISPATCH_GL(gc.total)(DISPATCH)
925 | lwz TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
926 | cmplw TMP0, TMP1
927 | bgel ->fff_gcstep
928 |.endmacro
929 |
930 |//-- Base library: checks -----------------------------------------------
931 |
932 |.ffunc assert
933 | cmplwi NARGS8:RC, 8
934 | evldd TMP0, 0(BASE)
935 | blt ->fff_fallback
936 | evaddw TMP1, TISNIL, TISNIL // Synthesize LJ_TFALSE.
937 | la RA, -8(BASE)
938 | evcmpltu cr1, TMP0, TMP1
939 | lwz PC, FRAME_PC(BASE)
940 | bge cr1, ->fff_fallback
941 | evstdd TMP0, 0(RA)
942 | addi RD, NARGS8:RC, 8 // Compute (nresults+1)*8.
943 | beq ->fff_res // Done if exactly 1 argument.
944 | li TMP1, 8
945 | subi RC, RC, 8
946 |1:
947 | cmplw TMP1, RC
948 | evlddx TMP0, BASE, TMP1
949 | evstddx TMP0, RA, TMP1
950 | addi TMP1, TMP1, 8
951 | bne <1
952 | b ->fff_res
953 |
954 |.ffunc type
955 | cmplwi NARGS8:RC, 8
956 | lwz CARG1, 0(BASE)
957 | blt ->fff_fallback
958 | li TMP2, ~LJ_TNUMX
959 | cmplw CARG1, TISNUM
960 | not TMP1, CARG1
961 | isellt TMP1, TMP2, TMP1
962 | slwi TMP1, TMP1, 3
963 | la TMP2, CFUNC:RB->upvalue
964 | evlddx STR:CRET1, TMP2, TMP1
965 | b ->fff_restv
966 |
967 |//-- Base library: getters and setters ---------------------------------
968 |
969 |.ffunc_1 getmetatable
970 | checktab CARG1
971 | evmergehi TMP1, CARG1, CARG1
972 | checkfail >6
973 |1: // Field metatable must be at same offset for GCtab and GCudata!
974 | lwz TAB:RB, TAB:CARG1->metatable
975 |2:
976 | evmr CRET1, TISNIL
977 | cmplwi TAB:RB, 0
978 | lwz STR:RC, DISPATCH_GL(gcroot[GCROOT_MMNAME+MM_metatable])(DISPATCH)
979 | beq ->fff_restv
980 | lwz TMP0, TAB:RB->hmask
981 | evmergelo CRET1, TISTAB, TAB:RB // Use metatable as default result.
982 | lwz TMP1, STR:RC->hash
983 | lwz NODE:TMP2, TAB:RB->node
984 | evmergelo STR:RC, TISSTR, STR:RC
985 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
986 | slwi TMP0, TMP1, 5
987 | slwi TMP1, TMP1, 3
988 | sub TMP1, TMP0, TMP1
989 | add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
990 |3: // Rearranged logic, because we expect _not_ to find the key.
991 | evldd TMP0, NODE:TMP2->key
992 | evldd TMP1, NODE:TMP2->val
993 | evcmpeq TMP0, STR:RC
994 | lwz NODE:TMP2, NODE:TMP2->next
995 | checkallok >5
996 | cmplwi NODE:TMP2, 0
997 | beq ->fff_restv // Not found, keep default result.
998 | b <3
999 |5:
1000 | checknil TMP1
1001 | checkok ->fff_restv // Ditto for nil value.
1002 | evmr CRET1, TMP1 // Return value of mt.__metatable.
1003 | b ->fff_restv
1004 |
1005 |6:
1006 | cmpwi TMP1, LJ_TUDATA
1007 | not TMP1, TMP1
1008 | beq <1
1009 | checknum CARG1
1010 | slwi TMP1, TMP1, 2
1011 | li TMP2, 4*~LJ_TNUMX
1012 | isellt TMP1, TMP2, TMP1
1013 | la TMP2, DISPATCH_GL(gcroot[GCROOT_BASEMT])(DISPATCH)
1014 | lwzx TAB:RB, TMP2, TMP1
1015 | b <2
1016 |
1017 |.ffunc_2 setmetatable
1018 | // Fast path: no mt for table yet and not clearing the mt.
1019 | evmergehi TMP0, TAB:CARG1, TAB:CARG2
1020 | checktab TMP0
1021 | checkanyfail ->fff_fallback
1022 | lwz TAB:TMP1, TAB:CARG1->metatable
1023 | cmplwi TAB:TMP1, 0
1024 | lbz TMP3, TAB:CARG1->marked
1025 | bne ->fff_fallback
1026 | andi. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
1027 | stw TAB:CARG2, TAB:CARG1->metatable
1028 | beq ->fff_restv
1029 | barrierback TAB:CARG1, TMP3, TMP0
1030 | b ->fff_restv
1031 |
1032 |.ffunc rawget
1033 | cmplwi NARGS8:RC, 16
1034 | evldd CARG2, 0(BASE)
1035 | blt ->fff_fallback
1036 | checktab CARG2
1037 | la CARG3, 8(BASE)
1038 | checkfail ->fff_fallback
1039 | mr CARG1, L
1040 | bl extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
1041 | // Returns cTValue *.
1042 | evldd CRET1, 0(CRET1)
1043 | b ->fff_restv
1044 |
1045 |//-- Base library: conversions ------------------------------------------
1046 |
1047 |.ffunc tonumber
1048 | // Only handles the number case inline (without a base argument).
1049 | cmplwi NARGS8:RC, 8
1050 | evldd CARG1, 0(BASE)
1051 | bne ->fff_fallback // Exactly one argument.
1052 | checknum CARG1
1053 | checkok ->fff_restv
1054 | b ->fff_fallback
1055 |
1056 |.ffunc_1 tostring
1057 | // Only handles the string or number case inline.
1058 | checkstr CARG1
1059 | // A __tostring method in the string base metatable is ignored.
1060 | checkok ->fff_restv // String key?
1061 | // Handle numbers inline, unless a number base metatable is present.
1062 | lwz TMP0, DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])(DISPATCH)
1063 | checknum CARG1
1064 | cmplwi cr1, TMP0, 0
1065 | stw BASE, L->base // Add frame since C call can throw.
1066 | crand 4*cr0+eq, 4*cr0+lt, 4*cr1+eq
1067 | stw PC, SAVE_PC // Redundant (but a defined value).
1068 | bne ->fff_fallback
1069 | ffgccheck
1070 | mr CARG1, L
1071 | mr CARG2, BASE
1072 | bl extern lj_str_fromnum // (lua_State *L, lua_Number *np)
1073 | // Returns GCstr *.
1074 | evmergelo STR:CRET1, TISSTR, STR:CRET1
1075 | b ->fff_restv
1076 |
1077 |//-- Base library: iterators -------------------------------------------
1078 |
1079 |.ffunc next
1080 | cmplwi NARGS8:RC, 8
1081 | evldd CARG2, 0(BASE)
1082 | blt ->fff_fallback
1083 | evstddx TISNIL, BASE, NARGS8:RC // Set missing 2nd arg to nil.
1084 | checktab TAB:CARG2
1085 | lwz PC, FRAME_PC(BASE)
1086 | checkfail ->fff_fallback
1087 | stw BASE, L->base // Add frame since C call can throw.
1088 | mr CARG1, L
1089 | stw BASE, L->top // Dummy frame length is ok.
1090 | la CARG3, 8(BASE)
1091 | stw PC, SAVE_PC
1092 | bl extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key)
1093 | // Returns 0 at end of traversal.
1094 | cmplwi CRET1, 0
1095 | evmr CRET1, TISNIL
1096 | beq ->fff_restv // End of traversal: return nil.
1097 | evldd TMP0, 8(BASE) // Copy key and value to results.
1098 | la RA, -8(BASE)
1099 | evldd TMP1, 16(BASE)
1100 | evstdd TMP0, 0(RA)
1101 | li RD, (2+1)*8
1102 | evstdd TMP1, 8(RA)
1103 | b ->fff_res
1104 |
1105 |.ffunc_1 pairs
1106 | checktab TAB:CARG1
1107 | lwz PC, FRAME_PC(BASE)
1108 | checkfail ->fff_fallback
1109#if LJ_52
1110 | lwz TAB:TMP2, TAB:CARG1->metatable
1111 | evldd CFUNC:TMP0, CFUNC:RB->upvalue[0]
1112 | cmplwi TAB:TMP2, 0
1113 | la RA, -8(BASE)
1114 | bne ->fff_fallback
1115#else
1116 | evldd CFUNC:TMP0, CFUNC:RB->upvalue[0]
1117 | la RA, -8(BASE)
1118#endif
1119 | evstdd TISNIL, 8(BASE)
1120 | li RD, (3+1)*8
1121 | evstdd CFUNC:TMP0, 0(RA)
1122 | b ->fff_res
1123 |
1124 |.ffunc_2 ipairs_aux
1125 | checktab TAB:CARG1
1126 | lwz PC, FRAME_PC(BASE)
1127 | checkfail ->fff_fallback
1128 | checknum CARG2
1129 | lus TMP3, 0x3ff0
1130 | checkfail ->fff_fallback
1131 | efdctsi TMP2, CARG2
1132 | lwz TMP0, TAB:CARG1->asize
1133 | evmergelo TMP3, TMP3, ZERO
1134 | lwz TMP1, TAB:CARG1->array
1135 | efdadd CARG2, CARG2, TMP3
1136 | addi TMP2, TMP2, 1
1137 | la RA, -8(BASE)
1138 | cmplw TMP0, TMP2
1139 | slwi TMP3, TMP2, 3
1140 | evstdd CARG2, 0(RA)
1141 | ble >2 // Not in array part?
1142 | evlddx TMP1, TMP1, TMP3
1143 |1:
1144 | checknil TMP1
1145 | li RD, (0+1)*8
1146 | checkok ->fff_res // End of iteration, return 0 results.
1147 | li RD, (2+1)*8
1148 | evstdd TMP1, 8(RA)
1149 | b ->fff_res
1150 |2: // Check for empty hash part first. Otherwise call C function.
1151 | lwz TMP0, TAB:CARG1->hmask
1152 | cmplwi TMP0, 0
1153 | li RD, (0+1)*8
1154 | beq ->fff_res
1155 | mr CARG2, TMP2
1156 | bl extern lj_tab_getinth // (GCtab *t, int32_t key)
1157 | // Returns cTValue * or NULL.
1158 | cmplwi CRET1, 0
1159 | li RD, (0+1)*8
1160 | beq ->fff_res
1161 | evldd TMP1, 0(CRET1)
1162 | b <1
1163 |
1164 |.ffunc_1 ipairs
1165 | checktab TAB:CARG1
1166 | lwz PC, FRAME_PC(BASE)
1167 | checkfail ->fff_fallback
1168#if LJ_52
1169 | lwz TAB:TMP2, TAB:CARG1->metatable
1170 | evldd CFUNC:TMP0, CFUNC:RB->upvalue[0]
1171 | cmplwi TAB:TMP2, 0
1172 | la RA, -8(BASE)
1173 | bne ->fff_fallback
1174#else
1175 | evldd CFUNC:TMP0, CFUNC:RB->upvalue[0]
1176 | la RA, -8(BASE)
1177#endif
1178 | evsplati TMP1, 0
1179 | li RD, (3+1)*8
1180 | evstdd TMP1, 8(BASE)
1181 | evstdd CFUNC:TMP0, 0(RA)
1182 | b ->fff_res
1183 |
1184 |//-- Base library: catch errors ----------------------------------------
1185 |
1186 |.ffunc pcall
1187 | cmplwi NARGS8:RC, 8
1188 | lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
1189 | blt ->fff_fallback
1190 | mr TMP2, BASE
1191 | la BASE, 8(BASE)
1192 | // Remember active hook before pcall.
1193 | rlwinm TMP3, TMP3, 32-HOOK_ACTIVE_SHIFT, 31, 31
1194 | subi NARGS8:RC, NARGS8:RC, 8
1195 | addi PC, TMP3, 8+FRAME_PCALL
1196 | b ->vm_call_dispatch
1197 |
1198 |.ffunc_2 xpcall
1199 | lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
1200 | mr TMP2, BASE
1201 | checkfunc CARG2 // Traceback must be a function.
1202 | checkfail ->fff_fallback
1203 | la BASE, 16(BASE)
1204 | // Remember active hook before pcall.
1205 | rlwinm TMP3, TMP3, 32-HOOK_ACTIVE_SHIFT, 31, 31
1206 | evstdd CARG2, 0(TMP2) // Swap function and traceback.
1207 | subi NARGS8:RC, NARGS8:RC, 16
1208 | evstdd CARG1, 8(TMP2)
1209 | addi PC, TMP3, 16+FRAME_PCALL
1210 | b ->vm_call_dispatch
1211 |
1212 |//-- Coroutine library --------------------------------------------------
1213 |
1214 |.macro coroutine_resume_wrap, resume
1215 |.if resume
1216 |.ffunc_1 coroutine_resume
1217 | evmergehi TMP0, L:CARG1, L:CARG1
1218 |.else
1219 |.ffunc coroutine_wrap_aux
1220 | lwz L:CARG1, CFUNC:RB->upvalue[0].gcr
1221 |.endif
1222 |.if resume
1223 | cmpwi TMP0, LJ_TTHREAD
1224 | bne ->fff_fallback
1225 |.endif
1226 | lbz TMP0, L:CARG1->status
1227 | lwz TMP1, L:CARG1->cframe
1228 | lwz CARG2, L:CARG1->top
1229 | cmplwi cr0, TMP0, LUA_YIELD
1230 | lwz TMP2, L:CARG1->base
1231 | cmplwi cr1, TMP1, 0
1232 | lwz TMP0, L:CARG1->maxstack
1233 | cmplw cr7, CARG2, TMP2
1234 | lwz PC, FRAME_PC(BASE)
1235 | crorc 4*cr6+lt, 4*cr0+gt, 4*cr1+eq // st>LUA_YIELD || cframe!=0
1236 | add TMP2, CARG2, NARGS8:RC
1237 | crandc 4*cr6+gt, 4*cr7+eq, 4*cr0+eq // base==top && st!=LUA_YIELD
1238 | cmplw cr1, TMP2, TMP0
1239 | cror 4*cr6+lt, 4*cr6+lt, 4*cr6+gt
1240 | stw PC, SAVE_PC
1241 | cror 4*cr6+lt, 4*cr6+lt, 4*cr1+gt // cond1 || cond2 || stackov
1242 | stw BASE, L->base
1243 | blt cr6, ->fff_fallback
1244 |1:
1245 |.if resume
1246 | addi BASE, BASE, 8 // Keep resumed thread in stack for GC.
1247 | subi NARGS8:RC, NARGS8:RC, 8
1248 | subi TMP2, TMP2, 8
1249 |.endif
1250 | stw TMP2, L:CARG1->top
1251 | li TMP1, 0
1252 | stw BASE, L->top
1253 |2: // Move args to coroutine.
1254 | cmpw TMP1, NARGS8:RC
1255 | evlddx TMP0, BASE, TMP1
1256 | beq >3
1257 | evstddx TMP0, CARG2, TMP1
1258 | addi TMP1, TMP1, 8
1259 | b <2
1260 |3:
1261 | li CARG3, 0
1262 | mr L:SAVE0, L:CARG1
1263 | li CARG4, 0
1264 | bl ->vm_resume // (lua_State *L, TValue *base, 0, 0)
1265 | // Returns thread status.
1266 |4:
1267 | lwz TMP2, L:SAVE0->base
1268 | cmplwi CRET1, LUA_YIELD
1269 | lwz TMP3, L:SAVE0->top
1270 | li_vmstate INTERP
1271 | lwz BASE, L->base
1272 | st_vmstate
1273 | bgt >8
1274 | sub RD, TMP3, TMP2
1275 | lwz TMP0, L->maxstack
1276 | cmplwi RD, 0
1277 | add TMP1, BASE, RD
1278 | beq >6 // No results?
1279 | cmplw TMP1, TMP0
1280 | li TMP1, 0
1281 | bgt >9 // Need to grow stack?
1282 |
1283 | subi TMP3, RD, 8
1284 | stw TMP2, L:SAVE0->top // Clear coroutine stack.
1285 |5: // Move results from coroutine.
1286 | cmplw TMP1, TMP3
1287 | evlddx TMP0, TMP2, TMP1
1288 | evstddx TMP0, BASE, TMP1
1289 | addi TMP1, TMP1, 8
1290 | bne <5
1291 |6:
1292 | andi. TMP0, PC, FRAME_TYPE
1293 |.if resume
1294 | li TMP1, LJ_TTRUE
1295 | la RA, -8(BASE)
1296 | stw TMP1, -8(BASE) // Prepend true to results.
1297 | addi RD, RD, 16
1298 |.else
1299 | mr RA, BASE
1300 | addi RD, RD, 8
1301 |.endif
1302 |7:
1303 | stw PC, SAVE_PC
1304 | mr MULTRES, RD
1305 | beq ->BC_RET_Z
1306 | b ->vm_return
1307 |
1308 |8: // Coroutine returned with error (at co->top-1).
1309 |.if resume
1310 | andi. TMP0, PC, FRAME_TYPE
1311 | la TMP3, -8(TMP3)
1312 | li TMP1, LJ_TFALSE
1313 | evldd TMP0, 0(TMP3)
1314 | stw TMP3, L:SAVE0->top // Remove error from coroutine stack.
1315 | li RD, (2+1)*8
1316 | stw TMP1, -8(BASE) // Prepend false to results.
1317 | la RA, -8(BASE)
1318 | evstdd TMP0, 0(BASE) // Copy error message.
1319 | b <7
1320 |.else
1321 | mr CARG1, L
1322 | mr CARG2, L:SAVE0
1323 | bl extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co)
1324 |.endif
1325 |
1326 |9: // Handle stack expansion on return from yield.
1327 | mr CARG1, L
1328 | srwi CARG2, RD, 3
1329 | bl extern lj_state_growstack // (lua_State *L, int n)
1330 | li CRET1, 0
1331 | b <4
1332 |.endmacro
1333 |
1334 | coroutine_resume_wrap 1 // coroutine.resume
1335 | coroutine_resume_wrap 0 // coroutine.wrap
1336 |
1337 |.ffunc coroutine_yield
1338 | lwz TMP0, L->cframe
1339 | add TMP1, BASE, NARGS8:RC
1340 | stw BASE, L->base
1341 | andi. TMP0, TMP0, CFRAME_RESUME
1342 | stw TMP1, L->top
1343 | li CRET1, LUA_YIELD
1344 | beq ->fff_fallback
1345 | stw ZERO, L->cframe
1346 | stb CRET1, L->status
1347 | b ->vm_leave_unw
1348 |
1349 |//-- Math library -------------------------------------------------------
1350 |
1351 |.ffunc_n math_abs
1352 | efdabs CRET1, CARG1
1353 | // Fallthrough.
1354 |
1355 |->fff_restv:
1356 | // CRET1 = TValue result.
1357 | lwz PC, FRAME_PC(BASE)
1358 | la RA, -8(BASE)
1359 | evstdd CRET1, 0(RA)
1360 |->fff_res1:
1361 | // RA = results, PC = return.
1362 | li RD, (1+1)*8
1363 |->fff_res:
1364 | // RA = results, RD = (nresults+1)*8, PC = return.
1365 | andi. TMP0, PC, FRAME_TYPE
1366 | mr MULTRES, RD
1367 | bne ->vm_return
1368 | lwz INS, -4(PC)
1369 | decode_RB8 RB, INS
1370 |5:
1371 | cmplw RB, RD // More results expected?
1372 | decode_RA8 TMP0, INS
1373 | bgt >6
1374 | ins_next1
1375 | // Adjust BASE. KBASE is assumed to be set for the calling frame.
1376 | sub BASE, RA, TMP0
1377 | ins_next2
1378 |
1379 |6: // Fill up results with nil.
1380 | subi TMP1, RD, 8
1381 | addi RD, RD, 8
1382 | evstddx TISNIL, RA, TMP1
1383 | b <5
1384 |
1385 |.macro math_extern, func
1386 | .ffunc math_ .. func
1387 | cmplwi NARGS8:RC, 8
1388 | evldd CARG2, 0(BASE)
1389 | blt ->fff_fallback
1390 | checknum CARG2
1391 | evmergehi CARG1, CARG2, CARG2
1392 | checkfail ->fff_fallback
1393 | bl extern func@plt
1394 | evmergelo CRET1, CRET1, CRET2
1395 | b ->fff_restv
1396 |.endmacro
1397 |
1398 |.macro math_extern2, func
1399 | .ffunc math_ .. func
1400 | cmplwi NARGS8:RC, 16
1401 | evldd CARG2, 0(BASE)
1402 | evldd CARG4, 8(BASE)
1403 | blt ->fff_fallback
1404 | evmergehi CARG1, CARG4, CARG2
1405 | checknum CARG1
1406 | evmergehi CARG3, CARG4, CARG4
1407 | checkanyfail ->fff_fallback
1408 | bl extern func@plt
1409 | evmergelo CRET1, CRET1, CRET2
1410 | b ->fff_restv
1411 |.endmacro
1412 |
1413 |.macro math_round, func
1414 | .ffunc math_ .. func
1415 | cmplwi NARGS8:RC, 8
1416 | evldd CARG2, 0(BASE)
1417 | blt ->fff_fallback
1418 | checknum CARG2
1419 | evmergehi CARG1, CARG2, CARG2
1420 | checkfail ->fff_fallback
1421 | lwz PC, FRAME_PC(BASE)
1422 | bl ->vm_..func.._hilo;
1423 | la RA, -8(BASE)
1424 | evstdd CRET2, 0(RA)
1425 | b ->fff_res1
1426 |.endmacro
1427 |
1428 | math_round floor
1429 | math_round ceil
1430 |
1431 | math_extern sqrt
1432 |
1433 |.ffunc math_log
1434 | cmplwi NARGS8:RC, 8
1435 | evldd CARG2, 0(BASE)
1436 | bne ->fff_fallback // Need exactly 1 argument.
1437 | checknum CARG2
1438 | evmergehi CARG1, CARG2, CARG2
1439 | checkfail ->fff_fallback
1440 | bl extern log@plt
1441 | evmergelo CRET1, CRET1, CRET2
1442 | b ->fff_restv
1443 |
1444 | math_extern log10
1445 | math_extern exp
1446 | math_extern sin
1447 | math_extern cos
1448 | math_extern tan
1449 | math_extern asin
1450 | math_extern acos
1451 | math_extern atan
1452 | math_extern sinh
1453 | math_extern cosh
1454 | math_extern tanh
1455 | math_extern2 pow
1456 | math_extern2 atan2
1457 | math_extern2 fmod
1458 |
1459 |->ff_math_deg:
1460 |.ffunc_n math_rad
1461 | evldd CARG2, CFUNC:RB->upvalue[0]
1462 | efdmul CRET1, CARG1, CARG2
1463 | b ->fff_restv
1464 |
1465 |.ffunc math_ldexp
1466 | cmplwi NARGS8:RC, 16
1467 | evldd CARG2, 0(BASE)
1468 | evldd CARG4, 8(BASE)
1469 | blt ->fff_fallback
1470 | evmergehi CARG1, CARG4, CARG2
1471 | checknum CARG1
1472 | checkanyfail ->fff_fallback
1473 | efdctsi CARG3, CARG4
1474 | bl extern ldexp@plt
1475 | evmergelo CRET1, CRET1, CRET2
1476 | b ->fff_restv
1477 |
1478 |.ffunc math_frexp
1479 | cmplwi NARGS8:RC, 8
1480 | evldd CARG2, 0(BASE)
1481 | blt ->fff_fallback
1482 | checknum CARG2
1483 | evmergehi CARG1, CARG2, CARG2
1484 | checkfail ->fff_fallback
1485 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
1486 | lwz PC, FRAME_PC(BASE)
1487 | bl extern frexp@plt
1488 | lwz TMP1, DISPATCH_GL(tmptv)(DISPATCH)
1489 | evmergelo CRET1, CRET1, CRET2
1490 | efdcfsi CRET2, TMP1
1491 | la RA, -8(BASE)
1492 | evstdd CRET1, 0(RA)
1493 | li RD, (2+1)*8
1494 | evstdd CRET2, 8(RA)
1495 | b ->fff_res
1496 |
1497 |.ffunc math_modf
1498 | cmplwi NARGS8:RC, 8
1499 | evldd CARG2, 0(BASE)
1500 | blt ->fff_fallback
1501 | checknum CARG2
1502 | evmergehi CARG1, CARG2, CARG2
1503 | checkfail ->fff_fallback
1504 | la CARG3, -8(BASE)
1505 | lwz PC, FRAME_PC(BASE)
1506 | bl extern modf@plt
1507 | evmergelo CRET1, CRET1, CRET2
1508 | la RA, -8(BASE)
1509 | evstdd CRET1, 0(BASE)
1510 | li RD, (2+1)*8
1511 | b ->fff_res
1512 |
1513 |.macro math_minmax, name, cmpop
1514 | .ffunc_1 name
1515 | checknum CARG1
1516 | li TMP1, 8
1517 | checkfail ->fff_fallback
1518 |1:
1519 | evlddx CARG2, BASE, TMP1
1520 | cmplw cr1, TMP1, NARGS8:RC
1521 | checknum CARG2
1522 | bge cr1, ->fff_restv // Ok, since CRET1 = CARG1.
1523 | checkfail ->fff_fallback
1524 | cmpop CARG2, CARG1
1525 | addi TMP1, TMP1, 8
1526 | crmove 4*cr0+lt, 4*cr0+gt
1527 | evsel CARG1, CARG2, CARG1
1528 | b <1
1529 |.endmacro
1530 |
1531 | math_minmax math_min, efdtstlt
1532 | math_minmax math_max, efdtstgt
1533 |
1534 |//-- String library -----------------------------------------------------
1535 |
1536 |.ffunc_1 string_len
1537 | checkstr STR:CARG1
1538 | checkfail ->fff_fallback
1539 | lwz TMP0, STR:CARG1->len
1540 | efdcfsi CRET1, TMP0
1541 | b ->fff_restv
1542 |
1543 |.ffunc string_byte // Only handle the 1-arg case here.
1544 | cmplwi NARGS8:RC, 8
1545 | evldd STR:CARG1, 0(BASE)
1546 | bne ->fff_fallback // Need exactly 1 argument.
1547 | checkstr STR:CARG1
1548 | la RA, -8(BASE)
1549 | checkfail ->fff_fallback
1550 | lwz TMP0, STR:CARG1->len
1551 | li RD, (0+1)*8
1552 | lbz TMP1, STR:CARG1[1] // Access is always ok (NUL at end).
1553 | li TMP2, (1+1)*8
1554 | cmplwi TMP0, 0
1555 | lwz PC, FRAME_PC(BASE)
1556 | efdcfsi CRET1, TMP1
1557 | iseleq RD, RD, TMP2
1558 | evstdd CRET1, 0(RA)
1559 | b ->fff_res
1560 |
1561 |.ffunc string_char // Only handle the 1-arg case here.
1562 | ffgccheck
1563 | cmplwi NARGS8:RC, 8
1564 | evldd CARG1, 0(BASE)
1565 | bne ->fff_fallback // Exactly 1 argument.
1566 | checknum CARG1
1567 | la CARG2, DISPATCH_GL(tmptv)(DISPATCH)
1568 | checkfail ->fff_fallback
1569 | efdctsiz TMP0, CARG1
1570 | li CARG3, 1
1571 | cmplwi TMP0, 255
1572 | stb TMP0, 0(CARG2)
1573 | bgt ->fff_fallback
1574 |->fff_newstr:
1575 | mr CARG1, L
1576 | stw BASE, L->base
1577 | stw PC, SAVE_PC
1578 | bl extern lj_str_new // (lua_State *L, char *str, size_t l)
1579 | // Returns GCstr *.
1580 | lwz BASE, L->base
1581 | evmergelo STR:CRET1, TISSTR, STR:CRET1
1582 | b ->fff_restv
1583 |
1584 |.ffunc string_sub
1585 | ffgccheck
1586 | cmplwi NARGS8:RC, 16
1587 | evldd CARG3, 16(BASE)
1588 | evldd STR:CARG1, 0(BASE)
1589 | blt ->fff_fallback
1590 | evldd CARG2, 8(BASE)
1591 | li TMP2, -1
1592 | beq >1
1593 | checknum CARG3
1594 | checkfail ->fff_fallback
1595 | efdctsiz TMP2, CARG3
1596 |1:
1597 | checknum CARG2
1598 | checkfail ->fff_fallback
1599 | checkstr STR:CARG1
1600 | efdctsiz TMP1, CARG2
1601 | checkfail ->fff_fallback
1602 | lwz TMP0, STR:CARG1->len
1603 | cmplw TMP0, TMP2 // len < end? (unsigned compare)
1604 | add TMP3, TMP2, TMP0
1605 | blt >5
1606 |2:
1607 | cmpwi TMP1, 0 // start <= 0?
1608 | add TMP3, TMP1, TMP0
1609 | ble >7
1610 |3:
1611 | sub. CARG3, TMP2, TMP1
1612 | addi CARG2, STR:CARG1, #STR-1
1613 | addi CARG3, CARG3, 1
1614 | add CARG2, CARG2, TMP1
1615 | isellt CARG3, r0, CARG3
1616 | b ->fff_newstr
1617 |
1618 |5: // Negative end or overflow.
1619 | cmpw TMP0, TMP2
1620 | addi TMP3, TMP3, 1
1621 | iselgt TMP2, TMP3, TMP0 // end = end > len ? len : end+len+1
1622 | b <2
1623 |
1624 |7: // Negative start or underflow.
1625 | cmpwi cr1, TMP3, 0
1626 | iseleq TMP1, r0, TMP3
1627 | isel TMP1, r0, TMP1, 4*cr1+lt
1628 | addi TMP1, TMP1, 1 // start = 1 + (start ? start+len : 0)
1629 | b <3
1630 |
1631 |.ffunc string_rep // Only handle the 1-char case inline.
1632 | ffgccheck
1633 | cmplwi NARGS8:RC, 16
1634 | evldd CARG1, 0(BASE)
1635 | evldd CARG2, 8(BASE)
1636 | bne ->fff_fallback // Exactly 2 arguments.
1637 | checknum CARG2
1638 | checkfail ->fff_fallback
1639 | checkstr STR:CARG1
1640 | efdctsiz CARG3, CARG2
1641 | checkfail ->fff_fallback
1642 | lwz TMP0, STR:CARG1->len
1643 | cmpwi CARG3, 0
1644 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
1645 | ble >2 // Count <= 0? (or non-int)
1646 | cmplwi TMP0, 1
1647 | subi TMP2, CARG3, 1
1648 | blt >2 // Zero length string?
1649 | cmplw cr1, TMP1, CARG3
1650 | bne ->fff_fallback // Fallback for > 1-char strings.
1651 | lbz TMP0, STR:CARG1[1]
1652 | lwz CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
1653 | blt cr1, ->fff_fallback
1654 |1: // Fill buffer with char. Yes, this is suboptimal code (do you care?).
1655 | cmplwi TMP2, 0
1656 | stbx TMP0, CARG2, TMP2
1657 | subi TMP2, TMP2, 1
1658 | bne <1
1659 | b ->fff_newstr
1660 |2: // Return empty string.
1661 | la STR:CRET1, DISPATCH_GL(strempty)(DISPATCH)
1662 | evmergelo CRET1, TISSTR, STR:CRET1
1663 | b ->fff_restv
1664 |
1665 |.ffunc string_reverse
1666 | ffgccheck
1667 | cmplwi NARGS8:RC, 8
1668 | evldd CARG1, 0(BASE)
1669 | blt ->fff_fallback
1670 | checkstr STR:CARG1
1671 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
1672 | checkfail ->fff_fallback
1673 | lwz CARG3, STR:CARG1->len
1674 | la CARG1, #STR(STR:CARG1)
1675 | lwz CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
1676 | li TMP2, 0
1677 | cmplw TMP1, CARG3
1678 | subi TMP3, CARG3, 1
1679 | blt ->fff_fallback
1680 |1: // Reverse string copy.
1681 | cmpwi TMP3, 0
1682 | lbzx TMP1, CARG1, TMP2
1683 | blt ->fff_newstr
1684 | stbx TMP1, CARG2, TMP3
1685 | subi TMP3, TMP3, 1
1686 | addi TMP2, TMP2, 1
1687 | b <1
1688 |
1689 |.macro ffstring_case, name, lo
1690 | .ffunc name
1691 | ffgccheck
1692 | cmplwi NARGS8:RC, 8
1693 | evldd CARG1, 0(BASE)
1694 | blt ->fff_fallback
1695 | checkstr STR:CARG1
1696 | lwz TMP1, DISPATCH_GL(tmpbuf.sz)(DISPATCH)
1697 | checkfail ->fff_fallback
1698 | lwz CARG3, STR:CARG1->len
1699 | la CARG1, #STR(STR:CARG1)
1700 | lwz CARG2, DISPATCH_GL(tmpbuf.buf)(DISPATCH)
1701 | cmplw TMP1, CARG3
1702 | li TMP2, 0
1703 | blt ->fff_fallback
1704 |1: // ASCII case conversion.
1705 | cmplw TMP2, CARG3
1706 | lbzx TMP1, CARG1, TMP2
1707 | bge ->fff_newstr
1708 | subi TMP0, TMP1, lo
1709 | xori TMP3, TMP1, 0x20
1710 | cmplwi TMP0, 26
1711 | isellt TMP1, TMP3, TMP1
1712 | stbx TMP1, CARG2, TMP2
1713 | addi TMP2, TMP2, 1
1714 | b <1
1715 |.endmacro
1716 |
1717 |ffstring_case string_lower, 65
1718 |ffstring_case string_upper, 97
1719 |
1720 |//-- Table library ------------------------------------------------------
1721 |
1722 |.ffunc_1 table_getn
1723 | checktab CARG1
1724 | checkfail ->fff_fallback
1725 | bl extern lj_tab_len // (GCtab *t)
1726 | // Returns uint32_t (but less than 2^31).
1727 | efdcfsi CRET1, CRET1
1728 | b ->fff_restv
1729 |
1730 |//-- Bit library --------------------------------------------------------
1731 |
1732 |.macro .ffunc_bit, name
1733 | .ffunc_n bit_..name
1734 | efdadd CARG1, CARG1, TOBIT
1735 |.endmacro
1736 |
1737 |.ffunc_bit tobit
1738 |->fff_resbit:
1739 | efdcfsi CRET1, CARG1
1740 | b ->fff_restv
1741 |
1742 |.macro .ffunc_bit_op, name, ins
1743 | .ffunc_bit name
1744 | li TMP1, 8
1745 |1:
1746 | evlddx CARG2, BASE, TMP1
1747 | cmplw cr1, TMP1, NARGS8:RC
1748 | checknum CARG2
1749 | bge cr1, ->fff_resbit
1750 | checkfail ->fff_fallback
1751 | efdadd CARG2, CARG2, TOBIT
1752 | ins CARG1, CARG1, CARG2
1753 | addi TMP1, TMP1, 8
1754 | b <1
1755 |.endmacro
1756 |
1757 |.ffunc_bit_op band, and
1758 |.ffunc_bit_op bor, or
1759 |.ffunc_bit_op bxor, xor
1760 |
1761 |.ffunc_bit bswap
1762 | rotlwi TMP0, CARG1, 8
1763 | rlwimi TMP0, CARG1, 24, 0, 7
1764 | rlwimi TMP0, CARG1, 24, 16, 23
1765 | efdcfsi CRET1, TMP0
1766 | b ->fff_restv
1767 |
1768 |.ffunc_bit bnot
1769 | not TMP0, CARG1
1770 | efdcfsi CRET1, TMP0
1771 | b ->fff_restv
1772 |
1773 |.macro .ffunc_bit_sh, name, ins, shmod
1774 | .ffunc_nn bit_..name
1775 | efdadd CARG2, CARG2, TOBIT
1776 | efdadd CARG1, CARG1, TOBIT
1777 |.if shmod == 1
1778 | rlwinm CARG2, CARG2, 0, 27, 31
1779 |.elif shmod == 2
1780 | neg CARG2, CARG2
1781 |.endif
1782 | ins TMP0, CARG1, CARG2
1783 | efdcfsi CRET1, TMP0
1784 | b ->fff_restv
1785 |.endmacro
1786 |
1787 |.ffunc_bit_sh lshift, slw, 1
1788 |.ffunc_bit_sh rshift, srw, 1
1789 |.ffunc_bit_sh arshift, sraw, 1
1790 |.ffunc_bit_sh rol, rotlw, 0
1791 |.ffunc_bit_sh ror, rotlw, 2
1792 |
1793 |//-----------------------------------------------------------------------
1794 |
1795 |->fff_fallback: // Call fast function fallback handler.
1796 | // BASE = new base, RB = CFUNC, RC = nargs*8
1797 | lwz TMP3, CFUNC:RB->f
1798 | add TMP1, BASE, NARGS8:RC
1799 | lwz PC, FRAME_PC(BASE) // Fallback may overwrite PC.
1800 | addi TMP0, TMP1, 8*LUA_MINSTACK
1801 | lwz TMP2, L->maxstack
1802 | stw PC, SAVE_PC // Redundant (but a defined value).
1803 | cmplw TMP0, TMP2
1804 | stw BASE, L->base
1805 | stw TMP1, L->top
1806 | mr CARG1, L
1807 | bgt >5 // Need to grow stack.
1808 | mtctr TMP3
1809 | bctrl // (lua_State *L)
1810 | // Either throws an error, or recovers and returns -1, 0 or nresults+1.
1811 | lwz BASE, L->base
1812 | cmpwi CRET1, 0
1813 | slwi RD, CRET1, 3
1814 | la RA, -8(BASE)
1815 | bgt ->fff_res // Returned nresults+1?
1816 |1: // Returned 0 or -1: retry fast path.
1817 | lwz TMP0, L->top
1818 | lwz LFUNC:RB, FRAME_FUNC(BASE)
1819 | sub NARGS8:RC, TMP0, BASE
1820 | bne ->vm_call_tail // Returned -1?
1821 | ins_callt // Returned 0: retry fast path.
1822 |
1823 |// Reconstruct previous base for vmeta_call during tailcall.
1824 |->vm_call_tail:
1825 | andi. TMP0, PC, FRAME_TYPE
1826 | rlwinm TMP1, PC, 0, 0, 28
1827 | bne >3
1828 | lwz INS, -4(PC)
1829 | decode_RA8 TMP1, INS
1830 | addi TMP1, TMP1, 8
1831 |3:
1832 | sub TMP2, BASE, TMP1
1833 | b ->vm_call_dispatch // Resolve again for tailcall.
1834 |
1835 |5: // Grow stack for fallback handler.
1836 | li CARG2, LUA_MINSTACK
1837 | bl extern lj_state_growstack // (lua_State *L, int n)
1838 | lwz BASE, L->base
1839 | cmpw TMP0, TMP0 // Set 4*cr0+eq to force retry.
1840 | b <1
1841 |
1842 |->fff_gcstep: // Call GC step function.
1843 | // BASE = new base, RC = nargs*8
1844 | mflr SAVE0
1845 | stw BASE, L->base
1846 | add TMP0, BASE, NARGS8:RC
1847 | stw PC, SAVE_PC // Redundant (but a defined value).
1848 | stw TMP0, L->top
1849 | mr CARG1, L
1850 | bl extern lj_gc_step // (lua_State *L)
1851 | lwz BASE, L->base
1852 | mtlr SAVE0
1853 | lwz TMP0, L->top
1854 | sub NARGS8:RC, TMP0, BASE
1855 | lwz CFUNC:RB, FRAME_FUNC(BASE)
1856 | blr
1857 |
1858 |//-----------------------------------------------------------------------
1859 |//-- Special dispatch targets -------------------------------------------
1860 |//-----------------------------------------------------------------------
1861 |
1862 |->vm_record: // Dispatch target for recording phase.
1863 |.if JIT
1864 | NYI
1865 |.endif
1866 |
1867 |->vm_rethook: // Dispatch target for return hooks.
1868 | lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
1869 | andi. TMP0, TMP3, HOOK_ACTIVE // Hook already active?
1870 | beq >1
1871 |5: // Re-dispatch to static ins.
1872 | addi TMP1, TMP1, GG_DISP2STATIC // Assumes decode_OP4 TMP1, INS.
1873 | lwzx TMP0, DISPATCH, TMP1
1874 | mtctr TMP0
1875 | bctr
1876 |
1877 |->vm_inshook: // Dispatch target for instr/line hooks.
1878 | lbz TMP3, DISPATCH_GL(hookmask)(DISPATCH)
1879 | lwz TMP2, DISPATCH_GL(hookcount)(DISPATCH)
1880 | andi. TMP0, TMP3, HOOK_ACTIVE // Hook already active?
1881 | rlwinm TMP0, TMP3, 31-LUA_HOOKLINE, 31, 0
1882 | bne <5
1883 |
1884 | cmpwi cr1, TMP0, 0
1885 | addic. TMP2, TMP2, -1
1886 | beq cr1, <5
1887 | stw TMP2, DISPATCH_GL(hookcount)(DISPATCH)
1888 | beq >1
1889 | bge cr1, <5
1890 |1:
1891 | mr CARG1, L
1892 | stw MULTRES, SAVE_MULTRES
1893 | mr CARG2, PC
1894 | stw BASE, L->base
1895 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
1896 | bl extern lj_dispatch_ins // (lua_State *L, const BCIns *pc)
1897 |3:
1898 | lwz BASE, L->base
1899 |4: // Re-dispatch to static ins.
1900 | lwz INS, -4(PC)
1901 | decode_OP4 TMP1, INS
1902 | decode_RB8 RB, INS
1903 | addi TMP1, TMP1, GG_DISP2STATIC
1904 | decode_RD8 RD, INS
1905 | lwzx TMP0, DISPATCH, TMP1
1906 | decode_RA8 RA, INS
1907 | decode_RC8 RC, INS
1908 | mtctr TMP0
1909 | bctr
1910 |
1911 |->cont_hook: // Continue from hook yield.
1912 | addi PC, PC, 4
1913 | lwz MULTRES, -20(RB) // Restore MULTRES for *M ins.
1914 | b <4
1915 |
1916 |->vm_hotloop: // Hot loop counter underflow.
1917 |.if JIT
1918 | NYI
1919 |.endif
1920 |
1921 |->vm_callhook: // Dispatch target for call hooks.
1922 | mr CARG2, PC
1923 |.if JIT
1924 | b >1
1925 |.endif
1926 |
1927 |->vm_hotcall: // Hot call counter underflow.
1928 |.if JIT
1929 | ori CARG2, PC, 1
1930 |1:
1931 |.endif
1932 | add TMP0, BASE, RC
1933 | stw PC, SAVE_PC
1934 | mr CARG1, L
1935 | stw BASE, L->base
1936 | sub RA, RA, BASE
1937 | stw TMP0, L->top
1938 | bl extern lj_dispatch_call // (lua_State *L, const BCIns *pc)
1939 | // Returns ASMFunction.
1940 | lwz BASE, L->base
1941 | lwz TMP0, L->top
1942 | stw ZERO, SAVE_PC // Invalidate for subsequent line hook.
1943 | sub NARGS8:RC, TMP0, BASE
1944 | add RA, BASE, RA
1945 | lwz LFUNC:RB, FRAME_FUNC(BASE)
1946 | mtctr CRET1
1947 | bctr
1948 |
1949 |//-----------------------------------------------------------------------
1950 |//-- Trace exit handler -------------------------------------------------
1951 |//-----------------------------------------------------------------------
1952 |
1953 |->vm_exit_handler:
1954 |.if JIT
1955 | NYI
1956 |.endif
1957 |->vm_exit_interp:
1958 |.if JIT
1959 | NYI
1960 |.endif
1961 |
1962 |//-----------------------------------------------------------------------
1963 |//-- Math helper functions ----------------------------------------------
1964 |//-----------------------------------------------------------------------
1965 |
1966 |// FP value rounding. Called by math.floor/math.ceil fast functions
1967 |// and from JIT code.
1968 |//
1969 |// This can be inlined if the CPU has the frin/friz/frip/frim instructions.
1970 |// The alternative hard-float approaches have a deep dependency chain.
1971 |// The resulting latency is at least 3x-7x the double-precision FP latency
1972 |// (e500v2: 6cy, e600: 5cy, Cell: 10cy) or around 20-70 cycles.
1973 |//
1974 |// The soft-float approach is tedious, but much faster (e500v2: ~11cy/~6cy).
1975 |// However it relies on a fast way to transfer the FP value to GPRs
1976 |// (e500v2: 0cy for lo-word, 1cy for hi-word).
1977 |//
1978 |.macro vm_round, name, mode
1979 | // Used temporaries: TMP0, TMP1, TMP2, TMP3.
1980 |->name.._efd: // Input: CARG2, output: CRET2
1981 | evmergehi CARG1, CARG2, CARG2
1982 |->name.._hilo:
1983 | // Input: CARG1 (hi), CARG2 (hi, lo), output: CRET2
1984 | rlwinm TMP2, CARG1, 12, 21, 31
1985 | addic. TMP2, TMP2, -1023 // exp = exponent(x) - 1023
1986 | li TMP1, -1
1987 | cmplwi cr1, TMP2, 51 // 0 <= exp <= 51?
1988 | subfic TMP0, TMP2, 52
1989 | bgt cr1, >1
1990 | lus TMP3, 0xfff0
1991 | slw TMP0, TMP1, TMP0 // lomask = -1 << (52-exp)
1992 | sraw TMP1, TMP3, TMP2 // himask = (int32_t)0xfff00000 >> exp
1993 |.if mode == 2 // trunc(x):
1994 | evmergelo TMP0, TMP1, TMP0
1995 | evand CRET2, CARG2, TMP0 // hi &= himask, lo &= lomask
1996 |.else
1997 | andc TMP2, CARG2, TMP0
1998 | andc TMP3, CARG1, TMP1
1999 | or TMP2, TMP2, TMP3 // ztest = (hi&~himask) | (lo&~lomask)
2000 | srawi TMP3, CARG1, 31 // signmask = (int32_t)hi >> 31
2001 |.if mode == 0 // floor(x):
2002 | and. TMP2, TMP2, TMP3 // iszero = ((ztest & signmask) == 0)
2003 |.else // ceil(x):
2004 | andc. TMP2, TMP2, TMP3 // iszero = ((ztest & ~signmask) == 0)
2005 |.endif
2006 | and CARG2, CARG2, TMP0 // lo &= lomask
2007 | and CARG1, CARG1, TMP1 // hi &= himask
2008 | subc TMP0, CARG2, TMP0
2009 | iseleq TMP0, CARG2, TMP0 // lo = iszero ? lo : lo-lomask
2010 | sube TMP1, CARG1, TMP1
2011 | iseleq TMP1, CARG1, TMP1 // hi = iszero ? hi : hi-himask+carry
2012 | evmergelo CRET2, TMP1, TMP0
2013 |.endif
2014 | blr
2015 |1:
2016 | bgtlr // Already done if >=2^52, +-inf or nan.
2017 |.if mode == 2 // trunc(x):
2018 | rlwinm TMP1, CARG1, 0, 0, 0 // hi = sign(x)
2019 | li TMP0, 0
2020 | evmergelo CRET2, TMP1, TMP0
2021 |.else
2022 | rlwinm TMP2, CARG1, 0, 1, 31
2023 | srawi TMP0, CARG1, 31 // signmask = (int32_t)hi >> 31
2024 | or TMP2, TMP2, CARG2 // ztest = abs(hi) | lo
2025 | lus TMP1, 0x3ff0
2026 |.if mode == 0 // floor(x):
2027 | and. TMP2, TMP2, TMP0 // iszero = ((ztest & signmask) == 0)
2028 |.else // ceil(x):
2029 | andc. TMP2, TMP2, TMP0 // iszero = ((ztest & ~signmask) == 0)
2030 |.endif
2031 | li TMP0, 0
2032 | iseleq TMP1, r0, TMP1
2033 | rlwimi CARG1, TMP1, 0, 1, 31 // hi = sign(x) | (iszero ? 0.0 : 1.0)
2034 | evmergelo CRET2, CARG1, TMP0
2035 |.endif
2036 | blr
2037 |.endmacro
2038 |
2039 |->vm_floor:
2040 | mflr CARG3
2041 | evmergelo CARG2, CARG1, CARG2
2042 | bl ->vm_floor_hilo
2043 | mtlr CARG3
2044 | evmergehi CRET1, CRET2, CRET2
2045 | blr
2046 |
2047 | vm_round vm_floor, 0
2048 | vm_round vm_ceil, 1
2049 |.if JIT
2050 | vm_round vm_trunc, 2
2051 |.else
2052 |->vm_trunc_efd:
2053 |->vm_trunc_hilo:
2054 |.endif
2055 |
2056 |//-----------------------------------------------------------------------
2057 |//-- Miscellaneous functions --------------------------------------------
2058 |//-----------------------------------------------------------------------
2059 |
2060 |//-----------------------------------------------------------------------
2061 |//-- FFI helper functions -----------------------------------------------
2062 |//-----------------------------------------------------------------------
2063 |
2064 |->vm_ffi_call:
2065 |.if FFI
2066 | NYI
2067 |.endif
2068 |
2069 |//-----------------------------------------------------------------------
2070}
2071
2072/* Generate the code for a single instruction. */
2073static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2074{
2075 int vk = 0;
2076 |=>defop:
2077
2078 switch (op) {
2079
2080 /* -- Comparison ops ---------------------------------------------------- */
2081
2082 /* Remember: all ops branch for a true comparison, fall through otherwise. */
2083
2084 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
2085 | // RA = src1*8, RD = src2*8, JMP with RD = target
2086 | evlddx TMP0, BASE, RA
2087 | addi PC, PC, 4
2088 | evlddx TMP1, BASE, RD
2089 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2090 | lwz TMP2, -4(PC)
2091 | evmergehi RB, TMP0, TMP1
2092 | decode_RD4 TMP2, TMP2
2093 | checknum RB
2094 | add TMP2, TMP2, TMP3
2095 | checkanyfail ->vmeta_comp
2096 | efdcmplt TMP0, TMP1
2097 if (op == BC_ISLE || op == BC_ISGT) {
2098 | efdcmpeq cr1, TMP0, TMP1
2099 | cror 4*cr0+gt, 4*cr0+gt, 4*cr1+gt
2100 }
2101 if (op == BC_ISLT || op == BC_ISLE) {
2102 | iselgt PC, TMP2, PC
2103 } else {
2104 | iselgt PC, PC, TMP2
2105 }
2106 | ins_next
2107 break;
2108
2109 case BC_ISEQV: case BC_ISNEV:
2110 vk = op == BC_ISEQV;
2111 | // RA = src1*8, RD = src2*8, JMP with RD = target
2112 | evlddx CARG2, BASE, RA
2113 | addi PC, PC, 4
2114 | evlddx CARG3, BASE, RD
2115 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2116 | lwz TMP2, -4(PC)
2117 | evmergehi RB, CARG2, CARG3
2118 | decode_RD4 TMP2, TMP2
2119 | checknum RB
2120 | add TMP2, TMP2, TMP3
2121 | checkanyfail >5
2122 | efdcmpeq CARG2, CARG3
2123 if (vk) {
2124 | iselgt PC, TMP2, PC
2125 } else {
2126 | iselgt PC, PC, TMP2
2127 }
2128 |1:
2129 | ins_next
2130 |
2131 |5: // Either or both types are not numbers.
2132 | evcmpeq CARG2, CARG3
2133 | not TMP3, RB
2134 | cmplwi cr1, TMP3, ~LJ_TISPRI // Primitive?
2135 | crorc 4*cr7+lt, 4*cr0+so, 4*cr0+lt // 1: Same tv or different type.
2136 | cmplwi cr6, TMP3, ~LJ_TISTABUD // Table or userdata?
2137 | crandc 4*cr7+gt, 4*cr0+lt, 4*cr1+gt // 2: Same type and primitive.
2138 | mr SAVE0, PC
2139 if (vk) {
2140 | isel PC, TMP2, PC, 4*cr7+gt
2141 } else {
2142 | isel TMP2, PC, TMP2, 4*cr7+gt
2143 }
2144 | cror 4*cr7+lt, 4*cr7+lt, 4*cr7+gt // 1 or 2.
2145 if (vk) {
2146 | isel PC, TMP2, PC, 4*cr0+so
2147 } else {
2148 | isel PC, PC, TMP2, 4*cr0+so
2149 }
2150 | blt cr7, <1 // Done if 1 or 2.
2151 | blt cr6, <1 // Done if not tab/ud.
2152 |
2153 | // Different tables or userdatas. Need to check __eq metamethod.
2154 | // Field metatable must be at same offset for GCtab and GCudata!
2155 | lwz TAB:TMP2, TAB:CARG2->metatable
2156 | li CARG4, 1-vk // ne = 0 or 1.
2157 | cmplwi TAB:TMP2, 0
2158 | beq <1 // No metatable?
2159 | lbz TMP2, TAB:TMP2->nomm
2160 | andi. TMP2, TMP2, 1<<MM_eq
2161 | bne <1 // Or 'no __eq' flag set?
2162 | mr PC, SAVE0 // Restore old PC.
2163 | b ->vmeta_equal // Handle __eq metamethod.
2164 break;
2165
2166 case BC_ISEQS: case BC_ISNES:
2167 vk = op == BC_ISEQS;
2168 | // RA = src*8, RD = str_const*8 (~), JMP with RD = target
2169 | evlddx TMP0, BASE, RA
2170 | srwi RD, RD, 1
2171 | lwz INS, 0(PC)
2172 | subfic RD, RD, -4
2173 | addi PC, PC, 4
2174 | lwzx STR:TMP1, KBASE, RD // KBASE-4-str_const*4
2175 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2176 | decode_RD4 TMP2, INS
2177 | evmergelo STR:TMP1, TISSTR, STR:TMP1
2178 | add TMP2, TMP2, TMP3
2179 | evcmpeq TMP0, STR:TMP1
2180 if (vk) {
2181 | isel PC, TMP2, PC, 4*cr0+so
2182 } else {
2183 | isel PC, PC, TMP2, 4*cr0+so
2184 }
2185 | ins_next
2186 break;
2187
2188 case BC_ISEQN: case BC_ISNEN:
2189 vk = op == BC_ISEQN;
2190 | // RA = src*8, RD = num_const*8, JMP with RD = target
2191 | evlddx TMP0, BASE, RA
2192 | addi PC, PC, 4
2193 | evlddx TMP1, KBASE, RD
2194 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2195 | lwz INS, -4(PC)
2196 | checknum TMP0
2197 | checkfail >5
2198 | efdcmpeq TMP0, TMP1
2199 |1:
2200 | decode_RD4 TMP2, INS
2201 | add TMP2, TMP2, TMP3
2202 if (vk) {
2203 | iselgt PC, TMP2, PC
2204 |5:
2205 } else {
2206 | iselgt PC, PC, TMP2
2207 }
2208 |3:
2209 | ins_next
2210 if (!vk) {
2211 |5:
2212 | decode_RD4 TMP2, INS
2213 | add PC, TMP2, TMP3
2214 | b <3
2215 }
2216 break;
2217
2218 case BC_ISEQP: case BC_ISNEP:
2219 vk = op == BC_ISEQP;
2220 | // RA = src*8, RD = primitive_type*8 (~), JMP with RD = target
2221 | lwzx TMP0, BASE, RA
2222 | srwi TMP1, RD, 3
2223 | lwz INS, 0(PC)
2224 | addi PC, PC, 4
2225 | not TMP1, TMP1
2226 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2227 | cmplw TMP0, TMP1
2228 | decode_RD4 TMP2, INS
2229 | add TMP2, TMP2, TMP3
2230 if (vk) {
2231 | iseleq PC, TMP2, PC
2232 } else {
2233 | iseleq PC, PC, TMP2
2234 }
2235 | ins_next
2236 break;
2237
2238 /* -- Unary test and copy ops ------------------------------------------- */
2239
2240 case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
2241 | // RA = dst*8 or unused, RD = src*8, JMP with RD = target
2242 | evlddx TMP0, BASE, RD
2243 | evaddw TMP1, TISNIL, TISNIL // Synthesize LJ_TFALSE.
2244 | lwz INS, 0(PC)
2245 | evcmpltu TMP0, TMP1
2246 | addi PC, PC, 4
2247 if (op == BC_IST || op == BC_ISF) {
2248 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
2249 | decode_RD4 TMP2, INS
2250 | add TMP2, TMP2, TMP3
2251 if (op == BC_IST) {
2252 | isellt PC, TMP2, PC
2253 } else {
2254 | isellt PC, PC, TMP2
2255 }
2256 } else {
2257 if (op == BC_ISTC) {
2258 | checkfail >1
2259 } else {
2260 | checkok >1
2261 }
2262 | addis PC, PC, -(BCBIAS_J*4 >> 16)
2263 | decode_RD4 TMP2, INS
2264 | evstddx TMP0, BASE, RA
2265 | add PC, PC, TMP2
2266 |1:
2267 }
2268 | ins_next
2269 break;
2270
2271 /* -- Unary ops --------------------------------------------------------- */
2272
2273 case BC_MOV:
2274 | // RA = dst*8, RD = src*8
2275 | ins_next1
2276 | evlddx TMP0, BASE, RD
2277 | evstddx TMP0, BASE, RA
2278 | ins_next2
2279 break;
2280 case BC_NOT:
2281 | // RA = dst*8, RD = src*8
2282 | ins_next1
2283 | lwzx TMP0, BASE, RD
2284 | subfic TMP1, TMP0, LJ_TTRUE
2285 | adde TMP0, TMP0, TMP1
2286 | stwx TMP0, BASE, RA
2287 | ins_next2
2288 break;
2289 case BC_UNM:
2290 | // RA = dst*8, RD = src*8
2291 | evlddx TMP0, BASE, RD
2292 | checknum TMP0
2293 | checkfail ->vmeta_unm
2294 | efdneg TMP0, TMP0
2295 | ins_next1
2296 | evstddx TMP0, BASE, RA
2297 | ins_next2
2298 break;
2299 case BC_LEN:
2300 | // RA = dst*8, RD = src*8
2301 | evlddx CARG1, BASE, RD
2302 | checkstr CARG1
2303 | checkfail >2
2304 | lwz CRET1, STR:CARG1->len
2305 |1:
2306 | ins_next1
2307 | efdcfsi TMP0, CRET1
2308 | evstddx TMP0, BASE, RA
2309 | ins_next2
2310 |2:
2311 | checktab CARG1
2312 | checkfail ->vmeta_len
2313#if LJ_52
2314 | lwz TAB:TMP2, TAB:CARG1->metatable
2315 | cmplwi TAB:TMP2, 0
2316 | bne >9
2317 |3:
2318#endif
2319 |->BC_LEN_Z:
2320 | bl extern lj_tab_len // (GCtab *t)
2321 | // Returns uint32_t (but less than 2^31).
2322 | b <1
2323#if LJ_52
2324 |9:
2325 | lbz TMP0, TAB:TMP2->nomm
2326 | andi. TMP0, TMP0, 1<<MM_len
2327 | bne <3 // 'no __len' flag set: done.
2328 | b ->vmeta_len
2329#endif
2330 break;
2331
2332 /* -- Binary ops -------------------------------------------------------- */
2333
2334 |.macro ins_arithpre, t0, t1
2335 | // RA = dst*8, RB = src1*8, RC = src2*8 | num_const*8
2336 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
2337 ||switch (vk) {
2338 ||case 0:
2339 | evlddx t0, BASE, RB
2340 | checknum t0
2341 | evlddx t1, KBASE, RC
2342 | checkfail ->vmeta_arith_vn
2343 || break;
2344 ||case 1:
2345 | evlddx t1, BASE, RB
2346 | checknum t1
2347 | evlddx t0, KBASE, RC
2348 | checkfail ->vmeta_arith_nv
2349 || break;
2350 ||default:
2351 | evlddx t0, BASE, RB
2352 | evlddx t1, BASE, RC
2353 | evmergehi TMP2, t0, t1
2354 | checknum TMP2
2355 | checkanyfail ->vmeta_arith_vv
2356 || break;
2357 ||}
2358 |.endmacro
2359 |
2360 |.macro ins_arith, ins
2361 | ins_arithpre TMP0, TMP1
2362 | ins_next1
2363 | ins TMP0, TMP0, TMP1
2364 | evstddx TMP0, BASE, RA
2365 | ins_next2
2366 |.endmacro
2367
2368 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
2369 | ins_arith efdadd
2370 break;
2371 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
2372 | ins_arith efdsub
2373 break;
2374 case BC_MULVN: case BC_MULNV: case BC_MULVV:
2375 | ins_arith efdmul
2376 break;
2377 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
2378 | ins_arith efddiv
2379 break;
2380 case BC_MODVN:
2381 | ins_arithpre RD, SAVE0
2382 |->BC_MODVN_Z:
2383 | efddiv CARG2, RD, SAVE0
2384 | bl ->vm_floor_efd // floor(b/c)
2385 | efdmul TMP0, CRET2, SAVE0
2386 | ins_next1
2387 | efdsub TMP0, RD, TMP0 // b - floor(b/c)*c
2388 | evstddx TMP0, BASE, RA
2389 | ins_next2
2390 break;
2391 case BC_MODNV: case BC_MODVV:
2392 | ins_arithpre RD, SAVE0
2393 | b ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
2394 break;
2395 case BC_POW:
2396 | evlddx CARG2, BASE, RB
2397 | evlddx CARG4, BASE, RC
2398 | evmergehi CARG1, CARG4, CARG2
2399 | checknum CARG1
2400 | evmergehi CARG3, CARG4, CARG4
2401 | checkanyfail ->vmeta_arith_vv
2402 | bl extern pow@plt
2403 | evmergelo CRET2, CRET1, CRET2
2404 | evstddx CRET2, BASE, RA
2405 | ins_next
2406 break;
2407
2408 case BC_CAT:
2409 | // RA = dst*8, RB = src_start*8, RC = src_end*8
2410 | sub CARG3, RC, RB
2411 | stw BASE, L->base
2412 | add CARG2, BASE, RC
2413 | mr SAVE0, RB
2414 |->BC_CAT_Z:
2415 | stw PC, SAVE_PC
2416 | mr CARG1, L
2417 | srwi CARG3, CARG3, 3
2418 | bl extern lj_meta_cat // (lua_State *L, TValue *top, int left)
2419 | // Returns NULL (finished) or TValue * (metamethod).
2420 | cmplwi CRET1, 0
2421 | lwz BASE, L->base
2422 | bne ->vmeta_binop
2423 | evlddx TMP0, BASE, SAVE0 // Copy result from RB to RA.
2424 | evstddx TMP0, BASE, RA
2425 | ins_next
2426 break;
2427
2428 /* -- Constant ops ------------------------------------------------------ */
2429
2430 case BC_KSTR:
2431 | // RA = dst*8, RD = str_const*8 (~)
2432 | ins_next1
2433 | srwi TMP1, RD, 1
2434 | subfic TMP1, TMP1, -4
2435 | lwzx TMP0, KBASE, TMP1 // KBASE-4-str_const*4
2436 | evmergelo TMP0, TISSTR, TMP0
2437 | evstddx TMP0, BASE, RA
2438 | ins_next2
2439 break;
2440 case BC_KCDATA:
2441 |.if FFI
2442 | // RA = dst*8, RD = cdata_const*8 (~)
2443 | ins_next1
2444 | srwi TMP1, RD, 1
2445 | subfic TMP1, TMP1, -4
2446 | lwzx TMP0, KBASE, TMP1 // KBASE-4-cdata_const*4
2447 | li TMP2, LJ_TCDATA
2448 | evmergelo TMP0, TMP2, TMP0
2449 | evstddx TMP0, BASE, RA
2450 | ins_next2
2451 |.endif
2452 break;
2453 case BC_KSHORT:
2454 | // RA = dst*8, RD = int16_literal*8
2455 | srwi TMP1, RD, 3
2456 | extsh TMP1, TMP1
2457 | ins_next1
2458 | efdcfsi TMP0, TMP1
2459 | evstddx TMP0, BASE, RA
2460 | ins_next2
2461 break;
2462 case BC_KNUM:
2463 | // RA = dst*8, RD = num_const*8
2464 | evlddx TMP0, KBASE, RD
2465 | ins_next1
2466 | evstddx TMP0, BASE, RA
2467 | ins_next2
2468 break;
2469 case BC_KPRI:
2470 | // RA = dst*8, RD = primitive_type*8 (~)
2471 | srwi TMP1, RD, 3
2472 | not TMP0, TMP1
2473 | ins_next1
2474 | stwx TMP0, BASE, RA
2475 | ins_next2
2476 break;
2477 case BC_KNIL:
2478 | // RA = base*8, RD = end*8
2479 | evstddx TISNIL, BASE, RA
2480 | addi RA, RA, 8
2481 |1:
2482 | evstddx TISNIL, BASE, RA
2483 | cmpw RA, RD
2484 | addi RA, RA, 8
2485 | blt <1
2486 | ins_next_
2487 break;
2488
2489 /* -- Upvalue and function ops ------------------------------------------ */
2490
2491 case BC_UGET:
2492 | // RA = dst*8, RD = uvnum*8
2493 | ins_next1
2494 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2495 | srwi RD, RD, 1
2496 | addi RD, RD, offsetof(GCfuncL, uvptr)
2497 | lwzx UPVAL:RB, LFUNC:RB, RD
2498 | lwz TMP1, UPVAL:RB->v
2499 | evldd TMP0, 0(TMP1)
2500 | evstddx TMP0, BASE, RA
2501 | ins_next2
2502 break;
2503 case BC_USETV:
2504 | // RA = uvnum*8, RD = src*8
2505 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2506 | srwi RA, RA, 1
2507 | addi RA, RA, offsetof(GCfuncL, uvptr)
2508 | evlddx TMP1, BASE, RD
2509 | lwzx UPVAL:RB, LFUNC:RB, RA
2510 | lbz TMP3, UPVAL:RB->marked
2511 | lwz CARG2, UPVAL:RB->v
2512 | andi. TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
2513 | lbz TMP0, UPVAL:RB->closed
2514 | evmergehi TMP2, TMP1, TMP1
2515 | evstdd TMP1, 0(CARG2)
2516 | cmplwi cr1, TMP0, 0
2517 | cror 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
2518 | subi TMP2, TMP2, (LJ_TISNUM+1)
2519 | bne >2 // Upvalue is closed and black?
2520 |1:
2521 | ins_next
2522 |
2523 |2: // Check if new value is collectable.
2524 | cmplwi TMP2, LJ_TISGCV - (LJ_TISNUM+1)
2525 | bge <1 // tvisgcv(v)
2526 | lbz TMP3, GCOBJ:TMP1->gch.marked
2527 | andi. TMP3, TMP3, LJ_GC_WHITES // iswhite(v)
2528 | la CARG1, GG_DISP2G(DISPATCH)
2529 | // Crossed a write barrier. Move the barrier forward.
2530 | beq <1
2531 | bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
2532 | b <1
2533 break;
2534 case BC_USETS:
2535 | // RA = uvnum*8, RD = str_const*8 (~)
2536 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2537 | srwi TMP1, RD, 1
2538 | srwi RA, RA, 1
2539 | subfic TMP1, TMP1, -4
2540 | addi RA, RA, offsetof(GCfuncL, uvptr)
2541 | lwzx STR:TMP1, KBASE, TMP1 // KBASE-4-str_const*4
2542 | lwzx UPVAL:RB, LFUNC:RB, RA
2543 | evmergelo STR:TMP1, TISSTR, STR:TMP1
2544 | lbz TMP3, UPVAL:RB->marked
2545 | lwz CARG2, UPVAL:RB->v
2546 | andi. TMP3, TMP3, LJ_GC_BLACK // isblack(uv)
2547 | lbz TMP3, STR:TMP1->marked
2548 | lbz TMP2, UPVAL:RB->closed
2549 | evstdd STR:TMP1, 0(CARG2)
2550 | bne >2
2551 |1:
2552 | ins_next
2553 |
2554 |2: // Check if string is white and ensure upvalue is closed.
2555 | andi. TMP3, TMP3, LJ_GC_WHITES // iswhite(str)
2556 | cmplwi cr1, TMP2, 0
2557 | cror 4*cr0+eq, 4*cr0+eq, 4*cr1+eq
2558 | la CARG1, GG_DISP2G(DISPATCH)
2559 | // Crossed a write barrier. Move the barrier forward.
2560 | beq <1
2561 | bl extern lj_gc_barrieruv // (global_State *g, TValue *tv)
2562 | b <1
2563 break;
2564 case BC_USETN:
2565 | // RA = uvnum*8, RD = num_const*8
2566 | ins_next1
2567 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2568 | srwi RA, RA, 1
2569 | addi RA, RA, offsetof(GCfuncL, uvptr)
2570 | evlddx TMP0, KBASE, RD
2571 | lwzx UPVAL:RB, LFUNC:RB, RA
2572 | lwz TMP1, UPVAL:RB->v
2573 | evstdd TMP0, 0(TMP1)
2574 | ins_next2
2575 break;
2576 case BC_USETP:
2577 | // RA = uvnum*8, RD = primitive_type*8 (~)
2578 | ins_next1
2579 | lwz LFUNC:RB, FRAME_FUNC(BASE)
2580 | srwi RA, RA, 1
2581 | addi RA, RA, offsetof(GCfuncL, uvptr)
2582 | srwi TMP0, RD, 3
2583 | lwzx UPVAL:RB, LFUNC:RB, RA
2584 | not TMP0, TMP0
2585 | lwz TMP1, UPVAL:RB->v
2586 | stw TMP0, 0(TMP1)
2587 | ins_next2
2588 break;
2589
2590 case BC_UCLO:
2591 | // RA = level*8, RD = target
2592 | lwz TMP1, L->openupval
2593 | branch_RD // Do this first since RD is not saved.
2594 | stw BASE, L->base
2595 | cmplwi TMP1, 0
2596 | mr CARG1, L
2597 | beq >1
2598 | add CARG2, BASE, RA
2599 | bl extern lj_func_closeuv // (lua_State *L, TValue *level)
2600 | lwz BASE, L->base
2601 |1:
2602 | ins_next
2603 break;
2604
2605 case BC_FNEW:
2606 | // RA = dst*8, RD = proto_const*8 (~) (holding function prototype)
2607 | srwi TMP1, RD, 1
2608 | stw BASE, L->base
2609 | subfic TMP1, TMP1, -4
2610 | stw PC, SAVE_PC
2611 | lwzx CARG2, KBASE, TMP1 // KBASE-4-tab_const*4
2612 | mr CARG1, L
2613 | lwz CARG3, FRAME_FUNC(BASE)
2614 | // (lua_State *L, GCproto *pt, GCfuncL *parent)
2615 | bl extern lj_func_newL_gc
2616 | // Returns GCfuncL *.
2617 | lwz BASE, L->base
2618 | evmergelo LFUNC:CRET1, TISFUNC, LFUNC:CRET1
2619 | evstddx LFUNC:CRET1, BASE, RA
2620 | ins_next
2621 break;
2622
2623 /* -- Table ops --------------------------------------------------------- */
2624
2625 case BC_TNEW:
2626 case BC_TDUP:
2627 | // RA = dst*8, RD = (hbits|asize)*8 | tab_const*8 (~)
2628 | lwz TMP0, DISPATCH_GL(gc.total)(DISPATCH)
2629 | mr CARG1, L
2630 | lwz TMP1, DISPATCH_GL(gc.threshold)(DISPATCH)
2631 | stw BASE, L->base
2632 | cmplw TMP0, TMP1
2633 | stw PC, SAVE_PC
2634 | bge >5
2635 |1:
2636 if (op == BC_TNEW) {
2637 | rlwinm CARG2, RD, 29, 21, 31
2638 | rlwinm CARG3, RD, 18, 27, 31
2639 | cmpwi CARG2, 0x7ff
2640 | li TMP1, 0x801
2641 | iseleq CARG2, TMP1, CARG2
2642 | bl extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits)
2643 | // Returns Table *.
2644 } else {
2645 | srwi TMP1, RD, 1
2646 | subfic TMP1, TMP1, -4
2647 | lwzx CARG2, KBASE, TMP1 // KBASE-4-tab_const*4
2648 | bl extern lj_tab_dup // (lua_State *L, Table *kt)
2649 | // Returns Table *.
2650 }
2651 | lwz BASE, L->base
2652 | evmergelo TAB:CRET1, TISTAB, TAB:CRET1
2653 | evstddx TAB:CRET1, BASE, RA
2654 | ins_next
2655 |5:
2656 | mr SAVE0, RD
2657 | bl extern lj_gc_step_fixtop // (lua_State *L)
2658 | mr RD, SAVE0
2659 | mr CARG1, L
2660 | b <1
2661 break;
2662
2663 case BC_GGET:
2664 | // RA = dst*8, RD = str_const*8 (~)
2665 case BC_GSET:
2666 | // RA = src*8, RD = str_const*8 (~)
2667 | lwz LFUNC:TMP2, FRAME_FUNC(BASE)
2668 | srwi TMP1, RD, 1
2669 | lwz TAB:RB, LFUNC:TMP2->env
2670 | subfic TMP1, TMP1, -4
2671 | lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
2672 if (op == BC_GGET) {
2673 | b ->BC_TGETS_Z
2674 } else {
2675 | b ->BC_TSETS_Z
2676 }
2677 break;
2678
2679 case BC_TGETV:
2680 | // RA = dst*8, RB = table*8, RC = key*8
2681 | evlddx TAB:RB, BASE, RB
2682 | evlddx RC, BASE, RC
2683 | checktab TAB:RB
2684 | checkfail ->vmeta_tgetv
2685 | checknum RC
2686 | checkfail >5
2687 | // Convert number key to integer
2688 | efdctsi TMP2, RC
2689 | lwz TMP0, TAB:RB->asize
2690 | efdcfsi TMP1, TMP2
2691 | cmplw cr0, TMP0, TMP2
2692 | efdcmpeq cr1, RC, TMP1
2693 | lwz TMP1, TAB:RB->array
2694 | crand 4*cr0+gt, 4*cr0+gt, 4*cr1+gt
2695 | slwi TMP2, TMP2, 3
2696 | ble ->vmeta_tgetv // Integer key and in array part?
2697 | evlddx TMP1, TMP1, TMP2
2698 | checknil TMP1
2699 | checkok >2
2700 |1:
2701 | evstddx TMP1, BASE, RA
2702 | ins_next
2703 |
2704 |2: // Check for __index if table value is nil.
2705 | lwz TAB:TMP2, TAB:RB->metatable
2706 | cmplwi TAB:TMP2, 0
2707 | beq <1 // No metatable: done.
2708 | lbz TMP0, TAB:TMP2->nomm
2709 | andi. TMP0, TMP0, 1<<MM_index
2710 | bne <1 // 'no __index' flag set: done.
2711 | b ->vmeta_tgetv
2712 |
2713 |5:
2714 | checkstr STR:RC // String key?
2715 | checkok ->BC_TGETS_Z
2716 | b ->vmeta_tgetv
2717 break;
2718 case BC_TGETS:
2719 | // RA = dst*8, RB = table*8, RC = str_const*8 (~)
2720 | evlddx TAB:RB, BASE, RB
2721 | srwi TMP1, RC, 1
2722 | checktab TAB:RB
2723 | subfic TMP1, TMP1, -4
2724 | lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
2725 | checkfail ->vmeta_tgets1
2726 |->BC_TGETS_Z:
2727 | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = dst*8
2728 | lwz TMP0, TAB:RB->hmask
2729 | lwz TMP1, STR:RC->hash
2730 | lwz NODE:TMP2, TAB:RB->node
2731 | evmergelo STR:RC, TISSTR, STR:RC
2732 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
2733 | slwi TMP0, TMP1, 5
2734 | slwi TMP1, TMP1, 3
2735 | sub TMP1, TMP0, TMP1
2736 | add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
2737 |1:
2738 | evldd TMP0, NODE:TMP2->key
2739 | evldd TMP1, NODE:TMP2->val
2740 | evcmpeq TMP0, STR:RC
2741 | checkanyfail >4
2742 | checknil TMP1
2743 | checkok >5 // Key found, but nil value?
2744 |3:
2745 | evstddx TMP1, BASE, RA
2746 | ins_next
2747 |
2748 |4: // Follow hash chain.
2749 | lwz NODE:TMP2, NODE:TMP2->next
2750 | cmplwi NODE:TMP2, 0
2751 | bne <1
2752 | // End of hash chain: key not found, nil result.
2753 | evmr TMP1, TISNIL
2754 |
2755 |5: // Check for __index if table value is nil.
2756 | lwz TAB:TMP2, TAB:RB->metatable
2757 | cmplwi TAB:TMP2, 0
2758 | beq <3 // No metatable: done.
2759 | lbz TMP0, TAB:TMP2->nomm
2760 | andi. TMP0, TMP0, 1<<MM_index
2761 | bne <3 // 'no __index' flag set: done.
2762 | b ->vmeta_tgets
2763 break;
2764 case BC_TGETB:
2765 | // RA = dst*8, RB = table*8, RC = index*8
2766 | evlddx TAB:RB, BASE, RB
2767 | srwi TMP0, RC, 3
2768 | checktab TAB:RB
2769 | checkfail ->vmeta_tgetb
2770 | lwz TMP1, TAB:RB->asize
2771 | lwz TMP2, TAB:RB->array
2772 | cmplw TMP0, TMP1
2773 | bge ->vmeta_tgetb
2774 | evlddx TMP1, TMP2, RC
2775 | checknil TMP1
2776 | checkok >5
2777 |1:
2778 | ins_next1
2779 | evstddx TMP1, BASE, RA
2780 | ins_next2
2781 |
2782 |5: // Check for __index if table value is nil.
2783 | lwz TAB:TMP2, TAB:RB->metatable
2784 | cmplwi TAB:TMP2, 0
2785 | beq <1 // No metatable: done.
2786 | lbz TMP2, TAB:TMP2->nomm
2787 | andi. TMP2, TMP2, 1<<MM_index
2788 | bne <1 // 'no __index' flag set: done.
2789 | b ->vmeta_tgetb // Caveat: preserve TMP0!
2790 break;
2791
2792 case BC_TSETV:
2793 | // RA = src*8, RB = table*8, RC = key*8
2794 | evlddx TAB:RB, BASE, RB
2795 | evlddx RC, BASE, RC
2796 | checktab TAB:RB
2797 | checkfail ->vmeta_tsetv
2798 | checknum RC
2799 | checkfail >5
2800 | // Convert number key to integer
2801 | efdctsi TMP2, RC
2802 | evlddx SAVE0, BASE, RA
2803 | lwz TMP0, TAB:RB->asize
2804 | efdcfsi TMP1, TMP2
2805 | cmplw cr0, TMP0, TMP2
2806 | efdcmpeq cr1, RC, TMP1
2807 | lwz TMP1, TAB:RB->array
2808 | crand 4*cr0+gt, 4*cr0+gt, 4*cr1+gt
2809 | slwi TMP0, TMP2, 3
2810 | ble ->vmeta_tsetv // Integer key and in array part?
2811 | lbz TMP3, TAB:RB->marked
2812 | evlddx TMP2, TMP1, TMP0
2813 | checknil TMP2
2814 | checkok >3
2815 |1:
2816 | andi. TMP2, TMP3, LJ_GC_BLACK // isblack(table)
2817 | evstddx SAVE0, TMP1, TMP0
2818 | bne >7
2819 |2:
2820 | ins_next
2821 |
2822 |3: // Check for __newindex if previous value is nil.
2823 | lwz TAB:TMP2, TAB:RB->metatable
2824 | cmplwi TAB:TMP2, 0
2825 | beq <1 // No metatable: done.
2826 | lbz TMP2, TAB:TMP2->nomm
2827 | andi. TMP2, TMP2, 1<<MM_newindex
2828 | bne <1 // 'no __newindex' flag set: done.
2829 | b ->vmeta_tsetv
2830 |
2831 |5:
2832 | checkstr STR:RC // String key?
2833 | checkok ->BC_TSETS_Z
2834 | b ->vmeta_tsetv
2835 |
2836 |7: // Possible table write barrier for the value. Skip valiswhite check.
2837 | barrierback TAB:RB, TMP3, TMP0
2838 | b <2
2839 break;
2840 case BC_TSETS:
2841 | // RA = src*8, RB = table*8, RC = str_const*8 (~)
2842 | evlddx TAB:RB, BASE, RB
2843 | srwi TMP1, RC, 1
2844 | checktab TAB:RB
2845 | subfic TMP1, TMP1, -4
2846 | lwzx STR:RC, KBASE, TMP1 // KBASE-4-str_const*4
2847 | checkfail ->vmeta_tsets1
2848 |->BC_TSETS_Z:
2849 | // TAB:RB = GCtab *, STR:RC = GCstr *, RA = src*8
2850 | lwz TMP0, TAB:RB->hmask
2851 | lwz TMP1, STR:RC->hash
2852 | lwz NODE:TMP2, TAB:RB->node
2853 | evmergelo STR:RC, TISSTR, STR:RC
2854 | stb ZERO, TAB:RB->nomm // Clear metamethod cache.
2855 | and TMP1, TMP1, TMP0 // idx = str->hash & tab->hmask
2856 | evlddx SAVE0, BASE, RA
2857 | slwi TMP0, TMP1, 5
2858 | slwi TMP1, TMP1, 3
2859 | sub TMP1, TMP0, TMP1
2860 | lbz TMP3, TAB:RB->marked
2861 | add NODE:TMP2, NODE:TMP2, TMP1 // node = tab->node + (idx*32-idx*8)
2862 |1:
2863 | evldd TMP0, NODE:TMP2->key
2864 | evldd TMP1, NODE:TMP2->val
2865 | evcmpeq TMP0, STR:RC
2866 | checkanyfail >5
2867 | checknil TMP1
2868 | checkok >4 // Key found, but nil value?
2869 |2:
2870 | andi. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
2871 | evstdd SAVE0, NODE:TMP2->val
2872 | bne >7
2873 |3:
2874 | ins_next
2875 |
2876 |4: // Check for __newindex if previous value is nil.
2877 | lwz TAB:TMP1, TAB:RB->metatable
2878 | cmplwi TAB:TMP1, 0
2879 | beq <2 // No metatable: done.
2880 | lbz TMP0, TAB:TMP1->nomm
2881 | andi. TMP0, TMP0, 1<<MM_newindex
2882 | bne <2 // 'no __newindex' flag set: done.
2883 | b ->vmeta_tsets
2884 |
2885 |5: // Follow hash chain.
2886 | lwz NODE:TMP2, NODE:TMP2->next
2887 | cmplwi NODE:TMP2, 0
2888 | bne <1
2889 | // End of hash chain: key not found, add a new one.
2890 |
2891 | // But check for __newindex first.
2892 | lwz TAB:TMP1, TAB:RB->metatable
2893 | la CARG3, DISPATCH_GL(tmptv)(DISPATCH)
2894 | stw PC, SAVE_PC
2895 | mr CARG1, L
2896 | cmplwi TAB:TMP1, 0
2897 | stw BASE, L->base
2898 | beq >6 // No metatable: continue.
2899 | lbz TMP0, TAB:TMP1->nomm
2900 | andi. TMP0, TMP0, 1<<MM_newindex
2901 | beq ->vmeta_tsets // 'no __newindex' flag NOT set: check.
2902 |6:
2903 | mr CARG2, TAB:RB
2904 | evstdd STR:RC, 0(CARG3)
2905 | bl extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k)
2906 | // Returns TValue *.
2907 | lwz BASE, L->base
2908 | evstdd SAVE0, 0(CRET1)
2909 | b <3 // No 2nd write barrier needed.
2910 |
2911 |7: // Possible table write barrier for the value. Skip valiswhite check.
2912 | barrierback TAB:RB, TMP3, TMP0
2913 | b <3
2914 break;
2915 case BC_TSETB:
2916 | // RA = src*8, RB = table*8, RC = index*8
2917 | evlddx TAB:RB, BASE, RB
2918 | srwi TMP0, RC, 3
2919 | checktab TAB:RB
2920 | checkfail ->vmeta_tsetb
2921 | lwz TMP1, TAB:RB->asize
2922 | lwz TMP2, TAB:RB->array
2923 | lbz TMP3, TAB:RB->marked
2924 | cmplw TMP0, TMP1
2925 | evlddx SAVE0, BASE, RA
2926 | bge ->vmeta_tsetb
2927 | evlddx TMP1, TMP2, RC
2928 | checknil TMP1
2929 | checkok >5
2930 |1:
2931 | andi. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
2932 | evstddx SAVE0, TMP2, RC
2933 | bne >7
2934 |2:
2935 | ins_next
2936 |
2937 |5: // Check for __newindex if previous value is nil.
2938 | lwz TAB:TMP1, TAB:RB->metatable
2939 | cmplwi TAB:TMP1, 0
2940 | beq <1 // No metatable: done.
2941 | lbz TMP1, TAB:TMP1->nomm
2942 | andi. TMP1, TMP1, 1<<MM_newindex
2943 | bne <1 // 'no __newindex' flag set: done.
2944 | b ->vmeta_tsetb // Caveat: preserve TMP0!
2945 |
2946 |7: // Possible table write barrier for the value. Skip valiswhite check.
2947 | barrierback TAB:RB, TMP3, TMP0
2948 | b <2
2949 break;
2950
2951 case BC_TSETM:
2952 | // RA = base*8 (table at base-1), RD = num_const*8 (start index)
2953 | add RA, BASE, RA
2954 |1:
2955 | add TMP3, KBASE, RD
2956 | lwz TAB:CARG2, -4(RA) // Guaranteed to be a table.
2957 | addic. TMP0, MULTRES, -8
2958 | lwz TMP3, 4(TMP3) // Integer constant is in lo-word.
2959 | srwi CARG3, TMP0, 3
2960 | beq >4 // Nothing to copy?
2961 | add CARG3, CARG3, TMP3
2962 | lwz TMP2, TAB:CARG2->asize
2963 | slwi TMP1, TMP3, 3
2964 | lbz TMP3, TAB:CARG2->marked
2965 | cmplw CARG3, TMP2
2966 | add TMP2, RA, TMP0
2967 | lwz TMP0, TAB:CARG2->array
2968 | bgt >5
2969 | add TMP1, TMP1, TMP0
2970 | andi. TMP0, TMP3, LJ_GC_BLACK // isblack(table)
2971 |3: // Copy result slots to table.
2972 | evldd TMP0, 0(RA)
2973 | addi RA, RA, 8
2974 | cmpw cr1, RA, TMP2
2975 | evstdd TMP0, 0(TMP1)
2976 | addi TMP1, TMP1, 8
2977 | blt cr1, <3
2978 | bne >7
2979 |4:
2980 | ins_next
2981 |
2982 |5: // Need to resize array part.
2983 | stw BASE, L->base
2984 | mr CARG1, L
2985 | stw PC, SAVE_PC
2986 | mr SAVE0, RD
2987 | bl extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
2988 | // Must not reallocate the stack.
2989 | mr RD, SAVE0
2990 | b <1
2991 |
2992 |7: // Possible table write barrier for any value. Skip valiswhite check.
2993 | barrierback TAB:CARG2, TMP3, TMP0
2994 | b <4
2995 break;
2996
2997 /* -- Calls and vararg handling ----------------------------------------- */
2998
2999 case BC_CALLM:
3000 | // RA = base*8, (RB = (nresults+1)*8,) RC = extra_nargs*8
3001 | add NARGS8:RC, NARGS8:RC, MULTRES
3002 | // Fall through. Assumes BC_CALL follows.
3003 break;
3004 case BC_CALL:
3005 | // RA = base*8, (RB = (nresults+1)*8,) RC = (nargs+1)*8
3006 | evlddx LFUNC:RB, BASE, RA
3007 | mr TMP2, BASE
3008 | add BASE, BASE, RA
3009 | subi NARGS8:RC, NARGS8:RC, 8
3010 | checkfunc LFUNC:RB
3011 | addi BASE, BASE, 8
3012 | checkfail ->vmeta_call
3013 | ins_call
3014 break;
3015
3016 case BC_CALLMT:
3017 | // RA = base*8, (RB = 0,) RC = extra_nargs*8
3018 | add NARGS8:RC, NARGS8:RC, MULTRES
3019 | // Fall through. Assumes BC_CALLT follows.
3020 break;
3021 case BC_CALLT:
3022 | // RA = base*8, (RB = 0,) RC = (nargs+1)*8
3023 | evlddx LFUNC:RB, BASE, RA
3024 | add RA, BASE, RA
3025 | lwz TMP1, FRAME_PC(BASE)
3026 | subi NARGS8:RC, NARGS8:RC, 8
3027 | checkfunc LFUNC:RB
3028 | addi RA, RA, 8
3029 | checkfail ->vmeta_callt
3030 |->BC_CALLT_Z:
3031 | andi. TMP0, TMP1, FRAME_TYPE // Caveat: preserve cr0 until the crand.
3032 | lbz TMP3, LFUNC:RB->ffid
3033 | xori TMP2, TMP1, FRAME_VARG
3034 | cmplwi cr1, NARGS8:RC, 0
3035 | bne >7
3036 |1:
3037 | stw LFUNC:RB, FRAME_FUNC(BASE) // Copy function down, but keep PC.
3038 | li TMP2, 0
3039 | cmplwi cr7, TMP3, 1 // (> FF_C) Calling a fast function?
3040 | beq cr1, >3
3041 |2:
3042 | addi TMP3, TMP2, 8
3043 | evlddx TMP0, RA, TMP2
3044 | cmplw cr1, TMP3, NARGS8:RC
3045 | evstddx TMP0, BASE, TMP2
3046 | mr TMP2, TMP3
3047 | bne cr1, <2
3048 |3:
3049 | crand 4*cr0+eq, 4*cr0+eq, 4*cr7+gt
3050 | beq >5
3051 |4:
3052 | ins_callt
3053 |
3054 |5: // Tailcall to a fast function with a Lua frame below.
3055 | lwz INS, -4(TMP1)
3056 | decode_RA8 RA, INS
3057 | sub TMP1, BASE, RA
3058 | lwz LFUNC:TMP1, FRAME_FUNC-8(TMP1)
3059 | lwz TMP1, LFUNC:TMP1->pc
3060 | lwz KBASE, PC2PROTO(k)(TMP1) // Need to prepare KBASE.
3061 | b <4
3062 |
3063 |7: // Tailcall from a vararg function.
3064 | andi. TMP0, TMP2, FRAME_TYPEP
3065 | bne <1 // Vararg frame below?
3066 | sub BASE, BASE, TMP2 // Relocate BASE down.
3067 | lwz TMP1, FRAME_PC(BASE)
3068 | andi. TMP0, TMP1, FRAME_TYPE
3069 | b <1
3070 break;
3071
3072 case BC_ITERC:
3073 | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 ((2+1)*8))
3074 | subi RA, RA, 24 // evldd doesn't support neg. offsets.
3075 | mr TMP2, BASE
3076 | evlddx LFUNC:RB, BASE, RA
3077 | add BASE, BASE, RA
3078 | evldd TMP0, 8(BASE)
3079 | evldd TMP1, 16(BASE)
3080 | evstdd LFUNC:RB, 24(BASE) // Copy callable.
3081 | checkfunc LFUNC:RB
3082 | evstdd TMP0, 32(BASE) // Copy state.
3083 | li NARGS8:RC, 16 // Iterators get 2 arguments.
3084 | evstdd TMP1, 40(BASE) // Copy control var.
3085 | addi BASE, BASE, 32
3086 | checkfail ->vmeta_call
3087 | ins_call
3088 break;
3089
3090 case BC_ITERN:
3091 | // RA = base*8, (RB = (nresults+1)*8, RC = (nargs+1)*8 (2+1)*8)
3092 |.if JIT
3093 | // NYI: add hotloop, record BC_ITERN.
3094 |.endif
3095 | add RA, BASE, RA
3096 | lwz TAB:RB, -12(RA)
3097 | lwz RC, -4(RA) // Get index from control var.
3098 | lwz TMP0, TAB:RB->asize
3099 | lwz TMP1, TAB:RB->array
3100 | addi PC, PC, 4
3101 |1: // Traverse array part.
3102 | cmplw RC, TMP0
3103 | slwi TMP3, RC, 3
3104 | bge >5 // Index points after array part?
3105 | evlddx TMP2, TMP1, TMP3
3106 | checknil TMP2
3107 | lwz INS, -4(PC)
3108 | checkok >4
3109 | efdcfsi TMP0, RC
3110 | addi RC, RC, 1
3111 | addis TMP3, PC, -(BCBIAS_J*4 >> 16)
3112 | evstdd TMP2, 8(RA)
3113 | decode_RD4 TMP1, INS
3114 | stw RC, -4(RA) // Update control var.
3115 | add PC, TMP1, TMP3
3116 | evstdd TMP0, 0(RA)
3117 |3:
3118 | ins_next
3119 |
3120 |4: // Skip holes in array part.
3121 | addi RC, RC, 1
3122 | b <1
3123 |
3124 |5: // Traverse hash part.
3125 | lwz TMP1, TAB:RB->hmask
3126 | sub RC, RC, TMP0
3127 | lwz TMP2, TAB:RB->node
3128 |6:
3129 | cmplw RC, TMP1 // End of iteration? Branch to ITERL+1.
3130 | slwi TMP3, RC, 5
3131 | bgt <3
3132 | slwi RB, RC, 3
3133 | sub TMP3, TMP3, RB
3134 | evlddx RB, TMP2, TMP3
3135 | add NODE:TMP3, TMP2, TMP3
3136 | checknil RB
3137 | lwz INS, -4(PC)
3138 | checkok >7
3139 | evldd TMP3, NODE:TMP3->key
3140 | addis TMP2, PC, -(BCBIAS_J*4 >> 16)
3141 | evstdd RB, 8(RA)
3142 | add RC, RC, TMP0
3143 | decode_RD4 TMP1, INS
3144 | evstdd TMP3, 0(RA)
3145 | addi RC, RC, 1
3146 | add PC, TMP1, TMP2
3147 | stw RC, -4(RA) // Update control var.
3148 | b <3
3149 |
3150 |7: // Skip holes in hash part.
3151 | addi RC, RC, 1
3152 | b <6
3153 break;
3154
3155 case BC_ISNEXT:
3156 | // RA = base*8, RD = target (points to ITERN)
3157 | add RA, BASE, RA
3158 | li TMP2, -24
3159 | evlddx CFUNC:TMP1, RA, TMP2
3160 | lwz TMP2, -16(RA)
3161 | lwz TMP3, -8(RA)
3162 | evmergehi TMP0, CFUNC:TMP1, CFUNC:TMP1
3163 | cmpwi cr0, TMP2, LJ_TTAB
3164 | cmpwi cr1, TMP0, LJ_TFUNC
3165 | cmpwi cr6, TMP3, LJ_TNIL
3166 | bne cr1, >5
3167 | lbz TMP1, CFUNC:TMP1->ffid
3168 | crand 4*cr0+eq, 4*cr0+eq, 4*cr6+eq
3169 | cmpwi cr7, TMP1, FF_next_N
3170 | srwi TMP0, RD, 1
3171 | crand 4*cr0+eq, 4*cr0+eq, 4*cr7+eq
3172 | add TMP3, PC, TMP0
3173 | bne cr0, >5
3174 | lus TMP1, 0xfffe
3175 | ori TMP1, TMP1, 0x7fff
3176 | stw ZERO, -4(RA) // Initialize control var.
3177 | stw TMP1, -8(RA)
3178 | addis PC, TMP3, -(BCBIAS_J*4 >> 16)
3179 |1:
3180 | ins_next
3181 |5: // Despecialize bytecode if any of the checks fail.
3182 | li TMP0, BC_JMP
3183 | li TMP1, BC_ITERC
3184 | stb TMP0, -1(PC)
3185 | addis PC, TMP3, -(BCBIAS_J*4 >> 16)
3186 | stb TMP1, 3(PC)
3187 | b <1
3188 break;
3189
3190 case BC_VARG:
3191 | // RA = base*8, RB = (nresults+1)*8, RC = numparams*8
3192 | lwz TMP0, FRAME_PC(BASE)
3193 | add RC, BASE, RC
3194 | add RA, BASE, RA
3195 | addi RC, RC, FRAME_VARG
3196 | add TMP2, RA, RB
3197 | subi TMP3, BASE, 8 // TMP3 = vtop
3198 | sub RC, RC, TMP0 // RC = vbase
3199 | // Note: RC may now be even _above_ BASE if nargs was < numparams.
3200 | cmplwi cr1, RB, 0
3201 | sub. TMP1, TMP3, RC
3202 | beq cr1, >5 // Copy all varargs?
3203 | subi TMP2, TMP2, 16
3204 | ble >2 // No vararg slots?
3205 |1: // Copy vararg slots to destination slots.
3206 | evldd TMP0, 0(RC)
3207 | addi RC, RC, 8
3208 | evstdd TMP0, 0(RA)
3209 | cmplw RA, TMP2
3210 | cmplw cr1, RC, TMP3
3211 | bge >3 // All destination slots filled?
3212 | addi RA, RA, 8
3213 | blt cr1, <1 // More vararg slots?
3214 |2: // Fill up remainder with nil.
3215 | evstdd TISNIL, 0(RA)
3216 | cmplw RA, TMP2
3217 | addi RA, RA, 8
3218 | blt <2
3219 |3:
3220 | ins_next
3221 |
3222 |5: // Copy all varargs.
3223 | lwz TMP0, L->maxstack
3224 | li MULTRES, 8 // MULTRES = (0+1)*8
3225 | ble <3 // No vararg slots?
3226 | add TMP2, RA, TMP1
3227 | cmplw TMP2, TMP0
3228 | addi MULTRES, TMP1, 8
3229 | bgt >7
3230 |6:
3231 | evldd TMP0, 0(RC)
3232 | addi RC, RC, 8
3233 | evstdd TMP0, 0(RA)
3234 | cmplw RC, TMP3
3235 | addi RA, RA, 8
3236 | blt <6 // More vararg slots?
3237 | b <3
3238 |
3239 |7: // Grow stack for varargs.
3240 | mr CARG1, L
3241 | stw RA, L->top
3242 | sub SAVE0, RC, BASE // Need delta, because BASE may change.
3243 | stw BASE, L->base
3244 | sub RA, RA, BASE
3245 | stw PC, SAVE_PC
3246 | srwi CARG2, TMP1, 3
3247 | bl extern lj_state_growstack // (lua_State *L, int n)
3248 | lwz BASE, L->base
3249 | add RA, BASE, RA
3250 | add RC, BASE, SAVE0
3251 | subi TMP3, BASE, 8
3252 | b <6
3253 break;
3254
3255 /* -- Returns ----------------------------------------------------------- */
3256
3257 case BC_RETM:
3258 | // RA = results*8, RD = extra_nresults*8
3259 | add RD, RD, MULTRES // MULTRES >= 8, so RD >= 8.
3260 | // Fall through. Assumes BC_RET follows.
3261 break;
3262
3263 case BC_RET:
3264 | // RA = results*8, RD = (nresults+1)*8
3265 | lwz PC, FRAME_PC(BASE)
3266 | add RA, BASE, RA
3267 | mr MULTRES, RD
3268 |1:
3269 | andi. TMP0, PC, FRAME_TYPE
3270 | xori TMP1, PC, FRAME_VARG
3271 | bne ->BC_RETV_Z
3272 |
3273 |->BC_RET_Z:
3274 | // BASE = base, RA = resultptr, RD = (nresults+1)*8, PC = return
3275 | lwz INS, -4(PC)
3276 | cmpwi RD, 8
3277 | subi TMP2, BASE, 8
3278 | subi RC, RD, 8
3279 | decode_RB8 RB, INS
3280 | beq >3
3281 | li TMP1, 0
3282 |2:
3283 | addi TMP3, TMP1, 8
3284 | evlddx TMP0, RA, TMP1
3285 | cmpw TMP3, RC
3286 | evstddx TMP0, TMP2, TMP1
3287 | beq >3
3288 | addi TMP1, TMP3, 8
3289 | evlddx TMP0, RA, TMP3
3290 | cmpw TMP1, RC
3291 | evstddx TMP0, TMP2, TMP3
3292 | bne <2
3293 |3:
3294 |5:
3295 | cmplw RB, RD
3296 | decode_RA8 RA, INS
3297 | bgt >6
3298 | sub BASE, TMP2, RA
3299 | lwz LFUNC:TMP1, FRAME_FUNC(BASE)
3300 | ins_next1
3301 | lwz TMP1, LFUNC:TMP1->pc
3302 | lwz KBASE, PC2PROTO(k)(TMP1)
3303 | ins_next2
3304 |
3305 |6: // Fill up results with nil.
3306 | subi TMP1, RD, 8
3307 | addi RD, RD, 8
3308 | evstddx TISNIL, TMP2, TMP1
3309 | b <5
3310 |
3311 |->BC_RETV_Z: // Non-standard return case.
3312 | andi. TMP2, TMP1, FRAME_TYPEP
3313 | bne ->vm_return
3314 | // Return from vararg function: relocate BASE down.
3315 | sub BASE, BASE, TMP1
3316 | lwz PC, FRAME_PC(BASE)
3317 | b <1
3318 break;
3319
3320 case BC_RET0: case BC_RET1:
3321 | // RA = results*8, RD = (nresults+1)*8
3322 | lwz PC, FRAME_PC(BASE)
3323 | add RA, BASE, RA
3324 | mr MULTRES, RD
3325 | andi. TMP0, PC, FRAME_TYPE
3326 | xori TMP1, PC, FRAME_VARG
3327 | bne ->BC_RETV_Z
3328 |
3329 | lwz INS, -4(PC)
3330 | subi TMP2, BASE, 8
3331 | decode_RB8 RB, INS
3332 if (op == BC_RET1) {
3333 | evldd TMP0, 0(RA)
3334 | evstdd TMP0, 0(TMP2)
3335 }
3336 |5:
3337 | cmplw RB, RD
3338 | decode_RA8 RA, INS
3339 | bgt >6
3340 | sub BASE, TMP2, RA
3341 | lwz LFUNC:TMP1, FRAME_FUNC(BASE)
3342 | ins_next1
3343 | lwz TMP1, LFUNC:TMP1->pc
3344 | lwz KBASE, PC2PROTO(k)(TMP1)
3345 | ins_next2
3346 |
3347 |6: // Fill up results with nil.
3348 | subi TMP1, RD, 8
3349 | addi RD, RD, 8
3350 | evstddx TISNIL, TMP2, TMP1
3351 | b <5
3352 break;
3353
3354 /* -- Loops and branches ------------------------------------------------ */
3355
3356 case BC_FORL:
3357 |.if JIT
3358 | hotloop
3359 |.endif
3360 | // Fall through. Assumes BC_IFORL follows.
3361 break;
3362
3363 case BC_JFORI:
3364 case BC_JFORL:
3365#if !LJ_HASJIT
3366 break;
3367#endif
3368 case BC_FORI:
3369 case BC_IFORL:
3370 | // RA = base*8, RD = target (after end of loop or start of loop)
3371 vk = (op == BC_IFORL || op == BC_JFORL);
3372 | add RA, BASE, RA
3373 | evldd TMP1, FORL_IDX*8(RA)
3374 | evldd TMP3, FORL_STEP*8(RA)
3375 | evldd TMP2, FORL_STOP*8(RA)
3376 if (!vk) {
3377 | evcmpgtu cr0, TMP1, TISNUM
3378 | evcmpgtu cr7, TMP3, TISNUM
3379 | evcmpgtu cr1, TMP2, TISNUM
3380 | cror 4*cr0+lt, 4*cr0+lt, 4*cr7+lt
3381 | cror 4*cr0+lt, 4*cr0+lt, 4*cr1+lt
3382 | blt ->vmeta_for
3383 }
3384 if (vk) {
3385 | efdadd TMP1, TMP1, TMP3
3386 | evstdd TMP1, FORL_IDX*8(RA)
3387 }
3388 | evcmpgts TMP3, TISNIL
3389 | evstdd TMP1, FORL_EXT*8(RA)
3390 | bge >2
3391 | efdcmpgt TMP1, TMP2
3392 |1:
3393 if (op != BC_JFORL) {
3394 | srwi RD, RD, 1
3395 | add RD, PC, RD
3396 if (op == BC_JFORI) {
3397 | addis PC, RD, -(BCBIAS_J*4 >> 16)
3398 } else {
3399 | addis RD, RD, -(BCBIAS_J*4 >> 16)
3400 }
3401 }
3402 if (op == BC_FORI) {
3403 | iselgt PC, RD, PC
3404 } else if (op == BC_IFORL) {
3405 | iselgt PC, PC, RD
3406 } else {
3407 | ble =>BC_JLOOP
3408 }
3409 | ins_next
3410 |2:
3411 | efdcmpgt TMP2, TMP1
3412 | b <1
3413 break;
3414
3415 case BC_ITERL:
3416 |.if JIT
3417 | hotloop
3418 |.endif
3419 | // Fall through. Assumes BC_IITERL follows.
3420 break;
3421
3422 case BC_JITERL:
3423#if !LJ_HASJIT
3424 break;
3425#endif
3426 case BC_IITERL:
3427 | // RA = base*8, RD = target
3428 | evlddx TMP1, BASE, RA
3429 | subi RA, RA, 8
3430 | checknil TMP1
3431 | checkok >1 // Stop if iterator returned nil.
3432 if (op == BC_JITERL) {
3433 | NYI
3434 } else {
3435 | branch_RD // Otherwise save control var + branch.
3436 | evstddx TMP1, BASE, RA
3437 }
3438 |1:
3439 | ins_next
3440 break;
3441
3442 case BC_LOOP:
3443 | // RA = base*8, RD = target (loop extent)
3444 | // Note: RA/RD is only used by trace recorder to determine scope/extent
3445 | // This opcode does NOT jump, it's only purpose is to detect a hot loop.
3446 |.if JIT
3447 | hotloop
3448 |.endif
3449 | // Fall through. Assumes BC_ILOOP follows.
3450 break;
3451
3452 case BC_ILOOP:
3453 | // RA = base*8, RD = target (loop extent)
3454 | ins_next
3455 break;
3456
3457 case BC_JLOOP:
3458 |.if JIT
3459 | NYI
3460 |.endif
3461 break;
3462
3463 case BC_JMP:
3464 | // RA = base*8 (only used by trace recorder), RD = target
3465 | branch_RD
3466 | ins_next
3467 break;
3468
3469 /* -- Function headers -------------------------------------------------- */
3470
3471 case BC_FUNCF:
3472 |.if JIT
3473 | hotcall
3474 |.endif
3475 case BC_FUNCV: /* NYI: compiled vararg functions. */
3476 | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow.
3477 break;
3478
3479 case BC_JFUNCF:
3480#if !LJ_HASJIT
3481 break;
3482#endif
3483 case BC_IFUNCF:
3484 | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
3485 | lwz TMP2, L->maxstack
3486 | lbz TMP1, -4+PC2PROTO(numparams)(PC)
3487 | lwz KBASE, -4+PC2PROTO(k)(PC)
3488 | cmplw RA, TMP2
3489 | slwi TMP1, TMP1, 3
3490 | bgt ->vm_growstack_l
3491 | ins_next1
3492 |2:
3493 | cmplw NARGS8:RC, TMP1 // Check for missing parameters.
3494 | ble >3
3495 if (op == BC_JFUNCF) {
3496 | NYI
3497 } else {
3498 | ins_next2
3499 }
3500 |
3501 |3: // Clear missing parameters.
3502 | evstddx TISNIL, BASE, NARGS8:RC
3503 | addi NARGS8:RC, NARGS8:RC, 8
3504 | b <2
3505 break;
3506
3507 case BC_JFUNCV:
3508#if !LJ_HASJIT
3509 break;
3510#endif
3511 | NYI // NYI: compiled vararg functions
3512 break; /* NYI: compiled vararg functions. */
3513
3514 case BC_IFUNCV:
3515 | // BASE = new base, RA = BASE+framesize*8, RB = LFUNC, RC = nargs*8
3516 | lwz TMP2, L->maxstack
3517 | add TMP1, BASE, RC
3518 | add TMP0, RA, RC
3519 | stw LFUNC:RB, 4(TMP1) // Store copy of LFUNC.
3520 | addi TMP3, RC, 8+FRAME_VARG
3521 | lwz KBASE, -4+PC2PROTO(k)(PC)
3522 | cmplw TMP0, TMP2
3523 | stw TMP3, 0(TMP1) // Store delta + FRAME_VARG.
3524 | bge ->vm_growstack_l
3525 | lbz TMP2, -4+PC2PROTO(numparams)(PC)
3526 | mr RA, BASE
3527 | mr RC, TMP1
3528 | ins_next1
3529 | cmpwi TMP2, 0
3530 | addi BASE, TMP1, 8
3531 | beq >3
3532 |1:
3533 | cmplw RA, RC // Less args than parameters?
3534 | evldd TMP0, 0(RA)
3535 | bge >4
3536 | evstdd TISNIL, 0(RA) // Clear old fixarg slot (help the GC).
3537 | addi RA, RA, 8
3538 |2:
3539 | addic. TMP2, TMP2, -1
3540 | evstdd TMP0, 8(TMP1)
3541 | addi TMP1, TMP1, 8
3542 | bne <1
3543 |3:
3544 | ins_next2
3545 |
3546 |4: // Clear missing parameters.
3547 | evmr TMP0, TISNIL
3548 | b <2
3549 break;
3550
3551 case BC_FUNCC:
3552 case BC_FUNCCW:
3553 | // BASE = new base, RA = BASE+framesize*8, RB = CFUNC, RC = nargs*8
3554 if (op == BC_FUNCC) {
3555 | lwz TMP3, CFUNC:RB->f
3556 } else {
3557 | lwz TMP3, DISPATCH_GL(wrapf)(DISPATCH)
3558 }
3559 | add TMP1, RA, NARGS8:RC
3560 | lwz TMP2, L->maxstack
3561 | add RC, BASE, NARGS8:RC
3562 | stw BASE, L->base
3563 | cmplw TMP1, TMP2
3564 | stw RC, L->top
3565 | li_vmstate C
3566 | mtctr TMP3
3567 if (op == BC_FUNCCW) {
3568 | lwz CARG2, CFUNC:RB->f
3569 }
3570 | mr CARG1, L
3571 | bgt ->vm_growstack_c // Need to grow stack.
3572 | st_vmstate
3573 | bctrl // (lua_State *L [, lua_CFunction f])
3574 | // Returns nresults.
3575 | lwz TMP1, L->top
3576 | slwi RD, CRET1, 3
3577 | lwz BASE, L->base
3578 | li_vmstate INTERP
3579 | lwz PC, FRAME_PC(BASE) // Fetch PC of caller.
3580 | sub RA, TMP1, RD // RA = L->top - nresults*8
3581 | st_vmstate
3582 | b ->vm_returnc
3583 break;
3584
3585 /* ---------------------------------------------------------------------- */
3586
3587 default:
3588 fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
3589 exit(2);
3590 break;
3591 }
3592}
3593
3594static int build_backend(BuildCtx *ctx)
3595{
3596 int op;
3597
3598 dasm_growpc(Dst, BC__MAX);
3599
3600 build_subroutines(ctx);
3601
3602 |.code_op
3603 for (op = 0; op < BC__MAX; op++)
3604 build_ins(ctx, (BCOp)op, op);
3605
3606 return BC__MAX;
3607}
3608
3609/* Emit pseudo frame-info for all assembler functions. */
3610static void emit_asm_debug(BuildCtx *ctx)
3611{
3612 int i;
3613 switch (ctx->mode) {
3614 case BUILD_elfasm:
3615 fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n");
3616 fprintf(ctx->fp,
3617 ".Lframe0:\n"
3618 "\t.long .LECIE0-.LSCIE0\n"
3619 ".LSCIE0:\n"
3620 "\t.long 0xffffffff\n"
3621 "\t.byte 0x1\n"
3622 "\t.string \"\"\n"
3623 "\t.uleb128 0x1\n"
3624 "\t.sleb128 -4\n"
3625 "\t.byte 65\n"
3626 "\t.byte 0xc\n\t.uleb128 1\n\t.uleb128 0\n"
3627 "\t.align 2\n"
3628 ".LECIE0:\n\n");
3629 fprintf(ctx->fp,
3630 ".LSFDE0:\n"
3631 "\t.long .LEFDE0-.LASFDE0\n"
3632 ".LASFDE0:\n"
3633 "\t.long .Lframe0\n"
3634 "\t.long .Lbegin\n"
3635 "\t.long %d\n"
3636 "\t.byte 0xe\n\t.uleb128 %d\n"
3637 "\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
3638 "\t.byte 0x5\n\t.uleb128 70\n\t.sleb128 37\n",
3639 (int)ctx->codesz, CFRAME_SIZE);
3640 for (i = 14; i <= 31; i++)
3641 fprintf(ctx->fp,
3642 "\t.byte %d\n\t.uleb128 %d\n"
3643 "\t.byte 5\n\t.uleb128 %d\n\t.uleb128 %d\n",
3644 0x80+i, 1+2*(31-i), 1200+i, 2+2*(31-i));
3645 fprintf(ctx->fp,
3646 "\t.align 2\n"
3647 ".LEFDE0:\n\n");
3648 fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n");
3649 fprintf(ctx->fp,
3650 ".Lframe1:\n"
3651 "\t.long .LECIE1-.LSCIE1\n"
3652 ".LSCIE1:\n"
3653 "\t.long 0\n"
3654 "\t.byte 0x1\n"
3655 "\t.string \"zPR\"\n"
3656 "\t.uleb128 0x1\n"
3657 "\t.sleb128 -4\n"
3658 "\t.byte 65\n"
3659 "\t.uleb128 6\n" /* augmentation length */
3660 "\t.byte 0x1b\n" /* pcrel|sdata4 */
3661 "\t.long lj_err_unwind_dwarf-.\n"
3662 "\t.byte 0x1b\n" /* pcrel|sdata4 */
3663 "\t.byte 0xc\n\t.uleb128 1\n\t.uleb128 0\n"
3664 "\t.align 2\n"
3665 ".LECIE1:\n\n");
3666 fprintf(ctx->fp,
3667 ".LSFDE1:\n"
3668 "\t.long .LEFDE1-.LASFDE1\n"
3669 ".LASFDE1:\n"
3670 "\t.long .LASFDE1-.Lframe1\n"
3671 "\t.long .Lbegin-.\n"
3672 "\t.long %d\n"
3673 "\t.uleb128 0\n" /* augmentation length */
3674 "\t.byte 0xe\n\t.uleb128 %d\n"
3675 "\t.byte 0x11\n\t.uleb128 65\n\t.sleb128 -1\n"
3676 "\t.byte 0x5\n\t.uleb128 70\n\t.sleb128 37\n",
3677 (int)ctx->codesz, CFRAME_SIZE);
3678 for (i = 14; i <= 31; i++)
3679 fprintf(ctx->fp,
3680 "\t.byte %d\n\t.uleb128 %d\n"
3681 "\t.byte 5\n\t.uleb128 %d\n\t.uleb128 %d\n",
3682 0x80+i, 1+2*(31-i), 1200+i, 2+2*(31-i));
3683 fprintf(ctx->fp,
3684 "\t.align 2\n"
3685 ".LEFDE1:\n\n");
3686 break;
3687 default:
3688 break;
3689 }
3690}
3691
diff --git a/src/vm_x64.dasc b/src/vm_x64.dasc
new file mode 100644
index 00000000..a003fb4f
--- /dev/null
+++ b/src/vm_x64.dasc
@@ -0,0 +1,4909 @@
1|// Low-level VM code for x64 CPUs in LJ_GC64 mode.
2|// Bytecode interpreter, fast functions and helper functions.
3|// Copyright (C) 2005-2017 Mike Pall. See Copyright Notice in luajit.h
4|
5|.arch x64
6|.section code_op, code_sub
7|
8|.actionlist build_actionlist
9|.globals GLOB_
10|.globalnames globnames
11|.externnames extnames
12|
13|//-----------------------------------------------------------------------
14|
15|.if WIN
16|.define X64WIN, 1 // Windows/x64 calling conventions.
17|.endif
18|
19|// Fixed register assignments for the interpreter.
20|// This is very fragile and has many dependencies. Caveat emptor.
21|.define BASE, rdx // Not C callee-save, refetched anyway.
22|.if X64WIN
23|.define KBASE, rdi // Must be C callee-save.
24|.define PC, rsi // Must be C callee-save.
25|.define DISPATCH, rbx // Must be C callee-save.
26|.define KBASEd, edi
27|.define PCd, esi
28|.define DISPATCHd, ebx
29|.else
30|.define KBASE, r15 // Must be C callee-save.
31|.define PC, rbx // Must be C callee-save.
32|.define DISPATCH, r14 // Must be C callee-save.
33|.define KBASEd, r15d
34|.define PCd, ebx
35|.define DISPATCHd, r14d
36|.endif
37|
38|.define RA, rcx
39|.define RAd, ecx
40|.define RAH, ch
41|.define RAL, cl
42|.define RB, rbp // Must be rbp (C callee-save).
43|.define RBd, ebp
44|.define RC, rax // Must be rax.
45|.define RCd, eax
46|.define RCW, ax
47|.define RCH, ah
48|.define RCL, al
49|.define OP, RBd
50|.define RD, RC
51|.define RDd, RCd
52|.define RDW, RCW
53|.define RDL, RCL
54|.define TMPR, r10
55|.define TMPRd, r10d
56|.define ITYPE, r11
57|.define ITYPEd, r11d
58|
59|.if X64WIN
60|.define CARG1, rcx // x64/WIN64 C call arguments.
61|.define CARG2, rdx
62|.define CARG3, r8
63|.define CARG4, r9
64|.define CARG1d, ecx
65|.define CARG2d, edx
66|.define CARG3d, r8d
67|.define CARG4d, r9d
68|.else
69|.define CARG1, rdi // x64/POSIX C call arguments.
70|.define CARG2, rsi
71|.define CARG3, rdx
72|.define CARG4, rcx
73|.define CARG5, r8
74|.define CARG6, r9
75|.define CARG1d, edi
76|.define CARG2d, esi
77|.define CARG3d, edx
78|.define CARG4d, ecx
79|.define CARG5d, r8d
80|.define CARG6d, r9d
81|.endif
82|
83|// Type definitions. Some of these are only used for documentation.
84|.type L, lua_State
85|.type GL, global_State
86|.type TVALUE, TValue
87|.type GCOBJ, GCobj
88|.type STR, GCstr
89|.type TAB, GCtab
90|.type LFUNC, GCfuncL
91|.type CFUNC, GCfuncC
92|.type PROTO, GCproto
93|.type UPVAL, GCupval
94|.type NODE, Node
95|.type NARGS, int
96|.type TRACE, GCtrace
97|.type SBUF, SBuf
98|
99|// Stack layout while in interpreter. Must match with lj_frame.h.
100|//-----------------------------------------------------------------------
101|.if X64WIN // x64/Windows stack layout
102|
103|.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--).
104|.macro saveregs_
105| push rdi; push rsi; push rbx
106| sub rsp, CFRAME_SPACE
107|.endmacro
108|.macro saveregs
109| push rbp; saveregs_
110|.endmacro
111|.macro restoreregs
112| add rsp, CFRAME_SPACE
113| pop rbx; pop rsi; pop rdi; pop rbp
114|.endmacro
115|
116|.define SAVE_CFRAME, aword [rsp+aword*13]
117|.define SAVE_PC, aword [rsp+aword*12]
118|.define SAVE_L, aword [rsp+aword*11]
119|.define SAVE_ERRF, dword [rsp+dword*21]
120|.define SAVE_NRES, dword [rsp+dword*20]
121|//----- 16 byte aligned, ^^^ 32 byte register save area, owned by interpreter
122|.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter.
123|.define SAVE_R4, aword [rsp+aword*8]
124|.define SAVE_R3, aword [rsp+aword*7]
125|.define SAVE_R2, aword [rsp+aword*6]
126|.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves.
127|.define ARG5, aword [rsp+aword*4]
128|.define CSAVE_4, aword [rsp+aword*3]
129|.define CSAVE_3, aword [rsp+aword*2]
130|.define CSAVE_2, aword [rsp+aword*1]
131|.define CSAVE_1, aword [rsp] //<-- rsp while in interpreter.
132|//----- 16 byte aligned, ^^^ 32 byte register save area, owned by callee
133|
134|.define ARG5d, dword [rsp+dword*8]
135|.define TMP1, ARG5 // TMP1 overlaps ARG5
136|.define TMP1d, ARG5d
137|.define TMP1hi, dword [rsp+dword*9]
138|.define MULTRES, TMP1d // MULTRES overlaps TMP1d.
139|
140|//-----------------------------------------------------------------------
141|.else // x64/POSIX stack layout
142|
143|.define CFRAME_SPACE, aword*5 // Delta for rsp (see <--).
144|.macro saveregs_
145| push rbx; push r15; push r14
146|.if NO_UNWIND
147| push r13; push r12
148|.endif
149| sub rsp, CFRAME_SPACE
150|.endmacro
151|.macro saveregs
152| push rbp; saveregs_
153|.endmacro
154|.macro restoreregs
155| add rsp, CFRAME_SPACE
156|.if NO_UNWIND
157| pop r12; pop r13
158|.endif
159| pop r14; pop r15; pop rbx; pop rbp
160|.endmacro
161|
162|//----- 16 byte aligned,
163|.if NO_UNWIND
164|.define SAVE_RET, aword [rsp+aword*11] //<-- rsp entering interpreter.
165|.define SAVE_R4, aword [rsp+aword*10]
166|.define SAVE_R3, aword [rsp+aword*9]
167|.define SAVE_R2, aword [rsp+aword*8]
168|.define SAVE_R1, aword [rsp+aword*7]
169|.define SAVE_RU2, aword [rsp+aword*6]
170|.define SAVE_RU1, aword [rsp+aword*5] //<-- rsp after register saves.
171|.else
172|.define SAVE_RET, aword [rsp+aword*9] //<-- rsp entering interpreter.
173|.define SAVE_R4, aword [rsp+aword*8]
174|.define SAVE_R3, aword [rsp+aword*7]
175|.define SAVE_R2, aword [rsp+aword*6]
176|.define SAVE_R1, aword [rsp+aword*5] //<-- rsp after register saves.
177|.endif
178|.define SAVE_CFRAME, aword [rsp+aword*4]
179|.define SAVE_PC, aword [rsp+aword*3]
180|.define SAVE_L, aword [rsp+aword*2]
181|.define SAVE_ERRF, dword [rsp+dword*3]
182|.define SAVE_NRES, dword [rsp+dword*2]
183|.define TMP1, aword [rsp] //<-- rsp while in interpreter.
184|//----- 16 byte aligned
185|
186|.define TMP1d, dword [rsp]
187|.define TMP1hi, dword [rsp+dword*1]
188|.define MULTRES, TMP1d // MULTRES overlaps TMP1d.
189|
190|.endif
191|
192|//-----------------------------------------------------------------------
193|
194|// Instruction headers.
195|.macro ins_A; .endmacro
196|.macro ins_AD; .endmacro
197|.macro ins_AJ; .endmacro
198|.macro ins_ABC; movzx RBd, RCH; movzx RCd, RCL; .endmacro
199|.macro ins_AB_; movzx RBd, RCH; .endmacro
200|.macro ins_A_C; movzx RCd, RCL; .endmacro
201|.macro ins_AND; not RD; .endmacro
202|
203|// Instruction decode+dispatch. Carefully tuned (nope, lodsd is not faster).
204|.macro ins_NEXT
205| mov RCd, [PC]
206| movzx RAd, RCH
207| movzx OP, RCL
208| add PC, 4
209| shr RCd, 16
210| jmp aword [DISPATCH+OP*8]
211|.endmacro
212|
213|// Instruction footer.
214|.if 1
215| // Replicated dispatch. Less unpredictable branches, but higher I-Cache use.
216| .define ins_next, ins_NEXT
217| .define ins_next_, ins_NEXT
218|.else
219| // Common dispatch. Lower I-Cache use, only one (very) unpredictable branch.
220| // Affects only certain kinds of benchmarks (and only with -j off).
221| // Around 10%-30% slower on Core2, a lot more slower on P4.
222| .macro ins_next
223| jmp ->ins_next
224| .endmacro
225| .macro ins_next_
226| ->ins_next:
227| ins_NEXT
228| .endmacro
229|.endif
230|
231|// Call decode and dispatch.
232|.macro ins_callt
233| // BASE = new base, RB = LFUNC, RD = nargs+1, [BASE-8] = PC
234| mov PC, LFUNC:RB->pc
235| mov RAd, [PC]
236| movzx OP, RAL
237| movzx RAd, RAH
238| add PC, 4
239| jmp aword [DISPATCH+OP*8]
240|.endmacro
241|
242|.macro ins_call
243| // BASE = new base, RB = LFUNC, RD = nargs+1
244| mov [BASE-8], PC
245| ins_callt
246|.endmacro
247|
248|//-----------------------------------------------------------------------
249|
250|// Macros to clear or set tags.
251|.macro cleartp, reg; shl reg, 17; shr reg, 17; .endmacro
252|.macro settp, reg, tp
253| mov64 ITYPE, ((uint64_t)tp<<47)
254| or reg, ITYPE
255|.endmacro
256|.macro settp, dst, reg, tp
257| mov64 dst, ((uint64_t)tp<<47)
258| or dst, reg
259|.endmacro
260|.macro setint, reg
261| settp reg, LJ_TISNUM
262|.endmacro
263|.macro setint, dst, reg
264| settp dst, reg, LJ_TISNUM
265|.endmacro
266|
267|// Macros to test operand types.
268|.macro checktp_nc, reg, tp, target
269| mov ITYPE, reg
270| sar ITYPE, 47
271| cmp ITYPEd, tp
272| jne target
273|.endmacro
274|.macro checktp, reg, tp, target
275| mov ITYPE, reg
276| cleartp reg
277| sar ITYPE, 47
278| cmp ITYPEd, tp
279| jne target
280|.endmacro
281|.macro checktptp, src, tp, target
282| mov ITYPE, src
283| sar ITYPE, 47
284| cmp ITYPEd, tp
285| jne target
286|.endmacro
287|.macro checkstr, reg, target; checktp reg, LJ_TSTR, target; .endmacro
288|.macro checktab, reg, target; checktp reg, LJ_TTAB, target; .endmacro
289|.macro checkfunc, reg, target; checktp reg, LJ_TFUNC, target; .endmacro
290|
291|.macro checknumx, reg, target, jump
292| mov ITYPE, reg
293| sar ITYPE, 47
294| cmp ITYPEd, LJ_TISNUM
295| jump target
296|.endmacro
297|.macro checkint, reg, target; checknumx reg, target, jne; .endmacro
298|.macro checkinttp, src, target; checknumx src, target, jne; .endmacro
299|.macro checknum, reg, target; checknumx reg, target, jae; .endmacro
300|.macro checknumtp, src, target; checknumx src, target, jae; .endmacro
301|.macro checknumber, src, target; checknumx src, target, ja; .endmacro
302|
303|.macro mov_false, reg; mov64 reg, (int64_t)~((uint64_t)1<<47); .endmacro
304|.macro mov_true, reg; mov64 reg, (int64_t)~((uint64_t)2<<47); .endmacro
305|
306|// These operands must be used with movzx.
307|.define PC_OP, byte [PC-4]
308|.define PC_RA, byte [PC-3]
309|.define PC_RB, byte [PC-1]
310|.define PC_RC, byte [PC-2]
311|.define PC_RD, word [PC-2]
312|
313|.macro branchPC, reg
314| lea PC, [PC+reg*4-BCBIAS_J*4]
315|.endmacro
316|
317|// Assumes DISPATCH is relative to GL.
318#define DISPATCH_GL(field) (GG_DISP2G + (int)offsetof(global_State, field))
319#define DISPATCH_J(field) (GG_DISP2J + (int)offsetof(jit_State, field))
320|
321#define PC2PROTO(field) ((int)offsetof(GCproto, field)-(int)sizeof(GCproto))
322|
323|// Decrement hashed hotcount and trigger trace recorder if zero.
324|.macro hotloop, reg
325| mov reg, PCd
326| shr reg, 1
327| and reg, HOTCOUNT_PCMASK
328| sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_LOOP
329| jb ->vm_hotloop
330|.endmacro
331|
332|.macro hotcall, reg
333| mov reg, PCd
334| shr reg, 1
335| and reg, HOTCOUNT_PCMASK
336| sub word [DISPATCH+reg+GG_DISP2HOT], HOTCOUNT_CALL
337| jb ->vm_hotcall
338|.endmacro
339|
340|// Set current VM state.
341|.macro set_vmstate, st
342| mov dword [DISPATCH+DISPATCH_GL(vmstate)], ~LJ_VMST_..st
343|.endmacro
344|
345|.macro fpop1; fstp st1; .endmacro
346|
347|// Synthesize SSE FP constants.
348|.macro sseconst_abs, reg, tmp // Synthesize abs mask.
349| mov64 tmp, U64x(7fffffff,ffffffff); movd reg, tmp
350|.endmacro
351|
352|.macro sseconst_hi, reg, tmp, val // Synthesize hi-32 bit const.
353| mov64 tmp, U64x(val,00000000); movd reg, tmp
354|.endmacro
355|
356|.macro sseconst_sign, reg, tmp // Synthesize sign mask.
357| sseconst_hi reg, tmp, 80000000
358|.endmacro
359|.macro sseconst_1, reg, tmp // Synthesize 1.0.
360| sseconst_hi reg, tmp, 3ff00000
361|.endmacro
362|.macro sseconst_m1, reg, tmp // Synthesize -1.0.
363| sseconst_hi reg, tmp, bff00000
364|.endmacro
365|.macro sseconst_2p52, reg, tmp // Synthesize 2^52.
366| sseconst_hi reg, tmp, 43300000
367|.endmacro
368|.macro sseconst_tobit, reg, tmp // Synthesize 2^52 + 2^51.
369| sseconst_hi reg, tmp, 43380000
370|.endmacro
371|
372|// Move table write barrier back. Overwrites reg.
373|.macro barrierback, tab, reg
374| and byte tab->marked, (uint8_t)~LJ_GC_BLACK // black2gray(tab)
375| mov reg, [DISPATCH+DISPATCH_GL(gc.grayagain)]
376| mov [DISPATCH+DISPATCH_GL(gc.grayagain)], tab
377| mov tab->gclist, reg
378|.endmacro
379|
380|//-----------------------------------------------------------------------
381
382/* Generate subroutines used by opcodes and other parts of the VM. */
383/* The .code_sub section should be last to help static branch prediction. */
384static void build_subroutines(BuildCtx *ctx)
385{
386 |.code_sub
387 |
388 |//-----------------------------------------------------------------------
389 |//-- Return handling ----------------------------------------------------
390 |//-----------------------------------------------------------------------
391 |
392 |->vm_returnp:
393 | test PCd, FRAME_P
394 | jz ->cont_dispatch
395 |
396 | // Return from pcall or xpcall fast func.
397 | and PC, -8
398 | sub BASE, PC // Restore caller base.
399 | lea RA, [RA+PC-8] // Rebase RA and prepend one result.
400 | mov PC, [BASE-8] // Fetch PC of previous frame.
401 | // Prepending may overwrite the pcall frame, so do it at the end.
402 | mov_true ITYPE
403 | mov aword [BASE+RA], ITYPE // Prepend true to results.
404 |
405 |->vm_returnc:
406 | add RDd, 1 // RD = nresults+1
407 | jz ->vm_unwind_yield
408 | mov MULTRES, RDd
409 | test PC, FRAME_TYPE
410 | jz ->BC_RET_Z // Handle regular return to Lua.
411 |
412 |->vm_return:
413 | // BASE = base, RA = resultofs, RD = nresults+1 (= MULTRES), PC = return
414 | xor PC, FRAME_C
415 | test PCd, FRAME_TYPE
416 | jnz ->vm_returnp
417 |
418 | // Return to C.
419 | set_vmstate C
420 | and PC, -8
421 | sub PC, BASE
422 | neg PC // Previous base = BASE - delta.
423 |
424 | sub RDd, 1
425 | jz >2
426 |1: // Move results down.
427 | mov RB, [BASE+RA]
428 | mov [BASE-16], RB
429 | add BASE, 8
430 | sub RDd, 1
431 | jnz <1
432 |2:
433 | mov L:RB, SAVE_L
434 | mov L:RB->base, PC
435 |3:
436 | mov RDd, MULTRES
437 | mov RAd, SAVE_NRES // RA = wanted nresults+1
438 |4:
439 | cmp RAd, RDd
440 | jne >6 // More/less results wanted?
441 |5:
442 | sub BASE, 16
443 | mov L:RB->top, BASE
444 |
445 |->vm_leave_cp:
446 | mov RA, SAVE_CFRAME // Restore previous C frame.
447 | mov L:RB->cframe, RA
448 | xor eax, eax // Ok return status for vm_pcall.
449 |
450 |->vm_leave_unw:
451 | restoreregs
452 | ret
453 |
454 |6:
455 | jb >7 // Less results wanted?
456 | // More results wanted. Check stack size and fill up results with nil.
457 | cmp BASE, L:RB->maxstack
458 | ja >8
459 | mov aword [BASE-16], LJ_TNIL
460 | add BASE, 8
461 | add RDd, 1
462 | jmp <4
463 |
464 |7: // Less results wanted.
465 | test RAd, RAd
466 | jz <5 // But check for LUA_MULTRET+1.
467 | sub RA, RD // Negative result!
468 | lea BASE, [BASE+RA*8] // Correct top.
469 | jmp <5
470 |
471 |8: // Corner case: need to grow stack for filling up results.
472 | // This can happen if:
473 | // - A C function grows the stack (a lot).
474 | // - The GC shrinks the stack in between.
475 | // - A return back from a lua_call() with (high) nresults adjustment.
476 | mov L:RB->top, BASE // Save current top held in BASE (yes).
477 | mov MULTRES, RDd // Need to fill only remainder with nil.
478 | mov CARG2d, RAd
479 | mov CARG1, L:RB
480 | call extern lj_state_growstack // (lua_State *L, int n)
481 | mov BASE, L:RB->top // Need the (realloced) L->top in BASE.
482 | jmp <3
483 |
484 |->vm_unwind_yield:
485 | mov al, LUA_YIELD
486 | jmp ->vm_unwind_c_eh
487 |
488 |->vm_unwind_c: // Unwind C stack, return from vm_pcall.
489 | // (void *cframe, int errcode)
490 | mov eax, CARG2d // Error return status for vm_pcall.
491 | mov rsp, CARG1
492 |->vm_unwind_c_eh: // Landing pad for external unwinder.
493 | mov L:RB, SAVE_L
494 | mov GL:RB, L:RB->glref
495 | mov dword GL:RB->vmstate, ~LJ_VMST_C
496 | jmp ->vm_leave_unw
497 |
498 |->vm_unwind_rethrow:
499 |.if not X64WIN
500 | mov CARG1, SAVE_L
501 | mov CARG2d, eax
502 | restoreregs
503 | jmp extern lj_err_throw // (lua_State *L, int errcode)
504 |.endif
505 |
506 |->vm_unwind_ff: // Unwind C stack, return from ff pcall.
507 | // (void *cframe)
508 | and CARG1, CFRAME_RAWMASK
509 | mov rsp, CARG1
510 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
511 | mov L:RB, SAVE_L
512 | mov RDd, 1+1 // Really 1+2 results, incr. later.
513 | mov BASE, L:RB->base
514 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
515 | add DISPATCH, GG_G2DISP
516 | mov PC, [BASE-8] // Fetch PC of previous frame.
517 | mov_false RA
518 | mov RB, [BASE]
519 | mov [BASE-16], RA // Prepend false to error message.
520 | mov [BASE-8], RB
521 | mov RA, -16 // Results start at BASE+RA = BASE-16.
522 | set_vmstate INTERP
523 | jmp ->vm_returnc // Increments RD/MULTRES and returns.
524 |
525 |//-----------------------------------------------------------------------
526 |//-- Grow stack for calls -----------------------------------------------
527 |//-----------------------------------------------------------------------
528 |
529 |->vm_growstack_c: // Grow stack for C function.
530 | mov CARG2d, LUA_MINSTACK
531 | jmp >2
532 |
533 |->vm_growstack_v: // Grow stack for vararg Lua function.
534 | sub RD, 16 // LJ_FR2
535 | jmp >1
536 |
537 |->vm_growstack_f: // Grow stack for fixarg Lua function.
538 | // BASE = new base, RD = nargs+1, RB = L, PC = first PC
539 | lea RD, [BASE+NARGS:RD*8-8]
540 |1:
541 | movzx RAd, byte [PC-4+PC2PROTO(framesize)]
542 | add PC, 4 // Must point after first instruction.
543 | mov L:RB->base, BASE
544 | mov L:RB->top, RD
545 | mov SAVE_PC, PC
546 | mov CARG2, RA
547 |2:
548 | // RB = L, L->base = new base, L->top = top
549 | mov CARG1, L:RB
550 | call extern lj_state_growstack // (lua_State *L, int n)
551 | mov BASE, L:RB->base
552 | mov RD, L:RB->top
553 | mov LFUNC:RB, [BASE-16]
554 | cleartp LFUNC:RB
555 | sub RD, BASE
556 | shr RDd, 3
557 | add NARGS:RDd, 1
558 | // BASE = new base, RB = LFUNC, RD = nargs+1
559 | ins_callt // Just retry the call.
560 |
561 |//-----------------------------------------------------------------------
562 |//-- Entry points into the assembler VM ---------------------------------
563 |//-----------------------------------------------------------------------
564 |
565 |->vm_resume: // Setup C frame and resume thread.
566 | // (lua_State *L, TValue *base, int nres1 = 0, ptrdiff_t ef = 0)
567 | saveregs
568 | mov L:RB, CARG1 // Caveat: CARG1 may be RA.
569 | mov SAVE_L, CARG1
570 | mov RA, CARG2
571 | mov PCd, FRAME_CP
572 | xor RDd, RDd
573 | lea KBASE, [esp+CFRAME_RESUME]
574 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
575 | add DISPATCH, GG_G2DISP
576 | mov SAVE_PC, RD // Any value outside of bytecode is ok.
577 | mov SAVE_CFRAME, RD
578 | mov SAVE_NRES, RDd
579 | mov SAVE_ERRF, RDd
580 | mov L:RB->cframe, KBASE
581 | cmp byte L:RB->status, RDL
582 | je >2 // Initial resume (like a call).
583 |
584 | // Resume after yield (like a return).
585 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
586 | set_vmstate INTERP
587 | mov byte L:RB->status, RDL
588 | mov BASE, L:RB->base
589 | mov RD, L:RB->top
590 | sub RD, RA
591 | shr RDd, 3
592 | add RDd, 1 // RD = nresults+1
593 | sub RA, BASE // RA = resultofs
594 | mov PC, [BASE-8]
595 | mov MULTRES, RDd
596 | test PCd, FRAME_TYPE
597 | jz ->BC_RET_Z
598 | jmp ->vm_return
599 |
600 |->vm_pcall: // Setup protected C frame and enter VM.
601 | // (lua_State *L, TValue *base, int nres1, ptrdiff_t ef)
602 | saveregs
603 | mov PCd, FRAME_CP
604 | mov SAVE_ERRF, CARG4d
605 | jmp >1
606 |
607 |->vm_call: // Setup C frame and enter VM.
608 | // (lua_State *L, TValue *base, int nres1)
609 | saveregs
610 | mov PCd, FRAME_C
611 |
612 |1: // Entry point for vm_pcall above (PC = ftype).
613 | mov SAVE_NRES, CARG3d
614 | mov L:RB, CARG1 // Caveat: CARG1 may be RA.
615 | mov SAVE_L, CARG1
616 | mov RA, CARG2
617 |
618 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
619 | mov KBASE, L:RB->cframe // Add our C frame to cframe chain.
620 | mov SAVE_CFRAME, KBASE
621 | mov SAVE_PC, L:RB // Any value outside of bytecode is ok.
622 | add DISPATCH, GG_G2DISP
623 | mov L:RB->cframe, rsp
624 |
625 |2: // Entry point for vm_resume/vm_cpcall (RA = base, RB = L, PC = ftype).
626 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
627 | set_vmstate INTERP
628 | mov BASE, L:RB->base // BASE = old base (used in vmeta_call).
629 | add PC, RA
630 | sub PC, BASE // PC = frame delta + frame type
631 |
632 | mov RD, L:RB->top
633 | sub RD, RA
634 | shr NARGS:RDd, 3
635 | add NARGS:RDd, 1 // RD = nargs+1
636 |
637 |->vm_call_dispatch:
638 | mov LFUNC:RB, [RA-16]
639 | checkfunc LFUNC:RB, ->vmeta_call // Ensure KBASE defined and != BASE.
640 |
641 |->vm_call_dispatch_f:
642 | mov BASE, RA
643 | ins_call
644 | // BASE = new base, RB = func, RD = nargs+1, PC = caller PC
645 |
646 |->vm_cpcall: // Setup protected C frame, call C.
647 | // (lua_State *L, lua_CFunction func, void *ud, lua_CPFunction cp)
648 | saveregs
649 | mov L:RB, CARG1 // Caveat: CARG1 may be RA.
650 | mov SAVE_L, CARG1
651 | mov SAVE_PC, L:RB // Any value outside of bytecode is ok.
652 |
653 | mov KBASE, L:RB->stack // Compute -savestack(L, L->top).
654 | sub KBASE, L:RB->top
655 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
656 | mov SAVE_ERRF, 0 // No error function.
657 | mov SAVE_NRES, KBASEd // Neg. delta means cframe w/o frame.
658 | add DISPATCH, GG_G2DISP
659 | // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe).
660 |
661 | mov KBASE, L:RB->cframe // Add our C frame to cframe chain.
662 | mov SAVE_CFRAME, KBASE
663 | mov L:RB->cframe, rsp
664 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
665 |
666 | call CARG4 // (lua_State *L, lua_CFunction func, void *ud)
667 | // TValue * (new base) or NULL returned in eax (RC).
668 | test RC, RC
669 | jz ->vm_leave_cp // No base? Just remove C frame.
670 | mov RA, RC
671 | mov PCd, FRAME_CP
672 | jmp <2 // Else continue with the call.
673 |
674 |//-----------------------------------------------------------------------
675 |//-- Metamethod handling ------------------------------------------------
676 |//-----------------------------------------------------------------------
677 |
678 |//-- Continuation dispatch ----------------------------------------------
679 |
680 |->cont_dispatch:
681 | // BASE = meta base, RA = resultofs, RD = nresults+1 (also in MULTRES)
682 | add RA, BASE
683 | and PC, -8
684 | mov RB, BASE
685 | sub BASE, PC // Restore caller BASE.
686 | mov aword [RA+RD*8-8], LJ_TNIL // Ensure one valid arg.
687 | mov RC, RA // ... in [RC]
688 | mov PC, [RB-24] // Restore PC from [cont|PC].
689 | mov RA, qword [RB-32] // May be negative on WIN64 with debug.
690 |.if FFI
691 | cmp RA, 1
692 | jbe >1
693 |.endif
694 | mov LFUNC:KBASE, [BASE-16]
695 | cleartp LFUNC:KBASE
696 | mov KBASE, LFUNC:KBASE->pc
697 | mov KBASE, [KBASE+PC2PROTO(k)]
698 | // BASE = base, RC = result, RB = meta base
699 | jmp RA // Jump to continuation.
700 |
701 |.if FFI
702 |1:
703 | je ->cont_ffi_callback // cont = 1: return from FFI callback.
704 | // cont = 0: Tail call from C function.
705 | sub RB, BASE
706 | shr RBd, 3
707 | lea RDd, [RBd-3]
708 | jmp ->vm_call_tail
709 |.endif
710 |
711 |->cont_cat: // BASE = base, RC = result, RB = mbase
712 | movzx RAd, PC_RB
713 | sub RB, 32
714 | lea RA, [BASE+RA*8]
715 | sub RA, RB
716 | je ->cont_ra
717 | neg RA
718 | shr RAd, 3
719 |.if X64WIN
720 | mov CARG3d, RAd
721 | mov L:CARG1, SAVE_L
722 | mov L:CARG1->base, BASE
723 | mov RC, [RC]
724 | mov [RB], RC
725 | mov CARG2, RB
726 |.else
727 | mov L:CARG1, SAVE_L
728 | mov L:CARG1->base, BASE
729 | mov CARG3d, RAd
730 | mov RA, [RC]
731 | mov [RB], RA
732 | mov CARG2, RB
733 |.endif
734 | jmp ->BC_CAT_Z
735 |
736 |//-- Table indexing metamethods -----------------------------------------
737 |
738 |->vmeta_tgets:
739 | settp STR:RC, LJ_TSTR // STR:RC = GCstr *
740 | mov TMP1, STR:RC
741 | lea RC, TMP1
742 | cmp PC_OP, BC_GGET
743 | jne >1
744 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab *
745 | lea RB, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv.
746 | mov [RB], TAB:RA
747 | jmp >2
748 |
749 |->vmeta_tgetb:
750 | movzx RCd, PC_RC
751 |.if DUALNUM
752 | setint RC
753 | mov TMP1, RC
754 |.else
755 | cvtsi2sd xmm0, RCd
756 | movsd TMP1, xmm0
757 |.endif
758 | lea RC, TMP1
759 | jmp >1
760 |
761 |->vmeta_tgetv:
762 | movzx RCd, PC_RC // Reload TValue *k from RC.
763 | lea RC, [BASE+RC*8]
764 |1:
765 | movzx RBd, PC_RB // Reload TValue *t from RB.
766 | lea RB, [BASE+RB*8]
767 |2:
768 | mov L:CARG1, SAVE_L
769 | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE.
770 | mov CARG2, RB
771 | mov CARG3, RC
772 | mov L:RB, L:CARG1
773 | mov SAVE_PC, PC
774 | call extern lj_meta_tget // (lua_State *L, TValue *o, TValue *k)
775 | // TValue * (finished) or NULL (metamethod) returned in eax (RC).
776 | mov BASE, L:RB->base
777 | test RC, RC
778 | jz >3
779 |->cont_ra: // BASE = base, RC = result
780 | movzx RAd, PC_RA
781 | mov RB, [RC]
782 | mov [BASE+RA*8], RB
783 | ins_next
784 |
785 |3: // Call __index metamethod.
786 | // BASE = base, L->top = new base, stack = cont/func/t/k
787 | mov RA, L:RB->top
788 | mov [RA-24], PC // [cont|PC]
789 | lea PC, [RA+FRAME_CONT]
790 | sub PC, BASE
791 | mov LFUNC:RB, [RA-16] // Guaranteed to be a function here.
792 | mov NARGS:RDd, 2+1 // 2 args for func(t, k).
793 | cleartp LFUNC:RB
794 | jmp ->vm_call_dispatch_f
795 |
796 |->vmeta_tgetr:
797 | mov CARG1, TAB:RB
798 | mov RB, BASE // Save BASE.
799 | mov CARG2d, RCd // Caveat: CARG2 == BASE
800 | call extern lj_tab_getinth // (GCtab *t, int32_t key)
801 | // cTValue * or NULL returned in eax (RC).
802 | movzx RAd, PC_RA
803 | mov BASE, RB // Restore BASE.
804 | test RC, RC
805 | jnz ->BC_TGETR_Z
806 | mov ITYPE, LJ_TNIL
807 | jmp ->BC_TGETR2_Z
808 |
809 |//-----------------------------------------------------------------------
810 |
811 |->vmeta_tsets:
812 | settp STR:RC, LJ_TSTR // STR:RC = GCstr *
813 | mov TMP1, STR:RC
814 | lea RC, TMP1
815 | cmp PC_OP, BC_GSET
816 | jne >1
817 | settp TAB:RA, TAB:RB, LJ_TTAB // TAB:RB = GCtab *
818 | lea RB, [DISPATCH+DISPATCH_GL(tmptv)] // Store fn->l.env in g->tmptv.
819 | mov [RB], TAB:RA
820 | jmp >2
821 |
822 |->vmeta_tsetb:
823 | movzx RCd, PC_RC
824 |.if DUALNUM
825 | setint RC
826 | mov TMP1, RC
827 |.else
828 | cvtsi2sd xmm0, RCd
829 | movsd TMP1, xmm0
830 |.endif
831 | lea RC, TMP1
832 | jmp >1
833 |
834 |->vmeta_tsetv:
835 | movzx RCd, PC_RC // Reload TValue *k from RC.
836 | lea RC, [BASE+RC*8]
837 |1:
838 | movzx RBd, PC_RB // Reload TValue *t from RB.
839 | lea RB, [BASE+RB*8]
840 |2:
841 | mov L:CARG1, SAVE_L
842 | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE.
843 | mov CARG2, RB
844 | mov CARG3, RC
845 | mov L:RB, L:CARG1
846 | mov SAVE_PC, PC
847 | call extern lj_meta_tset // (lua_State *L, TValue *o, TValue *k)
848 | // TValue * (finished) or NULL (metamethod) returned in eax (RC).
849 | mov BASE, L:RB->base
850 | test RC, RC
851 | jz >3
852 | // NOBARRIER: lj_meta_tset ensures the table is not black.
853 | movzx RAd, PC_RA
854 | mov RB, [BASE+RA*8]
855 | mov [RC], RB
856 |->cont_nop: // BASE = base, (RC = result)
857 | ins_next
858 |
859 |3: // Call __newindex metamethod.
860 | // BASE = base, L->top = new base, stack = cont/func/t/k/(v)
861 | mov RA, L:RB->top
862 | mov [RA-24], PC // [cont|PC]
863 | movzx RCd, PC_RA
864 | // Copy value to third argument.
865 | mov RB, [BASE+RC*8]
866 | mov [RA+16], RB
867 | lea PC, [RA+FRAME_CONT]
868 | sub PC, BASE
869 | mov LFUNC:RB, [RA-16] // Guaranteed to be a function here.
870 | mov NARGS:RDd, 3+1 // 3 args for func(t, k, v).
871 | cleartp LFUNC:RB
872 | jmp ->vm_call_dispatch_f
873 |
874 |->vmeta_tsetr:
875 |.if X64WIN
876 | mov L:CARG1, SAVE_L
877 | mov CARG3d, RCd
878 | mov L:CARG1->base, BASE
879 | xchg CARG2, TAB:RB // Caveat: CARG2 == BASE.
880 |.else
881 | mov L:CARG1, SAVE_L
882 | mov CARG2, TAB:RB
883 | mov L:CARG1->base, BASE
884 | mov RB, BASE // Save BASE.
885 | mov CARG3d, RCd // Caveat: CARG3 == BASE.
886 |.endif
887 | mov SAVE_PC, PC
888 | call extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
889 | // TValue * returned in eax (RC).
890 | movzx RAd, PC_RA
891 | mov BASE, RB // Restore BASE.
892 | jmp ->BC_TSETR_Z
893 |
894 |//-- Comparison metamethods ---------------------------------------------
895 |
896 |->vmeta_comp:
897 | movzx RDd, PC_RD
898 | movzx RAd, PC_RA
899 | mov L:RB, SAVE_L
900 | mov L:RB->base, BASE // Caveat: CARG2/CARG3 == BASE.
901 |.if X64WIN
902 | lea CARG3, [BASE+RD*8]
903 | lea CARG2, [BASE+RA*8]
904 |.else
905 | lea CARG2, [BASE+RA*8]
906 | lea CARG3, [BASE+RD*8]
907 |.endif
908 | mov CARG1, L:RB // Caveat: CARG1/CARG4 == RA.
909 | movzx CARG4d, PC_OP
910 | mov SAVE_PC, PC
911 | call extern lj_meta_comp // (lua_State *L, TValue *o1, *o2, int op)
912 | // 0/1 or TValue * (metamethod) returned in eax (RC).
913 |3:
914 | mov BASE, L:RB->base
915 | cmp RC, 1
916 | ja ->vmeta_binop
917 |4:
918 | lea PC, [PC+4]
919 | jb >6
920 |5:
921 | movzx RDd, PC_RD
922 | branchPC RD
923 |6:
924 | ins_next
925 |
926 |->cont_condt: // BASE = base, RC = result
927 | add PC, 4
928 | mov ITYPE, [RC]
929 | sar ITYPE, 47
930 | cmp ITYPEd, LJ_TISTRUECOND // Branch if result is true.
931 | jb <5
932 | jmp <6
933 |
934 |->cont_condf: // BASE = base, RC = result
935 | mov ITYPE, [RC]
936 | sar ITYPE, 47
937 | cmp ITYPEd, LJ_TISTRUECOND // Branch if result is false.
938 | jmp <4
939 |
940 |->vmeta_equal:
941 | cleartp TAB:RD
942 | sub PC, 4
943 |.if X64WIN
944 | mov CARG3, RD
945 | mov CARG4d, RBd
946 | mov L:RB, SAVE_L
947 | mov L:RB->base, BASE // Caveat: CARG2 == BASE.
948 | mov CARG2, RA
949 | mov CARG1, L:RB // Caveat: CARG1 == RA.
950 |.else
951 | mov CARG2, RA
952 | mov CARG4d, RBd // Caveat: CARG4 == RA.
953 | mov L:RB, SAVE_L
954 | mov L:RB->base, BASE // Caveat: CARG3 == BASE.
955 | mov CARG3, RD
956 | mov CARG1, L:RB
957 |.endif
958 | mov SAVE_PC, PC
959 | call extern lj_meta_equal // (lua_State *L, GCobj *o1, *o2, int ne)
960 | // 0/1 or TValue * (metamethod) returned in eax (RC).
961 | jmp <3
962 |
963 |->vmeta_equal_cd:
964 |.if FFI
965 | sub PC, 4
966 | mov L:RB, SAVE_L
967 | mov L:RB->base, BASE
968 | mov CARG1, L:RB
969 | mov CARG2d, dword [PC-4]
970 | mov SAVE_PC, PC
971 | call extern lj_meta_equal_cd // (lua_State *L, BCIns ins)
972 | // 0/1 or TValue * (metamethod) returned in eax (RC).
973 | jmp <3
974 |.endif
975 |
976 |->vmeta_istype:
977 | mov L:RB, SAVE_L
978 | mov L:RB->base, BASE // Caveat: CARG2/CARG3 may be BASE.
979 | mov CARG2d, RAd
980 | mov CARG3d, RDd
981 | mov L:CARG1, L:RB
982 | mov SAVE_PC, PC
983 | call extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
984 | mov BASE, L:RB->base
985 | jmp <6
986 |
987 |//-- Arithmetic metamethods ---------------------------------------------
988 |
989 |->vmeta_arith_vno:
990 |.if DUALNUM
991 | movzx RBd, PC_RB
992 | movzx RCd, PC_RC
993 |.endif
994 |->vmeta_arith_vn:
995 | lea RC, [KBASE+RC*8]
996 | jmp >1
997 |
998 |->vmeta_arith_nvo:
999 |.if DUALNUM
1000 | movzx RBd, PC_RB
1001 | movzx RCd, PC_RC
1002 |.endif
1003 |->vmeta_arith_nv:
1004 | lea TMPR, [KBASE+RC*8]
1005 | lea RC, [BASE+RB*8]
1006 | mov RB, TMPR
1007 | jmp >2
1008 |
1009 |->vmeta_unm:
1010 | lea RC, [BASE+RD*8]
1011 | mov RB, RC
1012 | jmp >2
1013 |
1014 |->vmeta_arith_vvo:
1015 |.if DUALNUM
1016 | movzx RBd, PC_RB
1017 | movzx RCd, PC_RC
1018 |.endif
1019 |->vmeta_arith_vv:
1020 | lea RC, [BASE+RC*8]
1021 |1:
1022 | lea RB, [BASE+RB*8]
1023 |2:
1024 | lea RA, [BASE+RA*8]
1025 |.if X64WIN
1026 | mov CARG3, RB
1027 | mov CARG4, RC
1028 | movzx RCd, PC_OP
1029 | mov ARG5d, RCd
1030 | mov L:RB, SAVE_L
1031 | mov L:RB->base, BASE // Caveat: CARG2 == BASE.
1032 | mov CARG2, RA
1033 | mov CARG1, L:RB // Caveat: CARG1 == RA.
1034 |.else
1035 | movzx CARG5d, PC_OP
1036 | mov CARG2, RA
1037 | mov CARG4, RC // Caveat: CARG4 == RA.
1038 | mov L:CARG1, SAVE_L
1039 | mov L:CARG1->base, BASE // Caveat: CARG3 == BASE.
1040 | mov CARG3, RB
1041 | mov L:RB, L:CARG1
1042 |.endif
1043 | mov SAVE_PC, PC
1044 | call extern lj_meta_arith // (lua_State *L, TValue *ra,*rb,*rc, BCReg op)
1045 | // NULL (finished) or TValue * (metamethod) returned in eax (RC).
1046 | mov BASE, L:RB->base
1047 | test RC, RC
1048 | jz ->cont_nop
1049 |
1050 | // Call metamethod for binary op.
1051 |->vmeta_binop:
1052 | // BASE = base, RC = new base, stack = cont/func/o1/o2
1053 | mov RA, RC
1054 | sub RC, BASE
1055 | mov [RA-24], PC // [cont|PC]
1056 | lea PC, [RC+FRAME_CONT]
1057 | mov NARGS:RDd, 2+1 // 2 args for func(o1, o2).
1058 | jmp ->vm_call_dispatch
1059 |
1060 |->vmeta_len:
1061 | movzx RDd, PC_RD
1062 | mov L:RB, SAVE_L
1063 | mov L:RB->base, BASE
1064 | lea CARG2, [BASE+RD*8] // Caveat: CARG2 == BASE
1065 | mov L:CARG1, L:RB
1066 | mov SAVE_PC, PC
1067 | call extern lj_meta_len // (lua_State *L, TValue *o)
1068 | // NULL (retry) or TValue * (metamethod) returned in eax (RC).
1069 | mov BASE, L:RB->base
1070#if LJ_52
1071 | test RC, RC
1072 | jne ->vmeta_binop // Binop call for compatibility.
1073 | movzx RDd, PC_RD
1074 | mov TAB:CARG1, [BASE+RD*8]
1075 | cleartp TAB:CARG1
1076 | jmp ->BC_LEN_Z
1077#else
1078 | jmp ->vmeta_binop // Binop call for compatibility.
1079#endif
1080 |
1081 |//-- Call metamethod ----------------------------------------------------
1082 |
1083 |->vmeta_call_ra:
1084 | lea RA, [BASE+RA*8+16]
1085 |->vmeta_call: // Resolve and call __call metamethod.
1086 | // BASE = old base, RA = new base, RC = nargs+1, PC = return
1087 | mov TMP1d, NARGS:RDd // Save RA, RC for us.
1088 | mov RB, RA
1089 |.if X64WIN
1090 | mov L:TMPR, SAVE_L
1091 | mov L:TMPR->base, BASE // Caveat: CARG2 is BASE.
1092 | lea CARG2, [RA-16]
1093 | lea CARG3, [RA+NARGS:RD*8-8]
1094 | mov CARG1, L:TMPR // Caveat: CARG1 is RA.
1095 |.else
1096 | mov L:CARG1, SAVE_L
1097 | mov L:CARG1->base, BASE // Caveat: CARG3 is BASE.
1098 | lea CARG2, [RA-16]
1099 | lea CARG3, [RA+NARGS:RD*8-8]
1100 |.endif
1101 | mov SAVE_PC, PC
1102 | call extern lj_meta_call // (lua_State *L, TValue *func, TValue *top)
1103 | mov RA, RB
1104 | mov L:RB, SAVE_L
1105 | mov BASE, L:RB->base
1106 | mov NARGS:RDd, TMP1d
1107 | mov LFUNC:RB, [RA-16]
1108 | add NARGS:RDd, 1
1109 | // This is fragile. L->base must not move, KBASE must always be defined.
1110 | cmp KBASE, BASE // Continue with CALLT if flag set.
1111 | je ->BC_CALLT_Z
1112 | cleartp LFUNC:RB
1113 | mov BASE, RA
1114 | ins_call // Otherwise call resolved metamethod.
1115 |
1116 |//-- Argument coercion for 'for' statement ------------------------------
1117 |
1118 |->vmeta_for:
1119 | mov L:RB, SAVE_L
1120 | mov L:RB->base, BASE
1121 | mov CARG2, RA // Caveat: CARG2 == BASE
1122 | mov L:CARG1, L:RB // Caveat: CARG1 == RA
1123 | mov SAVE_PC, PC
1124 | call extern lj_meta_for // (lua_State *L, TValue *base)
1125 | mov BASE, L:RB->base
1126 | mov RCd, [PC-4]
1127 | movzx RAd, RCH
1128 | movzx OP, RCL
1129 | shr RCd, 16
1130 | jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Retry FORI or JFORI.
1131 |
1132 |//-----------------------------------------------------------------------
1133 |//-- Fast functions -----------------------------------------------------
1134 |//-----------------------------------------------------------------------
1135 |
1136 |.macro .ffunc, name
1137 |->ff_ .. name:
1138 |.endmacro
1139 |
1140 |.macro .ffunc_1, name
1141 |->ff_ .. name:
1142 | cmp NARGS:RDd, 1+1; jb ->fff_fallback
1143 |.endmacro
1144 |
1145 |.macro .ffunc_2, name
1146 |->ff_ .. name:
1147 | cmp NARGS:RDd, 2+1; jb ->fff_fallback
1148 |.endmacro
1149 |
1150 |.macro .ffunc_n, name, op
1151 | .ffunc_1 name
1152 | checknumtp [BASE], ->fff_fallback
1153 | op xmm0, qword [BASE]
1154 |.endmacro
1155 |
1156 |.macro .ffunc_n, name
1157 | .ffunc_n name, movsd
1158 |.endmacro
1159 |
1160 |.macro .ffunc_nn, name
1161 | .ffunc_2 name
1162 | checknumtp [BASE], ->fff_fallback
1163 | checknumtp [BASE+8], ->fff_fallback
1164 | movsd xmm0, qword [BASE]
1165 | movsd xmm1, qword [BASE+8]
1166 |.endmacro
1167 |
1168 |// Inlined GC threshold check. Caveat: uses label 1.
1169 |.macro ffgccheck
1170 | mov RB, [DISPATCH+DISPATCH_GL(gc.total)]
1171 | cmp RB, [DISPATCH+DISPATCH_GL(gc.threshold)]
1172 | jb >1
1173 | call ->fff_gcstep
1174 |1:
1175 |.endmacro
1176 |
1177 |//-- Base library: checks -----------------------------------------------
1178 |
1179 |.ffunc_1 assert
1180 | mov ITYPE, [BASE]
1181 | mov RB, ITYPE
1182 | sar ITYPE, 47
1183 | cmp ITYPEd, LJ_TISTRUECOND; jae ->fff_fallback
1184 | mov PC, [BASE-8]
1185 | mov MULTRES, RDd
1186 | mov RB, [BASE]
1187 | mov [BASE-16], RB
1188 | sub RDd, 2
1189 | jz >2
1190 | mov RA, BASE
1191 |1:
1192 | add RA, 8
1193 | mov RB, [RA]
1194 | mov [RA-16], RB
1195 | sub RDd, 1
1196 | jnz <1
1197 |2:
1198 | mov RDd, MULTRES
1199 | jmp ->fff_res_
1200 |
1201 |.ffunc_1 type
1202 | mov RC, [BASE]
1203 | sar RC, 47
1204 | mov RBd, LJ_TISNUM
1205 | cmp RCd, RBd
1206 | cmovb RCd, RBd
1207 | not RCd
1208 |2:
1209 | mov CFUNC:RB, [BASE-16]
1210 | cleartp CFUNC:RB
1211 | mov STR:RC, [CFUNC:RB+RC*8+((char *)(&((GCfuncC *)0)->upvalue))]
1212 | mov PC, [BASE-8]
1213 | settp STR:RC, LJ_TSTR
1214 | mov [BASE-16], STR:RC
1215 | jmp ->fff_res1
1216 |
1217 |//-- Base library: getters and setters ---------------------------------
1218 |
1219 |.ffunc_1 getmetatable
1220 | mov TAB:RB, [BASE]
1221 | mov PC, [BASE-8]
1222 | checktab TAB:RB, >6
1223 |1: // Field metatable must be at same offset for GCtab and GCudata!
1224 | mov TAB:RB, TAB:RB->metatable
1225 |2:
1226 | test TAB:RB, TAB:RB
1227 | mov aword [BASE-16], LJ_TNIL
1228 | jz ->fff_res1
1229 | settp TAB:RC, TAB:RB, LJ_TTAB
1230 | mov [BASE-16], TAB:RC // Store metatable as default result.
1231 | mov STR:RC, [DISPATCH+DISPATCH_GL(gcroot)+8*(GCROOT_MMNAME+MM_metatable)]
1232 | mov RAd, TAB:RB->hmask
1233 | and RAd, STR:RC->hash
1234 | settp STR:RC, LJ_TSTR
1235 | imul RAd, #NODE
1236 | add NODE:RA, TAB:RB->node
1237 |3: // Rearranged logic, because we expect _not_ to find the key.
1238 | cmp NODE:RA->key, STR:RC
1239 | je >5
1240 |4:
1241 | mov NODE:RA, NODE:RA->next
1242 | test NODE:RA, NODE:RA
1243 | jnz <3
1244 | jmp ->fff_res1 // Not found, keep default result.
1245 |5:
1246 | mov RB, NODE:RA->val
1247 | cmp RB, LJ_TNIL; je ->fff_res1 // Ditto for nil value.
1248 | mov [BASE-16], RB // Return value of mt.__metatable.
1249 | jmp ->fff_res1
1250 |
1251 |6:
1252 | cmp ITYPEd, LJ_TUDATA; je <1
1253 | cmp ITYPEd, LJ_TISNUM; ja >7
1254 | mov ITYPEd, LJ_TISNUM
1255 |7:
1256 | not ITYPEd
1257 | mov TAB:RB, [DISPATCH+ITYPE*8+DISPATCH_GL(gcroot[GCROOT_BASEMT])]
1258 | jmp <2
1259 |
1260 |.ffunc_2 setmetatable
1261 | mov TAB:RB, [BASE]
1262 | mov TAB:TMPR, TAB:RB
1263 | checktab TAB:RB, ->fff_fallback
1264 | // Fast path: no mt for table yet and not clearing the mt.
1265 | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback
1266 | mov TAB:RA, [BASE+8]
1267 | checktab TAB:RA, ->fff_fallback
1268 | mov TAB:RB->metatable, TAB:RA
1269 | mov PC, [BASE-8]
1270 | mov [BASE-16], TAB:TMPR // Return original table.
1271 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
1272 | jz >1
1273 | // Possible write barrier. Table is black, but skip iswhite(mt) check.
1274 | barrierback TAB:RB, RC
1275 |1:
1276 | jmp ->fff_res1
1277 |
1278 |.ffunc_2 rawget
1279 |.if X64WIN
1280 | mov TAB:RA, [BASE]
1281 | checktab TAB:RA, ->fff_fallback
1282 | mov RB, BASE // Save BASE.
1283 | lea CARG3, [BASE+8]
1284 | mov CARG2, TAB:RA // Caveat: CARG2 == BASE.
1285 | mov CARG1, SAVE_L
1286 |.else
1287 | mov TAB:CARG2, [BASE]
1288 | checktab TAB:CARG2, ->fff_fallback
1289 | mov RB, BASE // Save BASE.
1290 | lea CARG3, [BASE+8] // Caveat: CARG3 == BASE.
1291 | mov CARG1, SAVE_L
1292 |.endif
1293 | call extern lj_tab_get // (lua_State *L, GCtab *t, cTValue *key)
1294 | // cTValue * returned in eax (RD).
1295 | mov BASE, RB // Restore BASE.
1296 | // Copy table slot.
1297 | mov RB, [RD]
1298 | mov PC, [BASE-8]
1299 | mov [BASE-16], RB
1300 | jmp ->fff_res1
1301 |
1302 |//-- Base library: conversions ------------------------------------------
1303 |
1304 |.ffunc tonumber
1305 | // Only handles the number case inline (without a base argument).
1306 | cmp NARGS:RDd, 1+1; jne ->fff_fallback // Exactly one argument.
1307 | mov RB, [BASE]
1308 | checknumber RB, ->fff_fallback
1309 | mov PC, [BASE-8]
1310 | mov [BASE-16], RB
1311 | jmp ->fff_res1
1312 |
1313 |.ffunc_1 tostring
1314 | // Only handles the string or number case inline.
1315 | mov PC, [BASE-8]
1316 | mov STR:RB, [BASE]
1317 | checktp_nc STR:RB, LJ_TSTR, >3
1318 | // A __tostring method in the string base metatable is ignored.
1319 |2:
1320 | mov [BASE-16], STR:RB
1321 | jmp ->fff_res1
1322 |3: // Handle numbers inline, unless a number base metatable is present.
1323 | cmp ITYPEd, LJ_TISNUM; ja ->fff_fallback_1
1324 | cmp aword [DISPATCH+DISPATCH_GL(gcroot[GCROOT_BASEMT_NUM])], 0
1325 | jne ->fff_fallback
1326 | ffgccheck // Caveat: uses label 1.
1327 | mov L:RB, SAVE_L
1328 | mov L:RB->base, BASE // Add frame since C call can throw.
1329 | mov SAVE_PC, PC // Redundant (but a defined value).
1330 |.if not X64WIN
1331 | mov CARG2, BASE // Otherwise: CARG2 == BASE
1332 |.endif
1333 | mov L:CARG1, L:RB
1334 |.if DUALNUM
1335 | call extern lj_strfmt_number // (lua_State *L, cTValue *o)
1336 |.else
1337 | call extern lj_strfmt_num // (lua_State *L, lua_Number *np)
1338 |.endif
1339 | // GCstr returned in eax (RD).
1340 | mov BASE, L:RB->base
1341 | settp STR:RB, RD, LJ_TSTR
1342 | jmp <2
1343 |
1344 |//-- Base library: iterators -------------------------------------------
1345 |
1346 |.ffunc_1 next
1347 | je >2 // Missing 2nd arg?
1348 |1:
1349 |.if X64WIN
1350 | mov RA, [BASE]
1351 | checktab RA, ->fff_fallback
1352 |.else
1353 | mov CARG2, [BASE]
1354 | checktab CARG2, ->fff_fallback
1355 |.endif
1356 | mov L:RB, SAVE_L
1357 | mov L:RB->base, BASE // Add frame since C call can throw.
1358 | mov L:RB->top, BASE // Dummy frame length is ok.
1359 | mov PC, [BASE-8]
1360 |.if X64WIN
1361 | lea CARG3, [BASE+8]
1362 | mov CARG2, RA // Caveat: CARG2 == BASE.
1363 | mov CARG1, L:RB
1364 |.else
1365 | lea CARG3, [BASE+8] // Caveat: CARG3 == BASE.
1366 | mov CARG1, L:RB
1367 |.endif
1368 | mov SAVE_PC, PC // Needed for ITERN fallback.
1369 | call extern lj_tab_next // (lua_State *L, GCtab *t, TValue *key)
1370 | // Flag returned in eax (RD).
1371 | mov BASE, L:RB->base
1372 | test RDd, RDd; jz >3 // End of traversal?
1373 | // Copy key and value to results.
1374 | mov RB, [BASE+8]
1375 | mov RD, [BASE+16]
1376 | mov [BASE-16], RB
1377 | mov [BASE-8], RD
1378 |->fff_res2:
1379 | mov RDd, 1+2
1380 | jmp ->fff_res
1381 |2: // Set missing 2nd arg to nil.
1382 | mov aword [BASE+8], LJ_TNIL
1383 | jmp <1
1384 |3: // End of traversal: return nil.
1385 | mov aword [BASE-16], LJ_TNIL
1386 | jmp ->fff_res1
1387 |
1388 |.ffunc_1 pairs
1389 | mov TAB:RB, [BASE]
1390 | mov TMPR, TAB:RB
1391 | checktab TAB:RB, ->fff_fallback
1392#if LJ_52
1393 | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback
1394#endif
1395 | mov CFUNC:RD, [BASE-16]
1396 | cleartp CFUNC:RD
1397 | mov CFUNC:RD, CFUNC:RD->upvalue[0]
1398 | settp CFUNC:RD, LJ_TFUNC
1399 | mov PC, [BASE-8]
1400 | mov [BASE-16], CFUNC:RD
1401 | mov [BASE-8], TMPR
1402 | mov aword [BASE], LJ_TNIL
1403 | mov RDd, 1+3
1404 | jmp ->fff_res
1405 |
1406 |.ffunc_2 ipairs_aux
1407 | mov TAB:RB, [BASE]
1408 | checktab TAB:RB, ->fff_fallback
1409 |.if DUALNUM
1410 | mov RA, [BASE+8]
1411 | checkint RA, ->fff_fallback
1412 |.else
1413 | checknumtp [BASE+8], ->fff_fallback
1414 | movsd xmm0, qword [BASE+8]
1415 |.endif
1416 | mov PC, [BASE-8]
1417 |.if DUALNUM
1418 | add RAd, 1
1419 | setint ITYPE, RA
1420 | mov [BASE-16], ITYPE
1421 |.else
1422 | sseconst_1 xmm1, TMPR
1423 | addsd xmm0, xmm1
1424 | cvttsd2si RAd, xmm0
1425 | movsd qword [BASE-16], xmm0
1426 |.endif
1427 | cmp RAd, TAB:RB->asize; jae >2 // Not in array part?
1428 | mov RD, TAB:RB->array
1429 | lea RD, [RD+RA*8]
1430 |1:
1431 | cmp aword [RD], LJ_TNIL; je ->fff_res0
1432 | // Copy array slot.
1433 | mov RB, [RD]
1434 | mov [BASE-8], RB
1435 | jmp ->fff_res2
1436 |2: // Check for empty hash part first. Otherwise call C function.
1437 | cmp dword TAB:RB->hmask, 0; je ->fff_res0
1438 |.if X64WIN
1439 | mov TMPR, BASE
1440 | mov CARG2d, RAd
1441 | mov CARG1, TAB:RB
1442 | mov RB, TMPR
1443 |.else
1444 | mov CARG1, TAB:RB
1445 | mov RB, BASE // Save BASE.
1446 | mov CARG2d, RAd // Caveat: CARG2 == BASE
1447 |.endif
1448 | call extern lj_tab_getinth // (GCtab *t, int32_t key)
1449 | // cTValue * or NULL returned in eax (RD).
1450 | mov BASE, RB
1451 | test RD, RD
1452 | jnz <1
1453 |->fff_res0:
1454 | mov RDd, 1+0
1455 | jmp ->fff_res
1456 |
1457 |.ffunc_1 ipairs
1458 | mov TAB:RB, [BASE]
1459 | mov TMPR, TAB:RB
1460 | checktab TAB:RB, ->fff_fallback
1461#if LJ_52
1462 | cmp aword TAB:RB->metatable, 0; jne ->fff_fallback
1463#endif
1464 | mov CFUNC:RD, [BASE-16]
1465 | cleartp CFUNC:RD
1466 | mov CFUNC:RD, CFUNC:RD->upvalue[0]
1467 | settp CFUNC:RD, LJ_TFUNC
1468 | mov PC, [BASE-8]
1469 | mov [BASE-16], CFUNC:RD
1470 | mov [BASE-8], TMPR
1471 |.if DUALNUM
1472 | mov64 RD, ((uint64_t)LJ_TISNUM<<47)
1473 | mov [BASE], RD
1474 |.else
1475 | mov qword [BASE], 0
1476 |.endif
1477 | mov RDd, 1+3
1478 | jmp ->fff_res
1479 |
1480 |//-- Base library: catch errors ----------------------------------------
1481 |
1482 |.ffunc_1 pcall
1483 | lea RA, [BASE+16]
1484 | sub NARGS:RDd, 1
1485 | mov PCd, 16+FRAME_PCALL
1486 |1:
1487 | movzx RBd, byte [DISPATCH+DISPATCH_GL(hookmask)]
1488 | shr RB, HOOK_ACTIVE_SHIFT
1489 | and RB, 1
1490 | add PC, RB // Remember active hook before pcall.
1491 | // Note: this does a (harmless) copy of the function to the PC slot, too.
1492 | mov KBASE, RD
1493 |2:
1494 | mov RB, [RA+KBASE*8-24]
1495 | mov [RA+KBASE*8-16], RB
1496 | sub KBASE, 1
1497 | ja <2
1498 | jmp ->vm_call_dispatch
1499 |
1500 |.ffunc_2 xpcall
1501 | mov LFUNC:RA, [BASE+8]
1502 | checktp_nc LFUNC:RA, LJ_TFUNC, ->fff_fallback
1503 | mov LFUNC:RB, [BASE] // Swap function and traceback.
1504 | mov [BASE], LFUNC:RA
1505 | mov [BASE+8], LFUNC:RB
1506 | lea RA, [BASE+24]
1507 | sub NARGS:RDd, 2
1508 | mov PCd, 24+FRAME_PCALL
1509 | jmp <1
1510 |
1511 |//-- Coroutine library --------------------------------------------------
1512 |
1513 |.macro coroutine_resume_wrap, resume
1514 |.if resume
1515 |.ffunc_1 coroutine_resume
1516 | mov L:RB, [BASE]
1517 | cleartp L:RB
1518 |.else
1519 |.ffunc coroutine_wrap_aux
1520 | mov CFUNC:RB, [BASE-16]
1521 | cleartp CFUNC:RB
1522 | mov L:RB, CFUNC:RB->upvalue[0].gcr
1523 | cleartp L:RB
1524 |.endif
1525 | mov PC, [BASE-8]
1526 | mov SAVE_PC, PC
1527 | mov TMP1, L:RB
1528 |.if resume
1529 | checktptp [BASE], LJ_TTHREAD, ->fff_fallback
1530 |.endif
1531 | cmp aword L:RB->cframe, 0; jne ->fff_fallback
1532 | cmp byte L:RB->status, LUA_YIELD; ja ->fff_fallback
1533 | mov RA, L:RB->top
1534 | je >1 // Status != LUA_YIELD (i.e. 0)?
1535 | cmp RA, L:RB->base // Check for presence of initial func.
1536 | je ->fff_fallback
1537 | mov PC, [RA-8] // Move initial function up.
1538 | mov [RA], PC
1539 | add RA, 8
1540 |1:
1541 |.if resume
1542 | lea PC, [RA+NARGS:RD*8-16] // Check stack space (-1-thread).
1543 |.else
1544 | lea PC, [RA+NARGS:RD*8-8] // Check stack space (-1).
1545 |.endif
1546 | cmp PC, L:RB->maxstack; ja ->fff_fallback
1547 | mov L:RB->top, PC
1548 |
1549 | mov L:RB, SAVE_L
1550 | mov L:RB->base, BASE
1551 |.if resume
1552 | add BASE, 8 // Keep resumed thread in stack for GC.
1553 |.endif
1554 | mov L:RB->top, BASE
1555 |.if resume
1556 | lea RB, [BASE+NARGS:RD*8-24] // RB = end of source for stack move.
1557 |.else
1558 | lea RB, [BASE+NARGS:RD*8-16] // RB = end of source for stack move.
1559 |.endif
1560 | sub RB, PC // Relative to PC.
1561 |
1562 | cmp PC, RA
1563 | je >3
1564 |2: // Move args to coroutine.
1565 | mov RC, [PC+RB]
1566 | mov [PC-8], RC
1567 | sub PC, 8
1568 | cmp PC, RA
1569 | jne <2
1570 |3:
1571 | mov CARG2, RA
1572 | mov CARG1, TMP1
1573 | call ->vm_resume // (lua_State *L, TValue *base, 0, 0)
1574 |
1575 | mov L:RB, SAVE_L
1576 | mov L:PC, TMP1
1577 | mov BASE, L:RB->base
1578 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
1579 | set_vmstate INTERP
1580 |
1581 | cmp eax, LUA_YIELD
1582 | ja >8
1583 |4:
1584 | mov RA, L:PC->base
1585 | mov KBASE, L:PC->top
1586 | mov L:PC->top, RA // Clear coroutine stack.
1587 | mov PC, KBASE
1588 | sub PC, RA
1589 | je >6 // No results?
1590 | lea RD, [BASE+PC]
1591 | shr PCd, 3
1592 | cmp RD, L:RB->maxstack
1593 | ja >9 // Need to grow stack?
1594 |
1595 | mov RB, BASE
1596 | sub RB, RA
1597 |5: // Move results from coroutine.
1598 | mov RD, [RA]
1599 | mov [RA+RB], RD
1600 | add RA, 8
1601 | cmp RA, KBASE
1602 | jne <5
1603 |6:
1604 |.if resume
1605 | lea RDd, [PCd+2] // nresults+1 = 1 + true + results.
1606 | mov_true ITYPE // Prepend true to results.
1607 | mov [BASE-8], ITYPE
1608 |.else
1609 | lea RDd, [PCd+1] // nresults+1 = 1 + results.
1610 |.endif
1611 |7:
1612 | mov PC, SAVE_PC
1613 | mov MULTRES, RDd
1614 |.if resume
1615 | mov RA, -8
1616 |.else
1617 | xor RAd, RAd
1618 |.endif
1619 | test PCd, FRAME_TYPE
1620 | jz ->BC_RET_Z
1621 | jmp ->vm_return
1622 |
1623 |8: // Coroutine returned with error (at co->top-1).
1624 |.if resume
1625 | mov_false ITYPE // Prepend false to results.
1626 | mov [BASE-8], ITYPE
1627 | mov RA, L:PC->top
1628 | sub RA, 8
1629 | mov L:PC->top, RA // Clear error from coroutine stack.
1630 | // Copy error message.
1631 | mov RD, [RA]
1632 | mov [BASE], RD
1633 | mov RDd, 1+2 // nresults+1 = 1 + false + error.
1634 | jmp <7
1635 |.else
1636 | mov CARG2, L:PC
1637 | mov CARG1, L:RB
1638 | call extern lj_ffh_coroutine_wrap_err // (lua_State *L, lua_State *co)
1639 | // Error function does not return.
1640 |.endif
1641 |
1642 |9: // Handle stack expansion on return from yield.
1643 | mov L:RA, TMP1
1644 | mov L:RA->top, KBASE // Undo coroutine stack clearing.
1645 | mov CARG2, PC
1646 | mov CARG1, L:RB
1647 | call extern lj_state_growstack // (lua_State *L, int n)
1648 | mov L:PC, TMP1
1649 | mov BASE, L:RB->base
1650 | jmp <4 // Retry the stack move.
1651 |.endmacro
1652 |
1653 | coroutine_resume_wrap 1 // coroutine.resume
1654 | coroutine_resume_wrap 0 // coroutine.wrap
1655 |
1656 |.ffunc coroutine_yield
1657 | mov L:RB, SAVE_L
1658 | test aword L:RB->cframe, CFRAME_RESUME
1659 | jz ->fff_fallback
1660 | mov L:RB->base, BASE
1661 | lea RD, [BASE+NARGS:RD*8-8]
1662 | mov L:RB->top, RD
1663 | xor RDd, RDd
1664 | mov aword L:RB->cframe, RD
1665 | mov al, LUA_YIELD
1666 | mov byte L:RB->status, al
1667 | jmp ->vm_leave_unw
1668 |
1669 |//-- Math library -------------------------------------------------------
1670 |
1671 | .ffunc_1 math_abs
1672 | mov RB, [BASE]
1673 |.if DUALNUM
1674 | checkint RB, >3
1675 | cmp RBd, 0; jns ->fff_resi
1676 | neg RBd; js >2
1677 |->fff_resbit:
1678 |->fff_resi:
1679 | setint RB
1680 |->fff_resRB:
1681 | mov PC, [BASE-8]
1682 | mov [BASE-16], RB
1683 | jmp ->fff_res1
1684 |2:
1685 | mov64 RB, U64x(41e00000,00000000) // 2^31.
1686 | jmp ->fff_resRB
1687 |3:
1688 | ja ->fff_fallback
1689 |.else
1690 | checknum RB, ->fff_fallback
1691 |.endif
1692 | shl RB, 1
1693 | shr RB, 1
1694 | mov PC, [BASE-8]
1695 | mov [BASE-16], RB
1696 | jmp ->fff_res1
1697 |
1698 |.ffunc_n math_sqrt, sqrtsd
1699 |->fff_resxmm0:
1700 | mov PC, [BASE-8]
1701 | movsd qword [BASE-16], xmm0
1702 | // fallthrough
1703 |
1704 |->fff_res1:
1705 | mov RDd, 1+1
1706 |->fff_res:
1707 | mov MULTRES, RDd
1708 |->fff_res_:
1709 | test PCd, FRAME_TYPE
1710 | jnz >7
1711 |5:
1712 | cmp PC_RB, RDL // More results expected?
1713 | ja >6
1714 | // Adjust BASE. KBASE is assumed to be set for the calling frame.
1715 | movzx RAd, PC_RA
1716 | neg RA
1717 | lea BASE, [BASE+RA*8-16] // base = base - (RA+2)*8
1718 | ins_next
1719 |
1720 |6: // Fill up results with nil.
1721 | mov aword [BASE+RD*8-24], LJ_TNIL
1722 | add RD, 1
1723 | jmp <5
1724 |
1725 |7: // Non-standard return case.
1726 | mov RA, -16 // Results start at BASE+RA = BASE-16.
1727 | jmp ->vm_return
1728 |
1729 |.macro math_round, func
1730 | .ffunc math_ .. func
1731 |.if DUALNUM
1732 | mov RB, [BASE]
1733 | checknumx RB, ->fff_resRB, je
1734 | ja ->fff_fallback
1735 |.else
1736 | checknumtp [BASE], ->fff_fallback
1737 |.endif
1738 | movsd xmm0, qword [BASE]
1739 | call ->vm_ .. func .. _sse
1740 |.if DUALNUM
1741 | cvttsd2si RBd, xmm0
1742 | cmp RBd, 0x80000000
1743 | jne ->fff_resi
1744 | cvtsi2sd xmm1, RBd
1745 | ucomisd xmm0, xmm1
1746 | jp ->fff_resxmm0
1747 | je ->fff_resi
1748 |.endif
1749 | jmp ->fff_resxmm0
1750 |.endmacro
1751 |
1752 | math_round floor
1753 | math_round ceil
1754 |
1755 |.ffunc math_log
1756 | cmp NARGS:RDd, 1+1; jne ->fff_fallback // Exactly one argument.
1757 | checknumtp [BASE], ->fff_fallback
1758 | movsd xmm0, qword [BASE]
1759 | mov RB, BASE
1760 | call extern log
1761 | mov BASE, RB
1762 | jmp ->fff_resxmm0
1763 |
1764 |.macro math_extern, func
1765 | .ffunc_n math_ .. func
1766 | mov RB, BASE
1767 | call extern func
1768 | mov BASE, RB
1769 | jmp ->fff_resxmm0
1770 |.endmacro
1771 |
1772 |.macro math_extern2, func
1773 | .ffunc_nn math_ .. func
1774 | mov RB, BASE
1775 | call extern func
1776 | mov BASE, RB
1777 | jmp ->fff_resxmm0
1778 |.endmacro
1779 |
1780 | math_extern log10
1781 | math_extern exp
1782 | math_extern sin
1783 | math_extern cos
1784 | math_extern tan
1785 | math_extern asin
1786 | math_extern acos
1787 | math_extern atan
1788 | math_extern sinh
1789 | math_extern cosh
1790 | math_extern tanh
1791 | math_extern2 pow
1792 | math_extern2 atan2
1793 | math_extern2 fmod
1794 |
1795 |.ffunc_2 math_ldexp
1796 | checknumtp [BASE], ->fff_fallback
1797 | checknumtp [BASE+8], ->fff_fallback
1798 | fld qword [BASE+8]
1799 | fld qword [BASE]
1800 | fscale
1801 | fpop1
1802 | mov PC, [BASE-8]
1803 | fstp qword [BASE-16]
1804 | jmp ->fff_res1
1805 |
1806 |.ffunc_n math_frexp
1807 | mov RB, BASE
1808 |.if X64WIN
1809 | lea CARG2, TMP1 // Caveat: CARG2 == BASE
1810 |.else
1811 | lea CARG1, TMP1
1812 |.endif
1813 | call extern frexp
1814 | mov BASE, RB
1815 | mov RBd, TMP1d
1816 | mov PC, [BASE-8]
1817 | movsd qword [BASE-16], xmm0
1818 |.if DUALNUM
1819 | setint RB
1820 | mov [BASE-8], RB
1821 |.else
1822 | cvtsi2sd xmm1, RBd
1823 | movsd qword [BASE-8], xmm1
1824 |.endif
1825 | mov RDd, 1+2
1826 | jmp ->fff_res
1827 |
1828 |.ffunc_n math_modf
1829 | mov RB, BASE
1830 |.if X64WIN
1831 | lea CARG2, [BASE-16] // Caveat: CARG2 == BASE
1832 |.else
1833 | lea CARG1, [BASE-16]
1834 |.endif
1835 | call extern modf
1836 | mov BASE, RB
1837 | mov PC, [BASE-8]
1838 | movsd qword [BASE-8], xmm0
1839 | mov RDd, 1+2
1840 | jmp ->fff_res
1841 |
1842 |.macro math_minmax, name, cmovop, sseop
1843 | .ffunc name
1844 | mov RAd, 2
1845 |.if DUALNUM
1846 | mov RB, [BASE]
1847 | checkint RB, >4
1848 |1: // Handle integers.
1849 | cmp RAd, RDd; jae ->fff_resRB
1850 | mov TMPR, [BASE+RA*8-8]
1851 | checkint TMPR, >3
1852 | cmp RBd, TMPRd
1853 | cmovop RB, TMPR
1854 | add RAd, 1
1855 | jmp <1
1856 |3:
1857 | ja ->fff_fallback
1858 | // Convert intermediate result to number and continue below.
1859 | cvtsi2sd xmm0, RBd
1860 | jmp >6
1861 |4:
1862 | ja ->fff_fallback
1863 |.else
1864 | checknumtp [BASE], ->fff_fallback
1865 |.endif
1866 |
1867 | movsd xmm0, qword [BASE]
1868 |5: // Handle numbers or integers.
1869 | cmp RAd, RDd; jae ->fff_resxmm0
1870 |.if DUALNUM
1871 | mov RB, [BASE+RA*8-8]
1872 | checknumx RB, >6, jb
1873 | ja ->fff_fallback
1874 | cvtsi2sd xmm1, RBd
1875 | jmp >7
1876 |.else
1877 | checknumtp [BASE+RA*8-8], ->fff_fallback
1878 |.endif
1879 |6:
1880 | movsd xmm1, qword [BASE+RA*8-8]
1881 |7:
1882 | sseop xmm0, xmm1
1883 | add RAd, 1
1884 | jmp <5
1885 |.endmacro
1886 |
1887 | math_minmax math_min, cmovg, minsd
1888 | math_minmax math_max, cmovl, maxsd
1889 |
1890 |//-- String library -----------------------------------------------------
1891 |
1892 |.ffunc string_byte // Only handle the 1-arg case here.
1893 | cmp NARGS:RDd, 1+1; jne ->fff_fallback
1894 | mov STR:RB, [BASE]
1895 | checkstr STR:RB, ->fff_fallback
1896 | mov PC, [BASE-8]
1897 | cmp dword STR:RB->len, 1
1898 | jb ->fff_res0 // Return no results for empty string.
1899 | movzx RBd, byte STR:RB[1]
1900 |.if DUALNUM
1901 | jmp ->fff_resi
1902 |.else
1903 | cvtsi2sd xmm0, RBd; jmp ->fff_resxmm0
1904 |.endif
1905 |
1906 |.ffunc string_char // Only handle the 1-arg case here.
1907 | ffgccheck
1908 | cmp NARGS:RDd, 1+1; jne ->fff_fallback // *Exactly* 1 arg.
1909 |.if DUALNUM
1910 | mov RB, [BASE]
1911 | checkint RB, ->fff_fallback
1912 |.else
1913 | checknumtp [BASE], ->fff_fallback
1914 | cvttsd2si RBd, qword [BASE]
1915 |.endif
1916 | cmp RBd, 255; ja ->fff_fallback
1917 | mov TMP1d, RBd
1918 | mov TMPRd, 1
1919 | lea RD, TMP1 // Points to stack. Little-endian.
1920 |->fff_newstr:
1921 | mov L:RB, SAVE_L
1922 | mov L:RB->base, BASE
1923 | mov CARG3d, TMPRd // Zero-extended to size_t.
1924 | mov CARG2, RD
1925 | mov CARG1, L:RB
1926 | mov SAVE_PC, PC
1927 | call extern lj_str_new // (lua_State *L, char *str, size_t l)
1928 |->fff_resstr:
1929 | // GCstr * returned in eax (RD).
1930 | mov BASE, L:RB->base
1931 | mov PC, [BASE-8]
1932 | settp STR:RD, LJ_TSTR
1933 | mov [BASE-16], STR:RD
1934 | jmp ->fff_res1
1935 |
1936 |.ffunc string_sub
1937 | ffgccheck
1938 | mov TMPRd, -1
1939 | cmp NARGS:RDd, 1+2; jb ->fff_fallback
1940 | jna >1
1941 |.if DUALNUM
1942 | mov TMPR, [BASE+16]
1943 | checkint TMPR, ->fff_fallback
1944 |.else
1945 | checknumtp [BASE+16], ->fff_fallback
1946 | cvttsd2si TMPRd, qword [BASE+16]
1947 |.endif
1948 |1:
1949 | mov STR:RB, [BASE]
1950 | checkstr STR:RB, ->fff_fallback
1951 |.if DUALNUM
1952 | mov ITYPE, [BASE+8]
1953 | mov RAd, ITYPEd // Must clear hiword for lea below.
1954 | sar ITYPE, 47
1955 | cmp ITYPEd, LJ_TISNUM
1956 | jne ->fff_fallback
1957 |.else
1958 | checknumtp [BASE+8], ->fff_fallback
1959 | cvttsd2si RAd, qword [BASE+8]
1960 |.endif
1961 | mov RCd, STR:RB->len
1962 | cmp RCd, TMPRd // len < end? (unsigned compare)
1963 | jb >5
1964 |2:
1965 | test RAd, RAd // start <= 0?
1966 | jle >7
1967 |3:
1968 | sub TMPRd, RAd // start > end?
1969 | jl ->fff_emptystr
1970 | lea RD, [STR:RB+RAd+#STR-1]
1971 | add TMPRd, 1
1972 |4:
1973 | jmp ->fff_newstr
1974 |
1975 |5: // Negative end or overflow.
1976 | jl >6
1977 | lea TMPRd, [TMPRd+RCd+1] // end = end+(len+1)
1978 | jmp <2
1979 |6: // Overflow.
1980 | mov TMPRd, RCd // end = len
1981 | jmp <2
1982 |
1983 |7: // Negative start or underflow.
1984 | je >8
1985 | add RAd, RCd // start = start+(len+1)
1986 | add RAd, 1
1987 | jg <3 // start > 0?
1988 |8: // Underflow.
1989 | mov RAd, 1 // start = 1
1990 | jmp <3
1991 |
1992 |->fff_emptystr: // Range underflow.
1993 | xor TMPRd, TMPRd // Zero length. Any ptr in RD is ok.
1994 | jmp <4
1995 |
1996 |.macro ffstring_op, name
1997 | .ffunc_1 string_ .. name
1998 | ffgccheck
1999 |.if X64WIN
2000 | mov STR:TMPR, [BASE]
2001 | checkstr STR:TMPR, ->fff_fallback
2002 |.else
2003 | mov STR:CARG2, [BASE]
2004 | checkstr STR:CARG2, ->fff_fallback
2005 |.endif
2006 | mov L:RB, SAVE_L
2007 | lea SBUF:CARG1, [DISPATCH+DISPATCH_GL(tmpbuf)]
2008 | mov L:RB->base, BASE
2009 |.if X64WIN
2010 | mov STR:CARG2, STR:TMPR // Caveat: CARG2 == BASE
2011 |.endif
2012 | mov RC, SBUF:CARG1->b
2013 | mov SBUF:CARG1->L, L:RB
2014 | mov SBUF:CARG1->p, RC
2015 | mov SAVE_PC, PC
2016 | call extern lj_buf_putstr_ .. name
2017 | mov CARG1, rax
2018 | call extern lj_buf_tostr
2019 | jmp ->fff_resstr
2020 |.endmacro
2021 |
2022 |ffstring_op reverse
2023 |ffstring_op lower
2024 |ffstring_op upper
2025 |
2026 |//-- Bit library --------------------------------------------------------
2027 |
2028 |.macro .ffunc_bit, name, kind, fdef
2029 | fdef name
2030 |.if kind == 2
2031 | sseconst_tobit xmm1, RB
2032 |.endif
2033 |.if DUALNUM
2034 | mov RB, [BASE]
2035 | checkint RB, >1
2036 |.if kind > 0
2037 | jmp >2
2038 |.else
2039 | jmp ->fff_resbit
2040 |.endif
2041 |1:
2042 | ja ->fff_fallback
2043 | movd xmm0, RB
2044 |.else
2045 | checknumtp [BASE], ->fff_fallback
2046 | movsd xmm0, qword [BASE]
2047 |.endif
2048 |.if kind < 2
2049 | sseconst_tobit xmm1, RB
2050 |.endif
2051 | addsd xmm0, xmm1
2052 | movd RBd, xmm0
2053 |2:
2054 |.endmacro
2055 |
2056 |.macro .ffunc_bit, name, kind
2057 | .ffunc_bit name, kind, .ffunc_1
2058 |.endmacro
2059 |
2060 |.ffunc_bit bit_tobit, 0
2061 | jmp ->fff_resbit
2062 |
2063 |.macro .ffunc_bit_op, name, ins
2064 | .ffunc_bit name, 2
2065 | mov TMPRd, NARGS:RDd // Save for fallback.
2066 | lea RD, [BASE+NARGS:RD*8-16]
2067 |1:
2068 | cmp RD, BASE
2069 | jbe ->fff_resbit
2070 |.if DUALNUM
2071 | mov RA, [RD]
2072 | checkint RA, >2
2073 | ins RBd, RAd
2074 | sub RD, 8
2075 | jmp <1
2076 |2:
2077 | ja ->fff_fallback_bit_op
2078 | movd xmm0, RA
2079 |.else
2080 | checknumtp [RD], ->fff_fallback_bit_op
2081 | movsd xmm0, qword [RD]
2082 |.endif
2083 | addsd xmm0, xmm1
2084 | movd RAd, xmm0
2085 | ins RBd, RAd
2086 | sub RD, 8
2087 | jmp <1
2088 |.endmacro
2089 |
2090 |.ffunc_bit_op bit_band, and
2091 |.ffunc_bit_op bit_bor, or
2092 |.ffunc_bit_op bit_bxor, xor
2093 |
2094 |.ffunc_bit bit_bswap, 1
2095 | bswap RBd
2096 | jmp ->fff_resbit
2097 |
2098 |.ffunc_bit bit_bnot, 1
2099 | not RBd
2100 |.if DUALNUM
2101 | jmp ->fff_resbit
2102 |.else
2103 |->fff_resbit:
2104 | cvtsi2sd xmm0, RBd
2105 | jmp ->fff_resxmm0
2106 |.endif
2107 |
2108 |->fff_fallback_bit_op:
2109 | mov NARGS:RDd, TMPRd // Restore for fallback
2110 | jmp ->fff_fallback
2111 |
2112 |.macro .ffunc_bit_sh, name, ins
2113 |.if DUALNUM
2114 | .ffunc_bit name, 1, .ffunc_2
2115 | // Note: no inline conversion from number for 2nd argument!
2116 | mov RA, [BASE+8]
2117 | checkint RA, ->fff_fallback
2118 |.else
2119 | .ffunc_nn name
2120 | sseconst_tobit xmm2, RB
2121 | addsd xmm0, xmm2
2122 | addsd xmm1, xmm2
2123 | movd RBd, xmm0
2124 | movd RAd, xmm1
2125 |.endif
2126 | ins RBd, cl // Assumes RA is ecx.
2127 | jmp ->fff_resbit
2128 |.endmacro
2129 |
2130 |.ffunc_bit_sh bit_lshift, shl
2131 |.ffunc_bit_sh bit_rshift, shr
2132 |.ffunc_bit_sh bit_arshift, sar
2133 |.ffunc_bit_sh bit_rol, rol
2134 |.ffunc_bit_sh bit_ror, ror
2135 |
2136 |//-----------------------------------------------------------------------
2137 |
2138 |->fff_fallback_2:
2139 | mov NARGS:RDd, 1+2 // Other args are ignored, anyway.
2140 | jmp ->fff_fallback
2141 |->fff_fallback_1:
2142 | mov NARGS:RDd, 1+1 // Other args are ignored, anyway.
2143 |->fff_fallback: // Call fast function fallback handler.
2144 | // BASE = new base, RD = nargs+1
2145 | mov L:RB, SAVE_L
2146 | mov PC, [BASE-8] // Fallback may overwrite PC.
2147 | mov SAVE_PC, PC // Redundant (but a defined value).
2148 | mov L:RB->base, BASE
2149 | lea RD, [BASE+NARGS:RD*8-8]
2150 | lea RA, [RD+8*LUA_MINSTACK] // Ensure enough space for handler.
2151 | mov L:RB->top, RD
2152 | mov CFUNC:RD, [BASE-16]
2153 | cleartp CFUNC:RD
2154 | cmp RA, L:RB->maxstack
2155 | ja >5 // Need to grow stack.
2156 | mov CARG1, L:RB
2157 | call aword CFUNC:RD->f // (lua_State *L)
2158 | mov BASE, L:RB->base
2159 | // Either throws an error, or recovers and returns -1, 0 or nresults+1.
2160 | test RDd, RDd; jg ->fff_res // Returned nresults+1?
2161 |1:
2162 | mov RA, L:RB->top
2163 | sub RA, BASE
2164 | shr RAd, 3
2165 | test RDd, RDd
2166 | lea NARGS:RDd, [RAd+1]
2167 | mov LFUNC:RB, [BASE-16]
2168 | jne ->vm_call_tail // Returned -1?
2169 | cleartp LFUNC:RB
2170 | ins_callt // Returned 0: retry fast path.
2171 |
2172 |// Reconstruct previous base for vmeta_call during tailcall.
2173 |->vm_call_tail:
2174 | mov RA, BASE
2175 | test PCd, FRAME_TYPE
2176 | jnz >3
2177 | movzx RBd, PC_RA
2178 | neg RB
2179 | lea BASE, [BASE+RB*8-16] // base = base - (RB+2)*8
2180 | jmp ->vm_call_dispatch // Resolve again for tailcall.
2181 |3:
2182 | mov RB, PC
2183 | and RB, -8
2184 | sub BASE, RB
2185 | jmp ->vm_call_dispatch // Resolve again for tailcall.
2186 |
2187 |5: // Grow stack for fallback handler.
2188 | mov CARG2d, LUA_MINSTACK
2189 | mov CARG1, L:RB
2190 | call extern lj_state_growstack // (lua_State *L, int n)
2191 | mov BASE, L:RB->base
2192 | xor RDd, RDd // Simulate a return 0.
2193 | jmp <1 // Dumb retry (goes through ff first).
2194 |
2195 |->fff_gcstep: // Call GC step function.
2196 | // BASE = new base, RD = nargs+1
2197 | pop RB // Must keep stack at same level.
2198 | mov TMP1, RB // Save return address
2199 | mov L:RB, SAVE_L
2200 | mov SAVE_PC, PC // Redundant (but a defined value).
2201 | mov L:RB->base, BASE
2202 | lea RD, [BASE+NARGS:RD*8-8]
2203 | mov CARG1, L:RB
2204 | mov L:RB->top, RD
2205 | call extern lj_gc_step // (lua_State *L)
2206 | mov BASE, L:RB->base
2207 | mov RD, L:RB->top
2208 | sub RD, BASE
2209 | shr RDd, 3
2210 | add NARGS:RDd, 1
2211 | mov RB, TMP1
2212 | push RB // Restore return address.
2213 | ret
2214 |
2215 |//-----------------------------------------------------------------------
2216 |//-- Special dispatch targets -------------------------------------------
2217 |//-----------------------------------------------------------------------
2218 |
2219 |->vm_record: // Dispatch target for recording phase.
2220 |.if JIT
2221 | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)]
2222 | test RDL, HOOK_VMEVENT // No recording while in vmevent.
2223 | jnz >5
2224 | // Decrement the hookcount for consistency, but always do the call.
2225 | test RDL, HOOK_ACTIVE
2226 | jnz >1
2227 | test RDL, LUA_MASKLINE|LUA_MASKCOUNT
2228 | jz >1
2229 | dec dword [DISPATCH+DISPATCH_GL(hookcount)]
2230 | jmp >1
2231 |.endif
2232 |
2233 |->vm_rethook: // Dispatch target for return hooks.
2234 | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)]
2235 | test RDL, HOOK_ACTIVE // Hook already active?
2236 | jnz >5
2237 | jmp >1
2238 |
2239 |->vm_inshook: // Dispatch target for instr/line hooks.
2240 | movzx RDd, byte [DISPATCH+DISPATCH_GL(hookmask)]
2241 | test RDL, HOOK_ACTIVE // Hook already active?
2242 | jnz >5
2243 |
2244 | test RDL, LUA_MASKLINE|LUA_MASKCOUNT
2245 | jz >5
2246 | dec dword [DISPATCH+DISPATCH_GL(hookcount)]
2247 | jz >1
2248 | test RDL, LUA_MASKLINE
2249 | jz >5
2250 |1:
2251 | mov L:RB, SAVE_L
2252 | mov L:RB->base, BASE
2253 | mov CARG2, PC // Caveat: CARG2 == BASE
2254 | mov CARG1, L:RB
2255 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
2256 | call extern lj_dispatch_ins // (lua_State *L, const BCIns *pc)
2257 |3:
2258 | mov BASE, L:RB->base
2259 |4:
2260 | movzx RAd, PC_RA
2261 |5:
2262 | movzx OP, PC_OP
2263 | movzx RDd, PC_RD
2264 | jmp aword [DISPATCH+OP*8+GG_DISP2STATIC] // Re-dispatch to static ins.
2265 |
2266 |->cont_hook: // Continue from hook yield.
2267 | add PC, 4
2268 | mov RA, [RB-40]
2269 | mov MULTRES, RAd // Restore MULTRES for *M ins.
2270 | jmp <4
2271 |
2272 |->vm_hotloop: // Hot loop counter underflow.
2273 |.if JIT
2274 | mov LFUNC:RB, [BASE-16] // Same as curr_topL(L).
2275 | cleartp LFUNC:RB
2276 | mov RB, LFUNC:RB->pc
2277 | movzx RDd, byte [RB+PC2PROTO(framesize)]
2278 | lea RD, [BASE+RD*8]
2279 | mov L:RB, SAVE_L
2280 | mov L:RB->base, BASE
2281 | mov L:RB->top, RD
2282 | mov CARG2, PC
2283 | lea CARG1, [DISPATCH+GG_DISP2J]
2284 | mov aword [DISPATCH+DISPATCH_J(L)], L:RB
2285 | mov SAVE_PC, PC
2286 | call extern lj_trace_hot // (jit_State *J, const BCIns *pc)
2287 | jmp <3
2288 |.endif
2289 |
2290 |->vm_callhook: // Dispatch target for call hooks.
2291 | mov SAVE_PC, PC
2292 |.if JIT
2293 | jmp >1
2294 |.endif
2295 |
2296 |->vm_hotcall: // Hot call counter underflow.
2297 |.if JIT
2298 | mov SAVE_PC, PC
2299 | or PC, 1 // Marker for hot call.
2300 |1:
2301 |.endif
2302 | lea RD, [BASE+NARGS:RD*8-8]
2303 | mov L:RB, SAVE_L
2304 | mov L:RB->base, BASE
2305 | mov L:RB->top, RD
2306 | mov CARG2, PC
2307 | mov CARG1, L:RB
2308 | call extern lj_dispatch_call // (lua_State *L, const BCIns *pc)
2309 | // ASMFunction returned in eax/rax (RD).
2310 | mov SAVE_PC, 0 // Invalidate for subsequent line hook.
2311 |.if JIT
2312 | and PC, -2
2313 |.endif
2314 | mov BASE, L:RB->base
2315 | mov RA, RD
2316 | mov RD, L:RB->top
2317 | sub RD, BASE
2318 | mov RB, RA
2319 | movzx RAd, PC_RA
2320 | shr RDd, 3
2321 | add NARGS:RDd, 1
2322 | jmp RB
2323 |
2324 |->cont_stitch: // Trace stitching.
2325 |.if JIT
2326 | // BASE = base, RC = result, RB = mbase
2327 | mov TRACE:ITYPE, [RB-40] // Save previous trace.
2328 | cleartp TRACE:ITYPE
2329 | mov TMPRd, MULTRES
2330 | movzx RAd, PC_RA
2331 | lea RA, [BASE+RA*8] // Call base.
2332 | sub TMPRd, 1
2333 | jz >2
2334 |1: // Move results down.
2335 | mov RB, [RC]
2336 | mov [RA], RB
2337 | add RC, 8
2338 | add RA, 8
2339 | sub TMPRd, 1
2340 | jnz <1
2341 |2:
2342 | movzx RCd, PC_RA
2343 | movzx RBd, PC_RB
2344 | add RC, RB
2345 | lea RC, [BASE+RC*8-8]
2346 |3:
2347 | cmp RC, RA
2348 | ja >9 // More results wanted?
2349 |
2350 | test TRACE:ITYPE, TRACE:ITYPE
2351 | jz ->cont_nop
2352 | movzx RBd, word TRACE:ITYPE->traceno
2353 | movzx RDd, word TRACE:ITYPE->link
2354 | cmp RDd, RBd
2355 | je ->cont_nop // Blacklisted.
2356 | test RDd, RDd
2357 | jne =>BC_JLOOP // Jump to stitched trace.
2358 |
2359 | // Stitch a new trace to the previous trace.
2360 | mov [DISPATCH+DISPATCH_J(exitno)], RB
2361 | mov L:RB, SAVE_L
2362 | mov L:RB->base, BASE
2363 | mov CARG2, PC
2364 | lea CARG1, [DISPATCH+GG_DISP2J]
2365 | mov aword [DISPATCH+DISPATCH_J(L)], L:RB
2366 | call extern lj_dispatch_stitch // (jit_State *J, const BCIns *pc)
2367 | mov BASE, L:RB->base
2368 | jmp ->cont_nop
2369 |
2370 |9: // Fill up results with nil.
2371 | mov aword [RA], LJ_TNIL
2372 | add RA, 8
2373 | jmp <3
2374 |.endif
2375 |
2376 |->vm_profhook: // Dispatch target for profiler hook.
2377#if LJ_HASPROFILE
2378 | mov L:RB, SAVE_L
2379 | mov L:RB->base, BASE
2380 | mov CARG2, PC // Caveat: CARG2 == BASE
2381 | mov CARG1, L:RB
2382 | call extern lj_dispatch_profile // (lua_State *L, const BCIns *pc)
2383 | mov BASE, L:RB->base
2384 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2385 | sub PC, 4
2386 | jmp ->cont_nop
2387#endif
2388 |
2389 |//-----------------------------------------------------------------------
2390 |//-- Trace exit handler -------------------------------------------------
2391 |//-----------------------------------------------------------------------
2392 |
2393 |// Called from an exit stub with the exit number on the stack.
2394 |// The 16 bit exit number is stored with two (sign-extended) push imm8.
2395 |->vm_exit_handler:
2396 |.if JIT
2397 | push r13; push r12
2398 | push r11; push r10; push r9; push r8
2399 | push rdi; push rsi; push rbp; lea rbp, [rsp+88]; push rbp
2400 | push rbx; push rdx; push rcx; push rax
2401 | movzx RCd, byte [rbp-8] // Reconstruct exit number.
2402 | mov RCH, byte [rbp-16]
2403 | mov [rbp-8], r15; mov [rbp-16], r14
2404 | // DISPATCH is preserved on-trace in LJ_GC64 mode.
2405 | mov RAd, [DISPATCH+DISPATCH_GL(vmstate)] // Get trace number.
2406 | set_vmstate EXIT
2407 | mov [DISPATCH+DISPATCH_J(exitno)], RCd
2408 | mov [DISPATCH+DISPATCH_J(parent)], RAd
2409 |.if X64WIN
2410 | sub rsp, 16*8+4*8 // Room for SSE regs + save area.
2411 |.else
2412 | sub rsp, 16*8 // Room for SSE regs.
2413 |.endif
2414 | add rbp, -128
2415 | movsd qword [rbp-8], xmm15; movsd qword [rbp-16], xmm14
2416 | movsd qword [rbp-24], xmm13; movsd qword [rbp-32], xmm12
2417 | movsd qword [rbp-40], xmm11; movsd qword [rbp-48], xmm10
2418 | movsd qword [rbp-56], xmm9; movsd qword [rbp-64], xmm8
2419 | movsd qword [rbp-72], xmm7; movsd qword [rbp-80], xmm6
2420 | movsd qword [rbp-88], xmm5; movsd qword [rbp-96], xmm4
2421 | movsd qword [rbp-104], xmm3; movsd qword [rbp-112], xmm2
2422 | movsd qword [rbp-120], xmm1; movsd qword [rbp-128], xmm0
2423 | // Caveat: RB is rbp.
2424 | mov L:RB, [DISPATCH+DISPATCH_GL(cur_L)]
2425 | mov BASE, [DISPATCH+DISPATCH_GL(jit_base)]
2426 | mov aword [DISPATCH+DISPATCH_J(L)], L:RB
2427 | mov L:RB->base, BASE
2428 |.if X64WIN
2429 | lea CARG2, [rsp+4*8]
2430 |.else
2431 | mov CARG2, rsp
2432 |.endif
2433 | lea CARG1, [DISPATCH+GG_DISP2J]
2434 | mov qword [DISPATCH+DISPATCH_GL(jit_base)], 0
2435 | call extern lj_trace_exit // (jit_State *J, ExitState *ex)
2436 | // MULTRES or negated error code returned in eax (RD).
2437 | mov RA, L:RB->cframe
2438 | and RA, CFRAME_RAWMASK
2439 | mov [RA+CFRAME_OFS_L], L:RB // Set SAVE_L (on-trace resume/yield).
2440 | mov BASE, L:RB->base
2441 | mov PC, [RA+CFRAME_OFS_PC] // Get SAVE_PC.
2442 | jmp >1
2443 |.endif
2444 |->vm_exit_interp:
2445 | // RD = MULTRES or negated error code, BASE, PC and DISPATCH set.
2446 |.if JIT
2447 | // Restore additional callee-save registers only used in compiled code.
2448 |.if X64WIN
2449 | lea RA, [rsp+10*16+4*8]
2450 |1:
2451 | movdqa xmm15, [RA-10*16]
2452 | movdqa xmm14, [RA-9*16]
2453 | movdqa xmm13, [RA-8*16]
2454 | movdqa xmm12, [RA-7*16]
2455 | movdqa xmm11, [RA-6*16]
2456 | movdqa xmm10, [RA-5*16]
2457 | movdqa xmm9, [RA-4*16]
2458 | movdqa xmm8, [RA-3*16]
2459 | movdqa xmm7, [RA-2*16]
2460 | mov rsp, RA // Reposition stack to C frame.
2461 | movdqa xmm6, [RA-1*16]
2462 | mov r15, CSAVE_1
2463 | mov r14, CSAVE_2
2464 | mov r13, CSAVE_3
2465 | mov r12, CSAVE_4
2466 |.else
2467 | lea RA, [rsp+16]
2468 |1:
2469 | mov r13, [RA-8]
2470 | mov r12, [RA]
2471 | mov rsp, RA // Reposition stack to C frame.
2472 |.endif
2473 | test RDd, RDd; js >9 // Check for error from exit.
2474 | mov L:RB, SAVE_L
2475 | mov MULTRES, RDd
2476 | mov LFUNC:KBASE, [BASE-16]
2477 | cleartp LFUNC:KBASE
2478 | mov KBASE, LFUNC:KBASE->pc
2479 | mov KBASE, [KBASE+PC2PROTO(k)]
2480 | mov L:RB->base, BASE
2481 | mov qword [DISPATCH+DISPATCH_GL(jit_base)], 0
2482 | set_vmstate INTERP
2483 | // Modified copy of ins_next which handles function header dispatch, too.
2484 | mov RCd, [PC]
2485 | movzx RAd, RCH
2486 | movzx OP, RCL
2487 | add PC, 4
2488 | shr RCd, 16
2489 | cmp OP, BC_FUNCF // Function header?
2490 | jb >3
2491 | cmp OP, BC_FUNCC+2 // Fast function?
2492 | jae >4
2493 |2:
2494 | mov RCd, MULTRES // RC/RD holds nres+1.
2495 |3:
2496 | jmp aword [DISPATCH+OP*8]
2497 |
2498 |4: // Check frame below fast function.
2499 | mov RC, [BASE-8]
2500 | test RCd, FRAME_TYPE
2501 | jnz <2 // Trace stitching continuation?
2502 | // Otherwise set KBASE for Lua function below fast function.
2503 | movzx RCd, byte [RC-3]
2504 | neg RC
2505 | mov LFUNC:KBASE, [BASE+RC*8-32]
2506 | cleartp LFUNC:KBASE
2507 | mov KBASE, LFUNC:KBASE->pc
2508 | mov KBASE, [KBASE+PC2PROTO(k)]
2509 | jmp <2
2510 |
2511 |9: // Rethrow error from the right C frame.
2512 | neg RD
2513 | mov CARG1, L:RB
2514 | mov CARG2, RD
2515 | call extern lj_err_throw // (lua_State *L, int errcode)
2516 |.endif
2517 |
2518 |//-----------------------------------------------------------------------
2519 |//-- Math helper functions ----------------------------------------------
2520 |//-----------------------------------------------------------------------
2521 |
2522 |// FP value rounding. Called by math.floor/math.ceil fast functions
2523 |// and from JIT code. arg/ret is xmm0. xmm0-xmm3 and RD (eax) modified.
2524 |.macro vm_round, name, mode, cond
2525 |->name:
2526 |->name .. _sse:
2527 | sseconst_abs xmm2, RD
2528 | sseconst_2p52 xmm3, RD
2529 | movaps xmm1, xmm0
2530 | andpd xmm1, xmm2 // |x|
2531 | ucomisd xmm3, xmm1 // No truncation if 2^52 <= |x|.
2532 | jbe >1
2533 | andnpd xmm2, xmm0 // Isolate sign bit.
2534 |.if mode == 2 // trunc(x)?
2535 | movaps xmm0, xmm1
2536 | addsd xmm1, xmm3 // (|x| + 2^52) - 2^52
2537 | subsd xmm1, xmm3
2538 | sseconst_1 xmm3, RD
2539 | cmpsd xmm0, xmm1, 1 // |x| < result?
2540 | andpd xmm0, xmm3
2541 | subsd xmm1, xmm0 // If yes, subtract -1.
2542 | orpd xmm1, xmm2 // Merge sign bit back in.
2543 |.else
2544 | addsd xmm1, xmm3 // (|x| + 2^52) - 2^52
2545 | subsd xmm1, xmm3
2546 | orpd xmm1, xmm2 // Merge sign bit back in.
2547 | .if mode == 1 // ceil(x)?
2548 | sseconst_m1 xmm2, RD // Must subtract -1 to preserve -0.
2549 | cmpsd xmm0, xmm1, 6 // x > result?
2550 | .else // floor(x)?
2551 | sseconst_1 xmm2, RD
2552 | cmpsd xmm0, xmm1, 1 // x < result?
2553 | .endif
2554 | andpd xmm0, xmm2
2555 | subsd xmm1, xmm0 // If yes, subtract +-1.
2556 |.endif
2557 | movaps xmm0, xmm1
2558 |1:
2559 | ret
2560 |.endmacro
2561 |
2562 | vm_round vm_floor, 0, 1
2563 | vm_round vm_ceil, 1, JIT
2564 | vm_round vm_trunc, 2, JIT
2565 |
2566 |// FP modulo x%y. Called by BC_MOD* and vm_arith.
2567 |->vm_mod:
2568 |// Args in xmm0/xmm1, return value in xmm0.
2569 |// Caveat: xmm0-xmm5 and RC (eax) modified!
2570 | movaps xmm5, xmm0
2571 | divsd xmm0, xmm1
2572 | sseconst_abs xmm2, RD
2573 | sseconst_2p52 xmm3, RD
2574 | movaps xmm4, xmm0
2575 | andpd xmm4, xmm2 // |x/y|
2576 | ucomisd xmm3, xmm4 // No truncation if 2^52 <= |x/y|.
2577 | jbe >1
2578 | andnpd xmm2, xmm0 // Isolate sign bit.
2579 | addsd xmm4, xmm3 // (|x/y| + 2^52) - 2^52
2580 | subsd xmm4, xmm3
2581 | orpd xmm4, xmm2 // Merge sign bit back in.
2582 | sseconst_1 xmm2, RD
2583 | cmpsd xmm0, xmm4, 1 // x/y < result?
2584 | andpd xmm0, xmm2
2585 | subsd xmm4, xmm0 // If yes, subtract 1.0.
2586 | movaps xmm0, xmm5
2587 | mulsd xmm1, xmm4
2588 | subsd xmm0, xmm1
2589 | ret
2590 |1:
2591 | mulsd xmm1, xmm0
2592 | movaps xmm0, xmm5
2593 | subsd xmm0, xmm1
2594 | ret
2595 |
2596 |// Args in xmm0/eax. Ret in xmm0. xmm0-xmm1 and eax modified.
2597 |->vm_powi_sse:
2598 | cmp eax, 1; jle >6 // i<=1?
2599 | // Now 1 < (unsigned)i <= 0x80000000.
2600 |1: // Handle leading zeros.
2601 | test eax, 1; jnz >2
2602 | mulsd xmm0, xmm0
2603 | shr eax, 1
2604 | jmp <1
2605 |2:
2606 | shr eax, 1; jz >5
2607 | movaps xmm1, xmm0
2608 |3: // Handle trailing bits.
2609 | mulsd xmm0, xmm0
2610 | shr eax, 1; jz >4
2611 | jnc <3
2612 | mulsd xmm1, xmm0
2613 | jmp <3
2614 |4:
2615 | mulsd xmm0, xmm1
2616 |5:
2617 | ret
2618 |6:
2619 | je <5 // x^1 ==> x
2620 | jb >7 // x^0 ==> 1
2621 | neg eax
2622 | call <1
2623 | sseconst_1 xmm1, RD
2624 | divsd xmm1, xmm0
2625 | movaps xmm0, xmm1
2626 | ret
2627 |7:
2628 | sseconst_1 xmm0, RD
2629 | ret
2630 |
2631 |//-----------------------------------------------------------------------
2632 |//-- Miscellaneous functions --------------------------------------------
2633 |//-----------------------------------------------------------------------
2634 |
2635 |// int lj_vm_cpuid(uint32_t f, uint32_t res[4])
2636 |->vm_cpuid:
2637 | mov eax, CARG1d
2638 | .if X64WIN; push rsi; mov rsi, CARG2; .endif
2639 | push rbx
2640 | xor ecx, ecx
2641 | cpuid
2642 | mov [rsi], eax
2643 | mov [rsi+4], ebx
2644 | mov [rsi+8], ecx
2645 | mov [rsi+12], edx
2646 | pop rbx
2647 | .if X64WIN; pop rsi; .endif
2648 | ret
2649 |
2650 |//-----------------------------------------------------------------------
2651 |//-- Assertions ---------------------------------------------------------
2652 |//-----------------------------------------------------------------------
2653 |
2654 |->assert_bad_for_arg_type:
2655#ifdef LUA_USE_ASSERT
2656 | int3
2657#endif
2658 | int3
2659 |
2660 |//-----------------------------------------------------------------------
2661 |//-- FFI helper functions -----------------------------------------------
2662 |//-----------------------------------------------------------------------
2663 |
2664 |// Handler for callback functions. Callback slot number in ah/al.
2665 |->vm_ffi_callback:
2666 |.if FFI
2667 |.type CTSTATE, CTState, PC
2668 | saveregs_ // ebp/rbp already saved. ebp now holds global_State *.
2669 | lea DISPATCH, [ebp+GG_G2DISP]
2670 | mov CTSTATE, GL:ebp->ctype_state
2671 | movzx eax, ax
2672 | mov CTSTATE->cb.slot, eax
2673 | mov CTSTATE->cb.gpr[0], CARG1
2674 | mov CTSTATE->cb.gpr[1], CARG2
2675 | mov CTSTATE->cb.gpr[2], CARG3
2676 | mov CTSTATE->cb.gpr[3], CARG4
2677 | movsd qword CTSTATE->cb.fpr[0], xmm0
2678 | movsd qword CTSTATE->cb.fpr[1], xmm1
2679 | movsd qword CTSTATE->cb.fpr[2], xmm2
2680 | movsd qword CTSTATE->cb.fpr[3], xmm3
2681 |.if X64WIN
2682 | lea rax, [rsp+CFRAME_SIZE+4*8]
2683 |.else
2684 | lea rax, [rsp+CFRAME_SIZE]
2685 | mov CTSTATE->cb.gpr[4], CARG5
2686 | mov CTSTATE->cb.gpr[5], CARG6
2687 | movsd qword CTSTATE->cb.fpr[4], xmm4
2688 | movsd qword CTSTATE->cb.fpr[5], xmm5
2689 | movsd qword CTSTATE->cb.fpr[6], xmm6
2690 | movsd qword CTSTATE->cb.fpr[7], xmm7
2691 |.endif
2692 | mov CTSTATE->cb.stack, rax
2693 | mov CARG2, rsp
2694 | mov SAVE_PC, CTSTATE // Any value outside of bytecode is ok.
2695 | mov CARG1, CTSTATE
2696 | call extern lj_ccallback_enter // (CTState *cts, void *cf)
2697 | // lua_State * returned in eax (RD).
2698 | set_vmstate INTERP
2699 | mov BASE, L:RD->base
2700 | mov RD, L:RD->top
2701 | sub RD, BASE
2702 | mov LFUNC:RB, [BASE-16]
2703 | cleartp LFUNC:RB
2704 | shr RD, 3
2705 | add RD, 1
2706 | ins_callt
2707 |.endif
2708 |
2709 |->cont_ffi_callback: // Return from FFI callback.
2710 |.if FFI
2711 | mov L:RA, SAVE_L
2712 | mov CTSTATE, [DISPATCH+DISPATCH_GL(ctype_state)]
2713 | mov aword CTSTATE->L, L:RA
2714 | mov L:RA->base, BASE
2715 | mov L:RA->top, RB
2716 | mov CARG1, CTSTATE
2717 | mov CARG2, RC
2718 | call extern lj_ccallback_leave // (CTState *cts, TValue *o)
2719 | mov rax, CTSTATE->cb.gpr[0]
2720 | movsd xmm0, qword CTSTATE->cb.fpr[0]
2721 | jmp ->vm_leave_unw
2722 |.endif
2723 |
2724 |->vm_ffi_call: // Call C function via FFI.
2725 | // Caveat: needs special frame unwinding, see below.
2726 |.if FFI
2727 | .type CCSTATE, CCallState, rbx
2728 | push rbp; mov rbp, rsp; push rbx; mov CCSTATE, CARG1
2729 |
2730 | // Readjust stack.
2731 | mov eax, CCSTATE->spadj
2732 | sub rsp, rax
2733 |
2734 | // Copy stack slots.
2735 | movzx ecx, byte CCSTATE->nsp
2736 | sub ecx, 1
2737 | js >2
2738 |1:
2739 | mov rax, [CCSTATE+rcx*8+offsetof(CCallState, stack)]
2740 | mov [rsp+rcx*8+CCALL_SPS_EXTRA*8], rax
2741 | sub ecx, 1
2742 | jns <1
2743 |2:
2744 |
2745 | movzx eax, byte CCSTATE->nfpr
2746 | mov CARG1, CCSTATE->gpr[0]
2747 | mov CARG2, CCSTATE->gpr[1]
2748 | mov CARG3, CCSTATE->gpr[2]
2749 | mov CARG4, CCSTATE->gpr[3]
2750 |.if not X64WIN
2751 | mov CARG5, CCSTATE->gpr[4]
2752 | mov CARG6, CCSTATE->gpr[5]
2753 |.endif
2754 | test eax, eax; jz >5
2755 | movaps xmm0, CCSTATE->fpr[0]
2756 | movaps xmm1, CCSTATE->fpr[1]
2757 | movaps xmm2, CCSTATE->fpr[2]
2758 | movaps xmm3, CCSTATE->fpr[3]
2759 |.if not X64WIN
2760 | cmp eax, 4; jbe >5
2761 | movaps xmm4, CCSTATE->fpr[4]
2762 | movaps xmm5, CCSTATE->fpr[5]
2763 | movaps xmm6, CCSTATE->fpr[6]
2764 | movaps xmm7, CCSTATE->fpr[7]
2765 |.endif
2766 |5:
2767 |
2768 | call aword CCSTATE->func
2769 |
2770 | mov CCSTATE->gpr[0], rax
2771 | movaps CCSTATE->fpr[0], xmm0
2772 |.if not X64WIN
2773 | mov CCSTATE->gpr[1], rdx
2774 | movaps CCSTATE->fpr[1], xmm1
2775 |.endif
2776 |
2777 | mov rbx, [rbp-8]; leave; ret
2778 |.endif
2779 |// Note: vm_ffi_call must be the last function in this object file!
2780 |
2781 |//-----------------------------------------------------------------------
2782}
2783
2784/* Generate the code for a single instruction. */
2785static void build_ins(BuildCtx *ctx, BCOp op, int defop)
2786{
2787 int vk = 0;
2788 |// Note: aligning all instructions does not pay off.
2789 |=>defop:
2790
2791 switch (op) {
2792
2793 /* -- Comparison ops ---------------------------------------------------- */
2794
2795 /* Remember: all ops branch for a true comparison, fall through otherwise. */
2796
2797 |.macro jmp_comp, lt, ge, le, gt, target
2798 ||switch (op) {
2799 ||case BC_ISLT:
2800 | lt target
2801 ||break;
2802 ||case BC_ISGE:
2803 | ge target
2804 ||break;
2805 ||case BC_ISLE:
2806 | le target
2807 ||break;
2808 ||case BC_ISGT:
2809 | gt target
2810 ||break;
2811 ||default: break; /* Shut up GCC. */
2812 ||}
2813 |.endmacro
2814
2815 case BC_ISLT: case BC_ISGE: case BC_ISLE: case BC_ISGT:
2816 | // RA = src1, RD = src2, JMP with RD = target
2817 | ins_AD
2818 | mov ITYPE, [BASE+RA*8]
2819 | mov RB, [BASE+RD*8]
2820 | mov RA, ITYPE
2821 | mov RD, RB
2822 | sar ITYPE, 47
2823 | sar RB, 47
2824 |.if DUALNUM
2825 | cmp ITYPEd, LJ_TISNUM; jne >7
2826 | cmp RBd, LJ_TISNUM; jne >8
2827 | add PC, 4
2828 | cmp RAd, RDd
2829 | jmp_comp jge, jl, jg, jle, >9
2830 |6:
2831 | movzx RDd, PC_RD
2832 | branchPC RD
2833 |9:
2834 | ins_next
2835 |
2836 |7: // RA is not an integer.
2837 | ja ->vmeta_comp
2838 | // RA is a number.
2839 | cmp RBd, LJ_TISNUM; jb >1; jne ->vmeta_comp
2840 | // RA is a number, RD is an integer.
2841 | cvtsi2sd xmm0, RDd
2842 | jmp >2
2843 |
2844 |8: // RA is an integer, RD is not an integer.
2845 | ja ->vmeta_comp
2846 | // RA is an integer, RD is a number.
2847 | cvtsi2sd xmm1, RAd
2848 | movd xmm0, RD
2849 | jmp >3
2850 |.else
2851 | cmp ITYPEd, LJ_TISNUM; jae ->vmeta_comp
2852 | cmp RBd, LJ_TISNUM; jae ->vmeta_comp
2853 |.endif
2854 |1:
2855 | movd xmm0, RD
2856 |2:
2857 | movd xmm1, RA
2858 |3:
2859 | add PC, 4
2860 | ucomisd xmm0, xmm1
2861 | // Unordered: all of ZF CF PF set, ordered: PF clear.
2862 | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't.
2863 |.if DUALNUM
2864 | jmp_comp jbe, ja, jb, jae, <9
2865 | jmp <6
2866 |.else
2867 | jmp_comp jbe, ja, jb, jae, >1
2868 | movzx RDd, PC_RD
2869 | branchPC RD
2870 |1:
2871 | ins_next
2872 |.endif
2873 break;
2874
2875 case BC_ISEQV: case BC_ISNEV:
2876 vk = op == BC_ISEQV;
2877 | ins_AD // RA = src1, RD = src2, JMP with RD = target
2878 | mov RB, [BASE+RD*8]
2879 | mov ITYPE, [BASE+RA*8]
2880 | add PC, 4
2881 | mov RD, RB
2882 | mov RA, ITYPE
2883 | sar RB, 47
2884 | sar ITYPE, 47
2885 |.if DUALNUM
2886 | cmp RBd, LJ_TISNUM; jne >7
2887 | cmp ITYPEd, LJ_TISNUM; jne >8
2888 | cmp RDd, RAd
2889 if (vk) {
2890 | jne >9
2891 } else {
2892 | je >9
2893 }
2894 | movzx RDd, PC_RD
2895 | branchPC RD
2896 |9:
2897 | ins_next
2898 |
2899 |7: // RD is not an integer.
2900 | ja >5
2901 | // RD is a number.
2902 | movd xmm1, RD
2903 | cmp ITYPEd, LJ_TISNUM; jb >1; jne >5
2904 | // RD is a number, RA is an integer.
2905 | cvtsi2sd xmm0, RAd
2906 | jmp >2
2907 |
2908 |8: // RD is an integer, RA is not an integer.
2909 | ja >5
2910 | // RD is an integer, RA is a number.
2911 | cvtsi2sd xmm1, RDd
2912 | jmp >1
2913 |
2914 |.else
2915 | cmp RBd, LJ_TISNUM; jae >5
2916 | cmp ITYPEd, LJ_TISNUM; jae >5
2917 | movd xmm1, RD
2918 |.endif
2919 |1:
2920 | movd xmm0, RA
2921 |2:
2922 | ucomisd xmm0, xmm1
2923 |4:
2924 iseqne_fp:
2925 if (vk) {
2926 | jp >2 // Unordered means not equal.
2927 | jne >2
2928 } else {
2929 | jp >2 // Unordered means not equal.
2930 | je >1
2931 }
2932 iseqne_end:
2933 if (vk) {
2934 |1: // EQ: Branch to the target.
2935 | movzx RDd, PC_RD
2936 | branchPC RD
2937 |2: // NE: Fallthrough to next instruction.
2938 |.if not FFI
2939 |3:
2940 |.endif
2941 } else {
2942 |.if not FFI
2943 |3:
2944 |.endif
2945 |2: // NE: Branch to the target.
2946 | movzx RDd, PC_RD
2947 | branchPC RD
2948 |1: // EQ: Fallthrough to next instruction.
2949 }
2950 if (LJ_DUALNUM && (op == BC_ISEQV || op == BC_ISNEV ||
2951 op == BC_ISEQN || op == BC_ISNEN)) {
2952 | jmp <9
2953 } else {
2954 | ins_next
2955 }
2956 |
2957 if (op == BC_ISEQV || op == BC_ISNEV) {
2958 |5: // Either or both types are not numbers.
2959 |.if FFI
2960 | cmp RBd, LJ_TCDATA; je ->vmeta_equal_cd
2961 | cmp ITYPEd, LJ_TCDATA; je ->vmeta_equal_cd
2962 |.endif
2963 | cmp RA, RD
2964 | je <1 // Same GCobjs or pvalues?
2965 | cmp RBd, ITYPEd
2966 | jne <2 // Not the same type?
2967 | cmp RBd, LJ_TISTABUD
2968 | ja <2 // Different objects and not table/ud?
2969 |
2970 | // Different tables or userdatas. Need to check __eq metamethod.
2971 | // Field metatable must be at same offset for GCtab and GCudata!
2972 | cleartp TAB:RA
2973 | mov TAB:RB, TAB:RA->metatable
2974 | test TAB:RB, TAB:RB
2975 | jz <2 // No metatable?
2976 | test byte TAB:RB->nomm, 1<<MM_eq
2977 | jnz <2 // Or 'no __eq' flag set?
2978 if (vk) {
2979 | xor RBd, RBd // ne = 0
2980 } else {
2981 | mov RBd, 1 // ne = 1
2982 }
2983 | jmp ->vmeta_equal // Handle __eq metamethod.
2984 } else {
2985 |.if FFI
2986 |3:
2987 | cmp ITYPEd, LJ_TCDATA
2988 if (LJ_DUALNUM && vk) {
2989 | jne <9
2990 } else {
2991 | jne <2
2992 }
2993 | jmp ->vmeta_equal_cd
2994 |.endif
2995 }
2996 break;
2997 case BC_ISEQS: case BC_ISNES:
2998 vk = op == BC_ISEQS;
2999 | ins_AND // RA = src, RD = str const, JMP with RD = target
3000 | mov RB, [BASE+RA*8]
3001 | add PC, 4
3002 | checkstr RB, >3
3003 | cmp RB, [KBASE+RD*8]
3004 iseqne_test:
3005 if (vk) {
3006 | jne >2
3007 } else {
3008 | je >1
3009 }
3010 goto iseqne_end;
3011 case BC_ISEQN: case BC_ISNEN:
3012 vk = op == BC_ISEQN;
3013 | ins_AD // RA = src, RD = num const, JMP with RD = target
3014 | mov RB, [BASE+RA*8]
3015 | add PC, 4
3016 |.if DUALNUM
3017 | checkint RB, >7
3018 | mov RD, [KBASE+RD*8]
3019 | checkint RD, >8
3020 | cmp RBd, RDd
3021 if (vk) {
3022 | jne >9
3023 } else {
3024 | je >9
3025 }
3026 | movzx RDd, PC_RD
3027 | branchPC RD
3028 |9:
3029 | ins_next
3030 |
3031 |7: // RA is not an integer.
3032 | ja >3
3033 | // RA is a number.
3034 | mov RD, [KBASE+RD*8]
3035 | checkint RD, >1
3036 | // RA is a number, RD is an integer.
3037 | cvtsi2sd xmm0, RDd
3038 | jmp >2
3039 |
3040 |8: // RA is an integer, RD is a number.
3041 | cvtsi2sd xmm0, RBd
3042 | movd xmm1, RD
3043 | ucomisd xmm0, xmm1
3044 | jmp >4
3045 |1:
3046 | movd xmm0, RD
3047 |.else
3048 | checknum RB, >3
3049 |1:
3050 | movsd xmm0, qword [KBASE+RD*8]
3051 |.endif
3052 |2:
3053 | ucomisd xmm0, qword [BASE+RA*8]
3054 |4:
3055 goto iseqne_fp;
3056 case BC_ISEQP: case BC_ISNEP:
3057 vk = op == BC_ISEQP;
3058 | ins_AND // RA = src, RD = primitive type (~), JMP with RD = target
3059 | mov RB, [BASE+RA*8]
3060 | sar RB, 47
3061 | add PC, 4
3062 | cmp RBd, RDd
3063 if (!LJ_HASFFI) goto iseqne_test;
3064 if (vk) {
3065 | jne >3
3066 | movzx RDd, PC_RD
3067 | branchPC RD
3068 |2:
3069 | ins_next
3070 |3:
3071 | cmp RBd, LJ_TCDATA; jne <2
3072 | jmp ->vmeta_equal_cd
3073 } else {
3074 | je >2
3075 | cmp RBd, LJ_TCDATA; je ->vmeta_equal_cd
3076 | movzx RDd, PC_RD
3077 | branchPC RD
3078 |2:
3079 | ins_next
3080 }
3081 break;
3082
3083 /* -- Unary test and copy ops ------------------------------------------- */
3084
3085 case BC_ISTC: case BC_ISFC: case BC_IST: case BC_ISF:
3086 | ins_AD // RA = dst or unused, RD = src, JMP with RD = target
3087 | mov ITYPE, [BASE+RD*8]
3088 | add PC, 4
3089 if (op == BC_ISTC || op == BC_ISFC) {
3090 | mov RB, ITYPE
3091 }
3092 | sar ITYPE, 47
3093 | cmp ITYPEd, LJ_TISTRUECOND
3094 if (op == BC_IST || op == BC_ISTC) {
3095 | jae >1
3096 } else {
3097 | jb >1
3098 }
3099 if (op == BC_ISTC || op == BC_ISFC) {
3100 | mov [BASE+RA*8], RB
3101 }
3102 | movzx RDd, PC_RD
3103 | branchPC RD
3104 |1: // Fallthrough to the next instruction.
3105 | ins_next
3106 break;
3107
3108 case BC_ISTYPE:
3109 | ins_AD // RA = src, RD = -type
3110 | mov RB, [BASE+RA*8]
3111 | sar RB, 47
3112 | add RBd, RDd
3113 | jne ->vmeta_istype
3114 | ins_next
3115 break;
3116 case BC_ISNUM:
3117 | ins_AD // RA = src, RD = -(TISNUM-1)
3118 | checknumtp [BASE+RA*8], ->vmeta_istype
3119 | ins_next
3120 break;
3121
3122 /* -- Unary ops --------------------------------------------------------- */
3123
3124 case BC_MOV:
3125 | ins_AD // RA = dst, RD = src
3126 | mov RB, [BASE+RD*8]
3127 | mov [BASE+RA*8], RB
3128 | ins_next_
3129 break;
3130 case BC_NOT:
3131 | ins_AD // RA = dst, RD = src
3132 | mov RB, [BASE+RD*8]
3133 | sar RB, 47
3134 | mov RCd, 2
3135 | cmp RB, LJ_TISTRUECOND
3136 | sbb RCd, 0
3137 | shl RC, 47
3138 | not RC
3139 | mov [BASE+RA*8], RC
3140 | ins_next
3141 break;
3142 case BC_UNM:
3143 | ins_AD // RA = dst, RD = src
3144 | mov RB, [BASE+RD*8]
3145 |.if DUALNUM
3146 | checkint RB, >5
3147 | neg RBd
3148 | jo >4
3149 | setint RB
3150 |9:
3151 | mov [BASE+RA*8], RB
3152 | ins_next
3153 |4:
3154 | mov64 RB, U64x(41e00000,00000000) // 2^31.
3155 | jmp <9
3156 |5:
3157 | ja ->vmeta_unm
3158 |.else
3159 | checknum RB, ->vmeta_unm
3160 |.endif
3161 | mov64 RD, U64x(80000000,00000000)
3162 | xor RB, RD
3163 |.if DUALNUM
3164 | jmp <9
3165 |.else
3166 | mov [BASE+RA*8], RB
3167 | ins_next
3168 |.endif
3169 break;
3170 case BC_LEN:
3171 | ins_AD // RA = dst, RD = src
3172 | mov RD, [BASE+RD*8]
3173 | checkstr RD, >2
3174 |.if DUALNUM
3175 | mov RDd, dword STR:RD->len
3176 |1:
3177 | setint RD
3178 | mov [BASE+RA*8], RD
3179 |.else
3180 | xorps xmm0, xmm0
3181 | cvtsi2sd xmm0, dword STR:RD->len
3182 |1:
3183 | movsd qword [BASE+RA*8], xmm0
3184 |.endif
3185 | ins_next
3186 |2:
3187 | cmp ITYPEd, LJ_TTAB; jne ->vmeta_len
3188 | mov TAB:CARG1, TAB:RD
3189#if LJ_52
3190 | mov TAB:RB, TAB:RD->metatable
3191 | cmp TAB:RB, 0
3192 | jnz >9
3193 |3:
3194#endif
3195 |->BC_LEN_Z:
3196 | mov RB, BASE // Save BASE.
3197 | call extern lj_tab_len // (GCtab *t)
3198 | // Length of table returned in eax (RD).
3199 |.if DUALNUM
3200 | // Nothing to do.
3201 |.else
3202 | cvtsi2sd xmm0, RDd
3203 |.endif
3204 | mov BASE, RB // Restore BASE.
3205 | movzx RAd, PC_RA
3206 | jmp <1
3207#if LJ_52
3208 |9: // Check for __len.
3209 | test byte TAB:RB->nomm, 1<<MM_len
3210 | jnz <3
3211 | jmp ->vmeta_len // 'no __len' flag NOT set: check.
3212#endif
3213 break;
3214
3215 /* -- Binary ops -------------------------------------------------------- */
3216
3217 |.macro ins_arithpre, sseins, ssereg
3218 | ins_ABC
3219 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
3220 ||switch (vk) {
3221 ||case 0:
3222 | checknumtp [BASE+RB*8], ->vmeta_arith_vn
3223 | .if DUALNUM
3224 | checknumtp [KBASE+RC*8], ->vmeta_arith_vn
3225 | .endif
3226 | movsd xmm0, qword [BASE+RB*8]
3227 | sseins ssereg, qword [KBASE+RC*8]
3228 || break;
3229 ||case 1:
3230 | checknumtp [BASE+RB*8], ->vmeta_arith_nv
3231 | .if DUALNUM
3232 | checknumtp [KBASE+RC*8], ->vmeta_arith_nv
3233 | .endif
3234 | movsd xmm0, qword [KBASE+RC*8]
3235 | sseins ssereg, qword [BASE+RB*8]
3236 || break;
3237 ||default:
3238 | checknumtp [BASE+RB*8], ->vmeta_arith_vv
3239 | checknumtp [BASE+RC*8], ->vmeta_arith_vv
3240 | movsd xmm0, qword [BASE+RB*8]
3241 | sseins ssereg, qword [BASE+RC*8]
3242 || break;
3243 ||}
3244 |.endmacro
3245 |
3246 |.macro ins_arithdn, intins
3247 | ins_ABC
3248 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
3249 ||switch (vk) {
3250 ||case 0:
3251 | mov RB, [BASE+RB*8]
3252 | mov RC, [KBASE+RC*8]
3253 | checkint RB, ->vmeta_arith_vno
3254 | checkint RC, ->vmeta_arith_vno
3255 | intins RBd, RCd; jo ->vmeta_arith_vno
3256 || break;
3257 ||case 1:
3258 | mov RB, [BASE+RB*8]
3259 | mov RC, [KBASE+RC*8]
3260 | checkint RB, ->vmeta_arith_nvo
3261 | checkint RC, ->vmeta_arith_nvo
3262 | intins RCd, RBd; jo ->vmeta_arith_nvo
3263 || break;
3264 ||default:
3265 | mov RB, [BASE+RB*8]
3266 | mov RC, [BASE+RC*8]
3267 | checkint RB, ->vmeta_arith_vvo
3268 | checkint RC, ->vmeta_arith_vvo
3269 | intins RBd, RCd; jo ->vmeta_arith_vvo
3270 || break;
3271 ||}
3272 ||if (vk == 1) {
3273 | setint RC
3274 | mov [BASE+RA*8], RC
3275 ||} else {
3276 | setint RB
3277 | mov [BASE+RA*8], RB
3278 ||}
3279 | ins_next
3280 |.endmacro
3281 |
3282 |.macro ins_arithpost
3283 | movsd qword [BASE+RA*8], xmm0
3284 |.endmacro
3285 |
3286 |.macro ins_arith, sseins
3287 | ins_arithpre sseins, xmm0
3288 | ins_arithpost
3289 | ins_next
3290 |.endmacro
3291 |
3292 |.macro ins_arith, intins, sseins
3293 |.if DUALNUM
3294 | ins_arithdn intins
3295 |.else
3296 | ins_arith, sseins
3297 |.endif
3298 |.endmacro
3299
3300 | // RA = dst, RB = src1 or num const, RC = src2 or num const
3301 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
3302 | ins_arith add, addsd
3303 break;
3304 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
3305 | ins_arith sub, subsd
3306 break;
3307 case BC_MULVN: case BC_MULNV: case BC_MULVV:
3308 | ins_arith imul, mulsd
3309 break;
3310 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
3311 | ins_arith divsd
3312 break;
3313 case BC_MODVN:
3314 | ins_arithpre movsd, xmm1
3315 |->BC_MODVN_Z:
3316 | call ->vm_mod
3317 | ins_arithpost
3318 | ins_next
3319 break;
3320 case BC_MODNV: case BC_MODVV:
3321 | ins_arithpre movsd, xmm1
3322 | jmp ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
3323 break;
3324 case BC_POW:
3325 | ins_arithpre movsd, xmm1
3326 | mov RB, BASE
3327 | call extern pow
3328 | movzx RAd, PC_RA
3329 | mov BASE, RB
3330 | ins_arithpost
3331 | ins_next
3332 break;
3333
3334 case BC_CAT:
3335 | ins_ABC // RA = dst, RB = src_start, RC = src_end
3336 | mov L:CARG1, SAVE_L
3337 | mov L:CARG1->base, BASE
3338 | lea CARG2, [BASE+RC*8]
3339 | mov CARG3d, RCd
3340 | sub CARG3d, RBd
3341 |->BC_CAT_Z:
3342 | mov L:RB, L:CARG1
3343 | mov SAVE_PC, PC
3344 | call extern lj_meta_cat // (lua_State *L, TValue *top, int left)
3345 | // NULL (finished) or TValue * (metamethod) returned in eax (RC).
3346 | mov BASE, L:RB->base
3347 | test RC, RC
3348 | jnz ->vmeta_binop
3349 | movzx RBd, PC_RB // Copy result to Stk[RA] from Stk[RB].
3350 | movzx RAd, PC_RA
3351 | mov RC, [BASE+RB*8]
3352 | mov [BASE+RA*8], RC
3353 | ins_next
3354 break;
3355
3356 /* -- Constant ops ------------------------------------------------------ */
3357
3358 case BC_KSTR:
3359 | ins_AND // RA = dst, RD = str const (~)
3360 | mov RD, [KBASE+RD*8]
3361 | settp RD, LJ_TSTR
3362 | mov [BASE+RA*8], RD
3363 | ins_next
3364 break;
3365 case BC_KCDATA:
3366 |.if FFI
3367 | ins_AND // RA = dst, RD = cdata const (~)
3368 | mov RD, [KBASE+RD*8]
3369 | settp RD, LJ_TCDATA
3370 | mov [BASE+RA*8], RD
3371 | ins_next
3372 |.endif
3373 break;
3374 case BC_KSHORT:
3375 | ins_AD // RA = dst, RD = signed int16 literal
3376 |.if DUALNUM
3377 | movsx RDd, RDW
3378 | setint RD
3379 | mov [BASE+RA*8], RD
3380 |.else
3381 | movsx RDd, RDW // Sign-extend literal.
3382 | cvtsi2sd xmm0, RDd
3383 | movsd qword [BASE+RA*8], xmm0
3384 |.endif
3385 | ins_next
3386 break;
3387 case BC_KNUM:
3388 | ins_AD // RA = dst, RD = num const
3389 | movsd xmm0, qword [KBASE+RD*8]
3390 | movsd qword [BASE+RA*8], xmm0
3391 | ins_next
3392 break;
3393 case BC_KPRI:
3394 | ins_AD // RA = dst, RD = primitive type (~)
3395 | shl RD, 47
3396 | not RD
3397 | mov [BASE+RA*8], RD
3398 | ins_next
3399 break;
3400 case BC_KNIL:
3401 | ins_AD // RA = dst_start, RD = dst_end
3402 | lea RA, [BASE+RA*8+8]
3403 | lea RD, [BASE+RD*8]
3404 | mov RB, LJ_TNIL
3405 | mov [RA-8], RB // Sets minimum 2 slots.
3406 |1:
3407 | mov [RA], RB
3408 | add RA, 8
3409 | cmp RA, RD
3410 | jbe <1
3411 | ins_next
3412 break;
3413
3414 /* -- Upvalue and function ops ------------------------------------------ */
3415
3416 case BC_UGET:
3417 | ins_AD // RA = dst, RD = upvalue #
3418 | mov LFUNC:RB, [BASE-16]
3419 | cleartp LFUNC:RB
3420 | mov UPVAL:RB, [LFUNC:RB+RD*8+offsetof(GCfuncL, uvptr)]
3421 | mov RB, UPVAL:RB->v
3422 | mov RD, [RB]
3423 | mov [BASE+RA*8], RD
3424 | ins_next
3425 break;
3426 case BC_USETV:
3427#define TV2MARKOFS \
3428 ((int32_t)offsetof(GCupval, marked)-(int32_t)offsetof(GCupval, tv))
3429 | ins_AD // RA = upvalue #, RD = src
3430 | mov LFUNC:RB, [BASE-16]
3431 | cleartp LFUNC:RB
3432 | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)]
3433 | cmp byte UPVAL:RB->closed, 0
3434 | mov RB, UPVAL:RB->v
3435 | mov RA, [BASE+RD*8]
3436 | mov [RB], RA
3437 | jz >1
3438 | // Check barrier for closed upvalue.
3439 | test byte [RB+TV2MARKOFS], LJ_GC_BLACK // isblack(uv)
3440 | jnz >2
3441 |1:
3442 | ins_next
3443 |
3444 |2: // Upvalue is black. Check if new value is collectable and white.
3445 | mov RD, RA
3446 | sar RD, 47
3447 | sub RDd, LJ_TISGCV
3448 | cmp RDd, LJ_TNUMX - LJ_TISGCV // tvisgcv(v)
3449 | jbe <1
3450 | cleartp GCOBJ:RA
3451 | test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(v)
3452 | jz <1
3453 | // Crossed a write barrier. Move the barrier forward.
3454 |.if not X64WIN
3455 | mov CARG2, RB
3456 | mov RB, BASE // Save BASE.
3457 |.else
3458 | xchg CARG2, RB // Save BASE (CARG2 == BASE).
3459 |.endif
3460 | lea GL:CARG1, [DISPATCH+GG_DISP2G]
3461 | call extern lj_gc_barrieruv // (global_State *g, TValue *tv)
3462 | mov BASE, RB // Restore BASE.
3463 | jmp <1
3464 break;
3465#undef TV2MARKOFS
3466 case BC_USETS:
3467 | ins_AND // RA = upvalue #, RD = str const (~)
3468 | mov LFUNC:RB, [BASE-16]
3469 | cleartp LFUNC:RB
3470 | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)]
3471 | mov STR:RA, [KBASE+RD*8]
3472 | mov RD, UPVAL:RB->v
3473 | settp STR:ITYPE, STR:RA, LJ_TSTR
3474 | mov [RD], STR:ITYPE
3475 | test byte UPVAL:RB->marked, LJ_GC_BLACK // isblack(uv)
3476 | jnz >2
3477 |1:
3478 | ins_next
3479 |
3480 |2: // Check if string is white and ensure upvalue is closed.
3481 | test byte GCOBJ:RA->gch.marked, LJ_GC_WHITES // iswhite(str)
3482 | jz <1
3483 | cmp byte UPVAL:RB->closed, 0
3484 | jz <1
3485 | // Crossed a write barrier. Move the barrier forward.
3486 | mov RB, BASE // Save BASE (CARG2 == BASE).
3487 | mov CARG2, RD
3488 | lea GL:CARG1, [DISPATCH+GG_DISP2G]
3489 | call extern lj_gc_barrieruv // (global_State *g, TValue *tv)
3490 | mov BASE, RB // Restore BASE.
3491 | jmp <1
3492 break;
3493 case BC_USETN:
3494 | ins_AD // RA = upvalue #, RD = num const
3495 | mov LFUNC:RB, [BASE-16]
3496 | cleartp LFUNC:RB
3497 | movsd xmm0, qword [KBASE+RD*8]
3498 | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)]
3499 | mov RA, UPVAL:RB->v
3500 | movsd qword [RA], xmm0
3501 | ins_next
3502 break;
3503 case BC_USETP:
3504 | ins_AD // RA = upvalue #, RD = primitive type (~)
3505 | mov LFUNC:RB, [BASE-16]
3506 | cleartp LFUNC:RB
3507 | mov UPVAL:RB, [LFUNC:RB+RA*8+offsetof(GCfuncL, uvptr)]
3508 | shl RD, 47
3509 | not RD
3510 | mov RA, UPVAL:RB->v
3511 | mov [RA], RD
3512 | ins_next
3513 break;
3514 case BC_UCLO:
3515 | ins_AD // RA = level, RD = target
3516 | branchPC RD // Do this first to free RD.
3517 | mov L:RB, SAVE_L
3518 | cmp aword L:RB->openupval, 0
3519 | je >1
3520 | mov L:RB->base, BASE
3521 | lea CARG2, [BASE+RA*8] // Caveat: CARG2 == BASE
3522 | mov L:CARG1, L:RB // Caveat: CARG1 == RA
3523 | call extern lj_func_closeuv // (lua_State *L, TValue *level)
3524 | mov BASE, L:RB->base
3525 |1:
3526 | ins_next
3527 break;
3528
3529 case BC_FNEW:
3530 | ins_AND // RA = dst, RD = proto const (~) (holding function prototype)
3531 | mov L:RB, SAVE_L
3532 | mov L:RB->base, BASE // Caveat: CARG2/CARG3 may be BASE.
3533 | mov CARG3, [BASE-16]
3534 | cleartp CARG3
3535 | mov CARG2, [KBASE+RD*8] // Fetch GCproto *.
3536 | mov CARG1, L:RB
3537 | mov SAVE_PC, PC
3538 | // (lua_State *L, GCproto *pt, GCfuncL *parent)
3539 | call extern lj_func_newL_gc
3540 | // GCfuncL * returned in eax (RC).
3541 | mov BASE, L:RB->base
3542 | movzx RAd, PC_RA
3543 | settp LFUNC:RC, LJ_TFUNC
3544 | mov [BASE+RA*8], LFUNC:RC
3545 | ins_next
3546 break;
3547
3548 /* -- Table ops --------------------------------------------------------- */
3549
3550 case BC_TNEW:
3551 | ins_AD // RA = dst, RD = hbits|asize
3552 | mov L:RB, SAVE_L
3553 | mov L:RB->base, BASE
3554 | mov RA, [DISPATCH+DISPATCH_GL(gc.total)]
3555 | cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)]
3556 | mov SAVE_PC, PC
3557 | jae >5
3558 |1:
3559 | mov CARG3d, RDd
3560 | and RDd, 0x7ff
3561 | shr CARG3d, 11
3562 | cmp RDd, 0x7ff
3563 | je >3
3564 |2:
3565 | mov L:CARG1, L:RB
3566 | mov CARG2d, RDd
3567 | call extern lj_tab_new // (lua_State *L, int32_t asize, uint32_t hbits)
3568 | // Table * returned in eax (RC).
3569 | mov BASE, L:RB->base
3570 | movzx RAd, PC_RA
3571 | settp TAB:RC, LJ_TTAB
3572 | mov [BASE+RA*8], TAB:RC
3573 | ins_next
3574 |3: // Turn 0x7ff into 0x801.
3575 | mov RDd, 0x801
3576 | jmp <2
3577 |5:
3578 | mov L:CARG1, L:RB
3579 | call extern lj_gc_step_fixtop // (lua_State *L)
3580 | movzx RDd, PC_RD
3581 | jmp <1
3582 break;
3583 case BC_TDUP:
3584 | ins_AND // RA = dst, RD = table const (~) (holding template table)
3585 | mov L:RB, SAVE_L
3586 | mov RA, [DISPATCH+DISPATCH_GL(gc.total)]
3587 | mov SAVE_PC, PC
3588 | cmp RA, [DISPATCH+DISPATCH_GL(gc.threshold)]
3589 | mov L:RB->base, BASE
3590 | jae >3
3591 |2:
3592 | mov TAB:CARG2, [KBASE+RD*8] // Caveat: CARG2 == BASE
3593 | mov L:CARG1, L:RB // Caveat: CARG1 == RA
3594 | call extern lj_tab_dup // (lua_State *L, Table *kt)
3595 | // Table * returned in eax (RC).
3596 | mov BASE, L:RB->base
3597 | movzx RAd, PC_RA
3598 | settp TAB:RC, LJ_TTAB
3599 | mov [BASE+RA*8], TAB:RC
3600 | ins_next
3601 |3:
3602 | mov L:CARG1, L:RB
3603 | call extern lj_gc_step_fixtop // (lua_State *L)
3604 | movzx RDd, PC_RD // Need to reload RD.
3605 | not RD
3606 | jmp <2
3607 break;
3608
3609 case BC_GGET:
3610 | ins_AND // RA = dst, RD = str const (~)
3611 | mov LFUNC:RB, [BASE-16]
3612 | cleartp LFUNC:RB
3613 | mov TAB:RB, LFUNC:RB->env
3614 | mov STR:RC, [KBASE+RD*8]
3615 | jmp ->BC_TGETS_Z
3616 break;
3617 case BC_GSET:
3618 | ins_AND // RA = src, RD = str const (~)
3619 | mov LFUNC:RB, [BASE-16]
3620 | cleartp LFUNC:RB
3621 | mov TAB:RB, LFUNC:RB->env
3622 | mov STR:RC, [KBASE+RD*8]
3623 | jmp ->BC_TSETS_Z
3624 break;
3625
3626 case BC_TGETV:
3627 | ins_ABC // RA = dst, RB = table, RC = key
3628 | mov TAB:RB, [BASE+RB*8]
3629 | mov RC, [BASE+RC*8]
3630 | checktab TAB:RB, ->vmeta_tgetv
3631 |
3632 | // Integer key?
3633 |.if DUALNUM
3634 | checkint RC, >5
3635 |.else
3636 | // Convert number to int and back and compare.
3637 | checknum RC, >5
3638 | movd xmm0, RC
3639 | cvttsd2si RCd, xmm0
3640 | cvtsi2sd xmm1, RCd
3641 | ucomisd xmm0, xmm1
3642 | jne ->vmeta_tgetv // Generic numeric key? Use fallback.
3643 |.endif
3644 | cmp RCd, TAB:RB->asize // Takes care of unordered, too.
3645 | jae ->vmeta_tgetv // Not in array part? Use fallback.
3646 | shl RCd, 3
3647 | add RC, TAB:RB->array
3648 | // Get array slot.
3649 | mov ITYPE, [RC]
3650 | cmp ITYPE, LJ_TNIL // Avoid overwriting RB in fastpath.
3651 | je >2
3652 |1:
3653 | mov [BASE+RA*8], ITYPE
3654 | ins_next
3655 |
3656 |2: // Check for __index if table value is nil.
3657 | mov TAB:TMPR, TAB:RB->metatable
3658 | test TAB:TMPR, TAB:TMPR
3659 | jz <1
3660 | test byte TAB:TMPR->nomm, 1<<MM_index
3661 | jz ->vmeta_tgetv // 'no __index' flag NOT set: check.
3662 | jmp <1
3663 |
3664 |5: // String key?
3665 | cmp ITYPEd, LJ_TSTR; jne ->vmeta_tgetv
3666 | cleartp STR:RC
3667 | jmp ->BC_TGETS_Z
3668 break;
3669 case BC_TGETS:
3670 | ins_ABC // RA = dst, RB = table, RC = str const (~)
3671 | mov TAB:RB, [BASE+RB*8]
3672 | not RC
3673 | mov STR:RC, [KBASE+RC*8]
3674 | checktab TAB:RB, ->vmeta_tgets
3675 |->BC_TGETS_Z: // RB = GCtab *, RC = GCstr *
3676 | mov TMPRd, TAB:RB->hmask
3677 | and TMPRd, STR:RC->hash
3678 | imul TMPRd, #NODE
3679 | add NODE:TMPR, TAB:RB->node
3680 | settp ITYPE, STR:RC, LJ_TSTR
3681 |1:
3682 | cmp NODE:TMPR->key, ITYPE
3683 | jne >4
3684 | // Get node value.
3685 | mov ITYPE, NODE:TMPR->val
3686 | cmp ITYPE, LJ_TNIL
3687 | je >5 // Key found, but nil value?
3688 |2:
3689 | mov [BASE+RA*8], ITYPE
3690 | ins_next
3691 |
3692 |4: // Follow hash chain.
3693 | mov NODE:TMPR, NODE:TMPR->next
3694 | test NODE:TMPR, NODE:TMPR
3695 | jnz <1
3696 | // End of hash chain: key not found, nil result.
3697 | mov ITYPE, LJ_TNIL
3698 |
3699 |5: // Check for __index if table value is nil.
3700 | mov TAB:TMPR, TAB:RB->metatable
3701 | test TAB:TMPR, TAB:TMPR
3702 | jz <2 // No metatable: done.
3703 | test byte TAB:TMPR->nomm, 1<<MM_index
3704 | jnz <2 // 'no __index' flag set: done.
3705 | jmp ->vmeta_tgets // Caveat: preserve STR:RC.
3706 break;
3707 case BC_TGETB:
3708 | ins_ABC // RA = dst, RB = table, RC = byte literal
3709 | mov TAB:RB, [BASE+RB*8]
3710 | checktab TAB:RB, ->vmeta_tgetb
3711 | cmp RCd, TAB:RB->asize
3712 | jae ->vmeta_tgetb
3713 | shl RCd, 3
3714 | add RC, TAB:RB->array
3715 | // Get array slot.
3716 | mov ITYPE, [RC]
3717 | cmp ITYPE, LJ_TNIL
3718 | je >2
3719 |1:
3720 | mov [BASE+RA*8], ITYPE
3721 | ins_next
3722 |
3723 |2: // Check for __index if table value is nil.
3724 | mov TAB:TMPR, TAB:RB->metatable
3725 | test TAB:TMPR, TAB:TMPR
3726 | jz <1
3727 | test byte TAB:TMPR->nomm, 1<<MM_index
3728 | jz ->vmeta_tgetb // 'no __index' flag NOT set: check.
3729 | jmp <1
3730 break;
3731 case BC_TGETR:
3732 | ins_ABC // RA = dst, RB = table, RC = key
3733 | mov TAB:RB, [BASE+RB*8]
3734 | cleartp TAB:RB
3735 |.if DUALNUM
3736 | mov RCd, dword [BASE+RC*8]
3737 |.else
3738 | cvttsd2si RCd, qword [BASE+RC*8]
3739 |.endif
3740 | cmp RCd, TAB:RB->asize
3741 | jae ->vmeta_tgetr // Not in array part? Use fallback.
3742 | shl RCd, 3
3743 | add RC, TAB:RB->array
3744 | // Get array slot.
3745 |->BC_TGETR_Z:
3746 | mov ITYPE, [RC]
3747 |->BC_TGETR2_Z:
3748 | mov [BASE+RA*8], ITYPE
3749 | ins_next
3750 break;
3751
3752 case BC_TSETV:
3753 | ins_ABC // RA = src, RB = table, RC = key
3754 | mov TAB:RB, [BASE+RB*8]
3755 | mov RC, [BASE+RC*8]
3756 | checktab TAB:RB, ->vmeta_tsetv
3757 |
3758 | // Integer key?
3759 |.if DUALNUM
3760 | checkint RC, >5
3761 |.else
3762 | // Convert number to int and back and compare.
3763 | checknum RC, >5
3764 | movd xmm0, RC
3765 | cvttsd2si RCd, xmm0
3766 | cvtsi2sd xmm1, RCd
3767 | ucomisd xmm0, xmm1
3768 | jne ->vmeta_tsetv // Generic numeric key? Use fallback.
3769 |.endif
3770 | cmp RCd, TAB:RB->asize // Takes care of unordered, too.
3771 | jae ->vmeta_tsetv
3772 | shl RCd, 3
3773 | add RC, TAB:RB->array
3774 | cmp aword [RC], LJ_TNIL
3775 | je >3 // Previous value is nil?
3776 |1:
3777 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
3778 | jnz >7
3779 |2: // Set array slot.
3780 | mov RB, [BASE+RA*8]
3781 | mov [RC], RB
3782 | ins_next
3783 |
3784 |3: // Check for __newindex if previous value is nil.
3785 | mov TAB:TMPR, TAB:RB->metatable
3786 | test TAB:TMPR, TAB:TMPR
3787 | jz <1
3788 | test byte TAB:TMPR->nomm, 1<<MM_newindex
3789 | jz ->vmeta_tsetv // 'no __newindex' flag NOT set: check.
3790 | jmp <1
3791 |
3792 |5: // String key?
3793 | cmp ITYPEd, LJ_TSTR; jne ->vmeta_tsetv
3794 | cleartp STR:RC
3795 | jmp ->BC_TSETS_Z
3796 |
3797 |7: // Possible table write barrier for the value. Skip valiswhite check.
3798 | barrierback TAB:RB, TMPR
3799 | jmp <2
3800 break;
3801 case BC_TSETS:
3802 | ins_ABC // RA = src, RB = table, RC = str const (~)
3803 | mov TAB:RB, [BASE+RB*8]
3804 | not RC
3805 | mov STR:RC, [KBASE+RC*8]
3806 | checktab TAB:RB, ->vmeta_tsets
3807 |->BC_TSETS_Z: // RB = GCtab *, RC = GCstr *
3808 | mov TMPRd, TAB:RB->hmask
3809 | and TMPRd, STR:RC->hash
3810 | imul TMPRd, #NODE
3811 | mov byte TAB:RB->nomm, 0 // Clear metamethod cache.
3812 | add NODE:TMPR, TAB:RB->node
3813 | settp ITYPE, STR:RC, LJ_TSTR
3814 |1:
3815 | cmp NODE:TMPR->key, ITYPE
3816 | jne >5
3817 | // Ok, key found. Assumes: offsetof(Node, val) == 0
3818 | cmp aword [TMPR], LJ_TNIL
3819 | je >4 // Previous value is nil?
3820 |2:
3821 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
3822 | jnz >7
3823 |3: // Set node value.
3824 | mov ITYPE, [BASE+RA*8]
3825 | mov [TMPR], ITYPE
3826 | ins_next
3827 |
3828 |4: // Check for __newindex if previous value is nil.
3829 | mov TAB:ITYPE, TAB:RB->metatable
3830 | test TAB:ITYPE, TAB:ITYPE
3831 | jz <2
3832 | test byte TAB:ITYPE->nomm, 1<<MM_newindex
3833 | jz ->vmeta_tsets // 'no __newindex' flag NOT set: check.
3834 | jmp <2
3835 |
3836 |5: // Follow hash chain.
3837 | mov NODE:TMPR, NODE:TMPR->next
3838 | test NODE:TMPR, NODE:TMPR
3839 | jnz <1
3840 | // End of hash chain: key not found, add a new one.
3841 |
3842 | // But check for __newindex first.
3843 | mov TAB:TMPR, TAB:RB->metatable
3844 | test TAB:TMPR, TAB:TMPR
3845 | jz >6 // No metatable: continue.
3846 | test byte TAB:TMPR->nomm, 1<<MM_newindex
3847 | jz ->vmeta_tsets // 'no __newindex' flag NOT set: check.
3848 |6:
3849 | mov TMP1, ITYPE
3850 | mov L:CARG1, SAVE_L
3851 | mov L:CARG1->base, BASE
3852 | lea CARG3, TMP1
3853 | mov CARG2, TAB:RB
3854 | mov SAVE_PC, PC
3855 | call extern lj_tab_newkey // (lua_State *L, GCtab *t, TValue *k)
3856 | // Handles write barrier for the new key. TValue * returned in eax (RC).
3857 | mov L:CARG1, SAVE_L
3858 | mov BASE, L:CARG1->base
3859 | mov TMPR, rax
3860 | movzx RAd, PC_RA
3861 | jmp <2 // Must check write barrier for value.
3862 |
3863 |7: // Possible table write barrier for the value. Skip valiswhite check.
3864 | barrierback TAB:RB, ITYPE
3865 | jmp <3
3866 break;
3867 case BC_TSETB:
3868 | ins_ABC // RA = src, RB = table, RC = byte literal
3869 | mov TAB:RB, [BASE+RB*8]
3870 | checktab TAB:RB, ->vmeta_tsetb
3871 | cmp RCd, TAB:RB->asize
3872 | jae ->vmeta_tsetb
3873 | shl RCd, 3
3874 | add RC, TAB:RB->array
3875 | cmp aword [RC], LJ_TNIL
3876 | je >3 // Previous value is nil?
3877 |1:
3878 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
3879 | jnz >7
3880 |2: // Set array slot.
3881 | mov ITYPE, [BASE+RA*8]
3882 | mov [RC], ITYPE
3883 | ins_next
3884 |
3885 |3: // Check for __newindex if previous value is nil.
3886 | mov TAB:TMPR, TAB:RB->metatable
3887 | test TAB:TMPR, TAB:TMPR
3888 | jz <1
3889 | test byte TAB:TMPR->nomm, 1<<MM_newindex
3890 | jz ->vmeta_tsetb // 'no __newindex' flag NOT set: check.
3891 | jmp <1
3892 |
3893 |7: // Possible table write barrier for the value. Skip valiswhite check.
3894 | barrierback TAB:RB, TMPR
3895 | jmp <2
3896 break;
3897 case BC_TSETR:
3898 | ins_ABC // RA = src, RB = table, RC = key
3899 | mov TAB:RB, [BASE+RB*8]
3900 | cleartp TAB:RB
3901 |.if DUALNUM
3902 | mov RC, [BASE+RC*8]
3903 |.else
3904 | cvttsd2si RCd, qword [BASE+RC*8]
3905 |.endif
3906 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
3907 | jnz >7
3908 |2:
3909 | cmp RCd, TAB:RB->asize
3910 | jae ->vmeta_tsetr
3911 | shl RCd, 3
3912 | add RC, TAB:RB->array
3913 | // Set array slot.
3914 |->BC_TSETR_Z:
3915 | mov ITYPE, [BASE+RA*8]
3916 | mov [RC], ITYPE
3917 | ins_next
3918 |
3919 |7: // Possible table write barrier for the value. Skip valiswhite check.
3920 | barrierback TAB:RB, TMPR
3921 | jmp <2
3922 break;
3923
3924 case BC_TSETM:
3925 | ins_AD // RA = base (table at base-1), RD = num const (start index)
3926 |1:
3927 | mov TMPRd, dword [KBASE+RD*8] // Integer constant is in lo-word.
3928 | lea RA, [BASE+RA*8]
3929 | mov TAB:RB, [RA-8] // Guaranteed to be a table.
3930 | cleartp TAB:RB
3931 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
3932 | jnz >7
3933 |2:
3934 | mov RDd, MULTRES
3935 | sub RDd, 1
3936 | jz >4 // Nothing to copy?
3937 | add RDd, TMPRd // Compute needed size.
3938 | cmp RDd, TAB:RB->asize
3939 | ja >5 // Doesn't fit into array part?
3940 | sub RDd, TMPRd
3941 | shl TMPRd, 3
3942 | add TMPR, TAB:RB->array
3943 |3: // Copy result slots to table.
3944 | mov RB, [RA]
3945 | add RA, 8
3946 | mov [TMPR], RB
3947 | add TMPR, 8
3948 | sub RDd, 1
3949 | jnz <3
3950 |4:
3951 | ins_next
3952 |
3953 |5: // Need to resize array part.
3954 | mov L:CARG1, SAVE_L
3955 | mov L:CARG1->base, BASE // Caveat: CARG2/CARG3 may be BASE.
3956 | mov CARG2, TAB:RB
3957 | mov CARG3d, RDd
3958 | mov L:RB, L:CARG1
3959 | mov SAVE_PC, PC
3960 | call extern lj_tab_reasize // (lua_State *L, GCtab *t, int nasize)
3961 | mov BASE, L:RB->base
3962 | movzx RAd, PC_RA // Restore RA.
3963 | movzx RDd, PC_RD // Restore RD.
3964 | jmp <1 // Retry.
3965 |
3966 |7: // Possible table write barrier for any value. Skip valiswhite check.
3967 | barrierback TAB:RB, RD
3968 | jmp <2
3969 break;
3970
3971 /* -- Calls and vararg handling ----------------------------------------- */
3972
3973 case BC_CALL: case BC_CALLM:
3974 | ins_A_C // RA = base, (RB = nresults+1,) RC = nargs+1 | extra_nargs
3975 if (op == BC_CALLM) {
3976 | add NARGS:RDd, MULTRES
3977 }
3978 | mov LFUNC:RB, [BASE+RA*8]
3979 | checkfunc LFUNC:RB, ->vmeta_call_ra
3980 | lea BASE, [BASE+RA*8+16]
3981 | ins_call
3982 break;
3983
3984 case BC_CALLMT:
3985 | ins_AD // RA = base, RD = extra_nargs
3986 | add NARGS:RDd, MULTRES
3987 | // Fall through. Assumes BC_CALLT follows and ins_AD is a no-op.
3988 break;
3989 case BC_CALLT:
3990 | ins_AD // RA = base, RD = nargs+1
3991 | lea RA, [BASE+RA*8+16]
3992 | mov KBASE, BASE // Use KBASE for move + vmeta_call hint.
3993 | mov LFUNC:RB, [RA-16]
3994 | checktp_nc LFUNC:RB, LJ_TFUNC, ->vmeta_call
3995 |->BC_CALLT_Z:
3996 | mov PC, [BASE-8]
3997 | test PCd, FRAME_TYPE
3998 | jnz >7
3999 |1:
4000 | mov [BASE-16], LFUNC:RB // Copy func+tag down, reloaded below.
4001 | mov MULTRES, NARGS:RDd
4002 | sub NARGS:RDd, 1
4003 | jz >3
4004 |2: // Move args down.
4005 | mov RB, [RA]
4006 | add RA, 8
4007 | mov [KBASE], RB
4008 | add KBASE, 8
4009 | sub NARGS:RDd, 1
4010 | jnz <2
4011 |
4012 | mov LFUNC:RB, [BASE-16]
4013 |3:
4014 | cleartp LFUNC:RB
4015 | mov NARGS:RDd, MULTRES
4016 | cmp byte LFUNC:RB->ffid, 1 // (> FF_C) Calling a fast function?
4017 | ja >5
4018 |4:
4019 | ins_callt
4020 |
4021 |5: // Tailcall to a fast function.
4022 | test PCd, FRAME_TYPE // Lua frame below?
4023 | jnz <4
4024 | movzx RAd, PC_RA
4025 | neg RA
4026 | mov LFUNC:KBASE, [BASE+RA*8-32] // Need to prepare KBASE.
4027 | cleartp LFUNC:KBASE
4028 | mov KBASE, LFUNC:KBASE->pc
4029 | mov KBASE, [KBASE+PC2PROTO(k)]
4030 | jmp <4
4031 |
4032 |7: // Tailcall from a vararg function.
4033 | sub PC, FRAME_VARG
4034 | test PCd, FRAME_TYPEP
4035 | jnz >8 // Vararg frame below?
4036 | sub BASE, PC // Need to relocate BASE/KBASE down.
4037 | mov KBASE, BASE
4038 | mov PC, [BASE-8]
4039 | jmp <1
4040 |8:
4041 | add PCd, FRAME_VARG
4042 | jmp <1
4043 break;
4044
4045 case BC_ITERC:
4046 | ins_A // RA = base, (RB = nresults+1,) RC = nargs+1 (2+1)
4047 | lea RA, [BASE+RA*8+16] // fb = base+2
4048 | mov RB, [RA-32] // Copy state. fb[0] = fb[-4].
4049 | mov RC, [RA-24] // Copy control var. fb[1] = fb[-3].
4050 | mov [RA], RB
4051 | mov [RA+8], RC
4052 | mov LFUNC:RB, [RA-40] // Copy callable. fb[-2] = fb[-5]
4053 | mov [RA-16], LFUNC:RB
4054 | mov NARGS:RDd, 2+1 // Handle like a regular 2-arg call.
4055 | checkfunc LFUNC:RB, ->vmeta_call
4056 | mov BASE, RA
4057 | ins_call
4058 break;
4059
4060 case BC_ITERN:
4061 | ins_A // RA = base, (RB = nresults+1, RC = nargs+1 (2+1))
4062 |.if JIT
4063 | // NYI: add hotloop, record BC_ITERN.
4064 |.endif
4065 | mov TAB:RB, [BASE+RA*8-16]
4066 | cleartp TAB:RB
4067 | mov RCd, [BASE+RA*8-8] // Get index from control var.
4068 | mov TMPRd, TAB:RB->asize
4069 | add PC, 4
4070 | mov ITYPE, TAB:RB->array
4071 |1: // Traverse array part.
4072 | cmp RCd, TMPRd; jae >5 // Index points after array part?
4073 | cmp aword [ITYPE+RC*8], LJ_TNIL; je >4
4074 |.if not DUALNUM
4075 | cvtsi2sd xmm0, RCd
4076 |.endif
4077 | // Copy array slot to returned value.
4078 | mov RB, [ITYPE+RC*8]
4079 | mov [BASE+RA*8+8], RB
4080 | // Return array index as a numeric key.
4081 |.if DUALNUM
4082 | setint ITYPE, RC
4083 | mov [BASE+RA*8], ITYPE
4084 |.else
4085 | movsd qword [BASE+RA*8], xmm0
4086 |.endif
4087 | add RCd, 1
4088 | mov [BASE+RA*8-8], RCd // Update control var.
4089 |2:
4090 | movzx RDd, PC_RD // Get target from ITERL.
4091 | branchPC RD
4092 |3:
4093 | ins_next
4094 |
4095 |4: // Skip holes in array part.
4096 | add RCd, 1
4097 | jmp <1
4098 |
4099 |5: // Traverse hash part.
4100 | sub RCd, TMPRd
4101 |6:
4102 | cmp RCd, TAB:RB->hmask; ja <3 // End of iteration? Branch to ITERL+1.
4103 | imul ITYPEd, RCd, #NODE
4104 | add NODE:ITYPE, TAB:RB->node
4105 | cmp aword NODE:ITYPE->val, LJ_TNIL; je >7
4106 | lea TMPRd, [RCd+TMPRd+1]
4107 | // Copy key and value from hash slot.
4108 | mov RB, NODE:ITYPE->key
4109 | mov RC, NODE:ITYPE->val
4110 | mov [BASE+RA*8], RB
4111 | mov [BASE+RA*8+8], RC
4112 | mov [BASE+RA*8-8], TMPRd
4113 | jmp <2
4114 |
4115 |7: // Skip holes in hash part.
4116 | add RCd, 1
4117 | jmp <6
4118 break;
4119
4120 case BC_ISNEXT:
4121 | ins_AD // RA = base, RD = target (points to ITERN)
4122 | mov CFUNC:RB, [BASE+RA*8-24]
4123 | checkfunc CFUNC:RB, >5
4124 | checktptp [BASE+RA*8-16], LJ_TTAB, >5
4125 | cmp aword [BASE+RA*8-8], LJ_TNIL; jne >5
4126 | cmp byte CFUNC:RB->ffid, FF_next_N; jne >5
4127 | branchPC RD
4128 | mov64 TMPR, U64x(fffe7fff, 00000000)
4129 | mov [BASE+RA*8-8], TMPR // Initialize control var.
4130 |1:
4131 | ins_next
4132 |5: // Despecialize bytecode if any of the checks fail.
4133 | mov PC_OP, BC_JMP
4134 | branchPC RD
4135 | mov byte [PC], BC_ITERC
4136 | jmp <1
4137 break;
4138
4139 case BC_VARG:
4140 | ins_ABC // RA = base, RB = nresults+1, RC = numparams
4141 | lea TMPR, [BASE+RC*8+(16+FRAME_VARG)]
4142 | lea RA, [BASE+RA*8]
4143 | sub TMPR, [BASE-8]
4144 | // Note: TMPR may now be even _above_ BASE if nargs was < numparams.
4145 | test RB, RB
4146 | jz >5 // Copy all varargs?
4147 | lea RB, [RA+RB*8-8]
4148 | cmp TMPR, BASE // No vararg slots?
4149 | jnb >2
4150 |1: // Copy vararg slots to destination slots.
4151 | mov RC, [TMPR-16]
4152 | add TMPR, 8
4153 | mov [RA], RC
4154 | add RA, 8
4155 | cmp RA, RB // All destination slots filled?
4156 | jnb >3
4157 | cmp TMPR, BASE // No more vararg slots?
4158 | jb <1
4159 |2: // Fill up remainder with nil.
4160 | mov aword [RA], LJ_TNIL
4161 | add RA, 8
4162 | cmp RA, RB
4163 | jb <2
4164 |3:
4165 | ins_next
4166 |
4167 |5: // Copy all varargs.
4168 | mov MULTRES, 1 // MULTRES = 0+1
4169 | mov RC, BASE
4170 | sub RC, TMPR
4171 | jbe <3 // No vararg slots?
4172 | mov RBd, RCd
4173 | shr RBd, 3
4174 | add RBd, 1
4175 | mov MULTRES, RBd // MULTRES = #varargs+1
4176 | mov L:RB, SAVE_L
4177 | add RC, RA
4178 | cmp RC, L:RB->maxstack
4179 | ja >7 // Need to grow stack?
4180 |6: // Copy all vararg slots.
4181 | mov RC, [TMPR-16]
4182 | add TMPR, 8
4183 | mov [RA], RC
4184 | add RA, 8
4185 | cmp TMPR, BASE // No more vararg slots?
4186 | jb <6
4187 | jmp <3
4188 |
4189 |7: // Grow stack for varargs.
4190 | mov L:RB->base, BASE
4191 | mov L:RB->top, RA
4192 | mov SAVE_PC, PC
4193 | sub TMPR, BASE // Need delta, because BASE may change.
4194 | mov TMP1hi, TMPRd
4195 | mov CARG2d, MULTRES
4196 | sub CARG2d, 1
4197 | mov CARG1, L:RB
4198 | call extern lj_state_growstack // (lua_State *L, int n)
4199 | mov BASE, L:RB->base
4200 | movsxd TMPR, TMP1hi
4201 | mov RA, L:RB->top
4202 | add TMPR, BASE
4203 | jmp <6
4204 break;
4205
4206 /* -- Returns ----------------------------------------------------------- */
4207
4208 case BC_RETM:
4209 | ins_AD // RA = results, RD = extra_nresults
4210 | add RDd, MULTRES // MULTRES >=1, so RD >=1.
4211 | // Fall through. Assumes BC_RET follows and ins_AD is a no-op.
4212 break;
4213
4214 case BC_RET: case BC_RET0: case BC_RET1:
4215 | ins_AD // RA = results, RD = nresults+1
4216 if (op != BC_RET0) {
4217 | shl RAd, 3
4218 }
4219 |1:
4220 | mov PC, [BASE-8]
4221 | mov MULTRES, RDd // Save nresults+1.
4222 | test PCd, FRAME_TYPE // Check frame type marker.
4223 | jnz >7 // Not returning to a fixarg Lua func?
4224 switch (op) {
4225 case BC_RET:
4226 |->BC_RET_Z:
4227 | mov KBASE, BASE // Use KBASE for result move.
4228 | sub RDd, 1
4229 | jz >3
4230 |2: // Move results down.
4231 | mov RB, [KBASE+RA]
4232 | mov [KBASE-16], RB
4233 | add KBASE, 8
4234 | sub RDd, 1
4235 | jnz <2
4236 |3:
4237 | mov RDd, MULTRES // Note: MULTRES may be >255.
4238 | movzx RBd, PC_RB // So cannot compare with RDL!
4239 |5:
4240 | cmp RBd, RDd // More results expected?
4241 | ja >6
4242 break;
4243 case BC_RET1:
4244 | mov RB, [BASE+RA]
4245 | mov [BASE-16], RB
4246 /* fallthrough */
4247 case BC_RET0:
4248 |5:
4249 | cmp PC_RB, RDL // More results expected?
4250 | ja >6
4251 default:
4252 break;
4253 }
4254 | movzx RAd, PC_RA
4255 | neg RA
4256 | lea BASE, [BASE+RA*8-16] // base = base - (RA+2)*8
4257 | mov LFUNC:KBASE, [BASE-16]
4258 | cleartp LFUNC:KBASE
4259 | mov KBASE, LFUNC:KBASE->pc
4260 | mov KBASE, [KBASE+PC2PROTO(k)]
4261 | ins_next
4262 |
4263 |6: // Fill up results with nil.
4264 if (op == BC_RET) {
4265 | mov aword [KBASE-16], LJ_TNIL // Note: relies on shifted base.
4266 | add KBASE, 8
4267 } else {
4268 | mov aword [BASE+RD*8-24], LJ_TNIL
4269 }
4270 | add RD, 1
4271 | jmp <5
4272 |
4273 |7: // Non-standard return case.
4274 | lea RB, [PC-FRAME_VARG]
4275 | test RBd, FRAME_TYPEP
4276 | jnz ->vm_return
4277 | // Return from vararg function: relocate BASE down and RA up.
4278 | sub BASE, RB
4279 if (op != BC_RET0) {
4280 | add RA, RB
4281 }
4282 | jmp <1
4283 break;
4284
4285 /* -- Loops and branches ------------------------------------------------ */
4286
4287 |.define FOR_IDX, [RA]
4288 |.define FOR_STOP, [RA+8]
4289 |.define FOR_STEP, [RA+16]
4290 |.define FOR_EXT, [RA+24]
4291
4292 case BC_FORL:
4293 |.if JIT
4294 | hotloop RBd
4295 |.endif
4296 | // Fall through. Assumes BC_IFORL follows and ins_AJ is a no-op.
4297 break;
4298
4299 case BC_JFORI:
4300 case BC_JFORL:
4301#if !LJ_HASJIT
4302 break;
4303#endif
4304 case BC_FORI:
4305 case BC_IFORL:
4306 vk = (op == BC_IFORL || op == BC_JFORL);
4307 | ins_AJ // RA = base, RD = target (after end of loop or start of loop)
4308 | lea RA, [BASE+RA*8]
4309 if (LJ_DUALNUM) {
4310 | mov RB, FOR_IDX
4311 | checkint RB, >9
4312 | mov TMPR, FOR_STOP
4313 if (!vk) {
4314 | checkint TMPR, ->vmeta_for
4315 | mov ITYPE, FOR_STEP
4316 | test ITYPEd, ITYPEd; js >5
4317 | sar ITYPE, 47;
4318 | cmp ITYPEd, LJ_TISNUM; jne ->vmeta_for
4319 } else {
4320#ifdef LUA_USE_ASSERT
4321 | checkinttp FOR_STOP, ->assert_bad_for_arg_type
4322 | checkinttp FOR_STEP, ->assert_bad_for_arg_type
4323#endif
4324 | mov ITYPE, FOR_STEP
4325 | test ITYPEd, ITYPEd; js >5
4326 | add RBd, ITYPEd; jo >1
4327 | setint RB
4328 | mov FOR_IDX, RB
4329 }
4330 | cmp RBd, TMPRd
4331 | mov FOR_EXT, RB
4332 if (op == BC_FORI) {
4333 | jle >7
4334 |1:
4335 |6:
4336 | branchPC RD
4337 } else if (op == BC_JFORI) {
4338 | branchPC RD
4339 | movzx RDd, PC_RD
4340 | jle =>BC_JLOOP
4341 |1:
4342 |6:
4343 } else if (op == BC_IFORL) {
4344 | jg >7
4345 |6:
4346 | branchPC RD
4347 |1:
4348 } else {
4349 | jle =>BC_JLOOP
4350 |1:
4351 |6:
4352 }
4353 |7:
4354 | ins_next
4355 |
4356 |5: // Invert check for negative step.
4357 if (!vk) {
4358 | sar ITYPE, 47;
4359 | cmp ITYPEd, LJ_TISNUM; jne ->vmeta_for
4360 } else {
4361 | add RBd, ITYPEd; jo <1
4362 | setint RB
4363 | mov FOR_IDX, RB
4364 }
4365 | cmp RBd, TMPRd
4366 | mov FOR_EXT, RB
4367 if (op == BC_FORI) {
4368 | jge <7
4369 } else if (op == BC_JFORI) {
4370 | branchPC RD
4371 | movzx RDd, PC_RD
4372 | jge =>BC_JLOOP
4373 } else if (op == BC_IFORL) {
4374 | jl <7
4375 } else {
4376 | jge =>BC_JLOOP
4377 }
4378 | jmp <6
4379 |9: // Fallback to FP variant.
4380 if (!vk) {
4381 | jae ->vmeta_for
4382 }
4383 } else if (!vk) {
4384 | checknumtp FOR_IDX, ->vmeta_for
4385 }
4386 if (!vk) {
4387 | checknumtp FOR_STOP, ->vmeta_for
4388 } else {
4389#ifdef LUA_USE_ASSERT
4390 | checknumtp FOR_STOP, ->assert_bad_for_arg_type
4391 | checknumtp FOR_STEP, ->assert_bad_for_arg_type
4392#endif
4393 }
4394 | mov RB, FOR_STEP
4395 if (!vk) {
4396 | checknum RB, ->vmeta_for
4397 }
4398 | movsd xmm0, qword FOR_IDX
4399 | movsd xmm1, qword FOR_STOP
4400 if (vk) {
4401 | addsd xmm0, qword FOR_STEP
4402 | movsd qword FOR_IDX, xmm0
4403 | test RB, RB; js >3
4404 } else {
4405 | jl >3
4406 }
4407 | ucomisd xmm1, xmm0
4408 |1:
4409 | movsd qword FOR_EXT, xmm0
4410 if (op == BC_FORI) {
4411 |.if DUALNUM
4412 | jnb <7
4413 |.else
4414 | jnb >2
4415 | branchPC RD
4416 |.endif
4417 } else if (op == BC_JFORI) {
4418 | branchPC RD
4419 | movzx RDd, PC_RD
4420 | jnb =>BC_JLOOP
4421 } else if (op == BC_IFORL) {
4422 |.if DUALNUM
4423 | jb <7
4424 |.else
4425 | jb >2
4426 | branchPC RD
4427 |.endif
4428 } else {
4429 | jnb =>BC_JLOOP
4430 }
4431 |.if DUALNUM
4432 | jmp <6
4433 |.else
4434 |2:
4435 | ins_next
4436 |.endif
4437 |
4438 |3: // Invert comparison if step is negative.
4439 | ucomisd xmm0, xmm1
4440 | jmp <1
4441 break;
4442
4443 case BC_ITERL:
4444 |.if JIT
4445 | hotloop RBd
4446 |.endif
4447 | // Fall through. Assumes BC_IITERL follows and ins_AJ is a no-op.
4448 break;
4449
4450 case BC_JITERL:
4451#if !LJ_HASJIT
4452 break;
4453#endif
4454 case BC_IITERL:
4455 | ins_AJ // RA = base, RD = target
4456 | lea RA, [BASE+RA*8]
4457 | mov RB, [RA]
4458 | cmp RB, LJ_TNIL; je >1 // Stop if iterator returned nil.
4459 if (op == BC_JITERL) {
4460 | mov [RA-8], RB
4461 | jmp =>BC_JLOOP
4462 } else {
4463 | branchPC RD // Otherwise save control var + branch.
4464 | mov [RA-8], RB
4465 }
4466 |1:
4467 | ins_next
4468 break;
4469
4470 case BC_LOOP:
4471 | ins_A // RA = base, RD = target (loop extent)
4472 | // Note: RA/RD is only used by trace recorder to determine scope/extent
4473 | // This opcode does NOT jump, it's only purpose is to detect a hot loop.
4474 |.if JIT
4475 | hotloop RBd
4476 |.endif
4477 | // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op.
4478 break;
4479
4480 case BC_ILOOP:
4481 | ins_A // RA = base, RD = target (loop extent)
4482 | ins_next
4483 break;
4484
4485 case BC_JLOOP:
4486 |.if JIT
4487 | ins_AD // RA = base (ignored), RD = traceno
4488 | mov RA, [DISPATCH+DISPATCH_J(trace)]
4489 | mov TRACE:RD, [RA+RD*8]
4490 | mov RD, TRACE:RD->mcode
4491 | mov L:RB, SAVE_L
4492 | mov [DISPATCH+DISPATCH_GL(jit_base)], BASE
4493 | mov [DISPATCH+DISPATCH_GL(tmpbuf.L)], L:RB
4494 | // Save additional callee-save registers only used in compiled code.
4495 |.if X64WIN
4496 | mov CSAVE_4, r12
4497 | mov CSAVE_3, r13
4498 | mov CSAVE_2, r14
4499 | mov CSAVE_1, r15
4500 | mov RA, rsp
4501 | sub rsp, 10*16+4*8
4502 | movdqa [RA-1*16], xmm6
4503 | movdqa [RA-2*16], xmm7
4504 | movdqa [RA-3*16], xmm8
4505 | movdqa [RA-4*16], xmm9
4506 | movdqa [RA-5*16], xmm10
4507 | movdqa [RA-6*16], xmm11
4508 | movdqa [RA-7*16], xmm12
4509 | movdqa [RA-8*16], xmm13
4510 | movdqa [RA-9*16], xmm14
4511 | movdqa [RA-10*16], xmm15
4512 |.else
4513 | sub rsp, 16
4514 | mov [rsp+16], r12
4515 | mov [rsp+8], r13
4516 |.endif
4517 | jmp RD
4518 |.endif
4519 break;
4520
4521 case BC_JMP:
4522 | ins_AJ // RA = unused, RD = target
4523 | branchPC RD
4524 | ins_next
4525 break;
4526
4527 /* -- Function headers -------------------------------------------------- */
4528
4529 /*
4530 ** Reminder: A function may be called with func/args above L->maxstack,
4531 ** i.e. occupying EXTRA_STACK slots. And vmeta_call may add one extra slot,
4532 ** too. This means all FUNC* ops (including fast functions) must check
4533 ** for stack overflow _before_ adding more slots!
4534 */
4535
4536 case BC_FUNCF:
4537 |.if JIT
4538 | hotcall RBd
4539 |.endif
4540 case BC_FUNCV: /* NYI: compiled vararg functions. */
4541 | // Fall through. Assumes BC_IFUNCF/BC_IFUNCV follow and ins_AD is a no-op.
4542 break;
4543
4544 case BC_JFUNCF:
4545#if !LJ_HASJIT
4546 break;
4547#endif
4548 case BC_IFUNCF:
4549 | ins_AD // BASE = new base, RA = framesize, RD = nargs+1
4550 | mov KBASE, [PC-4+PC2PROTO(k)]
4551 | mov L:RB, SAVE_L
4552 | lea RA, [BASE+RA*8] // Top of frame.
4553 | cmp RA, L:RB->maxstack
4554 | ja ->vm_growstack_f
4555 | movzx RAd, byte [PC-4+PC2PROTO(numparams)]
4556 | cmp NARGS:RDd, RAd // Check for missing parameters.
4557 | jbe >3
4558 |2:
4559 if (op == BC_JFUNCF) {
4560 | movzx RDd, PC_RD
4561 | jmp =>BC_JLOOP
4562 } else {
4563 | ins_next
4564 }
4565 |
4566 |3: // Clear missing parameters.
4567 | mov aword [BASE+NARGS:RD*8-8], LJ_TNIL
4568 | add NARGS:RDd, 1
4569 | cmp NARGS:RDd, RAd
4570 | jbe <3
4571 | jmp <2
4572 break;
4573
4574 case BC_JFUNCV:
4575#if !LJ_HASJIT
4576 break;
4577#endif
4578 | int3 // NYI: compiled vararg functions
4579 break; /* NYI: compiled vararg functions. */
4580
4581 case BC_IFUNCV:
4582 | ins_AD // BASE = new base, RA = framesize, RD = nargs+1
4583 | lea RBd, [NARGS:RD*8+FRAME_VARG+8]
4584 | lea RD, [BASE+NARGS:RD*8+8]
4585 | mov LFUNC:KBASE, [BASE-16]
4586 | mov [RD-8], RB // Store delta + FRAME_VARG.
4587 | mov [RD-16], LFUNC:KBASE // Store copy of LFUNC.
4588 | mov L:RB, SAVE_L
4589 | lea RA, [RD+RA*8]
4590 | cmp RA, L:RB->maxstack
4591 | ja ->vm_growstack_v // Need to grow stack.
4592 | mov RA, BASE
4593 | mov BASE, RD
4594 | movzx RBd, byte [PC-4+PC2PROTO(numparams)]
4595 | test RBd, RBd
4596 | jz >2
4597 | add RA, 8
4598 |1: // Copy fixarg slots up to new frame.
4599 | add RA, 8
4600 | cmp RA, BASE
4601 | jnb >3 // Less args than parameters?
4602 | mov KBASE, [RA-16]
4603 | mov [RD], KBASE
4604 | add RD, 8
4605 | mov aword [RA-16], LJ_TNIL // Clear old fixarg slot (help the GC).
4606 | sub RBd, 1
4607 | jnz <1
4608 |2:
4609 if (op == BC_JFUNCV) {
4610 | movzx RDd, PC_RD
4611 | jmp =>BC_JLOOP
4612 } else {
4613 | mov KBASE, [PC-4+PC2PROTO(k)]
4614 | ins_next
4615 }
4616 |
4617 |3: // Clear missing parameters.
4618 | mov aword [RD], LJ_TNIL
4619 | add RD, 8
4620 | sub RBd, 1
4621 | jnz <3
4622 | jmp <2
4623 break;
4624
4625 case BC_FUNCC:
4626 case BC_FUNCCW:
4627 | ins_AD // BASE = new base, RA = ins RA|RD (unused), RD = nargs+1
4628 | mov CFUNC:RB, [BASE-16]
4629 | cleartp CFUNC:RB
4630 | mov KBASE, CFUNC:RB->f
4631 | mov L:RB, SAVE_L
4632 | lea RD, [BASE+NARGS:RD*8-8]
4633 | mov L:RB->base, BASE
4634 | lea RA, [RD+8*LUA_MINSTACK]
4635 | cmp RA, L:RB->maxstack
4636 | mov L:RB->top, RD
4637 if (op == BC_FUNCC) {
4638 | mov CARG1, L:RB // Caveat: CARG1 may be RA.
4639 } else {
4640 | mov CARG2, KBASE
4641 | mov CARG1, L:RB // Caveat: CARG1 may be RA.
4642 }
4643 | ja ->vm_growstack_c // Need to grow stack.
4644 | set_vmstate C
4645 if (op == BC_FUNCC) {
4646 | call KBASE // (lua_State *L)
4647 } else {
4648 | // (lua_State *L, lua_CFunction f)
4649 | call aword [DISPATCH+DISPATCH_GL(wrapf)]
4650 }
4651 | // nresults returned in eax (RD).
4652 | mov BASE, L:RB->base
4653 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
4654 | set_vmstate INTERP
4655 | lea RA, [BASE+RD*8]
4656 | neg RA
4657 | add RA, L:RB->top // RA = (L->top-(L->base+nresults))*8
4658 | mov PC, [BASE-8] // Fetch PC of caller.
4659 | jmp ->vm_returnc
4660 break;
4661
4662 /* ---------------------------------------------------------------------- */
4663
4664 default:
4665 fprintf(stderr, "Error: undefined opcode BC_%s\n", bc_names[op]);
4666 exit(2);
4667 break;
4668 }
4669}
4670
4671static int build_backend(BuildCtx *ctx)
4672{
4673 int op;
4674 dasm_growpc(Dst, BC__MAX);
4675 build_subroutines(ctx);
4676 |.code_op
4677 for (op = 0; op < BC__MAX; op++)
4678 build_ins(ctx, (BCOp)op, op);
4679 return BC__MAX;
4680}
4681
4682/* Emit pseudo frame-info for all assembler functions. */
4683static void emit_asm_debug(BuildCtx *ctx)
4684{
4685 int fcofs = (int)((uint8_t *)ctx->glob[GLOB_vm_ffi_call] - ctx->code);
4686 switch (ctx->mode) {
4687 case BUILD_elfasm:
4688 fprintf(ctx->fp, "\t.section .debug_frame,\"\",@progbits\n");
4689 fprintf(ctx->fp,
4690 ".Lframe0:\n"
4691 "\t.long .LECIE0-.LSCIE0\n"
4692 ".LSCIE0:\n"
4693 "\t.long 0xffffffff\n"
4694 "\t.byte 0x1\n"
4695 "\t.string \"\"\n"
4696 "\t.uleb128 0x1\n"
4697 "\t.sleb128 -8\n"
4698 "\t.byte 0x10\n"
4699 "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n"
4700 "\t.byte 0x80+0x10\n\t.uleb128 0x1\n"
4701 "\t.align 8\n"
4702 ".LECIE0:\n\n");
4703 fprintf(ctx->fp,
4704 ".LSFDE0:\n"
4705 "\t.long .LEFDE0-.LASFDE0\n"
4706 ".LASFDE0:\n"
4707 "\t.long .Lframe0\n"
4708 "\t.quad .Lbegin\n"
4709 "\t.quad %d\n"
4710 "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
4711 "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
4712 "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
4713 "\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */
4714 "\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */
4715#if LJ_NO_UNWIND
4716 "\t.byte 0x8d\n\t.uleb128 0x6\n" /* offset r13 */
4717 "\t.byte 0x8c\n\t.uleb128 0x7\n" /* offset r12 */
4718#endif
4719 "\t.align 8\n"
4720 ".LEFDE0:\n\n", fcofs, CFRAME_SIZE);
4721#if LJ_HASFFI
4722 fprintf(ctx->fp,
4723 ".LSFDE1:\n"
4724 "\t.long .LEFDE1-.LASFDE1\n"
4725 ".LASFDE1:\n"
4726 "\t.long .Lframe0\n"
4727 "\t.quad lj_vm_ffi_call\n"
4728 "\t.quad %d\n"
4729 "\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */
4730 "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
4731 "\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */
4732 "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
4733 "\t.align 8\n"
4734 ".LEFDE1:\n\n", (int)ctx->codesz - fcofs);
4735#endif
4736#if !LJ_NO_UNWIND
4737#if (defined(__sun__) && defined(__svr4__))
4738 fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@unwind\n");
4739#else
4740 fprintf(ctx->fp, "\t.section .eh_frame,\"a\",@progbits\n");
4741#endif
4742 fprintf(ctx->fp,
4743 ".Lframe1:\n"
4744 "\t.long .LECIE1-.LSCIE1\n"
4745 ".LSCIE1:\n"
4746 "\t.long 0\n"
4747 "\t.byte 0x1\n"
4748 "\t.string \"zPR\"\n"
4749 "\t.uleb128 0x1\n"
4750 "\t.sleb128 -8\n"
4751 "\t.byte 0x10\n"
4752 "\t.uleb128 6\n" /* augmentation length */
4753 "\t.byte 0x1b\n" /* pcrel|sdata4 */
4754 "\t.long lj_err_unwind_dwarf-.\n"
4755 "\t.byte 0x1b\n" /* pcrel|sdata4 */
4756 "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n"
4757 "\t.byte 0x80+0x10\n\t.uleb128 0x1\n"
4758 "\t.align 8\n"
4759 ".LECIE1:\n\n");
4760 fprintf(ctx->fp,
4761 ".LSFDE2:\n"
4762 "\t.long .LEFDE2-.LASFDE2\n"
4763 ".LASFDE2:\n"
4764 "\t.long .LASFDE2-.Lframe1\n"
4765 "\t.long .Lbegin-.\n"
4766 "\t.long %d\n"
4767 "\t.uleb128 0\n" /* augmentation length */
4768 "\t.byte 0xe\n\t.uleb128 %d\n" /* def_cfa_offset */
4769 "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
4770 "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
4771 "\t.byte 0x8f\n\t.uleb128 0x4\n" /* offset r15 */
4772 "\t.byte 0x8e\n\t.uleb128 0x5\n" /* offset r14 */
4773 "\t.align 8\n"
4774 ".LEFDE2:\n\n", fcofs, CFRAME_SIZE);
4775#if LJ_HASFFI
4776 fprintf(ctx->fp,
4777 ".Lframe2:\n"
4778 "\t.long .LECIE2-.LSCIE2\n"
4779 ".LSCIE2:\n"
4780 "\t.long 0\n"
4781 "\t.byte 0x1\n"
4782 "\t.string \"zR\"\n"
4783 "\t.uleb128 0x1\n"
4784 "\t.sleb128 -8\n"
4785 "\t.byte 0x10\n"
4786 "\t.uleb128 1\n" /* augmentation length */
4787 "\t.byte 0x1b\n" /* pcrel|sdata4 */
4788 "\t.byte 0xc\n\t.uleb128 0x7\n\t.uleb128 8\n"
4789 "\t.byte 0x80+0x10\n\t.uleb128 0x1\n"
4790 "\t.align 8\n"
4791 ".LECIE2:\n\n");
4792 fprintf(ctx->fp,
4793 ".LSFDE3:\n"
4794 "\t.long .LEFDE3-.LASFDE3\n"
4795 ".LASFDE3:\n"
4796 "\t.long .LASFDE3-.Lframe2\n"
4797 "\t.long lj_vm_ffi_call-.\n"
4798 "\t.long %d\n"
4799 "\t.uleb128 0\n" /* augmentation length */
4800 "\t.byte 0xe\n\t.uleb128 16\n" /* def_cfa_offset */
4801 "\t.byte 0x86\n\t.uleb128 0x2\n" /* offset rbp */
4802 "\t.byte 0xd\n\t.uleb128 0x6\n" /* def_cfa_register rbp */
4803 "\t.byte 0x83\n\t.uleb128 0x3\n" /* offset rbx */
4804 "\t.align 8\n"
4805 ".LEFDE3:\n\n", (int)ctx->codesz - fcofs);
4806#endif
4807#endif
4808 break;
4809#if !LJ_NO_UNWIND
4810 /* Mental note: never let Apple design an assembler.
4811 ** Or a linker. Or a plastic case. But I digress.
4812 */
4813 case BUILD_machasm: {
4814#if LJ_HASFFI
4815 int fcsize = 0;
4816#endif
4817 int i;
4818 fprintf(ctx->fp, "\t.section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support\n");
4819 fprintf(ctx->fp,
4820 "EH_frame1:\n"
4821 "\t.set L$set$x,LECIEX-LSCIEX\n"
4822 "\t.long L$set$x\n"
4823 "LSCIEX:\n"
4824 "\t.long 0\n"
4825 "\t.byte 0x1\n"
4826 "\t.ascii \"zPR\\0\"\n"
4827 "\t.byte 0x1\n"
4828 "\t.byte 128-8\n"
4829 "\t.byte 0x10\n"
4830 "\t.byte 6\n" /* augmentation length */
4831 "\t.byte 0x9b\n" /* indirect|pcrel|sdata4 */
4832 "\t.long _lj_err_unwind_dwarf+4@GOTPCREL\n"
4833 "\t.byte 0x1b\n" /* pcrel|sdata4 */
4834 "\t.byte 0xc\n\t.byte 0x7\n\t.byte 8\n"
4835 "\t.byte 0x80+0x10\n\t.byte 0x1\n"
4836 "\t.align 3\n"
4837 "LECIEX:\n\n");
4838 for (i = 0; i < ctx->nsym; i++) {
4839 const char *name = ctx->sym[i].name;
4840 int32_t size = ctx->sym[i+1].ofs - ctx->sym[i].ofs;
4841 if (size == 0) continue;
4842#if LJ_HASFFI
4843 if (!strcmp(name, "_lj_vm_ffi_call")) { fcsize = size; continue; }
4844#endif
4845 fprintf(ctx->fp,
4846 "%s.eh:\n"
4847 "LSFDE%d:\n"
4848 "\t.set L$set$%d,LEFDE%d-LASFDE%d\n"
4849 "\t.long L$set$%d\n"
4850 "LASFDE%d:\n"
4851 "\t.long LASFDE%d-EH_frame1\n"
4852 "\t.long %s-.\n"
4853 "\t.long %d\n"
4854 "\t.byte 0\n" /* augmentation length */
4855 "\t.byte 0xe\n\t.byte %d\n" /* def_cfa_offset */
4856 "\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */
4857 "\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */
4858 "\t.byte 0x8f\n\t.byte 0x4\n" /* offset r15 */
4859 "\t.byte 0x8e\n\t.byte 0x5\n" /* offset r14 */
4860 "\t.align 3\n"
4861 "LEFDE%d:\n\n",
4862 name, i, i, i, i, i, i, i, name, size, CFRAME_SIZE, i);
4863 }
4864#if LJ_HASFFI
4865 if (fcsize) {
4866 fprintf(ctx->fp,
4867 "EH_frame2:\n"
4868 "\t.set L$set$y,LECIEY-LSCIEY\n"
4869 "\t.long L$set$y\n"
4870 "LSCIEY:\n"
4871 "\t.long 0\n"
4872 "\t.byte 0x1\n"
4873 "\t.ascii \"zR\\0\"\n"
4874 "\t.byte 0x1\n"
4875 "\t.byte 128-8\n"
4876 "\t.byte 0x10\n"
4877 "\t.byte 1\n" /* augmentation length */
4878 "\t.byte 0x1b\n" /* pcrel|sdata4 */
4879 "\t.byte 0xc\n\t.byte 0x7\n\t.byte 8\n"
4880 "\t.byte 0x80+0x10\n\t.byte 0x1\n"
4881 "\t.align 3\n"
4882 "LECIEY:\n\n");
4883 fprintf(ctx->fp,
4884 "_lj_vm_ffi_call.eh:\n"
4885 "LSFDEY:\n"
4886 "\t.set L$set$yy,LEFDEY-LASFDEY\n"
4887 "\t.long L$set$yy\n"
4888 "LASFDEY:\n"
4889 "\t.long LASFDEY-EH_frame2\n"
4890 "\t.long _lj_vm_ffi_call-.\n"
4891 "\t.long %d\n"
4892 "\t.byte 0\n" /* augmentation length */
4893 "\t.byte 0xe\n\t.byte 16\n" /* def_cfa_offset */
4894 "\t.byte 0x86\n\t.byte 0x2\n" /* offset rbp */
4895 "\t.byte 0xd\n\t.byte 0x6\n" /* def_cfa_register rbp */
4896 "\t.byte 0x83\n\t.byte 0x3\n" /* offset rbx */
4897 "\t.align 3\n"
4898 "LEFDEY:\n\n", fcsize);
4899 }
4900#endif
4901 fprintf(ctx->fp, ".subsections_via_symbols\n");
4902 }
4903 break;
4904#endif
4905 default: /* Difficult for other modes. */
4906 break;
4907 }
4908}
4909
diff --git a/src/vm_x86.dasc b/src/vm_x86.dasc
index 359ad4f4..211ae7b9 100644
--- a/src/vm_x86.dasc
+++ b/src/vm_x86.dasc
@@ -18,7 +18,6 @@
18| 18|
19|.if P64 19|.if P64
20|.define X64, 1 20|.define X64, 1
21|.define SSE, 1
22|.if WIN 21|.if WIN
23|.define X64WIN, 1 22|.define X64WIN, 1
24|.endif 23|.endif
@@ -116,24 +115,74 @@
116|.type NODE, Node 115|.type NODE, Node
117|.type NARGS, int 116|.type NARGS, int
118|.type TRACE, GCtrace 117|.type TRACE, GCtrace
118|.type SBUF, SBuf
119| 119|
120|// Stack layout while in interpreter. Must match with lj_frame.h. 120|// Stack layout while in interpreter. Must match with lj_frame.h.
121|//----------------------------------------------------------------------- 121|//-----------------------------------------------------------------------
122|.if not X64 // x86 stack layout. 122|.if not X64 // x86 stack layout.
123| 123|
124|.define CFRAME_SPACE, aword*7 // Delta for esp (see <--). 124|.if WIN
125|
126|.define CFRAME_SPACE, aword*9 // Delta for esp (see <--).
125|.macro saveregs_ 127|.macro saveregs_
126| push edi; push esi; push ebx 128| push edi; push esi; push ebx
129| push extern lj_err_unwind_win
130| fs; push dword [0]
131| fs; mov [0], esp
127| sub esp, CFRAME_SPACE 132| sub esp, CFRAME_SPACE
128|.endmacro 133|.endmacro
129|.macro saveregs 134|.macro restoreregs
130| push ebp; saveregs_ 135| add esp, CFRAME_SPACE
136| fs; pop dword [0]
137| pop edi // Short for esp += 4.
138| pop ebx; pop esi; pop edi; pop ebp
139|.endmacro
140|
141|.else
142|
143|.define CFRAME_SPACE, aword*7 // Delta for esp (see <--).
144|.macro saveregs_
145| push edi; push esi; push ebx
146| sub esp, CFRAME_SPACE
131|.endmacro 147|.endmacro
132|.macro restoreregs 148|.macro restoreregs
133| add esp, CFRAME_SPACE 149| add esp, CFRAME_SPACE
134| pop ebx; pop esi; pop edi; pop ebp 150| pop ebx; pop esi; pop edi; pop ebp
135|.endmacro 151|.endmacro
136| 152|
153|.endif
154|
155|.macro saveregs
156| push ebp; saveregs_
157|.endmacro
158|
159|.if WIN
160|.define SAVE_ERRF, aword [esp+aword*19] // vm_pcall/vm_cpcall only.
161|.define SAVE_NRES, aword [esp+aword*18]
162|.define SAVE_CFRAME, aword [esp+aword*17]
163|.define SAVE_L, aword [esp+aword*16]
164|//----- 16 byte aligned, ^^^ arguments from C caller
165|.define SAVE_RET, aword [esp+aword*15] //<-- esp entering interpreter.
166|.define SAVE_R4, aword [esp+aword*14]
167|.define SAVE_R3, aword [esp+aword*13]
168|.define SAVE_R2, aword [esp+aword*12]
169|//----- 16 byte aligned
170|.define SAVE_R1, aword [esp+aword*11]
171|.define SEH_FUNC, aword [esp+aword*10]
172|.define SEH_NEXT, aword [esp+aword*9] //<-- esp after register saves.
173|.define UNUSED2, aword [esp+aword*8]
174|//----- 16 byte aligned
175|.define UNUSED1, aword [esp+aword*7]
176|.define SAVE_PC, aword [esp+aword*6]
177|.define TMP2, aword [esp+aword*5]
178|.define TMP1, aword [esp+aword*4]
179|//----- 16 byte aligned
180|.define ARG4, aword [esp+aword*3]
181|.define ARG3, aword [esp+aword*2]
182|.define ARG2, aword [esp+aword*1]
183|.define ARG1, aword [esp] //<-- esp while in interpreter.
184|//----- 16 byte aligned, ^^^ arguments for C callee
185|.else
137|.define SAVE_ERRF, aword [esp+aword*15] // vm_pcall/vm_cpcall only. 186|.define SAVE_ERRF, aword [esp+aword*15] // vm_pcall/vm_cpcall only.
138|.define SAVE_NRES, aword [esp+aword*14] 187|.define SAVE_NRES, aword [esp+aword*14]
139|.define SAVE_CFRAME, aword [esp+aword*13] 188|.define SAVE_CFRAME, aword [esp+aword*13]
@@ -154,6 +203,7 @@
154|.define ARG2, aword [esp+aword*1] 203|.define ARG2, aword [esp+aword*1]
155|.define ARG1, aword [esp] //<-- esp while in interpreter. 204|.define ARG1, aword [esp] //<-- esp while in interpreter.
156|//----- 16 byte aligned, ^^^ arguments for C callee 205|//----- 16 byte aligned, ^^^ arguments for C callee
206|.endif
157| 207|
158|// FPARGx overlaps ARGx and ARG(x+1) on x86. 208|// FPARGx overlaps ARGx and ARG(x+1) on x86.
159|.define FPARG3, qword [esp+qword*1] 209|.define FPARG3, qword [esp+qword*1]
@@ -389,7 +439,6 @@
389| fpop 439| fpop
390|.endmacro 440|.endmacro
391| 441|
392|.macro fdup; fld st0; .endmacro
393|.macro fpop1; fstp st1; .endmacro 442|.macro fpop1; fstp st1; .endmacro
394| 443|
395|// Synthesize SSE FP constants. 444|// Synthesize SSE FP constants.
@@ -555,6 +604,10 @@ static void build_subroutines(BuildCtx *ctx)
555 |.else 604 |.else
556 | mov eax, FCARG2 // Error return status for vm_pcall. 605 | mov eax, FCARG2 // Error return status for vm_pcall.
557 | mov esp, FCARG1 606 | mov esp, FCARG1
607 |.if WIN
608 | lea FCARG1, SEH_NEXT
609 | fs; mov [0], FCARG1
610 |.endif
558 |.endif 611 |.endif
559 |->vm_unwind_c_eh: // Landing pad for external unwinder. 612 |->vm_unwind_c_eh: // Landing pad for external unwinder.
560 | mov L:RB, SAVE_L 613 | mov L:RB, SAVE_L
@@ -578,6 +631,10 @@ static void build_subroutines(BuildCtx *ctx)
578 |.else 631 |.else
579 | and FCARG1, CFRAME_RAWMASK 632 | and FCARG1, CFRAME_RAWMASK
580 | mov esp, FCARG1 633 | mov esp, FCARG1
634 |.if WIN
635 | lea FCARG1, SEH_NEXT
636 | fs; mov [0], FCARG1
637 |.endif
581 |.endif 638 |.endif
582 |->vm_unwind_ff_eh: // Landing pad for external unwinder. 639 |->vm_unwind_ff_eh: // Landing pad for external unwinder.
583 | mov L:RB, SAVE_L 640 | mov L:RB, SAVE_L
@@ -591,6 +648,19 @@ static void build_subroutines(BuildCtx *ctx)
591 | set_vmstate INTERP 648 | set_vmstate INTERP
592 | jmp ->vm_returnc // Increments RD/MULTRES and returns. 649 | jmp ->vm_returnc // Increments RD/MULTRES and returns.
593 | 650 |
651 |.if WIN and not X64
652 |->vm_rtlunwind@16: // Thin layer around RtlUnwind.
653 | // (void *cframe, void *excptrec, void *unwinder, int errcode)
654 | mov [esp], FCARG1 // Return value for RtlUnwind.
655 | push FCARG2 // Exception record for RtlUnwind.
656 | push 0 // Ignored by RtlUnwind.
657 | push dword [FCARG1+CFRAME_OFS_SEH]
658 | call extern RtlUnwind@16 // Violates ABI (clobbers too much).
659 | mov FCARG1, eax
660 | mov FCARG2, [esp+4] // errcode (for vm_unwind_c).
661 | ret // Jump to unwinder.
662 |.endif
663 |
594 |//----------------------------------------------------------------------- 664 |//-----------------------------------------------------------------------
595 |//-- Grow stack for calls ----------------------------------------------- 665 |//-- Grow stack for calls -----------------------------------------------
596 |//----------------------------------------------------------------------- 666 |//-----------------------------------------------------------------------
@@ -646,17 +716,18 @@ static void build_subroutines(BuildCtx *ctx)
646 | lea KBASEa, [esp+CFRAME_RESUME] 716 | lea KBASEa, [esp+CFRAME_RESUME]
647 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. 717 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
648 | add DISPATCH, GG_G2DISP 718 | add DISPATCH, GG_G2DISP
649 | mov L:RB->cframe, KBASEa
650 | mov SAVE_PC, RD // Any value outside of bytecode is ok. 719 | mov SAVE_PC, RD // Any value outside of bytecode is ok.
651 | mov SAVE_CFRAME, RDa 720 | mov SAVE_CFRAME, RDa
652 |.if X64 721 |.if X64
653 | mov SAVE_NRES, RD 722 | mov SAVE_NRES, RD
654 | mov SAVE_ERRF, RD 723 | mov SAVE_ERRF, RD
655 |.endif 724 |.endif
725 | mov L:RB->cframe, KBASEa
656 | cmp byte L:RB->status, RDL 726 | cmp byte L:RB->status, RDL
657 | je >3 // Initial resume (like a call). 727 | je >2 // Initial resume (like a call).
658 | 728 |
659 | // Resume after yield (like a return). 729 | // Resume after yield (like a return).
730 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
660 | set_vmstate INTERP 731 | set_vmstate INTERP
661 | mov byte L:RB->status, RDL 732 | mov byte L:RB->status, RDL
662 | mov BASE, L:RB->base 733 | mov BASE, L:RB->base
@@ -696,20 +767,19 @@ static void build_subroutines(BuildCtx *ctx)
696 | mov RA, INARG_BASE // Caveat: overlaps SAVE_CFRAME! 767 | mov RA, INARG_BASE // Caveat: overlaps SAVE_CFRAME!
697 |.endif 768 |.endif
698 | 769 |
770 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
699 | mov KBASEa, L:RB->cframe // Add our C frame to cframe chain. 771 | mov KBASEa, L:RB->cframe // Add our C frame to cframe chain.
700 | mov SAVE_CFRAME, KBASEa 772 | mov SAVE_CFRAME, KBASEa
701 | mov SAVE_PC, L:RB // Any value outside of bytecode is ok. 773 | mov SAVE_PC, L:RB // Any value outside of bytecode is ok.
774 | add DISPATCH, GG_G2DISP
702 |.if X64 775 |.if X64
703 | mov L:RB->cframe, rsp 776 | mov L:RB->cframe, rsp
704 |.else 777 |.else
705 | mov L:RB->cframe, esp 778 | mov L:RB->cframe, esp
706 |.endif 779 |.endif
707 | 780 |
708 |2: // Entry point for vm_cpcall below (RA = base, RB = L, PC = ftype). 781 |2: // Entry point for vm_resume/vm_cpcall (RA = base, RB = L, PC = ftype).
709 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table. 782 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
710 | add DISPATCH, GG_G2DISP
711 |
712 |3: // Entry point for vm_resume above (RA = base, RB = L, PC = ftype).
713 | set_vmstate INTERP 783 | set_vmstate INTERP
714 | mov BASE, L:RB->base // BASE = old base (used in vmeta_call). 784 | mov BASE, L:RB->base // BASE = old base (used in vmeta_call).
715 | add PC, RA 785 | add PC, RA
@@ -747,14 +817,17 @@ static void build_subroutines(BuildCtx *ctx)
747 | 817 |
748 | mov KBASE, L:RB->stack // Compute -savestack(L, L->top). 818 | mov KBASE, L:RB->stack // Compute -savestack(L, L->top).
749 | sub KBASE, L:RB->top 819 | sub KBASE, L:RB->top
820 | mov DISPATCH, L:RB->glref // Setup pointer to dispatch table.
750 | mov SAVE_ERRF, 0 // No error function. 821 | mov SAVE_ERRF, 0 // No error function.
751 | mov SAVE_NRES, KBASE // Neg. delta means cframe w/o frame. 822 | mov SAVE_NRES, KBASE // Neg. delta means cframe w/o frame.
823 | add DISPATCH, GG_G2DISP
752 | // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe). 824 | // Handler may change cframe_nres(L->cframe) or cframe_errfunc(L->cframe).
753 | 825 |
754 |.if X64 826 |.if X64
755 | mov KBASEa, L:RB->cframe // Add our C frame to cframe chain. 827 | mov KBASEa, L:RB->cframe // Add our C frame to cframe chain.
756 | mov SAVE_CFRAME, KBASEa 828 | mov SAVE_CFRAME, KBASEa
757 | mov L:RB->cframe, rsp 829 | mov L:RB->cframe, rsp
830 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
758 | 831 |
759 | call CARG4 // (lua_State *L, lua_CFunction func, void *ud) 832 | call CARG4 // (lua_State *L, lua_CFunction func, void *ud)
760 |.else 833 |.else
@@ -765,6 +838,7 @@ static void build_subroutines(BuildCtx *ctx)
765 | mov KBASE, L:RB->cframe // Add our C frame to cframe chain. 838 | mov KBASE, L:RB->cframe // Add our C frame to cframe chain.
766 | mov SAVE_CFRAME, KBASE 839 | mov SAVE_CFRAME, KBASE
767 | mov L:RB->cframe, esp 840 | mov L:RB->cframe, esp
841 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
768 | 842 |
769 | call BASE // (lua_State *L, lua_CFunction func, void *ud) 843 | call BASE // (lua_State *L, lua_CFunction func, void *ud)
770 |.endif 844 |.endif
@@ -872,13 +946,9 @@ static void build_subroutines(BuildCtx *ctx)
872 |.if DUALNUM 946 |.if DUALNUM
873 | mov TMP2, LJ_TISNUM 947 | mov TMP2, LJ_TISNUM
874 | mov TMP1, RC 948 | mov TMP1, RC
875 |.elif SSE 949 |.else
876 | cvtsi2sd xmm0, RC 950 | cvtsi2sd xmm0, RC
877 | movsd TMPQ, xmm0 951 | movsd TMPQ, xmm0
878 |.else
879 | mov ARG4, RC
880 | fild ARG4
881 | fstp TMPQ
882 |.endif 952 |.endif
883 | lea RCa, TMPQ // Store temp. TValue in TMPQ. 953 | lea RCa, TMPQ // Store temp. TValue in TMPQ.
884 | jmp >1 954 | jmp >1
@@ -932,6 +1002,19 @@ static void build_subroutines(BuildCtx *ctx)
932 | mov NARGS:RD, 2+1 // 2 args for func(t, k). 1002 | mov NARGS:RD, 2+1 // 2 args for func(t, k).
933 | jmp ->vm_call_dispatch_f 1003 | jmp ->vm_call_dispatch_f
934 | 1004 |
1005 |->vmeta_tgetr:
1006 | mov FCARG1, TAB:RB
1007 | mov RB, BASE // Save BASE.
1008 | mov FCARG2, RC // Caveat: FCARG2 == BASE
1009 | call extern lj_tab_getinth@8 // (GCtab *t, int32_t key)
1010 | // cTValue * or NULL returned in eax (RC).
1011 | movzx RA, PC_RA
1012 | mov BASE, RB // Restore BASE.
1013 | test RC, RC
1014 | jnz ->BC_TGETR_Z
1015 | mov dword [BASE+RA*8+4], LJ_TNIL
1016 | jmp ->BC_TGETR2_Z
1017 |
935 |//----------------------------------------------------------------------- 1018 |//-----------------------------------------------------------------------
936 | 1019 |
937 |->vmeta_tsets: 1020 |->vmeta_tsets:
@@ -951,13 +1034,9 @@ static void build_subroutines(BuildCtx *ctx)
951 |.if DUALNUM 1034 |.if DUALNUM
952 | mov TMP2, LJ_TISNUM 1035 | mov TMP2, LJ_TISNUM
953 | mov TMP1, RC 1036 | mov TMP1, RC
954 |.elif SSE 1037 |.else
955 | cvtsi2sd xmm0, RC 1038 | cvtsi2sd xmm0, RC
956 | movsd TMPQ, xmm0 1039 | movsd TMPQ, xmm0
957 |.else
958 | mov ARG4, RC
959 | fild ARG4
960 | fstp TMPQ
961 |.endif 1040 |.endif
962 | lea RCa, TMPQ // Store temp. TValue in TMPQ. 1041 | lea RCa, TMPQ // Store temp. TValue in TMPQ.
963 | jmp >1 1042 | jmp >1
@@ -1023,6 +1102,33 @@ static void build_subroutines(BuildCtx *ctx)
1023 | mov NARGS:RD, 3+1 // 3 args for func(t, k, v). 1102 | mov NARGS:RD, 3+1 // 3 args for func(t, k, v).
1024 | jmp ->vm_call_dispatch_f 1103 | jmp ->vm_call_dispatch_f
1025 | 1104 |
1105 |->vmeta_tsetr:
1106 |.if X64WIN
1107 | mov L:CARG1d, SAVE_L
1108 | mov CARG3d, RC
1109 | mov L:CARG1d->base, BASE
1110 | xchg CARG2d, TAB:RB // Caveat: CARG2d == BASE.
1111 |.elif X64
1112 | mov L:CARG1d, SAVE_L
1113 | mov CARG2d, TAB:RB
1114 | mov L:CARG1d->base, BASE
1115 | mov RB, BASE // Save BASE.
1116 | mov CARG3d, RC // Caveat: CARG3d == BASE.
1117 |.else
1118 | mov L:RA, SAVE_L
1119 | mov ARG2, TAB:RB
1120 | mov RB, BASE // Save BASE.
1121 | mov ARG3, RC
1122 | mov ARG1, L:RA
1123 | mov L:RA->base, BASE
1124 |.endif
1125 | mov SAVE_PC, PC
1126 | call extern lj_tab_setinth // (lua_State *L, GCtab *t, int32_t key)
1127 | // TValue * returned in eax (RC).
1128 | movzx RA, PC_RA
1129 | mov BASE, RB // Restore BASE.
1130 | jmp ->BC_TSETR_Z
1131 |
1026 |//-- Comparison metamethods --------------------------------------------- 1132 |//-- Comparison metamethods ---------------------------------------------
1027 | 1133 |
1028 |->vmeta_comp: 1134 |->vmeta_comp:
@@ -1117,6 +1223,26 @@ static void build_subroutines(BuildCtx *ctx)
1117 | jmp <3 1223 | jmp <3
1118 |.endif 1224 |.endif
1119 | 1225 |
1226 |->vmeta_istype:
1227 |.if X64
1228 | mov L:RB, SAVE_L
1229 | mov L:RB->base, BASE // Caveat: CARG2d/CARG3d may be BASE.
1230 | mov CARG2d, RA
1231 | movzx CARG3d, PC_RD
1232 | mov L:CARG1d, L:RB
1233 |.else
1234 | movzx RD, PC_RD
1235 | mov ARG2, RA
1236 | mov L:RB, SAVE_L
1237 | mov ARG3, RD
1238 | mov ARG1, L:RB
1239 | mov L:RB->base, BASE
1240 |.endif
1241 | mov SAVE_PC, PC
1242 | call extern lj_meta_istype // (lua_State *L, BCReg ra, BCReg tp)
1243 | mov BASE, L:RB->base
1244 | jmp <6
1245 |
1120 |//-- Arithmetic metamethods --------------------------------------------- 1246 |//-- Arithmetic metamethods ---------------------------------------------
1121 | 1247 |
1122 |->vmeta_arith_vno: 1248 |->vmeta_arith_vno:
@@ -1289,19 +1415,6 @@ static void build_subroutines(BuildCtx *ctx)
1289 | cmp NARGS:RD, 2+1; jb ->fff_fallback 1415 | cmp NARGS:RD, 2+1; jb ->fff_fallback
1290 |.endmacro 1416 |.endmacro
1291 | 1417 |
1292 |.macro .ffunc_n, name
1293 | .ffunc_1 name
1294 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
1295 | fld qword [BASE]
1296 |.endmacro
1297 |
1298 |.macro .ffunc_n, name, op
1299 | .ffunc_1 name
1300 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
1301 | op
1302 | fld qword [BASE]
1303 |.endmacro
1304 |
1305 |.macro .ffunc_nsse, name, op 1418 |.macro .ffunc_nsse, name, op
1306 | .ffunc_1 name 1419 | .ffunc_1 name
1307 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback 1420 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
@@ -1312,14 +1425,6 @@ static void build_subroutines(BuildCtx *ctx)
1312 | .ffunc_nsse name, movsd 1425 | .ffunc_nsse name, movsd
1313 |.endmacro 1426 |.endmacro
1314 | 1427 |
1315 |.macro .ffunc_nn, name
1316 | .ffunc_2 name
1317 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
1318 | cmp dword [BASE+12], LJ_TISNUM; jae ->fff_fallback
1319 | fld qword [BASE]
1320 | fld qword [BASE+8]
1321 |.endmacro
1322 |
1323 |.macro .ffunc_nnsse, name 1428 |.macro .ffunc_nnsse, name
1324 | .ffunc_2 name 1429 | .ffunc_2 name
1325 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback 1430 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
@@ -1525,11 +1630,7 @@ static void build_subroutines(BuildCtx *ctx)
1525 |.else 1630 |.else
1526 | jae ->fff_fallback 1631 | jae ->fff_fallback
1527 |.endif 1632 |.endif
1528 |.if SSE
1529 | movsd xmm0, qword [BASE]; jmp ->fff_resxmm0 1633 | movsd xmm0, qword [BASE]; jmp ->fff_resxmm0
1530 |.else
1531 | fld qword [BASE]; jmp ->fff_resn
1532 |.endif
1533 | 1634 |
1534 |.ffunc_1 tostring 1635 |.ffunc_1 tostring
1535 | // Only handles the string or number case inline. 1636 | // Only handles the string or number case inline.
@@ -1554,9 +1655,9 @@ static void build_subroutines(BuildCtx *ctx)
1554 |.endif 1655 |.endif
1555 | mov L:FCARG1, L:RB 1656 | mov L:FCARG1, L:RB
1556 |.if DUALNUM 1657 |.if DUALNUM
1557 | call extern lj_str_fromnumber@8 // (lua_State *L, cTValue *o) 1658 | call extern lj_strfmt_number@8 // (lua_State *L, cTValue *o)
1558 |.else 1659 |.else
1559 | call extern lj_str_fromnum@8 // (lua_State *L, lua_Number *np) 1660 | call extern lj_strfmt_num@8 // (lua_State *L, lua_Number *np)
1560 |.endif 1661 |.endif
1561 | // GCstr returned in eax (RD). 1662 | // GCstr returned in eax (RD).
1562 | mov BASE, L:RB->base 1663 | mov BASE, L:RB->base
@@ -1647,19 +1748,12 @@ static void build_subroutines(BuildCtx *ctx)
1647 | add RD, 1 1748 | add RD, 1
1648 | mov dword [BASE-4], LJ_TISNUM 1749 | mov dword [BASE-4], LJ_TISNUM
1649 | mov dword [BASE-8], RD 1750 | mov dword [BASE-8], RD
1650 |.elif SSE 1751 |.else
1651 | movsd xmm0, qword [BASE+8] 1752 | movsd xmm0, qword [BASE+8]
1652 | sseconst_1 xmm1, RBa 1753 | sseconst_1 xmm1, RBa
1653 | addsd xmm0, xmm1 1754 | addsd xmm0, xmm1
1654 | cvtsd2si RD, xmm0 1755 | cvttsd2si RD, xmm0
1655 | movsd qword [BASE-8], xmm0 1756 | movsd qword [BASE-8], xmm0
1656 |.else
1657 | fld qword [BASE+8]
1658 | fld1
1659 | faddp st1
1660 | fist ARG1
1661 | fstp qword [BASE-8]
1662 | mov RD, ARG1
1663 |.endif 1757 |.endif
1664 | mov TAB:RB, [BASE] 1758 | mov TAB:RB, [BASE]
1665 | cmp RD, TAB:RB->asize; jae >2 // Not in array part? 1759 | cmp RD, TAB:RB->asize; jae >2 // Not in array part?
@@ -1706,12 +1800,9 @@ static void build_subroutines(BuildCtx *ctx)
1706 |.if DUALNUM 1800 |.if DUALNUM
1707 | mov dword [BASE+12], LJ_TISNUM 1801 | mov dword [BASE+12], LJ_TISNUM
1708 | mov dword [BASE+8], 0 1802 | mov dword [BASE+8], 0
1709 |.elif SSE 1803 |.else
1710 | xorps xmm0, xmm0 1804 | xorps xmm0, xmm0
1711 | movsd qword [BASE+8], xmm0 1805 | movsd qword [BASE+8], xmm0
1712 |.else
1713 | fldz
1714 | fstp qword [BASE+8]
1715 |.endif 1806 |.endif
1716 | mov RD, 1+3 1807 | mov RD, 1+3
1717 | jmp ->fff_res 1808 | jmp ->fff_res
@@ -1818,7 +1909,6 @@ static void build_subroutines(BuildCtx *ctx)
1818 | mov ARG3, RA 1909 | mov ARG3, RA
1819 |.endif 1910 |.endif
1820 | call ->vm_resume // (lua_State *L, TValue *base, 0, 0) 1911 | call ->vm_resume // (lua_State *L, TValue *base, 0, 0)
1821 | set_vmstate INTERP
1822 | 1912 |
1823 | mov L:RB, SAVE_L 1913 | mov L:RB, SAVE_L
1824 |.if X64 1914 |.if X64
@@ -1827,6 +1917,9 @@ static void build_subroutines(BuildCtx *ctx)
1827 | mov L:PC, ARG1 // The callee doesn't modify SAVE_L. 1917 | mov L:PC, ARG1 // The callee doesn't modify SAVE_L.
1828 |.endif 1918 |.endif
1829 | mov BASE, L:RB->base 1919 | mov BASE, L:RB->base
1920 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
1921 | set_vmstate INTERP
1922 |
1830 | cmp eax, LUA_YIELD 1923 | cmp eax, LUA_YIELD
1831 | ja >8 1924 | ja >8
1832 |4: 1925 |4:
@@ -1941,12 +2034,10 @@ static void build_subroutines(BuildCtx *ctx)
1941 |->fff_resi: // Dummy. 2034 |->fff_resi: // Dummy.
1942 |.endif 2035 |.endif
1943 | 2036 |
1944 |.if SSE
1945 |->fff_resn: 2037 |->fff_resn:
1946 | mov PC, [BASE-4] 2038 | mov PC, [BASE-4]
1947 | fstp qword [BASE-8] 2039 | fstp qword [BASE-8]
1948 | jmp ->fff_res1 2040 | jmp ->fff_res1
1949 |.endif
1950 | 2041 |
1951 | .ffunc_1 math_abs 2042 | .ffunc_1 math_abs
1952 |.if DUALNUM 2043 |.if DUALNUM
@@ -1970,8 +2061,6 @@ static void build_subroutines(BuildCtx *ctx)
1970 |.else 2061 |.else
1971 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback 2062 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
1972 |.endif 2063 |.endif
1973 |
1974 |.if SSE
1975 | movsd xmm0, qword [BASE] 2064 | movsd xmm0, qword [BASE]
1976 | sseconst_abs xmm1, RDa 2065 | sseconst_abs xmm1, RDa
1977 | andps xmm0, xmm1 2066 | andps xmm0, xmm1
@@ -1979,15 +2068,6 @@ static void build_subroutines(BuildCtx *ctx)
1979 | mov PC, [BASE-4] 2068 | mov PC, [BASE-4]
1980 | movsd qword [BASE-8], xmm0 2069 | movsd qword [BASE-8], xmm0
1981 | // fallthrough 2070 | // fallthrough
1982 |.else
1983 | fld qword [BASE]
1984 | fabs
1985 | // fallthrough
1986 |->fff_resxmm0: // Dummy.
1987 |->fff_resn:
1988 | mov PC, [BASE-4]
1989 | fstp qword [BASE-8]
1990 |.endif
1991 | 2071 |
1992 |->fff_res1: 2072 |->fff_res1:
1993 | mov RD, 1+1 2073 | mov RD, 1+1
@@ -2014,6 +2094,12 @@ static void build_subroutines(BuildCtx *ctx)
2014 | mov RAa, -8 // Results start at BASE+RA = BASE-8. 2094 | mov RAa, -8 // Results start at BASE+RA = BASE-8.
2015 | jmp ->vm_return 2095 | jmp ->vm_return
2016 | 2096 |
2097 |.if X64
2098 |.define fff_resfp, fff_resxmm0
2099 |.else
2100 |.define fff_resfp, fff_resn
2101 |.endif
2102 |
2017 |.macro math_round, func 2103 |.macro math_round, func
2018 | .ffunc math_ .. func 2104 | .ffunc math_ .. func
2019 |.if DUALNUM 2105 |.if DUALNUM
@@ -2024,107 +2110,75 @@ static void build_subroutines(BuildCtx *ctx)
2024 |.else 2110 |.else
2025 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback 2111 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
2026 |.endif 2112 |.endif
2027 |.if SSE
2028 | movsd xmm0, qword [BASE] 2113 | movsd xmm0, qword [BASE]
2029 | call ->vm_ .. func 2114 | call ->vm_ .. func .. _sse
2030 | .if DUALNUM 2115 |.if DUALNUM
2031 | cvtsd2si RB, xmm0 2116 | cvttsd2si RB, xmm0
2032 | cmp RB, 0x80000000 2117 | cmp RB, 0x80000000
2033 | jne ->fff_resi 2118 | jne ->fff_resi
2034 | cvtsi2sd xmm1, RB 2119 | cvtsi2sd xmm1, RB
2035 | ucomisd xmm0, xmm1 2120 | ucomisd xmm0, xmm1
2036 | jp ->fff_resxmm0 2121 | jp ->fff_resxmm0
2037 | je ->fff_resi 2122 | je ->fff_resi
2038 | .endif
2039 | jmp ->fff_resxmm0
2040 |.else
2041 | fld qword [BASE]
2042 | call ->vm_ .. func
2043 | .if DUALNUM
2044 | fist ARG1
2045 | mov RB, ARG1
2046 | cmp RB, 0x80000000; jne >2
2047 | fdup
2048 | fild ARG1
2049 | fcomparepp
2050 | jp ->fff_resn
2051 | jne ->fff_resn
2052 |2:
2053 | fpop
2054 | jmp ->fff_resi
2055 | .else
2056 | jmp ->fff_resn
2057 | .endif
2058 |.endif 2123 |.endif
2124 | jmp ->fff_resxmm0
2059 |.endmacro 2125 |.endmacro
2060 | 2126 |
2061 | math_round floor 2127 | math_round floor
2062 | math_round ceil 2128 | math_round ceil
2063 | 2129 |
2064 |.if SSE
2065 |.ffunc_nsse math_sqrt, sqrtsd; jmp ->fff_resxmm0 2130 |.ffunc_nsse math_sqrt, sqrtsd; jmp ->fff_resxmm0
2066 |.else
2067 |.ffunc_n math_sqrt; fsqrt; jmp ->fff_resn
2068 |.endif
2069 | 2131 |
2070 |.ffunc math_log 2132 |.ffunc math_log
2071 | cmp NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument. 2133 | cmp NARGS:RD, 1+1; jne ->fff_fallback // Exactly one argument.
2072 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback 2134 | cmp dword [BASE+4], LJ_TISNUM; jae ->fff_fallback
2073 | fldln2; fld qword [BASE]; fyl2x; jmp ->fff_resn 2135 | movsd xmm0, qword [BASE]
2074 | 2136 |.if not X64
2075 |.ffunc_n math_log10, fldlg2; fyl2x; jmp ->fff_resn 2137 | movsd FPARG1, xmm0
2076 |.ffunc_n math_exp; call ->vm_exp_x87; jmp ->fff_resn 2138 |.endif
2077 | 2139 | mov RB, BASE
2078 |.ffunc_n math_sin; fsin; jmp ->fff_resn 2140 | call extern log
2079 |.ffunc_n math_cos; fcos; jmp ->fff_resn 2141 | mov BASE, RB
2080 |.ffunc_n math_tan; fptan; fpop; jmp ->fff_resn 2142 | jmp ->fff_resfp
2081 |
2082 |.ffunc_n math_asin
2083 | fdup; fmul st0; fld1; fsubrp st1; fsqrt; fpatan
2084 | jmp ->fff_resn
2085 |.ffunc_n math_acos
2086 | fdup; fmul st0; fld1; fsubrp st1; fsqrt; fxch; fpatan
2087 | jmp ->fff_resn
2088 |.ffunc_n math_atan; fld1; fpatan; jmp ->fff_resn
2089 | 2143 |
2090 |.macro math_extern, func 2144 |.macro math_extern, func
2091 |.if SSE
2092 | .ffunc_nsse math_ .. func 2145 | .ffunc_nsse math_ .. func
2093 | .if not X64 2146 |.if not X64
2094 | movsd FPARG1, xmm0 2147 | movsd FPARG1, xmm0
2095 | .endif
2096 |.else
2097 | .ffunc_n math_ .. func
2098 | fstp FPARG1
2099 |.endif 2148 |.endif
2100 | mov RB, BASE 2149 | mov RB, BASE
2101 | call extern lj_vm_ .. func 2150 | call extern func
2102 | mov BASE, RB 2151 | mov BASE, RB
2103 | .if X64 2152 | jmp ->fff_resfp
2104 | jmp ->fff_resxmm0 2153 |.endmacro
2105 | .else 2154 |
2106 | jmp ->fff_resn 2155 |.macro math_extern2, func
2107 | .endif 2156 | .ffunc_nnsse math_ .. func
2157 |.if not X64
2158 | movsd FPARG1, xmm0
2159 | movsd FPARG3, xmm1
2160 |.endif
2161 | mov RB, BASE
2162 | call extern func
2163 | mov BASE, RB
2164 | jmp ->fff_resfp
2108 |.endmacro 2165 |.endmacro
2109 | 2166 |
2167 | math_extern log10
2168 | math_extern exp
2169 | math_extern sin
2170 | math_extern cos
2171 | math_extern tan
2172 | math_extern asin
2173 | math_extern acos
2174 | math_extern atan
2110 | math_extern sinh 2175 | math_extern sinh
2111 | math_extern cosh 2176 | math_extern cosh
2112 | math_extern tanh 2177 | math_extern tanh
2178 | math_extern2 pow
2179 | math_extern2 atan2
2180 | math_extern2 fmod
2113 | 2181 |
2114 |->ff_math_deg:
2115 |.if SSE
2116 |.ffunc_nsse math_rad
2117 | mov CFUNC:RB, [BASE-8]
2118 | mulsd xmm0, qword CFUNC:RB->upvalue[0]
2119 | jmp ->fff_resxmm0
2120 |.else
2121 |.ffunc_n math_rad
2122 | mov CFUNC:RB, [BASE-8]
2123 | fmul qword CFUNC:RB->upvalue[0]
2124 | jmp ->fff_resn
2125 |.endif
2126 |
2127 |.ffunc_nn math_atan2; fpatan; jmp ->fff_resn
2128 |.ffunc_nnr math_ldexp; fscale; fpop1; jmp ->fff_resn 2182 |.ffunc_nnr math_ldexp; fscale; fpop1; jmp ->fff_resn
2129 | 2183 |
2130 |.ffunc_1 math_frexp 2184 |.ffunc_1 math_frexp
@@ -2139,65 +2193,34 @@ static void build_subroutines(BuildCtx *ctx)
2139 | cmp RB, 0x00200000; jb >4 2193 | cmp RB, 0x00200000; jb >4
2140 |1: 2194 |1:
2141 | shr RB, 21; sub RB, RC // Extract and unbias exponent. 2195 | shr RB, 21; sub RB, RC // Extract and unbias exponent.
2142 |.if SSE
2143 | cvtsi2sd xmm0, RB 2196 | cvtsi2sd xmm0, RB
2144 |.else
2145 | mov TMP1, RB; fild TMP1
2146 |.endif
2147 | mov RB, [BASE-4] 2197 | mov RB, [BASE-4]
2148 | and RB, 0x800fffff // Mask off exponent. 2198 | and RB, 0x800fffff // Mask off exponent.
2149 | or RB, 0x3fe00000 // Put mantissa in range [0.5,1) or 0. 2199 | or RB, 0x3fe00000 // Put mantissa in range [0.5,1) or 0.
2150 | mov [BASE-4], RB 2200 | mov [BASE-4], RB
2151 |2: 2201 |2:
2152 |.if SSE
2153 | movsd qword [BASE], xmm0 2202 | movsd qword [BASE], xmm0
2154 |.else
2155 | fstp qword [BASE]
2156 |.endif
2157 | mov RD, 1+2 2203 | mov RD, 1+2
2158 | jmp ->fff_res 2204 | jmp ->fff_res
2159 |3: // Return +-0, +-Inf, NaN unmodified and an exponent of 0. 2205 |3: // Return +-0, +-Inf, NaN unmodified and an exponent of 0.
2160 |.if SSE
2161 | xorps xmm0, xmm0; jmp <2 2206 | xorps xmm0, xmm0; jmp <2
2162 |.else
2163 | fldz; jmp <2
2164 |.endif
2165 |4: // Handle denormals by multiplying with 2^54 and adjusting the bias. 2207 |4: // Handle denormals by multiplying with 2^54 and adjusting the bias.
2166 |.if SSE
2167 | movsd xmm0, qword [BASE] 2208 | movsd xmm0, qword [BASE]
2168 | sseconst_hi xmm1, RBa, 43500000 // 2^54. 2209 | sseconst_hi xmm1, RBa, 43500000 // 2^54.
2169 | mulsd xmm0, xmm1 2210 | mulsd xmm0, xmm1
2170 | movsd qword [BASE-8], xmm0 2211 | movsd qword [BASE-8], xmm0
2171 |.else
2172 | fld qword [BASE]
2173 | mov TMP1, 0x5a800000; fmul TMP1 // x = x*2^54
2174 | fstp qword [BASE-8]
2175 |.endif
2176 | mov RB, [BASE-4]; mov RC, 1076; shl RB, 1; jmp <1 2212 | mov RB, [BASE-4]; mov RC, 1076; shl RB, 1; jmp <1
2177 | 2213 |
2178 |.if SSE
2179 |.ffunc_nsse math_modf 2214 |.ffunc_nsse math_modf
2180 |.else
2181 |.ffunc_n math_modf
2182 |.endif
2183 | mov RB, [BASE+4] 2215 | mov RB, [BASE+4]
2184 | mov PC, [BASE-4] 2216 | mov PC, [BASE-4]
2185 | shl RB, 1; cmp RB, 0xffe00000; je >4 // +-Inf? 2217 | shl RB, 1; cmp RB, 0xffe00000; je >4 // +-Inf?
2186 |.if SSE
2187 | movaps xmm4, xmm0 2218 | movaps xmm4, xmm0
2188 | call ->vm_trunc 2219 | call ->vm_trunc_sse
2189 | subsd xmm4, xmm0 2220 | subsd xmm4, xmm0
2190 |1: 2221 |1:
2191 | movsd qword [BASE-8], xmm0 2222 | movsd qword [BASE-8], xmm0
2192 | movsd qword [BASE], xmm4 2223 | movsd qword [BASE], xmm4
2193 |.else
2194 | fdup
2195 | call ->vm_trunc
2196 | fsub st1, st0
2197 |1:
2198 | fstp qword [BASE-8]
2199 | fstp qword [BASE]
2200 |.endif
2201 | mov RC, [BASE-4]; mov RB, [BASE+4] 2224 | mov RC, [BASE-4]; mov RB, [BASE+4]
2202 | xor RC, RB; js >3 // Need to adjust sign? 2225 | xor RC, RB; js >3 // Need to adjust sign?
2203 |2: 2226 |2:
@@ -2207,24 +2230,9 @@ static void build_subroutines(BuildCtx *ctx)
2207 | xor RB, 0x80000000; mov [BASE+4], RB // Flip sign of fraction. 2230 | xor RB, 0x80000000; mov [BASE+4], RB // Flip sign of fraction.
2208 | jmp <2 2231 | jmp <2
2209 |4: 2232 |4:
2210 |.if SSE
2211 | xorps xmm4, xmm4; jmp <1 // Return +-Inf and +-0. 2233 | xorps xmm4, xmm4; jmp <1 // Return +-Inf and +-0.
2212 |.else
2213 | fldz; fxch; jmp <1 // Return +-Inf and +-0.
2214 |.endif
2215 |
2216 |.ffunc_nnr math_fmod
2217 |1: ; fprem; fnstsw ax; and ax, 0x400; jnz <1
2218 | fpop1
2219 | jmp ->fff_resn
2220 | 2234 |
2221 |.if SSE 2235 |.macro math_minmax, name, cmovop, sseop
2222 |.ffunc_nnsse math_pow; call ->vm_pow; jmp ->fff_resxmm0
2223 |.else
2224 |.ffunc_nn math_pow; call ->vm_pow; jmp ->fff_resn
2225 |.endif
2226 |
2227 |.macro math_minmax, name, cmovop, fcmovop, sseop
2228 | .ffunc name 2236 | .ffunc name
2229 | mov RA, 2 2237 | mov RA, 2
2230 | cmp dword [BASE+4], LJ_TISNUM 2238 | cmp dword [BASE+4], LJ_TISNUM
@@ -2241,12 +2249,7 @@ static void build_subroutines(BuildCtx *ctx)
2241 |3: 2249 |3:
2242 | ja ->fff_fallback 2250 | ja ->fff_fallback
2243 | // Convert intermediate result to number and continue below. 2251 | // Convert intermediate result to number and continue below.
2244 |.if SSE
2245 | cvtsi2sd xmm0, RB 2252 | cvtsi2sd xmm0, RB
2246 |.else
2247 | mov TMP1, RB
2248 | fild TMP1
2249 |.endif
2250 | jmp >6 2253 | jmp >6
2251 |4: 2254 |4:
2252 | ja ->fff_fallback 2255 | ja ->fff_fallback
@@ -2254,7 +2257,6 @@ static void build_subroutines(BuildCtx *ctx)
2254 | jae ->fff_fallback 2257 | jae ->fff_fallback
2255 |.endif 2258 |.endif
2256 | 2259 |
2257 |.if SSE
2258 | movsd xmm0, qword [BASE] 2260 | movsd xmm0, qword [BASE]
2259 |5: // Handle numbers or integers. 2261 |5: // Handle numbers or integers.
2260 | cmp RA, RD; jae ->fff_resxmm0 2262 | cmp RA, RD; jae ->fff_resxmm0
@@ -2273,48 +2275,13 @@ static void build_subroutines(BuildCtx *ctx)
2273 | sseop xmm0, xmm1 2275 | sseop xmm0, xmm1
2274 | add RA, 1 2276 | add RA, 1
2275 | jmp <5 2277 | jmp <5
2276 |.else
2277 | fld qword [BASE]
2278 |5: // Handle numbers or integers.
2279 | cmp RA, RD; jae ->fff_resn
2280 | cmp dword [BASE+RA*8-4], LJ_TISNUM
2281 |.if DUALNUM
2282 | jb >6
2283 | ja >9
2284 | fild dword [BASE+RA*8-8]
2285 | jmp >7
2286 |.else
2287 | jae >9
2288 |.endif
2289 |6:
2290 | fld qword [BASE+RA*8-8]
2291 |7:
2292 | fucomi st1; fcmovop st1; fpop1
2293 | add RA, 1
2294 | jmp <5
2295 |.endif
2296 |.endmacro 2278 |.endmacro
2297 | 2279 |
2298 | math_minmax math_min, cmovg, fcmovnbe, minsd 2280 | math_minmax math_min, cmovg, minsd
2299 | math_minmax math_max, cmovl, fcmovbe, maxsd 2281 | math_minmax math_max, cmovl, maxsd
2300 |.if not SSE
2301 |9:
2302 | fpop; jmp ->fff_fallback
2303 |.endif
2304 | 2282 |
2305 |//-- String library ----------------------------------------------------- 2283 |//-- String library -----------------------------------------------------
2306 | 2284 |
2307 |.ffunc_1 string_len
2308 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
2309 | mov STR:RB, [BASE]
2310 |.if DUALNUM
2311 | mov RB, dword STR:RB->len; jmp ->fff_resi
2312 |.elif SSE
2313 | cvtsi2sd xmm0, dword STR:RB->len; jmp ->fff_resxmm0
2314 |.else
2315 | fild dword STR:RB->len; jmp ->fff_resn
2316 |.endif
2317 |
2318 |.ffunc string_byte // Only handle the 1-arg case here. 2285 |.ffunc string_byte // Only handle the 1-arg case here.
2319 | cmp NARGS:RD, 1+1; jne ->fff_fallback 2286 | cmp NARGS:RD, 1+1; jne ->fff_fallback
2320 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback 2287 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
@@ -2325,10 +2292,8 @@ static void build_subroutines(BuildCtx *ctx)
2325 | movzx RB, byte STR:RB[1] 2292 | movzx RB, byte STR:RB[1]
2326 |.if DUALNUM 2293 |.if DUALNUM
2327 | jmp ->fff_resi 2294 | jmp ->fff_resi
2328 |.elif SSE
2329 | cvtsi2sd xmm0, RB; jmp ->fff_resxmm0
2330 |.else 2295 |.else
2331 | mov TMP1, RB; fild TMP1; jmp ->fff_resn 2296 | cvtsi2sd xmm0, RB; jmp ->fff_resxmm0
2332 |.endif 2297 |.endif
2333 | 2298 |
2334 |.ffunc string_char // Only handle the 1-arg case here. 2299 |.ffunc string_char // Only handle the 1-arg case here.
@@ -2340,16 +2305,11 @@ static void build_subroutines(BuildCtx *ctx)
2340 | mov RB, dword [BASE] 2305 | mov RB, dword [BASE]
2341 | cmp RB, 255; ja ->fff_fallback 2306 | cmp RB, 255; ja ->fff_fallback
2342 | mov TMP2, RB 2307 | mov TMP2, RB
2343 |.elif SSE 2308 |.else
2344 | jae ->fff_fallback 2309 | jae ->fff_fallback
2345 | cvttsd2si RB, qword [BASE] 2310 | cvttsd2si RB, qword [BASE]
2346 | cmp RB, 255; ja ->fff_fallback 2311 | cmp RB, 255; ja ->fff_fallback
2347 | mov TMP2, RB 2312 | mov TMP2, RB
2348 |.else
2349 | jae ->fff_fallback
2350 | fld qword [BASE]
2351 | fistp TMP2
2352 | cmp TMP2, 255; ja ->fff_fallback
2353 |.endif 2313 |.endif
2354 |.if X64 2314 |.if X64
2355 | mov TMP3, 1 2315 | mov TMP3, 1
@@ -2370,6 +2330,7 @@ static void build_subroutines(BuildCtx *ctx)
2370 |.endif 2330 |.endif
2371 | mov SAVE_PC, PC 2331 | mov SAVE_PC, PC
2372 | call extern lj_str_new // (lua_State *L, char *str, size_t l) 2332 | call extern lj_str_new // (lua_State *L, char *str, size_t l)
2333 |->fff_resstr:
2373 | // GCstr * returned in eax (RD). 2334 | // GCstr * returned in eax (RD).
2374 | mov BASE, L:RB->base 2335 | mov BASE, L:RB->base
2375 | mov PC, [BASE-4] 2336 | mov PC, [BASE-4]
@@ -2387,14 +2348,10 @@ static void build_subroutines(BuildCtx *ctx)
2387 | jne ->fff_fallback 2348 | jne ->fff_fallback
2388 | mov RB, dword [BASE+16] 2349 | mov RB, dword [BASE+16]
2389 | mov TMP2, RB 2350 | mov TMP2, RB
2390 |.elif SSE 2351 |.else
2391 | jae ->fff_fallback 2352 | jae ->fff_fallback
2392 | cvttsd2si RB, qword [BASE+16] 2353 | cvttsd2si RB, qword [BASE+16]
2393 | mov TMP2, RB 2354 | mov TMP2, RB
2394 |.else
2395 | jae ->fff_fallback
2396 | fld qword [BASE+16]
2397 | fistp TMP2
2398 |.endif 2355 |.endif
2399 |1: 2356 |1:
2400 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback 2357 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
@@ -2409,12 +2366,8 @@ static void build_subroutines(BuildCtx *ctx)
2409 | mov RB, STR:RB->len 2366 | mov RB, STR:RB->len
2410 |.if DUALNUM 2367 |.if DUALNUM
2411 | mov RA, dword [BASE+8] 2368 | mov RA, dword [BASE+8]
2412 |.elif SSE
2413 | cvttsd2si RA, qword [BASE+8]
2414 |.else 2369 |.else
2415 | fld qword [BASE+8] 2370 | cvttsd2si RA, qword [BASE+8]
2416 | fistp ARG3
2417 | mov RA, ARG3
2418 |.endif 2371 |.endif
2419 | mov RC, TMP2 2372 | mov RC, TMP2
2420 | cmp RB, RC // len < end? (unsigned compare) 2373 | cmp RB, RC // len < end? (unsigned compare)
@@ -2458,136 +2411,34 @@ static void build_subroutines(BuildCtx *ctx)
2458 | xor RC, RC // Zero length. Any ptr in RB is ok. 2411 | xor RC, RC // Zero length. Any ptr in RB is ok.
2459 | jmp <4 2412 | jmp <4
2460 | 2413 |
2461 |.ffunc string_rep // Only handle the 1-char case inline. 2414 |.macro ffstring_op, name
2462 | ffgccheck 2415 | .ffunc_1 string_ .. name
2463 | cmp NARGS:RD, 2+1; jne ->fff_fallback // Exactly 2 arguments.
2464 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
2465 | cmp dword [BASE+12], LJ_TISNUM
2466 | mov STR:RB, [BASE]
2467 |.if DUALNUM
2468 | jne ->fff_fallback
2469 | mov RC, dword [BASE+8]
2470 |.elif SSE
2471 | jae ->fff_fallback
2472 | cvttsd2si RC, qword [BASE+8]
2473 |.else
2474 | jae ->fff_fallback
2475 | fld qword [BASE+8]
2476 | fistp TMP2
2477 | mov RC, TMP2
2478 |.endif
2479 | test RC, RC
2480 | jle ->fff_emptystr // Count <= 0? (or non-int)
2481 | cmp dword STR:RB->len, 1
2482 | jb ->fff_emptystr // Zero length string?
2483 | jne ->fff_fallback_2 // Fallback for > 1-char strings.
2484 | cmp [DISPATCH+DISPATCH_GL(tmpbuf.sz)], RC; jb ->fff_fallback_2
2485 | movzx RA, byte STR:RB[1]
2486 | mov RB, [DISPATCH+DISPATCH_GL(tmpbuf.buf)]
2487 |.if X64
2488 | mov TMP3, RC
2489 |.else
2490 | mov ARG3, RC
2491 |.endif
2492 |1: // Fill buffer with char. Yes, this is suboptimal code (do you care?).
2493 | mov [RB], RAL
2494 | add RB, 1
2495 | sub RC, 1
2496 | jnz <1
2497 | mov RD, [DISPATCH+DISPATCH_GL(tmpbuf.buf)]
2498 | jmp ->fff_newstr
2499 |
2500 |.ffunc_1 string_reverse
2501 | ffgccheck 2416 | ffgccheck
2502 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback 2417 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
2503 | mov STR:RB, [BASE] 2418 | mov L:RB, SAVE_L
2504 | mov RC, STR:RB->len 2419 | lea SBUF:FCARG1, [DISPATCH+DISPATCH_GL(tmpbuf)]
2505 | test RC, RC 2420 | mov L:RB->base, BASE
2506 | jz ->fff_emptystr // Zero length string? 2421 | mov STR:FCARG2, [BASE] // Caveat: FCARG2 == BASE
2507 | cmp [DISPATCH+DISPATCH_GL(tmpbuf.sz)], RC; jb ->fff_fallback_1 2422 | mov RC, SBUF:FCARG1->b
2508 | add RB, #STR 2423 | mov SBUF:FCARG1->L, L:RB
2509 | mov TMP2, PC // Need another temp register. 2424 | mov SBUF:FCARG1->p, RC
2510 |.if X64 2425 | mov SAVE_PC, PC
2511 | mov TMP3, RC 2426 | call extern lj_buf_putstr_ .. name .. @8
2512 |.else 2427 | mov FCARG1, eax
2513 | mov ARG3, RC 2428 | call extern lj_buf_tostr@4
2514 |.endif 2429 | jmp ->fff_resstr
2515 | mov PC, [DISPATCH+DISPATCH_GL(tmpbuf.buf)]
2516 |1:
2517 | movzx RA, byte [RB]
2518 | add RB, 1
2519 | sub RC, 1
2520 | mov [PC+RC], RAL
2521 | jnz <1
2522 | mov RD, PC
2523 | mov PC, TMP2
2524 | jmp ->fff_newstr
2525 |
2526 |.macro ffstring_case, name, lo, hi
2527 | .ffunc_1 name
2528 | ffgccheck
2529 | cmp dword [BASE+4], LJ_TSTR; jne ->fff_fallback
2530 | mov STR:RB, [BASE]
2531 | mov RC, STR:RB->len
2532 | cmp [DISPATCH+DISPATCH_GL(tmpbuf.sz)], RC; jb ->fff_fallback_1
2533 | add RB, #STR
2534 | mov TMP2, PC // Need another temp register.
2535 |.if X64
2536 | mov TMP3, RC
2537 |.else
2538 | mov ARG3, RC
2539 |.endif
2540 | mov PC, [DISPATCH+DISPATCH_GL(tmpbuf.buf)]
2541 | jmp >3
2542 |1: // ASCII case conversion. Yes, this is suboptimal code (do you care?).
2543 | movzx RA, byte [RB+RC]
2544 | cmp RA, lo
2545 | jb >2
2546 | cmp RA, hi
2547 | ja >2
2548 | xor RA, 0x20
2549 |2:
2550 | mov [PC+RC], RAL
2551 |3:
2552 | sub RC, 1
2553 | jns <1
2554 | mov RD, PC
2555 | mov PC, TMP2
2556 | jmp ->fff_newstr
2557 |.endmacro 2430 |.endmacro
2558 | 2431 |
2559 |ffstring_case string_lower, 0x41, 0x5a 2432 |ffstring_op reverse
2560 |ffstring_case string_upper, 0x61, 0x7a 2433 |ffstring_op lower
2561 | 2434 |ffstring_op upper
2562 |//-- Table library ------------------------------------------------------
2563 |
2564 |.ffunc_1 table_getn
2565 | cmp dword [BASE+4], LJ_TTAB; jne ->fff_fallback
2566 | mov RB, BASE // Save BASE.
2567 | mov TAB:FCARG1, [BASE]
2568 | call extern lj_tab_len@4 // LJ_FASTCALL (GCtab *t)
2569 | // Length of table returned in eax (RD).
2570 | mov BASE, RB // Restore BASE.
2571 |.if DUALNUM
2572 | mov RB, RD; jmp ->fff_resi
2573 |.elif SSE
2574 | cvtsi2sd xmm0, RD; jmp ->fff_resxmm0
2575 |.else
2576 | mov ARG1, RD; fild ARG1; jmp ->fff_resn
2577 |.endif
2578 | 2435 |
2579 |//-- Bit library -------------------------------------------------------- 2436 |//-- Bit library --------------------------------------------------------
2580 | 2437 |
2581 |.define TOBIT_BIAS, 0x59c00000 // 2^52 + 2^51 (float, not double!).
2582 |
2583 |.macro .ffunc_bit, name, kind, fdef 2438 |.macro .ffunc_bit, name, kind, fdef
2584 | fdef name 2439 | fdef name
2585 |.if kind == 2 2440 |.if kind == 2
2586 |.if SSE
2587 | sseconst_tobit xmm1, RBa 2441 | sseconst_tobit xmm1, RBa
2588 |.else
2589 | mov TMP1, TOBIT_BIAS
2590 |.endif
2591 |.endif 2442 |.endif
2592 | cmp dword [BASE+4], LJ_TISNUM 2443 | cmp dword [BASE+4], LJ_TISNUM
2593 |.if DUALNUM 2444 |.if DUALNUM
@@ -2603,24 +2454,12 @@ static void build_subroutines(BuildCtx *ctx)
2603 |.else 2454 |.else
2604 | jae ->fff_fallback 2455 | jae ->fff_fallback
2605 |.endif 2456 |.endif
2606 |.if SSE
2607 | movsd xmm0, qword [BASE] 2457 | movsd xmm0, qword [BASE]
2608 |.if kind < 2 2458 |.if kind < 2
2609 | sseconst_tobit xmm1, RBa 2459 | sseconst_tobit xmm1, RBa
2610 |.endif 2460 |.endif
2611 | addsd xmm0, xmm1 2461 | addsd xmm0, xmm1
2612 | movd RB, xmm0 2462 | movd RB, xmm0
2613 |.else
2614 | fld qword [BASE]
2615 |.if kind < 2
2616 | mov TMP1, TOBIT_BIAS
2617 |.endif
2618 | fadd TMP1
2619 | fstp FPARG1
2620 |.if kind > 0
2621 | mov RB, ARG1
2622 |.endif
2623 |.endif
2624 |2: 2463 |2:
2625 |.endmacro 2464 |.endmacro
2626 | 2465 |
@@ -2629,15 +2468,7 @@ static void build_subroutines(BuildCtx *ctx)
2629 |.endmacro 2468 |.endmacro
2630 | 2469 |
2631 |.ffunc_bit bit_tobit, 0 2470 |.ffunc_bit bit_tobit, 0
2632 |.if DUALNUM or SSE
2633 |.if not SSE
2634 | mov RB, ARG1
2635 |.endif
2636 | jmp ->fff_resbit 2471 | jmp ->fff_resbit
2637 |.else
2638 | fild ARG1
2639 | jmp ->fff_resn
2640 |.endif
2641 | 2472 |
2642 |.macro .ffunc_bit_op, name, ins 2473 |.macro .ffunc_bit_op, name, ins
2643 | .ffunc_bit name, 2 2474 | .ffunc_bit name, 2
@@ -2657,17 +2488,10 @@ static void build_subroutines(BuildCtx *ctx)
2657 |.else 2488 |.else
2658 | jae ->fff_fallback_bit_op 2489 | jae ->fff_fallback_bit_op
2659 |.endif 2490 |.endif
2660 |.if SSE
2661 | movsd xmm0, qword [RD] 2491 | movsd xmm0, qword [RD]
2662 | addsd xmm0, xmm1 2492 | addsd xmm0, xmm1
2663 | movd RA, xmm0 2493 | movd RA, xmm0
2664 | ins RB, RA 2494 | ins RB, RA
2665 |.else
2666 | fld qword [RD]
2667 | fadd TMP1
2668 | fstp FPARG1
2669 | ins RB, ARG1
2670 |.endif
2671 | sub RD, 8 2495 | sub RD, 8
2672 | jmp <1 2496 | jmp <1
2673 |.endmacro 2497 |.endmacro
@@ -2684,15 +2508,10 @@ static void build_subroutines(BuildCtx *ctx)
2684 | not RB 2508 | not RB
2685 |.if DUALNUM 2509 |.if DUALNUM
2686 | jmp ->fff_resbit 2510 | jmp ->fff_resbit
2687 |.elif SSE 2511 |.else
2688 |->fff_resbit: 2512 |->fff_resbit:
2689 | cvtsi2sd xmm0, RB 2513 | cvtsi2sd xmm0, RB
2690 | jmp ->fff_resxmm0 2514 | jmp ->fff_resxmm0
2691 |.else
2692 |->fff_resbit:
2693 | mov ARG1, RB
2694 | fild ARG1
2695 | jmp ->fff_resn
2696 |.endif 2515 |.endif
2697 | 2516 |
2698 |->fff_fallback_bit_op: 2517 |->fff_fallback_bit_op:
@@ -2705,22 +2524,13 @@ static void build_subroutines(BuildCtx *ctx)
2705 | // Note: no inline conversion from number for 2nd argument! 2524 | // Note: no inline conversion from number for 2nd argument!
2706 | cmp dword [BASE+12], LJ_TISNUM; jne ->fff_fallback 2525 | cmp dword [BASE+12], LJ_TISNUM; jne ->fff_fallback
2707 | mov RA, dword [BASE+8] 2526 | mov RA, dword [BASE+8]
2708 |.elif SSE 2527 |.else
2709 | .ffunc_nnsse name 2528 | .ffunc_nnsse name
2710 | sseconst_tobit xmm2, RBa 2529 | sseconst_tobit xmm2, RBa
2711 | addsd xmm0, xmm2 2530 | addsd xmm0, xmm2
2712 | addsd xmm1, xmm2 2531 | addsd xmm1, xmm2
2713 | movd RB, xmm0 2532 | movd RB, xmm0
2714 | movd RA, xmm1 2533 | movd RA, xmm1
2715 |.else
2716 | .ffunc_nn name
2717 | mov TMP1, TOBIT_BIAS
2718 | fadd TMP1
2719 | fstp FPARG3
2720 | fadd TMP1
2721 | fstp FPARG1
2722 | mov RA, ARG3
2723 | mov RB, ARG1
2724 |.endif 2534 |.endif
2725 | ins RB, cl // Assumes RA is ecx. 2535 | ins RB, cl // Assumes RA is ecx.
2726 | jmp ->fff_resbit 2536 | jmp ->fff_resbit
@@ -2854,7 +2664,7 @@ static void build_subroutines(BuildCtx *ctx)
2854 | mov FCARG2, PC // Caveat: FCARG2 == BASE 2664 | mov FCARG2, PC // Caveat: FCARG2 == BASE
2855 | mov FCARG1, L:RB 2665 | mov FCARG1, L:RB
2856 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC. 2666 | // SAVE_PC must hold the _previous_ PC. The callee updates it with PC.
2857 | call extern lj_dispatch_ins@8 // (lua_State *L, BCIns *pc) 2667 | call extern lj_dispatch_ins@8 // (lua_State *L, const BCIns *pc)
2858 |3: 2668 |3:
2859 | mov BASE, L:RB->base 2669 | mov BASE, L:RB->base
2860 |4: 2670 |4:
@@ -2925,6 +2735,79 @@ static void build_subroutines(BuildCtx *ctx)
2925 | add NARGS:RD, 1 2735 | add NARGS:RD, 1
2926 | jmp RBa 2736 | jmp RBa
2927 | 2737 |
2738 |->cont_stitch: // Trace stitching.
2739 |.if JIT
2740 | // BASE = base, RC = result, RB = mbase
2741 | mov TRACE:RA, [RB-24] // Save previous trace.
2742 | mov TMP1, TRACE:RA
2743 | mov TMP3, DISPATCH // Need one more register.
2744 | mov DISPATCH, MULTRES
2745 | movzx RA, PC_RA
2746 | lea RA, [BASE+RA*8] // Call base.
2747 | sub DISPATCH, 1
2748 | jz >2
2749 |1: // Move results down.
2750 |.if X64
2751 | mov RBa, [RC]
2752 | mov [RA], RBa
2753 |.else
2754 | mov RB, [RC]
2755 | mov [RA], RB
2756 | mov RB, [RC+4]
2757 | mov [RA+4], RB
2758 |.endif
2759 | add RC, 8
2760 | add RA, 8
2761 | sub DISPATCH, 1
2762 | jnz <1
2763 |2:
2764 | movzx RC, PC_RA
2765 | movzx RB, PC_RB
2766 | add RC, RB
2767 | lea RC, [BASE+RC*8-8]
2768 |3:
2769 | cmp RC, RA
2770 | ja >9 // More results wanted?
2771 |
2772 | mov DISPATCH, TMP3
2773 | mov TRACE:RD, TMP1 // Get previous trace.
2774 | movzx RB, word TRACE:RD->traceno
2775 | movzx RD, word TRACE:RD->link
2776 | cmp RD, RB
2777 | je ->cont_nop // Blacklisted.
2778 | test RD, RD
2779 | jne =>BC_JLOOP // Jump to stitched trace.
2780 |
2781 | // Stitch a new trace to the previous trace.
2782 | mov [DISPATCH+DISPATCH_J(exitno)], RB
2783 | mov L:RB, SAVE_L
2784 | mov L:RB->base, BASE
2785 | mov FCARG2, PC
2786 | lea FCARG1, [DISPATCH+GG_DISP2J]
2787 | mov aword [DISPATCH+DISPATCH_J(L)], L:RBa
2788 | call extern lj_dispatch_stitch@8 // (jit_State *J, const BCIns *pc)
2789 | mov BASE, L:RB->base
2790 | jmp ->cont_nop
2791 |
2792 |9: // Fill up results with nil.
2793 | mov dword [RA+4], LJ_TNIL
2794 | add RA, 8
2795 | jmp <3
2796 |.endif
2797 |
2798 |->vm_profhook: // Dispatch target for profiler hook.
2799#if LJ_HASPROFILE
2800 | mov L:RB, SAVE_L
2801 | mov L:RB->base, BASE
2802 | mov FCARG2, PC // Caveat: FCARG2 == BASE
2803 | mov FCARG1, L:RB
2804 | call extern lj_dispatch_profile@8 // (lua_State *L, const BCIns *pc)
2805 | mov BASE, L:RB->base
2806 | // HOOK_PROFILE is off again, so re-dispatch to dynamic instruction.
2807 | sub PC, 4
2808 | jmp ->cont_nop
2809#endif
2810 |
2928 |//----------------------------------------------------------------------- 2811 |//-----------------------------------------------------------------------
2929 |//-- Trace exit handler ------------------------------------------------- 2812 |//-- Trace exit handler -------------------------------------------------
2930 |//----------------------------------------------------------------------- 2813 |//-----------------------------------------------------------------------
@@ -2977,10 +2860,9 @@ static void build_subroutines(BuildCtx *ctx)
2977 | movsd qword [ebp-88], xmm1; movsd qword [ebp-96], xmm0 2860 | movsd qword [ebp-88], xmm1; movsd qword [ebp-96], xmm0
2978 |.endif 2861 |.endif
2979 | // Caveat: RB is ebp. 2862 | // Caveat: RB is ebp.
2980 | mov L:RB, [DISPATCH+DISPATCH_GL(jit_L)] 2863 | mov L:RB, [DISPATCH+DISPATCH_GL(cur_L)]
2981 | mov BASE, [DISPATCH+DISPATCH_GL(jit_base)] 2864 | mov BASE, [DISPATCH+DISPATCH_GL(jit_base)]
2982 | mov aword [DISPATCH+DISPATCH_J(L)], L:RBa 2865 | mov aword [DISPATCH+DISPATCH_J(L)], L:RBa
2983 | mov dword [DISPATCH+DISPATCH_GL(jit_L)], 0
2984 | mov L:RB->base, BASE 2866 | mov L:RB->base, BASE
2985 |.if X64WIN 2867 |.if X64WIN
2986 | lea CARG2, [rsp+4*8] 2868 | lea CARG2, [rsp+4*8]
@@ -2990,6 +2872,7 @@ static void build_subroutines(BuildCtx *ctx)
2990 | lea FCARG2, [esp+16] 2872 | lea FCARG2, [esp+16]
2991 |.endif 2873 |.endif
2992 | lea FCARG1, [DISPATCH+GG_DISP2J] 2874 | lea FCARG1, [DISPATCH+GG_DISP2J]
2875 | mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0
2993 | call extern lj_trace_exit@8 // (jit_State *J, ExitState *ex) 2876 | call extern lj_trace_exit@8 // (jit_State *J, ExitState *ex)
2994 | // MULTRES or negated error code returned in eax (RD). 2877 | // MULTRES or negated error code returned in eax (RD).
2995 | mov RAa, L:RB->cframe 2878 | mov RAa, L:RB->cframe
@@ -3036,12 +2919,14 @@ static void build_subroutines(BuildCtx *ctx)
3036 | mov r13, TMPa 2919 | mov r13, TMPa
3037 | mov r12, TMPQ 2920 | mov r12, TMPQ
3038 |.endif 2921 |.endif
3039 | test RD, RD; js >3 // Check for error from exit. 2922 | test RD, RD; js >9 // Check for error from exit.
2923 | mov L:RB, SAVE_L
3040 | mov MULTRES, RD 2924 | mov MULTRES, RD
3041 | mov LFUNC:KBASE, [BASE-8] 2925 | mov LFUNC:KBASE, [BASE-8]
3042 | mov KBASE, LFUNC:KBASE->pc 2926 | mov KBASE, LFUNC:KBASE->pc
3043 | mov KBASE, [KBASE+PC2PROTO(k)] 2927 | mov KBASE, [KBASE+PC2PROTO(k)]
3044 | mov dword [DISPATCH+DISPATCH_GL(jit_L)], 0 2928 | mov L:RB->base, BASE
2929 | mov dword [DISPATCH+DISPATCH_GL(jit_base)], 0
3045 | set_vmstate INTERP 2930 | set_vmstate INTERP
3046 | // Modified copy of ins_next which handles function header dispatch, too. 2931 | // Modified copy of ins_next which handles function header dispatch, too.
3047 | mov RC, [PC] 2932 | mov RC, [PC]
@@ -3050,16 +2935,31 @@ static void build_subroutines(BuildCtx *ctx)
3050 | add PC, 4 2935 | add PC, 4
3051 | shr RC, 16 2936 | shr RC, 16
3052 | cmp OP, BC_FUNCF // Function header? 2937 | cmp OP, BC_FUNCF // Function header?
3053 | jb >2 2938 | jb >3
3054 | mov RC, MULTRES // RC/RD holds nres+1. 2939 | cmp OP, BC_FUNCC+2 // Fast function?
2940 | jae >4
3055 |2: 2941 |2:
2942 | mov RC, MULTRES // RC/RD holds nres+1.
2943 |3:
3056 |.if X64 2944 |.if X64
3057 | jmp aword [DISPATCH+OP*8] 2945 | jmp aword [DISPATCH+OP*8]
3058 |.else 2946 |.else
3059 | jmp aword [DISPATCH+OP*4] 2947 | jmp aword [DISPATCH+OP*4]
3060 |.endif 2948 |.endif
3061 | 2949 |
3062 |3: // Rethrow error from the right C frame. 2950 |4: // Check frame below fast function.
2951 | mov RC, [BASE-4]
2952 | test RC, FRAME_TYPE
2953 | jnz <2 // Trace stitching continuation?
2954 | // Otherwise set KBASE for Lua function below fast function.
2955 | movzx RC, byte [RC-3]
2956 | not RCa
2957 | mov LFUNC:KBASE, [BASE+RC*8-8]
2958 | mov KBASE, LFUNC:KBASE->pc
2959 | mov KBASE, [KBASE+PC2PROTO(k)]
2960 | jmp <2
2961 |
2962 |9: // Rethrow error from the right C frame.
3063 | neg RD 2963 | neg RD
3064 | mov FCARG1, L:RB 2964 | mov FCARG1, L:RB
3065 | mov FCARG2, RD 2965 | mov FCARG2, RD
@@ -3071,27 +2971,18 @@ static void build_subroutines(BuildCtx *ctx)
3071 |//----------------------------------------------------------------------- 2971 |//-----------------------------------------------------------------------
3072 | 2972 |
3073 |// FP value rounding. Called by math.floor/math.ceil fast functions 2973 |// FP value rounding. Called by math.floor/math.ceil fast functions
3074 |// and from JIT code. 2974 |// and from JIT code. arg/ret is xmm0. xmm0-xmm3 and RD (eax) modified.
3075 | 2975 |.macro vm_round, name, mode, cond
3076 |// x87 variant: Arg/ret on x87 stack. No int/xmm registers modified. 2976 |->name:
3077 |.macro vm_round_x87, mode1, mode2 2977 |.if not X64 and cond
3078 | fnstcw word [esp+4] // Caveat: overwrites ARG1 and ARG2. 2978 | movsd xmm0, qword [esp+4]
3079 | mov [esp+8], eax 2979 | call ->name .. _sse
3080 | mov ax, mode1 2980 | movsd qword [esp+4], xmm0 // Overwrite callee-owned arg.
3081 | or ax, [esp+4] 2981 | fld qword [esp+4]
3082 |.if mode2 ~= 0xffff
3083 | and ax, mode2
3084 |.endif
3085 | mov [esp+6], ax
3086 | fldcw word [esp+6]
3087 | frndint
3088 | fldcw word [esp+4]
3089 | mov eax, [esp+8]
3090 | ret 2982 | ret
3091 |.endmacro 2983 |.endif
3092 | 2984 |
3093 |// SSE variant: arg/ret is xmm0. xmm0-xmm3 and RD (eax) modified. 2985 |->name .. _sse:
3094 |.macro vm_round_sse, mode
3095 | sseconst_abs xmm2, RDa 2986 | sseconst_abs xmm2, RDa
3096 | sseconst_2p52 xmm3, RDa 2987 | sseconst_2p52 xmm3, RDa
3097 | movaps xmm1, xmm0 2988 | movaps xmm1, xmm0
@@ -3127,22 +3018,12 @@ static void build_subroutines(BuildCtx *ctx)
3127 | ret 3018 | ret
3128 |.endmacro 3019 |.endmacro
3129 | 3020 |
3130 |.macro vm_round, name, ssemode, mode1, mode2 3021 | vm_round vm_floor, 0, 1
3131 |->name: 3022 | vm_round vm_ceil, 1, JIT
3132 |.if not SSE 3023 | vm_round vm_trunc, 2, JIT
3133 | vm_round_x87 mode1, mode2
3134 |.endif
3135 |->name .. _sse:
3136 | vm_round_sse ssemode
3137 |.endmacro
3138 |
3139 | vm_round vm_floor, 0, 0x0400, 0xf7ff
3140 | vm_round vm_ceil, 1, 0x0800, 0xfbff
3141 | vm_round vm_trunc, 2, 0x0c00, 0xffff
3142 | 3024 |
3143 |// FP modulo x%y. Called by BC_MOD* and vm_arith. 3025 |// FP modulo x%y. Called by BC_MOD* and vm_arith.
3144 |->vm_mod: 3026 |->vm_mod:
3145 |.if SSE
3146 |// Args in xmm0/xmm1, return value in xmm0. 3027 |// Args in xmm0/xmm1, return value in xmm0.
3147 |// Caveat: xmm0-xmm5 and RC (eax) modified! 3028 |// Caveat: xmm0-xmm5 and RC (eax) modified!
3148 | movaps xmm5, xmm0 3029 | movaps xmm5, xmm0
@@ -3170,172 +3051,6 @@ static void build_subroutines(BuildCtx *ctx)
3170 | movaps xmm0, xmm5 3051 | movaps xmm0, xmm5
3171 | subsd xmm0, xmm1 3052 | subsd xmm0, xmm1
3172 | ret 3053 | ret
3173 |.else
3174 |// Args/ret on x87 stack (y on top). No xmm registers modified.
3175 |// Caveat: needs 3 slots on x87 stack! RC (eax) modified!
3176 | fld st1
3177 | fdiv st1
3178 | fnstcw word [esp+4]
3179 | mov ax, 0x0400
3180 | or ax, [esp+4]
3181 | and ax, 0xf7ff
3182 | mov [esp+6], ax
3183 | fldcw word [esp+6]
3184 | frndint
3185 | fldcw word [esp+4]
3186 | fmulp st1
3187 | fsubp st1
3188 | ret
3189 |.endif
3190 |
3191 |// FP log2(x). Called by math.log(x, base).
3192 |->vm_log2:
3193 |.if X64WIN
3194 | movsd qword [rsp+8], xmm0 // Use scratch area.
3195 | fld1
3196 | fld qword [rsp+8]
3197 | fyl2x
3198 | fstp qword [rsp+8]
3199 | movsd xmm0, qword [rsp+8]
3200 |.elif X64
3201 | movsd qword [rsp-8], xmm0 // Use red zone.
3202 | fld1
3203 | fld qword [rsp-8]
3204 | fyl2x
3205 | fstp qword [rsp-8]
3206 | movsd xmm0, qword [rsp-8]
3207 |.else
3208 | fld1
3209 | fld qword [esp+4]
3210 | fyl2x
3211 |.endif
3212 | ret
3213 |
3214 |// FP exponentiation e^x and 2^x. Called by math.exp fast function and
3215 |// from JIT code. Arg/ret on x87 stack. No int/xmm regs modified.
3216 |// Caveat: needs 3 slots on x87 stack!
3217 |->vm_exp_x87:
3218 | fldl2e; fmulp st1 // e^x ==> 2^(x*log2(e))
3219 |->vm_exp2_x87:
3220 | .if X64WIN
3221 | .define expscratch, dword [rsp+8] // Use scratch area.
3222 | .elif X64
3223 | .define expscratch, dword [rsp-8] // Use red zone.
3224 | .else
3225 | .define expscratch, dword [esp+4] // Needs 4 byte scratch area.
3226 | .endif
3227 | fst expscratch // Caveat: overwrites ARG1.
3228 | cmp expscratch, 0x7f800000; je >1 // Special case: e^+Inf = +Inf
3229 | cmp expscratch, 0xff800000; je >2 // Special case: e^-Inf = 0
3230 |->vm_exp2raw: // Entry point for vm_pow. Without +-Inf check.
3231 | fdup; frndint; fsub st1, st0; fxch // Split into frac/int part.
3232 | f2xm1; fld1; faddp st1; fscale; fpop1 // ==> (2^frac-1 +1) << int
3233 |1:
3234 | ret
3235 |2:
3236 | fpop; fldz; ret
3237 |
3238 |// Generic power function x^y. Called by BC_POW, math.pow fast function,
3239 |// and vm_arith.
3240 |// Args/ret on x87 stack (y on top). RC (eax) modified.
3241 |// Caveat: needs 3 slots on x87 stack!
3242 |->vm_pow:
3243 |.if not SSE
3244 | fist dword [esp+4] // Store/reload int before comparison.
3245 | fild dword [esp+4] // Integral exponent used in vm_powi.
3246 | fucomip st1
3247 | jnz >8 // Branch for FP exponents.
3248 | jp >9 // Branch for NaN exponent.
3249 | fpop // Pop y and fallthrough to vm_powi.
3250 |
3251 |// FP/int power function x^i. Arg1/ret on x87 stack.
3252 |// Arg2 (int) on C stack. RC (eax) modified.
3253 |// Caveat: needs 2 slots on x87 stack!
3254 | mov eax, [esp+4]
3255 | cmp eax, 1; jle >6 // i<=1?
3256 | // Now 1 < (unsigned)i <= 0x80000000.
3257 |1: // Handle leading zeros.
3258 | test eax, 1; jnz >2
3259 | fmul st0
3260 | shr eax, 1
3261 | jmp <1
3262 |2:
3263 | shr eax, 1; jz >5
3264 | fdup
3265 |3: // Handle trailing bits.
3266 | fmul st0
3267 | shr eax, 1; jz >4
3268 | jnc <3
3269 | fmul st1, st0
3270 | jmp <3
3271 |4:
3272 | fmulp st1
3273 |5:
3274 | ret
3275 |6:
3276 | je <5 // x^1 ==> x
3277 | jb >7
3278 | fld1; fdivrp st1
3279 | neg eax
3280 | cmp eax, 1; je <5 // x^-1 ==> 1/x
3281 | jmp <1 // x^-i ==> (1/x)^i
3282 |7:
3283 | fpop; fld1 // x^0 ==> 1
3284 | ret
3285 |
3286 |8: // FP/FP power function x^y.
3287 | fst dword [esp+4]
3288 | fxch
3289 | fst dword [esp+8]
3290 | mov eax, [esp+4]; shl eax, 1
3291 | cmp eax, 0xff000000; je >2 // x^+-Inf?
3292 | mov eax, [esp+8]; shl eax, 1; je >4 // +-0^y?
3293 | cmp eax, 0xff000000; je >4 // +-Inf^y?
3294 | fyl2x
3295 | jmp ->vm_exp2raw
3296 |
3297 |9: // Handle x^NaN.
3298 | fld1
3299 | fucomip st2
3300 | je >1 // 1^NaN ==> 1
3301 | fxch // x^NaN ==> NaN
3302 |1:
3303 | fpop
3304 | ret
3305 |
3306 |2: // Handle x^+-Inf.
3307 | fabs
3308 | fld1
3309 | fucomip st1
3310 | je >3 // +-1^+-Inf ==> 1
3311 | fpop; fabs; fldz; mov eax, 0; setc al
3312 | ror eax, 1; xor eax, [esp+4]; jns >3 // |x|<>1, x^+-Inf ==> +Inf/0
3313 | fxch
3314 |3:
3315 | fpop1; fabs
3316 | ret
3317 |
3318 |4: // Handle +-0^y or +-Inf^y.
3319 | cmp dword [esp+4], 0; jge <3 // y >= 0, x^y ==> |x|
3320 | fpop; fpop
3321 | test eax, eax; jz >5 // y < 0, +-0^y ==> +Inf
3322 | fldz // y < 0, +-Inf^y ==> 0
3323 | ret
3324 |5:
3325 | mov dword [esp+4], 0x7f800000 // Return +Inf.
3326 | fld dword [esp+4]
3327 | ret
3328 |.endif
3329 |
3330 |// Args in xmm0/xmm1. Ret in xmm0. xmm0-xmm2 and RC (eax) modified.
3331 |// Needs 16 byte scratch area for x86. Also called from JIT code.
3332 |->vm_pow_sse:
3333 | cvtsd2si eax, xmm1
3334 | cvtsi2sd xmm2, eax
3335 | ucomisd xmm1, xmm2
3336 | jnz >8 // Branch for FP exponents.
3337 | jp >9 // Branch for NaN exponent.
3338 | // Fallthrough to vm_powi_sse.
3339 | 3054 |
3340 |// Args in xmm0/eax. Ret in xmm0. xmm0-xmm1 and eax modified. 3055 |// Args in xmm0/eax. Ret in xmm0. xmm0-xmm1 and eax modified.
3341 |->vm_powi_sse: 3056 |->vm_powi_sse:
@@ -3372,287 +3087,6 @@ static void build_subroutines(BuildCtx *ctx)
3372 | sseconst_1 xmm0, RDa 3087 | sseconst_1 xmm0, RDa
3373 | ret 3088 | ret
3374 | 3089 |
3375 |8: // FP/FP power function x^y.
3376 |.if X64
3377 | movd rax, xmm1; shl rax, 1
3378 | rol rax, 12; cmp rax, 0xffe; je >2 // x^+-Inf?
3379 | movd rax, xmm0; shl rax, 1; je >4 // +-0^y?
3380 | rol rax, 12; cmp rax, 0xffe; je >5 // +-Inf^y?
3381 | .if X64WIN
3382 | movsd qword [rsp+16], xmm1 // Use scratch area.
3383 | movsd qword [rsp+8], xmm0
3384 | fld qword [rsp+16]
3385 | fld qword [rsp+8]
3386 | .else
3387 | movsd qword [rsp-16], xmm1 // Use red zone.
3388 | movsd qword [rsp-8], xmm0
3389 | fld qword [rsp-16]
3390 | fld qword [rsp-8]
3391 | .endif
3392 |.else
3393 | movsd qword [esp+12], xmm1 // Needs 16 byte scratch area.
3394 | movsd qword [esp+4], xmm0
3395 | cmp dword [esp+12], 0; jne >1
3396 | mov eax, [esp+16]; shl eax, 1
3397 | cmp eax, 0xffe00000; je >2 // x^+-Inf?
3398 |1:
3399 | cmp dword [esp+4], 0; jne >1
3400 | mov eax, [esp+8]; shl eax, 1; je >4 // +-0^y?
3401 | cmp eax, 0xffe00000; je >5 // +-Inf^y?
3402 |1:
3403 | fld qword [esp+12]
3404 | fld qword [esp+4]
3405 |.endif
3406 | fyl2x // y*log2(x)
3407 | fdup; frndint; fsub st1, st0; fxch // Split into frac/int part.
3408 | f2xm1; fld1; faddp st1; fscale; fpop1 // ==> (2^frac-1 +1) << int
3409 |.if X64WIN
3410 | fstp qword [rsp+8] // Use scratch area.
3411 | movsd xmm0, qword [rsp+8]
3412 |.elif X64
3413 | fstp qword [rsp-8] // Use red zone.
3414 | movsd xmm0, qword [rsp-8]
3415 |.else
3416 | fstp qword [esp+4] // Needs 8 byte scratch area.
3417 | movsd xmm0, qword [esp+4]
3418 |.endif
3419 | ret
3420 |
3421 |9: // Handle x^NaN.
3422 | sseconst_1 xmm2, RDa
3423 | ucomisd xmm0, xmm2; je >1 // 1^NaN ==> 1
3424 | movaps xmm0, xmm1 // x^NaN ==> NaN
3425 |1:
3426 | ret
3427 |
3428 |2: // Handle x^+-Inf.
3429 | sseconst_abs xmm2, RDa
3430 | andpd xmm0, xmm2 // |x|
3431 | sseconst_1 xmm2, RDa
3432 | ucomisd xmm0, xmm2; je <1 // +-1^+-Inf ==> 1
3433 | movmskpd eax, xmm1
3434 | xorps xmm0, xmm0
3435 | mov ah, al; setc al; xor al, ah; jne <1 // |x|<>1, x^+-Inf ==> +Inf/0
3436 |3:
3437 | sseconst_hi xmm0, RDa, 7ff00000 // +Inf
3438 | ret
3439 |
3440 |4: // Handle +-0^y.
3441 | movmskpd eax, xmm1; test eax, eax; jnz <3 // y < 0, +-0^y ==> +Inf
3442 | xorps xmm0, xmm0 // y >= 0, +-0^y ==> 0
3443 | ret
3444 |
3445 |5: // Handle +-Inf^y.
3446 | movmskpd eax, xmm1; test eax, eax; jz <3 // y >= 0, +-Inf^y ==> +Inf
3447 | xorps xmm0, xmm0 // y < 0, +-Inf^y ==> 0
3448 | ret
3449 |
3450 |// Callable from C: double lj_vm_foldfpm(double x, int fpm)
3451 |// Computes fpm(x) for extended math functions. ORDER FPM.
3452 |->vm_foldfpm:
3453 |.if JIT
3454 |.if X64
3455 | .if X64WIN
3456 | .define fpmop, CARG2d
3457 | .else
3458 | .define fpmop, CARG1d
3459 | .endif
3460 | cmp fpmop, 1; jb ->vm_floor; je ->vm_ceil
3461 | cmp fpmop, 3; jb ->vm_trunc; ja >2
3462 | sqrtsd xmm0, xmm0; ret
3463 |2:
3464 | .if X64WIN
3465 | movsd qword [rsp+8], xmm0 // Use scratch area.
3466 | fld qword [rsp+8]
3467 | .else
3468 | movsd qword [rsp-8], xmm0 // Use red zone.
3469 | fld qword [rsp-8]
3470 | .endif
3471 | cmp fpmop, 5; ja >2
3472 | .if X64WIN; pop rax; .endif
3473 | je >1
3474 | call ->vm_exp_x87
3475 | .if X64WIN; push rax; .endif
3476 | jmp >7
3477 |1:
3478 | call ->vm_exp2_x87
3479 | .if X64WIN; push rax; .endif
3480 | jmp >7
3481 |2: ; cmp fpmop, 7; je >1; ja >2
3482 | fldln2; fxch; fyl2x; jmp >7
3483 |1: ; fld1; fxch; fyl2x; jmp >7
3484 |2: ; cmp fpmop, 9; je >1; ja >2
3485 | fldlg2; fxch; fyl2x; jmp >7
3486 |1: ; fsin; jmp >7
3487 |2: ; cmp fpmop, 11; je >1; ja >9
3488 | fcos; jmp >7
3489 |1: ; fptan; fpop
3490 |7:
3491 | .if X64WIN
3492 | fstp qword [rsp+8] // Use scratch area.
3493 | movsd xmm0, qword [rsp+8]
3494 | .else
3495 | fstp qword [rsp-8] // Use red zone.
3496 | movsd xmm0, qword [rsp-8]
3497 | .endif
3498 | ret
3499 |.else // x86 calling convention.
3500 | .define fpmop, eax
3501 |.if SSE
3502 | mov fpmop, [esp+12]
3503 | movsd xmm0, qword [esp+4]
3504 | cmp fpmop, 1; je >1; ja >2
3505 | call ->vm_floor; jmp >7
3506 |1: ; call ->vm_ceil; jmp >7
3507 |2: ; cmp fpmop, 3; je >1; ja >2
3508 | call ->vm_trunc; jmp >7
3509 |1:
3510 | sqrtsd xmm0, xmm0
3511 |7:
3512 | movsd qword [esp+4], xmm0 // Overwrite callee-owned args.
3513 | fld qword [esp+4]
3514 | ret
3515 |2: ; fld qword [esp+4]
3516 | cmp fpmop, 5; jb ->vm_exp_x87; je ->vm_exp2_x87
3517 |2: ; cmp fpmop, 7; je >1; ja >2
3518 | fldln2; fxch; fyl2x; ret
3519 |1: ; fld1; fxch; fyl2x; ret
3520 |2: ; cmp fpmop, 9; je >1; ja >2
3521 | fldlg2; fxch; fyl2x; ret
3522 |1: ; fsin; ret
3523 |2: ; cmp fpmop, 11; je >1; ja >9
3524 | fcos; ret
3525 |1: ; fptan; fpop; ret
3526 |.else
3527 | mov fpmop, [esp+12]
3528 | fld qword [esp+4]
3529 | cmp fpmop, 1; jb ->vm_floor; je ->vm_ceil
3530 | cmp fpmop, 3; jb ->vm_trunc; ja >2
3531 | fsqrt; ret
3532 |2: ; cmp fpmop, 5; jb ->vm_exp_x87; je ->vm_exp2_x87
3533 | cmp fpmop, 7; je >1; ja >2
3534 | fldln2; fxch; fyl2x; ret
3535 |1: ; fld1; fxch; fyl2x; ret
3536 |2: ; cmp fpmop, 9; je >1; ja >2
3537 | fldlg2; fxch; fyl2x; ret
3538 |1: ; fsin; ret
3539 |2: ; cmp fpmop, 11; je >1; ja >9
3540 | fcos; ret
3541 |1: ; fptan; fpop; ret
3542 |.endif
3543 |.endif
3544 |9: ; int3 // Bad fpm.
3545 |.endif
3546 |
3547 |// Callable from C: double lj_vm_foldarith(double x, double y, int op)
3548 |// Compute x op y for basic arithmetic operators (+ - * / % ^ and unary -)
3549 |// and basic math functions. ORDER ARITH
3550 |->vm_foldarith:
3551 |.if X64
3552 |
3553 | .if X64WIN
3554 | .define foldop, CARG3d
3555 | .else
3556 | .define foldop, CARG1d
3557 | .endif
3558 | cmp foldop, 1; je >1; ja >2
3559 | addsd xmm0, xmm1; ret
3560 |1: ; subsd xmm0, xmm1; ret
3561 |2: ; cmp foldop, 3; je >1; ja >2
3562 | mulsd xmm0, xmm1; ret
3563 |1: ; divsd xmm0, xmm1; ret
3564 |2: ; cmp foldop, 5; jb ->vm_mod; je ->vm_pow
3565 | cmp foldop, 7; je >1; ja >2
3566 | sseconst_sign xmm1, RDa; xorps xmm0, xmm1; ret
3567 |1: ; sseconst_abs xmm1, RDa; andps xmm0, xmm1; ret
3568 |2: ; cmp foldop, 9; ja >2
3569 |.if X64WIN
3570 | movsd qword [rsp+8], xmm0 // Use scratch area.
3571 | movsd qword [rsp+16], xmm1
3572 | fld qword [rsp+8]
3573 | fld qword [rsp+16]
3574 |.else
3575 | movsd qword [rsp-8], xmm0 // Use red zone.
3576 | movsd qword [rsp-16], xmm1
3577 | fld qword [rsp-8]
3578 | fld qword [rsp-16]
3579 |.endif
3580 | je >1
3581 | fpatan
3582 |7:
3583 |.if X64WIN
3584 | fstp qword [rsp+8] // Use scratch area.
3585 | movsd xmm0, qword [rsp+8]
3586 |.else
3587 | fstp qword [rsp-8] // Use red zone.
3588 | movsd xmm0, qword [rsp-8]
3589 |.endif
3590 | ret
3591 |1: ; fxch; fscale; fpop1; jmp <7
3592 |2: ; cmp foldop, 11; je >1; ja >9
3593 | minsd xmm0, xmm1; ret
3594 |1: ; maxsd xmm0, xmm1; ret
3595 |9: ; int3 // Bad op.
3596 |
3597 |.elif SSE // x86 calling convention with SSE ops.
3598 |
3599 | .define foldop, eax
3600 | mov foldop, [esp+20]
3601 | movsd xmm0, qword [esp+4]
3602 | movsd xmm1, qword [esp+12]
3603 | cmp foldop, 1; je >1; ja >2
3604 | addsd xmm0, xmm1
3605 |7:
3606 | movsd qword [esp+4], xmm0 // Overwrite callee-owned args.
3607 | fld qword [esp+4]
3608 | ret
3609 |1: ; subsd xmm0, xmm1; jmp <7
3610 |2: ; cmp foldop, 3; je >1; ja >2
3611 | mulsd xmm0, xmm1; jmp <7
3612 |1: ; divsd xmm0, xmm1; jmp <7
3613 |2: ; cmp foldop, 5
3614 | je >1; ja >2
3615 | call ->vm_mod; jmp <7
3616 |1: ; pop edx; call ->vm_pow; push edx; jmp <7 // Writes to scratch area.
3617 |2: ; cmp foldop, 7; je >1; ja >2
3618 | sseconst_sign xmm1, RDa; xorps xmm0, xmm1; jmp <7
3619 |1: ; sseconst_abs xmm1, RDa; andps xmm0, xmm1; jmp <7
3620 |2: ; cmp foldop, 9; ja >2
3621 | fld qword [esp+4] // Reload from stack
3622 | fld qword [esp+12]
3623 | je >1
3624 | fpatan; ret
3625 |1: ; fxch; fscale; fpop1; ret
3626 |2: ; cmp foldop, 11; je >1; ja >9
3627 | minsd xmm0, xmm1; jmp <7
3628 |1: ; maxsd xmm0, xmm1; jmp <7
3629 |9: ; int3 // Bad op.
3630 |
3631 |.else // x86 calling convention with x87 ops.
3632 |
3633 | mov eax, [esp+20]
3634 | fld qword [esp+4]
3635 | fld qword [esp+12]
3636 | cmp eax, 1; je >1; ja >2
3637 | faddp st1; ret
3638 |1: ; fsubp st1; ret
3639 |2: ; cmp eax, 3; je >1; ja >2
3640 | fmulp st1; ret
3641 |1: ; fdivp st1; ret
3642 |2: ; cmp eax, 5; jb ->vm_mod; je ->vm_pow
3643 | cmp eax, 7; je >1; ja >2
3644 | fpop; fchs; ret
3645 |1: ; fpop; fabs; ret
3646 |2: ; cmp eax, 9; je >1; ja >2
3647 | fpatan; ret
3648 |1: ; fxch; fscale; fpop1; ret
3649 |2: ; cmp eax, 11; je >1; ja >9
3650 | fucomi st1; fcmovnbe st1; fpop1; ret
3651 |1: ; fucomi st1; fcmovbe st1; fpop1; ret
3652 |9: ; int3 // Bad op.
3653 |
3654 |.endif
3655 |
3656 |//----------------------------------------------------------------------- 3090 |//-----------------------------------------------------------------------
3657 |//-- Miscellaneous functions -------------------------------------------- 3091 |//-- Miscellaneous functions --------------------------------------------
3658 |//----------------------------------------------------------------------- 3092 |//-----------------------------------------------------------------------
@@ -3663,6 +3097,7 @@ static void build_subroutines(BuildCtx *ctx)
3663 | mov eax, CARG1d 3097 | mov eax, CARG1d
3664 | .if X64WIN; push rsi; mov rsi, CARG2; .endif 3098 | .if X64WIN; push rsi; mov rsi, CARG2; .endif
3665 | push rbx 3099 | push rbx
3100 | xor ecx, ecx
3666 | cpuid 3101 | cpuid
3667 | mov [rsi], eax 3102 | mov [rsi], eax
3668 | mov [rsi+4], ebx 3103 | mov [rsi+4], ebx
@@ -3686,6 +3121,7 @@ static void build_subroutines(BuildCtx *ctx)
3686 | mov eax, [esp+4] // Argument 1 is function number. 3121 | mov eax, [esp+4] // Argument 1 is function number.
3687 | push edi 3122 | push edi
3688 | push ebx 3123 | push ebx
3124 | xor ecx, ecx
3689 | cpuid 3125 | cpuid
3690 | mov edi, [esp+16] // Argument 2 is result area. 3126 | mov edi, [esp+16] // Argument 2 is result area.
3691 | mov [edi], eax 3127 | mov [edi], eax
@@ -3963,19 +3399,12 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3963 | // RA is a number. 3399 | // RA is a number.
3964 | cmp dword [BASE+RD*8+4], LJ_TISNUM; jb >1; jne ->vmeta_comp 3400 | cmp dword [BASE+RD*8+4], LJ_TISNUM; jb >1; jne ->vmeta_comp
3965 | // RA is a number, RD is an integer. 3401 | // RA is a number, RD is an integer.
3966 |.if SSE
3967 | cvtsi2sd xmm0, dword [BASE+RD*8] 3402 | cvtsi2sd xmm0, dword [BASE+RD*8]
3968 | jmp >2 3403 | jmp >2
3969 |.else
3970 | fld qword [BASE+RA*8]
3971 | fild dword [BASE+RD*8]
3972 | jmp >3
3973 |.endif
3974 | 3404 |
3975 |8: // RA is an integer, RD is not an integer. 3405 |8: // RA is an integer, RD is not an integer.
3976 | ja ->vmeta_comp 3406 | ja ->vmeta_comp
3977 | // RA is an integer, RD is a number. 3407 | // RA is an integer, RD is a number.
3978 |.if SSE
3979 | cvtsi2sd xmm1, dword [BASE+RA*8] 3408 | cvtsi2sd xmm1, dword [BASE+RA*8]
3980 | movsd xmm0, qword [BASE+RD*8] 3409 | movsd xmm0, qword [BASE+RD*8]
3981 | add PC, 4 3410 | add PC, 4
@@ -3983,29 +3412,15 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
3983 | jmp_comp jbe, ja, jb, jae, <9 3412 | jmp_comp jbe, ja, jb, jae, <9
3984 | jmp <6 3413 | jmp <6
3985 |.else 3414 |.else
3986 | fild dword [BASE+RA*8]
3987 | jmp >2
3988 |.endif
3989 |.else
3990 | checknum RA, ->vmeta_comp 3415 | checknum RA, ->vmeta_comp
3991 | checknum RD, ->vmeta_comp 3416 | checknum RD, ->vmeta_comp
3992 |.endif 3417 |.endif
3993 |.if SSE
3994 |1: 3418 |1:
3995 | movsd xmm0, qword [BASE+RD*8] 3419 | movsd xmm0, qword [BASE+RD*8]
3996 |2: 3420 |2:
3997 | add PC, 4 3421 | add PC, 4
3998 | ucomisd xmm0, qword [BASE+RA*8] 3422 | ucomisd xmm0, qword [BASE+RA*8]
3999 |3: 3423 |3:
4000 |.else
4001 |1:
4002 | fld qword [BASE+RA*8] // Reverse order, i.e like cmp D, A.
4003 |2:
4004 | fld qword [BASE+RD*8]
4005 |3:
4006 | add PC, 4
4007 | fcomparepp
4008 |.endif
4009 | // Unordered: all of ZF CF PF set, ordered: PF clear. 3424 | // Unordered: all of ZF CF PF set, ordered: PF clear.
4010 | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't. 3425 | // To preserve NaN semantics GE/GT branch on unordered, but LT/LE don't.
4011 |.if DUALNUM 3426 |.if DUALNUM
@@ -4045,43 +3460,25 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4045 | // RD is a number. 3460 | // RD is a number.
4046 | cmp dword [BASE+RA*8+4], LJ_TISNUM; jb >1; jne >5 3461 | cmp dword [BASE+RA*8+4], LJ_TISNUM; jb >1; jne >5
4047 | // RD is a number, RA is an integer. 3462 | // RD is a number, RA is an integer.
4048 |.if SSE
4049 | cvtsi2sd xmm0, dword [BASE+RA*8] 3463 | cvtsi2sd xmm0, dword [BASE+RA*8]
4050 |.else
4051 | fild dword [BASE+RA*8]
4052 |.endif
4053 | jmp >2 3464 | jmp >2
4054 | 3465 |
4055 |8: // RD is an integer, RA is not an integer. 3466 |8: // RD is an integer, RA is not an integer.
4056 | ja >5 3467 | ja >5
4057 | // RD is an integer, RA is a number. 3468 | // RD is an integer, RA is a number.
4058 |.if SSE
4059 | cvtsi2sd xmm0, dword [BASE+RD*8] 3469 | cvtsi2sd xmm0, dword [BASE+RD*8]
4060 | ucomisd xmm0, qword [BASE+RA*8] 3470 | ucomisd xmm0, qword [BASE+RA*8]
4061 |.else
4062 | fild dword [BASE+RD*8]
4063 | fld qword [BASE+RA*8]
4064 |.endif
4065 | jmp >4 3471 | jmp >4
4066 | 3472 |
4067 |.else 3473 |.else
4068 | cmp RB, LJ_TISNUM; jae >5 3474 | cmp RB, LJ_TISNUM; jae >5
4069 | checknum RA, >5 3475 | checknum RA, >5
4070 |.endif 3476 |.endif
4071 |.if SSE
4072 |1: 3477 |1:
4073 | movsd xmm0, qword [BASE+RA*8] 3478 | movsd xmm0, qword [BASE+RA*8]
4074 |2: 3479 |2:
4075 | ucomisd xmm0, qword [BASE+RD*8] 3480 | ucomisd xmm0, qword [BASE+RD*8]
4076 |4: 3481 |4:
4077 |.else
4078 |1:
4079 | fld qword [BASE+RA*8]
4080 |2:
4081 | fld qword [BASE+RD*8]
4082 |4:
4083 | fcomparepp
4084 |.endif
4085 iseqne_fp: 3482 iseqne_fp:
4086 if (vk) { 3483 if (vk) {
4087 | jp >2 // Unordered means not equal. 3484 | jp >2 // Unordered means not equal.
@@ -4204,39 +3601,21 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4204 | // RA is a number. 3601 | // RA is a number.
4205 | cmp dword [KBASE+RD*8+4], LJ_TISNUM; jb >1 3602 | cmp dword [KBASE+RD*8+4], LJ_TISNUM; jb >1
4206 | // RA is a number, RD is an integer. 3603 | // RA is a number, RD is an integer.
4207 |.if SSE
4208 | cvtsi2sd xmm0, dword [KBASE+RD*8] 3604 | cvtsi2sd xmm0, dword [KBASE+RD*8]
4209 |.else
4210 | fild dword [KBASE+RD*8]
4211 |.endif
4212 | jmp >2 3605 | jmp >2
4213 | 3606 |
4214 |8: // RA is an integer, RD is a number. 3607 |8: // RA is an integer, RD is a number.
4215 |.if SSE
4216 | cvtsi2sd xmm0, dword [BASE+RA*8] 3608 | cvtsi2sd xmm0, dword [BASE+RA*8]
4217 | ucomisd xmm0, qword [KBASE+RD*8] 3609 | ucomisd xmm0, qword [KBASE+RD*8]
4218 |.else
4219 | fild dword [BASE+RA*8]
4220 | fld qword [KBASE+RD*8]
4221 |.endif
4222 | jmp >4 3610 | jmp >4
4223 |.else 3611 |.else
4224 | cmp RB, LJ_TISNUM; jae >3 3612 | cmp RB, LJ_TISNUM; jae >3
4225 |.endif 3613 |.endif
4226 |.if SSE
4227 |1: 3614 |1:
4228 | movsd xmm0, qword [KBASE+RD*8] 3615 | movsd xmm0, qword [KBASE+RD*8]
4229 |2: 3616 |2:
4230 | ucomisd xmm0, qword [BASE+RA*8] 3617 | ucomisd xmm0, qword [BASE+RA*8]
4231 |4: 3618 |4:
4232 |.else
4233 |1:
4234 | fld qword [KBASE+RD*8]
4235 |2:
4236 | fld qword [BASE+RA*8]
4237 |4:
4238 | fcomparepp
4239 |.endif
4240 goto iseqne_fp; 3619 goto iseqne_fp;
4241 case BC_ISEQP: case BC_ISNEP: 3620 case BC_ISEQP: case BC_ISNEP:
4242 vk = op == BC_ISEQP; 3621 vk = op == BC_ISEQP;
@@ -4287,6 +3666,18 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4287 | ins_next 3666 | ins_next
4288 break; 3667 break;
4289 3668
3669 case BC_ISTYPE:
3670 | ins_AD // RA = src, RD = -type
3671 | add RD, [BASE+RA*8+4]
3672 | jne ->vmeta_istype
3673 | ins_next
3674 break;
3675 case BC_ISNUM:
3676 | ins_AD // RA = src, RD = -(TISNUM-1)
3677 | checknum RA, ->vmeta_istype
3678 | ins_next
3679 break;
3680
4290 /* -- Unary ops --------------------------------------------------------- */ 3681 /* -- Unary ops --------------------------------------------------------- */
4291 3682
4292 case BC_MOV: 3683 case BC_MOV:
@@ -4330,16 +3721,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4330 |.else 3721 |.else
4331 | checknum RD, ->vmeta_unm 3722 | checknum RD, ->vmeta_unm
4332 |.endif 3723 |.endif
4333 |.if SSE
4334 | movsd xmm0, qword [BASE+RD*8] 3724 | movsd xmm0, qword [BASE+RD*8]
4335 | sseconst_sign xmm1, RDa 3725 | sseconst_sign xmm1, RDa
4336 | xorps xmm0, xmm1 3726 | xorps xmm0, xmm1
4337 | movsd qword [BASE+RA*8], xmm0 3727 | movsd qword [BASE+RA*8], xmm0
4338 |.else
4339 | fld qword [BASE+RD*8]
4340 | fchs
4341 | fstp qword [BASE+RA*8]
4342 |.endif
4343 |.if DUALNUM 3728 |.if DUALNUM
4344 | jmp <9 3729 | jmp <9
4345 |.else 3730 |.else
@@ -4355,15 +3740,11 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4355 |1: 3740 |1:
4356 | mov dword [BASE+RA*8+4], LJ_TISNUM 3741 | mov dword [BASE+RA*8+4], LJ_TISNUM
4357 | mov dword [BASE+RA*8], RD 3742 | mov dword [BASE+RA*8], RD
4358 |.elif SSE 3743 |.else
4359 | xorps xmm0, xmm0 3744 | xorps xmm0, xmm0
4360 | cvtsi2sd xmm0, dword STR:RD->len 3745 | cvtsi2sd xmm0, dword STR:RD->len
4361 |1: 3746 |1:
4362 | movsd qword [BASE+RA*8], xmm0 3747 | movsd qword [BASE+RA*8], xmm0
4363 |.else
4364 | fild dword STR:RD->len
4365 |1:
4366 | fstp qword [BASE+RA*8]
4367 |.endif 3748 |.endif
4368 | ins_next 3749 | ins_next
4369 |2: 3750 |2:
@@ -4381,11 +3762,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4381 | // Length of table returned in eax (RD). 3762 | // Length of table returned in eax (RD).
4382 |.if DUALNUM 3763 |.if DUALNUM
4383 | // Nothing to do. 3764 | // Nothing to do.
4384 |.elif SSE
4385 | cvtsi2sd xmm0, RD
4386 |.else 3765 |.else
4387 | mov ARG1, RD 3766 | cvtsi2sd xmm0, RD
4388 | fild ARG1
4389 |.endif 3767 |.endif
4390 | mov BASE, RB // Restore BASE. 3768 | mov BASE, RB // Restore BASE.
4391 | movzx RA, PC_RA 3769 | movzx RA, PC_RA
@@ -4400,7 +3778,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4400 3778
4401 /* -- Binary ops -------------------------------------------------------- */ 3779 /* -- Binary ops -------------------------------------------------------- */
4402 3780
4403 |.macro ins_arithpre, x87ins, sseins, ssereg 3781 |.macro ins_arithpre, sseins, ssereg
4404 | ins_ABC 3782 | ins_ABC
4405 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN); 3783 ||vk = ((int)op - BC_ADDVN) / (BC_ADDNV-BC_ADDVN);
4406 ||switch (vk) { 3784 ||switch (vk) {
@@ -4409,37 +3787,22 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4409 | .if DUALNUM 3787 | .if DUALNUM
4410 | cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_vn 3788 | cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_vn
4411 | .endif 3789 | .endif
4412 | .if SSE 3790 | movsd xmm0, qword [BASE+RB*8]
4413 | movsd xmm0, qword [BASE+RB*8] 3791 | sseins ssereg, qword [KBASE+RC*8]
4414 | sseins ssereg, qword [KBASE+RC*8]
4415 | .else
4416 | fld qword [BASE+RB*8]
4417 | x87ins qword [KBASE+RC*8]
4418 | .endif
4419 || break; 3792 || break;
4420 ||case 1: 3793 ||case 1:
4421 | checknum RB, ->vmeta_arith_nv 3794 | checknum RB, ->vmeta_arith_nv
4422 | .if DUALNUM 3795 | .if DUALNUM
4423 | cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_nv 3796 | cmp dword [KBASE+RC*8+4], LJ_TISNUM; jae ->vmeta_arith_nv
4424 | .endif 3797 | .endif
4425 | .if SSE 3798 | movsd xmm0, qword [KBASE+RC*8]
4426 | movsd xmm0, qword [KBASE+RC*8] 3799 | sseins ssereg, qword [BASE+RB*8]
4427 | sseins ssereg, qword [BASE+RB*8]
4428 | .else
4429 | fld qword [KBASE+RC*8]
4430 | x87ins qword [BASE+RB*8]
4431 | .endif
4432 || break; 3800 || break;
4433 ||default: 3801 ||default:
4434 | checknum RB, ->vmeta_arith_vv 3802 | checknum RB, ->vmeta_arith_vv
4435 | checknum RC, ->vmeta_arith_vv 3803 | checknum RC, ->vmeta_arith_vv
4436 | .if SSE 3804 | movsd xmm0, qword [BASE+RB*8]
4437 | movsd xmm0, qword [BASE+RB*8] 3805 | sseins ssereg, qword [BASE+RC*8]
4438 | sseins ssereg, qword [BASE+RC*8]
4439 | .else
4440 | fld qword [BASE+RB*8]
4441 | x87ins qword [BASE+RC*8]
4442 | .endif
4443 || break; 3806 || break;
4444 ||} 3807 ||}
4445 |.endmacro 3808 |.endmacro
@@ -4477,55 +3840,62 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4477 |.endmacro 3840 |.endmacro
4478 | 3841 |
4479 |.macro ins_arithpost 3842 |.macro ins_arithpost
4480 |.if SSE
4481 | movsd qword [BASE+RA*8], xmm0 3843 | movsd qword [BASE+RA*8], xmm0
4482 |.else
4483 | fstp qword [BASE+RA*8]
4484 |.endif
4485 |.endmacro 3844 |.endmacro
4486 | 3845 |
4487 |.macro ins_arith, x87ins, sseins 3846 |.macro ins_arith, sseins
4488 | ins_arithpre x87ins, sseins, xmm0 3847 | ins_arithpre sseins, xmm0
4489 | ins_arithpost 3848 | ins_arithpost
4490 | ins_next 3849 | ins_next
4491 |.endmacro 3850 |.endmacro
4492 | 3851 |
4493 |.macro ins_arith, intins, x87ins, sseins 3852 |.macro ins_arith, intins, sseins
4494 |.if DUALNUM 3853 |.if DUALNUM
4495 | ins_arithdn intins 3854 | ins_arithdn intins
4496 |.else 3855 |.else
4497 | ins_arith, x87ins, sseins 3856 | ins_arith, sseins
4498 |.endif 3857 |.endif
4499 |.endmacro 3858 |.endmacro
4500 3859
4501 | // RA = dst, RB = src1 or num const, RC = src2 or num const 3860 | // RA = dst, RB = src1 or num const, RC = src2 or num const
4502 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV: 3861 case BC_ADDVN: case BC_ADDNV: case BC_ADDVV:
4503 | ins_arith add, fadd, addsd 3862 | ins_arith add, addsd
4504 break; 3863 break;
4505 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV: 3864 case BC_SUBVN: case BC_SUBNV: case BC_SUBVV:
4506 | ins_arith sub, fsub, subsd 3865 | ins_arith sub, subsd
4507 break; 3866 break;
4508 case BC_MULVN: case BC_MULNV: case BC_MULVV: 3867 case BC_MULVN: case BC_MULNV: case BC_MULVV:
4509 | ins_arith imul, fmul, mulsd 3868 | ins_arith imul, mulsd
4510 break; 3869 break;
4511 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV: 3870 case BC_DIVVN: case BC_DIVNV: case BC_DIVVV:
4512 | ins_arith fdiv, divsd 3871 | ins_arith divsd
4513 break; 3872 break;
4514 case BC_MODVN: 3873 case BC_MODVN:
4515 | ins_arithpre fld, movsd, xmm1 3874 | ins_arithpre movsd, xmm1
4516 |->BC_MODVN_Z: 3875 |->BC_MODVN_Z:
4517 | call ->vm_mod 3876 | call ->vm_mod
4518 | ins_arithpost 3877 | ins_arithpost
4519 | ins_next 3878 | ins_next
4520 break; 3879 break;
4521 case BC_MODNV: case BC_MODVV: 3880 case BC_MODNV: case BC_MODVV:
4522 | ins_arithpre fld, movsd, xmm1 3881 | ins_arithpre movsd, xmm1
4523 | jmp ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway. 3882 | jmp ->BC_MODVN_Z // Avoid 3 copies. It's slow anyway.
4524 break; 3883 break;
4525 case BC_POW: 3884 case BC_POW:
4526 | ins_arithpre fld, movsd, xmm1 3885 | ins_arithpre movsd, xmm1
4527 | call ->vm_pow 3886 | mov RB, BASE
3887 |.if not X64
3888 | movsd FPARG1, xmm0
3889 | movsd FPARG3, xmm1
3890 |.endif
3891 | call extern pow
3892 | movzx RA, PC_RA
3893 | mov BASE, RB
3894 |.if X64
4528 | ins_arithpost 3895 | ins_arithpost
3896 |.else
3897 | fstp qword [BASE+RA*8]
3898 |.endif
4529 | ins_next 3899 | ins_next
4530 break; 3900 break;
4531 3901
@@ -4593,25 +3963,17 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4593 | movsx RD, RDW 3963 | movsx RD, RDW
4594 | mov dword [BASE+RA*8+4], LJ_TISNUM 3964 | mov dword [BASE+RA*8+4], LJ_TISNUM
4595 | mov dword [BASE+RA*8], RD 3965 | mov dword [BASE+RA*8], RD
4596 |.elif SSE 3966 |.else
4597 | movsx RD, RDW // Sign-extend literal. 3967 | movsx RD, RDW // Sign-extend literal.
4598 | cvtsi2sd xmm0, RD 3968 | cvtsi2sd xmm0, RD
4599 | movsd qword [BASE+RA*8], xmm0 3969 | movsd qword [BASE+RA*8], xmm0
4600 |.else
4601 | fild PC_RD // Refetch signed RD from instruction.
4602 | fstp qword [BASE+RA*8]
4603 |.endif 3970 |.endif
4604 | ins_next 3971 | ins_next
4605 break; 3972 break;
4606 case BC_KNUM: 3973 case BC_KNUM:
4607 | ins_AD // RA = dst, RD = num const 3974 | ins_AD // RA = dst, RD = num const
4608 |.if SSE
4609 | movsd xmm0, qword [KBASE+RD*8] 3975 | movsd xmm0, qword [KBASE+RD*8]
4610 | movsd qword [BASE+RA*8], xmm0 3976 | movsd qword [BASE+RA*8], xmm0
4611 |.else
4612 | fld qword [KBASE+RD*8]
4613 | fstp qword [BASE+RA*8]
4614 |.endif
4615 | ins_next 3977 | ins_next
4616 break; 3978 break;
4617 case BC_KPRI: 3979 case BC_KPRI:
@@ -4718,18 +4080,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4718 case BC_USETN: 4080 case BC_USETN:
4719 | ins_AD // RA = upvalue #, RD = num const 4081 | ins_AD // RA = upvalue #, RD = num const
4720 | mov LFUNC:RB, [BASE-8] 4082 | mov LFUNC:RB, [BASE-8]
4721 |.if SSE
4722 | movsd xmm0, qword [KBASE+RD*8] 4083 | movsd xmm0, qword [KBASE+RD*8]
4723 |.else
4724 | fld qword [KBASE+RD*8]
4725 |.endif
4726 | mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)] 4084 | mov UPVAL:RB, [LFUNC:RB+RA*4+offsetof(GCfuncL, uvptr)]
4727 | mov RA, UPVAL:RB->v 4085 | mov RA, UPVAL:RB->v
4728 |.if SSE
4729 | movsd qword [RA], xmm0 4086 | movsd qword [RA], xmm0
4730 |.else
4731 | fstp qword [RA]
4732 |.endif
4733 | ins_next 4087 | ins_next
4734 break; 4088 break;
4735 case BC_USETP: 4089 case BC_USETP:
@@ -4883,18 +4237,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
4883 |.else 4237 |.else
4884 | // Convert number to int and back and compare. 4238 | // Convert number to int and back and compare.
4885 | checknum RC, >5 4239 | checknum RC, >5
4886 |.if SSE
4887 | movsd xmm0, qword [BASE+RC*8] 4240 | movsd xmm0, qword [BASE+RC*8]
4888 | cvtsd2si RC, xmm0 4241 | cvttsd2si RC, xmm0
4889 | cvtsi2sd xmm1, RC 4242 | cvtsi2sd xmm1, RC
4890 | ucomisd xmm0, xmm1 4243 | ucomisd xmm0, xmm1
4891 |.else
4892 | fld qword [BASE+RC*8]
4893 | fist ARG1
4894 | fild ARG1
4895 | fcomparepp
4896 | mov RC, ARG1
4897 |.endif
4898 | jne ->vmeta_tgetv // Generic numeric key? Use fallback. 4244 | jne ->vmeta_tgetv // Generic numeric key? Use fallback.
4899 |.endif 4245 |.endif
4900 | cmp RC, TAB:RB->asize // Takes care of unordered, too. 4246 | cmp RC, TAB:RB->asize // Takes care of unordered, too.
@@ -5018,6 +4364,32 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5018 | mov dword [BASE+RA*8+4], LJ_TNIL 4364 | mov dword [BASE+RA*8+4], LJ_TNIL
5019 | jmp <1 4365 | jmp <1
5020 break; 4366 break;
4367 case BC_TGETR:
4368 | ins_ABC // RA = dst, RB = table, RC = key
4369 | mov TAB:RB, [BASE+RB*8]
4370 |.if DUALNUM
4371 | mov RC, dword [BASE+RC*8]
4372 |.else
4373 | cvttsd2si RC, qword [BASE+RC*8]
4374 |.endif
4375 | cmp RC, TAB:RB->asize
4376 | jae ->vmeta_tgetr // Not in array part? Use fallback.
4377 | shl RC, 3
4378 | add RC, TAB:RB->array
4379 | // Get array slot.
4380 |->BC_TGETR_Z:
4381 |.if X64
4382 | mov RBa, [RC]
4383 | mov [BASE+RA*8], RBa
4384 |.else
4385 | mov RB, [RC]
4386 | mov RC, [RC+4]
4387 | mov [BASE+RA*8], RB
4388 | mov [BASE+RA*8+4], RC
4389 |.endif
4390 |->BC_TGETR2_Z:
4391 | ins_next
4392 break;
5021 4393
5022 case BC_TSETV: 4394 case BC_TSETV:
5023 | ins_ABC // RA = src, RB = table, RC = key 4395 | ins_ABC // RA = src, RB = table, RC = key
@@ -5031,18 +4403,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5031 |.else 4403 |.else
5032 | // Convert number to int and back and compare. 4404 | // Convert number to int and back and compare.
5033 | checknum RC, >5 4405 | checknum RC, >5
5034 |.if SSE
5035 | movsd xmm0, qword [BASE+RC*8] 4406 | movsd xmm0, qword [BASE+RC*8]
5036 | cvtsd2si RC, xmm0 4407 | cvttsd2si RC, xmm0
5037 | cvtsi2sd xmm1, RC 4408 | cvtsi2sd xmm1, RC
5038 | ucomisd xmm0, xmm1 4409 | ucomisd xmm0, xmm1
5039 |.else
5040 | fld qword [BASE+RC*8]
5041 | fist ARG1
5042 | fild ARG1
5043 | fcomparepp
5044 | mov RC, ARG1
5045 |.endif
5046 | jne ->vmeta_tsetv // Generic numeric key? Use fallback. 4410 | jne ->vmeta_tsetv // Generic numeric key? Use fallback.
5047 |.endif 4411 |.endif
5048 | cmp RC, TAB:RB->asize // Takes care of unordered, too. 4412 | cmp RC, TAB:RB->asize // Takes care of unordered, too.
@@ -5212,6 +4576,39 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5212 | movzx RA, PC_RA // Restore RA. 4576 | movzx RA, PC_RA // Restore RA.
5213 | jmp <2 4577 | jmp <2
5214 break; 4578 break;
4579 case BC_TSETR:
4580 | ins_ABC // RA = src, RB = table, RC = key
4581 | mov TAB:RB, [BASE+RB*8]
4582 |.if DUALNUM
4583 | mov RC, dword [BASE+RC*8]
4584 |.else
4585 | cvttsd2si RC, qword [BASE+RC*8]
4586 |.endif
4587 | test byte TAB:RB->marked, LJ_GC_BLACK // isblack(table)
4588 | jnz >7
4589 |2:
4590 | cmp RC, TAB:RB->asize
4591 | jae ->vmeta_tsetr
4592 | shl RC, 3
4593 | add RC, TAB:RB->array
4594 | // Set array slot.
4595 |->BC_TSETR_Z:
4596 |.if X64
4597 | mov RBa, [BASE+RA*8]
4598 | mov [RC], RBa
4599 |.else
4600 | mov RB, [BASE+RA*8+4]
4601 | mov RA, [BASE+RA*8]
4602 | mov [RC+4], RB
4603 | mov [RC], RA
4604 |.endif
4605 | ins_next
4606 |
4607 |7: // Possible table write barrier for the value. Skip valiswhite check.
4608 | barrierback TAB:RB, RA
4609 | movzx RA, PC_RA // Restore RA.
4610 | jmp <2
4611 break;
5215 4612
5216 case BC_TSETM: 4613 case BC_TSETM:
5217 | ins_AD // RA = base (table at base-1), RD = num const (start index) 4614 | ins_AD // RA = base (table at base-1), RD = num const (start index)
@@ -5405,10 +4802,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5405 |.if DUALNUM 4802 |.if DUALNUM
5406 | mov dword [BASE+RA*8+4], LJ_TISNUM 4803 | mov dword [BASE+RA*8+4], LJ_TISNUM
5407 | mov dword [BASE+RA*8], RC 4804 | mov dword [BASE+RA*8], RC
5408 |.elif SSE
5409 | cvtsi2sd xmm0, RC
5410 |.else 4805 |.else
5411 | fild dword [BASE+RA*8-8] 4806 | cvtsi2sd xmm0, RC
5412 |.endif 4807 |.endif
5413 | // Copy array slot to returned value. 4808 | // Copy array slot to returned value.
5414 |.if X64 4809 |.if X64
@@ -5424,10 +4819,8 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5424 | // Return array index as a numeric key. 4819 | // Return array index as a numeric key.
5425 |.if DUALNUM 4820 |.if DUALNUM
5426 | // See above. 4821 | // See above.
5427 |.elif SSE
5428 | movsd qword [BASE+RA*8], xmm0
5429 |.else 4822 |.else
5430 | fstp qword [BASE+RA*8] 4823 | movsd qword [BASE+RA*8], xmm0
5431 |.endif 4824 |.endif
5432 | mov [BASE+RA*8-8], RC // Update control var. 4825 | mov [BASE+RA*8-8], RC // Update control var.
5433 |2: 4826 |2:
@@ -5440,9 +4833,6 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5440 | 4833 |
5441 |4: // Skip holes in array part. 4834 |4: // Skip holes in array part.
5442 | add RC, 1 4835 | add RC, 1
5443 |.if not (DUALNUM or SSE)
5444 | mov [BASE+RA*8-8], RC
5445 |.endif
5446 | jmp <1 4836 | jmp <1
5447 | 4837 |
5448 |5: // Traverse hash part. 4838 |5: // Traverse hash part.
@@ -5776,7 +5166,6 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5776 if (!vk) { 5166 if (!vk) {
5777 | cmp RB, LJ_TISNUM; jae ->vmeta_for 5167 | cmp RB, LJ_TISNUM; jae ->vmeta_for
5778 } 5168 }
5779 |.if SSE
5780 | movsd xmm0, qword FOR_IDX 5169 | movsd xmm0, qword FOR_IDX
5781 | movsd xmm1, qword FOR_STOP 5170 | movsd xmm1, qword FOR_STOP
5782 if (vk) { 5171 if (vk) {
@@ -5789,22 +5178,6 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5789 | ucomisd xmm1, xmm0 5178 | ucomisd xmm1, xmm0
5790 |1: 5179 |1:
5791 | movsd qword FOR_EXT, xmm0 5180 | movsd qword FOR_EXT, xmm0
5792 |.else
5793 | fld qword FOR_STOP
5794 | fld qword FOR_IDX
5795 if (vk) {
5796 | fadd qword FOR_STEP // nidx = idx + step
5797 | fst qword FOR_IDX
5798 | fst qword FOR_EXT
5799 | test RB, RB; js >1
5800 } else {
5801 | fst qword FOR_EXT
5802 | jl >1
5803 }
5804 | fxch // Swap lim/(n)idx if step non-negative.
5805 |1:
5806 | fcomparepp
5807 |.endif
5808 if (op == BC_FORI) { 5181 if (op == BC_FORI) {
5809 |.if DUALNUM 5182 |.if DUALNUM
5810 | jnb <7 5183 | jnb <7
@@ -5832,11 +5205,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5832 |2: 5205 |2:
5833 | ins_next 5206 | ins_next
5834 |.endif 5207 |.endif
5835 |.if SSE 5208 |
5836 |3: // Invert comparison if step is negative. 5209 |3: // Invert comparison if step is negative.
5837 | ucomisd xmm0, xmm1 5210 | ucomisd xmm0, xmm1
5838 | jmp <1 5211 | jmp <1
5839 |.endif
5840 break; 5212 break;
5841 5213
5842 case BC_ITERL: 5214 case BC_ITERL:
@@ -5874,7 +5246,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5874 | ins_A // RA = base, RD = target (loop extent) 5246 | ins_A // RA = base, RD = target (loop extent)
5875 | // Note: RA/RD is only used by trace recorder to determine scope/extent 5247 | // Note: RA/RD is only used by trace recorder to determine scope/extent
5876 | // This opcode does NOT jump, it's only purpose is to detect a hot loop. 5248 | // This opcode does NOT jump, it's only purpose is to detect a hot loop.
5877 |.if JIT 5249 |.if JIT
5878 | hotloop RB 5250 | hotloop RB
5879 |.endif 5251 |.endif
5880 | // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op. 5252 | // Fall through. Assumes BC_ILOOP follows and ins_A is a no-op.
@@ -5893,7 +5265,7 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
5893 | mov RDa, TRACE:RD->mcode 5265 | mov RDa, TRACE:RD->mcode
5894 | mov L:RB, SAVE_L 5266 | mov L:RB, SAVE_L
5895 | mov [DISPATCH+DISPATCH_GL(jit_base)], BASE 5267 | mov [DISPATCH+DISPATCH_GL(jit_base)], BASE
5896 | mov [DISPATCH+DISPATCH_GL(jit_L)], L:RB 5268 | mov [DISPATCH+DISPATCH_GL(tmpbuf.L)], L:RB
5897 | // Save additional callee-save registers only used in compiled code. 5269 | // Save additional callee-save registers only used in compiled code.
5898 |.if X64WIN 5270 |.if X64WIN
5899 | mov TMPQ, r12 5271 | mov TMPQ, r12
@@ -6060,9 +5432,10 @@ static void build_ins(BuildCtx *ctx, BCOp op, int defop)
6060 | // (lua_State *L, lua_CFunction f) 5432 | // (lua_State *L, lua_CFunction f)
6061 | call aword [DISPATCH+DISPATCH_GL(wrapf)] 5433 | call aword [DISPATCH+DISPATCH_GL(wrapf)]
6062 } 5434 }
6063 | set_vmstate INTERP
6064 | // nresults returned in eax (RD). 5435 | // nresults returned in eax (RD).
6065 | mov BASE, L:RB->base 5436 | mov BASE, L:RB->base
5437 | mov [DISPATCH+DISPATCH_GL(cur_L)], L:RB
5438 | set_vmstate INTERP
6066 | lea RA, [BASE+RD*8] 5439 | lea RA, [BASE+RD*8]
6067 | neg RA 5440 | neg RA
6068 | add RA, L:RB->top // RA = (L->top-(L->base+nresults))*8 5441 | add RA, L:RB->top // RA = (L->top-(L->base+nresults))*8
@@ -6382,15 +5755,21 @@ static void emit_asm_debug(BuildCtx *ctx)
6382 "LEFDEY:\n\n", fcsize); 5755 "LEFDEY:\n\n", fcsize);
6383 } 5756 }
6384#endif 5757#endif
6385#if LJ_64 5758#if !LJ_64
6386 fprintf(ctx->fp, "\t.subsections_via_symbols\n");
6387#else
6388 fprintf(ctx->fp, 5759 fprintf(ctx->fp,
6389 "\t.non_lazy_symbol_pointer\n" 5760 "\t.non_lazy_symbol_pointer\n"
6390 "L_lj_err_unwind_dwarf$non_lazy_ptr:\n" 5761 "L_lj_err_unwind_dwarf$non_lazy_ptr:\n"
6391 ".indirect_symbol _lj_err_unwind_dwarf\n" 5762 ".indirect_symbol _lj_err_unwind_dwarf\n"
6392 ".long 0\n"); 5763 ".long 0\n\n");
5764 fprintf(ctx->fp, "\t.section __IMPORT,__jump_table,symbol_stubs,pure_instructions+self_modifying_code,5\n");
5765 {
5766 const char *const *xn;
5767 for (xn = ctx->extnames; *xn; xn++)
5768 if (strncmp(*xn, LABEL_PREFIX, sizeof(LABEL_PREFIX)-1))
5769 fprintf(ctx->fp, "L_%s$stub:\n\t.indirect_symbol _%s\n\t.ascii \"\\364\\364\\364\\364\\364\"\n", *xn, *xn);
5770 }
6393#endif 5771#endif
5772 fprintf(ctx->fp, ".subsections_via_symbols\n");
6394 } 5773 }
6395 break; 5774 break;
6396#endif 5775#endif
diff --git a/src/xb1build.bat b/src/xb1build.bat
new file mode 100644
index 00000000..847e84a5
--- /dev/null
+++ b/src/xb1build.bat
@@ -0,0 +1,101 @@
1@rem Script to build LuaJIT with the Xbox One SDK.
2@rem Donated to the public domain.
3@rem
4@rem Open a "Visual Studio .NET Command Prompt" (64 bit host compiler)
5@rem Then cd to this directory and run this script.
6
7@if not defined INCLUDE goto :FAIL
8@if not defined DurangoXDK goto :FAIL
9
10@setlocal
11@echo ---- Host compiler ----
12@set LJCOMPILE=cl /nologo /c /MD /O2 /W3 /D_CRT_SECURE_NO_DEPRECATE /DLUAJIT_ENABLE_GC64
13@set LJLINK=link /nologo
14@set LJMT=mt /nologo
15@set DASMDIR=..\dynasm
16@set DASM=%DASMDIR%\dynasm.lua
17@set ALL_LIB=lib_base.c lib_math.c lib_bit.c lib_string.c lib_table.c lib_io.c lib_os.c lib_package.c lib_debug.c lib_jit.c lib_ffi.c
18
19%LJCOMPILE% host\minilua.c
20@if errorlevel 1 goto :BAD
21%LJLINK% /out:minilua.exe minilua.obj
22@if errorlevel 1 goto :BAD
23if exist minilua.exe.manifest^
24 %LJMT% -manifest minilua.exe.manifest -outputresource:minilua.exe
25
26@rem Error out for 64 bit host compiler
27@minilua
28@if not errorlevel 8 goto :FAIL
29
30@set DASMFLAGS=-D WIN -D FFI -D P64
31minilua %DASM% -LN %DASMFLAGS% -o host\buildvm_arch.h vm_x64.dasc
32@if errorlevel 1 goto :BAD
33
34%LJCOMPILE% /I "." /I %DASMDIR% /D_DURANGO host\buildvm*.c
35@if errorlevel 1 goto :BAD
36%LJLINK% /out:buildvm.exe buildvm*.obj
37@if errorlevel 1 goto :BAD
38if exist buildvm.exe.manifest^
39 %LJMT% -manifest buildvm.exe.manifest -outputresource:buildvm.exe
40
41buildvm -m peobj -o lj_vm.obj
42@if errorlevel 1 goto :BAD
43buildvm -m bcdef -o lj_bcdef.h %ALL_LIB%
44@if errorlevel 1 goto :BAD
45buildvm -m ffdef -o lj_ffdef.h %ALL_LIB%
46@if errorlevel 1 goto :BAD
47buildvm -m libdef -o lj_libdef.h %ALL_LIB%
48@if errorlevel 1 goto :BAD
49buildvm -m recdef -o lj_recdef.h %ALL_LIB%
50@if errorlevel 1 goto :BAD
51buildvm -m vmdef -o jit\vmdef.lua %ALL_LIB%
52@if errorlevel 1 goto :BAD
53buildvm -m folddef -o lj_folddef.h lj_opt_fold.c
54@if errorlevel 1 goto :BAD
55
56@echo ---- Cross compiler ----
57
58@set CWD=%cd%
59@call "%DurangoXDK%\xdk\DurangoVars.cmd" XDK
60@cd /D "%CWD%"
61@shift
62
63@set LJCOMPILE="cl" /nologo /c /W3 /GF /Gm- /GR- /GS- /Gy /openmp- /D_CRT_SECURE_NO_DEPRECATE /D_LIB /D_UNICODE /D_DURANGO
64@set LJLIB="lib" /nologo
65
66@if "%1"=="debug" (
67 @shift
68 @set LJCOMPILE=%LJCOMPILE% /Zi /MDd /Od
69 @set LJLINK=%LJLINK% /debug
70) else (
71 @set LJCOMPILE=%LJCOMPILE% /MD /O2 /DNDEBUG
72)
73
74@if "%1"=="amalg" goto :AMALG
75%LJCOMPILE% /DLUA_BUILD_AS_DLL lj_*.c lib_*.c
76@if errorlevel 1 goto :BAD
77%LJLIB% /OUT:luajit.lib lj_*.obj lib_*.obj
78@if errorlevel 1 goto :BAD
79@goto :NOAMALG
80:AMALG
81%LJCOMPILE% /DLUA_BUILD_AS_DLL ljamalg.c
82@if errorlevel 1 goto :BAD
83%LJLIB% /OUT:luajit.lib ljamalg.obj lj_vm.obj
84@if errorlevel 1 goto :BAD
85:NOAMALG
86
87@del *.obj *.manifest minilua.exe buildvm.exe
88@echo.
89@echo === Successfully built LuaJIT for Xbox One ===
90
91@goto :END
92:BAD
93@echo.
94@echo *******************************************************
95@echo *** Build FAILED -- Please check the error messages ***
96@echo *******************************************************
97@goto :END
98:FAIL
99@echo To run this script you must open a "Visual Studio .NET Command Prompt"
100@echo (64 bit host compiler). The Xbox One SDK must be installed, too.
101:END