blob: 638a340d51aea5ae7c1f50bf17e1cd8da03497d4 [file] [log] [blame]
Erick Tryzelaar31c6c5d2009-09-22 21:15:19 +00001#include "llvm/DerivedTypes.h"
2#include "llvm/ExecutionEngine/ExecutionEngine.h"
3#include "llvm/ExecutionEngine/Interpreter.h"
4#include "llvm/ExecutionEngine/JIT.h"
5#include "llvm/LLVMContext.h"
6#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"
11#include "llvm/Target/TargetSelect.h"
12#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
43static std::string IdentifierStr; // Filled in if tok_identifier
44static double NumVal; // Filled in if tok_number
45
46/// gettok - Return the next token from standard input.
47static int gettok() {
48 static int LastChar = ' ';
49
50 // Skip any whitespace.
51 while (isspace(LastChar))
52 LastChar = getchar();
53
54 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
55 IdentifierStr = LastChar;
56 while (isalnum((LastChar = getchar())))
57 IdentifierStr += LastChar;
58
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;
68 return tok_identifier;
69 }
70
71 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
72 std::string NumStr;
73 do {
74 NumStr += LastChar;
75 LastChar = getchar();
76 } while (isdigit(LastChar) || LastChar == '.');
77
78 NumVal = strtod(NumStr.c_str(), 0);
79 return tok_number;
80 }
81
82 if (LastChar == '#') {
83 // Comment until end of line.
84 do LastChar = getchar();
85 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
86
87 if (LastChar != EOF)
88 return gettok();
89 }
90
91 // Check for end of file. Don't eat the EOF.
92 if (LastChar == EOF)
93 return tok_eof;
94
95 // Otherwise, just return the character as its ascii value.
96 int ThisChar = LastChar;
97 LastChar = getchar();
98 return ThisChar;
99}
100
101//===----------------------------------------------------------------------===//
102// Abstract Syntax Tree (aka Parse Tree)
103//===----------------------------------------------------------------------===//
104
105/// ExprAST - Base class for all expression nodes.
106class ExprAST {
107public:
108 virtual ~ExprAST() {}
109 virtual Value *Codegen() = 0;
110};
111
112/// NumberExprAST - Expression class for numeric literals like "1.0".
113class NumberExprAST : public ExprAST {
114 double Val;
115public:
116 NumberExprAST(double val) : Val(val) {}
117 virtual Value *Codegen();
118};
119
120/// VariableExprAST - Expression class for referencing a variable, like "a".
121class VariableExprAST : public ExprAST {
122 std::string Name;
123public:
124 VariableExprAST(const std::string &name) : Name(name) {}
125 virtual Value *Codegen();
126};
127
128/// UnaryExprAST - Expression class for a unary operator.
129class UnaryExprAST : public ExprAST {
130 char Opcode;
131 ExprAST *Operand;
132public:
133 UnaryExprAST(char opcode, ExprAST *operand)
134 : Opcode(opcode), Operand(operand) {}
135 virtual Value *Codegen();
136};
137
138/// BinaryExprAST - Expression class for a binary operator.
139class BinaryExprAST : public ExprAST {
140 char Op;
141 ExprAST *LHS, *RHS;
142public:
143 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
144 : Op(op), LHS(lhs), RHS(rhs) {}
145 virtual Value *Codegen();
146};
147
148/// CallExprAST - Expression class for function calls.
149class CallExprAST : public ExprAST {
150 std::string Callee;
151 std::vector<ExprAST*> Args;
152public:
153 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
154 : Callee(callee), Args(args) {}
155 virtual Value *Codegen();
156};
157
158/// IfExprAST - Expression class for if/then/else.
159class IfExprAST : public ExprAST {
160 ExprAST *Cond, *Then, *Else;
161public:
162 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
163 : Cond(cond), Then(then), Else(_else) {}
164 virtual Value *Codegen();
165};
166
167/// ForExprAST - Expression class for for/in.
168class ForExprAST : public ExprAST {
169 std::string VarName;
170 ExprAST *Start, *End, *Step, *Body;
171public:
172 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
173 ExprAST *step, ExprAST *body)
174 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
175 virtual Value *Codegen();
176};
177
178/// PrototypeAST - This class represents the "prototype" for a function,
179/// which captures its name, and its argument names (thus implicitly the number
180/// of arguments the function takes), as well as if it is an operator.
181class PrototypeAST {
182 std::string Name;
183 std::vector<std::string> Args;
184 bool isOperator;
185 unsigned Precedence; // Precedence if a binary op.
186public:
187 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
188 bool isoperator = false, unsigned prec = 0)
189 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
190
191 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
192 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
193
194 char getOperatorName() const {
195 assert(isUnaryOp() || isBinaryOp());
196 return Name[Name.size()-1];
197 }
198
199 unsigned getBinaryPrecedence() const { return Precedence; }
200
201 Function *Codegen();
202};
203
204/// FunctionAST - This class represents a function definition itself.
205class FunctionAST {
206 PrototypeAST *Proto;
207 ExprAST *Body;
208public:
209 FunctionAST(PrototypeAST *proto, ExprAST *body)
210 : Proto(proto), Body(body) {}
211
212 Function *Codegen();
213};
214
215//===----------------------------------------------------------------------===//
216// Parser
217//===----------------------------------------------------------------------===//
218
219/// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
220/// token the parser is looking at. getNextToken reads another token from the
221/// lexer and updates CurTok with its results.
222static int CurTok;
223static int getNextToken() {
224 return CurTok = gettok();
225}
226
227/// BinopPrecedence - This holds the precedence for each binary operator that is
228/// defined.
229static std::map<char, int> BinopPrecedence;
230
231/// GetTokPrecedence - Get the precedence of the pending binary operator token.
232static int GetTokPrecedence() {
233 if (!isascii(CurTok))
234 return -1;
235
236 // Make sure it's a declared binop.
237 int TokPrec = BinopPrecedence[CurTok];
238 if (TokPrec <= 0) return -1;
239 return TokPrec;
240}
241
242/// Error* - These are little helper functions for error handling.
243ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
244PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
245FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
246
247static ExprAST *ParseExpression();
248
249/// identifierexpr
250/// ::= identifier
251/// ::= identifier '(' expression* ')'
252static ExprAST *ParseIdentifierExpr() {
253 std::string IdName = IdentifierStr;
254
255 getNextToken(); // eat identifier.
256
257 if (CurTok != '(') // Simple variable ref.
258 return new VariableExprAST(IdName);
259
260 // Call.
261 getNextToken(); // eat (
262 std::vector<ExprAST*> Args;
263 if (CurTok != ')') {
264 while (1) {
265 ExprAST *Arg = ParseExpression();
266 if (!Arg) return 0;
267 Args.push_back(Arg);
268
269 if (CurTok == ')') break;
270
271 if (CurTok != ',')
272 return Error("Expected ')' or ',' in argument list");
273 getNextToken();
274 }
275 }
276
277 // Eat the ')'.
278 getNextToken();
279
280 return new CallExprAST(IdName, Args);
281}
282
283/// numberexpr ::= number
284static ExprAST *ParseNumberExpr() {
285 ExprAST *Result = new NumberExprAST(NumVal);
286 getNextToken(); // consume the number
287 return Result;
288}
289
290/// parenexpr ::= '(' expression ')'
291static ExprAST *ParseParenExpr() {
292 getNextToken(); // eat (.
293 ExprAST *V = ParseExpression();
294 if (!V) return 0;
295
296 if (CurTok != ')')
297 return Error("expected ')'");
298 getNextToken(); // eat ).
299 return V;
300}
301
302/// ifexpr ::= 'if' expression 'then' expression 'else' expression
303static ExprAST *ParseIfExpr() {
304 getNextToken(); // eat the if.
305
306 // condition.
307 ExprAST *Cond = ParseExpression();
308 if (!Cond) return 0;
309
310 if (CurTok != tok_then)
311 return Error("expected then");
312 getNextToken(); // eat the then
313
314 ExprAST *Then = ParseExpression();
315 if (Then == 0) return 0;
316
317 if (CurTok != tok_else)
318 return Error("expected else");
319
320 getNextToken();
321
322 ExprAST *Else = ParseExpression();
323 if (!Else) return 0;
324
325 return new IfExprAST(Cond, Then, Else);
326}
327
328/// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
329static ExprAST *ParseForExpr() {
330 getNextToken(); // eat the for.
331
332 if (CurTok != tok_identifier)
333 return Error("expected identifier after for");
334
335 std::string IdName = IdentifierStr;
336 getNextToken(); // eat identifier.
337
338 if (CurTok != '=')
339 return Error("expected '=' after for");
340 getNextToken(); // eat '='.
341
342
343 ExprAST *Start = ParseExpression();
344 if (Start == 0) return 0;
345 if (CurTok != ',')
346 return Error("expected ',' after for start value");
347 getNextToken();
348
349 ExprAST *End = ParseExpression();
350 if (End == 0) return 0;
351
352 // The step value is optional.
353 ExprAST *Step = 0;
354 if (CurTok == ',') {
355 getNextToken();
356 Step = ParseExpression();
357 if (Step == 0) return 0;
358 }
359
360 if (CurTok != tok_in)
361 return Error("expected 'in' after for");
362 getNextToken(); // eat 'in'.
363
364 ExprAST *Body = ParseExpression();
365 if (Body == 0) return 0;
366
367 return new ForExprAST(IdName, Start, End, Step, Body);
368}
369
370/// primary
371/// ::= identifierexpr
372/// ::= numberexpr
373/// ::= parenexpr
374/// ::= ifexpr
375/// ::= forexpr
376static ExprAST *ParsePrimary() {
377 switch (CurTok) {
378 default: return Error("unknown token when expecting an expression");
379 case tok_identifier: return ParseIdentifierExpr();
380 case tok_number: return ParseNumberExpr();
381 case '(': return ParseParenExpr();
382 case tok_if: return ParseIfExpr();
383 case tok_for: return ParseForExpr();
384 }
385}
386
387/// unary
388/// ::= primary
389/// ::= '!' unary
390static ExprAST *ParseUnary() {
391 // If the current token is not an operator, it must be a primary expr.
392 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
393 return ParsePrimary();
394
395 // If this is a unary operator, read it.
396 int Opc = CurTok;
397 getNextToken();
398 if (ExprAST *Operand = ParseUnary())
399 return new UnaryExprAST(Opc, Operand);
400 return 0;
401}
402
403/// binoprhs
404/// ::= ('+' unary)*
405static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
406 // If this is a binop, find its precedence.
407 while (1) {
408 int TokPrec = GetTokPrecedence();
409
410 // If this is a binop that binds at least as tightly as the current binop,
411 // consume it, otherwise we are done.
412 if (TokPrec < ExprPrec)
413 return LHS;
414
415 // Okay, we know this is a binop.
416 int BinOp = CurTok;
417 getNextToken(); // eat binop
418
419 // Parse the unary expression after the binary operator.
420 ExprAST *RHS = ParseUnary();
421 if (!RHS) return 0;
422
423 // If BinOp binds less tightly with RHS than the operator after RHS, let
424 // the pending operator take RHS as its LHS.
425 int NextPrec = GetTokPrecedence();
426 if (TokPrec < NextPrec) {
427 RHS = ParseBinOpRHS(TokPrec+1, RHS);
428 if (RHS == 0) return 0;
429 }
430
431 // Merge LHS/RHS.
432 LHS = new BinaryExprAST(BinOp, LHS, RHS);
433 }
434}
435
436/// expression
437/// ::= unary binoprhs
438///
439static ExprAST *ParseExpression() {
440 ExprAST *LHS = ParseUnary();
441 if (!LHS) return 0;
442
443 return ParseBinOpRHS(0, LHS);
444}
445
446/// prototype
447/// ::= id '(' id* ')'
448/// ::= binary LETTER number? (id, id)
449/// ::= unary LETTER (id)
450static PrototypeAST *ParsePrototype() {
451 std::string FnName;
452
453 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
454 unsigned BinaryPrecedence = 30;
455
456 switch (CurTok) {
457 default:
458 return ErrorP("Expected function name in prototype");
459 case tok_identifier:
460 FnName = IdentifierStr;
461 Kind = 0;
462 getNextToken();
463 break;
464 case tok_unary:
465 getNextToken();
466 if (!isascii(CurTok))
467 return ErrorP("Expected unary operator");
468 FnName = "unary";
469 FnName += (char)CurTok;
470 Kind = 1;
471 getNextToken();
472 break;
473 case tok_binary:
474 getNextToken();
475 if (!isascii(CurTok))
476 return ErrorP("Expected binary operator");
477 FnName = "binary";
478 FnName += (char)CurTok;
479 Kind = 2;
480 getNextToken();
481
482 // Read the precedence if present.
483 if (CurTok == tok_number) {
484 if (NumVal < 1 || NumVal > 100)
485 return ErrorP("Invalid precedecnce: must be 1..100");
486 BinaryPrecedence = (unsigned)NumVal;
487 getNextToken();
488 }
489 break;
490 }
491
492 if (CurTok != '(')
493 return ErrorP("Expected '(' in prototype");
494
495 std::vector<std::string> ArgNames;
496 while (getNextToken() == tok_identifier)
497 ArgNames.push_back(IdentifierStr);
498 if (CurTok != ')')
499 return ErrorP("Expected ')' in prototype");
500
501 // success.
502 getNextToken(); // eat ')'.
503
504 // Verify right number of names for operator.
505 if (Kind && ArgNames.size() != Kind)
506 return ErrorP("Invalid number of operands for operator");
507
508 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
509}
510
511/// definition ::= 'def' prototype expression
512static FunctionAST *ParseDefinition() {
513 getNextToken(); // eat def.
514 PrototypeAST *Proto = ParsePrototype();
515 if (Proto == 0) return 0;
516
517 if (ExprAST *E = ParseExpression())
518 return new FunctionAST(Proto, E);
519 return 0;
520}
521
522/// toplevelexpr ::= expression
523static FunctionAST *ParseTopLevelExpr() {
524 if (ExprAST *E = ParseExpression()) {
525 // Make an anonymous proto.
526 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
527 return new FunctionAST(Proto, E);
528 }
529 return 0;
530}
531
532/// external ::= 'extern' prototype
533static PrototypeAST *ParseExtern() {
534 getNextToken(); // eat extern.
535 return ParsePrototype();
536}
537
538//===----------------------------------------------------------------------===//
539// Code Generation
540//===----------------------------------------------------------------------===//
541
542static Module *TheModule;
543static IRBuilder<> Builder(getGlobalContext());
544static std::map<std::string, Value*> NamedValues;
545static FunctionPassManager *TheFPM;
546
547Value *ErrorV(const char *Str) { Error(Str); return 0; }
548
549Value *NumberExprAST::Codegen() {
550 return ConstantFP::get(getGlobalContext(), APFloat(Val));
551}
552
553Value *VariableExprAST::Codegen() {
554 // Look this variable up in the function.
555 Value *V = NamedValues[Name];
556 return V ? V : ErrorV("Unknown variable name");
557}
558
559Value *UnaryExprAST::Codegen() {
560 Value *OperandV = Operand->Codegen();
561 if (OperandV == 0) return 0;
562
563 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
564 if (F == 0)
565 return ErrorV("Unknown unary operator");
566
567 return Builder.CreateCall(F, OperandV, "unop");
568}
569
570Value *BinaryExprAST::Codegen() {
571 Value *L = LHS->Codegen();
572 Value *R = RHS->Codegen();
573 if (L == 0 || R == 0) return 0;
574
575 switch (Op) {
576 case '+': return Builder.CreateAdd(L, R, "addtmp");
577 case '-': return Builder.CreateSub(L, R, "subtmp");
578 case '*': return Builder.CreateMul(L, R, "multmp");
579 case '<':
580 L = Builder.CreateFCmpULT(L, R, "cmptmp");
581 // Convert bool 0/1 to double 0.0 or 1.0
582 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
583 "booltmp");
584 default: break;
585 }
586
587 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
588 // a call to it.
589 Function *F = TheModule->getFunction(std::string("binary")+Op);
590 assert(F && "binary operator not found!");
591
592 Value *Ops[] = { L, R };
593 return Builder.CreateCall(F, Ops, Ops+2, "binop");
594}
595
596Value *CallExprAST::Codegen() {
597 // Look up the name in the global module table.
598 Function *CalleeF = TheModule->getFunction(Callee);
599 if (CalleeF == 0)
600 return ErrorV("Unknown function referenced");
601
602 // If argument mismatch error.
603 if (CalleeF->arg_size() != Args.size())
604 return ErrorV("Incorrect # arguments passed");
605
606 std::vector<Value*> ArgsV;
607 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
608 ArgsV.push_back(Args[i]->Codegen());
609 if (ArgsV.back() == 0) return 0;
610 }
611
612 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
613}
614
615Value *IfExprAST::Codegen() {
616 Value *CondV = Cond->Codegen();
617 if (CondV == 0) return 0;
618
619 // Convert condition to a bool by comparing equal to 0.0.
620 CondV = Builder.CreateFCmpONE(CondV,
621 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
622 "ifcond");
623
624 Function *TheFunction = Builder.GetInsertBlock()->getParent();
625
626 // Create blocks for the then and else cases. Insert the 'then' block at the
627 // end of the function.
628 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
629 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
630 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
631
632 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
633
634 // Emit then value.
635 Builder.SetInsertPoint(ThenBB);
636
637 Value *ThenV = Then->Codegen();
638 if (ThenV == 0) return 0;
639
640 Builder.CreateBr(MergeBB);
641 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
642 ThenBB = Builder.GetInsertBlock();
643
644 // Emit else block.
645 TheFunction->getBasicBlockList().push_back(ElseBB);
646 Builder.SetInsertPoint(ElseBB);
647
648 Value *ElseV = Else->Codegen();
649 if (ElseV == 0) return 0;
650
651 Builder.CreateBr(MergeBB);
652 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
653 ElseBB = Builder.GetInsertBlock();
654
655 // Emit merge block.
656 TheFunction->getBasicBlockList().push_back(MergeBB);
657 Builder.SetInsertPoint(MergeBB);
658 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
659 "iftmp");
660
661 PN->addIncoming(ThenV, ThenBB);
662 PN->addIncoming(ElseV, ElseBB);
663 return PN;
664}
665
666Value *ForExprAST::Codegen() {
667 // Output this as:
668 // ...
669 // start = startexpr
670 // goto loop
671 // loop:
672 // variable = phi [start, loopheader], [nextvariable, loopend]
673 // ...
674 // bodyexpr
675 // ...
676 // loopend:
677 // step = stepexpr
678 // nextvariable = variable + step
679 // endcond = endexpr
680 // br endcond, loop, endloop
681 // outloop:
682
683 // Emit the start code first, without 'variable' in scope.
684 Value *StartVal = Start->Codegen();
685 if (StartVal == 0) return 0;
686
687 // Make the new basic block for the loop header, inserting after current
688 // block.
689 Function *TheFunction = Builder.GetInsertBlock()->getParent();
690 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
691 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
692
693 // Insert an explicit fall through from the current block to the LoopBB.
694 Builder.CreateBr(LoopBB);
695
696 // Start insertion in LoopBB.
697 Builder.SetInsertPoint(LoopBB);
698
699 // Start the PHI node with an entry for Start.
700 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), VarName.c_str());
701 Variable->addIncoming(StartVal, PreheaderBB);
702
703 // Within the loop, the variable is defined equal to the PHI node. If it
704 // shadows an existing variable, we have to restore it, so save it now.
705 Value *OldVal = NamedValues[VarName];
706 NamedValues[VarName] = Variable;
707
708 // Emit the body of the loop. This, like any other expr, can change the
709 // current BB. Note that we ignore the value computed by the body, but don't
710 // allow an error.
711 if (Body->Codegen() == 0)
712 return 0;
713
714 // Emit the step value.
715 Value *StepVal;
716 if (Step) {
717 StepVal = Step->Codegen();
718 if (StepVal == 0) return 0;
719 } else {
720 // If not specified, use 1.0.
721 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
722 }
723
724 Value *NextVar = Builder.CreateAdd(Variable, StepVal, "nextvar");
725
726 // Compute the end condition.
727 Value *EndCond = End->Codegen();
728 if (EndCond == 0) return EndCond;
729
730 // Convert condition to a bool by comparing equal to 0.0.
731 EndCond = Builder.CreateFCmpONE(EndCond,
732 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
733 "loopcond");
734
735 // Create the "after loop" block and insert it.
736 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
737 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
738
739 // Insert the conditional branch into the end of LoopEndBB.
740 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
741
742 // Any new code will be inserted in AfterBB.
743 Builder.SetInsertPoint(AfterBB);
744
745 // Add a new entry to the PHI node for the backedge.
746 Variable->addIncoming(NextVar, LoopEndBB);
747
748 // Restore the unshadowed variable.
749 if (OldVal)
750 NamedValues[VarName] = OldVal;
751 else
752 NamedValues.erase(VarName);
753
754
755 // for expr always returns 0.0.
756 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
757}
758
759Function *PrototypeAST::Codegen() {
760 // Make the function type: double(double,double) etc.
761 std::vector<const Type*> Doubles(Args.size(),
762 Type::getDoubleTy(getGlobalContext()));
763 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
764 Doubles, false);
765
766 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
767
768 // If F conflicted, there was already something named 'Name'. If it has a
769 // body, don't allow redefinition or reextern.
770 if (F->getName() != Name) {
771 // Delete the one we just made and get the existing one.
772 F->eraseFromParent();
773 F = TheModule->getFunction(Name);
774
775 // If F already has a body, reject this.
776 if (!F->empty()) {
777 ErrorF("redefinition of function");
778 return 0;
779 }
780
781 // If F took a different number of args, reject.
782 if (F->arg_size() != Args.size()) {
783 ErrorF("redefinition of function with different # args");
784 return 0;
785 }
786 }
787
788 // Set names for all arguments.
789 unsigned Idx = 0;
790 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
791 ++AI, ++Idx) {
792 AI->setName(Args[Idx]);
793
794 // Add arguments to variable symbol table.
795 NamedValues[Args[Idx]] = AI;
796 }
797
798 return F;
799}
800
801Function *FunctionAST::Codegen() {
802 NamedValues.clear();
803
804 Function *TheFunction = Proto->Codegen();
805 if (TheFunction == 0)
806 return 0;
807
808 // If this is an operator, install it.
809 if (Proto->isBinaryOp())
810 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
811
812 // Create a new basic block to start insertion into.
813 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
814 Builder.SetInsertPoint(BB);
815
816 if (Value *RetVal = Body->Codegen()) {
817 // Finish off the function.
818 Builder.CreateRet(RetVal);
819
820 // Validate the generated code, checking for consistency.
821 verifyFunction(*TheFunction);
822
823 // Optimize the function.
824 TheFPM->run(*TheFunction);
825
826 return TheFunction;
827 }
828
829 // Error reading body, remove function.
830 TheFunction->eraseFromParent();
831
832 if (Proto->isBinaryOp())
833 BinopPrecedence.erase(Proto->getOperatorName());
834 return 0;
835}
836
837//===----------------------------------------------------------------------===//
838// Top-Level parsing and JIT Driver
839//===----------------------------------------------------------------------===//
840
841static ExecutionEngine *TheExecutionEngine;
842
843static void HandleDefinition() {
844 if (FunctionAST *F = ParseDefinition()) {
845 if (Function *LF = F->Codegen()) {
846 fprintf(stderr, "Read function definition:");
847 LF->dump();
848 }
849 } else {
850 // Skip token for error recovery.
851 getNextToken();
852 }
853}
854
855static void HandleExtern() {
856 if (PrototypeAST *P = ParseExtern()) {
857 if (Function *F = P->Codegen()) {
858 fprintf(stderr, "Read extern: ");
859 F->dump();
860 }
861 } else {
862 // Skip token for error recovery.
863 getNextToken();
864 }
865}
866
867static void HandleTopLevelExpression() {
868 // Evaluate a top-level expression into an anonymous function.
869 if (FunctionAST *F = ParseTopLevelExpr()) {
870 if (Function *LF = F->Codegen()) {
871 // JIT the function, returning a function pointer.
872 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
873
874 // Cast it to the right type (takes no arguments, returns a double) so we
875 // can call it as a native function.
876 double (*FP)() = (double (*)())(intptr_t)FPtr;
877 fprintf(stderr, "Evaluated to %f\n", FP());
878 }
879 } else {
880 // Skip token for error recovery.
881 getNextToken();
882 }
883}
884
885/// top ::= definition | external | expression | ';'
886static void MainLoop() {
887 while (1) {
888 fprintf(stderr, "ready> ");
889 switch (CurTok) {
890 case tok_eof: return;
891 case ';': getNextToken(); break; // ignore top-level semicolons.
892 case tok_def: HandleDefinition(); break;
893 case tok_extern: HandleExtern(); break;
894 default: HandleTopLevelExpression(); break;
895 }
896 }
897}
898
899//===----------------------------------------------------------------------===//
900// "Library" functions that can be "extern'd" from user code.
901//===----------------------------------------------------------------------===//
902
903/// putchard - putchar that takes a double and returns 0.
904extern "C"
905double putchard(double X) {
906 putchar((char)X);
907 return 0;
908}
909
910/// printd - printf that takes a double prints it as "%f\n", returning 0.
911extern "C"
912double printd(double X) {
913 printf("%f\n", X);
914 return 0;
915}
916
917//===----------------------------------------------------------------------===//
918// Main driver code.
919//===----------------------------------------------------------------------===//
920
921int main() {
922 InitializeNativeTarget();
923 LLVMContext &Context = getGlobalContext();
924
925 // Install standard binary operators.
926 // 1 is lowest precedence.
927 BinopPrecedence['<'] = 10;
928 BinopPrecedence['+'] = 20;
929 BinopPrecedence['-'] = 20;
930 BinopPrecedence['*'] = 40; // highest.
931
932 // Prime the first token.
933 fprintf(stderr, "ready> ");
934 getNextToken();
935
936 // Make the module, which holds all the code.
937 TheModule = new Module("my cool jit", Context);
938
939 ExistingModuleProvider *OurModuleProvider =
940 new ExistingModuleProvider(TheModule);
941
942 // Create the JIT. This takes ownership of the module and module provider.
943 TheExecutionEngine = EngineBuilder(OurModuleProvider).create();
944
945 FunctionPassManager OurFPM(OurModuleProvider);
946
947 // Set up the optimizer pipeline. Start with registering info about how the
948 // target lays out data structures.
949 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
950 // Do simple "peephole" optimizations and bit-twiddling optzns.
951 OurFPM.add(createInstructionCombiningPass());
952 // Reassociate expressions.
953 OurFPM.add(createReassociatePass());
954 // Eliminate Common SubExpressions.
955 OurFPM.add(createGVNPass());
956 // Simplify the control flow graph (deleting unreachable blocks, etc).
957 OurFPM.add(createCFGSimplificationPass());
958
959 OurFPM.doInitialization();
960
961 // Set the global so the code gen can use this.
962 TheFPM = &OurFPM;
963
964 // Run the main "interpreter loop" now.
965 MainLoop();
966
967 TheFPM = 0;
968
969 // Print out all of the generated code.
970 TheModule->dump();
971
972 return 0;
973}