1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/IR/IRBuilder.h"
5 #include "llvm/IR/LLVMContext.h"
6 #include "llvm/IR/LegacyPassManager.h"
7 #include "llvm/IR/Module.h"
8 #include "llvm/IR/Verifier.h"
9 #include "llvm/Support/TargetSelect.h"
10 #include "llvm/Transforms/Scalar.h"
16 #include "../include/KaleidoscopeJIT.h"
19 using namespace llvm::orc;
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26 // of these for known things.
46 static std::string IdentifierStr; // Filled in if tok_identifier
47 static double NumVal; // Filled in if tok_number
49 /// gettok - Return the next token from standard input.
51 static int LastChar = ' ';
53 // Skip any whitespace.
54 while (isspace(LastChar))
57 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
58 IdentifierStr = LastChar;
59 while (isalnum((LastChar = getchar())))
60 IdentifierStr += LastChar;
62 if (IdentifierStr == "def")
64 if (IdentifierStr == "extern")
66 if (IdentifierStr == "if")
68 if (IdentifierStr == "then")
70 if (IdentifierStr == "else")
72 if (IdentifierStr == "for")
74 if (IdentifierStr == "in")
76 return tok_identifier;
79 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
84 } while (isdigit(LastChar) || LastChar == '.');
86 NumVal = strtod(NumStr.c_str(), 0);
90 if (LastChar == '#') {
91 // Comment until end of line.
94 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
100 // Check for end of file. Don't eat the EOF.
104 // Otherwise, just return the character as its ascii value.
105 int ThisChar = LastChar;
106 LastChar = getchar();
110 //===----------------------------------------------------------------------===//
111 // Abstract Syntax Tree (aka Parse Tree)
112 //===----------------------------------------------------------------------===//
114 /// ExprAST - Base class for all expression nodes.
117 virtual ~ExprAST() {}
118 virtual Value *codegen() = 0;
121 /// NumberExprAST - Expression class for numeric literals like "1.0".
122 class NumberExprAST : public ExprAST {
126 NumberExprAST(double Val) : Val(Val) {}
127 Value *codegen() override;
130 /// VariableExprAST - Expression class for referencing a variable, like "a".
131 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;
145 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
146 std::unique_ptr<ExprAST> RHS)
147 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
148 Value *codegen() override;
151 /// CallExprAST - Expression class for function calls.
152 class CallExprAST : public ExprAST {
154 std::vector<std::unique_ptr<ExprAST>> Args;
157 CallExprAST(const std::string &Callee,
158 std::vector<std::unique_ptr<ExprAST>> Args)
159 : Callee(Callee), Args(std::move(Args)) {}
160 Value *codegen() override;
163 /// IfExprAST - Expression class for if/then/else.
164 class IfExprAST : public ExprAST {
165 std::unique_ptr<ExprAST> Cond, Then, Else;
168 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
169 std::unique_ptr<ExprAST> Else)
170 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
171 Value *codegen() override;
174 /// ForExprAST - Expression class for for/in.
175 class ForExprAST : public ExprAST {
177 std::unique_ptr<ExprAST> Start, End, Step, Body;
180 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
181 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
182 std::unique_ptr<ExprAST> Body)
183 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
184 Step(std::move(Step)), Body(std::move(Body)) {}
185 Value *codegen() override;
188 /// PrototypeAST - This class represents the "prototype" for a function,
189 /// which captures its name, and its argument names (thus implicitly the number
190 /// of arguments the function takes).
193 std::vector<std::string> Args;
196 PrototypeAST(const std::string &Name, std::vector<std::string> Args)
197 : Name(Name), Args(std::move(Args)) {}
199 const std::string &getName() const { return Name; }
202 /// FunctionAST - This class represents a function definition itself.
204 std::unique_ptr<PrototypeAST> Proto;
205 std::unique_ptr<ExprAST> Body;
208 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
209 std::unique_ptr<ExprAST> Body)
210 : Proto(std::move(Proto)), Body(std::move(Body)) {}
213 } // end anonymous namespace
215 //===----------------------------------------------------------------------===//
217 //===----------------------------------------------------------------------===//
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.
223 static int getNextToken() { return CurTok = gettok(); }
225 /// BinopPrecedence - This holds the precedence for each binary operator that is
227 static std::map<char, int> BinopPrecedence;
229 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
230 static int GetTokPrecedence() {
231 if (!isascii(CurTok))
234 // Make sure it's a declared binop.
235 int TokPrec = BinopPrecedence[CurTok];
241 /// Error* - These are little helper functions for error handling.
242 std::unique_ptr<ExprAST> Error(const char *Str) {
243 fprintf(stderr, "Error: %s\n", Str);
246 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
251 static std::unique_ptr<ExprAST> ParseExpression();
253 /// numberexpr ::= number
254 static std::unique_ptr<ExprAST> ParseNumberExpr() {
255 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
256 getNextToken(); // consume the number
257 return std::move(Result);
260 /// parenexpr ::= '(' expression ')'
261 static std::unique_ptr<ExprAST> ParseParenExpr() {
262 getNextToken(); // eat (.
263 auto V = ParseExpression();
268 return Error("expected ')'");
269 getNextToken(); // eat ).
275 /// ::= identifier '(' expression* ')'
276 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
277 std::string IdName = IdentifierStr;
279 getNextToken(); // eat identifier.
281 if (CurTok != '(') // Simple variable ref.
282 return llvm::make_unique<VariableExprAST>(IdName);
285 getNextToken(); // eat (
286 std::vector<std::unique_ptr<ExprAST>> Args;
289 if (auto Arg = ParseExpression())
290 Args.push_back(std::move(Arg));
298 return Error("Expected ')' or ',' in argument list");
306 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
309 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
310 static std::unique_ptr<ExprAST> ParseIfExpr() {
311 getNextToken(); // eat the if.
314 auto Cond = ParseExpression();
318 if (CurTok != tok_then)
319 return Error("expected then");
320 getNextToken(); // eat the then
322 auto Then = ParseExpression();
326 if (CurTok != tok_else)
327 return Error("expected else");
331 auto Else = ParseExpression();
335 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
339 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
340 static std::unique_ptr<ExprAST> ParseForExpr() {
341 getNextToken(); // eat the for.
343 if (CurTok != tok_identifier)
344 return Error("expected identifier after for");
346 std::string IdName = IdentifierStr;
347 getNextToken(); // eat identifier.
350 return Error("expected '=' after for");
351 getNextToken(); // eat '='.
353 auto Start = ParseExpression();
357 return Error("expected ',' after for start value");
360 auto End = ParseExpression();
364 // The step value is optional.
365 std::unique_ptr<ExprAST> Step;
368 Step = ParseExpression();
373 if (CurTok != tok_in)
374 return Error("expected 'in' after for");
375 getNextToken(); // eat 'in'.
377 auto Body = ParseExpression();
381 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
382 std::move(Step), std::move(Body));
386 /// ::= identifierexpr
391 static std::unique_ptr<ExprAST> ParsePrimary() {
394 return Error("unknown token when expecting an expression");
396 return ParseIdentifierExpr();
398 return ParseNumberExpr();
400 return ParseParenExpr();
402 return ParseIfExpr();
404 return ParseForExpr();
409 /// ::= ('+' primary)*
410 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
411 std::unique_ptr<ExprAST> LHS) {
412 // If this is a binop, find its precedence.
414 int TokPrec = GetTokPrecedence();
416 // If this is a binop that binds at least as tightly as the current binop,
417 // consume it, otherwise we are done.
418 if (TokPrec < ExprPrec)
421 // Okay, we know this is a binop.
423 getNextToken(); // eat binop
425 // Parse the primary expression after the binary operator.
426 auto RHS = ParsePrimary();
430 // If BinOp binds less tightly with RHS than the operator after RHS, let
431 // the pending operator take RHS as its LHS.
432 int NextPrec = GetTokPrecedence();
433 if (TokPrec < NextPrec) {
434 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
441 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
446 /// ::= primary binoprhs
448 static std::unique_ptr<ExprAST> ParseExpression() {
449 auto LHS = ParsePrimary();
453 return ParseBinOpRHS(0, std::move(LHS));
457 /// ::= id '(' id* ')'
458 static std::unique_ptr<PrototypeAST> ParsePrototype() {
459 if (CurTok != tok_identifier)
460 return ErrorP("Expected function name in prototype");
462 std::string FnName = IdentifierStr;
466 return ErrorP("Expected '(' in prototype");
468 std::vector<std::string> ArgNames;
469 while (getNextToken() == tok_identifier)
470 ArgNames.push_back(IdentifierStr);
472 return ErrorP("Expected ')' in prototype");
475 getNextToken(); // eat ')'.
477 return llvm::make_unique<PrototypeAST>(FnName, std::move(ArgNames));
480 /// definition ::= 'def' prototype expression
481 static std::unique_ptr<FunctionAST> ParseDefinition() {
482 getNextToken(); // eat def.
483 auto Proto = ParsePrototype();
487 if (auto E = ParseExpression())
488 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
492 /// toplevelexpr ::= expression
493 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
494 if (auto E = ParseExpression()) {
495 // Make an anonymous proto.
496 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
497 std::vector<std::string>());
498 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
503 /// external ::= 'extern' prototype
504 static std::unique_ptr<PrototypeAST> ParseExtern() {
505 getNextToken(); // eat extern.
506 return ParsePrototype();
509 //===----------------------------------------------------------------------===//
511 //===----------------------------------------------------------------------===//
513 static std::unique_ptr<Module> TheModule;
514 static IRBuilder<> Builder(getGlobalContext());
515 static std::map<std::string, Value *> NamedValues;
516 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
517 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
518 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
520 Value *ErrorV(const char *Str) {
525 Function *getFunction(std::string Name) {
526 // First, see if the function has already been added to the current module.
527 if (auto *F = TheModule->getFunction(Name))
530 // If not, check whether we can codegen the declaration from some existing
532 auto FI = FunctionProtos.find(Name);
533 if (FI != FunctionProtos.end())
534 return FI->second->codegen();
536 // If no existing prototype exists, return null.
540 Value *NumberExprAST::codegen() {
541 return ConstantFP::get(getGlobalContext(), APFloat(Val));
544 Value *VariableExprAST::codegen() {
545 // Look this variable up in the function.
546 Value *V = NamedValues[Name];
548 return ErrorV("Unknown variable name");
552 Value *BinaryExprAST::codegen() {
553 Value *L = LHS->codegen();
554 Value *R = RHS->codegen();
560 return Builder.CreateFAdd(L, R, "addtmp");
562 return Builder.CreateFSub(L, R, "subtmp");
564 return Builder.CreateFMul(L, R, "multmp");
566 L = Builder.CreateFCmpULT(L, R, "cmptmp");
567 // Convert bool 0/1 to double 0.0 or 1.0
568 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
571 return ErrorV("invalid binary operator");
575 Value *CallExprAST::codegen() {
576 // Look up the name in the global module table.
577 Function *CalleeF = getFunction(Callee);
579 return ErrorV("Unknown function referenced");
581 // If argument mismatch error.
582 if (CalleeF->arg_size() != Args.size())
583 return ErrorV("Incorrect # arguments passed");
585 std::vector<Value *> ArgsV;
586 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
587 ArgsV.push_back(Args[i]->codegen());
592 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
595 Value *IfExprAST::codegen() {
596 Value *CondV = Cond->codegen();
600 // Convert condition to a bool by comparing equal to 0.0.
601 CondV = Builder.CreateFCmpONE(
602 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
604 Function *TheFunction = Builder.GetInsertBlock()->getParent();
606 // Create blocks for the then and else cases. Insert the 'then' block at the
607 // end of the function.
609 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
610 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
611 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
613 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
616 Builder.SetInsertPoint(ThenBB);
618 Value *ThenV = Then->codegen();
622 Builder.CreateBr(MergeBB);
623 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
624 ThenBB = Builder.GetInsertBlock();
627 TheFunction->getBasicBlockList().push_back(ElseBB);
628 Builder.SetInsertPoint(ElseBB);
630 Value *ElseV = Else->codegen();
634 Builder.CreateBr(MergeBB);
635 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
636 ElseBB = Builder.GetInsertBlock();
639 TheFunction->getBasicBlockList().push_back(MergeBB);
640 Builder.SetInsertPoint(MergeBB);
642 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
644 PN->addIncoming(ThenV, ThenBB);
645 PN->addIncoming(ElseV, ElseBB);
649 // Output for-loop as:
654 // variable = phi [start, loopheader], [nextvariable, loopend]
660 // nextvariable = variable + step
662 // br endcond, loop, endloop
664 Value *ForExprAST::codegen() {
665 // Emit the start code first, without 'variable' in scope.
666 Value *StartVal = Start->codegen();
670 // Make the new basic block for the loop header, inserting after current
672 Function *TheFunction = Builder.GetInsertBlock()->getParent();
673 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
675 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
677 // Insert an explicit fall through from the current block to the LoopBB.
678 Builder.CreateBr(LoopBB);
680 // Start insertion in LoopBB.
681 Builder.SetInsertPoint(LoopBB);
683 // Start the PHI node with an entry for Start.
684 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
686 Variable->addIncoming(StartVal, PreheaderBB);
688 // Within the loop, the variable is defined equal to the PHI node. If it
689 // shadows an existing variable, we have to restore it, so save it now.
690 Value *OldVal = NamedValues[VarName];
691 NamedValues[VarName] = Variable;
693 // Emit the body of the loop. This, like any other expr, can change the
694 // current BB. Note that we ignore the value computed by the body, but don't
696 if (!Body->codegen())
699 // Emit the step value.
700 Value *StepVal = nullptr;
702 StepVal = Step->codegen();
706 // If not specified, use 1.0.
707 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
710 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
712 // Compute the end condition.
713 Value *EndCond = End->codegen();
717 // Convert condition to a bool by comparing equal to 0.0.
718 EndCond = Builder.CreateFCmpONE(
719 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
721 // Create the "after loop" block and insert it.
722 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
723 BasicBlock *AfterBB =
724 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
726 // Insert the conditional branch into the end of LoopEndBB.
727 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
729 // Any new code will be inserted in AfterBB.
730 Builder.SetInsertPoint(AfterBB);
732 // Add a new entry to the PHI node for the backedge.
733 Variable->addIncoming(NextVar, LoopEndBB);
735 // Restore the unshadowed variable.
737 NamedValues[VarName] = OldVal;
739 NamedValues.erase(VarName);
741 // for expr always returns 0.0.
742 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
745 Function *PrototypeAST::codegen() {
746 // Make the function type: double(double,double) etc.
747 std::vector<Type *> Doubles(Args.size(),
748 Type::getDoubleTy(getGlobalContext()));
750 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
753 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
755 // Set names for all arguments.
757 for (auto &Arg : F->args())
758 Arg.setName(Args[Idx++]);
763 Function *FunctionAST::codegen() {
764 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
765 // reference to it for use below.
767 FunctionProtos[Proto->getName()] = std::move(Proto);
768 Function *TheFunction = getFunction(P.getName());
772 // Create a new basic block to start insertion into.
773 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
774 Builder.SetInsertPoint(BB);
776 // Record the function arguments in the NamedValues map.
778 for (auto &Arg : TheFunction->args())
779 NamedValues[Arg.getName()] = &Arg;
781 if (Value *RetVal = Body->codegen()) {
782 // Finish off the function.
783 Builder.CreateRet(RetVal);
785 // Validate the generated code, checking for consistency.
786 verifyFunction(*TheFunction);
788 // Run the optimizer on the function.
789 TheFPM->run(*TheFunction);
794 // Error reading body, remove function.
795 TheFunction->eraseFromParent();
799 //===----------------------------------------------------------------------===//
800 // Top-Level parsing and JIT Driver
801 //===----------------------------------------------------------------------===//
803 static void InitializeModuleAndPassManager() {
804 // Open a new module.
805 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
806 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
808 // Create a new pass manager attached to it.
809 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
811 // Provide basic AliasAnalysis support for GVN.
812 TheFPM->add(createBasicAliasAnalysisPass());
813 // Do simple "peephole" optimizations and bit-twiddling optzns.
814 TheFPM->add(createInstructionCombiningPass());
815 // Reassociate expressions.
816 TheFPM->add(createReassociatePass());
817 // Eliminate Common SubExpressions.
818 TheFPM->add(createGVNPass());
819 // Simplify the control flow graph (deleting unreachable blocks, etc).
820 TheFPM->add(createCFGSimplificationPass());
822 TheFPM->doInitialization();
825 static void HandleDefinition() {
826 if (auto FnAST = ParseDefinition()) {
827 if (auto *FnIR = FnAST->codegen()) {
828 fprintf(stderr, "Read function definition:");
830 TheJIT->addModule(std::move(TheModule));
831 InitializeModuleAndPassManager();
834 // Skip token for error recovery.
839 static void HandleExtern() {
840 if (auto ProtoAST = ParseExtern()) {
841 if (auto *FnIR = ProtoAST->codegen()) {
842 fprintf(stderr, "Read extern: ");
844 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
847 // Skip token for error recovery.
852 static void HandleTopLevelExpression() {
853 // Evaluate a top-level expression into an anonymous function.
854 if (auto FnAST = ParseTopLevelExpr()) {
855 if (FnAST->codegen()) {
857 // JIT the module containing the anonymous expression, keeping a handle so
858 // we can free it later.
859 auto H = TheJIT->addModule(std::move(TheModule));
860 InitializeModuleAndPassManager();
862 // Search the JIT for the __anon_expr symbol.
863 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
864 assert(ExprSymbol && "Function not found");
866 // Get the symbol's address and cast it to the right type (takes no
867 // arguments, returns a double) so we can call it as a native function.
868 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
869 fprintf(stderr, "Evaluated to %f\n", FP());
871 // Delete the anonymous expression module from the JIT.
872 TheJIT->removeModule(H);
875 // Skip token for error recovery.
880 /// top ::= definition | external | expression | ';'
881 static void MainLoop() {
883 fprintf(stderr, "ready> ");
887 case ';': // ignore top-level semicolons.
897 HandleTopLevelExpression();
903 //===----------------------------------------------------------------------===//
904 // "Library" functions that can be "extern'd" from user code.
905 //===----------------------------------------------------------------------===//
907 /// putchard - putchar that takes a double and returns 0.
908 extern "C" double putchard(double X) {
913 /// printd - printf that takes a double prints it as "%f\n", returning 0.
914 extern "C" double printd(double X) {
919 //===----------------------------------------------------------------------===//
921 //===----------------------------------------------------------------------===//
924 InitializeNativeTarget();
925 InitializeNativeTargetAsmPrinter();
926 InitializeNativeTargetAsmParser();
928 // Install standard binary operators.
929 // 1 is lowest precedence.
930 BinopPrecedence['<'] = 10;
931 BinopPrecedence['+'] = 20;
932 BinopPrecedence['-'] = 20;
933 BinopPrecedence['*'] = 40; // highest.
935 // Prime the first token.
936 fprintf(stderr, "ready> ");
939 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
941 InitializeModuleAndPassManager();
943 // Run the main "interpreter loop" now.