-
Notifications
You must be signed in to change notification settings - Fork 101
/
CGProcedure.cpp
456 lines (421 loc) · 13.6 KB
/
CGProcedure.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
#include "tinylang/CodeGen/CGProcedure.h"
#include "llvm/IR/CFG.h"
#include "llvm/Support/Casting.h"
using namespace tinylang;
void CGProcedure::writeLocalVariable(llvm::BasicBlock *BB,
Decl *Decl,
llvm::Value *Val) {
assert(BB && "Basic block is nullptr");
assert(
(llvm::isa<VariableDeclaration>(Decl) ||
llvm::isa<FormalParameterDeclaration>(Decl)) &&
"Declaration must be variable or formal parameter");
assert(Val && "Value is nullptr");
CurrentDef[BB].Defs[Decl] = Val;
}
llvm::Value *
CGProcedure::readLocalVariable(llvm::BasicBlock *BB,
Decl *Decl) {
assert(BB && "Basic block is nullptr");
assert(
(llvm::isa<VariableDeclaration>(Decl) ||
llvm::isa<FormalParameterDeclaration>(Decl)) &&
"Declaration must be variable or formal parameter");
auto Val = CurrentDef[BB].Defs.find(Decl);
if (Val != CurrentDef[BB].Defs.end())
return Val->second;
return readLocalVariableRecursive(BB, Decl);
}
llvm::Value *CGProcedure::readLocalVariableRecursive(
llvm::BasicBlock *BB, Decl *Decl) {
llvm::Value *Val = nullptr;
if (!CurrentDef[BB].Sealed) {
// Add incomplete phi for variable.
llvm::PHINode *Phi = addEmptyPhi(BB, Decl);
CurrentDef[BB].IncompletePhis[Phi] = Decl;
Val = Phi;
} else if (auto *PredBB = BB->getSinglePredecessor()) {
// Only one predecessor.
Val = readLocalVariable(PredBB, Decl);
} else {
// Create empty phi instruction to break potential
// cycles.
llvm::PHINode *Phi = addEmptyPhi(BB, Decl);
Val = Phi;
writeLocalVariable(BB, Decl, Val);
addPhiOperands(BB, Decl, Phi);
}
writeLocalVariable(BB, Decl, Val);
return Val;
}
llvm::PHINode *
CGProcedure::addEmptyPhi(llvm::BasicBlock *BB, Decl *Decl) {
return BB->empty()
? llvm::PHINode::Create(mapType(Decl), 0, "",
BB)
: llvm::PHINode::Create(mapType(Decl), 0, "",
&BB->front());
}
void CGProcedure::addPhiOperands(llvm::BasicBlock *BB,
Decl *Decl,
llvm::PHINode *Phi) {
for (auto I = llvm::pred_begin(BB),
E = llvm::pred_end(BB);
I != E; ++I) {
Phi->addIncoming(readLocalVariable(*I, Decl), *I);
}
optimizePhi(Phi);
}
void CGProcedure::optimizePhi(llvm::PHINode *Phi) {
llvm::Value *Same = nullptr;
for (llvm::Value *V : Phi->incoming_values()) {
if (V == Same || V == Phi)
continue;
if (Same && V != Same)
return;
Same = V;
}
if (Same == nullptr)
Same = llvm::UndefValue::get(Phi->getType());
// Collect phi instructions using this one.
llvm::SmallVector<llvm::PHINode *, 8> CandidatePhis;
for (llvm::Use &U : Phi->uses()) {
if (auto *P =
llvm::dyn_cast<llvm::PHINode>(U.getUser()))
if (P != Phi)
CandidatePhis.push_back(P);
}
Phi->replaceAllUsesWith(Same);
Phi->eraseFromParent();
for (auto *P : CandidatePhis)
optimizePhi(P);
}
void CGProcedure::sealBlock(llvm::BasicBlock *BB) {
assert(!CurrentDef[BB].Sealed &&
"Attempt to seal already sealed block");
for (auto PhiDecl : CurrentDef[BB].IncompletePhis) {
addPhiOperands(BB, PhiDecl.second, PhiDecl.first);
}
CurrentDef[BB].IncompletePhis.clear();
CurrentDef[BB].Sealed = true;
}
void CGProcedure::writeVariable(llvm::BasicBlock *BB,
Decl *D, llvm::Value *Val) {
if (auto *V = llvm::dyn_cast<VariableDeclaration>(D)) {
if (V->getEnclosingDecl() == Proc)
writeLocalVariable(BB, D, Val);
else if (V->getEnclosingDecl() ==
CGM.getModuleDeclaration()) {
Builder.CreateStore(Val, CGM.getGlobal(D));
} else
llvm::report_fatal_error(
"Nested procedures not yet supported");
} else if (auto *FP =
llvm::dyn_cast<FormalParameterDeclaration>(
D)) {
if (FP->isVar()) {
Builder.CreateStore(Val, FormalParams[FP]);
} else
writeLocalVariable(BB, D, Val);
} else
llvm::report_fatal_error("Unsupported declaration");
}
llvm::Value *CGProcedure::readVariable(llvm::BasicBlock *BB,
Decl *D) {
if (auto *V = llvm::dyn_cast<VariableDeclaration>(D)) {
if (V->getEnclosingDecl() == Proc)
return readLocalVariable(BB, D);
else if (V->getEnclosingDecl() ==
CGM.getModuleDeclaration()) {
return Builder.CreateLoad(mapType(D),
CGM.getGlobal(D));
} else
llvm::report_fatal_error(
"Nested procedures not yet supported");
} else if (auto *FP =
llvm::dyn_cast<FormalParameterDeclaration>(
D)) {
if (FP->isVar()) {
return Builder.CreateLoad(
mapType(FP)->getPointerElementType(),
FormalParams[FP]);
} else
return readLocalVariable(BB, D);
} else
llvm::report_fatal_error("Unsupported declaration");
}
llvm::Type *CGProcedure::mapType(Decl *Decl) {
if (auto *FP = llvm::dyn_cast<FormalParameterDeclaration>(
Decl)) {
llvm::Type *Ty = CGM.convertType(FP->getType());
if (FP->isVar())
Ty = Ty->getPointerTo();
return Ty;
}
if (auto *V = llvm::dyn_cast<VariableDeclaration>(Decl))
return CGM.convertType(V->getType());
return CGM.convertType(llvm::cast<TypeDeclaration>(Decl));
}
llvm::FunctionType *CGProcedure::createFunctionType(
ProcedureDeclaration *Proc) {
llvm::Type *ResultTy = CGM.VoidTy;
if (Proc->getRetType()) {
ResultTy = mapType(Proc->getRetType());
}
auto FormalParams = Proc->getFormalParams();
llvm::SmallVector<llvm::Type *, 8> ParamTypes;
for (auto FP : FormalParams) {
llvm::Type *Ty = mapType(FP);
ParamTypes.push_back(Ty);
}
return llvm::FunctionType::get(ResultTy, ParamTypes,
/* IsVarArgs */ false);
}
llvm::Function *
CGProcedure::createFunction(ProcedureDeclaration *Proc,
llvm::FunctionType *FTy) {
llvm::Function *Fn = llvm::Function::Create(
Fty, llvm::GlobalValue::ExternalLinkage,
CGM.mangleName(Proc), CGM.getModule());
// Give parameters a name.
size_t Idx = 0;
for (auto I = Fn->arg_begin(), E = Fn->arg_end(); I != E;
++I, ++Idx) {
llvm::Argument *Arg = I;
FormalParameterDeclaration *FP =
Proc->getFormalParams()[Idx];
if (FP->isVar()) {
llvm::AttrBuilder Attr;
llvm::TypeSize Sz =
CGM.getModule()->getDataLayout().getTypeStoreSize(
CGM.convertType(FP->getType()));
Attr.addDereferenceableAttr(Sz);
Attr.addAttribute(llvm::Attribute::NoCapture);
Arg->addAttrs(Attr);
}
Arg->setName(FP->getName());
}
return Fn;
}
llvm::Value *
CGProcedure::emitInfixExpr(InfixExpression *E) {
llvm::Value *Left = emitExpr(E->getLeft());
llvm::Value *Right = emitExpr(E->getRight());
llvm::Value *Result = nullptr;
switch (E->getOperatorInfo().getKind()) {
case tok::plus:
Result = Builder.CreateNSWAdd(Left, Right);
break;
case tok::minus:
Result = Builder.CreateNSWSub(Left, Right);
break;
case tok::star:
Result = Builder.CreateNSWMul(Left, Right);
break;
case tok::kw_DIV:
Result = Builder.CreateSDiv(Left, Right);
break;
case tok::kw_MOD:
Result = Builder.CreateSRem(Left, Right);
break;
case tok::equal:
Result = Builder.CreateICmpEQ(Left, Right);
break;
case tok::hash:
Result = Builder.CreateICmpNE(Left, Right);
break;
case tok::less:
Result = Builder.CreateICmpSLT(Left, Right);
break;
case tok::lessequal:
Result = Builder.CreateICmpSLE(Left, Right);
break;
case tok::greater:
Result = Builder.CreateICmpSGT(Left, Right);
break;
case tok::greaterequal:
Result = Builder.CreateICmpSGE(Left, Right);
break;
case tok::kw_AND:
Result = Builder.CreateAnd(Left, Right);
break;
case tok::kw_OR:
Result = Builder.CreateOr(Left, Right);
break;
case tok::slash:
// Divide by real numbers not supported.
LLVM_FALLTHROUGH;
default:
llvm_unreachable("Wrong operator");
}
return Result;
}
llvm::Value *
CGProcedure::emitPrefixExpr(PrefixExpression *E) {
llvm::Value *Result = emitExpr(E->getExpr());
switch (E->getOperatorInfo().getKind()) {
case tok::plus:
// Identity - nothing to do.
break;
case tok::minus:
Result = Builder.CreateNeg(Result);
break;
case tok::kw_NOT:
Result = Builder.CreateNot(Result);
break;
default:
llvm_unreachable("Wrong operator");
}
return Result;
}
llvm::Value *CGProcedure::emitExpr(Expr *E) {
if (auto *Infix = llvm::dyn_cast<InfixExpression>(E)) {
return emitInfixExpr(Infix);
} else if (auto *Prefix =
llvm::dyn_cast<PrefixExpression>(E)) {
return emitPrefixExpr(Prefix);
} else if (auto *Var =
llvm::dyn_cast<VariableAccess>(E)) {
auto *Decl = Var->getDecl();
// With more languages features in place, here you need
// to add array and record support.
return readVariable(Curr, Decl);
} else if (auto *Const =
llvm::dyn_cast<ConstantAccess>(E)) {
return emitExpr(Const->getDecl()->getExpr());
} else if (auto *IntLit =
llvm::dyn_cast<IntegerLiteral>(E)) {
return llvm::ConstantInt::get(CGM.Int64Ty,
IntLit->getValue());
} else if (auto *BoolLit =
llvm::dyn_cast<BooleanLiteral>(E)) {
return llvm::ConstantInt::get(CGM.Int1Ty,
BoolLit->getValue());
}
llvm::report_fatal_error("Unsupported expression");
}
void CGProcedure::emitStmt(AssignmentStatement *Stmt) {
auto *Val = emitExpr(Stmt->getExpr());
writeVariable(Curr, Stmt->getVar(), Val);
}
void CGProcedure::emitStmt(ProcedureCallStatement *Stmt) {
llvm::report_fatal_error("not implemented");
}
void CGProcedure::emitStmt(IfStatement *Stmt) {
bool HasElse = Stmt->getElseStmts().size() > 0;
// Create the required basic blocks.
llvm::BasicBlock *IfBB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "if.body", Fn);
llvm::BasicBlock *ElseBB =
HasElse ? llvm::BasicBlock::Create(CGM.getLLVMCtx(),
"else.body", Fn)
: nullptr;
llvm::BasicBlock *AfterIfBB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "after.if", Fn);
llvm::Value *Cond = emitExpr(Stmt->getCond());
Builder.CreateCondBr(Cond, IfBB,
HasElse ? ElseBB : AfterIfBB);
sealBlock(Curr);
setCurr(IfBB);
emit(Stmt->getIfStmts());
if (!Curr->getTerminator()) {
Builder.CreateBr(AfterIfBB);
}
sealBlock(Curr);
if (HasElse) {
setCurr(ElseBB);
emit(Stmt->getElseStmts());
if (!Curr->getTerminator()) {
Builder.CreateBr(AfterIfBB);
}
sealBlock(Curr);
}
setCurr(AfterIfBB);
}
void CGProcedure::emitStmt(WhileStatement *Stmt) {
// The basic block for the condition.
llvm::BasicBlock *WhileCondBB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "while.cond", Fn);
// The basic block for the while body.
llvm::BasicBlock *WhileBodyBB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "while.body", Fn);
// The basic block after the while statement.
llvm::BasicBlock *AfterWhileBB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "after.while", Fn);
Builder.CreateBr(WhileCondBB);
sealBlock(Curr);
setCurr(WhileCondBB);
llvm::Value *Cond = emitExpr(Stmt->getCond());
Builder.CreateCondBr(Cond, WhileBodyBB, AfterWhileBB);
setCurr(WhileBodyBB);
emit(Stmt->getWhileStmts());
Builder.CreateBr(WhileCondBB);
sealBlock(Curr);
sealBlock(WhileCondBB);
setCurr(AfterWhileBB);
}
void CGProcedure::emitStmt(ReturnStatement *Stmt) {
if (Stmt->getRetVal()) {
llvm::Value *RetVal = emitExpr(Stmt->getRetVal());
Builder.CreateRet(RetVal);
} else {
Builder.CreateRetVoid();
}
}
void CGProcedure::emit(const StmtList &Stmts) {
for (auto *S : Stmts) {
if (auto *Stmt = llvm::dyn_cast<AssignmentStatement>(S))
emitStmt(Stmt);
else if (auto *Stmt =
llvm::dyn_cast<ProcedureCallStatement>(S))
emitStmt(Stmt);
else if (auto *Stmt = llvm::dyn_cast<IfStatement>(S))
emitStmt(Stmt);
else if (auto *Stmt = llvm::dyn_cast<WhileStatement>(S))
emitStmt(Stmt);
else if (auto *Stmt =
llvm::dyn_cast<ReturnStatement>(S))
emitStmt(Stmt);
else
llvm_unreachable("Unknown statement");
}
}
void CGProcedure::run(ProcedureDeclaration *Proc) {
this->Proc = Proc;
Fty = createFunctionType(Proc);
Fn = createFunction(Proc, Fty);
llvm::BasicBlock *BB = llvm::BasicBlock::Create(
CGM.getLLVMCtx(), "entry", Fn);
setCurr(BB);
size_t Idx = 0;
auto &Defs = CurrentDef[BB];
for (auto I = Fn->arg_begin(), E = Fn->arg_end(); I != E;
++I, ++Idx) {
llvm::Argument *Arg = I;
FormalParameterDeclaration *FP =
Proc->getFormalParams()[Idx];
// Create mapping FormalParameter -> llvm::Argument for
// VAR parameters.
FormalParams[FP] = Arg;
Defs.Defs.insert(
std::pair<Decl *, llvm::Value *>(FP, Arg));
}
for (auto *D : Proc->getDecls()) {
if (auto *Var =
llvm::dyn_cast<VariableDeclaration>(D)) {
llvm::Type *Ty = mapType(Var);
if (Ty->isAggregateType()) {
llvm::Value *Val = Builder.CreateAlloca(Ty);
Defs.Defs.insert(
std::pair<Decl *, llvm::Value *>(Var, Val));
}
}
}
auto Block = Proc->getStmts();
emit(Proc->getStmts());
if (!Curr->getTerminator()) {
Builder.CreateRetVoid();
}
sealBlock(Curr);
}
void CGProcedure::run() {}