forked from coder-mike/microvium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
microvium.c
6498 lines (5620 loc) · 234 KB
/
microvium.c
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
// Copyright 2020 Michael Hunter. Part of the Microvium project. Links to full code at https://microvium.com for license details.
/*
* Microvium Bytecode Interpreter
*
* Version: {{version}}
*
* This file contains the Microvium virtual machine C implementation.
*
* The key functions are mvm_restore() and mvm_call(), which perform the
* initialization and run loop respectively.
*
* I've written Microvium in C because lots of embedded projects for small
* processors are written in pure C, and so integration for them will be easier.
* Also, there are a surprising number of C++ compilers in the embedded world
* that deviate from the standard, and I don't want to be testing on all of them
* individually.
*
* For the moment, I'm keeping Microvium all in one file for usability. Users
* can treat this file as a black box that contains the VM, and there's only one
* file they need to have built into their project in order to have Microvium
* running. The build process also pulls in the dependent header files, so
* there's only one header file and it's the one that users of Microvium need to
* see. Certain compilers and optimization settings also do a better job when
* related functions are co-located the same compilation unit.
*
* User-facing functions and definitions are all prefixed with `mvm_` to
* namespace them separately from other functions in their project, some of
* which use the prefix `vm_` and some without a prefix. (TODO: this should be
* consolidated)
*/
#include "microvium.h"
#include <ctype.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdio.h> // Note: only uses snprintf from stdio.h
#include "microvium_internals.h"
#if MVM_IMPORT_MATH
#include "math.h"
#endif
/**
* Public API to call into the VM to run the given function with the given
* arguments (also contains the run loop).
*
* Control returns from `mvm_call` either when it hits an error or when it
* executes a RETURN instruction within the called function.
*
* If the return code is MVM_E_UNCAUGHT_EXCEPTION then `out_result` points to the exception.
*/
TeError mvm_call(VM* vm, Value targetFunc, Value* out_result, Value* args, uint8_t argCount) {
/*
Note: when microvium calls the host, only `mvm_call` is on the call stack.
This is for the objective of being lightweight. Each stack frame in an
embedded environment can be quite expensive in terms of memory because of all
the general-purpose registers that need to be preserved.
*/
// -------------------------------- Definitions -----------------------------
#define CACHE_REGISTERS() do { \
VM_ASSERT(vm, reg->usingCachedRegisters == false); \
VM_EXEC_SAFE_MODE(reg->usingCachedRegisters = true;) \
lpProgramCounter = reg->lpProgramCounter; \
pFrameBase = reg->pFrameBase; \
pStackPointer = reg->pStackPointer; \
} while (false)
#define FLUSH_REGISTER_CACHE() do { \
VM_ASSERT(vm, reg->usingCachedRegisters == true); \
VM_EXEC_SAFE_MODE(reg->usingCachedRegisters = false;) \
reg->lpProgramCounter = lpProgramCounter; \
reg->pFrameBase = pFrameBase; \
reg->pStackPointer = pStackPointer; \
} while (false)
#define READ_PGM_1(target) do { \
VM_ASSERT(vm, reg->usingCachedRegisters == true); \
target = LongPtr_read1(lpProgramCounter);\
lpProgramCounter = LongPtr_add(lpProgramCounter, 1); \
} while (false)
#define READ_PGM_2(target) do { \
VM_ASSERT(vm, reg->usingCachedRegisters == true); \
target = LongPtr_read2_unaligned(lpProgramCounter); \
lpProgramCounter = LongPtr_add(lpProgramCounter, 2); \
} while (false)
#define PUSH(v) do { \
VM_ASSERT(vm, reg->usingCachedRegisters == true); \
VM_ASSERT(vm, pStackPointer < getTopOfStackSpace(vm->stack)); \
*pStackPointer = v; \
pStackPointer++; \
} while (false)
#if MVM_SAFE_MODE
#define POP() vm_safePop(vm, --pStackPointer)
#else
#define POP() (*(--pStackPointer))
#endif
// Push the current registers onto the call stack
#define PUSH_REGISTERS(lpReturnAddress) do { \
VM_ASSERT(vm, VM_FRAME_BOUNDARY_VERSION == 2); \
PUSH((uint16_t)(uintptr_t)pStackPointer - (uint16_t)(uintptr_t)pFrameBase); \
PUSH(reg->closure); \
PUSH(reg->argCountAndFlags); \
PUSH((uint16_t)LongPtr_sub(lpReturnAddress, vm->lpBytecode)); \
} while (false)
// Inverse of PUSH_REGISTERS
#define POP_REGISTERS() do { \
VM_ASSERT(vm, VM_FRAME_BOUNDARY_VERSION == 2); \
lpProgramCounter = LongPtr_add(vm->lpBytecode, POP()); \
reg->argCountAndFlags = POP(); \
reg->closure = POP(); \
pStackPointer--; \
pFrameBase = (uint16_t*)((uint8_t*)pStackPointer - *pStackPointer); \
reg->pArgs = pFrameBase - VM_FRAME_BOUNDARY_SAVE_SIZE_WORDS - (uint8_t)reg->argCountAndFlags; \
} while (false)
// Reinterpret reg1 as 8-bit signed
#define SIGN_EXTEND_REG_1() reg1 = (uint16_t)((int16_t)((int8_t)reg1))
#define INSTRUCTION_RESERVED() VM_ASSERT(vm, false)
// ------------------------------ Common Variables --------------------------
VM_SAFE_CHECK_NOT_NULL(vm);
if (argCount) VM_SAFE_CHECK_NOT_NULL(args);
TeError err = MVM_E_SUCCESS;
// These are cached values of `vm->stack->reg`, for quick access. Note: I've
// chosen only the most important registers to be cached here, in the hope
// that the C compiler will promote these eagerly to the CPU registers,
// although it may choose not to.
register uint16_t* pFrameBase;
register uint16_t* pStackPointer;
register LongPtr lpProgramCounter;
// These are general-purpose scratch "registers". Note: probably the compiler
// would be fine at performing register allocation if we didn't have specific
// register variables, but having them explicit forces us to think about what
// state is being used and designing the code to minimize it.
register uint16_t reg1;
register uint16_t reg2;
register uint16_t reg3;
uint16_t* regP1 = 0;
LongPtr regLP1 = 0;
uint16_t* globals;
vm_TsRegisters* reg;
vm_TsRegisters registerValuesAtEntry;
#if MVM_DONT_TRUST_BYTECODE
LongPtr maxProgramCounter;
LongPtr minProgramCounter = getBytecodeSection(vm, BCS_ROM, &maxProgramCounter);
#endif
// Note: these initial values are not actually used, but some compilers give a
// warning if you omit them.
pFrameBase = 0;
pStackPointer = 0;
lpProgramCounter = 0;
reg1 = 0;
reg2 = 0;
reg3 = 0;
// ------------------------------ Initialization ---------------------------
CODE_COVERAGE(4); // Hit
// Create the call stack if it doesn't exist
if (!vm->stack) {
CODE_COVERAGE(230); // Hit
err = vm_createStackAndRegisters(vm);
if (err != MVM_E_SUCCESS) {
return err;
}
} else {
CODE_COVERAGE_UNTESTED(232); // Not hit
}
globals = vm->globals;
reg = &vm->stack->reg;
registerValuesAtEntry = *reg;
// Because we're coming from C-land, any exceptions that happen during
// mvm_call should register as host errors
reg->catchTarget = VM_VALUE_UNDEFINED;
// Copy the state of the VM registers into the logical variables for quick access
CACHE_REGISTERS();
// ---------------------- Push host arguments to the stack ------------------
// 254 is the maximum because we also push the `this` value implicitly
if (argCount > 254) {
CODE_COVERAGE_ERROR_PATH(220); // Not hit
return MVM_E_TOO_MANY_ARGUMENTS;
} else {
CODE_COVERAGE(15); // Hit
}
vm_requireStackSpace(vm, pStackPointer, argCount + 1);
PUSH(VM_VALUE_UNDEFINED); // Push `this` pointer of undefined
TABLE_COVERAGE(argCount ? 1 : 0, 2, 513); // Hit 2/2
reg1 = argCount;
while (reg1--) {
PUSH(*args++);
}
// ---------------------------- Call target function ------------------------
reg1 /* argCountAndFlags */ = (argCount + 1) | AF_CALLED_FROM_HOST; // +1 for the `this` value
reg2 /* target */ = targetFunc;
goto SUB_CALL;
// --------------------------------- Run Loop ------------------------------
// This forms the start of the run loop
//
// Some useful debug watches:
//
// - Program counter: /* pc */ (uint8_t*)lpProgramCounter - (uint8_t*)vm->lpBytecode
// /* pc */ (uint8_t*)vm->stack->reg.lpProgramCounter - (uint8_t*)vm->lpBytecode
//
// - Frame height (in words): /* fh */ (uint16_t*)pStackPointer - (uint16_t*)pFrameBase
// /* fh */ (uint16_t*)vm->stack->reg.pStackPointer - (uint16_t*)vm->stack->reg.pFrameBase
//
// - Frame: /* frame */ (uint16_t*)pFrameBase,10
// /* frame */ (uint16_t*)vm->stack->reg.pFrameBase,10
//
// - Stack height (in words): /* sp */ (uint16_t*)pStackPointer - (uint16_t*)(vm->stack + 1)
// /* sp */ (uint16_t*)vm->stack->reg.pStackPointer - (uint16_t*)(vm->stack + 1)
//
// - Frame base (in words): /* bp */ (uint16_t*)pFrameBase - (uint16_t*)(vm->stack + 1)
// /* bp */ (uint16_t*)vm->stack->reg.pFrameBase - (uint16_t*)(vm->stack + 1)
//
// - Arg count: /* argc */ (uint8_t)vm->stack->reg.argCountAndFlags
// - First 4 arg values: /* args */ vm->stack->reg.pArgs,4
//
// Notes:
//
// - The value of VM_VALUE_UNDEFINED is 0x001
// - If a value is _odd_, interpret it as a bytecode address by dividing by 2
//
SUB_DO_NEXT_INSTRUCTION:
CODE_COVERAGE(59); // Hit
if (vm->stopAfterNInstructions >= 0) {
CODE_COVERAGE(650); // Hit
if (vm->stopAfterNInstructions == 0) {
CODE_COVERAGE(651); // Hit
err = MVM_E_INSTRUCTION_COUNT_REACHED;
goto SUB_EXIT;
} else {
CODE_COVERAGE(652); // Hit
vm->stopAfterNInstructions--;
}
}
// This is not required for execution but is intended for diagnostics,
// required by mvm_getCurrentAddress.
// TODO: If MVM_INCLUDE_DEBUG_CAPABILITY is not included, maybe this shouldn't be here, and `mvm_getCurrentAddress` should also not be available.
reg->lpProgramCounter = lpProgramCounter;
// Check we're within range
#if MVM_DONT_TRUST_BYTECODE
if ((lpProgramCounter < minProgramCounter) || (lpProgramCounter >= maxProgramCounter)) {
VM_INVALID_BYTECODE(vm);
}
#endif
// Check breakpoints
#if MVM_INCLUDE_DEBUG_CAPABILITY
if (vm->pBreakpoints) {
TsBreakpoint* pBreakpoint = vm->pBreakpoints;
uint16_t currentBytecodeAddress = LongPtr_sub(lpProgramCounter, vm->lpBytecode);
do {
if (pBreakpoint->bytecodeAddress == currentBytecodeAddress) {
FLUSH_REGISTER_CACHE();
mvm_TfBreakpointCallback breakpointCallback = vm->breakpointCallback;
if (breakpointCallback)
breakpointCallback(vm, currentBytecodeAddress);
CACHE_REGISTERS();
break;
}
pBreakpoint = pBreakpoint->next;
} while (pBreakpoint);
}
#endif // MVM_INCLUDE_DEBUG_CAPABILITY
// Instruction bytes are divided into two nibbles
READ_PGM_1(reg3);
reg1 = reg3 & 0xF; // Primary opcode
reg3 = reg3 >> 4; // Secondary opcode or data
if (reg3 >= VM_OP_DIVIDER_1) {
CODE_COVERAGE(428); // Hit
reg2 = POP();
} else {
CODE_COVERAGE(429); // Hit
}
VM_ASSERT(vm, reg3 < VM_OP_END);
MVM_SWITCH(reg3, (VM_OP_END - 1)) {
/* ------------------------------------------------------------------------- */
/* VM_OP_LOAD_SMALL_LITERAL */
/* Expects: */
/* reg1: small literal ID */
/* ------------------------------------------------------------------------- */
MVM_CASE(VM_OP_LOAD_SMALL_LITERAL): {
CODE_COVERAGE(60); // Hit
TABLE_COVERAGE(reg1, smallLiteralsSize, 448); // Hit 11/12
#if MVM_DONT_TRUST_BYTECODE
if (reg1 >= smallLiteralsSize) {
err = vm_newError(vm, MVM_E_INVALID_BYTECODE);
goto SUB_EXIT;
}
#endif
reg1 = smallLiterals[reg1];
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_LOAD_VAR_1 */
/* Expects: */
/* reg1: variable index */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_LOAD_VAR_1):
CODE_COVERAGE(61); // Hit
SUB_OP_LOAD_VAR:
reg1 = pStackPointer[-reg1 - 1];
if (reg1 == VM_VALUE_DELETED) {
err = vm_newError(vm, MVM_E_TDZ_ERROR);
goto SUB_EXIT;
}
goto SUB_TAIL_POP_0_PUSH_REG1;
/* ------------------------------------------------------------------------- */
/* VM_OP_LOAD_SCOPED_1 */
/* Expects: */
/* reg1: variable index */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_LOAD_SCOPED_1):
CODE_COVERAGE(62); // Hit
LongPtr lpVar;
SUB_OP_LOAD_SCOPED:
lpVar = vm_findScopedVariable(vm, reg1);
reg1 = LongPtr_read2_aligned(lpVar);
goto SUB_TAIL_POP_0_PUSH_REG1;
/* ------------------------------------------------------------------------- */
/* VM_OP_LOAD_ARG_1 */
/* Expects: */
/* reg1: argument index */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_LOAD_ARG_1):
CODE_COVERAGE(63); // Hit
goto SUB_OP_LOAD_ARG;
/* ------------------------------------------------------------------------- */
/* VM_OP_CALL_1 */
/* Expects: */
/* reg1: index into short-call table */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_CALL_1): {
CODE_COVERAGE_UNTESTED(66); // Not hit
goto SUB_CALL_SHORT;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_FIXED_ARRAY_NEW_1 */
/* Expects: */
/* reg1: length of new fixed-length-array */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_FIXED_ARRAY_NEW_1): {
CODE_COVERAGE_UNTESTED(134); // Not hit
goto SUB_FIXED_ARRAY_NEW;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_EXTENDED_1 */
/* Expects: */
/* reg1: vm_TeOpcodeEx1 */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_EXTENDED_1):
CODE_COVERAGE(69); // Hit
goto SUB_OP_EXTENDED_1;
/* ------------------------------------------------------------------------- */
/* VM_OP_EXTENDED_2 */
/* Expects: */
/* reg1: vm_TeOpcodeEx2 */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_EXTENDED_2):
CODE_COVERAGE(70); // Hit
goto SUB_OP_EXTENDED_2;
/* ------------------------------------------------------------------------- */
/* VM_OP_EXTENDED_3 */
/* Expects: */
/* reg1: vm_TeOpcodeEx3 */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_EXTENDED_3):
CODE_COVERAGE(71); // Hit
goto SUB_OP_EXTENDED_3;
/* ------------------------------------------------------------------------- */
/* VM_OP_CALL_5 */
/* Expects: */
/* reg1: argCount */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_CALL_5): {
CODE_COVERAGE_UNTESTED(72); // Not hit
// Uses 16 bit literal for function offset
READ_PGM_2(reg2);
reg3 /* scope */ = VM_VALUE_UNDEFINED;
goto SUB_CALL_BYTECODE_FUNC;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_STORE_VAR_1 */
/* Expects: */
/* reg1: variable index relative to stack pointer */
/* reg2: value to store */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_STORE_VAR_1): {
CODE_COVERAGE(73); // Hit
SUB_OP_STORE_VAR:
// Note: the value to store has already been popped off the stack at this
// point. The index 0 refers to the slot currently at the top of the
// stack.
pStackPointer[-reg1 - 1] = reg2;
goto SUB_TAIL_POP_0_PUSH_0;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_STORE_SCOPED_1 */
/* Expects: */
/* reg1: variable index */
/* reg2: value to store */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_STORE_SCOPED_1): {
CODE_COVERAGE(74); // Hit
LongPtr lpVar;
SUB_OP_STORE_SCOPED:
lpVar = vm_findScopedVariable(vm, reg1);
Value* pVar = (Value*)LongPtr_truncate(lpVar);
// It would be an illegal operation to write to a closure variable stored in ROM
VM_BYTECODE_ASSERT(vm, lpVar == LongPtr_new(pVar));
*pVar = reg2;
goto SUB_TAIL_POP_0_PUSH_0;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_ARRAY_GET_1 */
/* Expects: */
/* reg1: item index (4-bit) */
/* reg2: reference to array */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_ARRAY_GET_1): {
CODE_COVERAGE_UNTESTED(75); // Not hit
// I think it makes sense for this instruction only to be an optimization for fixed-length arrays
VM_ASSERT(vm, deepTypeOf(vm, reg2) == TC_REF_FIXED_LENGTH_ARRAY);
regLP1 = DynamicPtr_decode_long(vm, reg2);
// These indexes should be compiler-generated, so they should never be out of range
VM_ASSERT(vm, reg1 < (vm_getAllocationSize_long(regLP1) >> 1));
regLP1 = LongPtr_add(regLP1, reg2 << 1);
reg1 = LongPtr_read2_aligned(regLP1);
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_ARRAY_SET_1 */
/* Expects: */
/* reg1: item index (4-bit) */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_ARRAY_SET_1): {
CODE_COVERAGE_UNTESTED(76); // Not hit
reg2 = POP(); // array reference
// I think it makes sense for this instruction only to be an optimization for fixed-length arrays
VM_ASSERT(vm, deepTypeOf(vm, reg3) == TC_REF_FIXED_LENGTH_ARRAY);
// We can only write to it if it's in RAM, so it must be a short-pointer
regP1 = (Value*)ShortPtr_decode(vm, reg3);
// These indexes should be compiler-generated, so they should never be out of range
VM_ASSERT(vm, reg1 < (vm_getAllocationSize(regP1) >> 1));
regP1[reg1] = reg2;
goto SUB_TAIL_POP_0_PUSH_0;
}
/* ------------------------------------------------------------------------- */
/* VM_OP_NUM_OP */
/* Expects: */
/* reg1: vm_TeNumberOp */
/* reg2: first popped operand */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_NUM_OP): {
CODE_COVERAGE(77); // Hit
goto SUB_OP_NUM_OP;
} // End of case VM_OP_NUM_OP
/* ------------------------------------------------------------------------- */
/* VM_OP_BIT_OP */
/* Expects: */
/* reg1: vm_TeBitwiseOp */
/* reg2: first popped operand */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP_BIT_OP): {
CODE_COVERAGE(92); // Hit
goto SUB_OP_BIT_OP;
}
} // End of primary switch
// All cases should loop explicitly back
VM_ASSERT_UNREACHABLE(vm);
/* ------------------------------------------------------------------------- */
/* SUB_OP_LOAD_ARG */
/* Expects: */
/* reg1: argument index */
/* ------------------------------------------------------------------------- */
SUB_OP_LOAD_ARG: {
CODE_COVERAGE(32); // Hit
reg2 /* argCountAndFlags */ = reg->argCountAndFlags;
if (reg1 /* argIndex */ < (uint8_t)reg2 /* argCount */) {
CODE_COVERAGE(64); // Hit
reg1 /* result */ = reg->pArgs[reg1 /* argIndex */];
} else {
CODE_COVERAGE(65); // Hit
reg1 = VM_VALUE_UNDEFINED;
}
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* SUB_CALL_SHORT */
/* Expects: */
/* reg1: index into short-call table */
/* ------------------------------------------------------------------------- */
SUB_CALL_SHORT: {
CODE_COVERAGE_UNTESTED(173); // Not hit
LongPtr lpShortCallTable = getBytecodeSection(vm, BCS_SHORT_CALL_TABLE, NULL);
LongPtr lpShortCallTableEntry = LongPtr_add(lpShortCallTable, reg1 * sizeof (vm_TsShortCallTableEntry));
#if MVM_SAFE_MODE
LongPtr lpShortCallTableEnd;
getBytecodeSection(vm, BCS_SHORT_CALL_TABLE, &lpShortCallTableEnd);
VM_ASSERT(vm, lpShortCallTableEntry < lpShortCallTableEnd);
#endif
reg2 /* target */ = LongPtr_read2_aligned(lpShortCallTableEntry);
lpShortCallTableEntry = LongPtr_add(lpShortCallTableEntry, 2);
// Note: reg1 holds the new argCountAndFlags, but the flags are zero in this situation
reg1 /* argCountAndFlags */ = LongPtr_read1(lpShortCallTableEntry);
reg3 /* scope */ = VM_VALUE_UNDEFINED;
// The high bit of function indicates if this is a call to the host
bool isHostCall = reg2 & 1;
if (isHostCall) {
CODE_COVERAGE_UNTESTED(67); // Not hit
goto SUB_CALL_HOST_COMMON;
} else {
CODE_COVERAGE_UNTESTED(68); // Not hit
reg2 >>= 1;
goto SUB_CALL_BYTECODE_FUNC;
}
} // SUB_CALL_SHORT
/* ------------------------------------------------------------------------- */
/* SUB_OP_BIT_OP */
/* Expects: */
/* reg1: vm_TeBitwiseOp */
/* reg2: first popped operand */
/* ------------------------------------------------------------------------- */
SUB_OP_BIT_OP: {
int32_t reg1I = 0;
int32_t reg2I = 0;
int8_t reg2B = 0;
reg3 = reg1;
// Convert second operand to an int32
reg2I = mvm_toInt32(vm, reg2);
// If it's a binary operator, then we pop a second operand
if (reg3 < VM_BIT_OP_DIVIDER_2) {
CODE_COVERAGE(117); // Hit
reg1 = POP();
reg1I = mvm_toInt32(vm, reg1);
// If we're doing a shift operation, the operand is in the 0-32 range
if (reg3 < VM_BIT_OP_END_OF_SHIFT_OPERATORS) {
reg2B = reg2I & 0x1F;
}
} else {
CODE_COVERAGE(118); // Hit
}
VM_ASSERT(vm, reg3 < VM_BIT_OP_END);
MVM_SWITCH (reg3, (VM_BIT_OP_END - 1)) {
MVM_CASE(VM_BIT_OP_SHR_ARITHMETIC): {
CODE_COVERAGE(93); // Hit
reg1I = reg1I >> reg2B;
break;
}
MVM_CASE(VM_BIT_OP_SHR_LOGICAL): {
CODE_COVERAGE(94); // Hit
// Cast the number to unsigned int so that the C interprets the shift
// as unsigned/logical rather than signed/arithmetic.
reg1I = (int32_t)((uint32_t)reg1I >> reg2B);
#if MVM_SUPPORT_FLOAT && MVM_PORT_INT32_OVERFLOW_CHECKS
// This is a rather annoying edge case if you ask me, since all
// other bitwise operations yield signed int32 results every time.
// If the shift is by exactly zero units, then negative numbers
// become positive and overflow the signed-32 bit type. Since we
// don't have an unsigned 32 bit type, this means they need to be
// extended to floats.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Signed_32-bit_integers
if ((reg2B == 0) & (reg1I < 0)) {
FLUSH_REGISTER_CACHE();
reg1 = mvm_newNumber(vm, (MVM_FLOAT64)((uint32_t)reg1I));
CACHE_REGISTERS();
goto SUB_TAIL_POP_0_PUSH_REG1;
}
#endif // MVM_PORT_INT32_OVERFLOW_CHECKS
break;
}
MVM_CASE(VM_BIT_OP_SHL): {
CODE_COVERAGE(95); // Hit
reg1I = reg1I << reg2B;
break;
}
MVM_CASE(VM_BIT_OP_OR): {
CODE_COVERAGE(96); // Hit
reg1I = reg1I | reg2I;
break;
}
MVM_CASE(VM_BIT_OP_AND): {
CODE_COVERAGE(97); // Hit
reg1I = reg1I & reg2I;
break;
}
MVM_CASE(VM_BIT_OP_XOR): {
CODE_COVERAGE(98); // Hit
reg1I = reg1I ^ reg2I;
break;
}
MVM_CASE(VM_BIT_OP_NOT): {
CODE_COVERAGE(99); // Hit
reg1I = ~reg2I;
break;
}
}
CODE_COVERAGE(101); // Hit
// Convert the result from a 32-bit integer
if ((reg1I >= VM_MIN_INT14) && (reg1I <= VM_MAX_INT14)) {
CODE_COVERAGE(34); // Hit
reg1 = VirtualInt14_encode(vm, (uint16_t)reg1I);
} else {
CODE_COVERAGE(35); // Hit
FLUSH_REGISTER_CACHE();
reg1 = mvm_newInt32(vm, reg1I);
CACHE_REGISTERS();
}
goto SUB_TAIL_POP_0_PUSH_REG1;
} // End of SUB_OP_BIT_OP
/* ------------------------------------------------------------------------- */
/* SUB_OP_EXTENDED_1 */
/* Expects: */
/* reg1: vm_TeOpcodeEx1 */
/* ------------------------------------------------------------------------- */
SUB_OP_EXTENDED_1: {
CODE_COVERAGE(102); // Hit
reg3 = reg1;
VM_ASSERT(vm, reg3 <= VM_OP1_END);
MVM_SWITCH (reg3, VM_OP1_END - 1) {
/* ------------------------------------------------------------------------- */
/* VM_OP1_RETURN_x */
/* Expects: */
/* reg1: vm_TeOpcodeEx1 */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_RETURN): {
CODE_COVERAGE(107); // Hit
reg1 = POP();
goto SUB_RETURN;
}
MVM_CASE (VM_OP1_THROW): {
CODE_COVERAGE(106); // Hit
reg1 = POP(); // The exception value
// Find the closest catch block
reg2 = reg->catchTarget;
// If none, it's an uncaught exception
if (reg2 == VM_VALUE_UNDEFINED) {
CODE_COVERAGE(208); // Hit
if (out_result) {
*out_result = reg1;
}
err = MVM_E_UNCAUGHT_EXCEPTION;
goto SUB_EXIT;
} else {
CODE_COVERAGE(209); // Hit
}
VM_ASSERT(vm, ((intptr_t)reg2 & 1) == 1);
// Unwind the stack. regP1 is the stack pointer address we want to land up at
regP1 = (uint16_t*)(((intptr_t)getBottomOfStack(vm->stack) + (intptr_t)reg2) & ~1);
VM_ASSERT(vm, pStackPointer >= getBottomOfStack(vm->stack));
VM_ASSERT(vm, pStackPointer < getTopOfStackSpace(vm->stack));
while (pFrameBase > regP1) {
CODE_COVERAGE(211); // Hit
// Near the beginning of mvm_call, we set `catchTarget` to undefined
// (and then restore at the end), which should direct exceptions through
// the path of "uncaught exception" above, so no frame here should ever
// be a host frame.
VM_ASSERT(vm, !(reg->argCountAndFlags & AF_CALLED_FROM_HOST));
// In the current frame structure, the size of the preceding frame is
// saved 4 words ahead of the frame base
pStackPointer = pFrameBase;
POP_REGISTERS();
}
pStackPointer = regP1;
// The next catch target is the outer one
reg->catchTarget = pStackPointer[0];
// Jump to the catch block
reg2 = pStackPointer[1];
VM_ASSERT(vm, (reg2 & 1) == 1);
lpProgramCounter = LongPtr_add(vm->lpBytecode, reg2 & ~1);
// Push the exception to the stack for the catch block to use
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_CLOSURE_NEW */
/* Expects: */
/* reg3: vm_TeOpcodeEx1 */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_CLOSURE_NEW): {
CODE_COVERAGE(599); // Hit
FLUSH_REGISTER_CACHE();
Value* pClosure = gc_allocateWithHeader(vm, 4, TC_REF_CLOSURE);
CACHE_REGISTERS();
reg1 = ShortPtr_encode(vm, pClosure);
*pClosure++ = POP(); // The function pointer
*pClosure = reg->closure; // Capture the current scope
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_NEW */
/* Expects: */
/* Nothing */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_NEW): {
CODE_COVERAGE(347); // Hit
READ_PGM_1(reg1); // arg count
regP1 = &pStackPointer[-reg1 - 1]; // Pointer to class
reg1 /*argCountAndFlags*/ |= AF_PUSHED_FUNCTION;
reg2 /*class*/ = regP1[0];
// Can only `new` classes in Microvium
if (deepTypeOf(vm, reg2) != TC_REF_CLASS) {
err = MVM_E_USING_NEW_ON_NON_CLASS;
goto SUB_EXIT;
}
regLP1 = DynamicPtr_decode_long(vm, reg2);
// Note: using the stack as a temporary store because things can shift
// during a GC collection and we these temporaries to be GC-visible. It's
// safe to trash these particular slots. The regP1[1] slot holds the
// `this` value passed by the caller, which will always be undefined
// because `new` doesn't allows passing a `this`, and `regP1[0]` holds the
// class, which we've already read.
regP1[1] /*props*/ = READ_FIELD_2(regLP1, TsClass, staticProps);
regP1[0] /*func*/ = READ_FIELD_2(regLP1, TsClass, constructorFunc);
// Using the stack just to root this in the GC graph
PUSH(getBuiltin(vm, BIN_STR_PROTOTYPE));
// We've already checked that the target of the `new` operation is a
// class. A class cannot existed without a `prototype` property. If the
// class was created at compile time, the "prototype" string will be
// embedded in the bytecode because the class definition uses it. If the
// class was created at runtime, the "prototype" string will *also* be
// embedded in the bytecode because classes at runtime are only created by
// sequences of instructions that also includes reference to the
// "prototype" string. So either way, the fact that we're at this point in
// the code means that the "prototype" string must exist as a builtin.
VM_ASSERT(vm, pStackPointer[-1] != VM_VALUE_UNDEFINED);
FLUSH_REGISTER_CACHE();
TsPropertyList* pObject = GC_ALLOCATE_TYPE(vm, TsPropertyList, TC_REF_PROPERTY_LIST);
pObject->dpNext = VM_VALUE_NULL;
getProperty(vm, ®P1[1], &pStackPointer[-1], &pObject->dpProto);
TeTypeCode tc = deepTypeOf(vm, pObject->dpProto);
if ((tc != TC_REF_PROPERTY_LIST) && (tc != TC_REF_CLASS) && (tc != TC_REF_ARRAY)) {
pObject->dpProto = VM_VALUE_NULL;
}
CACHE_REGISTERS();
POP(); // BIN_STR_PROTOTYPE
if (err != MVM_E_SUCCESS) goto SUB_EXIT;
// The first argument is the `this` value
regP1[1] = ShortPtr_encode(vm, pObject);
reg2 = regP1[0];
goto SUB_CALL;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_SCOPE_NEW */
/* Expects: */
/* Nothing */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_SCOPE_NEW): {
CODE_COVERAGE(605); // Hit
// A SCOPE_NEW is just like a SCOPE_PUSH without capturing the parent
reg3 /*capture parent*/ = false;
goto SUB_OP_SCOPE_PUSH_OR_NEW;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_TYPE_CODE_OF */
/* Expects: */
/* Nothing */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_TYPE_CODE_OF): {
CODE_COVERAGE_UNTESTED(607); // Not hit
reg1 = POP();
reg1 = mvm_typeOf(vm, reg1);
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_POP */
/* Expects: */
/* Nothing */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_POP): {
CODE_COVERAGE(138); // Hit
pStackPointer--;
goto SUB_TAIL_POP_0_PUSH_0;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_TYPEOF */
/* Expects: */
/* Nothing */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_TYPEOF): {
CODE_COVERAGE(167); // Hit
// TODO: This is should really be done using some kind of built-in helper
// function, but we don't support those yet. The trouble with this
// implementation is that it's doing a string allocation every time. Also
// the new string is not an interned string so it's expensive to compare
// `typeof x === y`. Basically this is just a stop-gap.
reg1 = mvm_typeOf(vm, pStackPointer[-1]);
VM_ASSERT(vm, reg1 < sizeof typeStringOffsetByType);
reg1 = typeStringOffsetByType[reg1];
VM_ASSERT(vm, reg1 < sizeof(TYPE_STRINGS) - 1);
const char* str = &TYPE_STRINGS[reg1];
FLUSH_REGISTER_CACHE();
reg1 = vm_newStringFromCStrNT(vm, str);
CACHE_REGISTERS();
goto SUB_TAIL_POP_1_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_OBJECT_NEW */
/* Expects: */
/* (nothing) */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_OBJECT_NEW): {
CODE_COVERAGE(112); // Hit
FLUSH_REGISTER_CACHE();
TsPropertyList* pObject = GC_ALLOCATE_TYPE(vm, TsPropertyList, TC_REF_PROPERTY_LIST);
CACHE_REGISTERS();
reg1 = ShortPtr_encode(vm, pObject);
pObject->dpNext = VM_VALUE_NULL;
pObject->dpProto = VM_VALUE_NULL;
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_LOGICAL_NOT */
/* Expects: */
/* (nothing) */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_LOGICAL_NOT): {
CODE_COVERAGE(113); // Hit
reg2 = POP(); // value to negate
reg1 = mvm_toBool(vm, reg2) ? VM_VALUE_FALSE : VM_VALUE_TRUE;
goto SUB_TAIL_POP_0_PUSH_REG1;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_OBJECT_GET_1 */
/* Expects: */
/* reg1: objectValue */
/* reg2: propertyName */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_OBJECT_GET_1): {
CODE_COVERAGE(114); // Hit
FLUSH_REGISTER_CACHE();
err = getProperty(vm, pStackPointer - 2, pStackPointer - 1, pStackPointer - 2);
CACHE_REGISTERS();
if (err != MVM_E_SUCCESS) goto SUB_EXIT;
goto SUB_TAIL_POP_1_PUSH_0;
}
/* ------------------------------------------------------------------------- */
/* VM_OP1_ADD */
/* Expects: */
/* reg1: left operand */
/* reg2: right operand */
/* ------------------------------------------------------------------------- */
MVM_CASE (VM_OP1_ADD): {
CODE_COVERAGE(115); // Hit
reg1 = pStackPointer[-2];
reg2 = pStackPointer[-1];
// Special case for adding unsigned 12 bit numbers, for example in most
// loops. 12 bit unsigned addition does not require any overflow checks
if (Value_isVirtualUInt12(reg1) && Value_isVirtualUInt12(reg2)) {
CODE_COVERAGE(116); // Hit
reg1 = reg1 + reg2 - VirtualInt14_encode(vm, 0);
goto SUB_TAIL_POP_2_PUSH_REG1;
} else {
CODE_COVERAGE(119); // Hit
}
if (vm_isString(vm, reg1) || vm_isString(vm, reg2)) {
CODE_COVERAGE(120); // Hit
FLUSH_REGISTER_CACHE();
// Note: the intermediate values are saved back to the stack so that