-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAST.hpp
More file actions
2208 lines (1964 loc) · 62.3 KB
/
AST.hpp
File metadata and controls
2208 lines (1964 loc) · 62.3 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
/*
* AST.hpp
*
* Created on: Apr 29, 2019
* Author: 26sra
*/
#ifndef EKCC_AST_HPP_
#define EKCC_AST_HPP_
#include<vector>
#include<iostream>
#include<string>
#include<utility>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
#include<tuple>
#include<memory>
#include<assert.h>
#include<stdlib.h>
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/STLExtras.h"
#include <llvm/ADT/Triple.h>
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Verifier.h"
#include <llvm/IR/DataLayout.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/LegacyPassNameParser.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Analysis/CallGraph.h>
#include <llvm/Analysis/CallGraphSCCPass.h>
#include <llvm/Analysis/LoopPass.h>
#include <llvm/Analysis/RegionPass.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/Bitcode/BitcodeWriterPass.h>
#include <llvm/CodeGen/TargetPassConfig.h>
#include <llvm/Config/llvm-config.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/InitializePasses.h>
#include <llvm/MC/SubtargetFeature.h>
#include <llvm/Support/Debug.h>
#include <llvm/Support/FileSystem.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/InitLLVM.h>
#include "llvm/Support/CommandLine.h"
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/SystemUtils.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Support/YAMLTraits.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/Coroutines.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/IPO/PassManagerBuilder.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include "llvm-c/Types.h"
#include "llvm/Object/ObjectFile.h"
#include "ValidTypes.hpp"
#include "LLVMGlobals.hpp"
using std::vector;
using std::string;
using std::to_string;
using std::move;
using std::stringstream;
using std::unordered_map;
using std::tuple;
using std::get;
using std::unique_ptr;
using std::unordered_set;
typedef unordered_map<string, tuple<ValidType *, llvm::AllocaInst *>> VarTable;
typedef unordered_map<string, tuple<ValidType *, llvm::AllocaInst * >>::const_iterator VarTableEntry;
typedef unordered_map<string, tuple<vector< ValidType * >, llvm::Function *> > FuncTable;
typedef unordered_map<string, tuple<vector< ValidType * >, llvm::Function *> >::const_iterator FuncTableEntry;
typedef int (*JitFunc)();
struct ASTNode {
static ASTNode * root_;
static bool ready_;
static vector< string > compilerErrors_;
static vector< int > lineNumberErrors_;
static FuncTable funcTable_;
static tuple<string, int> recursiveFuncPlaceHolder_;
static unordered_set<string> recursiveFuncNames_;
static llvm::Function * currentLLVMFunctionPrototype_;
static VarTable varTable_;
static bool runDefined_;
static VariableTypes currentFunctionReturnType_;
static llvm::Function * runFunction_;
static llvm::Function * printfFunction_;
static llvm::Function * cintAddFunction_;
static llvm::Function * cintMultiplyFunction_;
static llvm::Function * cintDivideFunction_;
static llvm::Function * cintSubtractFunction_;
static llvm::Function * cintNegateFunction_;
vector< ASTNode * > children_;
unsigned lineNumber_ = 0;
ValidType * resultType_ = nullptr;
ASTNode() : lineNumber_(0), resultType_(nullptr) {}
ASTNode(unsigned lineNumber) : lineNumber_(lineNumber) {}
ASTNode(ValidType * resultType) : resultType_(resultType) {}
ASTNode(unsigned lineNumber, ValidType * resultType) :
lineNumber_(lineNumber), resultType_(resultType) {}
virtual void
PrintRecursive(stringstream& ss, unsigned depth) {};
virtual
~ASTNode() {
for (auto n : this->children_) {
delete n;
n = nullptr;
}
if (this->resultType_) {
delete this->resultType_;
this->resultType_ = nullptr;
}
}
virtual llvm::Value *
GetLLVMValue(string identifier) {
llvm::Value * ret = nullptr;
VarTableEntry hit = ASTNode::varTable_.find(identifier);
if (ASTNode::varTable_.end() != hit) {
ret = get<1>(hit->second);
}
return ret;
}
virtual ValidType *
GetValidType(string identifier) {
ValidType * ret = nullptr;
VarTableEntry hit = ASTNode::varTable_.find(identifier);
if (ASTNode::varTable_.end() != hit) {
ret = get<0>(hit->second);
}
return ret;
}
virtual llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
if (this->children_.size() > 0) {
for (auto n: this->children_) {
n->GenerateCode(endBlock);
}
}
return nullptr;
}
virtual llvm::Value *
GetLLVMReturnValueRecursive() {
llvm::Value * ret = nullptr;
if(this->children_.size()>0) {
for (auto node : this->children_) {
ret = node->GetLLVMReturnValueRecursive();
if (ret != nullptr) {
return ret;
}
}
}
return ret;
}
static void
StaticInit(string inputFile) {
if (!ASTNode::ready_) {
// Set up for JIT
std::string HostTriple(llvm::sys::getProcessTriple());
std::string CPU = llvm::sys::getHostCPUName();
llvm::StringMap<bool> HostFeatures;
std::string FeaturesStr;
if (llvm::sys::getHostCPUFeatures(HostFeatures)) {
llvm::SubtargetFeatures Features;
for (auto &F : HostFeatures)
Features.AddFeature(F.first(), F.second);
FeaturesStr = Features.getString();
}
// construct global module
GlobalModuleUPtr = unique_ptr<llvm::Module>{new llvm::Module(inputFile, GlobalContext)};
GlobalModule = GlobalModuleUPtr.get();
// Note: If you're using the JIT, you'll get the TM from the JIT engine...
std::string Err;
const llvm::Target* Target = llvm::TargetRegistry::lookupTarget (HostTriple, Err);
std::unique_ptr<llvm::TargetMachine> TM(Target->createTargetMachine(HostTriple, CPU, FeaturesStr,
llvm::TargetOptions(), llvm::Reloc::PIC_));
GlobalTargetMachine = move(TM);
GlobalModule->setDataLayout(GlobalTargetMachine->createDataLayout());
GlobalModule->setTargetTriple(HostTriple);
// construct a print function
vector<llvm::Type *> printfCharPtrParam;
printfCharPtrParam.push_back(llvm::Type::getInt8PtrTy(GlobalContext));
llvm::FunctionType * printFType =
llvm::FunctionType::get(
llvm::Type::getInt32Ty(GlobalContext),
printfCharPtrParam, true);
ASTNode::printfFunction_ = llvm::Function::Create(
printFType, llvm::Function::ExternalLinkage,
llvm::Twine("printf"),
GlobalModule);
// construct the cint binary operations
vector<llvm::Type *> cintBinaryParams;
cintBinaryParams.push_back(llvm::Type::getInt32Ty(GlobalContext));
cintBinaryParams.push_back(llvm::Type::getInt32Ty(GlobalContext));
llvm::FunctionType * cintBinaryFType =
llvm::FunctionType::get(
llvm::Type::getInt32Ty(GlobalContext),
cintBinaryParams, false);
ASTNode::cintAddFunction_ = llvm::Function::Create(
cintBinaryFType, llvm::Function::ExternalLinkage,
llvm::Twine("cint_add"),
GlobalModule);
ASTNode::cintSubtractFunction_ = llvm::Function::Create(
cintBinaryFType, llvm::Function::ExternalLinkage,
llvm::Twine("cint_subtract"),
GlobalModule);
ASTNode::cintMultiplyFunction_ = llvm::Function::Create(
cintBinaryFType, llvm::Function::ExternalLinkage,
llvm::Twine("cint_multiply"),
GlobalModule);
ASTNode::cintDivideFunction_ = llvm::Function::Create(
cintBinaryFType, llvm::Function::ExternalLinkage,
llvm::Twine("cint_divide"),
GlobalModule);
// construct cint unary operations
vector<llvm::Type *> cintUnaryParams;
cintUnaryParams.push_back(llvm::Type::getInt32Ty(GlobalContext));
llvm::FunctionType * cintUnaryFType =
llvm::FunctionType::get(
llvm::Type::getInt32Ty(GlobalContext),
cintUnaryParams, false);
ASTNode::cintNegateFunction_ = llvm::Function::Create(
cintUnaryFType, llvm::Function::ExternalLinkage,
llvm::Twine("cint_negate"),
GlobalModule);
ASTNode::ready_ = true;
}
}
static void
LogError(unsigned lineNumber, string errorMessage, bool exitFast=false) {
stringstream ss;
ss << "error: line " << lineNumber << ": ";
ss << errorMessage;
ss << endl;
ASTNode::compilerErrors_.push_back(ss.str());
if (exitFast) {
cout << ASTNode::GetCompilerErrors() << endl;
exit(1);
}
}
static string
GetCompilerErrors() {
string ret = "";
for (auto e : ASTNode::compilerErrors_) {
ret += e;
}
return ret;
}
static bool
HasCompilerErrors() {
return ASTNode::compilerErrors_.size() > 0;
}
};
struct ProgramNode : public ASTNode {
ProgramNode(unsigned lineNumber, ASTNode * funcsNode) :
ASTNode(lineNumber) {
this->children_.push_back(funcsNode);
ASTNode::root_ = this;
if (!ASTNode::runDefined_) {
ASTNode::LogError(lineNumber, "Undefined run function");
}
}
ProgramNode(unsigned lineNumber, ASTNode * externs,
ASTNode * funcsNode) : ASTNode(lineNumber){
this->children_.push_back(funcsNode);
this->children_.push_back(externs);
ASTNode::root_ = this;
if (!ASTNode::runDefined_) {
ASTNode::LogError(lineNumber, "Undefined run function");
}
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
ss << "---" << '\n';
ss << "name: prog" << '\n';
for (auto node : this->children_) {
node->PrintRecursive(ss, depth+1);
}
}
void
GenerateCodeRecursive(llvm::raw_string_ostream& ss, bool optimize) {
ASTNode::GenerateCode(nullptr);
if (optimize) {
AddOptimizations();
}
// Print IR without optimization
GlobalModule->print(ss, nullptr);
}
void
AddOptimizations() {
// To build and run the pass manager...
llvm::Triple ModuleTriple(GlobalModule->getTargetTriple());
std::unique_ptr<llvm::legacy::PassManager> MPM(new llvm::legacy::PassManager);
llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
MPM->add(new llvm::TargetLibraryInfoWrapperPass(TLII));
std::unique_ptr<llvm::legacy::FunctionPassManager>
FPM(new llvm::legacy::FunctionPassManager(GlobalModule));
FPM->add(createTargetTransformInfoWrapperPass(GlobalTargetMachine->getTargetIRAnalysis()));
llvm::PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = 3;
PMBuilder.SizeLevel = 0;
PMBuilder.Inliner = llvm::createFunctionInliningPass(PMBuilder.OptLevel, PMBuilder.SizeLevel, false);
PMBuilder.LoopVectorize = true;
GlobalTargetMachine->adjustPassManager(PMBuilder);
PMBuilder.populateFunctionPassManager(*FPM);
PMBuilder.populateModulePassManager(*MPM);
FPM->doInitialization();
for (llvm::Function &F : *GlobalModule)
FPM->run(F);
FPM->doFinalization();
MPM->run(*GlobalModule);
}
void
ExecuteJIT(int argc, char ** argv){
string error;
llvm::EngineBuilder enginebuilder(move(GlobalModuleUPtr));
llvm::ExecutionEngine * engine = enginebuilder.setErrorStr(&error).create();
if (!engine) {
cout << "error: failed to create execution engine" << endl;
exit(1);
}
llvm::SMDiagnostic diagnostic;
unique_ptr<llvm::Module> m = parseIRFile("main.ll", diagnostic, GlobalContext);
engine->addModule(move(m));
engine->finalizeObject();
auto mainLLVMFunction = engine->FindFunctionNamed("main");
int (*mainFunc)(int, char **) = (int(*)(int,char**))engine->getPointerToFunction(mainLLVMFunction);
exit(mainFunc(argc, argv));
}
};
struct VdeclNode : public ASTNode {
ValidType * type_ = nullptr;
string identifier_;
virtual ~VdeclNode() {
if (this->type_ != nullptr) {
delete this->type_;
this->type_ = nullptr;
}
}
VdeclNode(unsigned lineNumber, ValidType * type, string identifier) :
ASTNode(lineNumber), type_(type),
identifier_(identifier.substr(1, string::npos)) {
if (ASTNode::varTable_.end() != ASTNode::varTable_.find(identifier_)) {
ASTNode::LogError(lineNumber,
string("variable identifier ") +
identifier +
string(" already defined"));
} else if (type->varType_ == VoidVarType){
ASTNode::LogError(lineNumber,
string("variable identifier ") +
identifier +
string(" cannot be void"));
} else if (type->varType_==RefVarType) {
RefType * refType = (RefType *) type;
if (refType->invalidConstructor_) {
ASTNode::LogError(lineNumber,
string("variable identifier ") +
identifier +
string(" is a ref and points to a ref."));
}
}
get<0>(ASTNode::varTable_[identifier_]) = type;
}
void
PrintSelf(stringstream & ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
string left2 = std::string(depth*2, ' ');
ss << left1 << "vdecl:" << '\n';
ss << left2 << "node: vdecl" << '\n';
ss << left2 << "type: " << this->type_->GetName() << '\n';
ss << left2 << "var: " << this->identifier_ << '\n';
}
llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
llvm::Function * parentFunction = GlobalBuilder.GetInsertBlock()->getParent();
llvm::AllocaInst * allocaInst = nullptr;
switch (this->type_->varType_) {
case IntVarType:
allocaInst = CreateEntryBlockAllocaInt(
parentFunction, this->identifier_);
break;
case FloatVarType:
allocaInst = CreateEntryBlockAllocaFloat(
parentFunction, this->identifier_);
break;
case BooleanVarType:
allocaInst = CreateEntryBlockAllocaBool(
parentFunction, this->identifier_);
break;
case CintVarType:
allocaInst = CreateEntryBlockAllocaInt(
parentFunction, this->identifier_);
break;
default:
cout << "unhandled case in vdeclnode" << endl;
break;
}
get<0>(ASTNode::varTable_[this->identifier_]) = this->type_;
get<1>(ASTNode::varTable_[this->identifier_]) = allocaInst;
return allocaInst;
}
void
PrintRecursive(stringstream & ss, unsigned depth) {
PrintSelf(ss, depth);
}
};
struct VdeclsNode : public ASTNode {
VdeclsNode(unsigned lineNumber, VdeclNode * vdeclNode) :
ASTNode(lineNumber) {
this->children_.push_back(vdeclNode);
}
VdeclsNode(unsigned lineNumber, VdeclsNode * vdeclsNode,
VdeclNode * vdeclNode) : ASTNode(lineNumber) {
for (auto node : vdeclsNode->children_) {
this->children_.push_back(node);
}
this->children_.push_back(vdeclNode);
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
string left2 = std::string(depth*2, ' ');
string left3 = std::string((depth+1)*2, ' ');
ss << left1 << "vdecls:" << '\n';
ss << left2 << "name: vdecls" << '\n';
ss << left2 << "vars:" << '\n';
ss << left3 << "-" << '\n';
for (unsigned i=0; i<this->children_.size(); ++i) {
this->children_[i]->PrintRecursive(ss, depth+3);
if (i!=this->children_.size()-1)
ss << left3 << "-" << '\n';
}
};
};
struct ExistingVarNode: public ASTNode {
string identifier_;
ExistingVarNode(unsigned lineNumber, string identifier) :
ASTNode(lineNumber), identifier_(identifier.substr(1, string::npos)) {
VarTableEntry hit = ASTNode::varTable_.find(this->identifier_);
this->resultType_ = get<0>(hit->second);
if (hit==ASTNode::varTable_.end()) {
ASTNode::LogError(lineNumber,
string("variable identifier ") +
identifier +
string(" not declared"));
}
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
ss << left1 << "name: varval" << '\n';
ss << left1 << "var: " <<
this->identifier_.substr(1, string::npos) << '\n';
}
llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
llvm::Value * val = GetLLVMValue(this->identifier_);
ValidType * vtype = get<0>(ASTNode::varTable_[this->identifier_]);
if (vtype->varType_==RefVarType) {
llvm::AllocaInst * alloca = get<1>(ASTNode::varTable_[this->identifier_]);
llvm::LoadInst * loadInstruction = GlobalBuilder.CreateLoad(alloca, this->identifier_);
return GlobalBuilder.CreateLoad(alloca, this->identifier_);
}
return GlobalBuilder.CreateLoad(val, this->identifier_);
}
};
struct ExistingFuncNode: public ASTNode {
string identifier_;
ExistingFuncNode(unsigned lineNumber, string identifier) :
ASTNode(lineNumber), identifier_(identifier){}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
ss << left1 << "name: funccall" << '\n';
ss << left1 << "globid: " << this->identifier_ << '\n';
}
llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
if ( this->identifier_ == ASTNode::currentLLVMFunctionPrototype_->getName().str() ) {
return ASTNode::currentLLVMFunctionPrototype_;
}
llvm::Function * function = get<1>(ASTNode::funcTable_[this->identifier_]);
return function;
}
};
struct TdeclsNode : public ASTNode {
ValidType * paramType_ = nullptr;
vector<ValidType *> paramTypes_;
TdeclsNode(unsigned lineNumber, ValidType * validType):
ASTNode(lineNumber), paramType_(validType) {
this->paramTypes_.push_back(validType);
}
TdeclsNode(unsigned lineNumber, TdeclsNode * tdeclsNode,
ValidType * validType):
ASTNode(lineNumber), paramType_(validType) {
for (auto type : tdeclsNode->paramTypes_) {
this->paramTypes_.push_back(type);
}
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
string left2 = std::string(depth*2, ' ');
string left3 = std::string((depth+1)*2, ' ');
ss << left1 << "tdecls:" << '\n';
ss << left2 << "name: tdecls" << '\n';
ss << left2 << "types:" << '\n';
for (auto type: this->paramTypes_) {
ss << left3 << "- " << type->GetName() << '\n';
}
};
virtual ~TdeclsNode() {
if (this->paramType_ != nullptr) {
delete this->paramType_;
this->paramType_ = nullptr;
}
};
};
struct ExternNode : public ASTNode {
ValidType * retType_ = nullptr;
TdeclsNode * tdeclsNode_ = nullptr;
string identifier_;
ExternNode(unsigned lineNumber,
ValidType * retType, string identifier) :
ASTNode(lineNumber), retType_(retType), identifier_(identifier) {
this->Validate(lineNumber,
retType, identifier);
}
ExternNode(unsigned lineNumber,
ValidType * retType,
string identifier,
TdeclsNode * tdeclsNode) :
ASTNode(lineNumber), retType_(retType),
tdeclsNode_(tdeclsNode), identifier_(identifier) {
this->Validate(lineNumber,
retType, identifier);
this->children_.push_back(tdeclsNode);
}
void
Validate(unsigned lineNumber,
ValidType * retType, string identifier) {
if(retType->varType_== RefVarType) {
ASTNode::LogError(lineNumber,
string("function return type can't be ref. \n"));
}
vector< ValidType * > vTypes;
vTypes.push_back(retType);
if (this->tdeclsNode_!=nullptr) {
for (auto t : this->tdeclsNode_->paramTypes_) {
vTypes.push_back(t);
}
}
FuncTableEntry hit = ASTNode::funcTable_.find(identifier);
if (hit != ASTNode::funcTable_.end()) {
ASTNode::LogError(lineNumber,
string("function identifer ") +
identifier + string("already defined\n"));
}
llvm::Type * getArgReturnType = nullptr;
if (identifier=="arg") {
getArgReturnType = llvm::Type::getInt32Ty(GlobalContext);
} else if (identifier=="argf") {
getArgReturnType = llvm::Type::getFloatTy(GlobalContext);
} else {
ASTNode::LogError(lineNumber, "invalid extern function", true);
}
vector<llvm::Type *> getArgParam { llvm::Type::getInt32Ty(GlobalContext) };
llvm::FunctionType * getArgFuncType =
llvm::FunctionType::get(
getArgReturnType,
getArgParam, false);
llvm::Function * getArgFunc = llvm::Function::Create(
getArgFuncType, llvm::Function::ExternalLinkage,
llvm::Twine(identifier),
GlobalModule);
get<0>(ASTNode::funcTable_[identifier]) = vTypes;
get<1>(ASTNode::funcTable_[identifier]) = getArgFunc;
}
virtual ~ExternNode() {
if (this->retType_ != nullptr) {
delete this->retType_;
this->retType_ = nullptr;
}
if (this->tdeclsNode_ != nullptr) {
delete this->tdeclsNode_;
this->tdeclsNode_ = nullptr;
}
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left = std::string(depth*2, ' ');
ss << left << "name: extern" << '\n';
ss << left << "ret_type: " << this->retType_->GetName() << '\n';
ss << left << "globid: " << this->identifier_ << '\n';
if (this->children_.size()>0) {
this->children_[0]->PrintRecursive(ss, depth+1);
}
}
};
struct ExternsNode : public ASTNode {
ExternsNode(unsigned lineNumber,
ExternNode * externNode) : ASTNode(lineNumber) {
this->children_.push_back(externNode);
}
ExternsNode(unsigned lineNumber, ExternsNode * externsNode,
ExternNode * externNode): ASTNode(lineNumber) {
for (auto node : externsNode->children_) {
this->children_.push_back(node);
}
this->children_.push_back(externNode);
}
void
PrintSelf(stringstream& ss, unsigned depth) {
string left1 = std::string((depth-1)*2, ' ');
string left2 = std::string(depth*2, ' ');
string left3 = std::string((depth+1)*2, ' ');
ss << left1 << "externs:" << '\n';
ss << left2 << "name: externs" << '\n';
ss << left2 << "externs:" << '\n';
ss << left3 << "-" << '\n';
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
PrintSelf(ss, depth);
string left3 = std::string((depth+1)*2, ' ');
for (unsigned i=0; i<this->children_.size(); ++i) {
this->children_[i]->PrintRecursive(ss, depth+2);
if (i!=this->children_.size()-1)
ss << left3 << "-" << '\n';
}
}
};
struct UnaryOperationNode: public ASTNode {
UnaryOperationTypes operationType_;
UnaryOperationNode(unsigned lineNumber,
UnaryOperationTypes operationType,
ASTNode * expressionNode1) :
ASTNode(lineNumber), operationType_(operationType) {
if (operationType==Not) {
this->resultType_ = new BoolType();
} else {
this->resultType_ = expressionNode1->resultType_;
}
this->children_.push_back(expressionNode1);
}
void
PrintRecursive(stringstream& ss, unsigned depth) {
string left1 = std::string(depth*2, ' ');
ss << left1 << "name: uop" << '\n';
ss << left1 << "op: ";
switch (this->operationType_) {
case Not:
ss << "not" << '\n';
break;
case Minus:
ss << "minus" << '\n';
break;
#ifndef NO_DEBUG
case EmptyUnaryOperation:
assert(false);
break;
#endif
}
this->children_[0]->PrintRecursive(ss, depth+1);
}
llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
llvm::Value * ret = nullptr;
llvm::Value * R = this->children_[0]->GenerateCode(endBlock);
string error = "error: invalid unary operation in GenerateCode";
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
switch (this->operationType_) {
case Not:
if (this->resultType_->varType_==BooleanVarType) {
return GlobalBuilder.CreateNot(R, "not");
} else {
cout << error << endl;
exit(1);
}
break;
case Minus:
switch (this->resultType_->varType_) {
case IntVarType:
case FloatVarType:
return GlobalBuilder.CreateNeg(R, "negate");
case CintVarType:
{
vector<llvm::Value *> params { R };
return GlobalBuilder.CreateCall(
ASTNode::cintNegateFunction_, params, "cint_negate");
}
default:
cout << error << endl;
exit(1);
}
}
}
};
struct BinaryOperationNode: public ASTNode {
BinaryOperationTypes operationType_;
ValidType * castTo_ = nullptr;
ValidType * castFrom_ = nullptr;
BinaryOperationNode(unsigned lineNumber,
BinaryOperationTypes operationType,
ASTNode * expressionNode1,
ASTNode * expressionNode2) :
ASTNode(lineNumber), operationType_(operationType) {
this->children_.push_back(expressionNode1);
this->children_.push_back(expressionNode2);
SetResultType();
}
BinaryOperationNode(unsigned lineNumber,
BinaryOperationTypes operationType,
ValidType * validType,
ASTNode * expressionNode1) :
ASTNode(lineNumber) , operationType_(Cast),
castTo_(validType) {
this->children_.push_back(expressionNode1);
this->castFrom_ = expressionNode1->resultType_;
SetResultType();
}
virtual ~BinaryOperationNode() {
if (this->castTo_ != nullptr) {
delete this->castTo_;
this->castTo_ = nullptr;
}
}
void
SetResultType() {
string error = "error: line " +
to_string(this->lineNumber_) +
" invalid binary operation";
if (this->operationType_ == Cast) {
if (!ValidType::IsValidCast(
this->castTo_, this->castFrom_)) {
ASTNode::LogError(this->lineNumber_,
string("invalid binary operation."));
}
} else {
if (!ValidType::IsValidBinaryOp(
this->children_[0]->resultType_,
this->children_[1]->resultType_)) {
ASTNode::LogError(this->lineNumber_,
string("invalid binary operation."));
}
}
switch (this->operationType_) {
case Assign:
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
break;
case Cast:
// castTo_ should be valid by this point
this->resultType_ = this->castTo_;
break;
case Multiply:
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
break;
case Divide:
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
break;
case Add:
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
break;
case Subtract:
this->resultType_ = ValidType::GetUnderlyingType(
this->children_[0]->resultType_);
break;
case Equality:
this->resultType_ = new BoolType();
break;
case LessThan:
this->resultType_ = new BoolType();
break;
case GreaterThan:
this->resultType_ = new BoolType();
break;
case Land:
this->resultType_ = new BoolType();
break;
case Lor:
this->resultType_ = new BoolType();
break;
}
}
llvm::Value *
GenerateCode(llvm::BasicBlock * endBlock) {
llvm::Value * ret = nullptr;
llvm::Value * L = nullptr;
llvm::Value * R = nullptr;
string error = "error: invalid binary operation in GenerateCode";
switch (this->operationType_) {
case Assign:
{
R = this->children_[1]->GenerateCode(endBlock);
ExistingVarNode * existingNode = (ExistingVarNode *)this->children_[0];
llvm::AllocaInst * alloca = get<1>(ASTNode::varTable_[existingNode->identifier_]);
return GlobalBuilder.CreateStore(R, alloca);
}
// the break below will never run
break;
case Cast:
{
R = this->children_[0]->GenerateCode(endBlock);
llvm::Type * castTo = ValidType::ConvertVariableTypeToLLVMType(
this->resultType_->varType_);
switch (this->castFrom_->varType_) {
case FloatVarType: // float -> int / cint
return GlobalBuilder.CreateFPCast(R, castTo, "cast_float");
case IntVarType: // int -> float / cint
return GlobalBuilder.CreateIntCast(R, castTo, true, "cast_int");
case CintVarType: // cint -> float / int
return GlobalBuilder.CreateIntCast(R, castTo, true, "cast_cint");
default:
cout << error << endl;
exit(1);
break;
}
}
break;
case Multiply:
{
L = this->children_[0]->GenerateCode(endBlock);
R = this->children_[1]->GenerateCode(endBlock);
switch (this->resultType_->varType_) {
case FloatVarType:
return GlobalBuilder.CreateFMul(L, R, "mul_float");
case IntVarType:
return GlobalBuilder.CreateNSWMul(L, R, "mul_int");
case CintVarType:
{
vector<llvm::Value *> params { L, R };
return GlobalBuilder.CreateCall(
ASTNode::cintMultiplyFunction_, params, "cint_multiply");
}
default:
cout << error << endl;
exit(1);
break;
}
}
break;
case Divide:
{
L = this->children_[0]->GenerateCode(endBlock);
R = this->children_[1]->GenerateCode(endBlock);
switch (this->resultType_->varType_) {
case FloatVarType:
return GlobalBuilder.CreateFDiv(L, R, "div_float");
case IntVarType:
return GlobalBuilder.CreateSDiv(L, R, "div_int");
case CintVarType:
{
vector<llvm::Value *> params { L, R };
return GlobalBuilder.CreateCall(
ASTNode::cintDivideFunction_, params, "cint_divide");
}
default:
cout << error << endl;
exit(1);
break;
}