-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathassem5.cpp
More file actions
1825 lines (1690 loc) · 72.7 KB
/
assem5.cpp
File metadata and controls
1825 lines (1690 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************** assem5.cpp ********************************
* Author: Agner Fog
* Date created: 2017-09-19
* Last modified: 2023-02-25
* Version: 1.13
* Project: Binary tools for ForwardCom instruction set
* Module: assem.cpp
* Description:
* Module for assembling ForwardCom .as files.
* This module contains functions for interpreting high level language constructs:
* functions, branches, and loops
*
* Copyright 2017-2024 GNU General Public License http://www.gnu.org/licenses
******************************************************************************/
#include "stdafx.h"
// Define high level block types
const int HL_SECTION = 1; // section
const int HL_FUNC = 2; // function
const int HL_IF = 3; // if branch
const int HL_ELSE = 4; // else branch
const int HL_SWITCH = 5; // switch-case branch
const int HL_FOR = 6; // for loop
const int HL_FOR_IN = 7; // vector loop. for (v1 in [r2-r3]) {}
const int HL_WHILE = 8; // while loop
const int HL_DO_WHILE = 9; // do-while loop
// invert condition code for branch instruction
void invertCondition(SCode & code) {
code.instruction ^= II_JUMP_INVERT; // invert condition code
if ((code.dtype & TYP_FLOAT)
&& (code.instruction & 0xFF) == II_COMPARE
&& (code.instruction & 0x7F00) - 0x1000 < 0x2000) {
// floating point compare instructions, except jump_ordered, must invert the unordered bit
code.instruction ^= II_JUMP_UNORDERED; // inverse condition is unordered
}
}
// if, else, switch, for, do, while statements
void CAssembler::interpretHighLevelStatement() {
//uint32_t label = 0;
if (tokenN > 2 && tokens[tokenB].type == TOK_SYM && tokens[tokenB+1].id == ':') {
// line starts with a label. insert label
// (this will prevent merging of jump instruction. merging is not allowed when there is a label between the two instructions)
SCode codeL;
zeroAllMembers(codeL);
//codeL.label = tokens[tokenB].value.w; //?
codeL.label = tokens[tokenB].id;
codeL.section = section;
codeBuffer.push(codeL);
// interpret directive after label
tokenB += 2;
tokenN -= 2;
}
uint32_t tok = tokenB;
if (tokenN > 1 && tokens[tok].type == TOK_TYP) {
tok++; // skip type keyword
if (tok+1 < tokenB+tokenN && tokens[tok].type == TOK_OPR && tokens[tok].id == '+') tok++; // skip '+' after type
}
// expect HLL keyword here. dispatch to the corresponding function
switch (tokens[tok].id) {
case HLL_IF:
codeIf(); break;
case HLL_SWITCH:
codeSwitch(); break;
case HLL_CASE:
codeCase(); break;
case HLL_FOR:
codeFor(); break;
case HLL_WHILE:
codeWhile(); break;
case HLL_DO:
codeDo(); break;
case HLL_BREAK: case HLL_CONTINUE:
if (tok != tokenB) {
errors.report(tokens[tok]); // cannot have type token before break or continue
break;
}
codeBreak(); break;
case HLL_PUSH: // may be replaced by macro later
codePush(); break;
case HLL_POP: // may be replaced by macro later
codePop(); break;
default:
errors.report(tokens[tok]);
}
}
// finish {} block
void CAssembler::interpretEndBracket() {
uint32_t n = hllBlocks.numEntries();
if (n == 0) {
errors.reportLine(ERR_BRACKET_END); // unmatched end bracket
return;
}
// dispatch depending on type of block
switch (hllBlocks[n-1].blockType) {
case HL_FUNC: // function
break;
case HL_IF: case HL_ELSE: // if branch
codeIf2();
break;
case HL_FOR: // for loop
codeFor2();
break;
case HL_FOR_IN: // vector loop. for (v1 in [r2-r3]) {}
codeForIn2();
break;
case HL_WHILE: // while loop
codeWhile2();
break;
case HL_DO_WHILE: // do-while loop
codeDo2();
break;
case HL_SWITCH: // switch-case branch
break;
default:
errors.reportLine(ERR_BRACKET_END); // should not occur
}
}
// Interpret if statement in assembly code
void CAssembler::codeIf() {
uint32_t state = 0; // 0: start, 1: after type, 2: after if, 3: after (, 4: after (type,
// 5: after expression, 6: after ')', 7: after {
uint32_t tok; // current token index
SBlock block; // block descriptor to save
zeroAllMembers(block); // reset
block.blockType = HL_IF; // if block
SToken token; // current token
SExpression expr; // expression in ()
SCode code; // instruction code
zeroAllMembers(code); // reset
// interpret line by state machine looping through tokens
for (tok = tokenB; tok < tokenB + tokenN; tok++) {
if (lineError) break;
token = tokens[tok];
switch (state) {
case 0: // start. expect type or 'if'
if (token.type == TOK_TYP) {
code.dtype = dataType = token.id & 0xFF;
state = 1;
}
else if (token.id == HLL_IF) state = 2;
else errors.report(token);
break;
case 1: // after type. expect '+' or 'if'
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
}
else if (token.id == HLL_IF) state = 2;
else errors.report(token);
break;
case 2: // after if. expect '('
if (token.type == TOK_OPR && token.id == '(') state = 3;
else errors.report(token.pos, token.stringLength, ERR_EXPECT_PARENTHESIS);
break;
case 3: // after '('. expect type or logical expression
if (token.type == TOK_TYP && !code.dtype) {
code.dtype = dataType = token.id & 0xFF;
state = 4;
break;
}
EXPRESSION:
expr = expression(tok, tokenB + tokenN-tok, (code.dtype & TYP_UNS) != 0);
if (lineError) return;
// insert logical expression into block
insertAll(code, expr);
tok += expr.tokens - 1;
state = 5;
break;
case 4: // after "if (type". expect '+' or expression
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
break;
}
// not a '+'. expect expression
goto EXPRESSION;
case 5: // after expression. expect ')'
if (token.type == TOK_OPR && token.id == ')') state = 6;
else {
errors.report(token); return;
}
break;
}
}
// should end at state 6 because '{' should be on next pseudo-line
if (state != 6) errors.report(token);
if (lineError) return;
if (linei == lines.numEntries()-1) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
// get next line
if (linei == lines.numEntries()-1) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
lineError = false;
// expect '{'
if (tokens[tokenB].id != '{') {
errors.reportLine(ERR_EXPECT_BRACKET);
return;
}
// interpret the condition expression
linei--; // make any error message apply to previous line
interpretCondition(code);
linei++;
// make instruction code
code.etype |= XPR_JUMPOS | XPR_SYM1;
code.section = section;
// check if {} contains a jump only
uint32_t target2 = hasJump(linei+1);
if (target2) {
if (linei + 2 < lines.numEntries() && lines[linei+2].numTokens == 1) {
tok = lines[linei+2].firstToken;
if (tokens[tok].type == TOK_OPR && tokens[tok].id == '}') {
// the {} block contains a jump and nothing else
// make conditional jump to target2 instead
code.sym5 = target2;
linei += 2; // finished processing these two lines
// check if it can be merged with previous instruction
mergeJump(code);
// finish code and fit it
checkCode1(code);
if (lineError) return;
fitCode(code); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code);// save code structure
// check if there is an 'else' after if(){}
if (linei + 2 < lines.numEntries() && lines[linei+1].numTokens == 1 && lines[linei+2].numTokens == 1) {
tok = lines[linei+1].firstToken;
if (tokens[tok].type == TOK_HLL && tokens[tok].id == HLL_ELSE) {
tok = lines[linei+2].firstToken;
if (tokens[tok].type == TOK_OPR && tokens[tok].id == '{') {
// make the 'else' ignored
linei += 2;
// make block record with no label
block.blockNumber = ++iIf;
block.startBracket = tok;
block.jumpLabel = 0;
// store block in hllBlocks stack. will be retrieved at matching '}'
hllBlocks.push(block);
}
}
}
return;
}
}
}
invertCondition(code); // invert condition. jump to else block if logical expression false
if (code.instruction == (II_JUMP | II_JUMP_INVERT)) {
// constant: don't jump
code.instruction = 0;
}
// make block record with label name
block.blockNumber = ++iIf;
block.startBracket = tokenB;
char name[32];
sprintf(name, "@if_%u_a", iIf);
uint32_t symi = makeLabelSymbol(name);
block.jumpLabel = symbols[symi].st_name;
// store block in hllBlocks stack. will be retrieved at matching '}'
hllBlocks.push(block);
// store jump instruction
code.sym5 = block.jumpLabel;
// check if it can be merged with previous instruction
mergeJump(code);
// finish code and fit it
checkCode1(code);
if (lineError) return;
fitCode(code); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code);// save code structure
}
// Finish if statement at end bracket
void CAssembler::codeIf2() {
SCode code; // code record for jump label
zeroAllMembers(code); // reset
SBlock block = hllBlocks.pop(); // pop the stack of {} blocks
uint32_t labelA = block.jumpLabel; // jump target label to place here
// check if there is an 'else' following the if(){}
if (block.blockType == HL_IF && linei+2 < lines.numEntries() && tokens[lines[linei+1].firstToken].id == HLL_ELSE) {
// there is an else. get next line with the else
linei++;
if (lines[linei].numTokens > 1) errors.report(tokens[lines[linei].firstToken+1]); // something other than '{' after else
// check if there is a '{' following the 'else'
linei++;
uint32_t tokenB = lines[linei].firstToken;
if (lines[linei].numTokens > 1 || tokens[tokenB].type != TOK_OPR || tokens[tokenB].id != '{') {
errors.reportLine(ERR_EXPECT_BRACKET); // expecting '{'
return;
}
// make block record for jump to label b
block.blockType = HL_ELSE; // if-else block
block.startBracket = tokenB;
// make label name
char name[32];
sprintf(name, "@if_%u_b", block.blockNumber);
uint32_t symi = makeLabelSymbol(name);
block.jumpLabel = symbols[symi].st_name;
hllBlocks.push(block); // store block in hllBlocks stack. will be retrieved at matching '}'
// make jump instruction
code.section = section;
code.instruction = II_JUMP;
code.etype = XPR_JUMPOS | XPR_SYM1;
code.sym5 = block.jumpLabel;
// check if it can be merged with previous instruction
mergeJump(code);
// finish code and save it
checkCode1(code);
if (lineError) return;
fitCode(code); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code);// save code structure
}
// make target label here
if (labelA) {
zeroAllMembers(code);
code.section = section;
code.label = labelA; // jump target label
codeBuffer.push(code); // save code structure
}
}
// Interpret while loop in assembly code
void CAssembler::codeWhile() {
uint32_t state = 0; // 0: start, 1: after type, 2: after while, 3: after (, 4: after (type,
// 5: after expression, 6: after ')', 7: after {
uint32_t tok; // current token index
SBlock block; // block descriptor to save
zeroAllMembers(block); // reset
SToken token; // current token
SExpression expr; // expression in ()
SCode code; // instruction code
zeroAllMembers(code); // reset
// interpret line by state machine looping through tokens (same as for codeIf)
for (tok = tokenB; tok < tokenB + tokenN; tok++) {
if (lineError) break;
token = tokens[tok];
switch (state) {
case 0: // start. expect type or 'while'
if (token.type == TOK_TYP) {
code.dtype = dataType = token.id & 0xFF;
state = 1;
}
else if (token.id == HLL_WHILE) state = 2;
else errors.report(token);
break;
case 1: // after type. expect '+' or 'while'
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
}
else if (token.id == HLL_WHILE) state = 2;
else errors.report(token);
break;
case 2: // after if. expect '('
if (token.type == TOK_OPR && token.id == '(') state = 3;
else errors.report(token.pos, token.stringLength, ERR_EXPECT_PARENTHESIS);
break;
case 3: // after '('. expect type or logical expression
if (token.type == TOK_TYP && !code.dtype) {
code.dtype = dataType = token.id & 0xFF;
state = 4;
break;
}
EXPRESSION:
expr = expression(tok, tokenB + tokenN-tok, (code.dtype & TYP_UNS) != 0);
if (lineError) return;
// insert logical expression into block
insertAll(code, expr);
tok += expr.tokens - 1;
state = 5;
break;
case 4: // after "while (type". expect '+' or expression
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
break;
}
// not a '+'. expect expression
goto EXPRESSION;
case 5: // after expression. expect ')'
if (token.type == TOK_OPR && token.id == ')') state = 6;
else {
errors.report(token); return;
}
break;
}
}
// should end at state 6 because '{' should be on next pseudo-line
if (state != 6) errors.report(token);
if (lineError) return;
if (linei == lines.numEntries()-1) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
// get next line
// get next line
if (linei == lines.numEntries()-1) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
lineError = false;
// expect '{'
if (tokens[tokenB].id != '{') {
errors.reportLine(ERR_EXPECT_BRACKET);
return;
}
// interpret the condition expression
linei--; // make any error message apply to previous line
interpretCondition(code);
linei++;
// make instruction code
code.etype |= XPR_JUMPOS | XPR_SYM1;
code.section = section;
// make block record with label names
block.blockType = HL_WHILE; // while-block
block.blockNumber = ++iLoop;
block.startBracket = tokenB;
char name[32];
sprintf(name, "@while_%u_a", iLoop);
uint32_t symi1 = makeLabelSymbol(name);
block.jumpLabel = symbols[symi1].st_name; // label to jump back to
sprintf(name, "@while_%u_b", iLoop);
uint32_t symi2 = makeLabelSymbol(name);
block.breakLabel = symbols[symi2].st_name; // label after loop. used if condition is false first time and for break statements
block.continueLabel = 0xFFFFFFFF; // this label will only be made if there is a continue statement
// make code to check condition before first iteration
SCode code1 = code;
invertCondition(code1); // invert condition to jump if false
if (code1.instruction == (II_JUMP | II_JUMP_INVERT)) {
// constant: don't jump
code1.instruction = 0;
}
code1.sym5 = block.breakLabel;
// check if it can be merged with previous instruction
mergeJump(code1);
// finish code and store it
checkCode1(code1);
if (lineError) return;
fitCode(code1); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code1);// save code structure
// make loop label
zeroAllMembers(code1);
code1.label = block.jumpLabel;
code1.section = section;
codeBuffer.push(code1);// save code structure
// make instruction to place at end of loop
code.sym5 = block.jumpLabel;
checkCode1(code);
// store in codeBuffer2 for later insertion at the end of the loop
block.codeBuffer2index = codeBuffer2.push(code);
block.codeBuffer2num = 1;
// store block in hllBlocks stack. will be retrieved at matching '}'
hllBlocks.push(block);
}
// Finish while-loop at end bracket
void CAssembler::codeWhile2() {
SCode code; // code record for jump back
SBlock block = hllBlocks.pop(); // pop the stack of {} blocks
if (block.continueLabel != 0xFFFFFFFF) {
// place label here as jump target for continue statements
zeroAllMembers(code);
code.label = block.continueLabel;
code.section = section;
codeBuffer.push(code);
}
uint32_t codebuf2num = codeBuffer2.numEntries();
if (block.codeBuffer2num && block.codeBuffer2index < codebuf2num) {
// retrieve jumpback instruction
code = codeBuffer2[block.codeBuffer2index];
if (code.instruction == (II_JUMP | II_JUMP_INVERT)) {
// constant: don't jump
code.instruction = 0;
}
// check if it can be merged with previous instruction
mergeJump(code);
// finish code and store it
checkCode1(code);
if (lineError) return;
fitCode(code); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code); // save code
// remove from temporary buffer
if (block.codeBuffer2index + 1 == codebuf2num) codeBuffer2.pop();
// place label for breaking out
zeroAllMembers(code);
code.label = block.breakLabel;
code.section = section;
codeBuffer.push(code); // save label
return;
}
}
// Interpret do-while loop in assembly code
void CAssembler::codeDo() {
SBlock block; // block record
SCode code; // code record for label
zeroAllMembers(block);
zeroAllMembers(code);
// make block record with label names
block.blockType = HL_DO_WHILE; // do-while-block
block.blockNumber = ++iLoop;
char name[32];
sprintf(name, "@do_%u_a", iLoop);
uint32_t symi1 = makeLabelSymbol(name);
block.jumpLabel = symbols[symi1].st_name; // label to jump back to
block.breakLabel = 0xFFFFFFFF; // this label will only be made if there is a break statement
block.continueLabel = 0xFFFFFFFF; // this label will only be made if there is a continue statement
// make loop label
code.label = block.jumpLabel;
code.section = section;
codeBuffer.push(code); // save label
// get next line with '{'
if (linei == lines.numEntries()-1) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
lineError = false;
// expect '{'
if (tokens[tokenB].id != '{') {
errors.report(tokens[tokenB]);
return;
}
block.startBracket = tokenB;
hllBlocks.push(block); // store block in hllBlocks stack. will be retrieved at matching '}'
}
// Finish do-while loop at end bracket
void CAssembler::codeDo2() {
SCode code; // code record
SBlock block = hllBlocks.pop(); // pop the stack of {} blocks
if (block.continueLabel != 0xFFFFFFFF) {
// place label here as jump target for continue statements
zeroAllMembers(code);
code.label = block.continueLabel;
code.section = section;
codeBuffer.push(code);
}
// find 'while' keyword in next pseudo-line after '}'
if (linei+1 >= lines.numEntries()) { // no more lines
errors.reportLine(ERR_WHILE_EXPECTED); return;
}
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
lineError = false;
// expect "while (expression)"
uint32_t state = 0; // 0: start, 1: after type, 2: after 'while', 3: after (, 4: after (type,
// 5: after expression, 6: after ')'
uint32_t tok; // current token index
SToken token; // current token
SExpression expr; // expression in ()
zeroAllMembers(code); // reset code
// interpret line by state machine looping through tokens
for (tok = tokenB; tok < tokenB + tokenN; tok++) {
if (lineError) return;
token = tokens[tok];
switch (state) {
case 0: // start. expect type or 'while'
if (token.type == TOK_TYP) {
code.dtype = dataType = token.id & 0xFF;
state = 1;
}
else if (token.id == HLL_WHILE) state = 2;
else errors.reportLine(ERR_WHILE_EXPECTED);
break;
case 1: // after type. expect '+' or 'while'
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
}
else if (token.id == HLL_WHILE) state = 2;
else errors.report(token);
break;
case 2: // after 'while'. expect '('
if (token.type == TOK_OPR && token.id == '(') state = 3;
else errors.report(token.pos, token.stringLength, ERR_EXPECT_PARENTHESIS);
break;
case 3: // after '('. expect type or logical expression
if (token.type == TOK_TYP && !code.dtype) {
code.dtype = dataType = token.id & 0xFF;
state = 4;
break;
}
EXPRESSION:
expr = expression(tok, tokenB + tokenN - tok, (code.dtype & TYP_UNS) != 0);
if (lineError) return;
// insert logical expression into block
insertAll(code, expr);
tok += expr.tokens - 1;
state = 5;
break;
case 4: // after "while (type". expect '+' or expression
if (token.type == TOK_OPR && token.id == '+') {
code.dtype |= TYP_PLUS;
break;
}
// not a '+'. expect expression
goto EXPRESSION;
case 5: // after expression. expect ')'
if (token.type == TOK_OPR && token.id == ')') state = 6;
else {
errors.report(token); return;
}
break;
}
}
// should end at state 6
if (state != 6) errors.report(token);
if (lineError) return;
// make instruction with condition
interpretCondition(code);
code.etype |= XPR_JUMPOS | XPR_SYM1;
code.section = section;
code.sym5 = block.jumpLabel;
if (code.instruction == (II_JUMP | II_JUMP_INVERT)) {
// constant: don't jump
code.instruction = 0;
}
// check if it can be merged with previous instruction
mergeJump(code);
// finish code and fit it
checkCode1(code);
if (lineError) return;
fitCode(code); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(code);// save code structure
if (block.breakLabel != 0xFFFFFFFF) {
// place label here as jump target for break statements
zeroAllMembers(code);
code.label = block.breakLabel;
code.section = section;
codeBuffer.push(code);
}
}
// Interpret for-loop in assembly code
void CAssembler::codeFor() {
uint32_t tok; // token number
// search for 'in' keyword
for (tok = tokenB; tok < tokenB + tokenN; tok++) {
if (tokens[tok].type == TOK_HLL && tokens[tok].id == HLL_IN) {
// this is a for-in vector loop
codeForIn();
return;
}
}
// this is a traditional for(;;) loop
uint32_t state = 0; // state while interpreting line
// 0: start, 1: after type, 2: after 'for', 3: after (, 4: after (type,
SBlock block; // block descriptor to save
zeroAllMembers(block); // reset
block.blockType = HL_FOR; // 'for' block
block.breakLabel = block.jumpLabel = block.continueLabel = 0xFFFFFFFF;
SToken token; // current token
SToken typeToken; // token defining type
// uint32_t type = 0; // operand type for all three expressions in for(;;)
dataType = 0; // operand type for all three expressions in for(;;)
uint32_t symi = 0; // symbol index
char name[48]; // symbol name
int conditionFirst = 0; // evaluation of the condition before first iteration:
// 0: condition must be checked before first iteration
// 2: condition is false before first iteration. zero iterations
// 3: condition is true before first iteration. no initial check needed
// interpret line by state machine looping through tokens
for (tok = tokenB; tok < tokenB + tokenN; tok++) {
if (lineError) break;
token = tokens[tok];
if (state == 0) { // start. expect type or 'for'
if (token.type == TOK_TYP) {
dataType = token.id & 0xFF;
typeToken = token;
state = 1;
}
else if (token.id == HLL_FOR) state = 2;
else errors.report(token);
}
else if (state == 1) { // after type. expect '+' or 'for'
if (token.type == TOK_OPR && token.id == '+') {
dataType |= TYP_PLUS;
}
else if (token.id == HLL_FOR) state = 2;
else errors.report(token);
}
else if (state == 2) { // after 'for'. expect '('
if (token.type == TOK_OPR && token.id == '(') state = 3;
else errors.report(token.pos, token.stringLength, ERR_EXPECT_PARENTHESIS);
}
else if (state == 3) { // after '('. expect type or initialization
if (token.type == TOK_TYP && !dataType) {
dataType = token.id & 0xFF;
typeToken = token;
tok++;
if (tok < tokenB + tokenN && tokens[tok].type == TOK_OPR && tokens[tok].id == '+') {
// '+' after type
dataType |= TYP_PLUS;
tok++;
}
}
state = 4;
break; // end tok loop here
}
}
if (state != 4) {
errors.report(token);
return;
}
if (lineError) return;
// check type
if (dataType == 0) {
errors.reportLine(ERR_TYPE_MISSING); return;
}
// extend type to int32 if allowed. this allows various optimizations
// (unsigned types not allowed, even if start and end values are known to be positive, because loop counter may become negative inside loop in rare cases)
if ((dataType & TYP_PLUS) && ((dataType & 0xFF) < (TYP_INT32 & 0xFF))) dataType = TYP_INT32;
// remake token sequence for generating initial instruction
uint32_t tokensRestorePoint = tokens.numEntries();
typeToken.id = dataType;
tokens.push(typeToken);
uint32_t tokenFirst = tok;
if (tokens[tokenFirst].type == TOK_TYP) tokenFirst++; // skip type token. it has already been inserted
for (; tok < tokenB + tokenN; tok++) { // insert remaining tokens
token = tokens[tok];
if (token.type == TOK_OPR && token.id == ';') break;
tokens.push(tokens[tok]);
}
// make an instruction out of this sequence
tokenB = tokensRestorePoint;
tokenN = tokens.numEntries() - tokensRestorePoint;
uint32_t codePoint = codeBuffer.numEntries();
SCode initializationCode;
zeroAllMembers(initializationCode);
if (tokenN > 1) { // skip if there is no code
interpretCodeLine();
if (codeBuffer.numEntries() == codePoint + 1) {
// remember initialization code
initializationCode = codeBuffer[codePoint];
}
}
// remove temporary token sequence
tokens.setNum(tokensRestorePoint);
if (lineError) return;
// get next line containing loop condition
SCode conditionCode;
zeroAllMembers(conditionCode);
conditionCode.section = section;
if (linei+2 >= lines.numEntries()) { // no more lines
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
if (tokenN == 1 && tokens[tokenB].type == TOK_OPR && tokens[tokenB].id == ';') {
// no condition specified. infinite loop
conditionFirst = 3;
conditionCode.instruction = II_JUMP;
conditionCode.etype = XPR_JUMPOS;
}
else {
SExpression expr = expression(tokenB, tokenN, (dataType & TYP_UNS) != 0);
if (lineError) return;
insertAll(conditionCode, expr); // insert logical expression into block
conditionCode.dtype = dataType;
interpretCondition(conditionCode); // convert expression to conditional jump
if (conditionCode.etype == XPR_INT) { // always true or always false
conditionFirst = 2 + (conditionCode.value.w & 1);
conditionCode.instruction = II_JUMP;
conditionCode.etype = XPR_JUMPOS;
conditionCode.value.i = 0;
conditionCode.dtype = 0;
}
else {
conditionCode.etype |= XPR_JUMPOS | XPR_SYM1;
conditionCode.section = section;
tok = tokenB + expr.tokens; // expect ';' after expression
if (tokens[tok].type != TOK_OPR || tokens[tok].id != ';') {
errors.report(tokens[tok]);
}
//uint32_t counterRegister = 0;
uint64_t counterStart = 0;
// are start and end values known constants?
if (initializationCode.instruction == II_MOVE && (initializationCode.etype & XPR_INT) && initializationCode.dest
&& !(initializationCode.etype & (XPR_REG1 | XPR_MEM | XPR_OPTION))) {
//counterRegister = initializationCode.dest;
counterStart = initializationCode.value.i;
if ((expr.etype & XPR_INT) && (expr.etype & XPR_REG1) && !(expr.etype & (XPR_REG2 | XPR_MEM | XPR_OPTION))) {
// start and end values are integer constants
if ((expr.instruction & 0xFF) == II_COMPARE) {
// compare instruction. condition is in option bits
switch ((expr.optionbits >> 1) & 3) {
case 0: // ==
conditionFirst = 2 + (counterStart == expr.value.u); break;
case 1: // <
if (dataType & TYP_UNS) conditionFirst = 2 + (counterStart < expr.value.u);
else conditionFirst = 2 + ((int64_t)counterStart < expr.value.i);
break;
case 2: // >
if (dataType & TYP_UNS) conditionFirst = 2 + (counterStart > expr.value.u);
else conditionFirst = 2 + ((int64_t)counterStart > expr.value.i);
break;
}
if (expr.optionbits & 1) conditionFirst ^= 1; // invert if bit 0
}
else if ((expr.instruction & 0xFF) == II_AND) {
// bit test. if (r1 & 1 << n)
conditionFirst = 2 + ((counterStart & ((uint64_t)1 << expr.value.u)) != 0);
}
}
}
}
}
// make block record with label name
block.blockNumber = ++iLoop;
if (conditionFirst == 0) {
// condition must be checked before first iteration
invertCondition(conditionCode); // invert condition
sprintf(name, "@for_%u_b", iLoop);
symi = makeLabelSymbol(name);
block.breakLabel = symbols[symi].st_name;
conditionCode.sym5 = block.breakLabel;
// check if it can be merged with previous instruction
mergeJump(conditionCode);
checkCode1(conditionCode); // finish code and fit it
if (lineError) return;
fitCode(conditionCode); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(conditionCode); // save code structure
invertCondition(conditionCode); // invert condition back again
}
else if (conditionFirst == 2) {
// condition is known to be false. loop goes zero times
SCode jumpAlways;
zeroAllMembers(jumpAlways);
jumpAlways.instruction = II_JUMP; // jump past loop
jumpAlways.section = section;
jumpAlways.etype = XPR_JUMPOS;
sprintf(name, "@for_%u_goes_zero_times", iLoop);
symi = makeLabelSymbol(name);
block.breakLabel = symbols[symi].st_name;
jumpAlways.sym5 = block.breakLabel;
// check if it can be merged with previous instruction
mergeJump(jumpAlways);
checkCode1(jumpAlways); // finish code and fit it
if (lineError) return;
fitCode(jumpAlways); // find an instruction variant that fits
if (lineError) return;
codeBuffer.push(jumpAlways); // save code structure
}
// make label for loop back
if (conditionCode.instruction != II_JUMP) {
sprintf(name, "@for_%u_a", iLoop);
}
else {
sprintf(name, "@infinite_loop_%u_a", iLoop);
}
symi = makeLabelSymbol(name);
block.jumpLabel = symbols[symi].st_name;
conditionCode.sym5 = block.jumpLabel;
SCode codeLabel;
zeroAllMembers(codeLabel);
codeLabel.label = block.jumpLabel;
codeLabel.section = section;
codeBuffer.push(codeLabel);
// get next line containing increment
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
// line must end with ')'
if (tokenN < 1) {
errors.reportLine(ERR_UNFINISHED_INSTRUCTION);
return;
}
if (tokens[tokenB+tokenN-1].type != TOK_OPR || tokens[tokenB+tokenN-1].id != ')') {
errors.report(tokens[tokenB+tokenN-1]); // expecting ')'
return;
}
// make instruction for loop counter increment
tokens.push(typeToken);
for (tok = tokenB; tok < tokenB + tokenN - 1; tok++) { // insert remaining tokens
tokens.push(tokens[tok]);
}
// make an instruction out of this sequence
tokenB = tokensRestorePoint;
tokenN = tokens.numEntries() - tokensRestorePoint;
SCode incrementCode;
zeroAllMembers(incrementCode);
codePoint = codeBuffer.numEntries();
if (tokenN > 1) {
interpretCodeLine();
if (codeBuffer.numEntries() == codePoint + 1) {
incrementCode = codeBuffer[codePoint];
incrementCode.section = section;
}
}
// remove temporary token sequence
tokens.setNum(tokensRestorePoint);
// remove temporary incrementation code. it has to be inserted after the loop
codeBuffer.setNum(codePoint);
if (lineError) return;
// save instructions in block
block.codeBuffer2index = codeBuffer2.push(incrementCode);
codeBuffer2.push(conditionCode);
block.codeBuffer2num = 2;
// get next line containing '{'
linei++;
tokenB = lines[linei].firstToken; // first token in line
tokenN = lines[linei].numTokens; // number of tokens in line
// line must contain '{'
if (tokenN != 1 || tokens[tokenB].type != TOK_OPR || tokens[tokenB].id != '{') {
errors.reportLine(ERR_EXPECT_BRACKET);
return;
}
block.startBracket = tokenB;
// save block to be recalled at end bracket
hllBlocks.push(block);
}
// Finish for-loop at end bracket
void CAssembler::codeFor2() {
SCode incrementCode; // code record for incrementing loop counter
SCode conditionCode; // code record for conditional jump back
SCode labelCode; // code record for label
SBlock block = hllBlocks.pop(); // pop the stack of {} blocks
if (block.continueLabel != 0xFFFFFFFF) {
// place label here as jump target for continue statements
zeroAllMembers(labelCode);