1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/Passes.h"
3 #include "llvm/IR/IRBuilder.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/LegacyPassManager.h"
6 #include "llvm/IR/Module.h"
7 #include "llvm/IR/Verifier.h"
8 #include "llvm/Support/TargetSelect.h"
9 #include "llvm/Transforms/Scalar.h"
15 #include "../include/KaleidoscopeJIT.h"
18 using namespace llvm::orc;
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
52 static std::string IdentifierStr; // Filled in if tok_identifier
53 static double NumVal; // Filled in if tok_number
55 /// gettok - Return the next token from standard input.
57 static int LastChar = ' ';
59 // Skip any whitespace.
60 while (isspace(LastChar))
63 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
64 IdentifierStr = LastChar;
65 while (isalnum((LastChar = getchar())))
66 IdentifierStr += LastChar;
68 if (IdentifierStr == "def")
70 if (IdentifierStr == "extern")
72 if (IdentifierStr == "if")
74 if (IdentifierStr == "then")
76 if (IdentifierStr == "else")
78 if (IdentifierStr == "for")
80 if (IdentifierStr == "in")
82 if (IdentifierStr == "binary")
84 if (IdentifierStr == "unary")
86 if (IdentifierStr == "var")
88 return tok_identifier;
91 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
96 } while (isdigit(LastChar) || LastChar == '.');
98 NumVal = strtod(NumStr.c_str(), 0);
102 if (LastChar == '#') {
103 // Comment until end of line.
105 LastChar = getchar();
106 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
112 // Check for end of file. Don't eat the EOF.
116 // Otherwise, just return the character as its ascii value.
117 int ThisChar = LastChar;
118 LastChar = getchar();
122 //===----------------------------------------------------------------------===//
123 // Abstract Syntax Tree (aka Parse Tree)
124 //===----------------------------------------------------------------------===//
126 /// ExprAST - Base class for all expression nodes.
129 virtual ~ExprAST() {}
130 virtual Value *codegen() = 0;
133 /// NumberExprAST - Expression class for numeric literals like "1.0".
134 class NumberExprAST : public ExprAST {
138 NumberExprAST(double Val) : Val(Val) {}
139 Value *codegen() override;
142 /// VariableExprAST - Expression class for referencing a variable, like "a".
143 class VariableExprAST : public ExprAST {
147 VariableExprAST(const std::string &Name) : Name(Name) {}
148 const std::string &getName() const { return Name; }
149 Value *codegen() override;
152 /// UnaryExprAST - Expression class for a unary operator.
153 class UnaryExprAST : public ExprAST {
155 std::unique_ptr<ExprAST> Operand;
158 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
159 : Opcode(Opcode), Operand(std::move(Operand)) {}
160 Value *codegen() override;
163 /// BinaryExprAST - Expression class for a binary operator.
164 class BinaryExprAST : public ExprAST {
166 std::unique_ptr<ExprAST> LHS, RHS;
169 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
170 std::unique_ptr<ExprAST> RHS)
171 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
172 Value *codegen() override;
175 /// CallExprAST - Expression class for function calls.
176 class CallExprAST : public ExprAST {
178 std::vector<std::unique_ptr<ExprAST>> Args;
181 CallExprAST(const std::string &Callee,
182 std::vector<std::unique_ptr<ExprAST>> Args)
183 : Callee(Callee), Args(std::move(Args)) {}
184 Value *codegen() override;
187 /// IfExprAST - Expression class for if/then/else.
188 class IfExprAST : public ExprAST {
189 std::unique_ptr<ExprAST> Cond, Then, Else;
192 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
193 std::unique_ptr<ExprAST> Else)
194 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
195 Value *codegen() override;
198 /// ForExprAST - Expression class for for/in.
199 class ForExprAST : public ExprAST {
201 std::unique_ptr<ExprAST> Start, End, Step, Body;
204 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
205 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
206 std::unique_ptr<ExprAST> Body)
207 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
208 Step(std::move(Step)), Body(std::move(Body)) {}
209 Value *codegen() override;
212 /// VarExprAST - Expression class for var/in
213 class VarExprAST : public ExprAST {
214 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
215 std::unique_ptr<ExprAST> Body;
219 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
220 std::unique_ptr<ExprAST> Body)
221 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
222 Value *codegen() override;
225 /// PrototypeAST - This class represents the "prototype" for a function,
226 /// which captures its name, and its argument names (thus implicitly the number
227 /// of arguments the function takes), as well as if it is an operator.
230 std::vector<std::string> Args;
232 unsigned Precedence; // Precedence if a binary op.
235 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
236 bool IsOperator = false, unsigned Prec = 0)
237 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
240 const std::string &getName() const { return Name; }
242 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
243 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
245 char getOperatorName() const {
246 assert(isUnaryOp() || isBinaryOp());
247 return Name[Name.size() - 1];
250 unsigned getBinaryPrecedence() const { return Precedence; }
253 /// FunctionAST - This class represents a function definition itself.
255 std::unique_ptr<PrototypeAST> Proto;
256 std::unique_ptr<ExprAST> Body;
259 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
260 std::unique_ptr<ExprAST> Body)
261 : Proto(std::move(Proto)), Body(std::move(Body)) {}
264 } // end anonymous namespace
266 //===----------------------------------------------------------------------===//
268 //===----------------------------------------------------------------------===//
270 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
271 /// token the parser is looking at. getNextToken reads another token from the
272 /// lexer and updates CurTok with its results.
274 static int getNextToken() { return CurTok = gettok(); }
276 /// BinopPrecedence - This holds the precedence for each binary operator that is
278 static std::map<char, int> BinopPrecedence;
280 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
281 static int GetTokPrecedence() {
282 if (!isascii(CurTok))
285 // Make sure it's a declared binop.
286 int TokPrec = BinopPrecedence[CurTok];
292 /// Error* - These are little helper functions for error handling.
293 std::unique_ptr<ExprAST> Error(const char *Str) {
294 fprintf(stderr, "Error: %s\n", Str);
297 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
302 static std::unique_ptr<ExprAST> ParseExpression();
304 /// numberexpr ::= number
305 static std::unique_ptr<ExprAST> ParseNumberExpr() {
306 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
307 getNextToken(); // consume the number
308 return std::move(Result);
311 /// parenexpr ::= '(' expression ')'
312 static std::unique_ptr<ExprAST> ParseParenExpr() {
313 getNextToken(); // eat (.
314 auto V = ParseExpression();
319 return Error("expected ')'");
320 getNextToken(); // eat ).
326 /// ::= identifier '(' expression* ')'
327 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
328 std::string IdName = IdentifierStr;
330 getNextToken(); // eat identifier.
332 if (CurTok != '(') // Simple variable ref.
333 return llvm::make_unique<VariableExprAST>(IdName);
336 getNextToken(); // eat (
337 std::vector<std::unique_ptr<ExprAST>> Args;
340 if (auto Arg = ParseExpression())
341 Args.push_back(std::move(Arg));
349 return Error("Expected ')' or ',' in argument list");
357 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
360 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
361 static std::unique_ptr<ExprAST> ParseIfExpr() {
362 getNextToken(); // eat the if.
365 auto Cond = ParseExpression();
369 if (CurTok != tok_then)
370 return Error("expected then");
371 getNextToken(); // eat the then
373 auto Then = ParseExpression();
377 if (CurTok != tok_else)
378 return Error("expected else");
382 auto Else = ParseExpression();
386 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
390 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
391 static std::unique_ptr<ExprAST> ParseForExpr() {
392 getNextToken(); // eat the for.
394 if (CurTok != tok_identifier)
395 return Error("expected identifier after for");
397 std::string IdName = IdentifierStr;
398 getNextToken(); // eat identifier.
401 return Error("expected '=' after for");
402 getNextToken(); // eat '='.
404 auto Start = ParseExpression();
408 return Error("expected ',' after for start value");
411 auto End = ParseExpression();
415 // The step value is optional.
416 std::unique_ptr<ExprAST> Step;
419 Step = ParseExpression();
424 if (CurTok != tok_in)
425 return Error("expected 'in' after for");
426 getNextToken(); // eat 'in'.
428 auto Body = ParseExpression();
432 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
433 std::move(Step), std::move(Body));
436 /// varexpr ::= 'var' identifier ('=' expression)?
437 // (',' identifier ('=' expression)?)* 'in' expression
438 static std::unique_ptr<ExprAST> ParseVarExpr() {
439 getNextToken(); // eat the var.
441 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
443 // At least one variable name is required.
444 if (CurTok != tok_identifier)
445 return Error("expected identifier after var");
448 std::string Name = IdentifierStr;
449 getNextToken(); // eat identifier.
451 // Read the optional initializer.
452 std::unique_ptr<ExprAST> Init = nullptr;
454 getNextToken(); // eat the '='.
456 Init = ParseExpression();
461 VarNames.push_back(std::make_pair(Name, std::move(Init)));
463 // End of var list, exit loop.
466 getNextToken(); // eat the ','.
468 if (CurTok != tok_identifier)
469 return Error("expected identifier list after var");
472 // At this point, we have to have 'in'.
473 if (CurTok != tok_in)
474 return Error("expected 'in' keyword after 'var'");
475 getNextToken(); // eat 'in'.
477 auto Body = ParseExpression();
481 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
485 /// ::= identifierexpr
491 static std::unique_ptr<ExprAST> ParsePrimary() {
494 return Error("unknown token when expecting an expression");
496 return ParseIdentifierExpr();
498 return ParseNumberExpr();
500 return ParseParenExpr();
502 return ParseIfExpr();
504 return ParseForExpr();
506 return ParseVarExpr();
513 static std::unique_ptr<ExprAST> ParseUnary() {
514 // If the current token is not an operator, it must be a primary expr.
515 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
516 return ParsePrimary();
518 // If this is a unary operator, read it.
521 if (auto Operand = ParseUnary())
522 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
528 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
529 std::unique_ptr<ExprAST> LHS) {
530 // If this is a binop, find its precedence.
532 int TokPrec = GetTokPrecedence();
534 // If this is a binop that binds at least as tightly as the current binop,
535 // consume it, otherwise we are done.
536 if (TokPrec < ExprPrec)
539 // Okay, we know this is a binop.
541 getNextToken(); // eat binop
543 // Parse the unary expression after the binary operator.
544 auto RHS = ParseUnary();
548 // If BinOp binds less tightly with RHS than the operator after RHS, let
549 // the pending operator take RHS as its LHS.
550 int NextPrec = GetTokPrecedence();
551 if (TokPrec < NextPrec) {
552 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
559 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
564 /// ::= unary binoprhs
566 static std::unique_ptr<ExprAST> ParseExpression() {
567 auto LHS = ParseUnary();
571 return ParseBinOpRHS(0, std::move(LHS));
575 /// ::= id '(' id* ')'
576 /// ::= binary LETTER number? (id, id)
577 /// ::= unary LETTER (id)
578 static std::unique_ptr<PrototypeAST> ParsePrototype() {
581 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
582 unsigned BinaryPrecedence = 30;
586 return ErrorP("Expected function name in prototype");
588 FnName = IdentifierStr;
594 if (!isascii(CurTok))
595 return ErrorP("Expected unary operator");
597 FnName += (char)CurTok;
603 if (!isascii(CurTok))
604 return ErrorP("Expected binary operator");
606 FnName += (char)CurTok;
610 // Read the precedence if present.
611 if (CurTok == tok_number) {
612 if (NumVal < 1 || NumVal > 100)
613 return ErrorP("Invalid precedecnce: must be 1..100");
614 BinaryPrecedence = (unsigned)NumVal;
621 return ErrorP("Expected '(' in prototype");
623 std::vector<std::string> ArgNames;
624 while (getNextToken() == tok_identifier)
625 ArgNames.push_back(IdentifierStr);
627 return ErrorP("Expected ')' in prototype");
630 getNextToken(); // eat ')'.
632 // Verify right number of names for operator.
633 if (Kind && ArgNames.size() != Kind)
634 return ErrorP("Invalid number of operands for operator");
636 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
640 /// definition ::= 'def' prototype expression
641 static std::unique_ptr<FunctionAST> ParseDefinition() {
642 getNextToken(); // eat def.
643 auto Proto = ParsePrototype();
647 if (auto E = ParseExpression())
648 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
652 /// toplevelexpr ::= expression
653 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
654 if (auto E = ParseExpression()) {
655 // Make an anonymous proto.
656 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
657 std::vector<std::string>());
658 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
663 /// external ::= 'extern' prototype
664 static std::unique_ptr<PrototypeAST> ParseExtern() {
665 getNextToken(); // eat extern.
666 return ParsePrototype();
669 //===----------------------------------------------------------------------===//
671 //===----------------------------------------------------------------------===//
673 static std::unique_ptr<Module> TheModule;
674 static IRBuilder<> Builder(getGlobalContext());
675 static std::map<std::string, AllocaInst *> NamedValues;
676 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
677 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
678 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
680 Value *ErrorV(const char *Str) {
685 Function *getFunction(std::string Name) {
686 // First, see if the function has already been added to the current module.
687 if (auto *F = TheModule->getFunction(Name))
690 // If not, check whether we can codegen the declaration from some existing
692 auto FI = FunctionProtos.find(Name);
693 if (FI != FunctionProtos.end())
694 return FI->second->codegen();
696 // If no existing prototype exists, return null.
700 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
701 /// the function. This is used for mutable variables etc.
702 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
703 const std::string &VarName) {
704 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
705 TheFunction->getEntryBlock().begin());
706 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
710 Value *NumberExprAST::codegen() {
711 return ConstantFP::get(getGlobalContext(), APFloat(Val));
714 Value *VariableExprAST::codegen() {
715 // Look this variable up in the function.
716 Value *V = NamedValues[Name];
718 return ErrorV("Unknown variable name");
721 return Builder.CreateLoad(V, Name.c_str());
724 Value *UnaryExprAST::codegen() {
725 Value *OperandV = Operand->codegen();
729 Function *F = getFunction(std::string("unary") + Opcode);
731 return ErrorV("Unknown unary operator");
733 return Builder.CreateCall(F, OperandV, "unop");
736 Value *BinaryExprAST::codegen() {
737 // Special case '=' because we don't want to emit the LHS as an expression.
739 // Assignment requires the LHS to be an identifier.
740 // This assume we're building without RTTI because LLVM builds that way by
741 // default. If you build LLVM with RTTI this can be changed to a
742 // dynamic_cast for automatic error checking.
743 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
745 return ErrorV("destination of '=' must be a variable");
747 Value *Val = RHS->codegen();
752 Value *Variable = NamedValues[LHSE->getName()];
754 return ErrorV("Unknown variable name");
756 Builder.CreateStore(Val, Variable);
760 Value *L = LHS->codegen();
761 Value *R = RHS->codegen();
767 return Builder.CreateFAdd(L, R, "addtmp");
769 return Builder.CreateFSub(L, R, "subtmp");
771 return Builder.CreateFMul(L, R, "multmp");
773 L = Builder.CreateFCmpULT(L, R, "cmptmp");
774 // Convert bool 0/1 to double 0.0 or 1.0
775 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
781 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
783 Function *F = getFunction(std::string("binary") + Op);
784 assert(F && "binary operator not found!");
786 Value *Ops[] = {L, R};
787 return Builder.CreateCall(F, Ops, "binop");
790 Value *CallExprAST::codegen() {
791 // Look up the name in the global module table.
792 Function *CalleeF = getFunction(Callee);
794 return ErrorV("Unknown function referenced");
796 // If argument mismatch error.
797 if (CalleeF->arg_size() != Args.size())
798 return ErrorV("Incorrect # arguments passed");
800 std::vector<Value *> ArgsV;
801 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
802 ArgsV.push_back(Args[i]->codegen());
807 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
810 Value *IfExprAST::codegen() {
811 Value *CondV = Cond->codegen();
815 // Convert condition to a bool by comparing equal to 0.0.
816 CondV = Builder.CreateFCmpONE(
817 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
819 Function *TheFunction = Builder.GetInsertBlock()->getParent();
821 // Create blocks for the then and else cases. Insert the 'then' block at the
822 // end of the function.
824 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
825 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
826 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
828 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
831 Builder.SetInsertPoint(ThenBB);
833 Value *ThenV = Then->codegen();
837 Builder.CreateBr(MergeBB);
838 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
839 ThenBB = Builder.GetInsertBlock();
842 TheFunction->getBasicBlockList().push_back(ElseBB);
843 Builder.SetInsertPoint(ElseBB);
845 Value *ElseV = Else->codegen();
849 Builder.CreateBr(MergeBB);
850 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
851 ElseBB = Builder.GetInsertBlock();
854 TheFunction->getBasicBlockList().push_back(MergeBB);
855 Builder.SetInsertPoint(MergeBB);
857 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
859 PN->addIncoming(ThenV, ThenBB);
860 PN->addIncoming(ElseV, ElseBB);
864 // Output for-loop as:
865 // var = alloca double
868 // store start -> var
879 // nextvar = curvar + step
880 // store nextvar -> var
881 // br endcond, loop, endloop
883 Value *ForExprAST::codegen() {
884 Function *TheFunction = Builder.GetInsertBlock()->getParent();
886 // Create an alloca for the variable in the entry block.
887 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
889 // Emit the start code first, without 'variable' in scope.
890 Value *StartVal = Start->codegen();
894 // Store the value into the alloca.
895 Builder.CreateStore(StartVal, Alloca);
897 // Make the new basic block for the loop header, inserting after current
900 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
902 // Insert an explicit fall through from the current block to the LoopBB.
903 Builder.CreateBr(LoopBB);
905 // Start insertion in LoopBB.
906 Builder.SetInsertPoint(LoopBB);
908 // Within the loop, the variable is defined equal to the PHI node. If it
909 // shadows an existing variable, we have to restore it, so save it now.
910 AllocaInst *OldVal = NamedValues[VarName];
911 NamedValues[VarName] = Alloca;
913 // Emit the body of the loop. This, like any other expr, can change the
914 // current BB. Note that we ignore the value computed by the body, but don't
916 if (!Body->codegen())
919 // Emit the step value.
920 Value *StepVal = nullptr;
922 StepVal = Step->codegen();
926 // If not specified, use 1.0.
927 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
930 // Compute the end condition.
931 Value *EndCond = End->codegen();
935 // Reload, increment, and restore the alloca. This handles the case where
936 // the body of the loop mutates the variable.
937 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
938 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
939 Builder.CreateStore(NextVar, Alloca);
941 // Convert condition to a bool by comparing equal to 0.0.
942 EndCond = Builder.CreateFCmpONE(
943 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
945 // Create the "after loop" block and insert it.
946 BasicBlock *AfterBB =
947 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
949 // Insert the conditional branch into the end of LoopEndBB.
950 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
952 // Any new code will be inserted in AfterBB.
953 Builder.SetInsertPoint(AfterBB);
955 // Restore the unshadowed variable.
957 NamedValues[VarName] = OldVal;
959 NamedValues.erase(VarName);
961 // for expr always returns 0.0.
962 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
965 Value *VarExprAST::codegen() {
966 std::vector<AllocaInst *> OldBindings;
968 Function *TheFunction = Builder.GetInsertBlock()->getParent();
970 // Register all variables and emit their initializer.
971 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
972 const std::string &VarName = VarNames[i].first;
973 ExprAST *Init = VarNames[i].second.get();
975 // Emit the initializer before adding the variable to scope, this prevents
976 // the initializer from referencing the variable itself, and permits stuff
979 // var a = a in ... # refers to outer 'a'.
982 InitVal = Init->codegen();
985 } else { // If not specified, use 0.0.
986 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
989 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
990 Builder.CreateStore(InitVal, Alloca);
992 // Remember the old variable binding so that we can restore the binding when
994 OldBindings.push_back(NamedValues[VarName]);
996 // Remember this binding.
997 NamedValues[VarName] = Alloca;
1000 // Codegen the body, now that all vars are in scope.
1001 Value *BodyVal = Body->codegen();
1005 // Pop all our variables from scope.
1006 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1007 NamedValues[VarNames[i].first] = OldBindings[i];
1009 // Return the body computation.
1013 Function *PrototypeAST::codegen() {
1014 // Make the function type: double(double,double) etc.
1015 std::vector<Type *> Doubles(Args.size(),
1016 Type::getDoubleTy(getGlobalContext()));
1018 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1021 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
1023 // Set names for all arguments.
1025 for (auto &Arg : F->args())
1026 Arg.setName(Args[Idx++]);
1031 Function *FunctionAST::codegen() {
1032 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1033 // reference to it for use below.
1035 FunctionProtos[Proto->getName()] = std::move(Proto);
1036 Function *TheFunction = getFunction(P.getName());
1040 // If this is an operator, install it.
1042 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1044 // Create a new basic block to start insertion into.
1045 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1046 Builder.SetInsertPoint(BB);
1048 // Record the function arguments in the NamedValues map.
1049 NamedValues.clear();
1050 for (auto &Arg : TheFunction->args()) {
1051 // Create an alloca for this variable.
1052 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
1054 // Store the initial value into the alloca.
1055 Builder.CreateStore(&Arg, Alloca);
1057 // Add arguments to variable symbol table.
1058 NamedValues[Arg.getName()] = Alloca;
1061 if (Value *RetVal = Body->codegen()) {
1062 // Finish off the function.
1063 Builder.CreateRet(RetVal);
1065 // Validate the generated code, checking for consistency.
1066 verifyFunction(*TheFunction);
1068 // Run the optimizer on the function.
1069 TheFPM->run(*TheFunction);
1074 // Error reading body, remove function.
1075 TheFunction->eraseFromParent();
1078 BinopPrecedence.erase(Proto->getOperatorName());
1082 //===----------------------------------------------------------------------===//
1083 // Top-Level parsing and JIT Driver
1084 //===----------------------------------------------------------------------===//
1086 static void InitializeModuleAndPassManager() {
1087 // Open a new module.
1088 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1089 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1091 // Create a new pass manager attached to it.
1092 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1094 // Do simple "peephole" optimizations and bit-twiddling optzns.
1095 TheFPM->add(createInstructionCombiningPass());
1096 // Reassociate expressions.
1097 TheFPM->add(createReassociatePass());
1098 // Eliminate Common SubExpressions.
1099 TheFPM->add(createGVNPass());
1100 // Simplify the control flow graph (deleting unreachable blocks, etc).
1101 TheFPM->add(createCFGSimplificationPass());
1103 TheFPM->doInitialization();
1106 static void HandleDefinition() {
1107 if (auto FnAST = ParseDefinition()) {
1108 if (auto *FnIR = FnAST->codegen()) {
1109 fprintf(stderr, "Read function definition:");
1111 TheJIT->addModule(std::move(TheModule));
1112 InitializeModuleAndPassManager();
1115 // Skip token for error recovery.
1120 static void HandleExtern() {
1121 if (auto ProtoAST = ParseExtern()) {
1122 if (auto *FnIR = ProtoAST->codegen()) {
1123 fprintf(stderr, "Read extern: ");
1125 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
1128 // Skip token for error recovery.
1133 static void HandleTopLevelExpression() {
1134 // Evaluate a top-level expression into an anonymous function.
1135 if (auto FnAST = ParseTopLevelExpr()) {
1136 if (FnAST->codegen()) {
1138 // JIT the module containing the anonymous expression, keeping a handle so
1139 // we can free it later.
1140 auto H = TheJIT->addModule(std::move(TheModule));
1141 InitializeModuleAndPassManager();
1143 // Search the JIT for the __anon_expr symbol.
1144 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1145 assert(ExprSymbol && "Function not found");
1147 // Get the symbol's address and cast it to the right type (takes no
1148 // arguments, returns a double) so we can call it as a native function.
1149 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1150 fprintf(stderr, "Evaluated to %f\n", FP());
1152 // Delete the anonymous expression module from the JIT.
1153 TheJIT->removeModule(H);
1156 // Skip token for error recovery.
1161 /// top ::= definition | external | expression | ';'
1162 static void MainLoop() {
1164 fprintf(stderr, "ready> ");
1168 case ';': // ignore top-level semicolons.
1178 HandleTopLevelExpression();
1184 //===----------------------------------------------------------------------===//
1185 // "Library" functions that can be "extern'd" from user code.
1186 //===----------------------------------------------------------------------===//
1188 /// putchard - putchar that takes a double and returns 0.
1189 extern "C" double putchard(double X) {
1190 fputc((char)X, stderr);
1194 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1195 extern "C" double printd(double X) {
1196 fprintf(stderr, "%f\n", X);
1200 //===----------------------------------------------------------------------===//
1201 // Main driver code.
1202 //===----------------------------------------------------------------------===//
1205 InitializeNativeTarget();
1206 InitializeNativeTargetAsmPrinter();
1207 InitializeNativeTargetAsmParser();
1209 // Install standard binary operators.
1210 // 1 is lowest precedence.
1211 BinopPrecedence['='] = 2;
1212 BinopPrecedence['<'] = 10;
1213 BinopPrecedence['+'] = 20;
1214 BinopPrecedence['-'] = 20;
1215 BinopPrecedence['*'] = 40; // highest.
1217 // Prime the first token.
1218 fprintf(stderr, "ready> ");
1221 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1223 InitializeModuleAndPassManager();
1225 // Run the main "interpreter loop" now.