-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcompiler.c
2797 lines (2643 loc) · 92.5 KB
/
compiler.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
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stddef.h>
#include "compiler.h"
#include "nodes.h"
#include "scanner.h"
#include "parser.h"
#include "value.h"
#include "debug.h"
#include "options.h"
#include "memory.h"
#include "vm.h"
#ifdef NDEBUG
#define COMP_TRACE(...) (void)0
#else
#define COMP_TRACE(...) compiler_trace_debug(__VA_ARGS__)
#endif
const char *compileScopeName(CompileScopeType stype) {
switch (stype) {
case COMPILE_SCOPE_MAIN: return "SCOPE_MAIN"; // in a { } block, NOT language-level function 'block'
case COMPILE_SCOPE_FUNCTION: return "SCOPE_FUNCTION";
case COMPILE_SCOPE_IF: return "SCOPE_IF";
case COMPILE_SCOPE_WHILE: return "SCOPE_WHILE";
case COMPILE_SCOPE_FOREACH: return "SCOPE_FOREACH";
case COMPILE_SCOPE_FOR: return "SCOPE_FOR";
case COMPILE_SCOPE_TRY: return "SCOPE_TRY";
case COMPILE_SCOPE_IN: return "SCOPE_IN";
case COMPILE_SCOPE_CLASS: return "SCOPE_CLASS";
case COMPILE_SCOPE_MODULE: return "SCOPE_MODULE";
case COMPILE_SCOPE_BLOCK: return "SCOPE_BLOCK";
default: {
UNREACHABLE("invalid scope type: %d", stype);
}
}
}
typedef enum eLoopType {
LOOP_T_NONE=0,
LOOP_T_FOR,
LOOP_T_FOREACH,
LOOP_T_WHILE,
LOOP_T_BLOCK,
} eLoopType;
static Compiler *current = NULL;
static Compiler *top = NULL; // compiler for main
static ClassCompiler *currentClassOrModule = NULL;
static bool inINBlock = false;
static Token *curTok = NULL;
static int loopStart = -1;
static eLoopType curLoopType = LOOP_T_NONE;
static int nodeDepth = 0;
static int nodeWidth = -1;
static int blockDepth = 0;
static bool breakBlock = false;
static Scope *curScope = NULL;
static int loopLocalCount = 0; // for continue statement
static int nextInsnIsLabel = false;
CompilerOpts compilerOpts; // [external]
typedef enum {
VAR_GET = 1,
VAR_SET,
} VarOp;
typedef enum {
CONST_T_NUMLIT = 1,
CONST_T_STRLIT,
CONST_T_ARYLIT,
CONST_T_MAPLIT,
CONST_T_CODE,
CONST_T_CALLINFO
} ConstType;
static void compiler_trace_debug(const char *fmt, ...) {
if (!CLOX_OPTION_T(traceCompiler)) return;
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "[COMP]: ");
if (current) {
fprintf(stderr, "(comp=%p,depth=%d): ", current, current->scopeDepth);
}
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
static void optimizer_debug(int lvl, const char *fmt, ...) {
if (GET_OPTION(debugOptimizerLvl) < lvl) return;
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "[OPT]: ");
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
#ifdef NDEBUG
#define OPT_DEBUG(lvl, ...) (void)0
#else
#define OPT_DEBUG(lvl, ...) optimizer_debug(lvl, __VA_ARGS__)
#endif
static void error(const char *format, ...) {
int line = curTok ? curTok->line : 0;
va_list args;
va_start(args, format);
ObjString *str = hiddenString("", 0, NEWOBJ_FLAG_NONE);
pushCStringFmt(str, "[Compile Error]: ");
if (line > 0) {
pushCStringFmt(str, "(line: %d) ", line);
}
pushCStringVFmt(str, format, args);
va_end(args);
pushCStringFmt(str, "%s", "\n");
vec_push(&top->v_errMessages, str);
current->hadError = true;
top->hadError = true;
}
static void outputCompilerErrors(Compiler *c, FILE *f) {
ASSERT(top);
ObjString *msg = NULL;
int i = 0;
vec_foreach(&top->v_errMessages, msg, i) {
fprintf(f, "%s", msg->chars);
}
}
static void freeCompiler(Compiler *c, bool freeErrMessages) {
if (freeErrMessages) {
vec_deinit(&c->v_errMessages);
}
freeTable(&c->constTbl);
freeIseq(&c->iseq);
}
static inline Chunk *currentChunk() {
DBG_ASSERT(current->function && current->function->chunk);
return current->function->chunk;
}
static inline ObjFunction *currentFunction() {
return current->function;
}
static inline Iseq *currentIseq() {
return ¤t->iseq;
}
static Insn *emitInsn(Insn in) {
COMP_TRACE("emitInsn: %s", opName(in.code));
in.lineno = curTok ? curTok->line : 0;
in.nlvl.depth = nodeDepth;
in.nlvl.width = nodeWidth;
Insn *inHeap = xcalloc(1, sizeof(Insn));
ASSERT_MEM(inHeap);
memcpy(inHeap, &in, sizeof(Insn));
if (nextInsnIsLabel) {
inHeap->isLabel = true;
nextInsnIsLabel = false;
}
iseqAddInsn(currentIseq(), inHeap);
return inHeap;
}
static Insn *emitOp0(bytecode_t code) {
Insn in;
memset(&in, 0, sizeof(Insn));
in.code = code;
in.numOperands = 0;
return emitInsn(in);
}
static Insn *emitOp1(bytecode_t code, bytecode_t op1) {
Insn in;
memset(&in, 0, sizeof(Insn));
in.code = code;
in.operands[0] = op1;
in.numOperands = 1;
return emitInsn(in);
}
static Insn *emitOp2(bytecode_t code, bytecode_t op1, bytecode_t op2) {
Insn in;
memset(&in, 0, sizeof(Insn));
in.code = code;
in.operands[0] = op1;
in.operands[1] = op2;
in.numOperands = 2;
return emitInsn(in);
}
static Insn *emitOp3(bytecode_t code, bytecode_t op1, bytecode_t op2, bytecode_t op3) {
Insn in;
memset(&in, 0, sizeof(Insn));
in.code = code;
in.operands[0] = op1;
in.operands[1] = op2;
in.operands[2] = op3;
in.numOperands = 3;
return emitInsn(in);
}
// blocks (`{}`) push new scopes
static void pushScope(CompileScopeType stype) {
ObjFunction *func = current->function;
Scope *s = ALLOCATE(Scope, 1);
s->type = stype;
s->line_start = curTok ? curTok->line : 0;
s->line_end = -1;
s->parent = curScope;
s->bytecode_start = current->iseq.wordCount;
s->bytecode_end = -1;
vec_push(&func->scopes, s);
current->scopeDepth++;
curScope = s;
COMP_TRACE("pushScope: %s (depth=%d)", compileScopeName(stype), current->scopeDepth);
}
static void namedVariable(Token name, VarOp getSet);
// returns nil, this is in case OP_RETURN wasn't emitted from an explicit
// `return` statement in a function.
static void emitReturn(Compiler *compiler) {
ASSERT(compiler->type != FUN_TYPE_TOP_LEVEL);
COMP_TRACE("Emitting return");
if (compiler->type == FUN_TYPE_INIT) {
emitOp0(OP_GET_THIS);
emitOp0(OP_RETURN);
} else {
if (breakBlock && compiler->type == FUN_TYPE_BLOCK) {
if (compiler->iseq.count == 0) {
emitOp0(OP_NIL);
}
emitOp0(OP_BLOCK_CONTINUE); // continue with last evaluated statement
} else if (compiler->type == FUN_TYPE_BLOCK) {
if (compiler->iseq.count == 0) {
emitOp0(OP_NIL);
emitOp0(OP_POP);
}
emitOp0(OP_BLOCK_CONTINUE); // continue with last evaluated statement
} else {
emitOp0(OP_NIL);
emitOp0(OP_RETURN);
}
}
}
static void emitCloseUpvalue(void) {
COMP_TRACE("Emitting close upvalue");
emitOp0(OP_CLOSE_UPVALUE);
}
static bool DEBUG_OP_POP = false;
static bytecode_t identifierLocal(Local *local);
static void popLocal(Local *local) {
if (DEBUG_OP_POP) {
emitOp1(OP_POP_DEBUG, identifierLocal(local));
} else {
emitOp0(OP_POP);
}
}
static void popScope(CompileScopeType stype) {
COMP_TRACE("popScope: %s (depth=%d)", compileScopeName(stype), current->scopeDepth);
while (current->localCount > 0 && current->locals[current->localCount - 1].depth >= current->scopeDepth) {
Local *local = ¤t->locals[current->localCount-1];
if (local->isUpvalue) {
COMP_TRACE("popScope closing upvalue");
emitCloseUpvalue();
} else {
if (current->type != FUN_TYPE_BLOCK && local->popOnScopeEnd) {
COMP_TRACE("popScope emitting OP_POP");
popLocal(local);
}
}
current->localCount--;
}
if (stype == COMPILE_SCOPE_FUNCTION || stype == COMPILE_SCOPE_MAIN) {
emitReturn(current);
}
curScope->bytecode_end = currentIseq()->wordCount;
curScope->line_end = curTok ? curTok->line : 0;
curScope = curScope->parent;
current->scopeDepth--;
}
static inline void emitNil() {
emitOp0(OP_NIL);
}
// exit from script
static inline void emitLeave() {
emitOp0(OP_LEAVE);
}
// Adds an upvalue to [compiler]'s function with the given properties. Does not
// add one if an upvalue for that variable is already in the list. Returns the
// index of the upvalue.
static int addUpvalue(Compiler *compiler, uint8_t index, bool isLocal) {
// Look for an existing one.
COMP_TRACE("Adding upvalue to COMP=%p, index: %d, isLocal: %s",
compiler, index, isLocal ? "true" : "false");
for (int i = 0; i < compiler->function->upvalueCount; i++) {
Upvalue *upvalue = &compiler->upvalues[i];
if (upvalue->index == index && upvalue->isLocal == isLocal) return i;
}
if (compiler->function->upvalueCount == LX_MAX_UPVALUES) {
error("Too many closure variables in function.");
return 0;
}
// If we got here, it's a new upvalue.
compiler->upvalues[compiler->function->upvalueCount].isLocal = isLocal;
compiler->upvalues[compiler->function->upvalueCount].index = index;
return compiler->function->upvalueCount++;
}
static bool identifiersEqual(Token *a, Token *b) {
if (a->length != b->length) return false;
return memcmp(tokStr(a), tokStr(b), a->length) == 0;
}
// returns -1 if local variable not found, otherwise returns slot index
// in the given compiler's locals table.
static int resolveLocal(Compiler *compiler, Token* name) {
// Look it up in the local scopes. Look in reverse order so that the most
// nested variable is found first and shadows outer ones.
for (int i = compiler->localCount - 1; i >= 0; i--) {
Local *local = &compiler->locals[i];
if (identifiersEqual(name, &local->name)) {
return i;
}
}
return -1;
}
// Attempts to look up [name] in the functions enclosing the one being compiled
// by [compiler]. If found, it adds an upvalue for it to this compiler's list
// of upvalues (unless it's already in there) and returns its index. If not
// found, returns -1.
//
// If the name is found outside of the immediately enclosing function, this
// will flatten the closure and add upvalues to all of the intermediate
// functions so that it gets walked down to this one.
static int resolveUpvalue(Compiler *compiler, Token *name) {
COMP_TRACE("Resolving upvalue for variable '%s'", tokStr(name));
// If we are at the top level, we didn't find it.
if (compiler->enclosing == NULL) return -1;
// See if it's a local variable in the immediately enclosing function.
int local = resolveLocal(compiler->enclosing, name);
if (local != -1) {
COMP_TRACE("Upvalue variable '%s' found as local", tokStr(name));
// Mark the local as an upvalue so we know to close it when it goes out of
// scope.
compiler->enclosing->locals[local].isUpvalue = true;
return addUpvalue(compiler, (uint8_t)local, true);
}
// See if it's an upvalue in the immediately enclosing function. In other
// words, if it's a local variable in a non-immediately enclosing function.
// This "flattens" closures automatically: it adds upvalues to all of the
// intermediate functions to get from the function where a local is declared
// all the way into the possibly deeply nested function that is closing over
// it.
int upvalue = resolveUpvalue(compiler->enclosing, name);
if (upvalue != -1) {
COMP_TRACE("Upvalue variable '%s' found as non-local", tokStr(name));
return addUpvalue(compiler, (uint8_t)upvalue, false);
}
// If we got here, we walked all the way up the parent chain and couldn't
// find it.
COMP_TRACE("Upvalue variable '%s' not found", tokStr(name));
return -1;
}
static bool isBinOp(Insn *in) {
bytecode_t code = in->code;
switch (code) {
case OP_ADD:
case OP_SUBTRACT:
case OP_MULTIPLY:
case OP_DIVIDE:
case OP_MODULO:
case OP_BITOR:
case OP_BITAND:
case OP_BITXOR:
case OP_SHOVEL_L:
case OP_SHOVEL_R:
return true;
default:
return false;
}
}
static bool isNumConstOp(Insn *in) {
return in->code == OP_CONSTANT && ((in->flags & INSN_FL_NUMBER) != 0);
}
static Value iseqGetConstant(Iseq *seq, bytecode_t idx) {
return seq->constants->values[idx];
}
static Value foldConstant(Iseq *seq, Insn *cur, Insn *bin, Insn *ain) {
Value b = iseqGetConstant(seq, bin->operands[0]);
Value a = iseqGetConstant(seq, ain->operands[0]);
double aNum = AS_NUMBER(a);
double bNum = AS_NUMBER(b);
switch (cur->code) {
case OP_ADD:
return NUMBER_VAL(aNum + bNum);
case OP_SUBTRACT:
return NUMBER_VAL(aNum - bNum);
case OP_MULTIPLY:
return NUMBER_VAL(aNum * bNum);
case OP_DIVIDE:
if (bNum == 0.00) {
fprintf(stderr, "[Warning]: Divide by 0 found on line %d during constant folding\n", bin->lineno);
return UNDEF_VAL;
}
return NUMBER_VAL(aNum / bNum);
case OP_MODULO:
if (bNum == 0.00) {
fprintf(stderr, "[Warning]: Divide by 0 found on line %d during constant folding\n", bin->lineno);
return UNDEF_VAL;
}
return NUMBER_VAL((int)aNum % (int)bNum);
case OP_BITOR:
return NUMBER_VAL((double)((int)aNum | (int)bNum));
case OP_BITAND:
return NUMBER_VAL((double)((int)aNum & (int)bNum));
case OP_BITXOR:
return NUMBER_VAL((double)((int)aNum ^ (int)bNum));
case OP_SHOVEL_L: {
// TODO: detect overflow for doubles
double num = (double)((int)aNum << (int)bNum);
return NUMBER_VAL(num);
}
case OP_SHOVEL_R:
return NUMBER_VAL((double)((int)aNum >> (int)bNum));
default:
UNREACHABLE("bug");
}
}
static void changeConstant(Iseq *seq, bytecode_t constIdx, Value newVal) {
ASSERT((int)constIdx < seq->constants->count);
seq->constants->values[constIdx] = newVal;
}
static bool isJump(Insn *in) {
switch (in->code) {
case OP_JUMP:
case OP_JUMP_IF_FALSE:
case OP_JUMP_IF_TRUE:
case OP_JUMP_IF_TRUE_PEEK:
case OP_JUMP_IF_FALSE_PEEK:
return true;
default:
return false;
}
}
static bool isLoop(Insn *in) {
return in->code == OP_LOOP;
}
static inline bool isJumpNextInsn(Insn *in) {
return in->operands[0] == 0;
}
static void patchJumpInsnWithOffset(Insn *jump, int offset) {
if (jump->operands[0]+offset > BYTECODE_MAX) {
ASSERT(0); // TODO: error out
}
if (jump->operands[0]+offset <= 0) {
ASSERT(0); // TODO: error out
}
jump->operands[0] += offset;
}
/* Remove the given instruction. If there's a forward jump to this instruction or
* to an instruction after it, the jump needs to be patched. If there's a backwards jump
* to this instruction or to an instruction before it, the jump needs to be patched.
*/
static void rmInsnAndPatchJumps(Iseq *seq, Insn *insn) {
int insnIdx = iseqInsnIndex(seq, insn);
ASSERT(insnIdx >= 0);
OPT_DEBUG(2, "rmInsnAndPatchLabels insnIdx: %d\n", insnIdx);
Insn *in = seq->insns;
int idx = 0;
while (in) {
if (in == insn) { // it will be removed at the end of the function
in = in->next;
idx++;
continue;
}
// jump instruction found before removed instruction, if it jumps
// to the removed instruction or after it, then patch the jump
if (idx < insnIdx && isJump(in)) {
OPT_DEBUG(2, "Found jump at %d", idx);
ASSERT(in->jumpTo || in->jumpToPrev);
Insn *jumpTo = in->jumpTo;
if (!jumpTo) {
jumpTo = in->jumpToPrev->next;
}
ASSERT(jumpTo);
int jumpToIndex = iseqInsnIndex(seq, jumpTo);
ASSERT(jumpToIndex >= 0);
OPT_DEBUG(2, "Jump to index: %d", jumpToIndex);
if (jumpToIndex >= insnIdx) {
if (jumpToIndex == insnIdx) {
in->jumpTo = insn->next; // TODO: might be last instruction, in which case the jump should be removed
}
OPT_DEBUG(2, "Patching jump, offset before: %d", in->operands[0]);
patchJumpInsnWithOffset(in, -(insn->numOperands+1));
OPT_DEBUG(2, "Patched jump, offset after: %d", in->operands[0]);
}
// loop instruction found after removed instruction, if it jumps
// to the removed instruction or before it, then patch the loop
} else if (idx > insnIdx && isLoop(in)) {
OPT_DEBUG(2, "Found loop at %d", idx);
ASSERT(in->jumpTo);
int jumpToIndex = iseqInsnIndex(seq, in->jumpTo);
ASSERT(jumpToIndex >= 0);
OPT_DEBUG(2, "Jump to index: %d", jumpToIndex);
if (jumpToIndex <= insnIdx) {
if (jumpToIndex == insnIdx) {
in->jumpTo = insn->next;
}
OPT_DEBUG(2, "Patching jump, offset before: %d", in->operands[0]);
patchJumpInsnWithOffset(in, -(insn->numOperands+1));
OPT_DEBUG(2, "Patched jump, offset after: %d", in->operands[0]);
}
}
in = in->next;
idx++;
}
iseqRmInsn(seq, insn);
}
static int replaceJumpInsn(Iseq *seq, Insn *jumpInsn) {
switch (jumpInsn->code) {
case OP_JUMP:
case OP_JUMP_IF_FALSE_PEEK:
case OP_JUMP_IF_TRUE_PEEK:
if (!jumpInsn->isLabel) {
rmInsnAndPatchJumps(seq, jumpInsn);
return -1;
} else {
return 0;
}
case OP_JUMP_IF_FALSE:
if (!jumpInsn->isLabel) {
jumpInsn->code = OP_POP;
jumpInsn->numOperands = 0;
}
return 0;
default:
UNREACHABLE("bug");
}
}
static bool isConst(Insn *insn) {
switch (insn->code) {
case OP_CONSTANT:
case OP_FALSE:
case OP_TRUE:
case OP_NIL:
return true;
}
return false;
}
static bool constBool(Insn *insn) {
switch (insn->code) {
case OP_CONSTANT:
case OP_TRUE:
return true;
case OP_FALSE:
case OP_NIL:
return false;
default:
UNREACHABLE("bug");
}
}
// Array literals can have side effects, ex;
static bool noSideEffectsConst(Insn *insn) {
return isConst(insn);
}
static inline bool isJumpIfFalse(Insn *insn) {
return insn->code == OP_JUMP_IF_FALSE;
}
static inline bool isJumpIfTrue(Insn *insn) {
return insn->code == OP_JUMP_IF_TRUE_PEEK;
}
static inline bool isPop(Insn *insn) {
return insn->code == OP_POP;
}
static inline bool isPopType(Insn *insn) {
return insn->code == OP_POP || insn->code == OP_POP_N;
}
static inline bool isPopType2(Insn *insn) {
return insn->code == OP_POP || insn->code == OP_POP_N ||
insn->code == OP_POP_DEBUG;
}
static inline bool isJumpTarget(Insn *insn) {
return insn->isLabel;
}
static void addInsnOperand(Iseq *seq, Insn *insn, bytecode_t operand) {
ASSERT(insn->numOperands >= 0);
if (insn->numOperands == MAX_INSN_OPERANDS) {
UNREACHABLE("too many operands"); // TODO: error out
}
insn->operands[insn->numOperands] = operand;
insn->numOperands+=1;
seq->wordCount += 1;
int insnIdx = iseqInsnIndex(seq, insn);
ASSERT(insnIdx >= 0);
Insn *in = seq->insns;
int idx = 0;
while (in) {
if (in == insn) {
in = in->next;
idx++;
continue;
}
// jump instruction found before altered instruction, if it jumps
// to the altered instruction or after it, then patch the jump
if (idx < insnIdx && isJump(in)) {
OPT_DEBUG(2, "Found jump at %d", idx);
Insn *jumpTo = in->jumpTo;
if (!jumpTo) {
jumpTo = in->jumpToPrev->next;
}
ASSERT(jumpTo);
int jumpToIndex = iseqInsnIndex(seq, jumpTo);
ASSERT(jumpToIndex >= 0);
OPT_DEBUG(2, "Jump to index: %d", jumpToIndex);
if (jumpToIndex >= insnIdx) {
if (jumpToIndex == insnIdx) {
in->jumpTo = insn->next; // TODO: might be last instruction, in which case the jump should be removed
in->jumpToPrev = NULL;
}
OPT_DEBUG(2, "Patching jump, offset before: %d", in->operands[0]);
patchJumpInsnWithOffset(in, 1);
OPT_DEBUG(2, "Patched jump, offset after: %d", in->operands[0]);
}
} else if (idx > insnIdx && isLoop(in)) {
OPT_DEBUG(2, "Found loop at %d", idx);
ASSERT(in->jumpTo);
int jumpToIndex = iseqInsnIndex(seq, in->jumpTo);
ASSERT(jumpToIndex >= 0);
OPT_DEBUG(2, "Jump to index: %d", jumpToIndex);
if (jumpToIndex <= insnIdx) {
if (jumpToIndex == insnIdx) {
in->jumpTo = insn->next;
}
OPT_DEBUG(2, "Patching jump, offset before: %d\n", in->operands[0]);
patchJumpInsnWithOffset(in, 1);
OPT_DEBUG(2, "Patched jump, offset after: %d\n", in->operands[0]);
}
}
in = in->next;
idx++;
}
}
static void optimizeIseq(Iseq *iseq) {
COMP_TRACE("OptimizeIseq");
Insn *cur = iseq->insns; // first insn
Insn *prev = NULL;
Insn *prevp = NULL;
int idx = 0;
while (cur) {
COMP_TRACE("optimize idx %d", idx);
prev = cur->prev; // can be NULL
prevp = NULL;
// constant folding, ex: turn 2+2 into 4
if (isBinOp(cur)) {
if (prev && ((prevp = prev->prev) != NULL)) {
if (isNumConstOp(prev) && isNumConstOp(prevp)) {
COMP_TRACE("constant folding candidate found");
Value newVal = foldConstant(iseq, cur, prev, prevp);
if (IS_UNDEF(newVal)) { // such as divide by 0
cur = cur->next;
idx++;
continue;
}
changeConstant(iseq, prevp->operands[0], newVal);
rmInsnAndPatchJumps(iseq, cur);
rmInsnAndPatchJumps(iseq, prev);
cur = prevp;
idx -= 2;
continue;
}
}
}
// consolidate OP_POPs
if (prev && isPopType(prev) && isPopType(cur) && !isJumpTarget(prev) && !isJumpTarget(cur)) {
int n = prev->code == OP_POP ? 1 : prev->operands[0];
rmInsnAndPatchJumps(iseq, prev);
if (cur->code == OP_POP) {
addInsnOperand(iseq, cur, n+1);
cur->code = OP_POP_N;
} else {
ASSERT(cur->code == OP_POP_N);
cur->operands[0] += n;
}
}
// jump to next insn replacement/deletion
if (isJump(cur) && isJumpNextInsn(cur)) {
COMP_TRACE("Turning jump to next insn into POP/deletion");
Insn *next = cur->next;
replaceJumpInsn(iseq, cur);
COMP_TRACE("replacement done");
idx = 0;
cur = next;
continue;
}
// replace/remove jump instruction if test is a constant (ex: `if (true)`) =>
// OP_TRUE, OP_POP
if (isJump(cur) && (prev && isConst(prev))) {
COMP_TRACE("Found constant conditional, removing/replacing JUMP");
bool deleted = false;
if (isJumpIfFalse(cur) && constBool(prev)) {
deleted = replaceJumpInsn(iseq, cur) < 0;
} else if (isJumpIfTrue(cur) && !constBool(prev)) {
deleted = replaceJumpInsn(iseq, cur) < 0;
}
COMP_TRACE("/removed/replaced JUMP? %s", deleted ? "removed" : "replaced");
if (deleted) {
cur = iseq->insns;
idx = 0;
continue;
} else {
cur = cur->next;
idx++;
continue;
}
}
// 1+1; OP_CONSTANT '2', OP_POP => nothing (unused constant expression)
if (!compilerOpts.noRemoveUnusedExpressions) {
if (isPop(cur) && (prev && noSideEffectsConst(prev))) {
Insn *next = cur->next;
// OP_BLOCK_CONTINUE takes the popped value from previous pop, so needs it
if (!next || next->code != OP_BLOCK_CONTINUE) {
COMP_TRACE("removing side effect expr 1");
rmInsnAndPatchJumps(iseq, prev);
COMP_TRACE("removing side effect expr 2");
rmInsnAndPatchJumps(iseq, cur);
cur = iseq->insns;
idx = 0;
continue;
}
}
}
idx++;
cur = cur->next;
}
COMP_TRACE("/OptimizeIseq");
}
static void copyIseqToChunk(Iseq *iseq, Chunk *chunk) {
ASSERT(iseq);
ASSERT(chunk);
if (!compilerOpts.noOptimize) {
optimizeIseq(iseq);
}
COMP_TRACE("copyIseqToChunk (%d insns, wordcount: %d)", iseq->count, iseq->wordCount);
chunk->catchTbl = iseq->catchTbl;
chunk->constants = iseq->constants;
ASSERT(chunk->constants);
Insn *in = iseq->insns;
int idx = 0;
while (in) {
idx++;
writeChunkWord(chunk, in->code, in->lineno, in->nlvl.depth, in->nlvl.width);
for (int i = 0; i < in->numOperands; i++) {
writeChunkWord(chunk, in->operands[i], in->lineno, in->nlvl.depth, in->nlvl.width);
}
in = in->next;
}
ASSERT(idx == iseq->count);
COMP_TRACE("/copyIseqToChunk");
}
static ObjFunction *endCompiler() {
COMP_TRACE("endCompiler");
ASSERT(current);
if (current->type == FUN_TYPE_TOP_LEVEL || current->type == FUN_TYPE_EVAL) {
emitLeave();
}
ObjFunction *func = current->function;
copyIseqToChunk(currentIseq(), currentChunk());
freeTable(¤t->constTbl);
freeIseq(¤t->iseq);
func->localCount = current->localCountMax;
current = current->enclosing;
COMP_TRACE("/endCompiler");
return func;
}
// Adds a constant to the current instruction sequence's constant pool
// and returns an index to it.
static bytecode_t makeConstant(Value value, ConstType ctype) {
Value existingIdx;
bool canMemoize = ctype == CONST_T_STRLIT;
if (canMemoize) {
if (tableGet(¤t->constTbl, value, &existingIdx)) {
return (bytecode_t)AS_NUMBER(existingIdx);
}
}
int constant = iseqAddConstant(currentIseq(), value);
if ((bytecode_t)constant > BYTECODE_MAX) {
error("Too many constants in one chunk.");
return 0;
}
if (canMemoize) {
ASSERT(
tableSet(¤t->constTbl, value, NUMBER_VAL(constant))
);
}
return (bytecode_t)constant;
}
// Add constant to constant pool from the token's lexeme, return index to it
static bytecode_t identifierConstant(Token *name) {
DBG_ASSERT(vm.inited);
ObjString *ident = INTERNED(tokStr(name), name->length);
STRING_SET_STATIC(ident);
return makeConstant(OBJ_VAL(ident), CONST_T_STRLIT);
}
static bytecode_t identifierLocal(Local *local) {
return identifierConstant(&local->name);
}
// Add constant to constant pool from the token's lexeme, return index to it
static bytecode_t identifierString(const char *str) {
DBG_ASSERT(vm.inited);
ObjString *ident = INTERN(str);
STRING_SET_STATIC(ident);
return makeConstant(OBJ_VAL(ident), CONST_T_STRLIT);
}
// emits a constant instruction with the given operand
static Insn *emitConstant(Value constant, ConstType ctype) {
Insn *ret = emitOp1(OP_CONSTANT, makeConstant(constant, ctype));
if (ctype == CONST_T_NUMLIT) ret->flags |= INSN_FL_NUMBER;
return ret;
}
static void emitNode(Node *n);
static void emitChildren(Node *n) {
Node *stmt = NULL;
int i = 0;
nodeDepth++;
int lastWidth = nodeWidth;
nodeWidth = 0;
ASSERT(n->children);
vec_foreach(n->children, stmt, i) {
ASSERT(stmt);
emitNode(stmt);
}
nodeDepth--;
nodeWidth = lastWidth;
}
// emit a jump (forwards) instruction, returns a pointer to the byte that needs patching
static inline Insn *emitJump(OpCode jumpOp) {
return emitOp1(jumpOp, 0); // patched later
}
static inline Insn *emitBreak(void) {
Insn *br = emitOp2(OP_BREAK, 0, current->localCount - loopLocalCount); // patched later
return br;
}
static int insnOffset(Insn *start, Insn *end) {
ASSERT(start);
ASSERT(end);
int offset = 0;
Insn *cur = start;
while (cur && cur != end) {
offset += (cur->numOperands)+1;
cur = cur->next;
}
if (cur != end) {
ASSERT(0);
return -1;
}
return offset;
}
// patch jump forwards instruction by given offset
static void patchJump(Insn *toPatch, int jumpoffset, Insn *jumpTo) {
ASSERT(toPatch->operands[0] == 0);
ASSERT(toPatch->jumpTo == NULL);
bool jumpToNext = false;
if (jumpoffset == -1) {
if (!jumpTo) {
jumpTo = currentIseq()->tail;
}
jumpoffset = insnOffset(toPatch, jumpTo)+jumpTo->numOperands;
if (jumpTo->next == NULL) {
jumpToNext = true;
}
}
toPatch->operands[0] = jumpoffset;
if (jumpToNext) {
nextInsnIsLabel = true;
toPatch->jumpToPrev = jumpTo;
} else {
toPatch->jumpTo = jumpTo;
jumpTo->isLabel = true;
}
}
static inline bool isContinue(Insn *in) {
return (in->code == OP_JUMP &&
(in->flags & INSN_FL_CONTINUE) != 0);
}
static Insn *getInsnTail(int tail_index) {
Insn *cur = currentIseq()->tail;
int idx = tail_index;
while (cur && idx > 0) {
cur = cur->prev;
idx--;
}
return cur;
}
static void patchContinuesBetween(Insn *a, Insn *b) {
Insn *cur = a;
while (cur != b) {
if (isContinue(cur)) {
int insn_tail_index = cur->extra; // number of pops to keep
Insn *jumpTo = getInsnTail(insn_tail_index);
if (insn_tail_index > 0) {
ASSERT(isPopType2(jumpTo));
}
patchJump(cur, -1, jumpTo);
COMP_TRACE("jump offset found, patching continue (pops=%d)", insn_tail_index);
}
cur = cur->next;
}
}
// Emit a jump backwards (loop) instruction from the current code count to offset `loopStart`
static void emitLoop(int loopStart) {
int offset = (currentIseq()->wordCount - loopStart)+2;
if ((bytecode_t)offset > BYTECODE_MAX) error("Loop body too large.");
ASSERT(offset >= 0);
Insn *loopInsn = emitOp1(OP_LOOP, offset);
loopInsn->jumpTo = insnAtOffset(currentIseq(), loopStart-2);
ASSERT(loopInsn->jumpTo);
loopInsn->jumpTo->isLabel = true;
}
static inline bool isBreak(Insn *in) {
return (in->code == OP_BREAK);
}
static void patchBreak(Insn *br, int offset, Insn *label) {
br->operands[0] = offset;
if (label) {
label->isLabel = true;
}
}
static void patchBreaks(Insn *start, Insn *end, int offset) {
Insn *cur = start;