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 {
128 NumberExprAST(double Val) : Val(Val) {}
129 Value *Codegen() override;
132 /// VariableExprAST - Expression class for referencing a variable, like "a".
133 class VariableExprAST : public ExprAST {
137 VariableExprAST(const std::string &Name) : Name(Name) {}
138 Value *Codegen() override;
141 /// BinaryExprAST - Expression class for a binary operator.
142 class BinaryExprAST : public ExprAST {
144 std::unique_ptr<ExprAST> LHS, RHS;
147 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
148 std::unique_ptr<ExprAST> RHS)
149 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
150 Value *Codegen() override;
153 /// CallExprAST - Expression class for function calls.
154 class CallExprAST : public ExprAST {
156 std::vector<std::unique_ptr<ExprAST>> Args;
159 CallExprAST(const std::string &Callee,
160 std::vector<std::unique_ptr<ExprAST>> Args)
161 : Callee(Callee), Args(std::move(Args)) {}
162 Value *Codegen() override;
165 /// IfExprAST - Expression class for if/then/else.
166 class IfExprAST : public ExprAST {
167 std::unique_ptr<ExprAST> Cond, Then, Else;
170 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
171 std::unique_ptr<ExprAST> Else)
172 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
173 Value *Codegen() override;
176 /// ForExprAST - Expression class for for/in.
177 class ForExprAST : public ExprAST {
179 std::unique_ptr<ExprAST> Start, End, Step, Body;
182 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
183 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
184 std::unique_ptr<ExprAST> Body)
185 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
186 Step(std::move(Step)), Body(std::move(Body)) {}
187 Value *Codegen() override;
190 /// PrototypeAST - This class represents the "prototype" for a function,
191 /// which captures its name, and its argument names (thus implicitly the number
192 /// of arguments the function takes).
195 std::vector<std::string> Args;
198 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
199 : Name(Name), Args(std::move(Args)) {}
203 /// FunctionAST - This class represents a function definition itself.
205 std::unique_ptr<PrototypeAST> Proto;
206 std::unique_ptr<ExprAST> Body;
209 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
210 std::unique_ptr<ExprAST> Body)
211 : Proto(std::move(Proto)), Body(std::move(Body)) {}
214 } // end anonymous namespace
216 //===----------------------------------------------------------------------===//
218 //===----------------------------------------------------------------------===//
220 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
221 /// token the parser is looking at. getNextToken reads another token from the
222 /// lexer and updates CurTok with its results.
224 static int getNextToken() { return CurTok = gettok(); }
226 /// BinopPrecedence - This holds the precedence for each binary operator that is
228 static std::map<char, int> BinopPrecedence;
230 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
231 static int GetTokPrecedence() {
232 if (!isascii(CurTok))
235 // Make sure it's a declared binop.
236 int TokPrec = BinopPrecedence[CurTok];
242 /// Error* - These are little helper functions for error handling.
243 std::unique_ptr<ExprAST> Error(const char *Str) {
244 fprintf(stderr, "Error: %s\n", Str);
247 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
251 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
256 static std::unique_ptr<ExprAST> ParseExpression();
258 /// numberexpr ::= number
259 static std::unique_ptr<ExprAST> ParseNumberExpr() {
260 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
261 getNextToken(); // consume the number
262 return std::move(Result);
265 /// parenexpr ::= '(' expression ')'
266 static std::unique_ptr<ExprAST> ParseParenExpr() {
267 getNextToken(); // eat (.
268 auto V = ParseExpression();
273 return Error("expected ')'");
274 getNextToken(); // eat ).
280 /// ::= identifier '(' expression* ')'
281 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
282 std::string IdName = IdentifierStr;
284 getNextToken(); // eat identifier.
286 if (CurTok != '(') // Simple variable ref.
287 return llvm::make_unique<VariableExprAST>(IdName);
290 getNextToken(); // eat (
291 std::vector<std::unique_ptr<ExprAST>> Args;
294 if (auto Arg = ParseExpression())
295 Args.push_back(std::move(Arg));
303 return Error("Expected ')' or ',' in argument list");
311 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
314 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
315 static std::unique_ptr<ExprAST> ParseIfExpr() {
316 getNextToken(); // eat the if.
319 auto Cond = ParseExpression();
323 if (CurTok != tok_then)
324 return Error("expected then");
325 getNextToken(); // eat the then
327 auto Then = ParseExpression();
331 if (CurTok != tok_else)
332 return Error("expected else");
336 auto Else = ParseExpression();
340 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
344 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
345 static std::unique_ptr<ExprAST> ParseForExpr() {
346 getNextToken(); // eat the for.
348 if (CurTok != tok_identifier)
349 return Error("expected identifier after for");
351 std::string IdName = IdentifierStr;
352 getNextToken(); // eat identifier.
355 return Error("expected '=' after for");
356 getNextToken(); // eat '='.
358 auto Start = ParseExpression();
362 return Error("expected ',' after for start value");
365 auto End = ParseExpression();
369 // The step value is optional.
370 std::unique_ptr<ExprAST> Step;
373 Step = ParseExpression();
378 if (CurTok != tok_in)
379 return Error("expected 'in' after for");
380 getNextToken(); // eat 'in'.
382 auto Body = ParseExpression();
386 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
387 std::move(Step), std::move(Body));
391 /// ::= identifierexpr
396 static std::unique_ptr<ExprAST> ParsePrimary() {
399 return Error("unknown token when expecting an expression");
401 return ParseIdentifierExpr();
403 return ParseNumberExpr();
405 return ParseParenExpr();
407 return ParseIfExpr();
409 return ParseForExpr();
414 /// ::= ('+' primary)*
415 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
416 std::unique_ptr<ExprAST> LHS) {
417 // If this is a binop, find its precedence.
419 int TokPrec = GetTokPrecedence();
421 // If this is a binop that binds at least as tightly as the current binop,
422 // consume it, otherwise we are done.
423 if (TokPrec < ExprPrec)
426 // Okay, we know this is a binop.
428 getNextToken(); // eat binop
430 // Parse the primary expression after the binary operator.
431 auto RHS = ParsePrimary();
435 // If BinOp binds less tightly with RHS than the operator after RHS, let
436 // the pending operator take RHS as its LHS.
437 int NextPrec = GetTokPrecedence();
438 if (TokPrec < NextPrec) {
439 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
446 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
451 /// ::= primary binoprhs
453 static std::unique_ptr<ExprAST> ParseExpression() {
454 auto LHS = ParsePrimary();
458 return ParseBinOpRHS(0, std::move(LHS));
462 /// ::= id '(' id* ')'
463 static std::unique_ptr<PrototypeAST> ParsePrototype() {
464 if (CurTok != tok_identifier)
465 return ErrorP("Expected function name in prototype");
467 std::string FnName = IdentifierStr;
471 return ErrorP("Expected '(' in prototype");
473 std::vector<std::string> ArgNames;
474 while (getNextToken() == tok_identifier)
475 ArgNames.push_back(IdentifierStr);
477 return ErrorP("Expected ')' in prototype");
480 getNextToken(); // eat ')'.
482 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
485 /// definition ::= 'def' prototype expression
486 static std::unique_ptr<FunctionAST> ParseDefinition() {
487 getNextToken(); // eat def.
488 auto Proto = ParsePrototype();
492 if (auto E = ParseExpression())
493 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
497 /// toplevelexpr ::= expression
498 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
499 if (auto E = ParseExpression()) {
500 // Make an anonymous proto.
502 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
503 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
508 /// external ::= 'extern' prototype
509 static std::unique_ptr<PrototypeAST> ParseExtern() {
510 getNextToken(); // eat extern.
511 return ParsePrototype();
514 //===----------------------------------------------------------------------===//
516 //===----------------------------------------------------------------------===//
518 static Module *TheModule;
519 static IRBuilder<> Builder(getGlobalContext());
520 static std::map<std::string, Value *> NamedValues;
521 static legacy::FunctionPassManager *TheFPM;
523 Value *ErrorV(const char *Str) {
528 Value *NumberExprAST::Codegen() {
529 return ConstantFP::get(getGlobalContext(), APFloat(Val));
532 Value *VariableExprAST::Codegen() {
533 // Look this variable up in the function.
534 Value *V = NamedValues[Name];
536 return ErrorV("Unknown variable name");
540 Value *BinaryExprAST::Codegen() {
541 Value *L = LHS->Codegen();
542 Value *R = RHS->Codegen();
548 return Builder.CreateFAdd(L, R, "addtmp");
550 return Builder.CreateFSub(L, R, "subtmp");
552 return Builder.CreateFMul(L, R, "multmp");
554 L = Builder.CreateFCmpULT(L, R, "cmptmp");
555 // Convert bool 0/1 to double 0.0 or 1.0
556 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
559 return ErrorV("invalid binary operator");
563 Value *CallExprAST::Codegen() {
564 // Look up the name in the global module table.
565 Function *CalleeF = TheModule->getFunction(Callee);
567 return ErrorV("Unknown function referenced");
569 // If argument mismatch error.
570 if (CalleeF->arg_size() != Args.size())
571 return ErrorV("Incorrect # arguments passed");
573 std::vector<Value *> ArgsV;
574 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
575 ArgsV.push_back(Args[i]->Codegen());
580 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
583 Value *IfExprAST::Codegen() {
584 Value *CondV = Cond->Codegen();
588 // Convert condition to a bool by comparing equal to 0.0.
589 CondV = Builder.CreateFCmpONE(
590 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
592 Function *TheFunction = Builder.GetInsertBlock()->getParent();
594 // Create blocks for the then and else cases. Insert the 'then' block at the
595 // end of the function.
597 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
598 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
599 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
601 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
604 Builder.SetInsertPoint(ThenBB);
606 Value *ThenV = Then->Codegen();
610 Builder.CreateBr(MergeBB);
611 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
612 ThenBB = Builder.GetInsertBlock();
615 TheFunction->getBasicBlockList().push_back(ElseBB);
616 Builder.SetInsertPoint(ElseBB);
618 Value *ElseV = Else->Codegen();
622 Builder.CreateBr(MergeBB);
623 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
624 ElseBB = Builder.GetInsertBlock();
627 TheFunction->getBasicBlockList().push_back(MergeBB);
628 Builder.SetInsertPoint(MergeBB);
630 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
632 PN->addIncoming(ThenV, ThenBB);
633 PN->addIncoming(ElseV, ElseBB);
637 // Output for-loop as:
642 // variable = phi [start, loopheader], [nextvariable, loopend]
648 // nextvariable = variable + step
650 // br endcond, loop, endloop
652 Value *ForExprAST::Codegen() {
653 // Emit the start code first, without 'variable' in scope.
654 Value *StartVal = Start->Codegen();
658 // Make the new basic block for the loop header, inserting after current
660 Function *TheFunction = Builder.GetInsertBlock()->getParent();
661 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
663 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
665 // Insert an explicit fall through from the current block to the LoopBB.
666 Builder.CreateBr(LoopBB);
668 // Start insertion in LoopBB.
669 Builder.SetInsertPoint(LoopBB);
671 // Start the PHI node with an entry for Start.
672 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
674 Variable->addIncoming(StartVal, PreheaderBB);
676 // Within the loop, the variable is defined equal to the PHI node. If it
677 // shadows an existing variable, we have to restore it, so save it now.
678 Value *OldVal = NamedValues[VarName];
679 NamedValues[VarName] = Variable;
681 // Emit the body of the loop. This, like any other expr, can change the
682 // current BB. Note that we ignore the value computed by the body, but don't
684 if (!Body->Codegen())
687 // Emit the step value.
688 Value *StepVal = nullptr;
690 StepVal = Step->Codegen();
694 // If not specified, use 1.0.
695 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
698 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
700 // Compute the end condition.
701 Value *EndCond = End->Codegen();
705 // Convert condition to a bool by comparing equal to 0.0.
706 EndCond = Builder.CreateFCmpONE(
707 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
709 // Create the "after loop" block and insert it.
710 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
711 BasicBlock *AfterBB =
712 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
714 // Insert the conditional branch into the end of LoopEndBB.
715 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
717 // Any new code will be inserted in AfterBB.
718 Builder.SetInsertPoint(AfterBB);
720 // Add a new entry to the PHI node for the backedge.
721 Variable->addIncoming(NextVar, LoopEndBB);
723 // Restore the unshadowed variable.
725 NamedValues[VarName] = OldVal;
727 NamedValues.erase(VarName);
729 // for expr always returns 0.0.
730 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
733 Function *PrototypeAST::Codegen() {
734 // Make the function type: double(double,double) etc.
735 std::vector<Type *> Doubles(Args.size(),
736 Type::getDoubleTy(getGlobalContext()));
738 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
741 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
743 // If F conflicted, there was already something named 'Name'. If it has a
744 // body, don't allow redefinition or reextern.
745 if (F->getName() != Name) {
746 // Delete the one we just made and get the existing one.
747 F->eraseFromParent();
748 F = TheModule->getFunction(Name);
750 // If F already has a body, reject this.
752 ErrorF("redefinition of function");
756 // If F took a different number of args, reject.
757 if (F->arg_size() != Args.size()) {
758 ErrorF("redefinition of function with different # args");
763 // Set names for all arguments.
765 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
767 AI->setName(Args[Idx]);
769 // Add arguments to variable symbol table.
770 NamedValues[Args[Idx]] = AI;
776 Function *FunctionAST::Codegen() {
779 Function *TheFunction = Proto->Codegen();
783 // Create a new basic block to start insertion into.
784 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
785 Builder.SetInsertPoint(BB);
787 if (Value *RetVal = Body->Codegen()) {
788 // Finish off the function.
789 Builder.CreateRet(RetVal);
791 // Validate the generated code, checking for consistency.
792 verifyFunction(*TheFunction);
794 // Optimize the function.
795 TheFPM->run(*TheFunction);
800 // Error reading body, remove function.
801 TheFunction->eraseFromParent();
805 //===----------------------------------------------------------------------===//
806 // Top-Level parsing and JIT Driver
807 //===----------------------------------------------------------------------===//
809 static ExecutionEngine *TheExecutionEngine;
811 static void HandleDefinition() {
812 if (auto FnAST = ParseDefinition()) {
813 if (auto *FnIR = FnAST->Codegen()) {
814 fprintf(stderr, "Read function definition:");
818 // Skip token for error recovery.
823 static void HandleExtern() {
824 if (auto ProtoAST = ParseExtern()) {
825 if (auto *FnIR = ProtoAST->Codegen()) {
826 fprintf(stderr, "Read extern: ");
830 // Skip token for error recovery.
835 static void HandleTopLevelExpression() {
836 // Evaluate a top-level expression into an anonymous function.
837 if (auto FnAST = ParseTopLevelExpr()) {
838 if (auto *FnIR = FnAST->Codegen()) {
839 TheExecutionEngine->finalizeObject();
840 // JIT the function, returning a function pointer.
841 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
843 // Cast it to the right type (takes no arguments, returns a double) so we
844 // can call it as a native function.
845 double (*FP)() = (double (*)())(intptr_t)FPtr;
846 fprintf(stderr, "Evaluated to %f\n", FP());
849 // Skip token for error recovery.
854 /// top ::= definition | external | expression | ';'
855 static void MainLoop() {
857 fprintf(stderr, "ready> ");
861 case ';': // ignore top-level semicolons.
871 HandleTopLevelExpression();
877 //===----------------------------------------------------------------------===//
878 // "Library" functions that can be "extern'd" from user code.
879 //===----------------------------------------------------------------------===//
881 /// putchard - putchar that takes a double and returns 0.
882 extern "C" double putchard(double X) {
887 /// printd - printf that takes a double prints it as "%f\n", returning 0.
888 extern "C" double printd(double X) {
893 //===----------------------------------------------------------------------===//
895 //===----------------------------------------------------------------------===//
898 InitializeNativeTarget();
899 InitializeNativeTargetAsmPrinter();
900 InitializeNativeTargetAsmParser();
901 LLVMContext &Context = getGlobalContext();
903 // Install standard binary operators.
904 // 1 is lowest precedence.
905 BinopPrecedence['<'] = 10;
906 BinopPrecedence['+'] = 20;
907 BinopPrecedence['-'] = 20;
908 BinopPrecedence['*'] = 40; // highest.
910 // Prime the first token.
911 fprintf(stderr, "ready> ");
914 // Make the module, which holds all the code.
915 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
916 TheModule = Owner.get();
918 // Create the JIT. This takes ownership of the module.
921 EngineBuilder(std::move(Owner))
922 .setErrorStr(&ErrStr)
923 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
925 if (!TheExecutionEngine) {
926 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
930 legacy::FunctionPassManager OurFPM(TheModule);
932 // Set up the optimizer pipeline. Start with registering info about how the
933 // target lays out data structures.
934 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
935 // Provide basic AliasAnalysis support for GVN.
936 OurFPM.add(createBasicAliasAnalysisPass());
937 // Do simple "peephole" optimizations and bit-twiddling optzns.
938 OurFPM.add(createInstructionCombiningPass());
939 // Reassociate expressions.
940 OurFPM.add(createReassociatePass());
941 // Eliminate Common SubExpressions.
942 OurFPM.add(createGVNPass());
943 // Simplify the control flow graph (deleting unreachable blocks, etc).
944 OurFPM.add(createCFGSimplificationPass());
946 OurFPM.doInitialization();
948 // Set the global so the code gen can use this.
951 // Run the main "interpreter loop" now.
956 // Print out all of the generated code.