llvm.org GIT mirror llvm / 6efccd0
Fix KS tutorial build failure. make all doesn't build the examples and it was uniquified since last build. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@223675 91177308-0d34-0410-b5e6-96231b3b80d8 Eric Christopher 4 years ago
5 changed file(s) with 1074 addition(s) and 790 deletion(s). Raw diff Collapse all Expand all
2727 tok_eof = -1,
2828
2929 // commands
30 tok_def = -2, tok_extern = -3,
30 tok_def = -2,
31 tok_extern = -3,
3132
3233 // primary
33 tok_identifier = -4, tok_number = -5
34 };
35
36 static std::string IdentifierStr; // Filled in if tok_identifier
37 static double NumVal; // Filled in if tok_number
34 tok_identifier = -4,
35 tok_number = -5
36 };
37
38 static std::string IdentifierStr; // Filled in if tok_identifier
39 static double NumVal; // Filled in if tok_number
3840
3941 /// gettok - Return the next token from standard input.
4042 static int gettok() {
4951 while (isalnum((LastChar = getchar())))
5052 IdentifierStr += LastChar;
5153
52 if (IdentifierStr == "def") return tok_def;
53 if (IdentifierStr == "extern") return tok_extern;
54 if (IdentifierStr == "def")
55 return tok_def;
56 if (IdentifierStr == "extern")
57 return tok_extern;
5458 return tok_identifier;
5559 }
5660
57 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
61 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
5862 std::string NumStr;
5963 do {
6064 NumStr += LastChar;
6771
6872 if (LastChar == '#') {
6973 // Comment until end of line.
70 do LastChar = getchar();
74 do
75 LastChar = getchar();
7176 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
72
77
7378 if (LastChar != EOF)
7479 return gettok();
7580 }
76
81
7782 // Check for end of file. Don't eat the EOF.
7883 if (LastChar == EOF)
7984 return tok_eof;
98103 /// NumberExprAST - Expression class for numeric literals like "1.0".
99104 class NumberExprAST : public ExprAST {
100105 double Val;
106
101107 public:
102108 NumberExprAST(double val) : Val(val) {}
103109 virtual Value *Codegen();
106112 /// VariableExprAST - Expression class for referencing a variable, like "a".
107113 class VariableExprAST : public ExprAST {
108114 std::string Name;
115
109116 public:
110117 VariableExprAST(const std::string &name) : Name(name) {}
111118 virtual Value *Codegen();
115122 class BinaryExprAST : public ExprAST {
116123 char Op;
117124 ExprAST *LHS, *RHS;
125
118126 public:
119 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
120 : Op(op), LHS(lhs), RHS(rhs) {}
127 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
128 : Op(op), LHS(lhs), RHS(rhs) {}
121129 virtual Value *Codegen();
122130 };
123131
124132 /// CallExprAST - Expression class for function calls.
125133 class CallExprAST : public ExprAST {
126134 std::string Callee;
127 std::vector*> Args;
135 std::vector *> Args;
136
128137 public:
129 CallExprAST(const std::string &callee, std::vector &args)
130 : Callee(callee), Args(args) {}
138 CallExprAST(const std::string &callee, std::vector &args)
139 : Callee(callee), Args(args) {}
131140 virtual Value *Codegen();
132141 };
133142
137146 class PrototypeAST {
138147 std::string Name;
139148 std::vector Args;
149
140150 public:
141151 PrototypeAST(const std::string &name, const std::vector &args)
142 : Name(name), Args(args) {}
143
152 : Name(name), Args(args) {}
153
144154 Function *Codegen();
145155 };
146156
148158 class FunctionAST {
149159 PrototypeAST *Proto;
150160 ExprAST *Body;
161
151162 public:
152 FunctionAST(PrototypeAST *proto, ExprAST *body)
153 : Proto(proto), Body(body) {}
154
163 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
164
155165 Function *Codegen();
156166 };
157167 } // end anonymous namespace
164174 /// token the parser is looking at. getNextToken reads another token from the
165175 /// lexer and updates CurTok with its results.
166176 static int CurTok;
167 static int getNextToken() {
168 return CurTok = gettok();
169 }
177 static int getNextToken() { return CurTok = gettok(); }
170178
171179 /// BinopPrecedence - This holds the precedence for each binary operator that is
172180 /// defined.
176184 static int GetTokPrecedence() {
177185 if (!isascii(CurTok))
178186 return -1;
179
187
180188 // Make sure it's a declared binop.
181189 int TokPrec = BinopPrecedence[CurTok];
182 if (TokPrec <= 0) return -1;
190 if (TokPrec <= 0)
191 return -1;
183192 return TokPrec;
184193 }
185194
186195 /// Error* - These are little helper functions for error handling.
187 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
188 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
189 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
196 ExprAST *Error(const char *Str) {
197 fprintf(stderr, "Error: %s\n", Str);
198 return 0;
199 }
200 PrototypeAST *ErrorP(const char *Str) {
201 Error(Str);
202 return 0;
203 }
204 FunctionAST *ErrorF(const char *Str) {
205 Error(Str);
206 return 0;
207 }
190208
191209 static ExprAST *ParseExpression();
192210
195213 /// ::= identifier '(' expression* ')'
196214 static ExprAST *ParseIdentifierExpr() {
197215 std::string IdName = IdentifierStr;
198
199 getNextToken(); // eat identifier.
200
216
217 getNextToken(); // eat identifier.
218
201219 if (CurTok != '(') // Simple variable ref.
202220 return new VariableExprAST(IdName);
203
221
204222 // Call.
205 getNextToken(); // eat (
206 std::vector Args;
223 getNextToken(); // eat (
224 std::vector Args;
207225 if (CurTok != ')') {
208226 while (1) {
209227 ExprAST *Arg = ParseExpression();
210 if (!Arg) return 0;
228 if (!Arg)
229 return 0;
211230 Args.push_back(Arg);
212231
213 if (CurTok == ')') break;
232 if (CurTok == ')')
233 break;
214234
215235 if (CurTok != ',')
216236 return Error("Expected ')' or ',' in argument list");
220240
221241 // Eat the ')'.
222242 getNextToken();
223
243
224244 return new CallExprAST(IdName, Args);
225245 }
226246
233253
234254 /// parenexpr ::= '(' expression ')'
235255 static ExprAST *ParseParenExpr() {
236 getNextToken(); // eat (.
256 getNextToken(); // eat (.
237257 ExprAST *V = ParseExpression();
238 if (!V) return 0;
239
258 if (!V)
259 return 0;
260
240261 if (CurTok != ')')
241262 return Error("expected ')'");
242 getNextToken(); // eat ).
263 getNextToken(); // eat ).
243264 return V;
244265 }
245266
249270 /// ::= parenexpr
250271 static ExprAST *ParsePrimary() {
251272 switch (CurTok) {
252 default: return Error("unknown token when expecting an expression");
253 case tok_identifier: return ParseIdentifierExpr();
254 case tok_number: return ParseNumberExpr();
255 case '(': return ParseParenExpr();
273 default:
274 return Error("unknown token when expecting an expression");
275 case tok_identifier:
276 return ParseIdentifierExpr();
277 case tok_number:
278 return ParseNumberExpr();
279 case '(':
280 return ParseParenExpr();
256281 }
257282 }
258283
262287 // If this is a binop, find its precedence.
263288 while (1) {
264289 int TokPrec = GetTokPrecedence();
265
290
266291 // If this is a binop that binds at least as tightly as the current binop,
267292 // consume it, otherwise we are done.
268293 if (TokPrec < ExprPrec)
269294 return LHS;
270
295
271296 // Okay, we know this is a binop.
272297 int BinOp = CurTok;
273 getNextToken(); // eat binop
274
298 getNextToken(); // eat binop
299
275300 // Parse the primary expression after the binary operator.
276301 ExprAST *RHS = ParsePrimary();
277 if (!RHS) return 0;
278
302 if (!RHS)
303 return 0;
304
279305 // If BinOp binds less tightly with RHS than the operator after RHS, let
280306 // the pending operator take RHS as its LHS.
281307 int NextPrec = GetTokPrecedence();
282308 if (TokPrec < NextPrec) {
283 RHS = ParseBinOpRHS(TokPrec+1, RHS);
284 if (RHS == 0) return 0;
285 }
286
309 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
310 if (RHS == 0)
311 return 0;
312 }
313
287314 // Merge LHS/RHS.
288315 LHS = new BinaryExprAST(BinOp, LHS, RHS);
289316 }
294321 ///
295322 static ExprAST *ParseExpression() {
296323 ExprAST *LHS = ParsePrimary();
297 if (!LHS) return 0;
298
324 if (!LHS)
325 return 0;
326
299327 return ParseBinOpRHS(0, LHS);
300328 }
301329
307335
308336 std::string FnName = IdentifierStr;
309337 getNextToken();
310
338
311339 if (CurTok != '(')
312340 return ErrorP("Expected '(' in prototype");
313
341
314342 std::vector ArgNames;
315343 while (getNextToken() == tok_identifier)
316344 ArgNames.push_back(IdentifierStr);
317345 if (CurTok != ')')
318346 return ErrorP("Expected ')' in prototype");
319
347
320348 // success.
321 getNextToken(); // eat ')'.
322
349 getNextToken(); // eat ')'.
350
323351 return new PrototypeAST(FnName, ArgNames);
324352 }
325353
326354 /// definition ::= 'def' prototype expression
327355 static FunctionAST *ParseDefinition() {
328 getNextToken(); // eat def.
356 getNextToken(); // eat def.
329357 PrototypeAST *Proto = ParsePrototype();
330 if (Proto == 0) return 0;
358 if (Proto == 0)
359 return 0;
331360
332361 if (ExprAST *E = ParseExpression())
333362 return new FunctionAST(Proto, E);
346375
347376 /// external ::= 'extern' prototype
348377 static PrototypeAST *ParseExtern() {
349 getNextToken(); // eat extern.
378 getNextToken(); // eat extern.
350379 return ParsePrototype();
351380 }
352381
356385
357386 static Module *TheModule;
358387 static IRBuilder<> Builder(getGlobalContext());
359 static std::map*> NamedValues;
388 static std::map *> NamedValues;
360389 static FunctionPassManager *TheFPM;
361390
362 Value *ErrorV(const char *Str) { Error(Str); return 0; }
391 Value *ErrorV(const char *Str) {
392 Error(Str);
393 return 0;
394 }
363395
364396 Value *NumberExprAST::Codegen() {
365397 return ConstantFP::get(getGlobalContext(), APFloat(Val));
374406 Value *BinaryExprAST::Codegen() {
375407 Value *L = LHS->Codegen();
376408 Value *R = RHS->Codegen();
377 if (L == 0 || R == 0) return 0;
378
409 if (L == 0 || R == 0)
410 return 0;
411
379412 switch (Op) {
380 case '+': return Builder.CreateFAdd(L, R, "addtmp");
381 case '-': return Builder.CreateFSub(L, R, "subtmp");
382 case '*': return Builder.CreateFMul(L, R, "multmp");
413 case '+':
414 return Builder.CreateFAdd(L, R, "addtmp");
415 case '-':
416 return Builder.CreateFSub(L, R, "subtmp");
417 case '*':
418 return Builder.CreateFMul(L, R, "multmp");
383419 case '<':
384420 L = Builder.CreateFCmpULT(L, R, "cmptmp");
385421 // Convert bool 0/1 to double 0.0 or 1.0
386422 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
387423 "booltmp");
388 default: return ErrorV("invalid binary operator");
424 default:
425 return ErrorV("invalid binary operator");
389426 }
390427 }
391428
394431 Function *CalleeF = TheModule->getFunction(Callee);
395432 if (CalleeF == 0)
396433 return ErrorV("Unknown function referenced");
397
434
398435 // If argument mismatch error.
399436 if (CalleeF->arg_size() != Args.size())
400437 return ErrorV("Incorrect # arguments passed");
401438
402 std::vector*> ArgsV;
439 std::vector *> ArgsV;
403440 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
404441 ArgsV.push_back(Args[i]->Codegen());
405 if (ArgsV.back() == 0) return 0;
406 }
407
442 if (ArgsV.back() == 0)
443 return 0;
444 }
445
408446 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
409447 }
410448
411449 Function *PrototypeAST::Codegen() {
412450 // Make the function type: double(double,double) etc.
413 std::vector Doubles(Args.size(),
414 Type::getDoubleTy(getGlobalContext()));
415 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
416 Doubles, false);
417
418 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
419
451 std::vector Doubles(Args.size(),
452 Type::getDoubleTy(getGlobalContext()));
453 FunctionType *FT =
454 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
455
456 Function *F =
457 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
458
420459 // If F conflicted, there was already something named 'Name'. If it has a
421460 // body, don't allow redefinition or reextern.
422461 if (F->getName() != Name) {
423462 // Delete the one we just made and get the existing one.
424463 F->eraseFromParent();
425464 F = TheModule->getFunction(Name);
426
465
427466 // If F already has a body, reject this.
428467 if (!F->empty()) {
429468 ErrorF("redefinition of function");
430469 return 0;
431470 }
432
471
433472 // If F took a different number of args, reject.
434473 if (F->arg_size() != Args.size()) {
435474 ErrorF("redefinition of function with different # args");
436475 return 0;
437476 }
438477 }
439
478
440479 // Set names for all arguments.
441480 unsigned Idx = 0;
442481 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
443482 ++AI, ++Idx) {
444483 AI->setName(Args[Idx]);
445
484
446485 // Add arguments to variable symbol table.
447486 NamedValues[Args[Idx]] = AI;
448487 }
449
488
450489 return F;
451490 }
452491
453492 Function *FunctionAST::Codegen() {
454493 NamedValues.clear();
455
494
456495 Function *TheFunction = Proto->Codegen();
457496 if (TheFunction == 0)
458497 return 0;
459
498
460499 // Create a new basic block to start insertion into.
461500 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
462501 Builder.SetInsertPoint(BB);
463
502
464503 if (Value *RetVal = Body->Codegen()) {
465504 // Finish off the function.
466505 Builder.CreateRet(RetVal);
470509
471510 // Optimize the function.
472511 TheFPM->run(*TheFunction);
473
512
474513 return TheFunction;
475514 }
476
515
477516 // Error reading body, remove function.
478517 TheFunction->eraseFromParent();
479518 return 0;
516555 TheExecutionEngine->finalizeObject();
517556 // JIT the function, returning a function pointer.
518557 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
519
558
520559 // Cast it to the right type (takes no arguments, returns a double) so we
521560 // can call it as a native function.
522561 double (*FP)() = (double (*)())(intptr_t)FPtr;
533572 while (1) {
534573 fprintf(stderr, "ready> ");
535574 switch (CurTok) {
536 case tok_eof: return;
537 case ';': getNextToken(); break; // ignore top-level semicolons.
538 case tok_def: HandleDefinition(); break;
539 case tok_extern: HandleExtern(); break;
540 default: HandleTopLevelExpression(); break;
575 case tok_eof:
576 return;
577 case ';':
578 getNextToken();
579 break; // ignore top-level semicolons.
580 case tok_def:
581 HandleDefinition();
582 break;
583 case tok_extern:
584 HandleExtern();
585 break;
586 default:
587 HandleTopLevelExpression();
588 break;
541589 }
542590 }
543591 }
547595 //===----------------------------------------------------------------------===//
548596
549597 /// putchard - putchar that takes a double and returns 0.
550 extern "C"
551 double putchard(double X) {
598 extern "C" double putchard(double X) {
552599 putchar((char)X);
553600 return 0;
554601 }
568615 BinopPrecedence['<'] = 10;
569616 BinopPrecedence['+'] = 20;
570617 BinopPrecedence['-'] = 20;
571 BinopPrecedence['*'] = 40; // highest.
618 BinopPrecedence['*'] = 40; // highest.
572619
573620 // Prime the first token.
574621 fprintf(stderr, "ready> ");
580627
581628 // Create the JIT. This takes ownership of the module.
582629 std::string ErrStr;
583 TheExecutionEngine = EngineBuilder(std::move(Owner))
584 .setErrorStr(&ErrStr)
585 .setMCJITMemoryManager(new SectionMemoryManager())
586 .create();
630 TheExecutionEngine =
631 EngineBuilder(std::move(Owner))
632 .setErrorStr(&ErrStr)
633 .setMCJITMemoryManager(llvm::make_unique())
634 .create();
587635 if (!TheExecutionEngine) {
588636 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
589637 exit(1);
2727 tok_eof = -1,
2828
2929 // commands
30 tok_def = -2, tok_extern = -3,
30 tok_def = -2,
31 tok_extern = -3,
3132
3233 // primary
33 tok_identifier = -4, tok_number = -5,
34
34 tok_identifier = -4,
35 tok_number = -5,
36
3537 // control
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10
38 tok_if = -6,
39 tok_then = -7,
40 tok_else = -8,
41 tok_for = -9,
42 tok_in = -10
3843 };
3944
40 static std::string IdentifierStr; // Filled in if tok_identifier
41 static double NumVal; // Filled in if tok_number
45 static std::string IdentifierStr; // Filled in if tok_identifier
46 static double NumVal; // Filled in if tok_number
4247
4348 /// gettok - Return the next token from standard input.
4449 static int gettok() {
5358 while (isalnum((LastChar = getchar())))
5459 IdentifierStr += LastChar;
5560
56 if (IdentifierStr == "def") return tok_def;
57 if (IdentifierStr == "extern") return tok_extern;
58 if (IdentifierStr == "if") return tok_if;
59 if (IdentifierStr == "then") return tok_then;
60 if (IdentifierStr == "else") return tok_else;
61 if (IdentifierStr == "for") return tok_for;
62 if (IdentifierStr == "in") return tok_in;
61 if (IdentifierStr == "def")
62 return tok_def;
63 if (IdentifierStr == "extern")
64 return tok_extern;
65 if (IdentifierStr == "if")
66 return tok_if;
67 if (IdentifierStr == "then")
68 return tok_then;
69 if (IdentifierStr == "else")
70 return tok_else;
71 if (IdentifierStr == "for")
72 return tok_for;
73 if (IdentifierStr == "in")
74 return tok_in;
6375 return tok_identifier;
6476 }
6577
66 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
78 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
6779 std::string NumStr;
6880 do {
6981 NumStr += LastChar;
7688
7789 if (LastChar == '#') {
7890 // Comment until end of line.
79 do LastChar = getchar();
91 do
92 LastChar = getchar();
8093 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
81
94
8295 if (LastChar != EOF)
8396 return gettok();
8497 }
85
98
8699 // Check for end of file. Don't eat the EOF.
87100 if (LastChar == EOF)
88101 return tok_eof;
107120 /// NumberExprAST - Expression class for numeric literals like "1.0".
108121 class NumberExprAST : public ExprAST {
109122 double Val;
123
110124 public:
111125 NumberExprAST(double val) : Val(val) {}
112126 virtual Value *Codegen();
115129 /// VariableExprAST - Expression class for referencing a variable, like "a".
116130 class VariableExprAST : public ExprAST {
117131 std::string Name;
132
118133 public:
119134 VariableExprAST(const std::string &name) : Name(name) {}
120135 virtual Value *Codegen();
124139 class BinaryExprAST : public ExprAST {
125140 char Op;
126141 ExprAST *LHS, *RHS;
142
127143 public:
128 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
129 : Op(op), LHS(lhs), RHS(rhs) {}
144 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
145 : Op(op), LHS(lhs), RHS(rhs) {}
130146 virtual Value *Codegen();
131147 };
132148
133149 /// CallExprAST - Expression class for function calls.
134150 class CallExprAST : public ExprAST {
135151 std::string Callee;
136 std::vector*> Args;
152 std::vector *> Args;
153
137154 public:
138 CallExprAST(const std::string &callee, std::vector &args)
139 : Callee(callee), Args(args) {}
155 CallExprAST(const std::string &callee, std::vector &args)
156 : Callee(callee), Args(args) {}
140157 virtual Value *Codegen();
141158 };
142159
143160 /// IfExprAST - Expression class for if/then/else.
144161 class IfExprAST : public ExprAST {
145162 ExprAST *Cond, *Then, *Else;
163
146164 public:
147165 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
148 : Cond(cond), Then(then), Else(_else) {}
166 : Cond(cond), Then(then), Else(_else) {}
149167 virtual Value *Codegen();
150168 };
151169
153171 class ForExprAST : public ExprAST {
154172 std::string VarName;
155173 ExprAST *Start, *End, *Step, *Body;
174
156175 public:
157176 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
158177 ExprAST *step, ExprAST *body)
159 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
178 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
160179 virtual Value *Codegen();
161180 };
162181
166185 class PrototypeAST {
167186 std::string Name;
168187 std::vector Args;
188
169189 public:
170190 PrototypeAST(const std::string &name, const std::vector &args)
171 : Name(name), Args(args) {}
172
191 : Name(name), Args(args) {}
192
173193 Function *Codegen();
174194 };
175195
177197 class FunctionAST {
178198 PrototypeAST *Proto;
179199 ExprAST *Body;
200
180201 public:
181 FunctionAST(PrototypeAST *proto, ExprAST *body)
182 : Proto(proto), Body(body) {}
183
202 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
203
184204 Function *Codegen();
185205 };
186206 } // end anonymous namespace
193213 /// token the parser is looking at. getNextToken reads another token from the
194214 /// lexer and updates CurTok with its results.
195215 static int CurTok;
196 static int getNextToken() {
197 return CurTok = gettok();
198 }
216 static int getNextToken() { return CurTok = gettok(); }
199217
200218 /// BinopPrecedence - This holds the precedence for each binary operator that is
201219 /// defined.
205223 static int GetTokPrecedence() {
206224 if (!isascii(CurTok))
207225 return -1;
208
226
209227 // Make sure it's a declared binop.
210228 int TokPrec = BinopPrecedence[CurTok];
211 if (TokPrec <= 0) return -1;
229 if (TokPrec <= 0)
230 return -1;
212231 return TokPrec;
213232 }
214233
215234 /// Error* - These are little helper functions for error handling.
216 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
217 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
218 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
235 ExprAST *Error(const char *Str) {
236 fprintf(stderr, "Error: %s\n", Str);
237 return 0;
238 }
239 PrototypeAST *ErrorP(const char *Str) {
240 Error(Str);
241 return 0;
242 }
243 FunctionAST *ErrorF(const char *Str) {
244 Error(Str);
245 return 0;
246 }
219247
220248 static ExprAST *ParseExpression();
221249
224252 /// ::= identifier '(' expression* ')'
225253 static ExprAST *ParseIdentifierExpr() {
226254 std::string IdName = IdentifierStr;
227
228 getNextToken(); // eat identifier.
229
255
256 getNextToken(); // eat identifier.
257
230258 if (CurTok != '(') // Simple variable ref.
231259 return new VariableExprAST(IdName);
232
260
233261 // Call.
234 getNextToken(); // eat (
235 std::vector Args;
262 getNextToken(); // eat (
263 std::vector Args;
236264 if (CurTok != ')') {
237265 while (1) {
238266 ExprAST *Arg = ParseExpression();
239 if (!Arg) return 0;
267 if (!Arg)
268 return 0;
240269 Args.push_back(Arg);
241270
242 if (CurTok == ')') break;
271 if (CurTok == ')')
272 break;
243273
244274 if (CurTok != ',')
245275 return Error("Expected ')' or ',' in argument list");
249279
250280 // Eat the ')'.
251281 getNextToken();
252
282
253283 return new CallExprAST(IdName, Args);
254284 }
255285
262292
263293 /// parenexpr ::= '(' expression ')'
264294 static ExprAST *ParseParenExpr() {
265 getNextToken(); // eat (.
295 getNextToken(); // eat (.
266296 ExprAST *V = ParseExpression();
267 if (!V) return 0;
268
297 if (!V)
298 return 0;
299
269300 if (CurTok != ')')
270301 return Error("expected ')'");
271 getNextToken(); // eat ).
302 getNextToken(); // eat ).
272303 return V;
273304 }
274305
275306 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
276307 static ExprAST *ParseIfExpr() {
277 getNextToken(); // eat the if.
278
308 getNextToken(); // eat the if.
309
279310 // condition.
280311 ExprAST *Cond = ParseExpression();
281 if (!Cond) return 0;
282
312 if (!Cond)
313 return 0;
314
283315 if (CurTok != tok_then)
284316 return Error("expected then");
285 getNextToken(); // eat the then
286
317 getNextToken(); // eat the then
318
287319 ExprAST *Then = ParseExpression();
288 if (Then == 0) return 0;
289
320 if (Then == 0)
321 return 0;
322
290323 if (CurTok != tok_else)
291324 return Error("expected else");
292
325
293326 getNextToken();
294
327
295328 ExprAST *Else = ParseExpression();
296 if (!Else) return 0;
297
329 if (!Else)
330 return 0;
331
298332 return new IfExprAST(Cond, Then, Else);
299333 }
300334
301335 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
302336 static ExprAST *ParseForExpr() {
303 getNextToken(); // eat the for.
337 getNextToken(); // eat the for.
304338
305339 if (CurTok != tok_identifier)
306340 return Error("expected identifier after for");
307
341
308342 std::string IdName = IdentifierStr;
309 getNextToken(); // eat identifier.
310
343 getNextToken(); // eat identifier.
344
311345 if (CurTok != '=')
312346 return Error("expected '=' after for");
313 getNextToken(); // eat '='.
314
315
347 getNextToken(); // eat '='.
348
316349 ExprAST *Start = ParseExpression();
317 if (Start == 0) return 0;
350 if (Start == 0)
351 return 0;
318352 if (CurTok != ',')
319353 return Error("expected ',' after for start value");
320354 getNextToken();
321
355
322356 ExprAST *End = ParseExpression();
323 if (End == 0) return 0;
324
357 if (End == 0)
358 return 0;
359
325360 // The step value is optional.
326361 ExprAST *Step = 0;
327362 if (CurTok == ',') {
328363 getNextToken();
329364 Step = ParseExpression();
330 if (Step == 0) return 0;
331 }
332
365 if (Step == 0)
366 return 0;
367 }
368
333369 if (CurTok != tok_in)
334370 return Error("expected 'in' after for");
335 getNextToken(); // eat 'in'.
336
371 getNextToken(); // eat 'in'.
372
337373 ExprAST *Body = ParseExpression();
338 if (Body == 0) return 0;
374 if (Body == 0)
375 return 0;
339376
340377 return new ForExprAST(IdName, Start, End, Step, Body);
341378 }
348385 /// ::= forexpr
349386 static ExprAST *ParsePrimary() {
350387 switch (CurTok) {
351 default: return Error("unknown token when expecting an expression");
352 case tok_identifier: return ParseIdentifierExpr();
353 case tok_number: return ParseNumberExpr();
354 case '(': return ParseParenExpr();
355 case tok_if: return ParseIfExpr();
356 case tok_for: return ParseForExpr();
388 default:
389 return Error("unknown token when expecting an expression");
390 case tok_identifier:
391 return ParseIdentifierExpr();
392 case tok_number:
393 return ParseNumberExpr();
394 case '(':
395 return ParseParenExpr();
396 case tok_if:
397 return ParseIfExpr();
398 case tok_for:
399 return ParseForExpr();
357400 }
358401 }
359402
363406 // If this is a binop, find its precedence.
364407 while (1) {
365408 int TokPrec = GetTokPrecedence();
366
409
367410 // If this is a binop that binds at least as tightly as the current binop,
368411 // consume it, otherwise we are done.
369412 if (TokPrec < ExprPrec)
370413 return LHS;
371
414
372415 // Okay, we know this is a binop.
373416 int BinOp = CurTok;
374 getNextToken(); // eat binop
375
417 getNextToken(); // eat binop
418
376419 // Parse the primary expression after the binary operator.
377420 ExprAST *RHS = ParsePrimary();
378 if (!RHS) return 0;
379
421 if (!RHS)
422 return 0;
423
380424 // If BinOp binds less tightly with RHS than the operator after RHS, let
381425 // the pending operator take RHS as its LHS.
382426 int NextPrec = GetTokPrecedence();
383427 if (TokPrec < NextPrec) {
384 RHS = ParseBinOpRHS(TokPrec+1, RHS);
385 if (RHS == 0) return 0;
428 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
429 if (RHS == 0)
430 return 0;
386431 }
387
432
388433 // Merge LHS/RHS.
389434 LHS = new BinaryExprAST(BinOp, LHS, RHS);
390435 }
395440 ///
396441 static ExprAST *ParseExpression() {
397442 ExprAST *LHS = ParsePrimary();
398 if (!LHS) return 0;
399
443 if (!LHS)
444 return 0;
445
400446 return ParseBinOpRHS(0, LHS);
401447 }
402448
408454
409455 std::string FnName = IdentifierStr;
410456 getNextToken();
411
457
412458 if (CurTok != '(')
413459 return ErrorP("Expected '(' in prototype");
414
460
415461 std::vector ArgNames;
416462 while (getNextToken() == tok_identifier)
417463 ArgNames.push_back(IdentifierStr);
418464 if (CurTok != ')')
419465 return ErrorP("Expected ')' in prototype");
420
466
421467 // success.
422 getNextToken(); // eat ')'.
423
468 getNextToken(); // eat ')'.
469
424470 return new PrototypeAST(FnName, ArgNames);
425471 }
426472
427473 /// definition ::= 'def' prototype expression
428474 static FunctionAST *ParseDefinition() {
429 getNextToken(); // eat def.
475 getNextToken(); // eat def.
430476 PrototypeAST *Proto = ParsePrototype();
431 if (Proto == 0) return 0;
477 if (Proto == 0)
478 return 0;
432479
433480 if (ExprAST *E = ParseExpression())
434481 return new FunctionAST(Proto, E);
447494
448495 /// external ::= 'extern' prototype
449496 static PrototypeAST *ParseExtern() {
450 getNextToken(); // eat extern.
497 getNextToken(); // eat extern.
451498 return ParsePrototype();
452499 }
453500
457504
458505 static Module *TheModule;
459506 static IRBuilder<> Builder(getGlobalContext());
460 static std::map*> NamedValues;
507 static std::map *> NamedValues;
461508 static FunctionPassManager *TheFPM;
462509
463 Value *ErrorV(const char *Str) { Error(Str); return 0; }
510 Value *ErrorV(const char *Str) {
511 Error(Str);
512 return 0;
513 }
464514
465515 Value *NumberExprAST::Codegen() {
466516 return ConstantFP::get(getGlobalContext(), APFloat(Val));
475525 Value *BinaryExprAST::Codegen() {
476526 Value *L = LHS->Codegen();
477527 Value *R = RHS->Codegen();
478 if (L == 0 || R == 0) return 0;
479
528 if (L == 0 || R == 0)
529 return 0;
530
480531 switch (Op) {
481 case '+': return Builder.CreateFAdd(L, R, "addtmp");
482 case '-': return Builder.CreateFSub(L, R, "subtmp");
483 case '*': return Builder.CreateFMul(L, R, "multmp");
532 case '+':
533 return Builder.CreateFAdd(L, R, "addtmp");
534 case '-':
535 return Builder.CreateFSub(L, R, "subtmp");
536 case '*':
537 return Builder.CreateFMul(L, R, "multmp");
484538 case '<':
485539 L = Builder.CreateFCmpULT(L, R, "cmptmp");
486540 // Convert bool 0/1 to double 0.0 or 1.0
487541 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
488542 "booltmp");
489 default: return ErrorV("invalid binary operator");
543 default:
544 return ErrorV("invalid binary operator");
490545 }
491546 }
492547
495550 Function *CalleeF = TheModule->getFunction(Callee);
496551 if (CalleeF == 0)
497552 return ErrorV("Unknown function referenced");
498
553
499554 // If argument mismatch error.
500555 if (CalleeF->arg_size() != Args.size())
501556 return ErrorV("Incorrect # arguments passed");
502557
503 std::vector*> ArgsV;
558 std::vector *> ArgsV;
504559 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
505560 ArgsV.push_back(Args[i]->Codegen());
506 if (ArgsV.back() == 0) return 0;
507 }
508
561 if (ArgsV.back() == 0)
562 return 0;
563 }
564
509565 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
510566 }
511567
512568 Value *IfExprAST::Codegen() {
513569 Value *CondV = Cond->Codegen();
514 if (CondV == 0) return 0;
515
570 if (CondV == 0)
571 return 0;
572
516573 // Convert condition to a bool by comparing equal to 0.0.
517 CondV = Builder.CreateFCmpONE(CondV,
518 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
519 "ifcond");
520
574 CondV = Builder.CreateFCmpONE(
575 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
576
521577 Function *TheFunction = Builder.GetInsertBlock()->getParent();
522
578
523579 // Create blocks for the then and else cases. Insert the 'then' block at the
524580 // end of the function.
525 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
581 BasicBlock *ThenBB =
582 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
526583 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
527584 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
528
585
529586 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
530
587
531588 // Emit then value.
532589 Builder.SetInsertPoint(ThenBB);
533
590
534591 Value *ThenV = Then->Codegen();
535 if (ThenV == 0) return 0;
536
592 if (ThenV == 0)
593 return 0;
594
537595 Builder.CreateBr(MergeBB);
538596 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
539597 ThenBB = Builder.GetInsertBlock();
540
598
541599 // Emit else block.
542600 TheFunction->getBasicBlockList().push_back(ElseBB);
543601 Builder.SetInsertPoint(ElseBB);
544
602
545603 Value *ElseV = Else->Codegen();
546 if (ElseV == 0) return 0;
547
604 if (ElseV == 0)
605 return 0;
606
548607 Builder.CreateBr(MergeBB);
549608 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
550609 ElseBB = Builder.GetInsertBlock();
551
610
552611 // Emit merge block.
553612 TheFunction->getBasicBlockList().push_back(MergeBB);
554613 Builder.SetInsertPoint(MergeBB);
555 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
556 "iftmp");
557
614 PHINode *PN =
615 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
616
558617 PN->addIncoming(ThenV, ThenBB);
559618 PN->addIncoming(ElseV, ElseBB);
560619 return PN;
565624 // ...
566625 // start = startexpr
567626 // goto loop
568 // loop:
627 // loop:
569628 // variable = phi [start, loopheader], [nextvariable, loopend]
570629 // ...
571630 // bodyexpr
576635 // endcond = endexpr
577636 // br endcond, loop, endloop
578637 // outloop:
579
638
580639 // Emit the start code first, without 'variable' in scope.
581640 Value *StartVal = Start->Codegen();
582 if (StartVal == 0) return 0;
583
641 if (StartVal == 0)
642 return 0;
643
584644 // Make the new basic block for the loop header, inserting after current
585645 // block.
586646 Function *TheFunction = Builder.GetInsertBlock()->getParent();
587647 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
588 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
589
648 BasicBlock *LoopBB =
649 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
650
590651 // Insert an explicit fall through from the current block to the LoopBB.
591652 Builder.CreateBr(LoopBB);
592653
593654 // Start insertion in LoopBB.
594655 Builder.SetInsertPoint(LoopBB);
595
656
596657 // Start the PHI node with an entry for Start.
597 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
658 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
659 2, VarName.c_str());
598660 Variable->addIncoming(StartVal, PreheaderBB);
599
661
600662 // Within the loop, the variable is defined equal to the PHI node. If it
601663 // shadows an existing variable, we have to restore it, so save it now.
602664 Value *OldVal = NamedValues[VarName];
603665 NamedValues[VarName] = Variable;
604
666
605667 // Emit the body of the loop. This, like any other expr, can change the
606668 // current BB. Note that we ignore the value computed by the body, but don't
607669 // allow an error.
608670 if (Body->Codegen() == 0)
609671 return 0;
610
672
611673 // Emit the step value.
612674 Value *StepVal;
613675 if (Step) {
614676 StepVal = Step->Codegen();
615 if (StepVal == 0) return 0;
677 if (StepVal == 0)
678 return 0;
616679 } else {
617680 // If not specified, use 1.0.
618681 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
619682 }
620
683
621684 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
622685
623686 // Compute the end condition.
624687 Value *EndCond = End->Codegen();
625 if (EndCond == 0) return EndCond;
626
688 if (EndCond == 0)
689 return EndCond;
690
627691 // Convert condition to a bool by comparing equal to 0.0.
628 EndCond = Builder.CreateFCmpONE(EndCond,
629 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
630 "loopcond");
631
692 EndCond = Builder.CreateFCmpONE(
693 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
694
632695 // Create the "after loop" block and insert it.
633696 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
634 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
635
697 BasicBlock *AfterBB =
698 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
699
636700 // Insert the conditional branch into the end of LoopEndBB.
637701 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
638
702
639703 // Any new code will be inserted in AfterBB.
640704 Builder.SetInsertPoint(AfterBB);
641
705
642706 // Add a new entry to the PHI node for the backedge.
643707 Variable->addIncoming(NextVar, LoopEndBB);
644
708
645709 // Restore the unshadowed variable.
646710 if (OldVal)
647711 NamedValues[VarName] = OldVal;
648712 else
649713 NamedValues.erase(VarName);
650714
651
652715 // for expr always returns 0.0.
653716 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
654717 }
655718
656719 Function *PrototypeAST::Codegen() {
657720 // Make the function type: double(double,double) etc.
658 std::vector Doubles(Args.size(),
659 Type::getDoubleTy(getGlobalContext()));
660 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
661 Doubles, false);
662
663 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
664
721 std::vector Doubles(Args.size(),
722 Type::getDoubleTy(getGlobalContext()));
723 FunctionType *FT =
724 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
725
726 Function *F =
727 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
728
665729 // If F conflicted, there was already something named 'Name'. If it has a
666730 // body, don't allow redefinition or reextern.
667731 if (F->getName() != Name) {
668732 // Delete the one we just made and get the existing one.
669733 F->eraseFromParent();
670734 F = TheModule->getFunction(Name);
671
735
672736 // If F already has a body, reject this.
673737 if (!F->empty()) {
674738 ErrorF("redefinition of function");
675739 return 0;
676740 }
677
741
678742 // If F took a different number of args, reject.
679743 if (F->arg_size() != Args.size()) {
680744 ErrorF("redefinition of function with different # args");
681745 return 0;
682746 }
683747 }
684
748
685749 // Set names for all arguments.
686750 unsigned Idx = 0;
687751 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
688752 ++AI, ++Idx) {
689753 AI->setName(Args[Idx]);
690
754
691755 // Add arguments to variable symbol table.
692756 NamedValues[Args[Idx]] = AI;
693757 }
694
758
695759 return F;
696760 }
697761
698762 Function *FunctionAST::Codegen() {
699763 NamedValues.clear();
700
764
701765 Function *TheFunction = Proto->Codegen();
702766 if (TheFunction == 0)
703767 return 0;
704
768
705769 // Create a new basic block to start insertion into.
706770 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
707771 Builder.SetInsertPoint(BB);
708
772
709773 if (Value *RetVal = Body->Codegen()) {
710774 // Finish off the function.
711775 Builder.CreateRet(RetVal);
715779
716780 // Optimize the function.
717781 TheFPM->run(*TheFunction);
718
782
719783 return TheFunction;
720784 }
721
785
722786 // Error reading body, remove function.
723787 TheFunction->eraseFromParent();
724788 return 0;
761825 TheExecutionEngine->finalizeObject();
762826 // JIT the function, returning a function pointer.
763827 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
764
828
765829 // Cast it to the right type (takes no arguments, returns a double) so we
766830 // can call it as a native function.
767831 double (*FP)() = (double (*)())(intptr_t)FPtr;
778842 while (1) {
779843 fprintf(stderr, "ready> ");
780844 switch (CurTok) {
781 case tok_eof: return;
782 case ';': getNextToken(); break; // ignore top-level semicolons.
783 case tok_def: HandleDefinition(); break;
784 case tok_extern: HandleExtern(); break;
785 default: HandleTopLevelExpression(); break;
845 case tok_eof:
846 return;
847 case ';':
848 getNextToken();
849 break; // ignore top-level semicolons.
850 case tok_def:
851 HandleDefinition();
852 break;
853 case tok_extern:
854 HandleExtern();
855 break;
856 default:
857 HandleTopLevelExpression();
858 break;
786859 }
787860 }
788861 }
792865 //===----------------------------------------------------------------------===//
793866
794867 /// putchard - putchar that takes a double and returns 0.
795 extern "C"
796 double putchard(double X) {
868 extern "C" double putchard(double X) {
797869 putchar((char)X);
798870 return 0;
799871 }
813885 BinopPrecedence['<'] = 10;
814886 BinopPrecedence['+'] = 20;
815887 BinopPrecedence['-'] = 20;
816 BinopPrecedence['*'] = 40; // highest.
888 BinopPrecedence['*'] = 40; // highest.
817889
818890 // Prime the first token.
819891 fprintf(stderr, "ready> ");
825897
826898 // Create the JIT. This takes ownership of the module.
827899 std::string ErrStr;
828 TheExecutionEngine = EngineBuilder(std::move(Owner))
829 .setErrorStr(&ErrStr)
830 .setMCJITMemoryManager(new SectionMemoryManager())
831 .create();
900 TheExecutionEngine =
901 EngineBuilder(std::move(Owner))
902 .setErrorStr(&ErrStr)
903 .setMCJITMemoryManager(llvm::make_unique())
904 .create();
832905 if (!TheExecutionEngine) {
833906 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
834907 exit(1);
2727 tok_eof = -1,
2828
2929 // commands
30 tok_def = -2, tok_extern = -3,
30 tok_def = -2,
31 tok_extern = -3,
3132
3233 // primary
33 tok_identifier = -4, tok_number = -5,
34
34 tok_identifier = -4,
35 tok_number = -5,
36
3537 // control
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10,
38
38 tok_if = -6,
39 tok_then = -7,
40 tok_else = -8,
41 tok_for = -9,
42 tok_in = -10,
43
3944 // operators
40 tok_binary = -11, tok_unary = -12
45 tok_binary = -11,
46 tok_unary = -12
4147 };
4248
43 static std::string IdentifierStr; // Filled in if tok_identifier
44 static double NumVal; // Filled in if tok_number
49 static std::string IdentifierStr; // Filled in if tok_identifier
50 static double NumVal; // Filled in if tok_number
4551
4652 /// gettok - Return the next token from standard input.
4753 static int gettok() {
5662 while (isalnum((LastChar = getchar())))
5763 IdentifierStr += LastChar;
5864
59 if (IdentifierStr == "def") return tok_def;
60 if (IdentifierStr == "extern") return tok_extern;
61 if (IdentifierStr == "if") return tok_if;
62 if (IdentifierStr == "then") return tok_then;
63 if (IdentifierStr == "else") return tok_else;
64 if (IdentifierStr == "for") return tok_for;
65 if (IdentifierStr == "in") return tok_in;
66 if (IdentifierStr == "binary") return tok_binary;
67 if (IdentifierStr == "unary") return tok_unary;
65 if (IdentifierStr == "def")
66 return tok_def;
67 if (IdentifierStr == "extern")
68 return tok_extern;
69 if (IdentifierStr == "if")
70 return tok_if;
71 if (IdentifierStr == "then")
72 return tok_then;
73 if (IdentifierStr == "else")
74 return tok_else;
75 if (IdentifierStr == "for")
76 return tok_for;
77 if (IdentifierStr == "in")
78 return tok_in;
79 if (IdentifierStr == "binary")
80 return tok_binary;
81 if (IdentifierStr == "unary")
82 return tok_unary;
6883 return tok_identifier;
6984 }
7085
71 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
86 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
7287 std::string NumStr;
7388 do {
7489 NumStr += LastChar;
8196
8297 if (LastChar == '#') {
8398 // Comment until end of line.
84 do LastChar = getchar();
99 do
100 LastChar = getchar();
85101 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
86
102
87103 if (LastChar != EOF)
88104 return gettok();
89105 }
90
106
91107 // Check for end of file. Don't eat the EOF.
92108 if (LastChar == EOF)
93109 return tok_eof;
112128 /// NumberExprAST - Expression class for numeric literals like "1.0".
113129 class NumberExprAST : public ExprAST {
114130 double Val;
131
115132 public:
116133 NumberExprAST(double val) : Val(val) {}
117134 virtual Value *Codegen();
120137 /// VariableExprAST - Expression class for referencing a variable, like "a".
121138 class VariableExprAST : public ExprAST {
122139 std::string Name;
140
123141 public:
124142 VariableExprAST(const std::string &name) : Name(name) {}
125143 virtual Value *Codegen();
129147 class UnaryExprAST : public ExprAST {
130148 char Opcode;
131149 ExprAST *Operand;
150
132151 public:
133 UnaryExprAST(char opcode, ExprAST *operand)
134 : Opcode(opcode), Operand(operand) {}
152 UnaryExprAST(char opcode, ExprAST *operand)
153 : Opcode(opcode), Operand(operand) {}
135154 virtual Value *Codegen();
136155 };
137156
139158 class BinaryExprAST : public ExprAST {
140159 char Op;
141160 ExprAST *LHS, *RHS;
161
142162 public:
143 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
144 : Op(op), LHS(lhs), RHS(rhs) {}
163 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
164 : Op(op), LHS(lhs), RHS(rhs) {}
145165 virtual Value *Codegen();
146166 };
147167
148168 /// CallExprAST - Expression class for function calls.
149169 class CallExprAST : public ExprAST {
150170 std::string Callee;
151 std::vector*> Args;
171 std::vector *> Args;
172
152173 public:
153 CallExprAST(const std::string &callee, std::vector &args)
154 : Callee(callee), Args(args) {}
174 CallExprAST(const std::string &callee, std::vector &args)
175 : Callee(callee), Args(args) {}
155176 virtual Value *Codegen();
156177 };
157178
158179 /// IfExprAST - Expression class for if/then/else.
159180 class IfExprAST : public ExprAST {
160181 ExprAST *Cond, *Then, *Else;
182
161183 public:
162184 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
163 : Cond(cond), Then(then), Else(_else) {}
185 : Cond(cond), Then(then), Else(_else) {}
164186 virtual Value *Codegen();
165187 };
166188
168190 class ForExprAST : public ExprAST {
169191 std::string VarName;
170192 ExprAST *Start, *End, *Step, *Body;
193
171194 public:
172195 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
173196 ExprAST *step, ExprAST *body)
174 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
197 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
175198 virtual Value *Codegen();
176199 };
177200
182205 std::string Name;
183206 std::vector Args;
184207 bool isOperator;
185 unsigned Precedence; // Precedence if a binary op.
208 unsigned Precedence; // Precedence if a binary op.
186209 public:
187210 PrototypeAST(const std::string &name, const std::vector &args,
188211 bool isoperator = false, unsigned prec = 0)
189 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
190
212 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
213
191214 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
192215 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
193
216
194217 char getOperatorName() const {
195218 assert(isUnaryOp() || isBinaryOp());
196 return Name[Name.size()-1];
197 }
198
219 return Name[Name.size() - 1];
220 }
221
199222 unsigned getBinaryPrecedence() const { return Precedence; }
200
223
201224 Function *Codegen();
202225 };
203226
205228 class FunctionAST {
206229 PrototypeAST *Proto;
207230 ExprAST *Body;
231
208232 public:
209 FunctionAST(PrototypeAST *proto, ExprAST *body)
210 : Proto(proto), Body(body) {}
211
233 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
234
212235 Function *Codegen();
213236 };
214237 } // end anonymous namespace
221244 /// token the parser is looking at. getNextToken reads another token from the
222245 /// lexer and updates CurTok with its results.
223246 static int CurTok;
224 static int getNextToken() {
225 return CurTok = gettok();
226 }
247 static int getNextToken() { return CurTok = gettok(); }
227248
228249 /// BinopPrecedence - This holds the precedence for each binary operator that is
229250 /// defined.
233254 static int GetTokPrecedence() {
234255 if (!isascii(CurTok))
235256 return -1;
236
257
237258 // Make sure it's a declared binop.
238259 int TokPrec = BinopPrecedence[CurTok];
239 if (TokPrec <= 0) return -1;
260 if (TokPrec <= 0)
261 return -1;
240262 return TokPrec;
241263 }
242264
243265 /// Error* - These are little helper functions for error handling.
244 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
245 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
246 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
266 ExprAST *Error(const char *Str) {
267 fprintf(stderr, "Error: %s\n", Str);
268 return 0;
269 }
270 PrototypeAST *ErrorP(const char *Str) {
271 Error(Str);
272 return 0;
273 }
274 FunctionAST *ErrorF(const char *Str) {
275 Error(Str);
276 return 0;
277 }
247278
248279 static ExprAST *ParseExpression();
249280
252283 /// ::= identifier '(' expression* ')'
253284 static ExprAST *ParseIdentifierExpr() {
254285 std::string IdName = IdentifierStr;
255
256 getNextToken(); // eat identifier.
257
286
287 getNextToken(); // eat identifier.
288
258289 if (CurTok != '(') // Simple variable ref.
259290 return new VariableExprAST(IdName);
260
291
261292 // Call.
262 getNextToken(); // eat (
263 std::vector Args;
293 getNextToken(); // eat (
294 std::vector Args;
264295 if (CurTok != ')') {
265296 while (1) {
266297 ExprAST *Arg = ParseExpression();
267 if (!Arg) return 0;
298 if (!Arg)
299 return 0;
268300 Args.push_back(Arg);
269301
270 if (CurTok == ')') break;
302 if (CurTok == ')')
303 break;
271304
272305 if (CurTok != ',')
273306 return Error("Expected ')' or ',' in argument list");
277310
278311 // Eat the ')'.
279312 getNextToken();
280
313
281314 return new CallExprAST(IdName, Args);
282315 }
283316
290323
291324 /// parenexpr ::= '(' expression ')'
292325 static ExprAST *ParseParenExpr() {
293 getNextToken(); // eat (.
326 getNextToken(); // eat (.
294327 ExprAST *V = ParseExpression();
295 if (!V) return 0;
296
328 if (!V)
329 return 0;
330
297331 if (CurTok != ')')
298332 return Error("expected ')'");
299 getNextToken(); // eat ).
333 getNextToken(); // eat ).
300334 return V;
301335 }
302336
303337 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
304338 static ExprAST *ParseIfExpr() {
305 getNextToken(); // eat the if.
306
339 getNextToken(); // eat the if.
340
307341 // condition.
308342 ExprAST *Cond = ParseExpression();
309 if (!Cond) return 0;
310
343 if (!Cond)
344 return 0;
345
311346 if (CurTok != tok_then)
312347 return Error("expected then");
313 getNextToken(); // eat the then
314
348 getNextToken(); // eat the then
349
315350 ExprAST *Then = ParseExpression();
316 if (Then == 0) return 0;
317
351 if (Then == 0)
352 return 0;
353
318354 if (CurTok != tok_else)
319355 return Error("expected else");
320
356
321357 getNextToken();
322
358
323359 ExprAST *Else = ParseExpression();
324 if (!Else) return 0;
325
360 if (!Else)
361 return 0;
362
326363 return new IfExprAST(Cond, Then, Else);
327364 }
328365
329366 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
330367 static ExprAST *ParseForExpr() {
331 getNextToken(); // eat the for.
368 getNextToken(); // eat the for.
332369
333370 if (CurTok != tok_identifier)
334371 return Error("expected identifier after for");
335
372
336373 std::string IdName = IdentifierStr;
337 getNextToken(); // eat identifier.
338
374 getNextToken(); // eat identifier.
375
339376 if (CurTok != '=')
340377 return Error("expected '=' after for");
341 getNextToken(); // eat '='.
342
343
378 getNextToken(); // eat '='.
379
344380 ExprAST *Start = ParseExpression();
345 if (Start == 0) return 0;
381 if (Start == 0)
382 return 0;
346383 if (CurTok != ',')
347384 return Error("expected ',' after for start value");
348385 getNextToken();
349
386
350387 ExprAST *End = ParseExpression();
351 if (End == 0) return 0;
352
388 if (End == 0)
389 return 0;
390
353391 // The step value is optional.
354392 ExprAST *Step = 0;
355393 if (CurTok == ',') {
356394 getNextToken();
357395 Step = ParseExpression();
358 if (Step == 0) return 0;
359 }
360
396 if (Step == 0)
397 return 0;
398 }
399
361400 if (CurTok != tok_in)
362401 return Error("expected 'in' after for");
363 getNextToken(); // eat 'in'.
364
402 getNextToken(); // eat 'in'.
403
365404 ExprAST *Body = ParseExpression();
366 if (Body == 0) return 0;
405 if (Body == 0)
406 return 0;
367407
368408 return new ForExprAST(IdName, Start, End, Step, Body);
369409 }
376416 /// ::= forexpr
377417 static ExprAST *ParsePrimary() {
378418 switch (CurTok) {
379 default: return Error("unknown token when expecting an expression");
380 case tok_identifier: return ParseIdentifierExpr();
381 case tok_number: return ParseNumberExpr();
382 case '(': return ParseParenExpr();
383 case tok_if: return ParseIfExpr();
384 case tok_for: return ParseForExpr();
419 default:
420 return Error("unknown token when expecting an expression");
421 case tok_identifier:
422 return ParseIdentifierExpr();
423 case tok_number:
424 return ParseNumberExpr();
425 case '(':
426 return ParseParenExpr();
427 case tok_if:
428 return ParseIfExpr();
429 case tok_for:
430 return ParseForExpr();
385431 }
386432 }
387433
392438 // If the current token is not an operator, it must be a primary expr.
393439 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
394440 return ParsePrimary();
395
441
396442 // If this is a unary operator, read it.
397443 int Opc = CurTok;
398444 getNextToken();
407453 // If this is a binop, find its precedence.
408454 while (1) {
409455 int TokPrec = GetTokPrecedence();
410
456
411457 // If this is a binop that binds at least as tightly as the current binop,
412458 // consume it, otherwise we are done.
413459 if (TokPrec < ExprPrec)
414460 return LHS;
415
461
416462 // Okay, we know this is a binop.
417463 int BinOp = CurTok;
418 getNextToken(); // eat binop
419
464 getNextToken(); // eat binop
465
420466 // Parse the unary expression after the binary operator.
421467 ExprAST *RHS = ParseUnary();
422 if (!RHS) return 0;
423
468 if (!RHS)
469 return 0;
470
424471 // If BinOp binds less tightly with RHS than the operator after RHS, let
425472 // the pending operator take RHS as its LHS.
426473 int NextPrec = GetTokPrecedence();
427474 if (TokPrec < NextPrec) {
428 RHS = ParseBinOpRHS(TokPrec+1, RHS);
429 if (RHS == 0) return 0;
475 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
476 if (RHS == 0)
477 return 0;
430478 }
431
479
432480 // Merge LHS/RHS.
433481 LHS = new BinaryExprAST(BinOp, LHS, RHS);
434482 }
439487 ///
440488 static ExprAST *ParseExpression() {
441489 ExprAST *LHS = ParseUnary();
442 if (!LHS) return 0;
443
490 if (!LHS)
491 return 0;
492
444493 return ParseBinOpRHS(0, LHS);
445494 }
446495
450499 /// ::= unary LETTER (id)
451500 static PrototypeAST *ParsePrototype() {
452501 std::string FnName;
453
502
454503 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
455504 unsigned BinaryPrecedence = 30;
456
505
457506 switch (CurTok) {
458507 default:
459508 return ErrorP("Expected function name in prototype");
479528 FnName += (char)CurTok;
480529 Kind = 2;
481530 getNextToken();
482
531
483532 // Read the precedence if present.
484533 if (CurTok == tok_number) {
485534 if (NumVal < 1 || NumVal > 100)
489538 }
490539 break;
491540 }
492
541
493542 if (CurTok != '(')
494543 return ErrorP("Expected '(' in prototype");
495
544
496545 std::vector ArgNames;
497546 while (getNextToken() == tok_identifier)
498547 ArgNames.push_back(IdentifierStr);
499548 if (CurTok != ')')
500549 return ErrorP("Expected ')' in prototype");
501
550
502551 // success.
503 getNextToken(); // eat ')'.
504
552 getNextToken(); // eat ')'.
553
505554 // Verify right number of names for operator.
506555 if (Kind && ArgNames.size() != Kind)
507556 return ErrorP("Invalid number of operands for operator");
508
557
509558 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
510559 }
511560
512561 /// definition ::= 'def' prototype expression
513562 static FunctionAST *ParseDefinition() {
514 getNextToken(); // eat def.
563 getNextToken(); // eat def.
515564 PrototypeAST *Proto = ParsePrototype();
516 if (Proto == 0) return 0;
565 if (Proto == 0)
566 return 0;
517567
518568 if (ExprAST *E = ParseExpression())
519569 return new FunctionAST(Proto, E);
532582
533583 /// external ::= 'extern' prototype
534584 static PrototypeAST *ParseExtern() {
535 getNextToken(); // eat extern.
585 getNextToken(); // eat extern.
536586 return ParsePrototype();
537587 }
538588
542592
543593 static Module *TheModule;
544594 static IRBuilder<> Builder(getGlobalContext());
545 static std::map*> NamedValues;
595 static std::map *> NamedValues;
546596 static FunctionPassManager *TheFPM;
547597
548 Value *ErrorV(const char *Str) { Error(Str); return 0; }
598 Value *ErrorV(const char *Str) {
599 Error(Str);
600 return 0;
601 }
549602
550603 Value *NumberExprAST::Codegen() {
551604 return ConstantFP::get(getGlobalContext(), APFloat(Val));
559612
560613 Value *UnaryExprAST::Codegen() {
561614 Value *OperandV = Operand->Codegen();
562 if (OperandV == 0) return 0;
563
564 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
615 if (OperandV == 0)
616 return 0;
617
618 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
565619 if (F == 0)
566620 return ErrorV("Unknown unary operator");
567
621
568622 return Builder.CreateCall(F, OperandV, "unop");
569623 }
570624
571625 Value *BinaryExprAST::Codegen() {
572626 Value *L = LHS->Codegen();
573627 Value *R = RHS->Codegen();
574 if (L == 0 || R == 0) return 0;
575
628 if (L == 0 || R == 0)
629 return 0;
630
576631 switch (Op) {
577 case '+': return Builder.CreateFAdd(L, R, "addtmp");
578 case '-': return Builder.CreateFSub(L, R, "subtmp");
579 case '*': return Builder.CreateFMul(L, R, "multmp");
632 case '+':
633 return Builder.CreateFAdd(L, R, "addtmp");
634 case '-':
635 return Builder.CreateFSub(L, R, "subtmp");
636 case '*':
637 return Builder.CreateFMul(L, R, "multmp");
580638 case '<':
581639 L = Builder.CreateFCmpULT(L, R, "cmptmp");
582640 // Convert bool 0/1 to double 0.0 or 1.0
583641 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
584642 "booltmp");
585 default: break;
586 }
587
643 default:
644 break;
645 }
646
588647 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
589648 // a call to it.
590 Function *F = TheModule->getFunction(std::string("binary")+Op);
649 Function *F = TheModule->getFunction(std::string("binary") + Op);
591650 assert(F && "binary operator not found!");
592
651
593652 Value *Ops[] = { L, R };
594653 return Builder.CreateCall(F, Ops, "binop");
595654 }
599658 Function *CalleeF = TheModule->getFunction(Callee);
600659 if (CalleeF == 0)
601660 return ErrorV("Unknown function referenced");
602
661
603662 // If argument mismatch error.
604663 if (CalleeF->arg_size() != Args.size())
605664 return ErrorV("Incorrect # arguments passed");
606665
607 std::vector*> ArgsV;
666 std::vector *> ArgsV;
608667 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
609668 ArgsV.push_back(Args[i]->Codegen());
610 if (ArgsV.back() == 0) return 0;
611 }
612
669 if (ArgsV.back() == 0)
670 return 0;
671 }
672
613673 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
614674 }
615675
616676 Value *IfExprAST::Codegen() {
617677 Value *CondV = Cond->Codegen();
618 if (CondV == 0) return 0;
619
678 if (CondV == 0)
679 return 0;
680
620681 // Convert condition to a bool by comparing equal to 0.0.
621 CondV = Builder.CreateFCmpONE(CondV,
622 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
623 "ifcond");
624
682 CondV = Builder.CreateFCmpONE(
683 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
684
625685 Function *TheFunction = Builder.GetInsertBlock()->getParent();
626
686
627687 // Create blocks for the then and else cases. Insert the 'then' block at the
628688 // end of the function.
629 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
689 BasicBlock *ThenBB =
690 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
630691 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
631692 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
632
693
633694 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
634
695
635696 // Emit then value.
636697 Builder.SetInsertPoint(ThenBB);
637
698
638699 Value *ThenV = Then->Codegen();
639 if (ThenV == 0) return 0;
640
700 if (ThenV == 0)
701 return 0;
702
641703 Builder.CreateBr(MergeBB);
642704 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
643705 ThenBB = Builder.GetInsertBlock();
644
706
645707 // Emit else block.
646708 TheFunction->getBasicBlockList().push_back(ElseBB);
647709 Builder.SetInsertPoint(ElseBB);
648
710
649711 Value *ElseV = Else->Codegen();
650 if (ElseV == 0) return 0;
651
712 if (ElseV == 0)
713 return 0;
714
652715 Builder.CreateBr(MergeBB);
653716 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
654717 ElseBB = Builder.GetInsertBlock();
655
718
656719 // Emit merge block.
657720 TheFunction->getBasicBlockList().push_back(MergeBB);
658721 Builder.SetInsertPoint(MergeBB);
659 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
660 "iftmp");
661
722 PHINode *PN =
723 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
724
662725 PN->addIncoming(ThenV, ThenBB);
663726 PN->addIncoming(ElseV, ElseBB);
664727 return PN;
669732 // ...
670733 // start = startexpr
671734 // goto loop
672 // loop:
735 // loop:
673736 // variable = phi [start, loopheader], [nextvariable, loopend]
674737 // ...
675738 // bodyexpr
680743 // endcond = endexpr
681744 // br endcond, loop, endloop
682745 // outloop:
683
746
684747 // Emit the start code first, without 'variable' in scope.
685748 Value *StartVal = Start->Codegen();
686 if (StartVal == 0) return 0;
687
749 if (StartVal == 0)
750 return 0;
751
688752 // Make the new basic block for the loop header, inserting after current
689753 // block.
690754 Function *TheFunction = Builder.GetInsertBlock()->getParent();
691755 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
692 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
693
756 BasicBlock *LoopBB =
757 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
758
694759 // Insert an explicit fall through from the current block to the LoopBB.
695760 Builder.CreateBr(LoopBB);
696761
697762 // Start insertion in LoopBB.
698763 Builder.SetInsertPoint(LoopBB);
699
764
700765 // Start the PHI node with an entry for Start.
701 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
766 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
767 2, VarName.c_str());
702768 Variable->addIncoming(StartVal, PreheaderBB);
703
769
704770 // Within the loop, the variable is defined equal to the PHI node. If it
705771 // shadows an existing variable, we have to restore it, so save it now.
706772 Value *OldVal = NamedValues[VarName];
707773 NamedValues[VarName] = Variable;
708
774
709775 // Emit the body of the loop. This, like any other expr, can change the
710776 // current BB. Note that we ignore the value computed by the body, but don't
711777 // allow an error.
712778 if (Body->Codegen() == 0)
713779 return 0;
714
780
715781 // Emit the step value.
716782 Value *StepVal;
717783 if (Step) {
718784 StepVal = Step->Codegen();
719 if (StepVal == 0) return 0;
785 if (StepVal == 0)
786 return 0;
720787 } else {
721788 // If not specified, use 1.0.
722789 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
723790 }
724
791
725792 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
726793
727794 // Compute the end condition.
728795 Value *EndCond = End->Codegen();
729 if (EndCond == 0) return EndCond;
730
796 if (EndCond == 0)
797 return EndCond;
798
731799 // Convert condition to a bool by comparing equal to 0.0.
732 EndCond = Builder.CreateFCmpONE(EndCond,
733 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
734 "loopcond");
735
800 EndCond = Builder.CreateFCmpONE(
801 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
802
736803 // Create the "after loop" block and insert it.
737804 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
738 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
739
805 BasicBlock *AfterBB =
806 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
807
740808 // Insert the conditional branch into the end of LoopEndBB.
741809 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
742
810
743811 // Any new code will be inserted in AfterBB.
744812 Builder.SetInsertPoint(AfterBB);
745
813
746814 // Add a new entry to the PHI node for the backedge.
747815 Variable->addIncoming(NextVar, LoopEndBB);
748
816
749817 // Restore the unshadowed variable.
750818 if (OldVal)
751819 NamedValues[VarName] = OldVal;
752820 else
753821 NamedValues.erase(VarName);
754822
755
756823 // for expr always returns 0.0.
757824 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
758825 }
759826
760827 Function *PrototypeAST::Codegen() {
761828 // Make the function type: double(double,double) etc.
762 std::vector Doubles(Args.size(),
763 Type::getDoubleTy(getGlobalContext()));
764 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
765 Doubles, false);
766
767 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
768
829 std::vector Doubles(Args.size(),
830 Type::getDoubleTy(getGlobalContext()));
831 FunctionType *FT =
832 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
833
834 Function *F =
835 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
836
769837 // If F conflicted, there was already something named 'Name'. If it has a
770838 // body, don't allow redefinition or reextern.
771839 if (F->getName() != Name) {
772840 // Delete the one we just made and get the existing one.
773841 F->eraseFromParent();
774842 F = TheModule->getFunction(Name);
775
843
776844 // If F already has a body, reject this.
777845 if (!F->empty()) {
778846 ErrorF("redefinition of function");
779847 return 0;
780848 }
781
849
782850 // If F took a different number of args, reject.
783851 if (F->arg_size() != Args.size()) {
784852 ErrorF("redefinition of function with different # args");
785853 return 0;
786854 }
787855 }
788
856
789857 // Set names for all arguments.
790858 unsigned Idx = 0;
791859 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
792860 ++AI, ++Idx) {
793861 AI->setName(Args[Idx]);
794
862
795863 // Add arguments to variable symbol table.
796864 NamedValues[Args[Idx]] = AI;
797865 }
798
866
799867 return F;
800868 }
801869
802870 Function *FunctionAST::Codegen() {
803871 NamedValues.clear();
804
872
805873 Function *TheFunction = Proto->Codegen();
806874 if (TheFunction == 0)
807875 return 0;
808
876
809877 // If this is an operator, install it.
810878 if (Proto->isBinaryOp())
811879 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
812
880
813881 // Create a new basic block to start insertion into.
814882 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
815883 Builder.SetInsertPoint(BB);
816
884
817885 if (Value *RetVal = Body->Codegen()) {
818886 // Finish off the function.
819887 Builder.CreateRet(RetVal);
823891
824892 // Optimize the function.
825893 TheFPM->run(*TheFunction);
826
894
827895 return TheFunction;
828896 }
829
897
830898 // Error reading body, remove function.
831899 TheFunction->eraseFromParent();
832900
872940 TheExecutionEngine->finalizeObject();
873941 // JIT the function, returning a function pointer.
874942 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
875
943
876944 // Cast it to the right type (takes no arguments, returns a double) so we
877945 // can call it as a native function.
878946 double (*FP)() = (double (*)())(intptr_t)FPtr;
889957 while (1) {
890958 fprintf(stderr, "ready> ");
891959 switch (CurTok) {
892 case tok_eof: return;
893 case ';': getNextToken(); break; // ignore top-level semicolons.
894 case tok_def: HandleDefinition(); break;
895 case tok_extern: HandleExtern(); break;
896 default: HandleTopLevelExpression(); break;
960 case tok_eof:
961 return;
962 case ';':
963 getNextToken();
964 break; // ignore top-level semicolons.
965 case tok_def:
966 HandleDefinition();
967 break;
968 case tok_extern:
969 HandleExtern();
970 break;
971 default:
972 HandleTopLevelExpression();
973 break;
897974 }
898975 }
899976 }
903980 //===----------------------------------------------------------------------===//
904981
905982 /// putchard - putchar that takes a double and returns 0.
906 extern "C"
907 double putchard(double X) {
983 extern "C" double putchard(double X) {
908984 putchar((char)X);
909985 return 0;
910986 }
911987
912988 /// printd - printf that takes a double prints it as "%f\n", returning 0.
913 extern "C"
914 double printd(double X) {
989 extern "C" double printd(double X) {
915990 printf("%f\n", X);
916991 return 0;
917992 }
9311006 BinopPrecedence['<'] = 10;
9321007 BinopPrecedence['+'] = 20;
9331008 BinopPrecedence['-'] = 20;
934 BinopPrecedence['*'] = 40; // highest.
1009 BinopPrecedence['*'] = 40; // highest.
9351010
9361011 // Prime the first token.
9371012 fprintf(stderr, "ready> ");
9431018
9441019 // Create the JIT. This takes ownership of the module.
9451020 std::string ErrStr;
946 TheExecutionEngine = EngineBuilder(std::move(Owner))
947 .setErrorStr(&ErrStr)
948 .setMCJITMemoryManager(new SectionMemoryManager())
949 .create();
1021 TheExecutionEngine =
1022 EngineBuilder(std::move(Owner))
1023 .setErrorStr(&ErrStr)
1024 .setMCJITMemoryManager(llvm::make_unique())
1025 .create();
9501026 if (!TheExecutionEngine) {
9511027 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
9521028 exit(1);
2727 tok_eof = -1,
2828
2929 // commands
30 tok_def = -2, tok_extern = -3,
30 tok_def = -2,
31 tok_extern = -3,
3132
3233 // primary
33 tok_identifier = -4, tok_number = -5,
34
34 tok_identifier = -4,
35 tok_number = -5,
36
3537 // control
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10,
38
38 tok_if = -6,
39 tok_then = -7,
40 tok_else = -8,
41 tok_for = -9,
42 tok_in = -10,
43
3944 // operators
40 tok_binary = -11, tok_unary = -12,
41
45 tok_binary = -11,
46 tok_unary = -12,
47
4248 // var definition
4349 tok_var = -13
4450 };
4551
46 static std::string IdentifierStr; // Filled in if tok_identifier
47 static double NumVal; // Filled in if tok_number
52 static std::string IdentifierStr; // Filled in if tok_identifier
53 static double NumVal; // Filled in if tok_number
4854
4955 /// gettok - Return the next token from standard input.
5056 static int gettok() {
5965 while (isalnum((LastChar = getchar())))
6066 IdentifierStr += LastChar;
6167
62 if (IdentifierStr == "def") return tok_def;
63 if (IdentifierStr == "extern") return tok_extern;
64 if (IdentifierStr == "if") return tok_if;
65 if (IdentifierStr == "then") return tok_then;
66 if (IdentifierStr == "else") return tok_else;
67 if (IdentifierStr == "for") return tok_for;
68 if (IdentifierStr == "in") return tok_in;
69 if (IdentifierStr == "binary") return tok_binary;
70 if (IdentifierStr == "unary") return tok_unary;
71 if (IdentifierStr == "var") return tok_var;
68 if (IdentifierStr == "def")
69 return tok_def;
70 if (IdentifierStr == "extern")
71 return tok_extern;
72 if (IdentifierStr == "if")
73 return tok_if;
74 if (IdentifierStr == "then")
75 return tok_then;
76 if (IdentifierStr == "else")
77 return tok_else;
78 if (IdentifierStr == "for")
79 return tok_for;
80 if (IdentifierStr == "in")
81 return tok_in;
82 if (IdentifierStr == "binary")
83 return tok_binary;
84 if (IdentifierStr == "unary")
85 return tok_unary;
86 if (IdentifierStr == "var")
87 return tok_var;
7288 return tok_identifier;
7389 }
7490
75 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
91 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
7692 std::string NumStr;
7793 do {
7894 NumStr += LastChar;
85101
86102 if (LastChar == '#') {
87103 // Comment until end of line.
88 do LastChar = getchar();
104 do
105 LastChar = getchar();
89106 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
90
107
91108 if (LastChar != EOF)
92109 return gettok();
93110 }
94
111
95112 // Check for end of file. Don't eat the EOF.
96113 if (LastChar == EOF)
97114 return tok_eof;
116133 /// NumberExprAST - Expression class for numeric literals like "1.0".
117134 class NumberExprAST : public ExprAST {
118135 double Val;
136
119137 public:
120138 NumberExprAST(double val) : Val(val) {}
121139 virtual Value *Codegen();
124142 /// VariableExprAST - Expression class for referencing a variable, like "a".
125143 class VariableExprAST : public ExprAST {
126144 std::string Name;
145
127146 public:
128147 VariableExprAST(const std::string &name) : Name(name) {}
129148 const std::string &getName() const { return Name; }
134153 class UnaryExprAST : public ExprAST {
135154 char Opcode;
136155 ExprAST *Operand;
156
137157 public:
138 UnaryExprAST(char opcode, ExprAST *operand)
139 : Opcode(opcode), Operand(operand) {}
158 UnaryExprAST(char opcode, ExprAST *operand)
159 : Opcode(opcode), Operand(operand) {}
140160 virtual Value *Codegen();
141161 };
142162
144164 class BinaryExprAST : public ExprAST {
145165 char Op;
146166 ExprAST *LHS, *RHS;
167
147168 public:
148 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
149 : Op(op), LHS(lhs), RHS(rhs) {}
169 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
170 : Op(op), LHS(lhs), RHS(rhs) {}
150171 virtual Value *Codegen();
151172 };
152173
153174 /// CallExprAST - Expression class for function calls.
154175 class CallExprAST : public ExprAST {
155176 std::string Callee;
156 std::vector*> Args;
177 std::vector *> Args;
178
157179 public:
158 CallExprAST(const std::string &callee, std::vector &args)
159 : Callee(callee), Args(args) {}
180 CallExprAST(const std::string &callee, std::vector &args)
181 : Callee(callee), Args(args) {}
160182 virtual Value *Codegen();
161183 };
162184
163185 /// IfExprAST - Expression class for if/then/else.
164186 class IfExprAST : public ExprAST {
165187 ExprAST *Cond, *Then, *Else;
188
166189 public:
167190 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
168 : Cond(cond), Then(then), Else(_else) {}
191 : Cond(cond), Then(then), Else(_else) {}
169192 virtual Value *Codegen();
170193 };
171194
173196 class ForExprAST : public ExprAST {
174197 std::string VarName;
175198 ExprAST *Start, *End, *Step, *Body;
199
176200 public:
177201 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
178202 ExprAST *step, ExprAST *body)
179 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
203 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
180204 virtual Value *Codegen();
181205 };
182206
183207 /// VarExprAST - Expression class for var/in
184208 class VarExprAST : public ExprAST {
185 std::vector*> > VarNames;
209 std::vector *> > VarNames;
186210 ExprAST *Body;
211
187212 public:
188 VarExprAST(const std::vector*> > &varnames,
213 VarExprAST(const std::vector *> > &varnames,
189214 ExprAST *body)
190 : VarNames(varnames), Body(body) {}
191
215 : VarNames(varnames), Body(body) {}
216
192217 virtual Value *Codegen();
193218 };
194219
198223 std::string Name;
199224 std::vector Args;
200225 bool isOperator;
201 unsigned Precedence; // Precedence if a binary op.
226 unsigned Precedence; // Precedence if a binary op.
202227 public:
203228 PrototypeAST(const std::string &name, const std::vector &args,
204229 bool isoperator = false, unsigned prec = 0)
205 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
206
230 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
231
207232 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
208233 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
209
234
210235 char getOperatorName() const {
211236 assert(isUnaryOp() || isBinaryOp());
212 return Name[Name.size()-1];
213 }
214
237 return Name[Name.size() - 1];
238 }
239
215240 unsigned getBinaryPrecedence() const { return Precedence; }
216
241
217242 Function *Codegen();
218
243
219244 void CreateArgumentAllocas(Function *F);
220245 };
221246
223248 class FunctionAST {
224249 PrototypeAST *Proto;
225250 ExprAST *Body;
251
226252 public:
227 FunctionAST(PrototypeAST *proto, ExprAST *body)
228 : Proto(proto), Body(body) {}
229
253 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
254
230255 Function *Codegen();
231256 };
232257 } // end anonymous namespace
239264 /// token the parser is looking at. getNextToken reads another token from the
240265 /// lexer and updates CurTok with its results.
241266 static int CurTok;
242 static int getNextToken() {
243 return CurTok = gettok();
244 }
267 static int getNextToken() { return CurTok = gettok(); }
245268
246269 /// BinopPrecedence - This holds the precedence for each binary operator that is
247270 /// defined.
251274 static int GetTokPrecedence() {
252275 if (!isascii(CurTok))
253276 return -1;
254
277
255278 // Make sure it's a declared binop.
256279 int TokPrec = BinopPrecedence[CurTok];
257 if (TokPrec <= 0) return -1;
280 if (TokPrec <= 0)
281 return -1;
258282 return TokPrec;
259283 }
260284
261285 /// Error* - These are little helper functions for error handling.
262 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
263 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
264 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
286 ExprAST *Error(const char *Str) {
287 fprintf(stderr, "Error: %s\n", Str);
288 return 0;
289 }
290 PrototypeAST *ErrorP(const char *Str) {
291 Error(Str);
292 return 0;
293 }
294 FunctionAST *ErrorF(const char *Str) {
295 Error(Str);
296 return 0;
297 }
265298
266299 static ExprAST *ParseExpression();
267300
270303 /// ::= identifier '(' expression* ')'
271304 static ExprAST *ParseIdentifierExpr() {
272305 std::string IdName = IdentifierStr;
273
274 getNextToken(); // eat identifier.
275
306
307 getNextToken(); // eat identifier.
308
276309 if (CurTok != '(') // Simple variable ref.
277310 return new VariableExprAST(IdName);
278
311
279312 // Call.
280 getNextToken(); // eat (
281 std::vector Args;
313 getNextToken(); // eat (
314 std::vector Args;
282315 if (CurTok != ')') {
283316 while (1) {
284317 ExprAST *Arg = ParseExpression();
285 if (!Arg) return 0;
318 if (!Arg)
319 return 0;
286320 Args.push_back(Arg);
287321
288 if (CurTok == ')') break;
322 if (CurTok == ')')
323 break;
289324
290325 if (CurTok != ',')
291326 return Error("Expected ')' or ',' in argument list");
295330
296331 // Eat the ')'.
297332 getNextToken();
298
333
299334 return new CallExprAST(IdName, Args);
300335 }
301336
308343
309344 /// parenexpr ::= '(' expression ')'
310345 static ExprAST *ParseParenExpr() {
311 getNextToken(); // eat (.
346 getNextToken(); // eat (.
312347 ExprAST *V = ParseExpression();
313 if (!V) return 0;
314
348 if (!V)
349 return 0;
350
315351 if (CurTok != ')')
316352 return Error("expected ')'");
317 getNextToken(); // eat ).
353 getNextToken(); // eat ).
318354 return V;
319355 }
320356
321357 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
322358 static ExprAST *ParseIfExpr() {
323 getNextToken(); // eat the if.
324
359 getNextToken(); // eat the if.
360
325361 // condition.
326362 ExprAST *Cond = ParseExpression();
327 if (!Cond) return 0;
328
363 if (!Cond)
364 return 0;
365
329366 if (CurTok != tok_then)
330367 return Error("expected then");
331 getNextToken(); // eat the then
332
368 getNextToken(); // eat the then
369
333370 ExprAST *Then = ParseExpression();
334 if (Then == 0) return 0;
335
371 if (Then == 0)
372 return 0;
373
336374 if (CurTok != tok_else)
337375 return Error("expected else");
338
376
339377 getNextToken();
340
378
341379 ExprAST *Else = ParseExpression();
342 if (!Else) return 0;
343
380 if (!Else)
381 return 0;
382
344383 return new IfExprAST(Cond, Then, Else);
345384 }
346385
347386 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
348387 static ExprAST *ParseForExpr() {
349 getNextToken(); // eat the for.
388 getNextToken(); // eat the for.
350389
351390 if (CurTok != tok_identifier)
352391 return Error("expected identifier after for");
353
392
354393 std::string IdName = IdentifierStr;
355 getNextToken(); // eat identifier.
356
394 getNextToken(); // eat identifier.
395
357396 if (CurTok != '=')
358397 return Error("expected '=' after for");
359 getNextToken(); // eat '='.
360
361
398 getNextToken(); // eat '='.
399
362400 ExprAST *Start = ParseExpression();
363 if (Start == 0) return 0;
401 if (Start == 0)
402 return 0;
364403 if (CurTok != ',')
365404 return Error("expected ',' after for start value");
366405 getNextToken();
367
406
368407 ExprAST *End = ParseExpression();
369 if (End == 0) return 0;
370
408 if (End == 0)
409 return 0;
410
371411 // The step value is optional.
372412 ExprAST *Step = 0;
373413 if (CurTok == ',') {
374414 getNextToken();
375415 Step = ParseExpression();
376 if (Step == 0) return 0;
377 }
378
416 if (Step == 0)
417 return 0;
418 }
419
379420 if (CurTok != tok_in)
380421 return Error("expected 'in' after for");
381 getNextToken(); // eat 'in'.
382
422 getNextToken(); // eat 'in'.
423
383424 ExprAST *Body = ParseExpression();
384 if (Body == 0) return 0;
425 if (Body == 0)
426 return 0;
385427
386428 return new ForExprAST(IdName, Start, End, Step, Body);
387429 }
388430
389 /// varexpr ::= 'var' identifier ('=' expression)?
431 /// varexpr ::= 'var' identifier ('=' expression)?
390432 // (',' identifier ('=' expression)?)* 'in' expression
391433 static ExprAST *ParseVarExpr() {
392 getNextToken(); // eat the var.
393
394 std::vector > VarNames;
434 getNextToken(); // eat the var.
435
436 std::vector > VarNames;
395437
396438 // At least one variable name is required.
397439 if (CurTok != tok_identifier)
398440 return Error("expected identifier after var");
399
441
400442 while (1) {
401443 std::string Name = IdentifierStr;
402 getNextToken(); // eat identifier.
444 getNextToken(); // eat identifier.
403445
404446 // Read the optional initializer.
405447 ExprAST *Init = 0;
406448 if (CurTok == '=') {
407449 getNextToken(); // eat the '='.
408
450
409451 Init = ParseExpression();
410 if (Init == 0) return 0;
452 if (Init == 0)
453 return 0;
411454 }
412
455
413456 VarNames.push_back(std::make_pair(Name, Init));
414
457
415458 // End of var list, exit loop.
416 if (CurTok != ',') break;
459 if (CurTok != ',')
460 break;
417461 getNextToken(); // eat the ','.
418
462
419463 if (CurTok != tok_identifier)
420464 return Error("expected identifier list after var");
421465 }
422
466
423467 // At this point, we have to have 'in'.
424468 if (CurTok != tok_in)
425469 return Error("expected 'in' keyword after 'var'");
426 getNextToken(); // eat 'in'.
427
470 getNextToken(); // eat 'in'.
471
428472 ExprAST *Body = ParseExpression();
429 if (Body == 0) return 0;
430
473 if (Body == 0)
474 return 0;
475
431476 return new VarExprAST(VarNames, Body);
432477 }
433478
440485 /// ::= varexpr
441486 static ExprAST *ParsePrimary() {
442487 switch (CurTok) {
443 default: return Error("unknown token when expecting an expression");
444 case tok_identifier: return ParseIdentifierExpr();
445 case tok_number: return ParseNumberExpr();
446 case '(': return ParseParenExpr();
447 case tok_if: return ParseIfExpr();
448 case tok_for: return ParseForExpr();
449 case tok_var: return ParseVarExpr();
488 default:
489 return Error("unknown token when expecting an expression");
490 case tok_identifier:
491 return ParseIdentifierExpr();
492 case tok_number:
493 return ParseNumberExpr();
494 case '(':
495 return ParseParenExpr();
496 case tok_if:
497 return ParseIfExpr();
498 case tok_for:
499 return ParseForExpr();
500 case tok_var:
501 return ParseVarExpr();
450502 }
451503 }
452504
457509 // If the current token is not an operator, it must be a primary expr.
458510 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
459511 return ParsePrimary();
460
512
461513 // If this is a unary operator, read it.
462514 int Opc = CurTok;
463515 getNextToken();
472524 // If this is a binop, find its precedence.
473525 while (1) {
474526 int TokPrec = GetTokPrecedence();
475
527
476528 // If this is a binop that binds at least as tightly as the current binop,
477529 // consume it, otherwise we are done.
478530 if (TokPrec < ExprPrec)
479531 return LHS;
480
532
481533 // Okay, we know this is a binop.
482534 int BinOp = CurTok;
483 getNextToken(); // eat binop
484
535 getNextToken(); // eat binop
536
485537 // Parse the unary expression after the binary operator.
486538 ExprAST *RHS = ParseUnary();
487 if (!RHS) return 0;
488
539 if (!RHS)
540 return 0;
541
489542 // If BinOp binds less tightly with RHS than the operator after RHS, let
490543 // the pending operator take RHS as its LHS.
491544 int NextPrec = GetTokPrecedence();
492545 if (TokPrec < NextPrec) {
493 RHS = ParseBinOpRHS(TokPrec+1, RHS);
494 if (RHS == 0) return 0;
546 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
547 if (RHS == 0)
548 return 0;
495549 }
496
550
497551 // Merge LHS/RHS.
498552 LHS = new BinaryExprAST(BinOp, LHS, RHS);
499553 }
504558 ///
505559 static ExprAST *ParseExpression() {
506560 ExprAST *LHS = ParseUnary();
507 if (!LHS) return 0;
508
561 if (!LHS)
562 return 0;
563
509564 return ParseBinOpRHS(0, LHS);
510565 }
511566
515570 /// ::= unary LETTER (id)
516571 static PrototypeAST *ParsePrototype() {
517572 std::string FnName;
518
573
519574 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
520575 unsigned BinaryPrecedence = 30;
521
576
522577 switch (CurTok) {
523578 default:
524579 return ErrorP("Expected function name in prototype");
544599 FnName += (char)CurTok;
545600 Kind = 2;
546601 getNextToken();
547
602
548603 // Read the precedence if present.
549604 if (CurTok == tok_number) {
550605 if (NumVal < 1 || NumVal > 100)
554609 }
555610 break;
556611 }
557
612
558613 if (CurTok != '(')
559614 return ErrorP("Expected '(' in prototype");
560
615
561616 std::vector ArgNames;
562617 while (getNextToken() == tok_identifier)
563618 ArgNames.push_back(IdentifierStr);
564619 if (CurTok != ')')
565620 return ErrorP("Expected ')' in prototype");
566
621
567622 // success.
568 getNextToken(); // eat ')'.
569
623 getNextToken(); // eat ')'.
624
570625 // Verify right number of names for operator.
571626 if (Kind && ArgNames.size() != Kind)
572627 return ErrorP("Invalid number of operands for operator");
573
628
574629 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
575630 }
576631
577632 /// definition ::= 'def' prototype expression
578633 static FunctionAST *ParseDefinition() {
579 getNextToken(); // eat def.
634 getNextToken(); // eat def.
580635 PrototypeAST *Proto = ParsePrototype();
581 if (Proto == 0) return 0;
636 if (Proto == 0)
637 return 0;
582638
583639 if (ExprAST *E = ParseExpression())
584640 return new FunctionAST(Proto, E);
597653
598654 /// external ::= 'extern' prototype
599655 static PrototypeAST *ParseExtern() {
600 getNextToken(); // eat extern.
656 getNextToken(); // eat extern.
601657 return ParsePrototype();
602658 }
603659
607663
608664 static Module *TheModule;
609665 static IRBuilder<> Builder(getGlobalContext());
610 static std::map*> NamedValues;
666 static std::map *> NamedValues;
611667 static FunctionPassManager *TheFPM;
612668
613 Value *ErrorV(const char *Str) { Error(Str); return 0; }
669 Value *ErrorV(const char *Str) {
670 Error(Str);
671 return 0;
672 }
614673
615674 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
616675 /// the function. This is used for mutable variables etc.
617676 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
618677 const std::string &VarName) {
619678 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
620 TheFunction->getEntryBlock().begin());
679 TheFunction->getEntryBlock().begin());
621680 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
622681 VarName.c_str());
623682 }
629688 Value *VariableExprAST::Codegen() {
630689 // Look this variable up in the function.
631690 Value *V = NamedValues[Name];
632 if (V == 0) return ErrorV("Unknown variable name");
691 if (V == 0)
692 return ErrorV("Unknown variable name");
633693
634694 // Load the value.
635695 return Builder.CreateLoad(V, Name.c_str());
637697
638698 Value *UnaryExprAST::Codegen() {
639699 Value *OperandV = Operand->Codegen();
640 if (OperandV == 0) return 0;
641
642 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
700 if (OperandV == 0)
701 return 0;
702
703 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
643704 if (F == 0)
644705 return ErrorV("Unknown unary operator");
645
706
646707 return Builder.CreateCall(F, OperandV, "unop");
647708 }
648709
650711 // Special case '=' because we don't want to emit the LHS as an expression.
651712 if (Op == '=') {
652713 // Assignment requires the LHS to be an identifier.
653 VariableExprAST *LHSE = dynamic_cast*>(LHS);
714 VariableExprAST *LHSE = dynamic_cast *>(LHS);
654715 if (!LHSE)
655716 return ErrorV("destination of '=' must be a variable");
656717 // Codegen the RHS.
657718 Value *Val = RHS->Codegen();
658 if (Val == 0) return 0;
719 if (Val == 0)
720 return 0;
659721
660722 // Look up the name.
661723 Value *Variable = NamedValues[LHSE->getName()];
662 if (Variable == 0) return ErrorV("Unknown variable name");
724 if (Variable == 0)
725 return ErrorV("Unknown variable name");
663726
664727 Builder.CreateStore(Val, Variable);
665728 return Val;
666729 }
667
730
668731 Value *L = LHS->Codegen();
669732 Value *R = RHS->Codegen();
670 if (L == 0 || R == 0) return 0;
671
733 if (L == 0 || R == 0)
734 return 0;
735
672736 switch (Op) {
673 case '+': return Builder.CreateFAdd(L, R, "addtmp");
674 case '-': return Builder.CreateFSub(L, R, "subtmp");
675 case '*': return Builder.CreateFMul(L, R, "multmp");
737 case '+':
738 return Builder.CreateFAdd(L, R, "addtmp");
739 case '-':
740 return Builder.CreateFSub(L, R, "subtmp");
741 case '*':
742 return Builder.CreateFMul(L, R, "multmp");
676743 case '<':
677744 L = Builder.CreateFCmpULT(L, R, "cmptmp");
678745 // Convert bool 0/1 to double 0.0 or 1.0
679746 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
680747 "booltmp");
681 default: break;
682 }
683
748 default:
749 break;
750 }
751
684752 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
685753 // a call to it.
686 Function *F = TheModule->getFunction(std::string("binary")+Op);
754 Function *F = TheModule->getFunction(std::string("binary") + Op);
687755 assert(F && "binary operator not found!");
688
756
689757 Value *Ops[] = { L, R };
690758 return Builder.CreateCall(F, Ops, "binop");
691759 }
695763 Function *CalleeF = TheModule->getFunction(Callee);
696764 if (CalleeF == 0)
697765 return ErrorV("Unknown function referenced");
698
766
699767 // If argument mismatch error.
700768 if (CalleeF->arg_size() != Args.size())
701769 return ErrorV("Incorrect # arguments passed");
702770
703 std::vector*> ArgsV;
771 std::vector *> ArgsV;
704772 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
705773 ArgsV.push_back(Args[i]->Codegen());
706 if (ArgsV.back() == 0) return 0;
707 }
708
774 if (ArgsV.back() == 0)
775 return 0;
776 }
777
709778 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
710779 }
711780
712781 Value *IfExprAST::Codegen() {
713782 Value *CondV = Cond->Codegen();
714 if (CondV == 0) return 0;
715
783 if (CondV == 0)
784 return 0;
785
716786 // Convert condition to a bool by comparing equal to 0.0.
717 CondV = Builder.CreateFCmpONE(CondV,
718 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
719 "ifcond");
720
787 CondV = Builder.CreateFCmpONE(
788 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
789
721790 Function *TheFunction = Builder.GetInsertBlock()->getParent();
722
791
723792 // Create blocks for the then and else cases. Insert the 'then' block at the
724793 // end of the function.
725 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
794 BasicBlock *ThenBB =
795 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
726796 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
727797 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
728
798
729799 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
730
800
731801 // Emit then value.
732802 Builder.SetInsertPoint(ThenBB);
733
803
734804 Value *ThenV = Then->Codegen();
735 if (ThenV == 0) return 0;
736
805 if (ThenV == 0)
806 return 0;
807
737808 Builder.CreateBr(MergeBB);
738809 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
739810 ThenBB = Builder.GetInsertBlock();
740 </