blob: 8b0c321c06c5d310848af35d975ecaed306cc02a [file] [log] [blame]
Nick Lewycky9f856342009-04-12 20:47:23 +00001#include "llvm/DerivedTypes.h"
2#include "llvm/ExecutionEngine/ExecutionEngine.h"
Xerxes Ranby6ce6daa2009-07-19 08:10:01 +00003#include "llvm/ExecutionEngine/Interpreter.h"
4#include "llvm/ExecutionEngine/JIT.h"
Owen Anderson8b477ed2009-07-01 16:58:40 +00005#include "llvm/LLVMContext.h"
Nick Lewycky9f856342009-04-12 20:47:23 +00006#include "llvm/Module.h"
7#include "llvm/ModuleProvider.h"
8#include "llvm/PassManager.h"
9#include "llvm/Analysis/Verifier.h"
10#include "llvm/Target/TargetData.h"
Chris Lattnerda062882009-06-17 16:48:44 +000011#include "llvm/Target/TargetSelect.h"
Nick Lewycky9f856342009-04-12 20:47:23 +000012#include "llvm/Transforms/Scalar.h"
13#include "llvm/Support/IRBuilder.h"
14#include <cstdio>
15#include <string>
16#include <map>
17#include <vector>
18using namespace llvm;
19
20//===----------------------------------------------------------------------===//
21// Lexer
22//===----------------------------------------------------------------------===//
23
24// The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25// of these for known things.
26enum Token {
27 tok_eof = -1,
28
29 // commands
30 tok_def = -2, tok_extern = -3,
31
32 // primary
33 tok_identifier = -4, tok_number = -5,
34
35 // control
36 tok_if = -6, tok_then = -7, tok_else = -8,
37 tok_for = -9, tok_in = -10,
38
39 // operators
40 tok_binary = -11, tok_unary = -12,
41
42 // var definition
43 tok_var = -13
44};
45
46static std::string IdentifierStr; // Filled in if tok_identifier
47static double NumVal; // Filled in if tok_number
48
49/// gettok - Return the next token from standard input.
50static int gettok() {
51 static int LastChar = ' ';
52
53 // Skip any whitespace.
54 while (isspace(LastChar))
55 LastChar = getchar();
56
57 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
58 IdentifierStr = LastChar;
59 while (isalnum((LastChar = getchar())))
60 IdentifierStr += LastChar;
61
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;
72 return tok_identifier;
73 }
74
75 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
76 std::string NumStr;
77 do {
78 NumStr += LastChar;
79 LastChar = getchar();
80 } while (isdigit(LastChar) || LastChar == '.');
81
82 NumVal = strtod(NumStr.c_str(), 0);
83 return tok_number;
84 }
85
86 if (LastChar == '#') {
87 // Comment until end of line.
88 do LastChar = getchar();
89 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
90
91 if (LastChar != EOF)
92 return gettok();
93 }
94
95 // Check for end of file. Don't eat the EOF.
96 if (LastChar == EOF)
97 return tok_eof;
98
99 // Otherwise, just return the character as its ascii value.
100 int ThisChar = LastChar;
101 LastChar = getchar();
102 return ThisChar;
103}
104
105//===----------------------------------------------------------------------===//
106// Abstract Syntax Tree (aka Parse Tree)
107//===----------------------------------------------------------------------===//
108
109/// ExprAST - Base class for all expression nodes.
110class ExprAST {
111public:
112 virtual ~ExprAST() {}
113 virtual Value *Codegen() = 0;
114};
115
116/// NumberExprAST - Expression class for numeric literals like "1.0".
117class NumberExprAST : public ExprAST {
118 double Val;
119public:
120 NumberExprAST(double val) : Val(val) {}
121 virtual Value *Codegen();
122};
123
124/// VariableExprAST - Expression class for referencing a variable, like "a".
125class VariableExprAST : public ExprAST {
126 std::string Name;
127public:
128 VariableExprAST(const std::string &name) : Name(name) {}
129 const std::string &getName() const { return Name; }
130 virtual Value *Codegen();
131};
132
133/// UnaryExprAST - Expression class for a unary operator.
134class UnaryExprAST : public ExprAST {
135 char Opcode;
136 ExprAST *Operand;
137public:
138 UnaryExprAST(char opcode, ExprAST *operand)
139 : Opcode(opcode), Operand(operand) {}
140 virtual Value *Codegen();
141};
142
143/// BinaryExprAST - Expression class for a binary operator.
144class BinaryExprAST : public ExprAST {
145 char Op;
146 ExprAST *LHS, *RHS;
147public:
148 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
149 : Op(op), LHS(lhs), RHS(rhs) {}
150 virtual Value *Codegen();
151};
152
153/// CallExprAST - Expression class for function calls.
154class CallExprAST : public ExprAST {
155 std::string Callee;
156 std::vector<ExprAST*> Args;
157public:
158 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
159 : Callee(callee), Args(args) {}
160 virtual Value *Codegen();
161};
162
163/// IfExprAST - Expression class for if/then/else.
164class IfExprAST : public ExprAST {
165 ExprAST *Cond, *Then, *Else;
166public:
167 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
168 : Cond(cond), Then(then), Else(_else) {}
169 virtual Value *Codegen();
170};
171
172/// ForExprAST - Expression class for for/in.
173class ForExprAST : public ExprAST {
174 std::string VarName;
175 ExprAST *Start, *End, *Step, *Body;
176public:
177 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
178 ExprAST *step, ExprAST *body)
179 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
180 virtual Value *Codegen();
181};
182
183/// VarExprAST - Expression class for var/in
184class VarExprAST : public ExprAST {
185 std::vector<std::pair<std::string, ExprAST*> > VarNames;
186 ExprAST *Body;
187public:
188 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
189 ExprAST *body)
190 : VarNames(varnames), Body(body) {}
191
192 virtual Value *Codegen();
193};
194
195/// PrototypeAST - This class represents the "prototype" for a function,
196/// which captures its argument names as well as if it is an operator.
197class PrototypeAST {
198 std::string Name;
199 std::vector<std::string> Args;
200 bool isOperator;
201 unsigned Precedence; // Precedence if a binary op.
202public:
203 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
204 bool isoperator = false, unsigned prec = 0)
205 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
206
207 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
208 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
209
210 char getOperatorName() const {
211 assert(isUnaryOp() || isBinaryOp());
212 return Name[Name.size()-1];
213 }
214
215 unsigned getBinaryPrecedence() const { return Precedence; }
216
217 Function *Codegen();
218
219 void CreateArgumentAllocas(Function *F);
220};
221
222/// FunctionAST - This class represents a function definition itself.
223class FunctionAST {
224 PrototypeAST *Proto;
225 ExprAST *Body;
226public:
227 FunctionAST(PrototypeAST *proto, ExprAST *body)
228 : Proto(proto), Body(body) {}
229
230 Function *Codegen();
231};
232
233//===----------------------------------------------------------------------===//
234// Parser
235//===----------------------------------------------------------------------===//
236
237/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000238/// token the parser is looking at. getNextToken reads another token from the
Nick Lewycky9f856342009-04-12 20:47:23 +0000239/// lexer and updates CurTok with its results.
240static int CurTok;
241static int getNextToken() {
242 return CurTok = gettok();
243}
244
245/// BinopPrecedence - This holds the precedence for each binary operator that is
246/// defined.
247static std::map<char, int> BinopPrecedence;
248
249/// GetTokPrecedence - Get the precedence of the pending binary operator token.
250static int GetTokPrecedence() {
251 if (!isascii(CurTok))
252 return -1;
253
254 // Make sure it's a declared binop.
255 int TokPrec = BinopPrecedence[CurTok];
256 if (TokPrec <= 0) return -1;
257 return TokPrec;
258}
259
260/// Error* - These are little helper functions for error handling.
261ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
262PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
263FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
264
265static ExprAST *ParseExpression();
266
267/// identifierexpr
268/// ::= identifier
269/// ::= identifier '(' expression* ')'
270static ExprAST *ParseIdentifierExpr() {
271 std::string IdName = IdentifierStr;
272
273 getNextToken(); // eat identifier.
274
275 if (CurTok != '(') // Simple variable ref.
276 return new VariableExprAST(IdName);
277
278 // Call.
279 getNextToken(); // eat (
280 std::vector<ExprAST*> Args;
281 if (CurTok != ')') {
282 while (1) {
283 ExprAST *Arg = ParseExpression();
284 if (!Arg) return 0;
285 Args.push_back(Arg);
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000286
Nick Lewycky9f856342009-04-12 20:47:23 +0000287 if (CurTok == ')') break;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000288
Nick Lewycky9f856342009-04-12 20:47:23 +0000289 if (CurTok != ',')
290 return Error("Expected ')' or ',' in argument list");
291 getNextToken();
292 }
293 }
294
295 // Eat the ')'.
296 getNextToken();
297
298 return new CallExprAST(IdName, Args);
299}
300
301/// numberexpr ::= number
302static ExprAST *ParseNumberExpr() {
303 ExprAST *Result = new NumberExprAST(NumVal);
304 getNextToken(); // consume the number
305 return Result;
306}
307
308/// parenexpr ::= '(' expression ')'
309static ExprAST *ParseParenExpr() {
310 getNextToken(); // eat (.
311 ExprAST *V = ParseExpression();
312 if (!V) return 0;
313
314 if (CurTok != ')')
315 return Error("expected ')'");
316 getNextToken(); // eat ).
317 return V;
318}
319
320/// ifexpr ::= 'if' expression 'then' expression 'else' expression
321static ExprAST *ParseIfExpr() {
322 getNextToken(); // eat the if.
323
324 // condition.
325 ExprAST *Cond = ParseExpression();
326 if (!Cond) return 0;
327
328 if (CurTok != tok_then)
329 return Error("expected then");
330 getNextToken(); // eat the then
331
332 ExprAST *Then = ParseExpression();
333 if (Then == 0) return 0;
334
335 if (CurTok != tok_else)
336 return Error("expected else");
337
338 getNextToken();
339
340 ExprAST *Else = ParseExpression();
341 if (!Else) return 0;
342
343 return new IfExprAST(Cond, Then, Else);
344}
345
346/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
347static ExprAST *ParseForExpr() {
348 getNextToken(); // eat the for.
349
350 if (CurTok != tok_identifier)
351 return Error("expected identifier after for");
352
353 std::string IdName = IdentifierStr;
354 getNextToken(); // eat identifier.
355
356 if (CurTok != '=')
357 return Error("expected '=' after for");
358 getNextToken(); // eat '='.
359
360
361 ExprAST *Start = ParseExpression();
362 if (Start == 0) return 0;
363 if (CurTok != ',')
364 return Error("expected ',' after for start value");
365 getNextToken();
366
367 ExprAST *End = ParseExpression();
368 if (End == 0) return 0;
369
370 // The step value is optional.
371 ExprAST *Step = 0;
372 if (CurTok == ',') {
373 getNextToken();
374 Step = ParseExpression();
375 if (Step == 0) return 0;
376 }
377
378 if (CurTok != tok_in)
379 return Error("expected 'in' after for");
380 getNextToken(); // eat 'in'.
381
382 ExprAST *Body = ParseExpression();
383 if (Body == 0) return 0;
384
385 return new ForExprAST(IdName, Start, End, Step, Body);
386}
387
388/// varexpr ::= 'var' identifier ('=' expression)?
389// (',' identifier ('=' expression)?)* 'in' expression
390static ExprAST *ParseVarExpr() {
391 getNextToken(); // eat the var.
392
393 std::vector<std::pair<std::string, ExprAST*> > VarNames;
394
395 // At least one variable name is required.
396 if (CurTok != tok_identifier)
397 return Error("expected identifier after var");
398
399 while (1) {
400 std::string Name = IdentifierStr;
401 getNextToken(); // eat identifier.
402
403 // Read the optional initializer.
404 ExprAST *Init = 0;
405 if (CurTok == '=') {
406 getNextToken(); // eat the '='.
407
408 Init = ParseExpression();
409 if (Init == 0) return 0;
410 }
411
412 VarNames.push_back(std::make_pair(Name, Init));
413
414 // End of var list, exit loop.
415 if (CurTok != ',') break;
416 getNextToken(); // eat the ','.
417
418 if (CurTok != tok_identifier)
419 return Error("expected identifier list after var");
420 }
421
422 // At this point, we have to have 'in'.
423 if (CurTok != tok_in)
424 return Error("expected 'in' keyword after 'var'");
425 getNextToken(); // eat 'in'.
426
427 ExprAST *Body = ParseExpression();
428 if (Body == 0) return 0;
429
430 return new VarExprAST(VarNames, Body);
431}
432
Nick Lewycky9f856342009-04-12 20:47:23 +0000433/// primary
434/// ::= identifierexpr
435/// ::= numberexpr
436/// ::= parenexpr
437/// ::= ifexpr
438/// ::= forexpr
439/// ::= varexpr
440static ExprAST *ParsePrimary() {
441 switch (CurTok) {
442 default: return Error("unknown token when expecting an expression");
443 case tok_identifier: return ParseIdentifierExpr();
444 case tok_number: return ParseNumberExpr();
445 case '(': return ParseParenExpr();
446 case tok_if: return ParseIfExpr();
447 case tok_for: return ParseForExpr();
448 case tok_var: return ParseVarExpr();
449 }
450}
451
452/// unary
453/// ::= primary
454/// ::= '!' unary
455static ExprAST *ParseUnary() {
456 // If the current token is not an operator, it must be a primary expr.
457 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
458 return ParsePrimary();
459
460 // If this is a unary operator, read it.
461 int Opc = CurTok;
462 getNextToken();
463 if (ExprAST *Operand = ParseUnary())
464 return new UnaryExprAST(Opc, Operand);
465 return 0;
466}
467
468/// binoprhs
469/// ::= ('+' unary)*
470static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
471 // If this is a binop, find its precedence.
472 while (1) {
473 int TokPrec = GetTokPrecedence();
474
475 // If this is a binop that binds at least as tightly as the current binop,
476 // consume it, otherwise we are done.
477 if (TokPrec < ExprPrec)
478 return LHS;
479
480 // Okay, we know this is a binop.
481 int BinOp = CurTok;
482 getNextToken(); // eat binop
483
484 // Parse the unary expression after the binary operator.
485 ExprAST *RHS = ParseUnary();
486 if (!RHS) return 0;
487
488 // If BinOp binds less tightly with RHS than the operator after RHS, let
489 // the pending operator take RHS as its LHS.
490 int NextPrec = GetTokPrecedence();
491 if (TokPrec < NextPrec) {
492 RHS = ParseBinOpRHS(TokPrec+1, RHS);
493 if (RHS == 0) return 0;
494 }
495
496 // Merge LHS/RHS.
497 LHS = new BinaryExprAST(BinOp, LHS, RHS);
498 }
499}
500
501/// expression
502/// ::= unary binoprhs
503///
504static ExprAST *ParseExpression() {
505 ExprAST *LHS = ParseUnary();
506 if (!LHS) return 0;
507
508 return ParseBinOpRHS(0, LHS);
509}
510
511/// prototype
512/// ::= id '(' id* ')'
513/// ::= binary LETTER number? (id, id)
514/// ::= unary LETTER (id)
515static PrototypeAST *ParsePrototype() {
516 std::string FnName;
517
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000518 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
Nick Lewycky9f856342009-04-12 20:47:23 +0000519 unsigned BinaryPrecedence = 30;
520
521 switch (CurTok) {
522 default:
523 return ErrorP("Expected function name in prototype");
524 case tok_identifier:
525 FnName = IdentifierStr;
526 Kind = 0;
527 getNextToken();
528 break;
529 case tok_unary:
530 getNextToken();
531 if (!isascii(CurTok))
532 return ErrorP("Expected unary operator");
533 FnName = "unary";
534 FnName += (char)CurTok;
535 Kind = 1;
536 getNextToken();
537 break;
538 case tok_binary:
539 getNextToken();
540 if (!isascii(CurTok))
541 return ErrorP("Expected binary operator");
542 FnName = "binary";
543 FnName += (char)CurTok;
544 Kind = 2;
545 getNextToken();
546
547 // Read the precedence if present.
548 if (CurTok == tok_number) {
549 if (NumVal < 1 || NumVal > 100)
550 return ErrorP("Invalid precedecnce: must be 1..100");
551 BinaryPrecedence = (unsigned)NumVal;
552 getNextToken();
553 }
554 break;
555 }
556
557 if (CurTok != '(')
558 return ErrorP("Expected '(' in prototype");
559
560 std::vector<std::string> ArgNames;
561 while (getNextToken() == tok_identifier)
562 ArgNames.push_back(IdentifierStr);
563 if (CurTok != ')')
564 return ErrorP("Expected ')' in prototype");
565
566 // success.
567 getNextToken(); // eat ')'.
568
569 // Verify right number of names for operator.
570 if (Kind && ArgNames.size() != Kind)
571 return ErrorP("Invalid number of operands for operator");
572
573 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
574}
575
576/// definition ::= 'def' prototype expression
577static FunctionAST *ParseDefinition() {
578 getNextToken(); // eat def.
579 PrototypeAST *Proto = ParsePrototype();
580 if (Proto == 0) return 0;
581
582 if (ExprAST *E = ParseExpression())
583 return new FunctionAST(Proto, E);
584 return 0;
585}
586
587/// toplevelexpr ::= expression
588static FunctionAST *ParseTopLevelExpr() {
589 if (ExprAST *E = ParseExpression()) {
590 // Make an anonymous proto.
591 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
592 return new FunctionAST(Proto, E);
593 }
594 return 0;
595}
596
597/// external ::= 'extern' prototype
598static PrototypeAST *ParseExtern() {
599 getNextToken(); // eat extern.
600 return ParsePrototype();
601}
602
603//===----------------------------------------------------------------------===//
604// Code Generation
605//===----------------------------------------------------------------------===//
606
607static Module *TheModule;
Owen Andersond1fbd142009-07-08 20:50:47 +0000608static IRBuilder<> Builder(getGlobalContext());
Nick Lewycky9f856342009-04-12 20:47:23 +0000609static std::map<std::string, AllocaInst*> NamedValues;
610static FunctionPassManager *TheFPM;
611
612Value *ErrorV(const char *Str) { Error(Str); return 0; }
613
614/// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
615/// the function. This is used for mutable variables etc.
616static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
617 const std::string &VarName) {
618 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
619 TheFunction->getEntryBlock().begin());
Owen Anderson1d0be152009-08-13 21:58:54 +0000620 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
621 VarName.c_str());
Nick Lewycky9f856342009-04-12 20:47:23 +0000622}
623
Nick Lewycky9f856342009-04-12 20:47:23 +0000624Value *NumberExprAST::Codegen() {
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000625 return ConstantFP::get(getGlobalContext(), APFloat(Val));
Nick Lewycky9f856342009-04-12 20:47:23 +0000626}
627
628Value *VariableExprAST::Codegen() {
629 // Look this variable up in the function.
630 Value *V = NamedValues[Name];
631 if (V == 0) return ErrorV("Unknown variable name");
632
633 // Load the value.
634 return Builder.CreateLoad(V, Name.c_str());
635}
636
637Value *UnaryExprAST::Codegen() {
638 Value *OperandV = Operand->Codegen();
639 if (OperandV == 0) return 0;
640
641 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
642 if (F == 0)
643 return ErrorV("Unknown unary operator");
644
645 return Builder.CreateCall(F, OperandV, "unop");
646}
647
Nick Lewycky9f856342009-04-12 20:47:23 +0000648Value *BinaryExprAST::Codegen() {
649 // Special case '=' because we don't want to emit the LHS as an expression.
650 if (Op == '=') {
651 // Assignment requires the LHS to be an identifier.
652 VariableExprAST *LHSE = dynamic_cast<VariableExprAST*>(LHS);
653 if (!LHSE)
654 return ErrorV("destination of '=' must be a variable");
655 // Codegen the RHS.
656 Value *Val = RHS->Codegen();
657 if (Val == 0) return 0;
658
659 // Look up the name.
660 Value *Variable = NamedValues[LHSE->getName()];
661 if (Variable == 0) return ErrorV("Unknown variable name");
662
663 Builder.CreateStore(Val, Variable);
664 return Val;
665 }
666
Nick Lewycky9f856342009-04-12 20:47:23 +0000667 Value *L = LHS->Codegen();
668 Value *R = RHS->Codegen();
669 if (L == 0 || R == 0) return 0;
670
671 switch (Op) {
672 case '+': return Builder.CreateAdd(L, R, "addtmp");
673 case '-': return Builder.CreateSub(L, R, "subtmp");
674 case '*': return Builder.CreateMul(L, R, "multmp");
675 case '<':
676 L = Builder.CreateFCmpULT(L, R, "cmptmp");
677 // Convert bool 0/1 to double 0.0 or 1.0
Owen Anderson1d0be152009-08-13 21:58:54 +0000678 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
679 "booltmp");
Nick Lewycky9f856342009-04-12 20:47:23 +0000680 default: break;
681 }
682
683 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
684 // a call to it.
685 Function *F = TheModule->getFunction(std::string("binary")+Op);
686 assert(F && "binary operator not found!");
687
688 Value *Ops[] = { L, R };
689 return Builder.CreateCall(F, Ops, Ops+2, "binop");
690}
691
692Value *CallExprAST::Codegen() {
693 // Look up the name in the global module table.
694 Function *CalleeF = TheModule->getFunction(Callee);
695 if (CalleeF == 0)
696 return ErrorV("Unknown function referenced");
697
698 // If argument mismatch error.
699 if (CalleeF->arg_size() != Args.size())
700 return ErrorV("Incorrect # arguments passed");
701
702 std::vector<Value*> ArgsV;
703 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
704 ArgsV.push_back(Args[i]->Codegen());
705 if (ArgsV.back() == 0) return 0;
706 }
707
708 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
709}
710
711Value *IfExprAST::Codegen() {
712 Value *CondV = Cond->Codegen();
713 if (CondV == 0) return 0;
714
715 // Convert condition to a bool by comparing equal to 0.0.
716 CondV = Builder.CreateFCmpONE(CondV,
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000717 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
Nick Lewycky9f856342009-04-12 20:47:23 +0000718 "ifcond");
719
720 Function *TheFunction = Builder.GetInsertBlock()->getParent();
721
722 // Create blocks for the then and else cases. Insert the 'then' block at the
723 // end of the function.
Owen Anderson1d0be152009-08-13 21:58:54 +0000724 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
725 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
726 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
Nick Lewycky9f856342009-04-12 20:47:23 +0000727
728 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
729
730 // Emit then value.
731 Builder.SetInsertPoint(ThenBB);
732
733 Value *ThenV = Then->Codegen();
734 if (ThenV == 0) return 0;
735
736 Builder.CreateBr(MergeBB);
737 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
738 ThenBB = Builder.GetInsertBlock();
739
740 // Emit else block.
741 TheFunction->getBasicBlockList().push_back(ElseBB);
742 Builder.SetInsertPoint(ElseBB);
743
744 Value *ElseV = Else->Codegen();
745 if (ElseV == 0) return 0;
746
747 Builder.CreateBr(MergeBB);
748 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
749 ElseBB = Builder.GetInsertBlock();
750
751 // Emit merge block.
752 TheFunction->getBasicBlockList().push_back(MergeBB);
753 Builder.SetInsertPoint(MergeBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000754 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
755 "iftmp");
Nick Lewycky9f856342009-04-12 20:47:23 +0000756
757 PN->addIncoming(ThenV, ThenBB);
758 PN->addIncoming(ElseV, ElseBB);
759 return PN;
760}
761
762Value *ForExprAST::Codegen() {
763 // Output this as:
764 // var = alloca double
765 // ...
766 // start = startexpr
767 // store start -> var
768 // goto loop
769 // loop:
770 // ...
771 // bodyexpr
772 // ...
773 // loopend:
774 // step = stepexpr
775 // endcond = endexpr
776 //
777 // curvar = load var
778 // nextvar = curvar + step
779 // store nextvar -> var
780 // br endcond, loop, endloop
781 // outloop:
782
783 Function *TheFunction = Builder.GetInsertBlock()->getParent();
784
785 // Create an alloca for the variable in the entry block.
786 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
787
788 // Emit the start code first, without 'variable' in scope.
789 Value *StartVal = Start->Codegen();
790 if (StartVal == 0) return 0;
791
792 // Store the value into the alloca.
793 Builder.CreateStore(StartVal, Alloca);
794
795 // Make the new basic block for the loop header, inserting after current
796 // block.
Owen Anderson1d0be152009-08-13 21:58:54 +0000797 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000798
799 // Insert an explicit fall through from the current block to the LoopBB.
800 Builder.CreateBr(LoopBB);
801
802 // Start insertion in LoopBB.
803 Builder.SetInsertPoint(LoopBB);
804
805 // Within the loop, the variable is defined equal to the PHI node. If it
806 // shadows an existing variable, we have to restore it, so save it now.
807 AllocaInst *OldVal = NamedValues[VarName];
808 NamedValues[VarName] = Alloca;
809
810 // Emit the body of the loop. This, like any other expr, can change the
811 // current BB. Note that we ignore the value computed by the body, but don't
812 // allow an error.
813 if (Body->Codegen() == 0)
814 return 0;
815
816 // Emit the step value.
817 Value *StepVal;
818 if (Step) {
819 StepVal = Step->Codegen();
820 if (StepVal == 0) return 0;
821 } else {
822 // If not specified, use 1.0.
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000823 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
Nick Lewycky9f856342009-04-12 20:47:23 +0000824 }
825
826 // Compute the end condition.
827 Value *EndCond = End->Codegen();
828 if (EndCond == 0) return EndCond;
829
830 // Reload, increment, and restore the alloca. This handles the case where
831 // the body of the loop mutates the variable.
832 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
833 Value *NextVar = Builder.CreateAdd(CurVar, StepVal, "nextvar");
834 Builder.CreateStore(NextVar, Alloca);
835
836 // Convert condition to a bool by comparing equal to 0.0.
837 EndCond = Builder.CreateFCmpONE(EndCond,
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000838 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
Nick Lewycky9f856342009-04-12 20:47:23 +0000839 "loopcond");
840
841 // Create the "after loop" block and insert it.
Owen Anderson1d0be152009-08-13 21:58:54 +0000842 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000843
844 // Insert the conditional branch into the end of LoopEndBB.
845 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
846
847 // Any new code will be inserted in AfterBB.
848 Builder.SetInsertPoint(AfterBB);
849
850 // Restore the unshadowed variable.
851 if (OldVal)
852 NamedValues[VarName] = OldVal;
853 else
854 NamedValues.erase(VarName);
855
856
857 // for expr always returns 0.0.
Owen Anderson1d0be152009-08-13 21:58:54 +0000858 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
Nick Lewycky9f856342009-04-12 20:47:23 +0000859}
860
861Value *VarExprAST::Codegen() {
862 std::vector<AllocaInst *> OldBindings;
863
864 Function *TheFunction = Builder.GetInsertBlock()->getParent();
865
866 // Register all variables and emit their initializer.
867 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
868 const std::string &VarName = VarNames[i].first;
869 ExprAST *Init = VarNames[i].second;
870
871 // Emit the initializer before adding the variable to scope, this prevents
872 // the initializer from referencing the variable itself, and permits stuff
873 // like this:
874 // var a = 1 in
875 // var a = a in ... # refers to outer 'a'.
876 Value *InitVal;
877 if (Init) {
878 InitVal = Init->Codegen();
879 if (InitVal == 0) return 0;
880 } else { // If not specified, use 0.0.
Owen Anderson6f83c9c2009-07-27 20:59:43 +0000881 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
Nick Lewycky9f856342009-04-12 20:47:23 +0000882 }
883
884 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
885 Builder.CreateStore(InitVal, Alloca);
886
887 // Remember the old variable binding so that we can restore the binding when
888 // we unrecurse.
889 OldBindings.push_back(NamedValues[VarName]);
890
891 // Remember this binding.
892 NamedValues[VarName] = Alloca;
893 }
894
895 // Codegen the body, now that all vars are in scope.
896 Value *BodyVal = Body->Codegen();
897 if (BodyVal == 0) return 0;
898
899 // Pop all our variables from scope.
900 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
901 NamedValues[VarNames[i].first] = OldBindings[i];
902
903 // Return the body computation.
904 return BodyVal;
905}
906
Nick Lewycky9f856342009-04-12 20:47:23 +0000907Function *PrototypeAST::Codegen() {
908 // Make the function type: double(double,double) etc.
Owen Anderson1d0be152009-08-13 21:58:54 +0000909 std::vector<const Type*> Doubles(Args.size(),
910 Type::getDoubleTy(getGlobalContext()));
911 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
912 Doubles, false);
Nick Lewycky9f856342009-04-12 20:47:23 +0000913
914 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
915
916 // If F conflicted, there was already something named 'Name'. If it has a
917 // body, don't allow redefinition or reextern.
918 if (F->getName() != Name) {
919 // Delete the one we just made and get the existing one.
920 F->eraseFromParent();
921 F = TheModule->getFunction(Name);
922
923 // If F already has a body, reject this.
924 if (!F->empty()) {
925 ErrorF("redefinition of function");
926 return 0;
927 }
928
929 // If F took a different number of args, reject.
930 if (F->arg_size() != Args.size()) {
931 ErrorF("redefinition of function with different # args");
932 return 0;
933 }
934 }
935
936 // Set names for all arguments.
937 unsigned Idx = 0;
938 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
939 ++AI, ++Idx)
940 AI->setName(Args[Idx]);
941
942 return F;
943}
944
945/// CreateArgumentAllocas - Create an alloca for each argument and register the
946/// argument in the symbol table so that references to it will succeed.
947void PrototypeAST::CreateArgumentAllocas(Function *F) {
948 Function::arg_iterator AI = F->arg_begin();
949 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
950 // Create an alloca for this variable.
951 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
952
953 // Store the initial value into the alloca.
954 Builder.CreateStore(AI, Alloca);
955
956 // Add arguments to variable symbol table.
957 NamedValues[Args[Idx]] = Alloca;
958 }
959}
960
Nick Lewycky9f856342009-04-12 20:47:23 +0000961Function *FunctionAST::Codegen() {
962 NamedValues.clear();
963
964 Function *TheFunction = Proto->Codegen();
965 if (TheFunction == 0)
966 return 0;
967
968 // If this is an operator, install it.
969 if (Proto->isBinaryOp())
970 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
971
972 // Create a new basic block to start insertion into.
Owen Anderson1d0be152009-08-13 21:58:54 +0000973 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
Nick Lewycky9f856342009-04-12 20:47:23 +0000974 Builder.SetInsertPoint(BB);
975
976 // Add all arguments to the symbol table and create their allocas.
977 Proto->CreateArgumentAllocas(TheFunction);
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +0000978
Nick Lewycky9f856342009-04-12 20:47:23 +0000979 if (Value *RetVal = Body->Codegen()) {
980 // Finish off the function.
981 Builder.CreateRet(RetVal);
982
983 // Validate the generated code, checking for consistency.
984 verifyFunction(*TheFunction);
985
986 // Optimize the function.
987 TheFPM->run(*TheFunction);
988
989 return TheFunction;
990 }
991
992 // Error reading body, remove function.
993 TheFunction->eraseFromParent();
994
995 if (Proto->isBinaryOp())
996 BinopPrecedence.erase(Proto->getOperatorName());
997 return 0;
998}
999
1000//===----------------------------------------------------------------------===//
1001// Top-Level parsing and JIT Driver
1002//===----------------------------------------------------------------------===//
1003
1004static ExecutionEngine *TheExecutionEngine;
1005
1006static void HandleDefinition() {
1007 if (FunctionAST *F = ParseDefinition()) {
1008 if (Function *LF = F->Codegen()) {
1009 fprintf(stderr, "Read function definition:");
1010 LF->dump();
1011 }
1012 } else {
1013 // Skip token for error recovery.
1014 getNextToken();
1015 }
1016}
1017
1018static void HandleExtern() {
1019 if (PrototypeAST *P = ParseExtern()) {
1020 if (Function *F = P->Codegen()) {
1021 fprintf(stderr, "Read extern: ");
1022 F->dump();
1023 }
1024 } else {
1025 // Skip token for error recovery.
1026 getNextToken();
1027 }
1028}
1029
1030static void HandleTopLevelExpression() {
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001031 // Evaluate a top-level expression into an anonymous function.
Nick Lewycky9f856342009-04-12 20:47:23 +00001032 if (FunctionAST *F = ParseTopLevelExpr()) {
1033 if (Function *LF = F->Codegen()) {
1034 // JIT the function, returning a function pointer.
1035 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1036
1037 // Cast it to the right type (takes no arguments, returns a double) so we
1038 // can call it as a native function.
Chris Lattnerd25bff62009-04-15 00:16:05 +00001039 double (*FP)() = (double (*)())(intptr_t)FPtr;
Nick Lewycky9f856342009-04-12 20:47:23 +00001040 fprintf(stderr, "Evaluated to %f\n", FP());
1041 }
1042 } else {
1043 // Skip token for error recovery.
1044 getNextToken();
1045 }
1046}
1047
1048/// top ::= definition | external | expression | ';'
1049static void MainLoop() {
1050 while (1) {
1051 fprintf(stderr, "ready> ");
1052 switch (CurTok) {
1053 case tok_eof: return;
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001054 case ';': getNextToken(); break; // ignore top-level semicolons.
Nick Lewycky9f856342009-04-12 20:47:23 +00001055 case tok_def: HandleDefinition(); break;
1056 case tok_extern: HandleExtern(); break;
1057 default: HandleTopLevelExpression(); break;
1058 }
1059 }
1060}
1061
Nick Lewycky9f856342009-04-12 20:47:23 +00001062//===----------------------------------------------------------------------===//
1063// "Library" functions that can be "extern'd" from user code.
1064//===----------------------------------------------------------------------===//
1065
1066/// putchard - putchar that takes a double and returns 0.
1067extern "C"
1068double putchard(double X) {
1069 putchar((char)X);
1070 return 0;
1071}
1072
1073/// printd - printf that takes a double prints it as "%f\n", returning 0.
1074extern "C"
1075double printd(double X) {
1076 printf("%f\n", X);
1077 return 0;
1078}
1079
1080//===----------------------------------------------------------------------===//
1081// Main driver code.
1082//===----------------------------------------------------------------------===//
1083
1084int main() {
Chris Lattnerda062882009-06-17 16:48:44 +00001085 InitializeNativeTarget();
Owen Anderson914e50c2009-07-16 19:05:41 +00001086 LLVMContext &Context = getGlobalContext();
Erick Tryzelaarfd1ec5e2009-09-22 21:14:49 +00001087
Nick Lewycky9f856342009-04-12 20:47:23 +00001088 // Install standard binary operators.
1089 // 1 is lowest precedence.
1090 BinopPrecedence['='] = 2;
1091 BinopPrecedence['<'] = 10;
1092 BinopPrecedence['+'] = 20;
1093 BinopPrecedence['-'] = 20;
1094 BinopPrecedence['*'] = 40; // highest.
1095
1096 // Prime the first token.
1097 fprintf(stderr, "ready> ");
1098 getNextToken();
1099
1100 // Make the module, which holds all the code.
Owen Anderson31895e72009-07-01 21:22:36 +00001101 TheModule = new Module("my cool jit", Context);
Nick Lewycky9f856342009-04-12 20:47:23 +00001102
Reid Kleckner60130f02009-08-26 20:58:25 +00001103 ExistingModuleProvider *OurModuleProvider =
1104 new ExistingModuleProvider(TheModule);
Reid Kleckner9e6f3f22009-08-24 05:42:21 +00001105
Reid Kleckner60130f02009-08-26 20:58:25 +00001106 // Create the JIT. This takes ownership of the module and module provider.
1107 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
Reid Kleckner9e6f3f22009-08-24 05:42:21 +00001108
Reid Kleckner60130f02009-08-26 20:58:25 +00001109 FunctionPassManager OurFPM(OurModuleProvider);
Nick Lewycky9f856342009-04-12 20:47:23 +00001110
Reid Kleckner60130f02009-08-26 20:58:25 +00001111 // Set up the optimizer pipeline. Start with registering info about how the
1112 // target lays out data structures.
1113 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
1114 // Promote allocas to registers.
1115 OurFPM.add(createPromoteMemoryToRegisterPass());
1116 // Do simple "peephole" optimizations and bit-twiddling optzns.
1117 OurFPM.add(createInstructionCombiningPass());
1118 // Reassociate expressions.
1119 OurFPM.add(createReassociatePass());
1120 // Eliminate Common SubExpressions.
1121 OurFPM.add(createGVNPass());
1122 // Simplify the control flow graph (deleting unreachable blocks, etc).
1123 OurFPM.add(createCFGSimplificationPass());
Eli Friedman8e9b1712009-07-20 14:50:07 +00001124
Reid Kleckner60130f02009-08-26 20:58:25 +00001125 OurFPM.doInitialization();
Nick Lewycky9f856342009-04-12 20:47:23 +00001126
Reid Kleckner60130f02009-08-26 20:58:25 +00001127 // Set the global so the code gen can use this.
1128 TheFPM = &OurFPM;
1129
1130 // Run the main "interpreter loop" now.
1131 MainLoop();
1132
1133 TheFPM = 0;
1134
1135 // Print out all of the generated code.
1136 TheModule->dump();
1137
Nick Lewycky9f856342009-04-12 20:47:23 +00001138 return 0;
1139}