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
|
#include <utility>
#include "LLVMVisitor.h"
LLVMVisitor::LLVMVisitor(const char* fileName) : outFile(std::ofstream(fileName)), reg() {
if (!outFile.is_open())
throw std::runtime_error("Couldn't open file for writing!");
outFile << "define i32 @main() {\n";
}
void LLVMVisitor::finalizeFile() {
outFile << "ret i32 0\n}\n";
}
std::string LLVMVisitor::Visit(const Integer& vint) {
return std::to_string(vint.get_value());
}
std::string LLVMVisitor::Visit(const Float& vfloat) {
return std::to_string(vfloat.get_value());
}
void f_add(std::string reg, std::string first, std::string second, std::ofstream& of) {
of << reg << " = add i32 " << first << ", " << second << "\n";
}
void f_sub(std::string reg, std::string first, std::string second, std::ofstream& of) {
of << reg << " = sub i32 " << first << ", " << second << "\n";
}
std::string LLVMVisitor::rightAssoc(BiFout f, const BuiltInFunction& bfun, unsigned i) {
std::string leftArg = bfun.get_args()[i]->Visit(*this);
std::string rightArg;
if (bfun.get_args().size() - 2 == i)
rightArg = bfun.get_args()[i+1]->Visit(*this);
else
rightArg = rightAssoc(f, bfun, i+1);
std::string valRegister = *(reg++);
f(valRegister, leftArg, rightArg, outFile);
return valRegister;
}
std::string LLVMVisitor::Visit(const BuiltInFunction& bfun) {
if (bfun.get_name() == "+") return rightAssoc(f_add, bfun);
if (bfun.get_name() == "-") return rightAssoc(f_sub, bfun);
return "";
}
|