-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlvm.cpp
More file actions
1537 lines (1436 loc) · 50.1 KB
/
lvm.cpp
File metadata and controls
1537 lines (1436 loc) · 50.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** $Id: lvm.c $
** Lua virtual machine
** See Copyright Notice in lua.h
*/
#define lvm_c
#define LUA_CORE
#include "lprefix.h"
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lvm.h"
/*
** By default, use jump tables in the main interpreter loop on gcc
** and compatible compilers.
**
** PERFORMANCE NOTE: Jump tables (computed goto) provide faster dispatch
** in the VM's main interpreter loop compared to a switch statement. GCC
** and Clang can generate a single indirect jump instead of cascading
** comparisons, improving instruction cache utilization and branch prediction.
*/
#if !defined(LUA_USE_JUMPTABLE)
#if defined(__GNUC__)
#define LUA_USE_JUMPTABLE 1
#else
#define LUA_USE_JUMPTABLE 0
#endif
#endif
/*
** Limit for table tag-method (metamethod) chains to prevent infinite loops.
** When __index or __newindex metamethods redirect to other tables/objects,
** this limit ensures we don't loop forever if there's a cycle in the chain.
*/
inline constexpr int MAXTAGLOOP = 2000;
/*
** ===========================================================================
** Type conversion functions
** ===========================================================================
** Moved to lvm_conversion.cpp:
** - l_strton() - String to number conversion
** - luaV_tonumber_() - Value to float conversion
** - luaV_flttointeger() - Float to integer with rounding
** - luaV_tointegerns() - Value to integer (no string coercion)
** - luaV_tointeger() - Value to integer (with string coercion)
** - TValue::toNumber() - TValue conversion methods
** - TValue::toInteger()
** - TValue::toIntegerNoString()
** ===========================================================================
*/
/*
** ===========================================================================
** For-loop operations (lua_State methods)
** ===========================================================================
** Moved to lvm_loops.cpp:
** - lua_State::forLimit() - Convert for-loop limit to integer
** - lua_State::forPrep() - Prepare numerical for loop (OP_FORPREP)
** - lua_State::floatForLoop() - Execute float for-loop step
** ===========================================================================
*/
/*
** ===========================================================================
** Table access operations
** ===========================================================================
** Moved to lvm_table.cpp:
** - luaV_finishget() - Finish table access with __index metamethod
** - luaV_finishset() - Finish table assignment with __newindex metamethod
** ===========================================================================
*/
/*
** ===========================================================================
** Comparison operations
** ===========================================================================
** Moved to lvm_comparison.cpp:
** - l_strcmp() - String comparison with locale support
** - LTintfloat(), LEintfloat() - Integer vs float comparisons
** - LTfloatint(), LEfloatint() - Float vs integer comparisons
** - lua_State::lessThanOthers(), lua_State::lessEqualOthers()
** - luaV_lessthan(), luaV_lessequal() - Main comparison operations
** - luaV_equalobj() - Equality comparison with metamethods
** ===========================================================================
*/
/*
** ===========================================================================
** String concatenation and length operations
** ===========================================================================
** Moved to lvm_string.cpp:
** - tostring() - Ensure value is a string (with coercion)
** - isemptystr() - Check if string is empty
** - copy2buff() - Copy strings from stack to buffer
** - luaV_concat() - Main concatenation operation
** - luaV_objlen() - Length operator (#) implementation
** ===========================================================================
*/
/*
** create a new Lua closure, push it in the stack, and initialize
** its upvalues.
*/
void lua_State::pushClosure(Proto *p, UpVal **encup, StkId base, StkId ra) {
int nup = p->getUpvaluesSize();
Upvaldesc *uv = p->getUpvalues();
int i;
LClosure *ncl = LClosure::create(this, nup);
ncl->setProto(p);
setclLvalue2s(this, ra, ncl); /* anchor new closure in stack */
for (i = 0; i < nup; i++) { /* fill in its upvalues */
if (uv[i].isInStack()) /* upvalue refers to local variable? */
ncl->setUpval(i, luaF_findupval(this, base + uv[i].getIndex()));
else /* get upvalue from enclosing function */
ncl->setUpval(i, encup[uv[i].getIndex()]);
luaC_objbarrier(this, ncl, ncl->getUpval(i));
}
}
/*
** finish execution of an opcode interrupted by a yield
*/
void luaV_finishOp (lua_State *L) {
CallInfo *ci = L->getCI();
StkId base = ci->funcRef().p + 1;
Instruction inst = *(ci->getSavedPC() - 1); /* interrupted instruction */
OpCode op = static_cast<OpCode>(InstructionView(inst).opcode());
switch (op) { /* finish its execution */
case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
*s2v(base + InstructionView(*(ci->getSavedPC() - 2)).a()) = *s2v(--L->getTop().p);
break;
}
case OP_UNM: case OP_BNOT: case OP_LEN:
case OP_GETTABUP: case OP_GETTABLE: case OP_GETI:
case OP_GETFIELD: case OP_SELF: {
*s2v(base + InstructionView(inst).a()) = *s2v(--L->getTop().p);
break;
}
case OP_LT: case OP_LE:
case OP_LTI: case OP_LEI:
case OP_GTI: case OP_GEI:
case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */
lua_assert(L->getTop().p > L->getStack().p); /* ensure stack not empty */
int res = !l_isfalse(s2v(L->getTop().p - 1));
L->getStackSubsystem().pop();
lua_assert(InstructionView(*ci->getSavedPC()).opcode() == OP_JMP);
if (res != InstructionView(inst).k()) /* condition failed? */
ci->setSavedPC(ci->getSavedPC() + 1); /* skip jump instruction */
break;
}
case OP_CONCAT: {
StkId top = L->getTop().p - 1; /* top when 'luaT_tryconcatTM' was called */
int a = InstructionView(inst).a(); /* first element to concatenate */
lua_assert(top >= base + a + 1); /* ensure valid range for subtraction */
lua_assert(top >= L->getStack().p + 2); /* ensure top-2 is valid */
int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */
*s2v(top - 2) = *s2v(top); /* put TM result in proper position (operator=) */
L->getStackSubsystem().setTopPtr(top - 1); /* top is one after last element (at top-2) */
luaV_concat(L, total); /* concat them (may yield again) */
break;
}
case OP_CLOSE: { /* yielded closing variables */
ci->setSavedPC(ci->getSavedPC() - 1); /* repeat instruction to close other vars. */
break;
}
case OP_RETURN: { /* yielded closing variables */
StkId ra = base + InstructionView(inst).a();
/* adjust top to signal correct number of returns, in case the
return is "up to top" ('isIT') */
L->getStackSubsystem().setTopPtr(ra + ci->getNRes());
/* repeat instruction to close other vars. and complete the return */
ci->setSavedPC(ci->getSavedPC() - 1);
break;
}
default: {
/* only these other opcodes can yield */
lua_assert(op == OP_TFORCALL || op == OP_CALL ||
op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||
op == OP_SETI || op == OP_SETFIELD);
break;
}
}
}
/*
** {==================================================================
** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'
**
** All these macros are to be used exclusively inside the main
** iterpreter loop (function luaV_execute) and may access directly
** the local variables of that function (L, i, pc, ci, etc.).
** ===================================================================
*/
inline constexpr lua_Integer l_addi(lua_State*, lua_Integer a, lua_Integer b) noexcept {
return intop(+, a, b);
}
inline constexpr lua_Integer l_subi(lua_State*, lua_Integer a, lua_Integer b) noexcept {
return intop(-, a, b);
}
inline constexpr lua_Integer l_muli(lua_State*, lua_Integer a, lua_Integer b) noexcept {
return intop(*, a, b);
}
inline constexpr lua_Integer l_band(lua_Integer a, lua_Integer b) noexcept {
return intop(&, a, b);
}
inline constexpr lua_Integer l_bor(lua_Integer a, lua_Integer b) noexcept {
return intop(|, a, b);
}
inline constexpr lua_Integer l_bxor(lua_Integer a, lua_Integer b) noexcept {
return intop(^, a, b);
}
inline constexpr bool l_lti(lua_Integer a, lua_Integer b) noexcept {
return a < b;
}
inline constexpr bool l_lei(lua_Integer a, lua_Integer b) noexcept {
return a <= b;
}
inline constexpr bool l_gti(lua_Integer a, lua_Integer b) noexcept {
return a > b;
}
inline constexpr bool l_gei(lua_Integer a, lua_Integer b) noexcept {
return a >= b;
}
/*
** NOTE: The VM operation macros (op_arithI, op_arith, op_arithK, op_bitwise, etc.)
** have been converted to lambdas defined inside luaV_execute() for better type safety
** and debuggability. See lines 1378-1514 for the lambda implementations.
*/
/* }================================================================== */
/*
** {==================================================================
** Function 'luaV_execute': main interpreter loop
** ===================================================================
**
** ARCHITECTURE OVERVIEW:
** This is the heart of the Lua VM - a register-based bytecode interpreter.
** Unlike stack-based VMs (like the JVM or Python's CPython), Lua uses
** registers for local variables and intermediate values, reducing stack
** manipulation overhead.
**
** KEY DESIGN DECISIONS:
** 1. Register-based: Instructions reference register indices (A, B, C fields)
** rather than implicitly using a stack. This reduces instruction count
** and improves cache locality.
**
** 2. Inline dispatch: The main loop uses either computed goto (jump tables)
** or a large switch statement to dispatch instructions. Computed goto is
** ~10-30% faster on modern CPUs due to better branch prediction.
**
** 3. Hot-path optimization: Common operations (table access, arithmetic on
** integers) have fast paths inlined directly in the VM loop to avoid
** function call overhead.
**
** 4. Protect macros: Operations that can raise errors or trigger GC use
** Protect() macros to save VM state (pc, top) before the operation.
** This enables proper stack unwinding via C++ exceptions.
**
** 5. Trap mechanism: The 'trap' variable tracks whether hooks are enabled
** or stack reallocation is needed. Checked before each instruction fetch
** to handle debugger breakpoints and step-through.
**
** PERFORMANCE CRITICAL: This function processes billions of instructions
** per second. Every cycle counts. Changes here should be benchmarked.
*/
/*
** some macros for common tasks in 'luaV_execute'
*/
/*
** Register and constant access functions (converted from macros to lambdas)
**
** RA, RB, RC: Convert instruction field to stack index (StkId pointer)
** vRA, vRB, vRC: Get TValue* from stack index (s2v = stack-to-value)
** KB, KC: Get constant from constant table using instruction field
** RKC: Get either register or constant depending on 'k' bit in instruction
**
** Example instruction format (iABC):
** OP_ADD A B C means: R(A) := R(B) + R(C)
** OP_ADDK A B C means: R(A) := R(B) + K(C) [if k bit set]
**
** NOTE: These have been converted to lambdas defined inside luaV_execute()
** for better type safety and debuggability. See lines 1274-1301 for implementations.
*/
/*
** State management functions (converted from macros to lambdas)
**
** updatetrap(ci): Update local trap variable from CallInfo
** updatebase(ci): Update local base pointer from CallInfo
** updatestack(ra,ci,i): Conditionally update base and ra if trap is set
**
** NOTE: These have been converted to lambdas defined inside luaV_execute()
** for better type safety. See lines ~1304-1323 for implementations.
*/
/*
** Control flow functions (converted from macros to lambdas)
**
** dojump(ci,i,e): Execute a jump instruction. The 'updatetrap' allows signals
** to stop tight loops. (Without it, the local copy of 'trap'
** could never change.)
** donextjump(ci): For test instructions, execute the jump instruction that follows it
** docondjump(cond,ci,i): Conditional jump - skip next instruction if 'cond' is not
** what was expected (parameter 'k'), else do next instruction,
** which must be a jump.
**
** NOTE: These have been converted to lambdas defined inside luaV_execute()
** for better type safety. See lines ~1331-1345 for implementations.
*/
/*
** Correct global 'pc' (program counter).
** The local 'pc' variable is kept in a register for performance. Before any
** operation that might throw an exception, we must save it to the CallInfo
** so stack unwinding can report the correct error location.
**
** savepc(ci): Save local pc to CallInfo
** savestate(L,ci): Save both pc and top to CallInfo and lua_State
**
** NOTE: These have been converted to lambdas defined inside luaV_execute()
** for better type safety. See lines ~1317-1323 for implementations.
**
** EXCEPTION HANDLING: This implementation uses C++ exceptions instead of
** setjmp/longjmp. When an error is thrown, the exception handler needs
** accurate pc and top values to:
** 1. Report the correct line number in error messages
** 2. Properly unwind the stack to the correct depth
** 3. Close any to-be-closed variables at the right stack level
*/
/*
** function executed during Lua functions at points where the
** function can yield.
*/
#if !defined(luai_threadyield)
inline void luai_threadyield(lua_State* L) noexcept {
lua_unlock(L);
lua_lock(L);
}
#endif
/*
** Check if garbage collection is needed and yield thread if necessary.
**
** 'c' is the limit of live values in the stack (typically L->top or ci->top)
**
** PERFORMANCE vs CORRECTNESS: GC is expensive, so we only check conditionally
** (luaC_condGC) rather than forcing collection. The GC uses a debt-based system
** to determine when collection is needed.
**
** The macro saves state before GC (because GC can trigger __gc metamethods that
** might throw errors), then updates trap after (because GC might have changed hooks).
**
** luai_threadyield allows the OS to schedule other threads. Without it, tight
** loops could starve other threads on single-core systems.
*/
#define checkGC(L,c) \
{ luaC_condGC(L, (savepc(ci), L->getStackSubsystem().setTopPtr(c)), \
updatetrap(ci)); \
luai_threadyield(L); }
#define vmdispatch(o) switch(o)
#define vmcase(l) case l:
#define vmbreak break
/*
** Execute a Lua function (LClosure) starting at the given CallInfo.
**
** PARAMETERS:
** - L: Lua state (contains stack, current CI, and global state)
** - ci: CallInfo for the function being executed
**
** LOCAL VARIABLES (kept in registers for performance):
** - cl: Current LClosure (Lua function) being executed
** - k: Constant table for current function (cl->proto->k)
** - base: Base of current stack frame (points to function's first register)
** - pc: Program counter (points to next instruction to execute)
** - trap: Cached copy of hook mask (0 if no hooks, non-zero if hooks enabled)
**
** EXECUTION FLOW:
** startfunc: Initialize for a new function call
** returning: Return from a nested call, continue in current function
** ret: Common return point for all return opcodes
**
** The function continues executing until:
** 1. A return instruction is executed and ci has CIST_FRESH flag (new C frame)
** 2. An error is thrown (C++ exception)
** 3. The function yields (coroutine suspend)
*/
void luaV_execute (lua_State *L, CallInfo *ci) {
LClosure *cl;
TValue *k;
StkId base;
const Instruction *pc;
int trap;
#if LUA_USE_JUMPTABLE
#include "ljumptab.h"
#endif
/* Convert operation macros to lambdas for better type safety and debuggability.
* These lambdas capture local variables (L, pc, base, k, etc.) automatically.
* Note: User has explicitly allowed performance regression for this conversion.
*/
// Undefine operation macros to avoid naming conflicts
#undef op_arithI
#undef op_arithf_aux
#undef op_arithf
#undef op_arithfK
#undef op_arith_aux
#undef op_arith
#undef op_arithK
#undef op_bitwiseK
#undef op_bitwise
#undef op_order
#undef op_orderI
// Undefine register access macros to avoid naming conflicts
#undef RA
#undef vRA
#undef RB
#undef vRB
#undef KB
#undef RC
#undef vRC
#undef KC
#undef RKC
// Undefine state management macros to avoid naming conflicts
#undef updatetrap
#undef updatebase
#undef updatestack
#undef savepc
#undef savestate
// Undefine control flow macros to avoid naming conflicts
#undef dojump
#undef donextjump
#undef docondjump
// Undefine exception handling macros to avoid naming conflicts
#undef Protect
#undef ProtectNT
#undef halfProtect
#undef checkGC
// Undefine VM dispatch macro to avoid naming conflict
#undef vmfetch
// Register access lambdas (defined before operation lambdas that use them)
auto RA = [&](Instruction i) -> StkId {
return base + InstructionView(i).a();
};
auto vRA = [&](Instruction i) -> TValue* {
return s2v(base + InstructionView(i).a());
};
[[maybe_unused]] auto RB = [&](Instruction i) -> StkId {
return base + InstructionView(i).b();
};
auto vRB = [&](Instruction i) -> TValue* {
return s2v(base + InstructionView(i).b());
};
auto KB = [&](Instruction i) -> TValue* {
return k + InstructionView(i).b();
};
[[maybe_unused]] auto RC = [&](Instruction i) -> StkId {
return base + InstructionView(i).c();
};
auto vRC = [&](Instruction i) -> TValue* {
return s2v(base + InstructionView(i).c());
};
auto KC = [&](Instruction i) -> TValue* {
return k + InstructionView(i).c();
};
auto RKC = [&](Instruction i) -> TValue* {
return InstructionView(i).testk() ? (k + InstructionView(i).c()) : s2v(base + InstructionView(i).c());
};
// State management lambdas
auto updatetrap = [&](CallInfo* ci_arg) {
trap = ci_arg->getTrap();
};
auto updatebase = [&](CallInfo* ci_arg) {
base = ci_arg->funcRef().p + 1;
};
auto updatestack = [&](StkId& ra_arg, CallInfo* ci_arg, Instruction inst) {
if (l_unlikely(trap)) {
updatebase(ci_arg);
ra_arg = RA(inst);
}
};
auto savepc = [&](CallInfo* ci_arg) {
ci_arg->setSavedPC(pc);
};
auto savestate = [&](lua_State* L_arg, CallInfo* ci_arg) {
savepc(ci_arg);
L_arg->getStackSubsystem().setTopPtr(ci_arg->topRef().p);
};
// Control flow lambdas
auto dojump = [&](CallInfo* ci_arg, Instruction inst, int e) {
pc += InstructionView(inst).sj() + e;
updatetrap(ci_arg);
};
auto donextjump = [&](CallInfo* ci_arg) {
Instruction ni = *pc;
dojump(ci_arg, ni, 1);
};
auto docondjump = [&](int cond, CallInfo* ci_arg, Instruction inst) {
if (cond != InstructionView(inst).k())
pc++;
else
donextjump(ci_arg);
};
// Exception handling lambdas
auto Protect = [&](auto&& expr) {
savestate(L, ci);
expr();
updatetrap(ci);
};
auto ProtectNT = [&](auto&& expr) {
savepc(ci);
expr();
updatetrap(ci);
};
auto halfProtect = [&](auto&& expr) {
savestate(L, ci);
expr();
};
auto checkGC = [&](lua_State* L_arg, StkId c_val) {
luaC_condGC(L_arg,
(savepc(ci), L_arg->getStackSubsystem().setTopPtr(c_val)),
updatetrap(ci));
luai_threadyield(L_arg);
};
// Lambda: Arithmetic with immediate operand
auto op_arithI = [&](auto iop, auto fop, Instruction i) {
TValue *ra = vRA(i);
TValue *v1 = vRB(i);
int imm = InstructionView(i).sc();
if (ttisinteger(v1)) {
lua_Integer iv1 = ivalue(v1);
pc++; setivalue(ra, iop(L, iv1, imm));
}
else if (ttisfloat(v1)) {
lua_Number nb = fltvalue(v1);
lua_Number fimm = cast_num(imm);
pc++; setfltvalue(ra, fop(L, nb, fimm));
}
};
// Lambda: Auxiliary function for arithmetic operations over floats
auto op_arithf_aux = [&](const TValue *v1, const TValue *v2, auto fop, Instruction i) {
lua_Number n1, n2;
if (tonumberns(v1, n1) && tonumberns(v2, n2)) {
StkId ra = RA(i);
pc++; setfltvalue(s2v(ra), fop(L, n1, n2));
}
};
// Lambda: Arithmetic operations over floats with register operands
auto op_arithf = [&](auto fop, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = vRC(i);
op_arithf_aux(v1, v2, fop, i);
};
// Lambda: Arithmetic operations with K operands for floats
auto op_arithfK = [&](auto fop, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = KC(i);
lua_assert(ttisnumber(v2));
op_arithf_aux(v1, v2, fop, i);
};
// Lambda: Auxiliary for arithmetic operations over integers and floats
auto op_arith_aux = [&](const TValue *v1, const TValue *v2, auto iop, auto fop, Instruction i) {
if (ttisinteger(v1) && ttisinteger(v2)) {
StkId ra = RA(i);
lua_Integer i1 = ivalue(v1);
lua_Integer i2 = ivalue(v2);
pc++; setivalue(s2v(ra), iop(L, i1, i2));
}
else {
op_arithf_aux(v1, v2, fop, i);
}
};
// Lambda: Arithmetic operations with register operands
auto op_arith = [&](auto iop, auto fop, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = vRC(i);
op_arith_aux(v1, v2, iop, fop, i);
};
// Lambda: Arithmetic operations with K operands
auto op_arithK = [&](auto iop, auto fop, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = KC(i);
lua_assert(ttisnumber(v2));
op_arith_aux(v1, v2, iop, fop, i);
};
// Lambda: Bitwise operations with constant operand
auto op_bitwiseK = [&](auto op, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = KC(i);
lua_Integer i1;
lua_Integer i2 = ivalue(v2);
if (tointegerns(v1, &i1)) {
StkId ra = RA(i);
pc++; setivalue(s2v(ra), op(i1, i2));
}
};
// Lambda: Bitwise operations with register operands
auto op_bitwise = [&](auto op, Instruction i) {
TValue *v1 = vRB(i);
TValue *v2 = vRC(i);
lua_Integer i1, i2;
if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) {
StkId ra = RA(i);
pc++; setivalue(s2v(ra), op(i1, i2));
}
};
// Lambda: Order operations with register operands
// Note: Cannot use operators as template parameters, so we pass comparator function objects
auto op_order = [&](auto cmp, auto other, Instruction i) {
TValue *ra = vRA(i);
int cond;
TValue *rb = vRB(i);
if (ttisnumber(ra) && ttisnumber(rb))
cond = cmp(ra, rb); // Use comparator function object
else
Protect([&]() { cond = other(L, ra, rb); });
docondjump(cond, ci, i);
};
// Lambda: Order operations with immediate operand
auto op_orderI = [&](auto opi, auto opf, int inv, TMS tm, Instruction i) {
TValue *ra = vRA(i);
int cond;
int im = InstructionView(i).sb();
if (ttisinteger(ra))
cond = opi(ivalue(ra), im);
else if (ttisfloat(ra)) {
lua_Number fa = fltvalue(ra);
lua_Number fim = cast_num(im);
cond = opf(fa, fim);
}
else {
int isf = InstructionView(i).c();
Protect([&]() { cond = luaT_callorderiTM(L, ra, im, inv, isf, tm); });
}
docondjump(cond, ci, i);
};
// Comparator function objects for op_order (operators cannot be passed as template params)
auto cmp_lt = [](const TValue* a, const TValue* b) { return *a < *b; };
auto cmp_le = [](const TValue* a, const TValue* b) { return *a <= *b; };
// "Other" comparison lambdas for op_order (non-numeric comparisons)
auto other_lt = [&](lua_State* L_arg, const TValue* l, const TValue* r) {
return L_arg->lessThanOthers(l, r);
};
auto other_le = [&](lua_State* L_arg, const TValue* l, const TValue* r) {
return L_arg->lessEqualOthers(l, r);
};
startfunc:
trap = L->getHookMask();
returning: /* trap already set */
cl = ci->getFunc();
k = cl->getProto()->getConstants();
pc = ci->getSavedPC();
if (l_unlikely(trap))
trap = luaG_tracecall(L);
base = ci->funcRef().p + 1;
Instruction i; /* instruction being executed (moved outside loop for lambda capture) */
// VM instruction fetch lambda
auto vmfetch = [&]() {
if (l_unlikely(trap)) { /* stack reallocation or hooks? */
trap = luaG_traceexec(L, pc); /* handle hooks */
updatebase(ci); /* correct stack */
}
i = *(pc++);
};
/* main loop of interpreter */
for (;;) {
vmfetch();
lua_assert(base == ci->funcRef().p + 1);
lua_assert(base <= L->getTop().p && L->getTop().p <= L->getStackLast().p);
/* for tests, invalidate top for instructions not expecting it */
lua_assert(luaP_isIT(i) || (cast_void(L->getStackSubsystem().setTopPtr(base)), 1));
vmdispatch (InstructionView(i).opcode()) {
vmcase(OP_MOVE) {
StkId ra = RA(i);
*s2v(ra) = *s2v(RB(i)); /* Use operator= for move */
vmbreak;
}
vmcase(OP_LOADI) {
StkId ra = RA(i);
lua_Integer b = InstructionView(i).sbx();
setivalue(s2v(ra), b);
vmbreak;
}
vmcase(OP_LOADF) {
StkId ra = RA(i);
int b = InstructionView(i).sbx();
setfltvalue(s2v(ra), cast_num(b));
vmbreak;
}
vmcase(OP_LOADK) {
StkId ra = RA(i);
TValue *rb = k + InstructionView(i).bx();
L->getStackSubsystem().setSlot(ra, rb);
vmbreak;
}
vmcase(OP_LOADKX) {
StkId ra = RA(i);
TValue *rb;
rb = k + InstructionView(*pc).ax(); pc++;
L->getStackSubsystem().setSlot(ra, rb);
vmbreak;
}
vmcase(OP_LOADFALSE) {
StkId ra = RA(i);
setbfvalue(s2v(ra));
vmbreak;
}
vmcase(OP_LFALSESKIP) {
StkId ra = RA(i);
setbfvalue(s2v(ra));
pc++; /* skip next instruction */
vmbreak;
}
vmcase(OP_LOADTRUE) {
StkId ra = RA(i);
setbtvalue(s2v(ra));
vmbreak;
}
vmcase(OP_LOADNIL) {
StkId ra = RA(i);
int b = InstructionView(i).b();
do {
setnilvalue(s2v(ra++));
} while (b--);
vmbreak;
}
vmcase(OP_GETUPVAL) {
StkId ra = RA(i);
int b = InstructionView(i).b();
L->getStackSubsystem().setSlot(ra, cl->getUpval(b)->getVP());
vmbreak;
}
vmcase(OP_SETUPVAL) {
StkId ra = RA(i);
UpVal *uv = cl->getUpval(InstructionView(i).b());
*uv->getVP() = *s2v(ra);
luaC_barrier(L, uv, s2v(ra));
vmbreak;
}
vmcase(OP_GETTABUP) {
StkId ra = RA(i);
TValue *upval = cl->getUpval(InstructionView(i).b())->getVP();
TValue *rc = KC(i);
TString *key = tsvalue(rc); /* key must be a short string */
lu_byte tag;
tag = luaV_fastget(upval, key, s2v(ra), luaH_getshortstr);
if (tagisempty(tag))
Protect([&]() { luaV_finishget(L, upval, rc, ra, tag); });
vmbreak;
}
vmcase(OP_GETTABLE) {
StkId ra = RA(i);
TValue *rb = vRB(i);
TValue *rc = vRC(i);
lu_byte tag;
if (ttisinteger(rc)) { /* fast track for integers? */
luaV_fastgeti(rb, ivalue(rc), s2v(ra), tag);
}
else
tag = luaV_fastget(rb, rc, s2v(ra), luaH_get);
if (tagisempty(tag))
Protect([&]() { luaV_finishget(L, rb, rc, ra, tag); });
vmbreak;
}
vmcase(OP_GETI) {
StkId ra = RA(i);
TValue *rb = vRB(i);
int c = InstructionView(i).c();
lu_byte tag;
luaV_fastgeti(rb, c, s2v(ra), tag);
if (tagisempty(tag)) {
TValue key;
setivalue(&key, c);
Protect([&]() { luaV_finishget(L, rb, &key, ra, tag); });
}
vmbreak;
}
vmcase(OP_GETFIELD) {
StkId ra = RA(i);
TValue *rb = vRB(i);
TValue *rc = KC(i);
TString *key = tsvalue(rc); /* key must be a short string */
lu_byte tag;
tag = luaV_fastget(rb, key, s2v(ra), luaH_getshortstr);
if (tagisempty(tag))
Protect([&]() { luaV_finishget(L, rb, rc, ra, tag); });
vmbreak;
}
vmcase(OP_SETTABUP) {
int hres;
TValue *upval = cl->getUpval(InstructionView(i).a())->getVP();
TValue *rb = KB(i);
TValue *rc = RKC(i);
TString *key = tsvalue(rb); /* key must be a short string */
hres = luaV_fastset(upval, key, rc, luaH_psetshortstr);
if (hres == HOK)
luaV_finishfastset(L, upval, rc);
else
Protect([&]() { luaV_finishset(L, upval, rb, rc, hres); });
vmbreak;
}
vmcase(OP_SETTABLE) {
StkId ra = RA(i);
int hres;
TValue *rb = vRB(i); /* key (table is in 'ra') */
TValue *rc = RKC(i); /* value */
if (ttisinteger(rb)) { /* fast track for integers? */
luaV_fastseti(s2v(ra), ivalue(rb), rc, hres);
}
else {
hres = luaV_fastset(s2v(ra), rb, rc, luaH_pset);
}
if (hres == HOK)
luaV_finishfastset(L, s2v(ra), rc);
else
Protect([&]() { luaV_finishset(L, s2v(ra), rb, rc, hres); });
vmbreak;
}
vmcase(OP_SETI) {
StkId ra = RA(i);
int hres;
int b = InstructionView(i).b();
TValue *rc = RKC(i);
luaV_fastseti(s2v(ra), b, rc, hres);
if (hres == HOK)
luaV_finishfastset(L, s2v(ra), rc);
else {
TValue key;
setivalue(&key, b);
Protect([&]() { luaV_finishset(L, s2v(ra), &key, rc, hres); });
}
vmbreak;
}
vmcase(OP_SETFIELD) {
StkId ra = RA(i);
int hres;
TValue *rb = KB(i);
TValue *rc = RKC(i);
TString *key = tsvalue(rb); /* key must be a short string */
hres = luaV_fastset(s2v(ra), key, rc, luaH_psetshortstr);
if (hres == HOK)
luaV_finishfastset(L, s2v(ra), rc);
else
Protect([&]() { luaV_finishset(L, s2v(ra), rb, rc, hres); });
vmbreak;
}
vmcase(OP_NEWTABLE) {
StkId ra = RA(i);
unsigned b = cast_uint(InstructionView(i).vb()); /* log2(hash size) + 1 */
unsigned c = cast_uint(InstructionView(i).vc()); /* array size */
Table *t;
if (b > 0)
b = 1u << (b - 1); /* hash size is 2^(b - 1) */
if (InstructionView(i).testk()) { /* non-zero extra argument? */
lua_assert(InstructionView(*pc).ax() != 0);
/* add it to array size */
c += cast_uint(InstructionView(*pc).ax()) * (MAXARG_vC + 1);
}
pc++; /* skip extra argument */
L->getStackSubsystem().setTopPtr(ra + 1); /* correct top in case of emergency GC */
t = luaH_new(L); /* memory allocation */
sethvalue2s(L, ra, t);
if (b != 0 || c != 0)
luaH_resize(L, t, c, b); /* idem */
checkGC(L, ra + 1);
vmbreak;
}
vmcase(OP_SELF) {
StkId ra = RA(i);
lu_byte tag;
TValue *rb = vRB(i);
TValue *rc = KC(i);
TString *key = tsvalue(rc); /* key must be a short string */
L->getStackSubsystem().setSlot(ra + 1, rb);
tag = luaV_fastget(rb, key, s2v(ra), luaH_getshortstr);
if (tagisempty(tag))
Protect([&]() { luaV_finishget(L, rb, rc, ra, tag); });
vmbreak;
}
vmcase(OP_ADDI) {
op_arithI(l_addi, luai_numadd, i);
vmbreak;
}
vmcase(OP_ADDK) {
op_arithK(l_addi, luai_numadd, i);
vmbreak;
}
vmcase(OP_SUBK) {
op_arithK(l_subi, luai_numsub, i);
vmbreak;
}
vmcase(OP_MULK) {
op_arithK(l_muli, luai_nummul, i);
vmbreak;
}
vmcase(OP_MODK) {
savestate(L, ci); /* in case of division by 0 */
op_arithK(luaV_mod, luaV_modf, i);
vmbreak;
}
vmcase(OP_POWK) {
op_arithfK(luai_numpow, i);
vmbreak;
}
vmcase(OP_DIVK) {
op_arithfK(luai_numdiv, i);
vmbreak;
}
vmcase(OP_IDIVK) {
savestate(L, ci); /* in case of division by 0 */
op_arithK(luaV_idiv, luai_numidiv, i);