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.
53 static std::string IdentifierStr; // Filled in if tok_identifier
54 static double NumVal; // Filled in if tok_number
56 /// gettok - Return the next token from standard input.
58 static int LastChar = ' ';
60 // Skip any whitespace.
61 while (isspace(LastChar))
64 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
65 IdentifierStr = LastChar;
66 while (isalnum((LastChar = getchar())))
67 IdentifierStr += LastChar;
69 if (IdentifierStr == "def")
71 if (IdentifierStr == "extern")
73 if (IdentifierStr == "if")
75 if (IdentifierStr == "then")
77 if (IdentifierStr == "else")
79 if (IdentifierStr == "for")
81 if (IdentifierStr == "in")
83 if (IdentifierStr == "binary")
85 if (IdentifierStr == "unary")
87 if (IdentifierStr == "var")
89 return tok_identifier;
92 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
97 } while (isdigit(LastChar) || LastChar == '.');
99 NumVal = strtod(NumStr.c_str(), 0);
103 if (LastChar == '#') {
104 // Comment until end of line.
106 LastChar = getchar();
107 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
113 // Check for end of file. Don't eat the EOF.
117 // Otherwise, just return the character as its ascii value.
118 int ThisChar = LastChar;
119 LastChar = getchar();
123 //===----------------------------------------------------------------------===//
124 // Abstract Syntax Tree (aka Parse Tree)
125 //===----------------------------------------------------------------------===//
127 /// ExprAST - Base class for all expression nodes.
130 virtual ~ExprAST() {}
131 virtual Value *codegen() = 0;
134 /// NumberExprAST - Expression class for numeric literals like "1.0".
135 class NumberExprAST : public ExprAST {
139 NumberExprAST(double Val) : Val(Val) {}
140 Value *codegen() override;
143 /// VariableExprAST - Expression class for referencing a variable, like "a".
144 class VariableExprAST : public ExprAST {
148 VariableExprAST(const std::string &Name) : Name(Name) {}
149 const std::string &getName() const { return Name; }
150 Value *codegen() override;
153 /// UnaryExprAST - Expression class for a unary operator.
154 class UnaryExprAST : public ExprAST {
156 std::unique_ptr<ExprAST> Operand;
159 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
160 : Opcode(Opcode), Operand(std::move(Operand)) {}
161 Value *codegen() override;
164 /// BinaryExprAST - Expression class for a binary operator.
165 class BinaryExprAST : public ExprAST {
167 std::unique_ptr<ExprAST> LHS, RHS;
170 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
171 std::unique_ptr<ExprAST> RHS)
172 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
173 Value *codegen() override;
176 /// CallExprAST - Expression class for function calls.
177 class CallExprAST : public ExprAST {
179 std::vector<std::unique_ptr<ExprAST>> Args;
182 CallExprAST(const std::string &Callee,
183 std::vector<std::unique_ptr<ExprAST>> Args)
184 : Callee(Callee), Args(std::move(Args)) {}
185 Value *codegen() override;
188 /// IfExprAST - Expression class for if/then/else.
189 class IfExprAST : public ExprAST {
190 std::unique_ptr<ExprAST> Cond, Then, Else;
193 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
194 std::unique_ptr<ExprAST> Else)
195 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
196 Value *codegen() override;
199 /// ForExprAST - Expression class for for/in.
200 class ForExprAST : public ExprAST {
202 std::unique_ptr<ExprAST> Start, End, Step, Body;
205 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
206 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
207 std::unique_ptr<ExprAST> Body)
208 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
209 Step(std::move(Step)), Body(std::move(Body)) {}
210 Value *codegen() override;
213 /// VarExprAST - Expression class for var/in
214 class VarExprAST : public ExprAST {
215 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
216 std::unique_ptr<ExprAST> Body;
220 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
221 std::unique_ptr<ExprAST> Body)
222 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
223 Value *codegen() override;
226 /// PrototypeAST - This class represents the "prototype" for a function,
227 /// which captures its name, and its argument names (thus implicitly the number
228 /// of arguments the function takes), as well as if it is an operator.
231 std::vector<std::string> Args;
233 unsigned Precedence; // Precedence if a binary op.
236 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
237 bool IsOperator = false, unsigned Prec = 0)
238 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
241 const std::string &getName() const { return Name; }
243 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
244 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
246 char getOperatorName() const {
247 assert(isUnaryOp() || isBinaryOp());
248 return Name[Name.size() - 1];
251 unsigned getBinaryPrecedence() const { return Precedence; }
254 /// FunctionAST - This class represents a function definition itself.
256 std::unique_ptr<PrototypeAST> Proto;
257 std::unique_ptr<ExprAST> Body;
260 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
261 std::unique_ptr<ExprAST> Body)
262 : Proto(std::move(Proto)), Body(std::move(Body)) {}
265 } // end anonymous namespace
267 //===----------------------------------------------------------------------===//
269 //===----------------------------------------------------------------------===//
271 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
272 /// token the parser is looking at. getNextToken reads another token from the
273 /// lexer and updates CurTok with its results.
275 static int getNextToken() { return CurTok = gettok(); }
277 /// BinopPrecedence - This holds the precedence for each binary operator that is
279 static std::map<char, int> BinopPrecedence;
281 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
282 static int GetTokPrecedence() {
283 if (!isascii(CurTok))
286 // Make sure it's a declared binop.
287 int TokPrec = BinopPrecedence[CurTok];
293 /// Error* - These are little helper functions for error handling.
294 std::unique_ptr<ExprAST> Error(const char *Str) {
295 fprintf(stderr, "Error: %s\n", Str);
298 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
303 static std::unique_ptr<ExprAST> ParseExpression();
305 /// numberexpr ::= number
306 static std::unique_ptr<ExprAST> ParseNumberExpr() {
307 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
308 getNextToken(); // consume the number
309 return std::move(Result);
312 /// parenexpr ::= '(' expression ')'
313 static std::unique_ptr<ExprAST> ParseParenExpr() {
314 getNextToken(); // eat (.
315 auto V = ParseExpression();
320 return Error("expected ')'");
321 getNextToken(); // eat ).
327 /// ::= identifier '(' expression* ')'
328 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
329 std::string IdName = IdentifierStr;
331 getNextToken(); // eat identifier.
333 if (CurTok != '(') // Simple variable ref.
334 return llvm::make_unique<VariableExprAST>(IdName);
337 getNextToken(); // eat (
338 std::vector<std::unique_ptr<ExprAST>> Args;
341 if (auto Arg = ParseExpression())
342 Args.push_back(std::move(Arg));
350 return Error("Expected ')' or ',' in argument list");
358 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
361 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
362 static std::unique_ptr<ExprAST> ParseIfExpr() {
363 getNextToken(); // eat the if.
366 auto Cond = ParseExpression();
370 if (CurTok != tok_then)
371 return Error("expected then");
372 getNextToken(); // eat the then
374 auto Then = ParseExpression();
378 if (CurTok != tok_else)
379 return Error("expected else");
383 auto Else = ParseExpression();
387 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
391 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
392 static std::unique_ptr<ExprAST> ParseForExpr() {
393 getNextToken(); // eat the for.
395 if (CurTok != tok_identifier)
396 return Error("expected identifier after for");
398 std::string IdName = IdentifierStr;
399 getNextToken(); // eat identifier.
402 return Error("expected '=' after for");
403 getNextToken(); // eat '='.
405 auto Start = ParseExpression();
409 return Error("expected ',' after for start value");
412 auto End = ParseExpression();
416 // The step value is optional.
417 std::unique_ptr<ExprAST> Step;
420 Step = ParseExpression();
425 if (CurTok != tok_in)
426 return Error("expected 'in' after for");
427 getNextToken(); // eat 'in'.
429 auto Body = ParseExpression();
433 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
434 std::move(Step), std::move(Body));
437 /// varexpr ::= 'var' identifier ('=' expression)?
438 // (',' identifier ('=' expression)?)* 'in' expression
439 static std::unique_ptr<ExprAST> ParseVarExpr() {
440 getNextToken(); // eat the var.
442 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
444 // At least one variable name is required.
445 if (CurTok != tok_identifier)
446 return Error("expected identifier after var");
449 std::string Name = IdentifierStr;
450 getNextToken(); // eat identifier.
452 // Read the optional initializer.
453 std::unique_ptr<ExprAST> Init = nullptr;
455 getNextToken(); // eat the '='.
457 Init = ParseExpression();
462 VarNames.push_back(std::make_pair(Name, std::move(Init)));
464 // End of var list, exit loop.
467 getNextToken(); // eat the ','.
469 if (CurTok != tok_identifier)
470 return Error("expected identifier list after var");
473 // At this point, we have to have 'in'.
474 if (CurTok != tok_in)
475 return Error("expected 'in' keyword after 'var'");
476 getNextToken(); // eat 'in'.
478 auto Body = ParseExpression();
482 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
486 /// ::= identifierexpr
492 static std::unique_ptr<ExprAST> ParsePrimary() {
495 return Error("unknown token when expecting an expression");
497 return ParseIdentifierExpr();
499 return ParseNumberExpr();
501 return ParseParenExpr();
503 return ParseIfExpr();
505 return ParseForExpr();
507 return ParseVarExpr();
514 static std::unique_ptr<ExprAST> ParseUnary() {
515 // If the current token is not an operator, it must be a primary expr.
516 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
517 return ParsePrimary();
519 // If this is a unary operator, read it.
522 if (auto Operand = ParseUnary())
523 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
529 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
530 std::unique_ptr<ExprAST> LHS) {
531 // If this is a binop, find its precedence.
533 int TokPrec = GetTokPrecedence();
535 // If this is a binop that binds at least as tightly as the current binop,
536 // consume it, otherwise we are done.
537 if (TokPrec < ExprPrec)
540 // Okay, we know this is a binop.
542 getNextToken(); // eat binop
544 // Parse the unary expression after the binary operator.
545 auto RHS = ParseUnary();
549 // If BinOp binds less tightly with RHS than the operator after RHS, let
550 // the pending operator take RHS as its LHS.
551 int NextPrec = GetTokPrecedence();
552 if (TokPrec < NextPrec) {
553 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
560 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
565 /// ::= unary binoprhs
567 static std::unique_ptr<ExprAST> ParseExpression() {
568 auto LHS = ParseUnary();
572 return ParseBinOpRHS(0, std::move(LHS));
576 /// ::= id '(' id* ')'
577 /// ::= binary LETTER number? (id, id)
578 /// ::= unary LETTER (id)
579 static std::unique_ptr<PrototypeAST> ParsePrototype() {
582 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
583 unsigned BinaryPrecedence = 30;
587 return ErrorP("Expected function name in prototype");
589 FnName = IdentifierStr;
595 if (!isascii(CurTok))
596 return ErrorP("Expected unary operator");
598 FnName += (char)CurTok;
604 if (!isascii(CurTok))
605 return ErrorP("Expected binary operator");
607 FnName += (char)CurTok;
611 // Read the precedence if present.
612 if (CurTok == tok_number) {
613 if (NumVal < 1 || NumVal > 100)
614 return ErrorP("Invalid precedecnce: must be 1..100");
615 BinaryPrecedence = (unsigned)NumVal;
622 return ErrorP("Expected '(' in prototype");
624 std::vector<std::string> ArgNames;
625 while (getNextToken() == tok_identifier)
626 ArgNames.push_back(IdentifierStr);
628 return ErrorP("Expected ')' in prototype");
631 getNextToken(); // eat ')'.
633 // Verify right number of names for operator.
634 if (Kind && ArgNames.size() != Kind)
635 return ErrorP("Invalid number of operands for operator");
637 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
641 /// definition ::= 'def' prototype expression
642 static std::unique_ptr<FunctionAST> ParseDefinition() {
643 getNextToken(); // eat def.
644 auto Proto = ParsePrototype();
648 if (auto E = ParseExpression())
649 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
653 /// toplevelexpr ::= expression
654 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
655 if (auto E = ParseExpression()) {
656 // Make an anonymous proto.
657 auto Proto = llvm::make_unique<PrototypeAST>("__anon_expr",
658 std::vector<std::string>());
659 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
664 /// external ::= 'extern' prototype
665 static std::unique_ptr<PrototypeAST> ParseExtern() {
666 getNextToken(); // eat extern.
667 return ParsePrototype();
670 //===----------------------------------------------------------------------===//
672 //===----------------------------------------------------------------------===//
674 static std::unique_ptr<Module> TheModule;
675 static IRBuilder<> Builder(getGlobalContext());
676 static std::map<std::string, AllocaInst *> NamedValues;
677 static std::unique_ptr<legacy::FunctionPassManager> TheFPM;
678 static std::unique_ptr<KaleidoscopeJIT> TheJIT;
679 static std::map<std::string, std::unique_ptr<PrototypeAST>> FunctionProtos;
681 Value *ErrorV(const char *Str) {
686 Function *getFunction(std::string Name) {
687 // First, see if the function has already been added to the current module.
688 if (auto *F = TheModule->getFunction(Name))
691 // If not, check whether we can codegen the declaration from some existing
693 auto FI = FunctionProtos.find(Name);
694 if (FI != FunctionProtos.end())
695 return FI->second->codegen();
697 // If no existing prototype exists, return null.
701 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
702 /// the function. This is used for mutable variables etc.
703 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
704 const std::string &VarName) {
705 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
706 TheFunction->getEntryBlock().begin());
707 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
711 Value *NumberExprAST::codegen() {
712 return ConstantFP::get(getGlobalContext(), APFloat(Val));
715 Value *VariableExprAST::codegen() {
716 // Look this variable up in the function.
717 Value *V = NamedValues[Name];
719 return ErrorV("Unknown variable name");
722 return Builder.CreateLoad(V, Name.c_str());
725 Value *UnaryExprAST::codegen() {
726 Value *OperandV = Operand->codegen();
730 Function *F = getFunction(std::string("unary") + Opcode);
732 return ErrorV("Unknown unary operator");
734 return Builder.CreateCall(F, OperandV, "unop");
737 Value *BinaryExprAST::codegen() {
738 // Special case '=' because we don't want to emit the LHS as an expression.
740 // Assignment requires the LHS to be an identifier.
741 // This assume we're building without RTTI because LLVM builds that way by
742 // default. If you build LLVM with RTTI this can be changed to a
743 // dynamic_cast for automatic error checking.
744 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
746 return ErrorV("destination of '=' must be a variable");
748 Value *Val = RHS->codegen();
753 Value *Variable = NamedValues[LHSE->getName()];
755 return ErrorV("Unknown variable name");
757 Builder.CreateStore(Val, Variable);
761 Value *L = LHS->codegen();
762 Value *R = RHS->codegen();
768 return Builder.CreateFAdd(L, R, "addtmp");
770 return Builder.CreateFSub(L, R, "subtmp");
772 return Builder.CreateFMul(L, R, "multmp");
774 L = Builder.CreateFCmpULT(L, R, "cmptmp");
775 // Convert bool 0/1 to double 0.0 or 1.0
776 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
782 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
784 Function *F = getFunction(std::string("binary") + Op);
785 assert(F && "binary operator not found!");
787 Value *Ops[] = {L, R};
788 return Builder.CreateCall(F, Ops, "binop");
791 Value *CallExprAST::codegen() {
792 // Look up the name in the global module table.
793 Function *CalleeF = getFunction(Callee);
795 return ErrorV("Unknown function referenced");
797 // If argument mismatch error.
798 if (CalleeF->arg_size() != Args.size())
799 return ErrorV("Incorrect # arguments passed");
801 std::vector<Value *> ArgsV;
802 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
803 ArgsV.push_back(Args[i]->codegen());
808 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
811 Value *IfExprAST::codegen() {
812 Value *CondV = Cond->codegen();
816 // Convert condition to a bool by comparing equal to 0.0.
817 CondV = Builder.CreateFCmpONE(
818 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
820 Function *TheFunction = Builder.GetInsertBlock()->getParent();
822 // Create blocks for the then and else cases. Insert the 'then' block at the
823 // end of the function.
825 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
826 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
827 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
829 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
832 Builder.SetInsertPoint(ThenBB);
834 Value *ThenV = Then->codegen();
838 Builder.CreateBr(MergeBB);
839 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
840 ThenBB = Builder.GetInsertBlock();
843 TheFunction->getBasicBlockList().push_back(ElseBB);
844 Builder.SetInsertPoint(ElseBB);
846 Value *ElseV = Else->codegen();
850 Builder.CreateBr(MergeBB);
851 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
852 ElseBB = Builder.GetInsertBlock();
855 TheFunction->getBasicBlockList().push_back(MergeBB);
856 Builder.SetInsertPoint(MergeBB);
858 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
860 PN->addIncoming(ThenV, ThenBB);
861 PN->addIncoming(ElseV, ElseBB);
865 // Output for-loop as:
866 // var = alloca double
869 // store start -> var
880 // nextvar = curvar + step
881 // store nextvar -> var
882 // br endcond, loop, endloop
884 Value *ForExprAST::codegen() {
885 Function *TheFunction = Builder.GetInsertBlock()->getParent();
887 // Create an alloca for the variable in the entry block.
888 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
890 // Emit the start code first, without 'variable' in scope.
891 Value *StartVal = Start->codegen();
895 // Store the value into the alloca.
896 Builder.CreateStore(StartVal, Alloca);
898 // Make the new basic block for the loop header, inserting after current
901 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
903 // Insert an explicit fall through from the current block to the LoopBB.
904 Builder.CreateBr(LoopBB);
906 // Start insertion in LoopBB.
907 Builder.SetInsertPoint(LoopBB);
909 // Within the loop, the variable is defined equal to the PHI node. If it
910 // shadows an existing variable, we have to restore it, so save it now.
911 AllocaInst *OldVal = NamedValues[VarName];
912 NamedValues[VarName] = Alloca;
914 // Emit the body of the loop. This, like any other expr, can change the
915 // current BB. Note that we ignore the value computed by the body, but don't
917 if (!Body->codegen())
920 // Emit the step value.
921 Value *StepVal = nullptr;
923 StepVal = Step->codegen();
927 // If not specified, use 1.0.
928 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
931 // Compute the end condition.
932 Value *EndCond = End->codegen();
936 // Reload, increment, and restore the alloca. This handles the case where
937 // the body of the loop mutates the variable.
938 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
939 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
940 Builder.CreateStore(NextVar, Alloca);
942 // Convert condition to a bool by comparing equal to 0.0.
943 EndCond = Builder.CreateFCmpONE(
944 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
946 // Create the "after loop" block and insert it.
947 BasicBlock *AfterBB =
948 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
950 // Insert the conditional branch into the end of LoopEndBB.
951 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
953 // Any new code will be inserted in AfterBB.
954 Builder.SetInsertPoint(AfterBB);
956 // Restore the unshadowed variable.
958 NamedValues[VarName] = OldVal;
960 NamedValues.erase(VarName);
962 // for expr always returns 0.0.
963 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
966 Value *VarExprAST::codegen() {
967 std::vector<AllocaInst *> OldBindings;
969 Function *TheFunction = Builder.GetInsertBlock()->getParent();
971 // Register all variables and emit their initializer.
972 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
973 const std::string &VarName = VarNames[i].first;
974 ExprAST *Init = VarNames[i].second.get();
976 // Emit the initializer before adding the variable to scope, this prevents
977 // the initializer from referencing the variable itself, and permits stuff
980 // var a = a in ... # refers to outer 'a'.
983 InitVal = Init->codegen();
986 } else { // If not specified, use 0.0.
987 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
990 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
991 Builder.CreateStore(InitVal, Alloca);
993 // Remember the old variable binding so that we can restore the binding when
995 OldBindings.push_back(NamedValues[VarName]);
997 // Remember this binding.
998 NamedValues[VarName] = Alloca;
1001 // Codegen the body, now that all vars are in scope.
1002 Value *BodyVal = Body->codegen();
1006 // Pop all our variables from scope.
1007 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
1008 NamedValues[VarNames[i].first] = OldBindings[i];
1010 // Return the body computation.
1014 Function *PrototypeAST::codegen() {
1015 // Make the function type: double(double,double) etc.
1016 std::vector<Type *> Doubles(Args.size(),
1017 Type::getDoubleTy(getGlobalContext()));
1019 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1022 Function::Create(FT, Function::ExternalLinkage, Name, TheModule.get());
1024 // Set names for all arguments.
1026 for (auto &Arg : F->args())
1027 Arg.setName(Args[Idx++]);
1032 Function *FunctionAST::codegen() {
1033 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1034 // reference to it for use below.
1036 FunctionProtos[Proto->getName()] = std::move(Proto);
1037 Function *TheFunction = getFunction(P.getName());
1041 // If this is an operator, install it.
1043 BinopPrecedence[P.getOperatorName()] = P.getBinaryPrecedence();
1045 // Create a new basic block to start insertion into.
1046 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1047 Builder.SetInsertPoint(BB);
1049 // Record the function arguments in the NamedValues map.
1050 NamedValues.clear();
1051 for (auto &Arg : TheFunction->args()) {
1052 // Create an alloca for this variable.
1053 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, Arg.getName());
1055 // Store the initial value into the alloca.
1056 Builder.CreateStore(&Arg, Alloca);
1058 // Add arguments to variable symbol table.
1059 NamedValues[Arg.getName()] = Alloca;
1062 if (Value *RetVal = Body->codegen()) {
1063 // Finish off the function.
1064 Builder.CreateRet(RetVal);
1066 // Validate the generated code, checking for consistency.
1067 verifyFunction(*TheFunction);
1069 // Run the optimizer on the function.
1070 TheFPM->run(*TheFunction);
1075 // Error reading body, remove function.
1076 TheFunction->eraseFromParent();
1079 BinopPrecedence.erase(Proto->getOperatorName());
1083 //===----------------------------------------------------------------------===//
1084 // Top-Level parsing and JIT Driver
1085 //===----------------------------------------------------------------------===//
1087 static void InitializeModuleAndPassManager() {
1088 // Open a new module.
1089 TheModule = llvm::make_unique<Module>("my cool jit", getGlobalContext());
1090 TheModule->setDataLayout(TheJIT->getTargetMachine().createDataLayout());
1092 // Create a new pass manager attached to it.
1093 TheFPM = llvm::make_unique<legacy::FunctionPassManager>(TheModule.get());
1095 // Provide basic AliasAnalysis support for GVN.
1096 TheFPM->add(createBasicAliasAnalysisPass());
1097 // Do simple "peephole" optimizations and bit-twiddling optzns.
1098 TheFPM->add(createInstructionCombiningPass());
1099 // Reassociate expressions.
1100 TheFPM->add(createReassociatePass());
1101 // Eliminate Common SubExpressions.
1102 TheFPM->add(createGVNPass());
1103 // Simplify the control flow graph (deleting unreachable blocks, etc).
1104 TheFPM->add(createCFGSimplificationPass());
1106 TheFPM->doInitialization();
1109 static void HandleDefinition() {
1110 if (auto FnAST = ParseDefinition()) {
1111 if (auto *FnIR = FnAST->codegen()) {
1112 fprintf(stderr, "Read function definition:");
1114 TheJIT->addModule(std::move(TheModule));
1115 InitializeModuleAndPassManager();
1118 // Skip token for error recovery.
1123 static void HandleExtern() {
1124 if (auto ProtoAST = ParseExtern()) {
1125 if (auto *FnIR = ProtoAST->codegen()) {
1126 fprintf(stderr, "Read extern: ");
1128 FunctionProtos[ProtoAST->getName()] = std::move(ProtoAST);
1131 // Skip token for error recovery.
1136 static void HandleTopLevelExpression() {
1137 // Evaluate a top-level expression into an anonymous function.
1138 if (auto FnAST = ParseTopLevelExpr()) {
1139 if (FnAST->codegen()) {
1141 // JIT the module containing the anonymous expression, keeping a handle so
1142 // we can free it later.
1143 auto H = TheJIT->addModule(std::move(TheModule));
1144 InitializeModuleAndPassManager();
1146 // Search the JIT for the __anon_expr symbol.
1147 auto ExprSymbol = TheJIT->findSymbol("__anon_expr");
1148 assert(ExprSymbol && "Function not found");
1150 // Get the symbol's address and cast it to the right type (takes no
1151 // arguments, returns a double) so we can call it as a native function.
1152 double (*FP)() = (double (*)())(intptr_t)ExprSymbol.getAddress();
1153 fprintf(stderr, "Evaluated to %f\n", FP());
1155 // Delete the anonymous expression module from the JIT.
1156 TheJIT->removeModule(H);
1159 // Skip token for error recovery.
1164 /// top ::= definition | external | expression | ';'
1165 static void MainLoop() {
1167 fprintf(stderr, "ready> ");
1171 case ';': // ignore top-level semicolons.
1181 HandleTopLevelExpression();
1187 //===----------------------------------------------------------------------===//
1188 // "Library" functions that can be "extern'd" from user code.
1189 //===----------------------------------------------------------------------===//
1191 /// putchard - putchar that takes a double and returns 0.
1192 extern "C" double putchard(double X) {
1197 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1198 extern "C" double printd(double X) {
1203 //===----------------------------------------------------------------------===//
1204 // Main driver code.
1205 //===----------------------------------------------------------------------===//
1208 InitializeNativeTarget();
1209 InitializeNativeTargetAsmPrinter();
1210 InitializeNativeTargetAsmParser();
1212 // Install standard binary operators.
1213 // 1 is lowest precedence.
1214 BinopPrecedence['='] = 2;
1215 BinopPrecedence['<'] = 10;
1216 BinopPrecedence['+'] = 20;
1217 BinopPrecedence['-'] = 20;
1218 BinopPrecedence['*'] = 40; // highest.
1220 // Prime the first token.
1221 fprintf(stderr, "ready> ");
1224 TheJIT = llvm::make_unique<KaleidoscopeJIT>();
1226 InitializeModuleAndPassManager();
1228 // Run the main "interpreter loop" now.