Repository navigation
Expand file tree
/
Copy pathIRGen.cpp
More file actions
443 lines (342 loc) · 13.4 KB
/
Copy pathIRGen.cpp
File metadata and controls
443 lines (342 loc) · 13.4 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
//
// Created by Richard Gong on 2019-08-02.
//
#include "IRGen.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/STLExtras.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/Verifier.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/InstCombine/InstCombine.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Scalar/GVN.h"
using namespace antlrcpp;
using namespace play;
using namespace antlr4;
using namespace llvm;
using namespace llvm::orc;
//static LLVMContext TheContext;
//static IRBuilder<> Builder(TheContext);
//static std::unique_ptr<Module> TheModule;
//static std::map<std::string, Value *> NamedValues;
//static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
//static std::unique_ptr<PlayScriptJIT> TheJIT;
//static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
void IRGen::InitializeModuleAndPassManager() {
TheJIT = llvm::make_unique<PlayScriptJIT>();
// Open a new module.
TheModule = llvm::make_unique<Module>("playscript", TheContext);
DataLayout dl = TheJIT->getTargetMachine().createDataLayout();
TheModule->setDataLayout(dl);
// TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
// Create a new pass manager attached to it.
TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
// Do simple "peephole" optimizations and bit-twiddling optzns.
TheFPM->add(createInstructionCombiningPass());
// Reassociate expressions.
TheFPM->add(createReassociatePass());
// Eliminate Common SubExpressions.
TheFPM->add(createGVNPass());
// Simplify the control flow graph (deleting unreachable blocks, etc).
TheFPM->add(createCFGSimplificationPass());
TheFPM->doInitialization();
}
void IRGen::ExecuteJIT(){
TheJIT->addModule(std::move(TheModule));
// Search the JIT for the __anon_expr symbol.
auto ExprSymbol = TheJIT->findSymbol("__prog");
assert(ExprSymbol && "__prog not found");
// Get the symbol's address and cast it to the right type (takes no
// arguments, returns a double) so we can call it as a native function.
double (*FP)() = (double (*)())(intptr_t)cantFail(ExprSymbol.getAddress());
fprintf(stdout, "Evaluated to %f\n", FP());
}
void IRGen::PrintIR() {
TheModule->print(outs(), nullptr);
std::cout << std::endl;
}
Value *IRGen::LogErrorV(const char *Str) {
fprintf(stderr, "Error: %s\n", Str);
return nullptr;
}
antlrcpp::Any IRGen::visitProg(PlayScriptParser::ProgContext *ctx) {
//对于最外层的的程序,建立一个缺省的函数
std::vector<Type *> Doubles(0, Type::getDoubleTy(TheContext));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
Function *TheFunction = Function::Create(FT, Function::ExternalLinkage, "__prog", TheModule.get());
// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(TheContext, "entry", TheFunction);
Builder.SetInsertPoint(BB);
// Record the function arguments in the NamedValues map.
NamedValues.clear();
Value *RetVal = nullptr;
try {
RetVal = visitBlockStatements(ctx->blockStatements());
} catch (std::bad_cast) {
fprintf(stdout, "bad_cast in visitPorg.\n");
}
// Finish off the function.
Builder.CreateRet(RetVal);
// Validate the generated code, checking for consistency.
verifyFunction(*TheFunction);
// fprintf(stdout, "prog:\n");
//
// TheFunction->print(outs());
// fprintf(stdout, "\n");
return TheFunction;
}
antlrcpp::Any IRGen::visitBlock(PlayScriptParser::BlockContext *ctx) {
Value *result = visitBlockStatements(ctx->blockStatements());
return result;
}
antlrcpp::Any IRGen::visitBlockStatements(PlayScriptParser::BlockStatementsContext *ctx) {
Value *result = nullptr;
if (ctx->blockStatement().size() > 0) {
for (unsigned i = 0; i < ctx->blockStatement().size(); i++) {
result = visitBlockStatement(ctx->blockStatement(i));
}
}
return result;
}
antlrcpp::Any IRGen::visitBlockStatement(PlayScriptParser::BlockStatementContext *ctx) {
Value *result = nullptr;
if (ctx->statement()) {
result = visitStatement(ctx->statement());
} else if (ctx->functionDeclaration()) {
result = visitFunctionDeclaration(ctx->functionDeclaration());
} else if (ctx->variableDeclarators()){
result = visitVariableDeclarators(ctx->variableDeclarators());
}
return result;
}
antlrcpp::Any IRGen::visitStatement(PlayScriptParser::StatementContext *ctx) {
Value *result = nullptr;
if (ctx->statementExpression) {
result = visitExpression(ctx->statementExpression);
} else if (ctx->RETURN()) {
result = visitExpression(ctx->expression());
}
return result;
}
antlrcpp::Any IRGen::visitExpression(PlayScriptParser::ExpressionContext *ctx) {
Value *result = nullptr;
//二元表达式
try {
if (ctx->bop && ctx->expression().size() >= 2) {
Value *L = visitExpression(ctx->expression(0));
Value *R = visitExpression(ctx->expression(1));
//std::cout<<"L:"<< L <<std::endl;
//std::cout<<"R:"<< R <<std::endl;
// if (ctx->bop->getType() == PlayScriptParser::ADD) {
// result = Builder.CreateAdd(L, R, "addtmp");
// } else if (ctx->bop->getType() == PlayScriptParser::SUB) {
// result = Builder.CreateSub(L, R, "subtmp");
// } else if (ctx->bop->getType() == PlayScriptParser::MUL) {
// result = Builder.CreateMul(L, R, "multmp");
// } else if (ctx->bop->getType() == PlayScriptParser::DIV) {
// result = Builder.CreateFDiv(L, R, "divtmp");
// }
if (ctx->bop->getType() == PlayScriptParser::ADD) {
result = Builder.CreateFAdd(L, R, "addtmp");
} else if (ctx->bop->getType() == PlayScriptParser::SUB) {
result = Builder.CreateFSub(L, R, "subtmp");
} else if (ctx->bop->getType() == PlayScriptParser::MUL) {
result = Builder.CreateFMul(L, R, "multmp");
} else if (ctx->bop->getType() == PlayScriptParser::DIV) {
result = Builder.CreateFDiv(L, R, "divtmp");
}
//std::cout<<"result:"<< result <<std::endl;
// result->print(outs());
// std::cout << std::endl;
} else if (ctx->primary()) {
result = visitPrimary(ctx->primary());
} else if (ctx->functionCall()) {
result = visitFunctionCall(ctx->functionCall());
}
}
catch (std::bad_cast) {
std::cout << "bad_cast in visitExpression" << std::endl;
}
return result;
}
antlrcpp::Any IRGen::visitPrimary(PlayScriptParser::PrimaryContext *ctx) {
Value *result = nullptr;
if (ctx->literal()) {
result = visitLiteral(ctx->literal());
} else if (ctx->IDENTIFIER()) {
// Look this variable up in the function.
std::string name = ctx->IDENTIFIER()->getText();
result = NamedValues[name];
if (!result)
result = LogErrorV("Unknown variable name");
}else if (ctx->expression()){
result = visitExpression(ctx->expression());
}
return result;
}
antlrcpp::Any IRGen::visitLiteral(PlayScriptParser::LiteralContext *ctx) {
if (ctx->integerLiteral()) {
return visitIntegerLiteral(ctx->integerLiteral());
} else if (ctx->floatLiteral()) {
return visitFloatLiteral(ctx->floatLiteral());
}
return nullptr;
}
antlrcpp::Any IRGen::visitIntegerLiteral(PlayScriptParser::IntegerLiteralContext *ctx) {
//int literal = std::stoi(ctx->getText());
try {
Value *result = ConstantInt::get(TheContext, APSInt(ctx->getText()));
//std::cout<<"result in visitIntegerLiteral:"<< result <<std::endl;
result->print(outs());
std::cout << std::endl;
return result;
}
catch (std::bad_cast) {
std::cout << "bad_cast in visitIntegerLiteral" << std::endl;
}
return nullptr;
}
antlrcpp::Any IRGen::visitFloatLiteral(PlayScriptParser::FloatLiteralContext *ctx) {
try {
double literal = std::stod(ctx->getText());
Value *result = ConstantFP::get(TheContext, APFloat(literal));
return result;
}
catch (std::bad_cast) {
std::cout << "bad_cast in visitFloatLiteral" << std::endl;
}
return nullptr;
}
antlrcpp::Any IRGen::visitFunctionDeclaration(PlayScriptParser::FunctionDeclarationContext *ctx) {
Value *result = nullptr;
int numParams = 0;
PlayScriptParser::FormalParameterListContext *list = ctx->formalParameters()->formalParameterList();
if (list) {
numParams = list->formalParameter().size();
}
std::vector<Type *> Doubles(numParams, Type::getDoubleTy(TheContext));
FunctionType *FT = FunctionType::get(Type::getDoubleTy(TheContext), Doubles, false);
std::string name = ctx->IDENTIFIER()->getText();
Function *F = Function::Create(FT, Function::ExternalLinkage, name, TheModule.get());
// Set names for all arguments.
unsigned Idx = 0;
for (auto &Arg : F->args())
Arg.setName(list->formalParameter(Idx++)->variableDeclaratorId()->IDENTIFIER()->getText());
// Create a new basic block to start insertion into.
BasicBlock *BB = BasicBlock::Create(TheContext, "entry", F);
BasicBlock *oldBB = Builder.GetInsertBlock();
Builder.SetInsertPoint(BB);
// Record the function arguments in the NamedValues map.
std::map<std::string, Value*> oldNamedValues(NamedValues);
NamedValues.clear();
for (auto &Arg : F->args())
NamedValues[Arg.getName()] = &Arg;
// for (auto iter = NamedValues.begin(); iter != NamedValues.end(); iter++) {
// std::cout << iter->first << " : " << iter->second << std::endl;
// }
if (Value *RetVal = visitFunctionBody(ctx->functionBody())) {
// Finish off the function.
Builder.CreateRet(RetVal);
// Validate the generated code, checking for consistency.
verifyFunction(*F);
// Run the optimizer on the function.
TheFPM->run(*F);
result = F;
} else {
// Error reading body, remove function.
F->eraseFromParent();
}
// fprintf(stdout, "Function definition:");
// F->print(outs());
// fprintf(stdout, "\n");
//恢复原来的代码插入点
Builder.SetInsertPoint(oldBB);
NamedValues = oldNamedValues;
return result;
}
antlrcpp::Any IRGen::visitFunctionBody(PlayScriptParser::FunctionBodyContext *ctx) {
Value *result = nullptr;
if (ctx->block()) {
result = visitBlock(ctx->block());
}
return result;
}
antlrcpp::Any IRGen::visitFormalParameters(PlayScriptParser::FormalParametersContext *ctx) {
Value *result = nullptr;
return result;
}
antlrcpp::Any IRGen::visitFormalParameterList(PlayScriptParser::FormalParameterListContext *ctx) {
Value *result = nullptr;
return result;
}
antlrcpp::Any IRGen::visitFormalParameter(PlayScriptParser::FormalParameterContext *ctx) {
Value *result = nullptr;
return result;
}
antlrcpp::Any IRGen::visitFunctionCall(PlayScriptParser::FunctionCallContext *ctx) {
Value *result = nullptr;
// Look up the name in the global module table.
Function *CalleeF = TheModule->getFunction(ctx->IDENTIFIER()->getText());
if (!CalleeF)
return LogErrorV("Unknown function referenced");
// If argument mismatch error.
int numArgs = 0;
if (ctx->expressionList()) {
numArgs = ctx->expressionList()->expression().size();
}
//TODO 检查参数类型
if (CalleeF->arg_size() != numArgs)
return LogErrorV("Incorrect # arguments passed");
std::vector<Value *> ArgsV;
for (unsigned i = 0; i < numArgs; i++) {
Value *argValue = visitExpression(ctx->expressionList()->expression(i));
if (!argValue) {
return nullptr;
}
ArgsV.push_back(argValue);
}
result = Builder.CreateCall(CalleeF, ArgsV, "calltmp");
return result;
}
antlrcpp::Any IRGen::visitVariableDeclarators(PlayScriptParser::VariableDeclaratorsContext *ctx) {
Value *result = nullptr;
for (unsigned i = 0; i < ctx->variableDeclarator().size(); i++){
result = visitVariableDeclarator(ctx->variableDeclarator(i));
}
return result;
}
antlrcpp::Any IRGen::visitVariableDeclarator(PlayScriptParser::VariableDeclaratorContext *ctx) {
Value *result = nullptr;
std::string name = ctx->variableDeclaratorId()->getText();
if (ctx->variableInitializer()){
result = visitVariableInitializer(ctx->variableInitializer());
}
//缺省初始化成0.0
if (!result){
result = ConstantFP::get(TheContext, APFloat(0.0));
}
//缓存变量的SSA
NamedValues[name]=result;
return result;
}
antlrcpp::Any IRGen::visitVariableDeclaratorId(PlayScriptParser::VariableDeclaratorIdContext *ctx) {
Value *result = nullptr;
return result;
}
antlrcpp::Any IRGen::visitVariableInitializer(PlayScriptParser::VariableInitializerContext *ctx) {
Value *result = nullptr;
if (ctx->expression()){
result = visitExpression(ctx->expression());
}
return result;
}