-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.cpp
2458 lines (2139 loc) · 87.2 KB
/
Parser.cpp
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
//
// Created by Taemin Park on 1/14/16.
//
#include "Parser.h"
#include "Helper.h"
#include <iomanip>
Parser* Parser::_parser = 0;
Parser :: Parser()
{
// pc = 0;
// globalBase = 0;
IRpc = 0;
//FIXME
numOfSym = 0;
numOfBlock = 0;
loopDepth = 0;
currentBlock = make_shared<BasicBlock> (0,blk_entry);
}
Parser* Parser::instance() {
if(!_parser)
_parser = new Parser();
return _parser;
}
RC Parser::openFile(const std::string &folder, const std::string &sourceFileName, const std::string &sourceFileFormat) {
RC rc;
fileName = sourceFileName;
Scanner *scanner = Scanner::instance();
rc = scanner->openFile(folder + sourceFileName + sourceFileFormat);
return rc;
}
RC Parser::closeFile() {
RC rc;
Scanner *scanner = Scanner::instance();
rc = scanner->closeFile();
return rc;
}
void Parser ::Next() {
Scanner *scanner = Scanner::instance();
scannerSym = scanner->GetSym();
}
void Parser :: startParse()
{
Next();
computation();
}
void Parser :: Error(std::string nonTerminal, std::initializer_list<std::string> missingTokens){
std::cerr << fileName << ": Parser error in " << nonTerminal << ", " <<std::flush;
for (auto i: missingTokens)
std::cerr << "(" << i << ") "<<std::flush;
std::cerr << "is missing" << std::endl<<std::flush;
}
/*
void Parser :: Error(std::string nonTerminal, std::string missingTerm){
std::cerr << "Parser error: in " << nonTerminal << ", " << missingTerm << " is missing" << std::endl;
}
void Parser :: Error(std::string nonTerminal, std::string missingTerm, int numOfToken, ...){
std::cerr << "Parser error: in " << nonTerminal << ", " << missingTerm;
va_list tokenLists;
va_start(tokenLists, numOfToken);
for(unsigned i = 0 ; i < numOfToken ; i++)
{
int missingToken = va_arg(tokenLists, int);
std::cerr << " or" << tokenStringMap.find(missingToken)->second;
}
va_end(tokenLists);
std::cerr << " is missing" << std::endl;
}*/
//Push down automaton
void Parser::computation() {
SymTable newSymTable;
symTableList.insert({"main",newSymTable});
//Result tempJumpLoc;tempJumpLoc.setConst(0);
//Default block for jump to the main
//finalizeAndStartNewBlock(false);
if(scannerSym == mainToken)
{
scopeStack.push("main"); //main function scope start
vector<shared_ptr<BasicBlock>> emptyBasicBlockList;
functionList.insert({"main",emptyBasicBlockList});
Next(); //Consume main
while(isVarDecl(scannerSym))
varDecl();
predefinedFunc(); //Predefined functions
while(isFuncDecl(scannerSym)) {
//At the start of block in function, the start block dominates itself
stack<int> dominatedBy;
dominatedBy.push(currentBlock->getBlockNum());
dominatedByInfo.insert({currentBlock->getBlockNum(),dominatedBy});
funcDecl();
}
if(scannerSym == beginToken)
{
//At the start of block in main, the start block dominates itself
stack<int> dominatedBy;
dominatedBy.push(currentBlock->getBlockNum());
dominatedByInfo.insert({currentBlock->getBlockNum(),dominatedBy});
ssaBuilder = SSABuilder("main", currentBlock->getBlockNum(), IRpc);
cseTracker = CSETracker();
//Fixup(0);//Fix bra to first reach out here
Next(); //Consume begin Token
if(isStatSequence(scannerSym))
{
statSequence();
if(scannerSym == endToken)
{
Next(); //Consume end Token
if(scannerSym == periodToken) {
emitIntermediate(IR_end,{});
finalizeAndStartNewBlock(blk_entry, false,false,false);
scopeStack.pop(); //end of main function
Next(); //Comsume period Token
}
else
Error("computation",{getTokenStr(periodToken)});
}
else
Error("computation",{"statSequence"});
}
else
Error("computation",{"statSequence"});
}
else
Error("computation",{getTokenStr(beginToken)});
}
else
Error("computation",{getTokenStr(mainToken)});
}
void Parser:: funcBody(){
while(isVarDecl(scannerSym))
{
varDecl();
}
if(scannerSym == beginToken)
{
Next();
if(isStatSequence(scannerSym))
{
statSequence();
}
if(scannerSym == endToken)
{
Next();
}
else
Error("funcBody",{getTokenStr(endToken)});
}
else
Error("funcBody",{getTokenStr(beginToken)});
}
vector<string> Parser::formalParam(){
Scanner *scanner = Scanner::instance();
vector<string> parameters;
if(scannerSym == openparenToken)
{
Next();
if(scannerSym == identToken)
{
parameters.push_back(scanner->id);
Next();
while(scannerSym == commaToken)
{
Next();
if(scannerSym == identToken)
{
parameters.push_back(scanner->id);
Next();
}
else
Error("formalParam",{getTokenStr(identToken)});
}
}
if(scannerSym == closeparenToken)
{
Next();
}
else
Error("formalParam",{getTokenStr(closeparenToken)});
}
else
Error("formalParam",{getTokenStr(openparenToken)});
return parameters;
}
void Parser::funcDecl(){
Scanner *scanner = Scanner::instance();
if(scannerSym == funcToken || scannerSym == procToken)
{
SymType symType;
if(scannerSym == funcToken)symType = sym_func; else symType = sym_proc;
Next();
if(scannerSym == identToken)
{
string symName = scanner->id;
vector<shared_ptr<BasicBlock>> emptyBasicBlockList;
functionList.insert({symName,emptyBasicBlockList}); //New function inserted in function list
Next();
vector<string> parameters;
if(isFormalParam(scannerSym))
parameters = formalParam();
if(scannerSym == semiToken)
{
Next();
addFuncSymbol(symType,symName,parameters.size()); //if declared add identifier to symbol table
if(isFuncBody(scannerSym))
{
scopeStack.push(symName); //Current Scope set
ssaBuilder = SSABuilder(symName, currentBlock->getBlockNum(), IRpc);
cseTracker = CSETracker();
//Parameters become local variable
int index = 0;//index in stack
for(auto param : parameters)
{
addParamSymbol(param,parameters.size(),index);//add symbol table
index++;
}
funcBody();
if(symType == sym_proc) //Procedure type does not have explicit return
{
//Return code emission
//Result offset = getAddressInStack(RETURN_IN_STACK);
//emitIntermediate(IR_bra,{offset});
}
//At the end of function means end of the block
finalizeAndStartNewBlock(blk_entry, false,false,false);
//give information that defined inst of global variable
SymTable globalSymTable = symTableList.at(GLOBAL_SCOPE_NAME);
for(auto symIter : globalSymTable.varSymbolList)
{
string globalSymName = symIter.first;
SymTable currentSymTable = symTableList.at(symName);
auto currentVarSymIter = currentSymTable.varSymbolList.find(globalSymName);
if(currentSymTable.varSymbolList.end() != currentVarSymIter)//If local variable has the same name with a global variable -> skip it
continue;
shared_ptr<Symbol> globalSym = symIter.second;
if(globalSym->getSymType() == sym_var)
{
DefinedInfo globalDefInfo = ssaBuilder.getDefinedInfo(globalSymName);
Kind defKind = globalDefInfo.getKind();
if(defKind != errKind && defKind != reloadKind) //There was definition for global variable
{
SymTable *symTable = &symTableList.at(symName);
symTable->definedGlobalVal.insert({symIter.first,globalDefInfo});
}
}
}
scopeStack.pop(); //Go out of function
if(scannerSym == semiToken)
{
Next();
}
else
Error("funcDecl",{getTokenStr(semiToken)});
}
else
Error("funcDecl",{"funcBody"});
}
else
Error("funcDecl",{getTokenStr(semiToken)});
}
else
Error("funcDecl",{getTokenStr(identToken)});
}
else
Error("funcDecl",{getTokenStr(funcToken),getTokenStr(procToken)});
}
void Parser::varDecl() {
Scanner *scanner = Scanner::instance();
if(isTypeDecl(scannerSym))
{
shared_ptr<Symbol> x = typeDecl();
if(scannerSym == identToken)
{
addVarSymbol(scanner->id,x->getSymType(),x->arrayCapacity);
Next();
while(scannerSym == commaToken)
{
Next(); // Consume comma
if(scannerSym == identToken) //Array do not allow multiple declaration. So it's just variable
{
addVarSymbol(scanner->id,x->getSymType(),x->arrayCapacity);
Next();
}
else
Error("varDecl",{getTokenStr(identToken)});
}
if(scannerSym == semiToken)
{
Next();
}
else
Error("varDecl",{getTokenStr(semiToken)});
}
else
Error("varDecl",{getTokenStr(identToken)});
}
else
Error("varDecl",{"typeDecl"});
}
shared_ptr<Symbol> Parser::typeDecl() {
Scanner *scanner = Scanner::instance();
shared_ptr<Symbol> result = make_shared<Symbol>();
if(scannerSym == varToken)
{
result->setSymType(sym_var); //Var type
Next(); //Consume var Token
}
else if(scannerSym == arrToken)
{
result->setSymType(sym_array); // Array type
Next(); //Consume var Token
if(scannerSym == openbracketToken)
{
Next(); //Consume open bracket Token
if(scannerSym == numberToken)
{
result->arrayCapacity.push_back(scanner->number); // first dimension capacity
Next();
if(scannerSym == closebracketToken)
{
Next();
while(scannerSym == openbracketToken) {
Next(); //Consume open bracket Token
if (scannerSym == numberToken) {
result->arrayCapacity.push_back(scanner->number); //subsequent dimension capacity
Next();
if (scannerSym == closebracketToken) {
Next();
}
else
Error("typeDecl",{getTokenStr(closebracketToken)});
}
else
Error("typeDecl",{getTokenStr(numberToken)});
}
}
else
Error("typeDecl",{getTokenStr(closebracketToken)});
}
else
Error("typeDecl",{getTokenStr(numberToken)});
}
else
Error("typeDecl",{getTokenStr(openbracketToken)});
}
else
Error("typeDecl",{getTokenStr(varToken),getTokenStr(arrToken)});
return result;
}
void Parser::statSequence() {
if(isStatement(scannerSym))
{
statement();
while(scannerSym == semiToken)
{
Next();
if(isStatement(scannerSym))
{
statement();
}
else
Error("statSequence",{"statement"});
}
}
else
Error("statSequence",{"statement"});
}
void Parser::statement()
{
if(isAssignment(scannerSym))
{
assignment();
}
else if(isFuncCall(scannerSym))
{
funcCall();
}
else if(isIfStatement(scannerSym))
{
ifStatement();
}
else if(isWhileStatement(scannerSym))
{
whileStatement();
}
else if(isReturnStatement(scannerSym))
{
returnStatement();
}
else
Error("statement",{"assignment","funcCall","ifStatement","whileStatement","returnStatement"});
}
void Parser::returnStatement() {
Result x;
if(scannerSym == returnToken)
{
Next();
if(isExpression(scannerSym))
{
x = expression();
Result ret;ret.setReg(REG_RET_VAL);
emitIntermediate(IR_miu,{x,ret});
Result returnAddr;returnAddr.setReg(REG_RET);returnAddr.setReturnAddr();
emitIntermediate(IR_bra,{returnAddr});
//Result offset = getAddressInStack(RETURN_IN_STACK);
//Result x = emitIntermediate(IR_load,{offset});
//emitIntermediate(IR_bra,{x});
}
}
else
Error("returnStatement",{getTokenStr(returnToken)});
}
void Parser::whileStatement() {
Result x,follow;
if(scannerSym == whileToken)
{
Next();
if(isRelation(scannerSym))
{
//CSE should include loads in while body(actually after blk_while_cond)
ssaBuilder.currentBlockKind.push(blk_while_body);
//for block of which outer block is inner block
BlockKind outerBlockKind = currentBlock->getOuterBlockKind();
int cseRevertBlock = currentBlock->getBlockNum();
//At the start of while, new Block starts
if(!finalizeAndStartNewBlock(blk_while_cond, false, true,true)) //Already New block is made(just change the name of block
currentBlock->setBlockKind(blk_while_cond);
currentBlock->setOuterBlockKind(outerBlockKind);
int dominatingBlockNum = currentBlock->getBlockNum();
int conditionBlockNum = dominatingBlockNum;
loopDepth++;//From condition block, instructions will loop
x = relation(); //Result is instruction with relational operator
CondJF(x); // x.fixloc indicate that the destination should be fixed
ssaBuilder.startJoinBlock(currentBlock->getBlockKind(),currentBlock->getBlockNum());
//After the condition, also new block starts
finalizeAndStartNewBlock(blk_while_body, true, true,true); //while block automatically dominated by cond block
ssaBuilder.protectDef();
if(scannerSym == doToken)
{
Next();
if(isStatSequence(scannerSym))
{
statSequence();
if(scannerSym == odToken)
{
Next();
//Next to od token
follow = x;
follow.setFixLoc(follow.getFixLoc());//jump one instruction more because while should check condition for every iteration
//cmp <- follow.fixloc
//bsh <- x.fixloc
currentBlock->CFGForwardEdges.push_back(instructionBlockPair.at(follow.getFixLoc())); //Connect forward edge to the point to the unconditional branch
UnCJF(follow); //unconditional branch follow.fixloc
//After inner block, ssa numbering should be revert to the previous state
ssaBuilder.revertToOuter(dominatingBlockNum);
cseTracker.revertToOuter(cseRevertBlock,false);
if(finalizeAndStartNewBlock(blk_while_end, false, false,false))//After unconditional jump means going back without reservation
updateBlockForDT(dominatingBlockNum);
currentBlock->setOuterBlockKind(outerBlockKind);
vector<shared_ptr<IRFormat>> phiCodes = ssaBuilder.getPhiCodes();
//vector<IRFormat> irCodes = phiCodes;
//irCodes.insert(irCodes.end(),std::make_move_iterator(joinBlockCodes.begin()),std::make_move_iterator(joinBlockCodes.end()));
updatePhiInBB(conditionBlockNum, phiCodes);
ssaBuilder.currentBlockKind.pop();
Fixup((unsigned long)x.getFixLoc()); //fix so that while branch here
ssaBuilder.endJoinBlock();
for(auto code : phiCodes)
{
//Phi is also kind of definition(defined kind: inst)
string targetOperandName = code->operands.at(0).getVariableName();
shared_ptr<Symbol> targetOperandSym = code->operands.at(0).getVarSym();
Result definedOperand;
definedOperand.setInst(code);
DefinedInfo defInfo(currentBlock->getBlockNum(), targetOperandName);
defInfo.setInst(code->getLineNo(),code);
ssaBuilder.prepareForProcess(targetOperandName, targetOperandSym, defInfo);
for(auto &operand : code->operands)
{
if(operand.getKind() == errKind)
{
DefinedInfo defJustBefore = ssaBuilder.getDefinedInfo();
Kind kind = defJustBefore.getKind();
if(kind == instKind)
operand.setInst(defJustBefore.getInst());
else if(kind == varKind) {
operand.setVariable(defJustBefore.getVar(), defJustBefore.getVarSym());
operand.setDefInst(defJustBefore.getDefinedInstOfVar());
}
else if(kind == constKind) {
operand.setConst(defJustBefore.getConst());
operand.setConstPropVar(targetOperandName);
}
}
}
ssaBuilder.insertDefinedInstr();
//If there is outer join block propagate
emitOrUpdatePhi(targetOperandName, definedOperand);
}
loopDepth--;
//When completely out of while block, do the cse for load
//if(ssaBuilder.currentBlockKind.empty() || ssaBuilder.currentBlockKind.top() != blk_while_body) {
cseForWhileInst(dominatingBlockNum);
//cseForLoad(dominatingBlockNum); // Do for for innner block
//}
}
else
Error("whileStatement",{getTokenStr(odToken)});
}
else
Error("whileStatement",{"statSequence"});
}
else
Error("whileStatement",{getTokenStr(doToken)});
}
else
Error("whileStatement",{"relation"});
}
else
Error("whileStatement",{getTokenStr(whileToken)});
}
void Parser::ifStatement() {
Result x, follow;
if(scannerSym == ifToken)
{
Next();
if(isRelation(scannerSym))
{
x = relation();
CondJF(x);
int dominatingBlockNum = currentBlock->getBlockNum();
//Join Block create
ssaBuilder.startJoinBlock(currentBlock->getBlockKind(),currentBlock->getBlockNum());
BlockKind outerBlockKind = currentBlock->getOuterBlockKind();
//In if statement, after the condition new block starts
if(!finalizeAndStartNewBlock(blk_if_then, true, true,true)) //Automatically dominated by previous block
currentBlock->setBlockKind(blk_if_then);
ssaBuilder.currentBlockKind.push(blk_if_then);
ssaBuilder.protectDef();
if(scannerSym == thenToken)
{
Next();
follow.setKind(instKind);
follow.setFixLoc(0);
if(isStatSequence(scannerSym))
{
statSequence();
if(scannerSym == elseToken)
{
Next();
UnCJF(follow);
//Until this point, still in the then block
//After inner block, ssa numbering should be revert to the previous state
ssaBuilder.revertToOuter(dominatingBlockNum);
cseTracker.revertToOuter(dominatingBlockNum,false);
//The start of else is new block
finalizeAndStartNewBlock(blk_if_else, false, false,false);//if then is performed it should avoid else
ssaBuilder.protectDef();
ssaBuilder.currentBlockKind.pop();
ssaBuilder.currentBlockKind.push(blk_if_else);
updateBlockForDT(dominatingBlockNum); //else should be dominated by condition block
Fixup((unsigned long)x.getFixLoc());
if(isStatSequence(scannerSym))
{
statSequence();
}
else
Error("ifStatement",{"statSequence"});
//After inner block, ssa numbering should be revert to the previous state
ssaBuilder.revertToOuter(dominatingBlockNum);
cseTracker.revertToOuter(dominatingBlockNum,true);
if(finalizeAndStartNewBlock(blk_if_end, false, true,false)) //After all if related statements end, new block start
updateBlockForDT(dominatingBlockNum);//if.end block should be dominated by condition
}
else {
//After inner block, ssa numbering should be revert to the previous state
ssaBuilder.revertToOuter(dominatingBlockNum);
cseTracker.revertToOuter(dominatingBlockNum,true);
if(finalizeAndStartNewBlock(blk_if_end, false, true,false))//After all if related statements end, new block start
updateBlockForDT(dominatingBlockNum);//if.end block should be dominated by condition
Fixup((unsigned long) x.getFixLoc());
}
currentBlock->setOuterBlockKind(outerBlockKind);
ssaBuilder.currentBlockKind.pop();
//updateBlockForDT(dominatingBlockNum);//if.end block should be dominated by condition
if(scannerSym == fiToken)
{
vector<shared_ptr<IRFormat>> phiCodes = ssaBuilder.getPhiCodes();
ssaBuilder.endJoinBlock(); //go back to outer joinBlock
for(auto code : phiCodes)
{
code->setBlkNo(currentBlock->getBlockNum());//Fix join block num which was not correct at first.
currentBlock->phiCodes.push_back(code);//contents of join block is copied
//Phi is also kind of definition(defined kind: inst)
string targetOperand = code->operands.at(0).getVariableName();
shared_ptr<Symbol> targetOperandSym = code->operands.at(0).getVarSym();
Result definedOperand;
definedOperand.setInst(code);
DefinedInfo defInfo(currentBlock->getBlockNum(),targetOperand);
defInfo.setInst(code->getLineNo(),code);
ssaBuilder.prepareForProcess(targetOperand, targetOperandSym,defInfo);
for(auto &operand : code->operands)
{
if(operand.getKind() == errKind)
{
DefinedInfo defJustBefore = ssaBuilder.getDefinedInfo();
Kind kind = defJustBefore.getKind();
if(kind == instKind)
operand.setInst(defJustBefore.getInst());
else if(kind == varKind) {
operand.setVariable(defJustBefore.getVar(), defJustBefore.getVarSym());
operand.setDefInst(defJustBefore.getDefinedInstOfVar());
}
else if(kind == constKind)
operand.setConst(defJustBefore.getConst());
}
}
ssaBuilder.insertDefinedInstr();
//If there is outer join block propagate
emitOrUpdatePhi(targetOperand,definedOperand);
}
Next();
FixLink((unsigned long)follow.getFixLoc());
}
else
Error("ifStatement",{getTokenStr(fiToken)});
}
else
Error("ifStatement",{"statSequence"});
}
else
Error("ifStatement",{getTokenStr(thenToken)});
}
else
Error("ifStatement",{"relation"});
}
else
Error("ifStatement",{getTokenStr(ifToken)});
}
Result Parser::funcCall() {
Scanner *scanner = Scanner::instance();
std::string functionName;
Result x, result;
int numOfParam = 0;
int locationOfFunc = 0;
//std::vector<Result> arguments;
if(scannerSym == callToken)
{
Next();
if(scannerSym == identToken)
{
functionName = scanner->id;
shared_ptr<Symbol> functionSym = symTableLookup(scopeStack.top(),functionName, sym_func);
numOfParam = functionSym->getNumOfParam(); //number of function parameter
locationOfFunc = functionSym->getBaseAddr(); //function location(instruction number)
Next();
if(scannerSym == openparenToken)
{
Next();
if(isExpression((scannerSym)))
{
int i = 0;
x = expression();
//Because of predefined function
if(functionName != "OutputNum")
{
Result reg_param;reg_param.setReg(REG_PARAM);
emitIntermediate(IR_miu,{x,reg_param}); //We assume that SP is automatically adjusted (So SP is adjusted and then store them)
i++;
while(scannerSym == commaToken)
{
Next();
if(isExpression(scannerSym))
{
x = expression();
if(i < NUM_OF_PARAM_REGS)
{
reg_param.setReg(REG_PARAM + i);
emitIntermediate(IR_miu,{x,reg_param});
}
else{
reg_param.setReg(REG_SP);
emitIntermediate(IR_miu,{x,reg_param});
}
i++;
}
else
Error("funcCall",{"expression"});
}
if(i != numOfParam)
cerr << "Number of parameter not matched" << endl;
}
}
if(scannerSym == closeparenToken)
{
Next();
}
else
Error("funcCall",{getTokenStr(closeparenToken)});
}
//Deal with predefined function
if(functionName == "InputNum")
result = emitIntermediate(IR_read,{});
else if (functionName =="OutputNum")
result = emitIntermediate(IR_write,{x});
else if (functionName =="OutputNewLine")
result = emitIntermediate(IR_writeNL,{});
//General Fucntion
else
{
//For all global variable
SymTable mainSymTable = symTableList.at(GLOBAL_SCOPE_NAME);
for(auto symbol : mainSymTable.varSymbolList)
{
string symName = symbol.first;
shared_ptr<Symbol> sym = symbol.second;
SymTable currentSymTable = symTableList.at(functionName);
auto currentVarSymIter = currentSymTable.varSymbolList.find(symName);
if(currentSymTable.varSymbolList.end() != currentVarSymIter)//If local variable has the same name with a global variable -> skip it
continue;
DefinedInfo defInfo = ssaBuilder.getDefinedInfo(symName);
Result storedValue;
Kind defKind = defInfo.getKind();
//store globals having been defined
if(defKind != errKind && defKind != reloadKind)//without No definition or definition nullified case
{
if(defKind == constKind)
{
storedValue.setConst(defInfo.getConst());
storedValue.setConstPropVar(symName);
}
else if(defKind == varKind) {
storedValue.setVariable(defInfo.getVar(), defInfo.getVarSym());
storedValue.setDefInst(defInfo.getDefinedInstOfVar());
}
else if(defKind == instKind)
storedValue.setInst(defInfo.getInst());
int loc = sym->getBaseAddr()*4;
Result operandGP;operandGP.setReg(REG_GP);
Result operandLoc;operandLoc.setConst(loc);
Result addrToStore = emitIntermediate(IR_adda,{operandGP,operandLoc});
emitIntermediate(IR_store,{storedValue,addrToStore});
}
}
Result jumpLocation;jumpLocation.setConst(locationOfFunc);
jumpLocation.setDiffFuncLoc(functionName, functionSym);
SymType symType = functionSym->getSymType();
jumpLocation.setFunctionType(symType);
/*
//For all global variable
SymTable mainSymTable = symTableList.at(GLOBAL_SCOPE_NAME);
for(auto symbol : mainSymTable.varSymbolList)
{
DefinedInfo defInfo = ssaBuilder.getDefinedInfo(symbol.first);
if(defInfo.getKind() != errKind)
{
GlobalDefInfo gDefInfo = {symbol.second, defInfo};
jumpLocation.globalDefInfo.insert({symbol.first,gDefInfo});
}
}*/
result = emitIntermediate(IR_bra,{jumpLocation});
Result returnValReg; returnValReg.setReg(REG_RET_VAL);
if(symType == sym_func)
emitIntermediate(IR_miu,{returnValReg,result}); //Return value get
//After branch update all global variable and make definition of it is load instruction
for(auto symbol : mainSymTable.varSymbolList)
{
string symName = symbol.first;
shared_ptr<Symbol> sym = symbol.second;
SymTable currentSymTable = symTableList.at(functionName);
auto currentVarSymIter = currentSymTable.varSymbolList.find(symName);
if(currentSymTable.varSymbolList.end() != currentVarSymIter)//If local variable has the same name with a global variable -> skip it
continue;
//After function call, all array load should be killed
if(sym->getSymType() == sym_array)
{
shared_ptr<IRFormat> irCode(new IRFormat);
irCode->setBlkNo(currentBlock->getBlockNum());
irCode->setLineNo(-1);
irCode->setIROP(IR_store);
Result definedVal;definedVal.setVariable(symName,sym);
irCode->operands = {Result(),definedVal};
shared_ptr<IRFormat> previousSameOpInst = cseTracker.getCurrentInstPtr(IR_store);
irCode->setPreviousSameOpInst(previousSameOpInst);
cseTracker.setCurrentInst(IR_store,irCode);
}
else//All global variable should be reinitialized
{
DefinedInfo defInfo;defInfo.setReload();
//int loc = sym->getBaseAddr()*4;
//Result operandGP;operandGP.setReg(REG_GP);
//Result operandLoc;operandLoc.setConst(loc);
//Result addrToLoad = emitIntermediate(IR_add,{operandGP,operandLoc});
//Result loadedVal = emitIntermediate(IR_load,{addrToLoad});
//defInfo.setInst(loadedVal.getInst()->getLineNo(),loadedVal.getInst());
ssaBuilder.prepareForProcess(symName,sym,defInfo);
ssaBuilder.insertDefinedInstr();
}
}
}
}
else
Error("funcCall",{getTokenStr(identToken)});
}
else
Error("funcCall",{getTokenStr(callToken)});
return result;
}
Result Parser::assignment() {
Result x, y, result;
if(scannerSym == letToken)
{
Next();
if(isDesignator(scannerSym))
{
x = designator();
if(scannerSym == becomesToken)
{
Next();
if(isExpression(scannerSym))
{
y = expression();
if(x.isArrayInst()) {
Result indexResult;indexResult.setInst(x.getIndexInst());
string arrayString = x.getVariableName();
x = emitIntermediate(IR_adda,{x,indexResult});
x.setArrayInst(arrayString);
result = emitIntermediate(IR_store, {y, x});
}
else {
result = emitIntermediate(IR_move, {y,x});
//No move instruction more, but return y:which is x(variable)'s phi updated value
emitOrUpdatePhi(x.getVariableName(), result);//For variable x
}
}
else
Error("assignment",{"expression"});
}
else
Error("assignment",{getTokenStr(becomesToken)});
}
else
Error("assignment",{"designator"});
}
else
Error("assignment",{getTokenStr(letToken)});
return result;
}
Result Parser::relation() {
Result x,y,result;
if(isExpression(scannerSym))
{
x = expression();
if(isRelOp(scannerSym))
{
IROP relop = relOp();
if(isExpression(scannerSym))
{
y = expression();
result = emitIntermediate(IR_cmp,{x,y});
result.setRelOp(relop);
}
else
Error("relation",{"expression"});
}
else
Error("relation",{"relOp"});
}
else
Error("relation",{"expression"});
return result;
}
Result Parser::expression() {
Result x,y, result;
if(isTerm(scannerSym))
{
x = term();
result = x;
while(scannerSym == plusToken || scannerSym == minusToken)
{
IROP irOp;if(scannerSym == plusToken)irOp = IR_add;else irOp = IR_sub; //Choose compute operation
Next();
if(isTerm(scannerSym))
{