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