1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/IR/DataLayout.h"
4 #include "llvm/IR/DerivedTypes.h"
5 #include "llvm/IR/IRBuilder.h"
6 #include "llvm/IR/LLVMContext.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/PassManager.h"
10 #include "llvm/Support/TargetSelect.h"
11 #include "llvm/Transforms/Scalar.h"
19 //===----------------------------------------------------------------------===//
21 //===----------------------------------------------------------------------===//
23 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
24 // of these for known things.
29 tok_def = -2, tok_extern = -3,
32 tok_identifier = -4, tok_number = -5,
35 tok_if = -6, tok_then = -7, tok_else = -8,
36 tok_for = -9, tok_in = -10
39 static std::string IdentifierStr; // Filled in if tok_identifier
40 static double NumVal; // Filled in if tok_number
42 /// gettok - Return the next token from standard input.
44 static int LastChar = ' ';
46 // Skip any whitespace.
47 while (isspace(LastChar))
50 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
51 IdentifierStr = LastChar;
52 while (isalnum((LastChar = getchar())))
53 IdentifierStr += LastChar;
55 if (IdentifierStr == "def") return tok_def;
56 if (IdentifierStr == "extern") return tok_extern;
57 if (IdentifierStr == "if") return tok_if;
58 if (IdentifierStr == "then") return tok_then;
59 if (IdentifierStr == "else") return tok_else;
60 if (IdentifierStr == "for") return tok_for;
61 if (IdentifierStr == "in") return tok_in;
62 return tok_identifier;
65 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
70 } while (isdigit(LastChar) || LastChar == '.');
72 NumVal = strtod(NumStr.c_str(), 0);
76 if (LastChar == '#') {
77 // Comment until end of line.
78 do LastChar = getchar();
79 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
85 // Check for end of file. Don't eat the EOF.
89 // Otherwise, just return the character as its ascii value.
90 int ThisChar = LastChar;
95 //===----------------------------------------------------------------------===//
96 // Abstract Syntax Tree (aka Parse Tree)
97 //===----------------------------------------------------------------------===//
99 /// ExprAST - Base class for all expression nodes.
102 virtual ~ExprAST() {}
103 virtual Value *Codegen() = 0;
106 /// NumberExprAST - Expression class for numeric literals like "1.0".
107 class NumberExprAST : public ExprAST {
110 NumberExprAST(double val) : Val(val) {}
111 virtual Value *Codegen();
114 /// VariableExprAST - Expression class for referencing a variable, like "a".
115 class VariableExprAST : public ExprAST {
118 VariableExprAST(const std::string &name) : Name(name) {}
119 virtual Value *Codegen();
122 /// BinaryExprAST - Expression class for a binary operator.
123 class BinaryExprAST : public ExprAST {
127 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
128 : Op(op), LHS(lhs), RHS(rhs) {}
129 virtual Value *Codegen();
132 /// CallExprAST - Expression class for function calls.
133 class CallExprAST : public ExprAST {
135 std::vector<ExprAST*> Args;
137 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
138 : Callee(callee), Args(args) {}
139 virtual Value *Codegen();
142 /// IfExprAST - Expression class for if/then/else.
143 class IfExprAST : public ExprAST {
144 ExprAST *Cond, *Then, *Else;
146 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
147 : Cond(cond), Then(then), Else(_else) {}
148 virtual Value *Codegen();
151 /// ForExprAST - Expression class for for/in.
152 class ForExprAST : public ExprAST {
154 ExprAST *Start, *End, *Step, *Body;
156 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
157 ExprAST *step, ExprAST *body)
158 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
159 virtual Value *Codegen();
162 /// PrototypeAST - This class represents the "prototype" for a function,
163 /// which captures its name, and its argument names (thus implicitly the number
164 /// of arguments the function takes).
167 std::vector<std::string> Args;
169 PrototypeAST(const std::string &name, const std::vector<std::string> &args)
170 : Name(name), Args(args) {}
175 /// FunctionAST - This class represents a function definition itself.
180 FunctionAST(PrototypeAST *proto, ExprAST *body)
181 : Proto(proto), Body(body) {}
185 } // end anonymous namespace
187 //===----------------------------------------------------------------------===//
189 //===----------------------------------------------------------------------===//
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.
195 static int getNextToken() {
196 return CurTok = gettok();
199 /// BinopPrecedence - This holds the precedence for each binary operator that is
201 static std::map<char, int> BinopPrecedence;
203 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
204 static int GetTokPrecedence() {
205 if (!isascii(CurTok))
208 // Make sure it's a declared binop.
209 int TokPrec = BinopPrecedence[CurTok];
210 if (TokPrec <= 0) return -1;
214 /// Error* - These are little helper functions for error handling.
215 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
216 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
217 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
219 static ExprAST *ParseExpression();
223 /// ::= identifier '(' expression* ')'
224 static ExprAST *ParseIdentifierExpr() {
225 std::string IdName = IdentifierStr;
227 getNextToken(); // eat identifier.
229 if (CurTok != '(') // Simple variable ref.
230 return new VariableExprAST(IdName);
233 getNextToken(); // eat (
234 std::vector<ExprAST*> Args;
237 ExprAST *Arg = ParseExpression();
241 if (CurTok == ')') break;
244 return Error("Expected ')' or ',' in argument list");
252 return new CallExprAST(IdName, Args);
255 /// numberexpr ::= number
256 static ExprAST *ParseNumberExpr() {
257 ExprAST *Result = new NumberExprAST(NumVal);
258 getNextToken(); // consume the number
262 /// parenexpr ::= '(' expression ')'
263 static ExprAST *ParseParenExpr() {
264 getNextToken(); // eat (.
265 ExprAST *V = ParseExpression();
269 return Error("expected ')'");
270 getNextToken(); // eat ).
274 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
275 static ExprAST *ParseIfExpr() {
276 getNextToken(); // eat the if.
279 ExprAST *Cond = ParseExpression();
282 if (CurTok != tok_then)
283 return Error("expected then");
284 getNextToken(); // eat the then
286 ExprAST *Then = ParseExpression();
287 if (Then == 0) return 0;
289 if (CurTok != tok_else)
290 return Error("expected else");
294 ExprAST *Else = ParseExpression();
297 return new IfExprAST(Cond, Then, Else);
300 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
301 static ExprAST *ParseForExpr() {
302 getNextToken(); // eat the for.
304 if (CurTok != tok_identifier)
305 return Error("expected identifier after for");
307 std::string IdName = IdentifierStr;
308 getNextToken(); // eat identifier.
311 return Error("expected '=' after for");
312 getNextToken(); // eat '='.
315 ExprAST *Start = ParseExpression();
316 if (Start == 0) return 0;
318 return Error("expected ',' after for start value");
321 ExprAST *End = ParseExpression();
322 if (End == 0) return 0;
324 // The step value is optional.
328 Step = ParseExpression();
329 if (Step == 0) return 0;
332 if (CurTok != tok_in)
333 return Error("expected 'in' after for");
334 getNextToken(); // eat 'in'.
336 ExprAST *Body = ParseExpression();
337 if (Body == 0) return 0;
339 return new ForExprAST(IdName, Start, End, Step, Body);
343 /// ::= identifierexpr
348 static ExprAST *ParsePrimary() {
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();
360 /// ::= ('+' primary)*
361 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
362 // If this is a binop, find its precedence.
364 int TokPrec = GetTokPrecedence();
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)
371 // Okay, we know this is a binop.
373 getNextToken(); // eat binop
375 // Parse the primary expression after the binary operator.
376 ExprAST *RHS = ParsePrimary();
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;
388 LHS = new BinaryExprAST(BinOp, LHS, RHS);
393 /// ::= primary binoprhs
395 static ExprAST *ParseExpression() {
396 ExprAST *LHS = ParsePrimary();
399 return ParseBinOpRHS(0, LHS);
403 /// ::= id '(' id* ')'
404 static PrototypeAST *ParsePrototype() {
405 if (CurTok != tok_identifier)
406 return ErrorP("Expected function name in prototype");
408 std::string FnName = IdentifierStr;
412 return ErrorP("Expected '(' in prototype");
414 std::vector<std::string> ArgNames;
415 while (getNextToken() == tok_identifier)
416 ArgNames.push_back(IdentifierStr);
418 return ErrorP("Expected ')' in prototype");
421 getNextToken(); // eat ')'.
423 return new PrototypeAST(FnName, ArgNames);
426 /// definition ::= 'def' prototype expression
427 static FunctionAST *ParseDefinition() {
428 getNextToken(); // eat def.
429 PrototypeAST *Proto = ParsePrototype();
430 if (Proto == 0) return 0;
432 if (ExprAST *E = ParseExpression())
433 return new FunctionAST(Proto, E);
437 /// toplevelexpr ::= expression
438 static 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);
447 /// external ::= 'extern' prototype
448 static PrototypeAST *ParseExtern() {
449 getNextToken(); // eat extern.
450 return ParsePrototype();
453 //===----------------------------------------------------------------------===//
455 //===----------------------------------------------------------------------===//
457 static Module *TheModule;
458 static IRBuilder<> Builder(getGlobalContext());
459 static std::map<std::string, Value*> NamedValues;
460 static FunctionPassManager *TheFPM;
462 Value *ErrorV(const char *Str) { Error(Str); return 0; }
464 Value *NumberExprAST::Codegen() {
465 return ConstantFP::get(getGlobalContext(), APFloat(Val));
468 Value *VariableExprAST::Codegen() {
469 // Look this variable up in the function.
470 Value *V = NamedValues[Name];
471 return V ? V : ErrorV("Unknown variable name");
474 Value *BinaryExprAST::Codegen() {
475 Value *L = LHS->Codegen();
476 Value *R = RHS->Codegen();
477 if (L == 0 || R == 0) return 0;
480 case '+': return Builder.CreateFAdd(L, R, "addtmp");
481 case '-': return Builder.CreateFSub(L, R, "subtmp");
482 case '*': return Builder.CreateFMul(L, R, "multmp");
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()),
488 default: return ErrorV("invalid binary operator");
492 Value *CallExprAST::Codegen() {
493 // Look up the name in the global module table.
494 Function *CalleeF = TheModule->getFunction(Callee);
496 return ErrorV("Unknown function referenced");
498 // If argument mismatch error.
499 if (CalleeF->arg_size() != Args.size())
500 return ErrorV("Incorrect # arguments passed");
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;
508 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
511 Value *IfExprAST::Codegen() {
512 Value *CondV = Cond->Codegen();
513 if (CondV == 0) return 0;
515 // Convert condition to a bool by comparing equal to 0.0.
516 CondV = Builder.CreateFCmpONE(CondV,
517 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
520 Function *TheFunction = Builder.GetInsertBlock()->getParent();
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");
528 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
531 Builder.SetInsertPoint(ThenBB);
533 Value *ThenV = Then->Codegen();
534 if (ThenV == 0) return 0;
536 Builder.CreateBr(MergeBB);
537 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
538 ThenBB = Builder.GetInsertBlock();
541 TheFunction->getBasicBlockList().push_back(ElseBB);
542 Builder.SetInsertPoint(ElseBB);
544 Value *ElseV = Else->Codegen();
545 if (ElseV == 0) return 0;
547 Builder.CreateBr(MergeBB);
548 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
549 ElseBB = Builder.GetInsertBlock();
552 TheFunction->getBasicBlockList().push_back(MergeBB);
553 Builder.SetInsertPoint(MergeBB);
554 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
557 PN->addIncoming(ThenV, ThenBB);
558 PN->addIncoming(ElseV, ElseBB);
562 Value *ForExprAST::Codegen() {
568 // variable = phi [start, loopheader], [nextvariable, loopend]
574 // nextvariable = variable + step
576 // br endcond, loop, endloop
579 // Emit the start code first, without 'variable' in scope.
580 Value *StartVal = Start->Codegen();
581 if (StartVal == 0) return 0;
583 // Make the new basic block for the loop header, inserting after current
585 Function *TheFunction = Builder.GetInsertBlock()->getParent();
586 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
587 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
589 // Insert an explicit fall through from the current block to the LoopBB.
590 Builder.CreateBr(LoopBB);
592 // Start insertion in LoopBB.
593 Builder.SetInsertPoint(LoopBB);
595 // Start the PHI node with an entry for Start.
596 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
597 Variable->addIncoming(StartVal, PreheaderBB);
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;
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
607 if (Body->Codegen() == 0)
610 // Emit the step value.
613 StepVal = Step->Codegen();
614 if (StepVal == 0) return 0;
616 // If not specified, use 1.0.
617 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
620 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
622 // Compute the end condition.
623 Value *EndCond = End->Codegen();
624 if (EndCond == 0) return EndCond;
626 // Convert condition to a bool by comparing equal to 0.0.
627 EndCond = Builder.CreateFCmpONE(EndCond,
628 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
631 // Create the "after loop" block and insert it.
632 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
633 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
635 // Insert the conditional branch into the end of LoopEndBB.
636 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
638 // Any new code will be inserted in AfterBB.
639 Builder.SetInsertPoint(AfterBB);
641 // Add a new entry to the PHI node for the backedge.
642 Variable->addIncoming(NextVar, LoopEndBB);
644 // Restore the unshadowed variable.
646 NamedValues[VarName] = OldVal;
648 NamedValues.erase(VarName);
651 // for expr always returns 0.0.
652 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
655 Function *PrototypeAST::Codegen() {
656 // Make the function type: double(double,double) etc.
657 std::vector<Type*> Doubles(Args.size(),
658 Type::getDoubleTy(getGlobalContext()));
659 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
662 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
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);
671 // If F already has a body, reject this.
673 ErrorF("redefinition of function");
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");
684 // Set names for all arguments.
686 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
688 AI->setName(Args[Idx]);
690 // Add arguments to variable symbol table.
691 NamedValues[Args[Idx]] = AI;
697 Function *FunctionAST::Codegen() {
700 Function *TheFunction = Proto->Codegen();
701 if (TheFunction == 0)
704 // Create a new basic block to start insertion into.
705 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
706 Builder.SetInsertPoint(BB);
708 if (Value *RetVal = Body->Codegen()) {
709 // Finish off the function.
710 Builder.CreateRet(RetVal);
712 // Validate the generated code, checking for consistency.
713 verifyFunction(*TheFunction);
715 // Optimize the function.
716 TheFPM->run(*TheFunction);
721 // Error reading body, remove function.
722 TheFunction->eraseFromParent();
726 //===----------------------------------------------------------------------===//
727 // Top-Level parsing and JIT Driver
728 //===----------------------------------------------------------------------===//
730 static ExecutionEngine *TheExecutionEngine;
732 static void HandleDefinition() {
733 if (FunctionAST *F = ParseDefinition()) {
734 if (Function *LF = F->Codegen()) {
735 fprintf(stderr, "Read function definition:");
739 // Skip token for error recovery.
744 static void HandleExtern() {
745 if (PrototypeAST *P = ParseExtern()) {
746 if (Function *F = P->Codegen()) {
747 fprintf(stderr, "Read extern: ");
751 // Skip token for error recovery.
756 static 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);
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());
769 // Skip token for error recovery.
774 /// top ::= definition | external | expression | ';'
775 static void MainLoop() {
777 fprintf(stderr, "ready> ");
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;
788 //===----------------------------------------------------------------------===//
789 // "Library" functions that can be "extern'd" from user code.
790 //===----------------------------------------------------------------------===//
792 /// putchard - putchar that takes a double and returns 0.
794 double putchard(double X) {
799 //===----------------------------------------------------------------------===//
801 //===----------------------------------------------------------------------===//
804 InitializeNativeTarget();
805 LLVMContext &Context = getGlobalContext();
807 // Install standard binary operators.
808 // 1 is lowest precedence.
809 BinopPrecedence['<'] = 10;
810 BinopPrecedence['+'] = 20;
811 BinopPrecedence['-'] = 20;
812 BinopPrecedence['*'] = 40; // highest.
814 // Prime the first token.
815 fprintf(stderr, "ready> ");
818 // Make the module, which holds all the code.
819 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
820 TheModule = Owner.get();
822 // Create the JIT. This takes ownership of the module.
825 EngineBuilder(std::move(Owner)).setErrorStr(&ErrStr).create();
826 if (!TheExecutionEngine) {
827 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
831 FunctionPassManager OurFPM(TheModule);
833 // Set up the optimizer pipeline. Start with registering info about how the
834 // target lays out data structures.
835 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
836 OurFPM.add(new DataLayoutPass());
837 // Provide basic AliasAnalysis support for GVN.
838 OurFPM.add(createBasicAliasAnalysisPass());
839 // Do simple "peephole" optimizations and bit-twiddling optzns.
840 OurFPM.add(createInstructionCombiningPass());
841 // Reassociate expressions.
842 OurFPM.add(createReassociatePass());
843 // Eliminate Common SubExpressions.
844 OurFPM.add(createGVNPass());
845 // Simplify the control flow graph (deleting unreachable blocks, etc).
846 OurFPM.add(createCFGSimplificationPass());
848 OurFPM.doInitialization();
850 // Set the global so the code gen can use this.
853 // Run the main "interpreter loop" now.
858 // Print out all of the generated code.