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.
55 static std::string IdentifierStr; // Filled in if tok_identifier
56 static double NumVal; // Filled in if tok_number
58 /// gettok - Return the next token from standard input.
60 static int LastChar = ' ';
62 // Skip any whitespace.
63 while (isspace(LastChar))
66 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
67 IdentifierStr = LastChar;
68 while (isalnum((LastChar = getchar())))
69 IdentifierStr += LastChar;
71 if (IdentifierStr == "def")
73 if (IdentifierStr == "extern")
75 if (IdentifierStr == "if")
77 if (IdentifierStr == "then")
79 if (IdentifierStr == "else")
81 if (IdentifierStr == "for")
83 if (IdentifierStr == "in")
85 if (IdentifierStr == "binary")
87 if (IdentifierStr == "unary")
89 if (IdentifierStr == "var")
91 return tok_identifier;
94 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
99 } while (isdigit(LastChar) || LastChar == '.');
101 NumVal = strtod(NumStr.c_str(), 0);
105 if (LastChar == '#') {
106 // Comment until end of line.
108 LastChar = getchar();
109 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
115 // Check for end of file. Don't eat the EOF.
119 // Otherwise, just return the character as its ascii value.
120 int ThisChar = LastChar;
121 LastChar = getchar();
125 //===----------------------------------------------------------------------===//
126 // Abstract Syntax Tree (aka Parse Tree)
127 //===----------------------------------------------------------------------===//
129 /// ExprAST - Base class for all expression nodes.
132 virtual ~ExprAST() {}
133 virtual Value *Codegen() = 0;
136 /// NumberExprAST - Expression class for numeric literals like "1.0".
137 class NumberExprAST : public ExprAST {
141 NumberExprAST(double Val) : Val(Val) {}
142 Value *Codegen() override;
145 /// VariableExprAST - Expression class for referencing a variable, like "a".
146 class VariableExprAST : public ExprAST {
150 VariableExprAST(const std::string &Name) : Name(Name) {}
151 const std::string &getName() const { return Name; }
152 Value *Codegen() override;
155 /// UnaryExprAST - Expression class for a unary operator.
156 class UnaryExprAST : public ExprAST {
158 std::unique_ptr<ExprAST> Operand;
161 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
162 : Opcode(Opcode), Operand(std::move(Operand)) {}
163 Value *Codegen() override;
166 /// BinaryExprAST - Expression class for a binary operator.
167 class BinaryExprAST : public ExprAST {
169 std::unique_ptr<ExprAST> LHS, RHS;
172 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
173 std::unique_ptr<ExprAST> RHS)
174 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
175 Value *Codegen() override;
178 /// CallExprAST - Expression class for function calls.
179 class CallExprAST : public ExprAST {
181 std::vector<std::unique_ptr<ExprAST>> Args;
184 CallExprAST(const std::string &Callee,
185 std::vector<std::unique_ptr<ExprAST>> Args)
186 : Callee(Callee), Args(std::move(Args)) {}
187 Value *Codegen() override;
190 /// IfExprAST - Expression class for if/then/else.
191 class IfExprAST : public ExprAST {
192 std::unique_ptr<ExprAST> Cond, Then, Else;
195 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
196 std::unique_ptr<ExprAST> Else)
197 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
198 Value *Codegen() override;
201 /// ForExprAST - Expression class for for/in.
202 class ForExprAST : public ExprAST {
204 std::unique_ptr<ExprAST> Start, End, Step, Body;
207 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
208 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
209 std::unique_ptr<ExprAST> Body)
210 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
211 Step(std::move(Step)), Body(std::move(Body)) {}
212 Value *Codegen() override;
215 /// VarExprAST - Expression class for var/in
216 class VarExprAST : public ExprAST {
217 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
218 std::unique_ptr<ExprAST> Body;
222 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
223 std::unique_ptr<ExprAST> Body)
224 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
225 Value *Codegen() override;
228 /// PrototypeAST - This class represents the "prototype" for a function,
229 /// which captures its name, and its argument names (thus implicitly the number
230 /// of arguments the function takes), as well as if it is an operator.
233 std::vector<std::string> Args;
235 unsigned Precedence; // Precedence if a binary op.
238 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
239 bool IsOperator = false, unsigned Prec = 0)
240 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
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; }
255 void CreateArgumentAllocas(Function *F);
258 /// FunctionAST - This class represents a function definition itself.
260 std::unique_ptr<PrototypeAST> Proto;
261 std::unique_ptr<ExprAST> Body;
264 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
265 std::unique_ptr<ExprAST> Body)
266 : Proto(std::move(Proto)), Body(std::move(Body)) {}
269 } // end anonymous namespace
271 //===----------------------------------------------------------------------===//
273 //===----------------------------------------------------------------------===//
275 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
276 /// token the parser is looking at. getNextToken reads another token from the
277 /// lexer and updates CurTok with its results.
279 static int getNextToken() { return CurTok = gettok(); }
281 /// BinopPrecedence - This holds the precedence for each binary operator that is
283 static std::map<char, int> BinopPrecedence;
285 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
286 static int GetTokPrecedence() {
287 if (!isascii(CurTok))
290 // Make sure it's a declared binop.
291 int TokPrec = BinopPrecedence[CurTok];
297 /// Error* - These are little helper functions for error handling.
298 std::unique_ptr<ExprAST> Error(const char *Str) {
299 fprintf(stderr, "Error: %s\n", Str);
302 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
306 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
311 static std::unique_ptr<ExprAST> ParseExpression();
313 /// numberexpr ::= number
314 static std::unique_ptr<ExprAST> ParseNumberExpr() {
315 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
316 getNextToken(); // consume the number
317 return std::move(Result);
320 /// parenexpr ::= '(' expression ')'
321 static std::unique_ptr<ExprAST> ParseParenExpr() {
322 getNextToken(); // eat (.
323 auto V = ParseExpression();
328 return Error("expected ')'");
329 getNextToken(); // eat ).
335 /// ::= identifier '(' expression* ')'
336 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
337 std::string IdName = IdentifierStr;
339 getNextToken(); // eat identifier.
341 if (CurTok != '(') // Simple variable ref.
342 return llvm::make_unique<VariableExprAST>(IdName);
345 getNextToken(); // eat (
346 std::vector<std::unique_ptr<ExprAST>> Args;
349 if (auto Arg = ParseExpression())
350 Args.push_back(std::move(Arg));
358 return Error("Expected ')' or ',' in argument list");
366 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
369 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
370 static std::unique_ptr<ExprAST> ParseIfExpr() {
371 getNextToken(); // eat the if.
374 auto Cond = ParseExpression();
378 if (CurTok != tok_then)
379 return Error("expected then");
380 getNextToken(); // eat the then
382 auto Then = ParseExpression();
386 if (CurTok != tok_else)
387 return Error("expected else");
391 auto Else = ParseExpression();
395 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
399 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
400 static std::unique_ptr<ExprAST> ParseForExpr() {
401 getNextToken(); // eat the for.
403 if (CurTok != tok_identifier)
404 return Error("expected identifier after for");
406 std::string IdName = IdentifierStr;
407 getNextToken(); // eat identifier.
410 return Error("expected '=' after for");
411 getNextToken(); // eat '='.
413 auto Start = ParseExpression();
417 return Error("expected ',' after for start value");
420 auto End = ParseExpression();
424 // The step value is optional.
425 std::unique_ptr<ExprAST> Step;
428 Step = ParseExpression();
433 if (CurTok != tok_in)
434 return Error("expected 'in' after for");
435 getNextToken(); // eat 'in'.
437 auto Body = ParseExpression();
441 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
442 std::move(Step), std::move(Body));
445 /// varexpr ::= 'var' identifier ('=' expression)?
446 // (',' identifier ('=' expression)?)* 'in' expression
447 static std::unique_ptr<ExprAST> ParseVarExpr() {
448 getNextToken(); // eat the var.
450 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
452 // At least one variable name is required.
453 if (CurTok != tok_identifier)
454 return Error("expected identifier after var");
457 std::string Name = IdentifierStr;
458 getNextToken(); // eat identifier.
460 // Read the optional initializer.
461 std::unique_ptr<ExprAST> Init = nullptr;
463 getNextToken(); // eat the '='.
465 Init = ParseExpression();
470 VarNames.push_back(std::make_pair(Name, std::move(Init)));
472 // End of var list, exit loop.
475 getNextToken(); // eat the ','.
477 if (CurTok != tok_identifier)
478 return Error("expected identifier list after var");
481 // At this point, we have to have 'in'.
482 if (CurTok != tok_in)
483 return Error("expected 'in' keyword after 'var'");
484 getNextToken(); // eat 'in'.
486 auto Body = ParseExpression();
490 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
494 /// ::= identifierexpr
500 static std::unique_ptr<ExprAST> ParsePrimary() {
503 return Error("unknown token when expecting an expression");
505 return ParseIdentifierExpr();
507 return ParseNumberExpr();
509 return ParseParenExpr();
511 return ParseIfExpr();
513 return ParseForExpr();
515 return ParseVarExpr();
522 static std::unique_ptr<ExprAST> ParseUnary() {
523 // If the current token is not an operator, it must be a primary expr.
524 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
525 return ParsePrimary();
527 // If this is a unary operator, read it.
530 if (auto Operand = ParseUnary())
531 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
537 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
538 std::unique_ptr<ExprAST> LHS) {
539 // If this is a binop, find its precedence.
541 int TokPrec = GetTokPrecedence();
543 // If this is a binop that binds at least as tightly as the current binop,
544 // consume it, otherwise we are done.
545 if (TokPrec < ExprPrec)
548 // Okay, we know this is a binop.
550 getNextToken(); // eat binop
552 // Parse the unary expression after the binary operator.
553 auto RHS = ParseUnary();
557 // If BinOp binds less tightly with RHS than the operator after RHS, let
558 // the pending operator take RHS as its LHS.
559 int NextPrec = GetTokPrecedence();
560 if (TokPrec < NextPrec) {
561 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
568 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
573 /// ::= unary binoprhs
575 static std::unique_ptr<ExprAST> ParseExpression() {
576 auto LHS = ParseUnary();
580 return ParseBinOpRHS(0, std::move(LHS));
584 /// ::= id '(' id* ')'
585 /// ::= binary LETTER number? (id, id)
586 /// ::= unary LETTER (id)
587 static std::unique_ptr<PrototypeAST> ParsePrototype() {
590 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
591 unsigned BinaryPrecedence = 30;
595 return ErrorP("Expected function name in prototype");
597 FnName = IdentifierStr;
603 if (!isascii(CurTok))
604 return ErrorP("Expected unary operator");
606 FnName += (char)CurTok;
612 if (!isascii(CurTok))
613 return ErrorP("Expected binary operator");
615 FnName += (char)CurTok;
619 // Read the precedence if present.
620 if (CurTok == tok_number) {
621 if (NumVal < 1 || NumVal > 100)
622 return ErrorP("Invalid precedecnce: must be 1..100");
623 BinaryPrecedence = (unsigned)NumVal;
630 return ErrorP("Expected '(' in prototype");
632 std::vector<std::string> ArgNames;
633 while (getNextToken() == tok_identifier)
634 ArgNames.push_back(IdentifierStr);
636 return ErrorP("Expected ')' in prototype");
639 getNextToken(); // eat ')'.
641 // Verify right number of names for operator.
642 if (Kind && ArgNames.size() != Kind)
643 return ErrorP("Invalid number of operands for operator");
645 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
649 /// definition ::= 'def' prototype expression
650 static std::unique_ptr<FunctionAST> ParseDefinition() {
651 getNextToken(); // eat def.
652 auto Proto = ParsePrototype();
656 if (auto E = ParseExpression())
657 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
661 /// toplevelexpr ::= expression
662 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
663 if (auto E = ParseExpression()) {
664 // Make an anonymous proto.
666 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
667 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
672 /// external ::= 'extern' prototype
673 static std::unique_ptr<PrototypeAST> ParseExtern() {
674 getNextToken(); // eat extern.
675 return ParsePrototype();
678 //===----------------------------------------------------------------------===//
680 //===----------------------------------------------------------------------===//
682 static Module *TheModule;
683 static IRBuilder<> Builder(getGlobalContext());
684 static std::map<std::string, AllocaInst *> NamedValues;
685 static legacy::FunctionPassManager *TheFPM;
687 Value *ErrorV(const char *Str) {
692 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
693 /// the function. This is used for mutable variables etc.
694 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
695 const std::string &VarName) {
696 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
697 TheFunction->getEntryBlock().begin());
698 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
702 Value *NumberExprAST::Codegen() {
703 return ConstantFP::get(getGlobalContext(), APFloat(Val));
706 Value *VariableExprAST::Codegen() {
707 // Look this variable up in the function.
708 Value *V = NamedValues[Name];
710 return ErrorV("Unknown variable name");
713 return Builder.CreateLoad(V, Name.c_str());
716 Value *UnaryExprAST::Codegen() {
717 Value *OperandV = Operand->Codegen();
721 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
723 return ErrorV("Unknown unary operator");
725 return Builder.CreateCall(F, OperandV, "unop");
728 Value *BinaryExprAST::Codegen() {
729 // Special case '=' because we don't want to emit the LHS as an expression.
731 // Assignment requires the LHS to be an identifier.
732 // This assume we're building without RTTI because LLVM builds that way by
733 // default. If you build LLVM with RTTI this can be changed to a
734 // dynamic_cast for automatic error checking.
735 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS.get());
737 return ErrorV("destination of '=' must be a variable");
739 Value *Val = RHS->Codegen();
744 Value *Variable = NamedValues[LHSE->getName()];
746 return ErrorV("Unknown variable name");
748 Builder.CreateStore(Val, Variable);
752 Value *L = LHS->Codegen();
753 Value *R = RHS->Codegen();
759 return Builder.CreateFAdd(L, R, "addtmp");
761 return Builder.CreateFSub(L, R, "subtmp");
763 return Builder.CreateFMul(L, R, "multmp");
765 L = Builder.CreateFCmpULT(L, R, "cmptmp");
766 // Convert bool 0/1 to double 0.0 or 1.0
767 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
773 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
775 Function *F = TheModule->getFunction(std::string("binary") + Op);
776 assert(F && "binary operator not found!");
778 Value *Ops[] = {L, R};
779 return Builder.CreateCall(F, Ops, "binop");
782 Value *CallExprAST::Codegen() {
783 // Look up the name in the global module table.
784 Function *CalleeF = TheModule->getFunction(Callee);
786 return ErrorV("Unknown function referenced");
788 // If argument mismatch error.
789 if (CalleeF->arg_size() != Args.size())
790 return ErrorV("Incorrect # arguments passed");
792 std::vector<Value *> ArgsV;
793 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
794 ArgsV.push_back(Args[i]->Codegen());
799 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
802 Value *IfExprAST::Codegen() {
803 Value *CondV = Cond->Codegen();
807 // Convert condition to a bool by comparing equal to 0.0.
808 CondV = Builder.CreateFCmpONE(
809 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
811 Function *TheFunction = Builder.GetInsertBlock()->getParent();
813 // Create blocks for the then and else cases. Insert the 'then' block at the
814 // end of the function.
816 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
817 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
818 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
820 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
823 Builder.SetInsertPoint(ThenBB);
825 Value *ThenV = Then->Codegen();
829 Builder.CreateBr(MergeBB);
830 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
831 ThenBB = Builder.GetInsertBlock();
834 TheFunction->getBasicBlockList().push_back(ElseBB);
835 Builder.SetInsertPoint(ElseBB);
837 Value *ElseV = Else->Codegen();
841 Builder.CreateBr(MergeBB);
842 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
843 ElseBB = Builder.GetInsertBlock();
846 TheFunction->getBasicBlockList().push_back(MergeBB);
847 Builder.SetInsertPoint(MergeBB);
849 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
851 PN->addIncoming(ThenV, ThenBB);
852 PN->addIncoming(ElseV, ElseBB);
856 // Output for-loop as:
857 // var = alloca double
860 // store start -> var
871 // nextvar = curvar + step
872 // store nextvar -> var
873 // br endcond, loop, endloop
875 Value *ForExprAST::Codegen() {
876 Function *TheFunction = Builder.GetInsertBlock()->getParent();
878 // Create an alloca for the variable in the entry block.
879 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
881 // Emit the start code first, without 'variable' in scope.
882 Value *StartVal = Start->Codegen();
886 // Store the value into the alloca.
887 Builder.CreateStore(StartVal, Alloca);
889 // Make the new basic block for the loop header, inserting after current
892 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
894 // Insert an explicit fall through from the current block to the LoopBB.
895 Builder.CreateBr(LoopBB);
897 // Start insertion in LoopBB.
898 Builder.SetInsertPoint(LoopBB);
900 // Within the loop, the variable is defined equal to the PHI node. If it
901 // shadows an existing variable, we have to restore it, so save it now.
902 AllocaInst *OldVal = NamedValues[VarName];
903 NamedValues[VarName] = Alloca;
905 // Emit the body of the loop. This, like any other expr, can change the
906 // current BB. Note that we ignore the value computed by the body, but don't
908 if (!Body->Codegen())
911 // Emit the step value.
912 Value *StepVal = nullptr;
914 StepVal = Step->Codegen();
918 // If not specified, use 1.0.
919 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
922 // Compute the end condition.
923 Value *EndCond = End->Codegen();
927 // Reload, increment, and restore the alloca. This handles the case where
928 // the body of the loop mutates the variable.
929 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
930 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
931 Builder.CreateStore(NextVar, Alloca);
933 // Convert condition to a bool by comparing equal to 0.0.
934 EndCond = Builder.CreateFCmpONE(
935 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
937 // Create the "after loop" block and insert it.
938 BasicBlock *AfterBB =
939 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
941 // Insert the conditional branch into the end of LoopEndBB.
942 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
944 // Any new code will be inserted in AfterBB.
945 Builder.SetInsertPoint(AfterBB);
947 // Restore the unshadowed variable.
949 NamedValues[VarName] = OldVal;
951 NamedValues.erase(VarName);
953 // for expr always returns 0.0.
954 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
957 Value *VarExprAST::Codegen() {
958 std::vector<AllocaInst *> OldBindings;
960 Function *TheFunction = Builder.GetInsertBlock()->getParent();
962 // Register all variables and emit their initializer.
963 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
964 const std::string &VarName = VarNames[i].first;
965 ExprAST *Init = VarNames[i].second.get();
967 // Emit the initializer before adding the variable to scope, this prevents
968 // the initializer from referencing the variable itself, and permits stuff
971 // var a = a in ... # refers to outer 'a'.
974 InitVal = Init->Codegen();
977 } else { // If not specified, use 0.0.
978 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
981 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
982 Builder.CreateStore(InitVal, Alloca);
984 // Remember the old variable binding so that we can restore the binding when
986 OldBindings.push_back(NamedValues[VarName]);
988 // Remember this binding.
989 NamedValues[VarName] = Alloca;
992 // Codegen the body, now that all vars are in scope.
993 Value *BodyVal = Body->Codegen();
997 // Pop all our variables from scope.
998 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
999 NamedValues[VarNames[i].first] = OldBindings[i];
1001 // Return the body computation.
1005 Function *PrototypeAST::Codegen() {
1006 // Make the function type: double(double,double) etc.
1007 std::vector<Type *> Doubles(Args.size(),
1008 Type::getDoubleTy(getGlobalContext()));
1010 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
1013 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1015 // If F conflicted, there was already something named 'Name'. If it has a
1016 // body, don't allow redefinition or reextern.
1017 if (F->getName() != Name) {
1018 // Delete the one we just made and get the existing one.
1019 F->eraseFromParent();
1020 F = TheModule->getFunction(Name);
1022 // If F already has a body, reject this.
1024 ErrorF("redefinition of function");
1028 // If F took a different number of args, reject.
1029 if (F->arg_size() != Args.size()) {
1030 ErrorF("redefinition of function with different # args");
1035 // Set names for all arguments.
1037 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1039 AI->setName(Args[Idx]);
1044 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1045 /// argument in the symbol table so that references to it will succeed.
1046 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1047 Function::arg_iterator AI = F->arg_begin();
1048 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1049 // Create an alloca for this variable.
1050 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1052 // Store the initial value into the alloca.
1053 Builder.CreateStore(AI, Alloca);
1055 // Add arguments to variable symbol table.
1056 NamedValues[Args[Idx]] = Alloca;
1060 Function *FunctionAST::Codegen() {
1061 NamedValues.clear();
1063 Function *TheFunction = Proto->Codegen();
1067 // If this is an operator, install it.
1068 if (Proto->isBinaryOp())
1069 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1071 // Create a new basic block to start insertion into.
1072 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1073 Builder.SetInsertPoint(BB);
1075 // Add all arguments to the symbol table and create their allocas.
1076 Proto->CreateArgumentAllocas(TheFunction);
1078 if (Value *RetVal = Body->Codegen()) {
1079 // Finish off the function.
1080 Builder.CreateRet(RetVal);
1082 // Validate the generated code, checking for consistency.
1083 verifyFunction(*TheFunction);
1085 // Optimize the function.
1086 TheFPM->run(*TheFunction);
1091 // Error reading body, remove function.
1092 TheFunction->eraseFromParent();
1094 if (Proto->isBinaryOp())
1095 BinopPrecedence.erase(Proto->getOperatorName());
1099 //===----------------------------------------------------------------------===//
1100 // Top-Level parsing and JIT Driver
1101 //===----------------------------------------------------------------------===//
1103 static ExecutionEngine *TheExecutionEngine;
1105 static void HandleDefinition() {
1106 if (auto FnAST = ParseDefinition()) {
1107 if (auto *FnIR = FnAST->Codegen()) {
1108 fprintf(stderr, "Read function definition:");
1112 // Skip token for error recovery.
1117 static void HandleExtern() {
1118 if (auto ProtoAST = ParseExtern()) {
1119 if (auto *FnIR = ProtoAST->Codegen()) {
1120 fprintf(stderr, "Read extern: ");
1124 // Skip token for error recovery.
1129 static void HandleTopLevelExpression() {
1130 // Evaluate a top-level expression into an anonymous function.
1131 if (auto FnAST = ParseTopLevelExpr()) {
1132 if (auto *FnIR = FnAST->Codegen()) {
1133 TheExecutionEngine->finalizeObject();
1134 // JIT the function, returning a function pointer.
1135 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
1137 // Cast it to the right type (takes no arguments, returns a double) so we
1138 // can call it as a native function.
1139 double (*FP)() = (double (*)())(intptr_t)FPtr;
1140 fprintf(stderr, "Evaluated to %f\n", FP());
1143 // Skip token for error recovery.
1148 /// top ::= definition | external | expression | ';'
1149 static void MainLoop() {
1151 fprintf(stderr, "ready> ");
1155 case ';': // ignore top-level semicolons.
1165 HandleTopLevelExpression();
1171 //===----------------------------------------------------------------------===//
1172 // "Library" functions that can be "extern'd" from user code.
1173 //===----------------------------------------------------------------------===//
1175 /// putchard - putchar that takes a double and returns 0.
1176 extern "C" double putchard(double X) {
1181 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1182 extern "C" double printd(double X) {
1187 //===----------------------------------------------------------------------===//
1188 // Main driver code.
1189 //===----------------------------------------------------------------------===//
1192 InitializeNativeTarget();
1193 InitializeNativeTargetAsmPrinter();
1194 InitializeNativeTargetAsmParser();
1195 LLVMContext &Context = getGlobalContext();
1197 // Install standard binary operators.
1198 // 1 is lowest precedence.
1199 BinopPrecedence['='] = 2;
1200 BinopPrecedence['<'] = 10;
1201 BinopPrecedence['+'] = 20;
1202 BinopPrecedence['-'] = 20;
1203 BinopPrecedence['*'] = 40; // highest.
1205 // Prime the first token.
1206 fprintf(stderr, "ready> ");
1209 // Make the module, which holds all the code.
1210 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1211 TheModule = Owner.get();
1213 // Create the JIT. This takes ownership of the module.
1215 TheExecutionEngine =
1216 EngineBuilder(std::move(Owner))
1217 .setErrorStr(&ErrStr)
1218 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1220 if (!TheExecutionEngine) {
1221 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1225 legacy::FunctionPassManager OurFPM(TheModule);
1227 // Set up the optimizer pipeline. Start with registering info about how the
1228 // target lays out data structures.
1229 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1230 // Provide basic AliasAnalysis support for GVN.
1231 OurFPM.add(createBasicAliasAnalysisPass());
1232 // Promote allocas to registers.
1233 OurFPM.add(createPromoteMemoryToRegisterPass());
1234 // Do simple "peephole" optimizations and bit-twiddling optzns.
1235 OurFPM.add(createInstructionCombiningPass());
1236 // Reassociate expressions.
1237 OurFPM.add(createReassociatePass());
1238 // Eliminate Common SubExpressions.
1239 OurFPM.add(createGVNPass());
1240 // Simplify the control flow graph (deleting unreachable blocks, etc).
1241 OurFPM.add(createCFGSimplificationPass());
1243 OurFPM.doInitialization();
1245 // Set the global so the code gen can use this.
1248 // Run the main "interpreter loop" now.
1253 // Print out all of the generated code.