-
Notifications
You must be signed in to change notification settings - Fork 159
/
amacc.c
2514 lines (2366 loc) · 92.3 KB
/
amacc.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
/*
* AMaCC is capable of compiling (subset of) C source files into GNU/Linux
* executables or running via just-in-time compilation on 32-bit ARM
* processor-based platforms. There is no preprocessor.
*
* The following options are supported:
* -s : Print source and generated intermediate representation (IR).
* -o : Create executable file and terminate normally.
*
* If -o and -s are omitted, the compiled code is executed immediately (if
* there were no compile errors) with the command line arguments passed
* after the source file parameter.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dlfcn.h>
/* 64-bit host support */
#if defined(__x86_64__) || defined(__aarch64__)
#define int long
#endif
char *freep, *p, *lp; // current position in source code
char *freedata, *data, *_data; // data/bss pointer
int *e, *le, *text; // current position in emitted code
int *cas; // case statement patch-up pointer
int *def; // default statement patch-up pointer
int *brks; // break statement patch-up pointer
int *cnts; // continue statement patch-up pointer
int swtc; // !0 -> in a switch-stmt context
int brkc; // !0 -> in a break-stmt context
int cntc; // !0 -> in a continue-stmt context
int *tsize; // array (indexed by type) of type sizes
int tnew; // next available type
int tk; // current token
int ival; // current token value
int ty; // current expression type
int compound; // handle precedence of compound assignment
int loc; // local variable offset
int line; // current line number
int src; // print source and assembly flag
int signed_char; // use `signed char` for `char`
int elf; // print ELF format
int *n; // current position in emitted abstract syntax tree
// With an AST, the compiler is not limited to generate
// code on the fly with parsing.
// This capability allows function parameter code to be
// emitted and pushed on the stack in the proper
// right-to-left order.
int ld; // local variable depth
// identifier
struct ident_s {
int tk; // type-id or keyword
int hash;
char *name; // name of this identifier
/* fields starting with 'h' were designed to save and restore
* the global class/type/val in order to handle the case if a
* function declares a local with the same name as a global.
*/
int class, hclass; // FUNC, GLO (global var), LOC (local var), Syscall
int type, htype; // data type such as char and int
int val, hval;
int stype;
} *id, // currently parsed identifier
*sym; // symbol table (simple list of identifiers)
// (library) external functions
struct ef_s {
char *name;
int addr;
} **ef_cache;
int ef_count;
struct member_s {
struct ident_s *id;
int offset;
int type;
struct member_s *next;
} **members; // array (indexed by type) of struct member lists
// tokens and classes (operators last and in precedence order)
// ( >= 128 so not to collide with ASCII-valued tokens)
enum {
Num = 128, // the character set of given source is limited to 7-bit ASCII
Func, Syscall, Main, ClearCache, Glo, Par, Loc, Keyword, Id, Label, Load, Enter,
Break, Continue, Case, Char, Default, Else, Enum, If, Int, Return,
Sizeof, Struct, Union, Switch, For, While, DoWhile, Goto,
Assign, // operator =, keep Assign as highest priority operator
OrAssign, XorAssign, AndAssign, ShlAssign, ShrAssign, // |=, ^=, &=, <<=, >>=
AddAssign, SubAssign, MulAssign, DivAssign, ModAssign, // +=, -=, *=, /=, %=
Cond, // operator: ?
Lor, Lan, Or, Xor, And, // operator: ||, &&, |, ^, &
Eq, Ne, Lt, Gt, Le, Ge, // operator: ==, !=, <, >, <=, >=
Shl, Shr, Add, Sub, Mul, Div, Mod, // operator: <<, >>, +, -, *, /, %
Inc, Dec, Dot, Arrow, Bracket, // operator: ++, --, ., ->, [
};
// opcodes
/* The instruction set is designed for building intermediate representation.
* Expression 10 + 20 will be translated into the following instructions:
* i = 0;
* text[i++] = IMM;
* text[i++] = 10;
* text[i++] = PSH;
* text[i++] = IMM;
* text[i++] = 20;
* text[i++] = ADD;
* text[i++] = PSH;
* text[i++] = EXIT;
* pc = text;
*/
enum {
LEA , /* 0 */
/* LEA addressed the problem how to fetch arguments inside sub-function.
* Let's check out what a calling frame looks like before learning how
* to fetch arguments (Note that arguments are pushed in its calling
* order):
*
* sub_function(arg1, arg2, arg3);
*
* | .... | high address
* +---------------+
* | arg: 1 | new_bp + 4
* +---------------+
* | arg: 2 | new_bp + 3
* +---------------+
* | arg: 3 | new_bp + 2
* +---------------+
* |return address | new_bp + 1
* +---------------+
* | old BP | <- new BP
* +---------------+
* | local var 1 | new_bp - 1
* +---------------+
* | local var 2 | new_bp - 2
* +---------------+
* | .... | low address
*
* If we need to refer to arg1, we need to fetch new_bp + 4, which can not
* be achieved by restricted ADD instruction. Thus another special
* Instruction is introduced to do this: LEA <offset>.
* The following pseudocode illustrates how LEA works.
* if (op == LEA) { ax = (int) (bp + *pc++); } // load address for arguments
* Together with JSR, ENT, ADJ, LEV, and LEA instruction, we are able to make
* function calls.
*/
IMM , /* 1 */
/* IMM <num> to put immediate <num> into general register */
JMP , /* 2 */
/* JMP <addr> will unconditionally set the value PC register to <addr> */
/* The following pseudocode illustrates how JMP works:
* if (op == JMP) { pc = (int *) *pc; } // jump to the address
* Note that PC points to the NEXT instruction to be executed. Thus *pc
* stores the argument of JMP instruction, i.e. the <addr>.
*/
JSR , /* 3 */
/* A function is a block of code, which may be far from the instruction
* we are currently executing. That is reason why JMP instruction exists,
* jumping into starting point of a function. JSR is introduced to perform
* some bookkeeping: store the current execution position so that the
* program can resume after function call returns.
*
* JSR <addr> to invoke the function whose starting point is <addr> and
* LEV to fetch the bookkeeping information to resume previous execution.
*/
BZ , /* 4 : conditional jump if general register is zero (jump-if-zero) */
BNZ , /* 5 : conditional jump if general register is not zero */
ENT , /* 6 */
/* ENT <size> is called when we are about to enter the function call to
* "make a new calling frame". It will store the current PC value onto
* the stack, and save some space(<size> bytes) to store the local
* variables for function.
*/
ADJ , /* 7 */
/* ADJ <size> is to adjust the stack, to "remove arguments from frame"
* The following pseudocode illustrates how ADJ works:
* if (op == ADJ) { sp += *pc++; } // add esp, <size>
*/
LEV , /* 8 */
/* LEV fetches bookkeeping info to resume previous execution.
* There is no POP instruction in our design, and the following pseudocode
* illustrates how LEV works:
* if (op == LEV) { sp = bp; bp = (int *) *sp++;
* pc = (int *) *sp++; } // restore call frame and PC
*/
LI , /* 9 */
/* LI loads an integer into general register from a given memory
* address which is stored in general register before execution.
*/
LC , /* 10 */
/* LC loads a character into general register from a given memory
* address which is stored in general register before execution.
*/
SI , /* 11 */
/* SI stores the integer in general register into the memory whose
* address is stored on the top of the stack.
*/
SC , /* 12 */
/* SC stores the character in general register into the memory whose
* address is stored on the top of the stack.
*/
PSH , /* 13 */
/* PSH pushes the value in general register onto the stack */
OR , /* 14 */ XOR , /* 15 */ AND , /* 16 */
EQ , /* 17 */ NE , /* 18 */
LT , /* 19 */ GT , /* 20 */ LE , /* 21 */ GE , /* 22 */
SHL , /* 23 */ SHR , /* 24 */
ADD , /* 25 */ SUB , /* 26 */ MUL , /* 27 */ DIV, /* 28 */ MOD, /* 29 */
/* arithmetic instructions
* Each operator has two arguments: the first one is stored on the top
* of the stack while the second is stored in general register.
* After the calculation is done, the argument on the stack will be poped
* out and the result will be stored in general register.
* So you are not able to fetch the first argument from the stack after
* the calculation.
*/
SYSC, /* 30 system call */
CLCA, /* 31 clear cache, used by JIT compilation */
INVALID
};
// types
enum { CHAR, INT, PTR = 256, PTR2 = 512 };
// ELF generation
char **plt_func_addr;
char *freebuf;
char *append_strtab(char **strtab, char *str)
{
char *s;
for (s = str; *s && (*s != ' '); s++) ; /* ignore trailing space */
int nbytes = s - str + 1;
char *res = *strtab;
memcpy(res, str, nbytes);
res[s - str] = 0; // null terminator
*strtab = res + nbytes;
return res;
}
char fatal(char *msg) { printf("%d: %s\n", line, msg); exit(-1); }
void ef_add(char *name, int addr) // add external function
{
ef_cache[ef_count] = malloc(sizeof(struct ef_s)) ;
ef_cache[ef_count]->name = malloc(strlen(name)+1);
strcpy(ef_cache[ef_count]->name, name);
ef_cache[ef_count]->addr = addr;
++ef_count;
}
int ef_getaddr(int idx) // get address external function
{
return (elf ? (int) plt_func_addr[idx] : ef_cache[idx]->addr);
}
int ef_getidx(char *name) // get cache index of external function
{
int i;
for (i = 0; i < ef_count; ++i)
if (!strcmp(ef_cache[i]->name, name))
break;
if (i == ef_count) { // add new external lib func to cache
int dladdr;
if ((dladdr = (int) dlsym(0, name))) {
ef_add(name, dladdr);
} else {
void *divmod_handle = dlopen("libgcc_s.so.1", 1);
if (!divmod_handle) fatal("failed to open libgcc_s.so.1");
dladdr = (int) dlsym(divmod_handle, name);
if (!dladdr) fatal("bad function call");
ef_add(name, dladdr);
}
}
return i;
}
/* parse next token
* 1. store data into id and then set the id to current lexical form
* 2. set tk to appropriate type
*/
void next()
{
char *pp;
/* using loop to ignore whitespace characters, but characters that
* cannot be recognized by the lexical analyzer are considered blank
* characters, such as '@' and '$'.
*/
while ((tk = *p)) {
++p;
if ((tk >= 'a' && tk <= 'z') || (tk >= 'A' && tk <= 'Z') ||
(tk == '_')) {
pp = p - 1;
while ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') || (*p == '_'))
tk = tk * 147 + *p++; // 147 is the magic number generating hash value
tk = (tk << 6) + (p - pp); // hash plus symbol length
// hash value is used for fast comparison. Since it is inaccurate,
// we have to validate the memory content as well.
for (id = sym; id->tk; id++) { // find one free slot in table
if (tk == id->hash && /* if token is found (hash match), overwrite */
!memcmp(id->name, pp, p - pp)) {
tk = id->tk;
return;
}
}
/* At this point, existing symbol name is not found.
* "id" points to the first unused symbol table entry.
*/
id->name = pp;
id->hash = tk;
tk = id->tk = Id; // token type identifier
return;
}
/* Calculate the constant */
// first byte is a number, and it is considered a numerical value
else if (tk >= '0' && tk <= '9') {
/* Parse with 3 conditions:
* 1) not starting with 0 :=> decimal number;
* 2) starting with 0x :=> hex number;
* 3) starting with 0: octal number;
*/
if ((ival = tk - '0')) {
while (*p >= '0' && *p <= '9')
ival = ival * 10 + *p++ - '0';
}
// first digit is 0 and it starts with 'x', and it is considered
// to be a hexadecimal number
else if (*p == 'x' || *p == 'X') {
while ((tk = *++p) &&
((tk >= '0' && tk <= '9') ||
(tk >= 'a' && tk <= 'f') || (tk >= 'A' && tk <= 'F')))
ival = ival * 16 + (tk & 15) + (tk >= 'A' ? 9 : 0);
} else { // considered octal
while (*p >= '0' && *p <= '7')
ival = ival * 8 + *p++ - '0';
}
tk = Num; // token is numeric, return
return;
}
switch (tk) {
case '\n':
/* Take an integer (representing an operation) and print out
* the name of that operation. First thing to say is that "* ++le"
* is the integer representing the operation to perform.
* This basically walks through the array of instructions
* returning each integer in turn.
*
* Starting at the beginning of the line, we have "printf" with
* a format string of "%8.4s". This means printing out the first 4
* characters of the string that we are about to pass next (padded
* to 8 characters). There then follows a string containing all of
* the operation names, in numerical order, padded to 4 characters
* and separated by commas (so the start of each is 5 apart).
*
* Finally, we do a lookup into this string (treating it as an
* array) at offset "* ++le * 5", i.e. the integer representing
* the operation multiplied by "5", being the number of characters
* between the start of each operation name). Doing this lookup
* gives us a char, but actually we wanted the pointer to this
* char (as we want printf to print out this char and the
* following 3 chars), so we take the address of this char
* (the "&" at the beginning of the whole expression).
*/
if (src) {
int *base = le;
printf("%d: %.*s", line, p - lp, lp);
lp = p;
while (le < e) {
int off = le - base; // Func IR instruction memory offset
printf("%04d: %8.4s", off,
& "LEA IMM JMP JSR BZ BNZ ENT ADJ LEV "
"LI LC SI SC PSH "
"OR XOR AND EQ NE LT GT LE GE "
"SHL SHR ADD SUB MUL DIV MOD "
"SYSC CLCA" [*++le * 5]);
if (*le <= ADJ) {
++le;
if (*le > (int) base && *le <= (int) e)
printf(" %04d\n", off + ((*le - (int) le) >> 2) + 1);
else
printf(" %d\n", *le);
}
else if (*le == SYSC) {
printf(" %s\n", ef_cache[*(++le)]->name);
}
else printf("\n");
}
}
++line;
case ' ':
case '\t':
case '\v':
case '\f':
case '\r':
break;
case '/':
if (*p == '/') { // comment
case '#': // skip #include statement, preprocessor directives ignored
while (*p != 0 && *p != '\n') ++p;
} else if (*p == '*') { // C-style multiline comments
int t = 0;
for (++p; (*p != 0) && (t == 0); ++p) {
pp = p + 1;
if (*p == '\n') line++;
else if (*p == '*' && *pp == '/') t = 1;
}
++p;
} else {
if (*p == '=') { ++p; tk = DivAssign; }
else tk = Div; return;
}
break;
case '\'': // quotes start with character (string)
case '"':
pp = data;
// While current character is not `\0` and current character is
// not the quote character.
while (*p != 0 && *p != tk) {
// If current character is '\', it is escape notation or simply
// '\' character.
if ((ival = *p++) == '\\') {
switch (ival = *p++) {
case 'n': ival = '\n'; break; // new line
case 't': ival = '\t'; break; // horizontal tab
case 'v': ival = '\v'; break; // vertical tab
case 'f': ival = '\f'; break; // form feed
case 'r': ival = '\r'; break; // carriage return
case '0': ival = '\0'; break; // an int with value 0
}
}
// If it is double quotes (string literal), it is considered as
// a string, copying characters to data
if (tk == '"') *data++ = ival;
}
++p;
// If .text too big rwdata v_addr will overlap it, add that to stay away from .text
if (tk == '"') ival = (int) pp; else tk = Num;
return;
case '=': if (*p == '=') { ++p; tk = Eq; } else tk = Assign; return;
case '+': if (*p == '+') { ++p; tk = Inc; }
else if (*p == '=') { ++p; tk = AddAssign; }
else tk = Add; return;
case '-': if (*p == '-') { ++p; tk = Dec; }
else if (*p == '>') { ++p; tk = Arrow; }
else if (*p == '=') { ++p; tk = SubAssign; }
else tk = Sub; return;
case '!': if (*p == '=') { ++p; tk = Ne; } return;
case '<': if (*p == '=') { ++p; tk = Le; }
else if (*p == '<') {
++p; if (*p == '=') { ++p ; tk = ShlAssign; } else tk = Shl;
}
else tk = Lt; return;
case '>': if (*p == '=') { ++p; tk = Ge; }
else if (*p == '>') {
++p; if (*p == '=') { ++p ; tk = ShrAssign; } else tk = Shr;
}
else tk = Gt; return;
case '|': if (*p == '|') { ++p; tk = Lor; }
else if (*p == '=') { ++p; tk = OrAssign; }
else tk = Or; return;
case '&': if (*p == '&') { ++p; tk = Lan; }
else if (*p == '=') { ++p; tk = AndAssign; }
else tk = And; return;
case '^': if (*p == '=') { ++p; tk = XorAssign; } else tk = Xor; return;
case '*': if (*p == '=') { ++p; tk = MulAssign; }
else tk = Mul; return;
case '%': if (*p == '=') { ++p; tk = ModAssign; }
else tk = Mod; return;
case '[': tk = Bracket; return;
case '?': tk = Cond; return;
case '.': tk = Dot; return;
default: return;
}
}
}
// https://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer
int popcount(int i)
{
i = i - ((i >> 1) & 0x55555555); // add pairs of bits
i = (i & 0x33333333) + ((i >> 2) & 0x33333333); // quads
i = (i + (i >> 4)) & 0x0F0F0F0F; // groups of 8
return (i * 0x01010101) >> 24; // horizontal sum of bytes
}
/* expression parsing
* lev represents an operator.
* because each operator `token` is arranged in order of priority, so
* large `lev` indicates a high priority.
*
* Operator precedence (lower first):
* Assign =
* Cond ?
* Lor ||
* Lan &&
* Or |
* Xor ^
* And &
* Eq ==
* Ne !=
* Lt <
* Gt >
* Le <=
* Ge >=
* Shl <<
* Shr >>
* Add +
* Sub -
* Mul *
* Div /
* Mod %
* Inc ++
* Dec --
* Bracket [
*/
enum { REENTRANT = 0x10000 };
void expr(int lev)
{
int tc;
int t, *b, sz, *c;
struct ident_s *d;
struct member_s *m;
switch (tk) {
case 0: fatal("unexpected EOF in expression");
// directly take an immediate value as the expression value
// IMM recorded in emit sequence
case Num: *--n = ival; *--n = Num; next(); ty = INT; break;
case '"': // string, as a literal in data segment
*--n = ival; *--n = Num; next();
// continuous `"` handles C-style multiline text such as `"abc" "def"`
while (tk == '"') next();
/* Point "data" to next integer-aligned address.
* e.g. "-sizeof(int)" is -4, i.e. 0b11111100.
* This guarantees to leave at least one '\0' after the string.
*
* append the end of string character '\0', all the data is defaulted
* to 0, so just move data one position forward. Specify result value
* type to char pointer. CHAR + PTR = PTR because CHAR is 0.
*/
data = (char *) (((int) data + sizeof(int)) & (-sizeof(int)));
ty = PTR;
break;
/* SIZEOF_expr -> 'sizeof' '(' 'TYPE' ')'
* sizeof is actually an unary operator.
* now only `sizeof(int)`, `sizeof(char)` and `sizeof(*...)` are supported.
* FIXME: not support "sizeof (Id)".
* In second line will not get next token, match ')' will fail.
*/
case Sizeof:
next();
if (tk != '(') fatal("open parentheses expected in sizeof");
next();
ty = INT;
switch (tk) {
case Int: next(); break;
case Char: next(); ty = CHAR; break;
case Struct:
case Union:
next();
if (tk != Id) fatal("bad struct/union type");
ty = id->stype; next(); break;
}
// multi-level pointers, plus `PTR` for each level
while (tk == Mul) { next(); ty += PTR; }
if (tk != ')') fatal("close parentheses expected in sizeof");
next();
*--n = ty >= PTR ? sizeof(int) : tsize[ty]; *--n = Num;
ty = INT;
break;
case Id:
d = id; next();
// function call
if (tk == '(') {
if (d->class < Func || d->class > ClearCache) {
if (d->class != 0) fatal("bad function call");
int namelen = d->hash & 0x3f;
char ch = d->name[namelen];
d->name[namelen] = 0;
d->val = ef_getidx(d->name) ;
d->name[namelen] = ch;
d->class = Syscall;
d->type = INT;
}
next();
t = 0; b = 0; // parameters count
while (tk != ')') {
expr(Assign); *--n = (int) b; b = n; ++t;
if (tk == ',') {
next();
if (tk == ')') fatal("unexpected comma in function call");
} else if (tk != ')') fatal("missing comma in function call");
}
next();
// function or system call id
*--n = t; *--n = d->val; *--n = (int) b; *--n = d->class;
ty = d->type;
}
// enumeration, only enums have ->class == Num
else if (d->class == Num) { *--n = d->val; *--n = Num; ty = INT; }
else {
// Variable get offset
switch (d->class) {
case Loc: case Par: *--n = loc - d->val; *--n = Loc; break;
case Glo: *--n = d->val; *--n = Num; break;
default: fatal("undefined variable");
}
*--n = ty = d->type; *--n = Load;
}
break;
// Type cast or parenthesis
case '(':
next();
if (tk == Int || tk == Char || tk == Struct || tk == Union) {
switch (tk) {
case Int: next(); t = INT; break;
case Char: next(); t = CHAR; break;
default:
next();
if (tk != Id) fatal("bad struct/union type");
t = id->stype; next(); break;
}
// t: pointer
while (tk == Mul) { next(); t += PTR; }
if (tk != ')') fatal("bad cast");
next();
expr(Inc); // cast has precedence as Inc(++)
ty = t;
} else {
expr(Assign);
while (tk == ',') { next(); expr(Assign); }
if (tk != ')') fatal("close parentheses expected");
next();
}
break;
case Mul: // "*", dereferencing the pointer operation
next();
expr(Inc); // dereference has the same precedence as Inc(++)
if (ty < PTR) fatal("bad dereference");
ty -= PTR;
if (ty < CHAR || ty >= PTR2) fatal("unexpected type");
*--n = ty; *--n = Load;
break;
case And: // "&", take the address operation
/* when "token" is a variable, it takes the address first and
* then LI/LC, so `--e` becomes the address of "a".
*/
next(); expr(Inc);
if (*n != Load) fatal("bad address-of");
n += 2;
ty += PTR;
break;
case '!': // "!x" is equivalent to "x == 0"
next(); expr(Inc);
if (*n == Num) n[1] = !n[1];
else { *--n = 0; *--n = Num; --n; *n = (int) (n + 3); *--n = Eq; }
ty = INT;
break;
case '~': // "~x" is equivalent to "x ^ -1"
next(); expr(Inc);
if (*n == Num) n[1] = ~n[1];
else { *--n = -1; *--n = Num; --n; *n = (int) (n + 3); *--n = Xor; }
ty = INT;
break;
case Add:
next(); expr(Inc); ty = INT;
break;
case Sub:
next();
expr(Inc);
if (*n == Num) n[1] = -n[1];
else { *--n = -1; *--n = Num; --n; *n = (int) (n + 3); *--n = Mul; }
ty = INT;
break;
case Div:
case Mod:
break;
// processing ++x and --x. x-- and x++ is handled later
case Inc:
case Dec:
t = tk; next(); expr(Inc);
if (*n != Load) fatal("bad lvalue in pre-increment");
*n = t;
break;
default:
if (tk & REENTRANT) tk ^= REENTRANT;
else fatal("bad expression");
}
// "precedence climbing" or "Top Down Operator Precedence" method
while (tk >= lev) {
// tk is ASCII code will not exceed `Num=128`. Its value may be changed
// during recursion, so back up currently processed expression type
t = ty; b = n;
switch (tk) {
case Assign:
next();
// the left part is processed by the variable part of `tk=ID`
// and pushes the address
if (*n != Load) fatal("bad lvalue in assignment");
// get the value of the right part `expr` as the result of `a=expr`
expr(Assign); *--n = (int) (b + 2); *--n = ty = t; *--n = Assign;
break;
case OrAssign: // right associated
case XorAssign:
case AndAssign:
case ShlAssign:
case ShrAssign:
case AddAssign:
case SubAssign:
case MulAssign:
case DivAssign:
case ModAssign:
*--n=';'; *--n = t; *--n = Load;
if (tk < ShlAssign) tk = Or + (tk - OrAssign);
else tk = Shl + (tk - ShlAssign);
tk |= REENTRANT; compound = 1; expr(Assign);
*--n = (int) (b + 2); *--n = ty = t; *--n = Assign;
break;
case Cond: // `x?a:b` is similar to if except that it relies on else
next(); expr(Assign);
if (tk != ':') fatal("conditional missing colon");
next(); c = n;
expr(Cond); --n;
*n = (int) (n + 1); *--n = (int) c; *--n = (int) b; *--n = Cond;
break;
case Lor: // short circuit, the logical or
next(); expr(Lan);
if (*n == Num && *b == Num) n[1] = b[1] || n[1];
else { *--n = (int) b; *--n = Lor; }
ty = INT;
break;
case Lan: // short circuit, logic and
next(); expr(Or);
if (*n == Num && *b == Num) n[1] = b[1] && n[1];
else { *--n = (int) b; *--n = Lan; }
ty = INT;
break;
case Or: // push the current value, calculate the right value
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Xor);
if (*n == Num && *b == Num) n[1] = b[1] | n[1];
else { *--n = (int) b; *--n = Or; }
ty = INT;
break;
case Xor:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(And);
if (*n == Num && *b == Num) n[1] = b[1] ^ n[1];
else { *--n = (int) b; *--n = Xor; }
ty = INT;
break;
case And:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Eq);
if (*n == Num && *b == Num) n[1] = b[1] & n[1];
else { *--n = (int) b; *--n = And; }
ty = INT;
break;
case Eq:
next(); expr(Lt);
if (*n == Num && *b == Num) n[1] = b[1] == n[1];
else { *--n = (int) b; *--n = Eq; }
ty = INT;
break;
case Ne:
next(); expr(Lt);
if (*n == Num && *b == Num) n[1] = b[1] != n[1];
else { *--n = (int) b; *--n = Ne; }
ty = INT;
break;
case Lt:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] < n[1];
else { *--n = (int) b; *--n = Lt; }
ty = INT;
break;
case Gt:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] > n[1];
else { *--n = (int) b; *--n = Gt; }
ty = INT;
break;
case Le:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] <= n[1];
else { *--n = (int) b; *--n = Le; }
ty = INT;
break;
case Ge:
next(); expr(Shl);
if (*n == Num && *b == Num) n[1] = b[1] >= n[1];
else { *--n = (int) b; *--n = Ge; }
ty = INT;
break;
case Shl:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Add);
if (*n == Num && *b == Num) {
n[1] = b[1] << n[1];
} else { *--n = (int) b; *--n = Shl; }
ty = INT;
break;
case Shr:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Add);
if (*n == Num && *b == Num) {
n[1] = b[1] >> n[1];
} else { *--n = (int) b; *--n = Shr; }
ty = INT;
break;
case Add:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Mul);
tc = ((t | ty) & (PTR | PTR2)) ? (t >= PTR) : (t >= ty);
c = n; if (tc) ty = t;
sz = (ty >= PTR2) ? sizeof(int) :
((ty >= PTR) ? tsize[ty - PTR] : 1);
if (*n == Num && tc) { n[1] *= sz; sz = 1; }
else if (*b == Num && !tc) { b[1] *= sz; sz = 1; }
if (*n == Num && *b == Num) n[1] += b[1];
else if (sz != 1) {
*--n = sz; *--n = Num;
*--n = (int) (tc ? c : b); *--n = Mul;
*--n = (int) (tc ? b : c); *--n = Add;
}
else { *--n = (int) b; *--n = Add; }
break;
case Sub: // 4 cases: ptr-ptr, ptr-int, int-ptr (err), int-int
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Mul); // t = left type, ty = right type
if (t < PTR && ty >= PTR) fatal("bad pointer subtraction");
if (t >= PTR) { // left arg is ptr
sz = (t >= PTR2) ? sizeof(int) : tsize[t - PTR];
if (ty >= PTR) { // ptr - ptr
if (t != ty) fatal("mismatched ptr type subtraction");
if (*n == Num && *b == Num) n[1] = (b[1] - n[1]) / sz;
else {
*--n = (int) b; *--n = Sub;
if (sz > 1) {
if ((sz & (sz - 1)) == 0) { // 2^n
*--n = popcount(sz - 1); *--n = Num;
--n; *n = (int) (n + 3); *--n = Shr;
} else {
*--n = sz; *--n = Num; --n; *n = (int) (n + 3);
*--n = Div; ef_getidx("__aeabi_idiv");
}
}
}
ty = INT;
} else { // ptr - int
if (*n == Num) {
n[1] *= sz;
if (*b == Num) n[1] = b[1] - n[1];
else { *--n = (int) b; *--n = Sub; }
} else {
if (sz > 1) {
if ((sz & (sz - 1)) == 0) { // 2^n
*--n = popcount(sz - 1); *--n = Num;
--n; *n = (int) (n + 3); *--n = Shl;
}
else {
*--n = sz; *--n = Num;
--n; *n = (int) (n + 3); *--n = Mul;
}
}
*--n = (int) b; *--n = Sub;
}
ty = t;
}
} else { // int - int
if (*n == Num && *b == Num) n[1] = b[1] - n[1];
else { *--n = (int) b; *--n = Sub; }
ty = INT;
}
break;
case Mul:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Inc);
if (*n == Num && *b == Num) n[1] *= b[1];
else {
*--n = (int) b;
if (n[1] == Num && n[2] > 0 && (n[2] & (n[2] - 1)) == 0) {
n[2] = popcount(n[2] - 1); *--n = Shl; // 2^n
}
else *--n = Mul;
}
ty = INT;
break;
case Inc:
case Dec:
sz = ty >= PTR2 ? sizeof(int) : ty >= PTR ? tsize[ty - PTR] : 1;
if (*n != Load) fatal("bad lvalue in post-increment");
*n = tk;
*--n = sz; *--n = Num;
*--n = (int) b; *--n = (tk == Inc) ? Sub : Add;
next();
break;
case Div:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Inc);
if (*n == Num && *b == Num) n[1] = b[1] / n[1];
else {
*--n = (int) b;
if (n[1] == Num && n[2] > 0 && (n[2] & (n[2] - 1)) == 0) {
n[2] = popcount(n[2] - 1); *--n = Shr; // 2^n
} else {
*--n = Div;
ef_getidx("__aeabi_idiv");
}
}
ty = INT;
break;
case Mod:
next();
if (compound) { compound = 0; expr(Assign); }
else expr(Inc);
if (*n == Num && *b == Num) n[1] = b[1] % n[1];
else {
*--n = (int) b;
if (n[1] == Num && n[2] > 0 && (n[2] & (n[2] - 1)) == 0) {
--n[2]; *--n = And; // 2^n
} else {
*--n = Mod;
ef_getidx("__aeabi_idivmod");
}
}
ty = INT;
break;
case Dot:
ty += PTR;
if (n[0] == Load && n[1] > INT && n[1] < PTR) n += 2; // struct
case Arrow:
if (ty <= PTR+INT || ty >= PTR2) fatal("structure expected");
next();
if (tk != Id) fatal("structure member expected");
m = members[ty - PTR]; while (m && m->id != id) m = m->next;
if (!m) fatal("structure member not found");
if (m->offset) {
*--n = m->offset; *--n = Num; --n; *n = (int) (n + 3);
*--n = Add;
}
ty = m->type;
if (ty <= INT || ty >= PTR) *--n = (ty == CHAR) ? CHAR : INT;
else *--n = ty; // struct, not struct pointer
*--n = Load;
next();
break;
case Bracket:
next(); expr(Assign);
if (tk != ']') fatal("close bracket expected");
next();
if (t < PTR) fatal("pointer type expected");
sz = (t = t - PTR) >= PTR ? sizeof(int) : tsize[t];
if (sz > 1) {
if (*n == Num) n[1] *= sz;
else {
*--n = sz; *--n = Num; --n; *n = (int) (n + 3); *--n = Mul;
}
}
if (*n == Num && *b == Num) n[1] += b[1];
else { *--n = (int) b; *--n = Add; }