1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28 // of these for known things.
48 static std::string IdentifierStr; // Filled in if tok_identifier
49 static double NumVal; // Filled in if tok_number
51 /// gettok - Return the next token from standard input.
53 static int LastChar = ' ';
55 // Skip any whitespace.
56 while (isspace(LastChar))
59 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
60 IdentifierStr = LastChar;
61 while (isalnum((LastChar = getchar())))
62 IdentifierStr += LastChar;
64 if (IdentifierStr == "def")
66 if (IdentifierStr == "extern")
68 if (IdentifierStr == "if")
70 if (IdentifierStr == "then")
72 if (IdentifierStr == "else")
74 if (IdentifierStr == "for")
76 if (IdentifierStr == "in")
78 return tok_identifier;
81 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
86 } while (isdigit(LastChar) || LastChar == '.');
88 NumVal = strtod(NumStr.c_str(), 0);
92 if (LastChar == '#') {
93 // Comment until end of line.
96 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
102 // Check for end of file. Don't eat the EOF.
106 // Otherwise, just return the character as its ascii value.
107 int ThisChar = LastChar;
108 LastChar = getchar();
112 //===----------------------------------------------------------------------===//
113 // Abstract Syntax Tree (aka Parse Tree)
114 //===----------------------------------------------------------------------===//
116 /// ExprAST - Base class for all expression nodes.
119 virtual ~ExprAST() {}
120 virtual Value *Codegen() = 0;
123 /// NumberExprAST - Expression class for numeric literals like "1.0".
124 class NumberExprAST : public ExprAST {
127 NumberExprAST(double Val) : Val(Val) {}
128 Value *Codegen() override;
131 /// VariableExprAST - Expression class for referencing a variable, like "a".
132 class VariableExprAST : public ExprAST {
135 VariableExprAST(const std::string &Name) : Name(Name) {}
136 Value *Codegen() override;
139 /// BinaryExprAST - Expression class for a binary operator.
140 class BinaryExprAST : public ExprAST {
142 std::unique_ptr<ExprAST> LHS, RHS;
144 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
145 std::unique_ptr<ExprAST> RHS)
146 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
147 Value *Codegen() override;
150 /// CallExprAST - Expression class for function calls.
151 class CallExprAST : public ExprAST {
153 std::vector<std::unique_ptr<ExprAST>> Args;
155 CallExprAST(const std::string &Callee,
156 std::vector<std::unique_ptr<ExprAST>> Args)
157 : Callee(Callee), Args(std::move(Args)) {}
158 Value *Codegen() override;
161 /// IfExprAST - Expression class for if/then/else.
162 class IfExprAST : public ExprAST {
163 std::unique_ptr<ExprAST> Cond, Then, Else;
165 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
166 std::unique_ptr<ExprAST> Else)
167 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
168 Value *Codegen() override;
171 /// ForExprAST - Expression class for for/in.
172 class ForExprAST : public ExprAST {
174 std::unique_ptr<ExprAST> Start, End, Step, Body;
176 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
177 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
178 std::unique_ptr<ExprAST> Body)
179 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
180 Step(std::move(Step)), Body(std::move(Body)) {}
181 Value *Codegen() override;
184 /// PrototypeAST - This class represents the "prototype" for a function,
185 /// which captures its name, and its argument names (thus implicitly the number
186 /// of arguments the function takes).
189 std::vector<std::string> Args;
191 PrototypeAST(const std::string &name, std::vector<std::string> Args)
192 : Name(name), Args(std::move(Args)) {}
196 /// FunctionAST - This class represents a function definition itself.
198 std::unique_ptr<PrototypeAST> Proto;
199 std::unique_ptr<ExprAST> Body;
201 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
202 std::unique_ptr<ExprAST> Body)
203 : Proto(std::move(Proto)), Body(std::move(Body)) {}
206 } // end anonymous namespace
208 //===----------------------------------------------------------------------===//
210 //===----------------------------------------------------------------------===//
212 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
213 /// token the parser is looking at. getNextToken reads another token from the
214 /// lexer and updates CurTok with its results.
216 static int getNextToken() { return CurTok = gettok(); }
218 /// BinopPrecedence - This holds the precedence for each binary operator that is
220 static std::map<char, int> BinopPrecedence;
222 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
223 static int GetTokPrecedence() {
224 if (!isascii(CurTok))
227 // Make sure it's a declared binop.
228 int TokPrec = BinopPrecedence[CurTok];
234 /// Error* - These are little helper functions for error handling.
235 std::unique_ptr<ExprAST> Error(const char *Str) {
236 fprintf(stderr, "Error: %s\n", Str);
239 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
243 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
248 static std::unique_ptr<ExprAST> ParseExpression();
252 /// ::= identifier '(' expression* ')'
253 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
254 std::string IdName = IdentifierStr;
256 getNextToken(); // eat identifier.
258 if (CurTok != '(') // Simple variable ref.
259 return llvm::make_unique<VariableExprAST>(IdName);
262 getNextToken(); // eat (
263 std::vector<std::unique_ptr<ExprAST>> Args;
266 if (auto Arg = ParseExpression())
267 Args.push_back(std::move(Arg));
275 return Error("Expected ')' or ',' in argument list");
283 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
286 /// numberexpr ::= number
287 static std::unique_ptr<ExprAST> ParseNumberExpr() {
288 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
289 getNextToken(); // consume the number
290 return std::move(Result);
293 /// parenexpr ::= '(' expression ')'
294 static std::unique_ptr<ExprAST> ParseParenExpr() {
295 getNextToken(); // eat (.
296 auto V = ParseExpression();
301 return Error("expected ')'");
302 getNextToken(); // eat ).
306 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
307 static std::unique_ptr<ExprAST> ParseIfExpr() {
308 getNextToken(); // eat the if.
311 auto Cond = ParseExpression();
315 if (CurTok != tok_then)
316 return Error("expected then");
317 getNextToken(); // eat the then
319 auto Then = ParseExpression();
323 if (CurTok != tok_else)
324 return Error("expected else");
328 auto Else = ParseExpression();
332 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
336 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
337 static std::unique_ptr<ExprAST> ParseForExpr() {
338 getNextToken(); // eat the for.
340 if (CurTok != tok_identifier)
341 return Error("expected identifier after for");
343 std::string IdName = IdentifierStr;
344 getNextToken(); // eat identifier.
347 return Error("expected '=' after for");
348 getNextToken(); // eat '='.
350 auto Start = ParseExpression();
354 return Error("expected ',' after for start value");
357 auto End = ParseExpression();
361 // The step value is optional.
362 std::unique_ptr<ExprAST> Step;
365 Step = ParseExpression();
370 if (CurTok != tok_in)
371 return Error("expected 'in' after for");
372 getNextToken(); // eat 'in'.
374 auto Body = ParseExpression();
378 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
379 std::move(Step), std::move(Body));
383 /// ::= identifierexpr
388 static std::unique_ptr<ExprAST> ParsePrimary() {
391 return Error("unknown token when expecting an expression");
393 return ParseIdentifierExpr();
395 return ParseNumberExpr();
397 return ParseParenExpr();
399 return ParseIfExpr();
401 return ParseForExpr();
406 /// ::= ('+' primary)*
407 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
408 std::unique_ptr<ExprAST> LHS) {
409 // If this is a binop, find its precedence.
411 int TokPrec = GetTokPrecedence();
413 // If this is a binop that binds at least as tightly as the current binop,
414 // consume it, otherwise we are done.
415 if (TokPrec < ExprPrec)
418 // Okay, we know this is a binop.
420 getNextToken(); // eat binop
422 // Parse the primary expression after the binary operator.
423 auto RHS = ParsePrimary();
427 // If BinOp binds less tightly with RHS than the operator after RHS, let
428 // the pending operator take RHS as its LHS.
429 int NextPrec = GetTokPrecedence();
430 if (TokPrec < NextPrec) {
431 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
437 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS),
443 /// ::= primary binoprhs
445 static std::unique_ptr<ExprAST> ParseExpression() {
446 auto LHS = ParsePrimary();
450 return ParseBinOpRHS(0, std::move(LHS));
454 /// ::= id '(' id* ')'
455 static std::unique_ptr<PrototypeAST> ParsePrototype() {
456 if (CurTok != tok_identifier)
457 return ErrorP("Expected function name in prototype");
459 std::string FnName = IdentifierStr;
463 return ErrorP("Expected '(' in prototype");
465 std::vector<std::string> ArgNames;
466 while (getNextToken() == tok_identifier)
467 ArgNames.push_back(IdentifierStr);
469 return ErrorP("Expected ')' in prototype");
472 getNextToken(); // eat ')'.
474 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
477 /// definition ::= 'def' prototype expression
478 static std::unique_ptr<FunctionAST> ParseDefinition() {
479 getNextToken(); // eat def.
480 auto Proto = ParsePrototype();
484 if (auto E = ParseExpression())
485 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
489 /// toplevelexpr ::= expression
490 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
491 if (auto E = ParseExpression()) {
492 // Make an anonymous proto.
493 auto Proto = llvm::make_unique<PrototypeAST>("",
494 std::vector<std::string>());
495 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
500 /// external ::= 'extern' prototype
501 static std::unique_ptr<PrototypeAST> ParseExtern() {
502 getNextToken(); // eat extern.
503 return ParsePrototype();
506 //===----------------------------------------------------------------------===//
508 //===----------------------------------------------------------------------===//
510 static Module *TheModule;
511 static IRBuilder<> Builder(getGlobalContext());
512 static std::map<std::string, Value *> NamedValues;
513 static legacy::FunctionPassManager *TheFPM;
515 Value *ErrorV(const char *Str) {
520 Value *NumberExprAST::Codegen() {
521 return ConstantFP::get(getGlobalContext(), APFloat(Val));
524 Value *VariableExprAST::Codegen() {
525 // Look this variable up in the function.
526 Value *V = NamedValues[Name];
527 return V ? V : ErrorV("Unknown variable name");
530 Value *BinaryExprAST::Codegen() {
531 Value *L = LHS->Codegen();
532 Value *R = RHS->Codegen();
538 return Builder.CreateFAdd(L, R, "addtmp");
540 return Builder.CreateFSub(L, R, "subtmp");
542 return Builder.CreateFMul(L, R, "multmp");
544 L = Builder.CreateFCmpULT(L, R, "cmptmp");
545 // Convert bool 0/1 to double 0.0 or 1.0
546 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
549 return ErrorV("invalid binary operator");
553 Value *CallExprAST::Codegen() {
554 // Look up the name in the global module table.
555 Function *CalleeF = TheModule->getFunction(Callee);
557 return ErrorV("Unknown function referenced");
559 // If argument mismatch error.
560 if (CalleeF->arg_size() != Args.size())
561 return ErrorV("Incorrect # arguments passed");
563 std::vector<Value *> ArgsV;
564 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
565 ArgsV.push_back(Args[i]->Codegen());
570 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
573 Value *IfExprAST::Codegen() {
574 Value *CondV = Cond->Codegen();
578 // Convert condition to a bool by comparing equal to 0.0.
579 CondV = Builder.CreateFCmpONE(
580 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
582 Function *TheFunction = Builder.GetInsertBlock()->getParent();
584 // Create blocks for the then and else cases. Insert the 'then' block at the
585 // end of the function.
587 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
588 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
589 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
591 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
594 Builder.SetInsertPoint(ThenBB);
596 Value *ThenV = Then->Codegen();
600 Builder.CreateBr(MergeBB);
601 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
602 ThenBB = Builder.GetInsertBlock();
605 TheFunction->getBasicBlockList().push_back(ElseBB);
606 Builder.SetInsertPoint(ElseBB);
608 Value *ElseV = Else->Codegen();
612 Builder.CreateBr(MergeBB);
613 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
614 ElseBB = Builder.GetInsertBlock();
617 TheFunction->getBasicBlockList().push_back(MergeBB);
618 Builder.SetInsertPoint(MergeBB);
620 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
622 PN->addIncoming(ThenV, ThenBB);
623 PN->addIncoming(ElseV, ElseBB);
627 Value *ForExprAST::Codegen() {
633 // variable = phi [start, loopheader], [nextvariable, loopend]
639 // nextvariable = variable + step
641 // br endcond, loop, endloop
644 // Emit the start code first, without 'variable' in scope.
645 Value *StartVal = Start->Codegen();
649 // Make the new basic block for the loop header, inserting after current
651 Function *TheFunction = Builder.GetInsertBlock()->getParent();
652 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
654 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
656 // Insert an explicit fall through from the current block to the LoopBB.
657 Builder.CreateBr(LoopBB);
659 // Start insertion in LoopBB.
660 Builder.SetInsertPoint(LoopBB);
662 // Start the PHI node with an entry for Start.
663 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
665 Variable->addIncoming(StartVal, PreheaderBB);
667 // Within the loop, the variable is defined equal to the PHI node. If it
668 // shadows an existing variable, we have to restore it, so save it now.
669 Value *OldVal = NamedValues[VarName];
670 NamedValues[VarName] = Variable;
672 // Emit the body of the loop. This, like any other expr, can change the
673 // current BB. Note that we ignore the value computed by the body, but don't
675 if (!Body->Codegen())
678 // Emit the step value.
681 StepVal = Step->Codegen();
685 // If not specified, use 1.0.
686 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
689 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
691 // Compute the end condition.
692 Value *EndCond = End->Codegen();
696 // Convert condition to a bool by comparing equal to 0.0.
697 EndCond = Builder.CreateFCmpONE(
698 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
700 // Create the "after loop" block and insert it.
701 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
702 BasicBlock *AfterBB =
703 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
705 // Insert the conditional branch into the end of LoopEndBB.
706 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
708 // Any new code will be inserted in AfterBB.
709 Builder.SetInsertPoint(AfterBB);
711 // Add a new entry to the PHI node for the backedge.
712 Variable->addIncoming(NextVar, LoopEndBB);
714 // Restore the unshadowed variable.
716 NamedValues[VarName] = OldVal;
718 NamedValues.erase(VarName);
720 // for expr always returns 0.0.
721 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
724 Function *PrototypeAST::Codegen() {
725 // Make the function type: double(double,double) etc.
726 std::vector<Type *> Doubles(Args.size(),
727 Type::getDoubleTy(getGlobalContext()));
729 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
732 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
734 // If F conflicted, there was already something named 'Name'. If it has a
735 // body, don't allow redefinition or reextern.
736 if (F->getName() != Name) {
737 // Delete the one we just made and get the existing one.
738 F->eraseFromParent();
739 F = TheModule->getFunction(Name);
741 // If F already has a body, reject this.
743 ErrorF("redefinition of function");
747 // If F took a different number of args, reject.
748 if (F->arg_size() != Args.size()) {
749 ErrorF("redefinition of function with different # args");
754 // Set names for all arguments.
756 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
758 AI->setName(Args[Idx]);
760 // Add arguments to variable symbol table.
761 NamedValues[Args[Idx]] = AI;
767 Function *FunctionAST::Codegen() {
770 Function *TheFunction = Proto->Codegen();
774 // Create a new basic block to start insertion into.
775 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
776 Builder.SetInsertPoint(BB);
778 if (Value *RetVal = Body->Codegen()) {
779 // Finish off the function.
780 Builder.CreateRet(RetVal);
782 // Validate the generated code, checking for consistency.
783 verifyFunction(*TheFunction);
785 // Optimize the function.
786 TheFPM->run(*TheFunction);
791 // Error reading body, remove function.
792 TheFunction->eraseFromParent();
796 //===----------------------------------------------------------------------===//
797 // Top-Level parsing and JIT Driver
798 //===----------------------------------------------------------------------===//
800 static ExecutionEngine *TheExecutionEngine;
802 static void HandleDefinition() {
803 if (auto FnAST = ParseDefinition()) {
804 if (auto *FnIR = FnAST->Codegen()) {
805 fprintf(stderr, "Read function definition:");
809 // Skip token for error recovery.
814 static void HandleExtern() {
815 if (auto ProtoAST = ParseExtern()) {
816 if (auto *FnIR = ProtoAST->Codegen()) {
817 fprintf(stderr, "Read extern: ");
821 // Skip token for error recovery.
826 static void HandleTopLevelExpression() {
827 // Evaluate a top-level expression into an anonymous function.
828 if (auto FnAST = ParseTopLevelExpr()) {
829 if (auto *FnIR = FnAST->Codegen()) {
830 TheExecutionEngine->finalizeObject();
831 // JIT the function, returning a function pointer.
832 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
834 // Cast it to the right type (takes no arguments, returns a double) so we
835 // can call it as a native function.
836 double (*FP)() = (double (*)())(intptr_t)FPtr;
837 fprintf(stderr, "Evaluated to %f\n", FP());
840 // Skip token for error recovery.
845 /// top ::= definition | external | expression | ';'
846 static void MainLoop() {
848 fprintf(stderr, "ready> ");
854 break; // ignore top-level semicolons.
862 HandleTopLevelExpression();
868 //===----------------------------------------------------------------------===//
869 // "Library" functions that can be "extern'd" from user code.
870 //===----------------------------------------------------------------------===//
872 /// putchard - putchar that takes a double and returns 0.
873 extern "C" double putchard(double X) {
878 //===----------------------------------------------------------------------===//
880 //===----------------------------------------------------------------------===//
883 InitializeNativeTarget();
884 InitializeNativeTargetAsmPrinter();
885 InitializeNativeTargetAsmParser();
886 LLVMContext &Context = getGlobalContext();
888 // Install standard binary operators.
889 // 1 is lowest precedence.
890 BinopPrecedence['<'] = 10;
891 BinopPrecedence['+'] = 20;
892 BinopPrecedence['-'] = 20;
893 BinopPrecedence['*'] = 40; // highest.
895 // Prime the first token.
896 fprintf(stderr, "ready> ");
899 // Make the module, which holds all the code.
900 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
901 TheModule = Owner.get();
903 // Create the JIT. This takes ownership of the module.
906 EngineBuilder(std::move(Owner))
907 .setErrorStr(&ErrStr)
908 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
910 if (!TheExecutionEngine) {
911 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
915 legacy::FunctionPassManager OurFPM(TheModule);
917 // Set up the optimizer pipeline. Start with registering info about how the
918 // target lays out data structures.
919 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
920 // Provide basic AliasAnalysis support for GVN.
921 OurFPM.add(createBasicAliasAnalysisPass());
922 // Do simple "peephole" optimizations and bit-twiddling optzns.
923 OurFPM.add(createInstructionCombiningPass());
924 // Reassociate expressions.
925 OurFPM.add(createReassociatePass());
926 // Eliminate Common SubExpressions.
927 OurFPM.add(createGVNPass());
928 // Simplify the control flow graph (deleting unreachable blocks, etc).
929 OurFPM.add(createCFGSimplificationPass());
931 OurFPM.doInitialization();
933 // Set the global so the code gen can use this.
936 // Run the main "interpreter loop" now.
941 // Print out all of the generated code.