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 {
140 NumberExprAST(double Val) : Val(Val) {}
141 Value *Codegen() override;
144 /// VariableExprAST - Expression class for referencing a variable, like "a".
145 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;
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;
168 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
169 std::unique_ptr<ExprAST> RHS)
170 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
171 Value *Codegen() override;
174 /// CallExprAST - Expression class for function calls.
175 class CallExprAST : public ExprAST {
177 std::vector<std::unique_ptr<ExprAST>> Args;
179 CallExprAST(const std::string &Callee,
180 std::vector<std::unique_ptr<ExprAST>> Args)
181 : Callee(Callee), Args(std::move(Args)) {}
182 Value *Codegen() override;
185 /// IfExprAST - Expression class for if/then/else.
186 class IfExprAST : public ExprAST {
187 std::unique_ptr<ExprAST> Cond, Then, Else;
189 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
190 std::unique_ptr<ExprAST> Else)
191 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
192 Value *Codegen() override;
195 /// ForExprAST - Expression class for for/in.
196 class ForExprAST : public ExprAST {
198 std::unique_ptr<ExprAST> Start, End, Step, Body;
200 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
201 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
202 std::unique_ptr<ExprAST> Body)
203 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
204 Step(std::move(Step)), Body(std::move(Body)) {}
205 Value *Codegen() override;
208 /// VarExprAST - Expression class for var/in
209 class VarExprAST : public ExprAST {
210 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
211 std::unique_ptr<ExprAST> Body;
213 VarExprAST(std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames,
214 std::unique_ptr<ExprAST> Body)
215 : VarNames(std::move(VarNames)), Body(std::move(Body)) {}
216 Value *Codegen() override;
219 /// PrototypeAST - This class represents the "prototype" for a function,
220 /// which captures its argument names as well as if it is an operator.
223 std::vector<std::string> Args;
225 unsigned Precedence; // Precedence if a binary op.
227 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
228 bool IsOperator = false, unsigned Prec = 0)
229 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
232 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
233 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
235 char getOperatorName() const {
236 assert(isUnaryOp() || isBinaryOp());
237 return Name[Name.size() - 1];
240 unsigned getBinaryPrecedence() const { return Precedence; }
244 void CreateArgumentAllocas(Function *F);
247 /// FunctionAST - This class represents a function definition itself.
249 std::unique_ptr<PrototypeAST> Proto;
250 std::unique_ptr<ExprAST> Body;
252 FunctionAST(std::unique_ptr<PrototypeAST> Proto, std::unique_ptr<ExprAST> Body)
253 : Proto(std::move(Proto)), Body(std::move(Body)) {}
256 } // end anonymous namespace
258 //===----------------------------------------------------------------------===//
260 //===----------------------------------------------------------------------===//
262 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
263 /// token the parser is looking at. getNextToken reads another token from the
264 /// lexer and updates CurTok with its results.
266 static int getNextToken() { return CurTok = gettok(); }
268 /// BinopPrecedence - This holds the precedence for each binary operator that is
270 static std::map<char, int> BinopPrecedence;
272 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
273 static int GetTokPrecedence() {
274 if (!isascii(CurTok))
277 // Make sure it's a declared binop.
278 int TokPrec = BinopPrecedence[CurTok];
284 /// Error* - These are little helper functions for error handling.
285 std::unique_ptr<ExprAST> Error(const char *Str) {
286 fprintf(stderr, "Error: %s\n", Str);
289 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
293 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
298 static std::unique_ptr<ExprAST> ParseExpression();
302 /// ::= identifier '(' expression* ')'
303 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
304 std::string IdName = IdentifierStr;
306 getNextToken(); // eat identifier.
308 if (CurTok != '(') // Simple variable ref.
309 return llvm::make_unique<VariableExprAST>(IdName);
312 getNextToken(); // eat (
313 std::vector<std::unique_ptr<ExprAST>> Args;
316 if (auto Arg = ParseExpression())
317 Args.push_back(std::move(Arg));
325 return Error("Expected ')' or ',' in argument list");
333 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
336 /// numberexpr ::= number
337 static std::unique_ptr<ExprAST> ParseNumberExpr() {
338 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
339 getNextToken(); // consume the number
340 return std::move(Result);
343 /// parenexpr ::= '(' expression ')'
344 static std::unique_ptr<ExprAST> ParseParenExpr() {
345 getNextToken(); // eat (.
346 auto V = ParseExpression();
351 return Error("expected ')'");
352 getNextToken(); // eat ).
356 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
357 static std::unique_ptr<ExprAST> ParseIfExpr() {
358 getNextToken(); // eat the if.
361 auto Cond = ParseExpression();
365 if (CurTok != tok_then)
366 return Error("expected then");
367 getNextToken(); // eat the then
369 auto Then = ParseExpression();
373 if (CurTok != tok_else)
374 return Error("expected else");
378 auto Else = ParseExpression();
382 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
386 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
387 static std::unique_ptr<ExprAST> ParseForExpr() {
388 getNextToken(); // eat the for.
390 if (CurTok != tok_identifier)
391 return Error("expected identifier after for");
393 std::string IdName = IdentifierStr;
394 getNextToken(); // eat identifier.
397 return Error("expected '=' after for");
398 getNextToken(); // eat '='.
400 auto Start = ParseExpression();
404 return Error("expected ',' after for start value");
407 auto End = ParseExpression();
411 // The step value is optional.
412 std::unique_ptr<ExprAST> Step;
415 Step = ParseExpression();
420 if (CurTok != tok_in)
421 return Error("expected 'in' after for");
422 getNextToken(); // eat 'in'.
424 auto Body = ParseExpression();
428 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
429 std::move(Step), std::move(Body));
432 /// varexpr ::= 'var' identifier ('=' expression)?
433 // (',' identifier ('=' expression)?)* 'in' expression
434 static std::unique_ptr<ExprAST> ParseVarExpr() {
435 getNextToken(); // eat the var.
437 std::vector<std::pair<std::string, std::unique_ptr<ExprAST>>> VarNames;
439 // At least one variable name is required.
440 if (CurTok != tok_identifier)
441 return Error("expected identifier after var");
444 std::string Name = IdentifierStr;
445 getNextToken(); // eat identifier.
447 // Read the optional initializer.
448 std::unique_ptr<ExprAST> Init = nullptr;
450 getNextToken(); // eat the '='.
452 Init = ParseExpression();
457 VarNames.push_back(std::make_pair(Name, std::move(Init)));
459 // End of var list, exit loop.
462 getNextToken(); // eat the ','.
464 if (CurTok != tok_identifier)
465 return Error("expected identifier list after var");
468 // At this point, we have to have 'in'.
469 if (CurTok != tok_in)
470 return Error("expected 'in' keyword after 'var'");
471 getNextToken(); // eat 'in'.
473 auto Body = ParseExpression();
477 return llvm::make_unique<VarExprAST>(std::move(VarNames), std::move(Body));
481 /// ::= identifierexpr
487 static std::unique_ptr<ExprAST> ParsePrimary() {
490 return Error("unknown token when expecting an expression");
492 return ParseIdentifierExpr();
494 return ParseNumberExpr();
496 return ParseParenExpr();
498 return ParseIfExpr();
500 return ParseForExpr();
502 return ParseVarExpr();
509 static std::unique_ptr<ExprAST> ParseUnary() {
510 // If the current token is not an operator, it must be a primary expr.
511 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
512 return ParsePrimary();
514 // If this is a unary operator, read it.
517 if (auto Operand = ParseUnary())
518 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
524 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec, std::unique_ptr<ExprAST> LHS) {
525 // If this is a binop, find its precedence.
527 int TokPrec = GetTokPrecedence();
529 // If this is a binop that binds at least as tightly as the current binop,
530 // consume it, otherwise we are done.
531 if (TokPrec < ExprPrec)
534 // Okay, we know this is a binop.
536 getNextToken(); // eat binop
538 // Parse the unary expression after the binary operator.
539 auto RHS = ParseUnary();
543 // If BinOp binds less tightly with RHS than the operator after RHS, let
544 // the pending operator take RHS as its LHS.
545 int NextPrec = GetTokPrecedence();
546 if (TokPrec < NextPrec) {
547 RHS = ParseBinOpRHS(TokPrec + 1, std::move(RHS));
553 LHS = llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
558 /// ::= unary binoprhs
560 static std::unique_ptr<ExprAST> ParseExpression() {
561 auto LHS = ParseUnary();
565 return ParseBinOpRHS(0, std::move(LHS));
569 /// ::= id '(' id* ')'
570 /// ::= binary LETTER number? (id, id)
571 /// ::= unary LETTER (id)
572 static std::unique_ptr<PrototypeAST> ParsePrototype() {
575 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
576 unsigned BinaryPrecedence = 30;
580 return ErrorP("Expected function name in prototype");
582 FnName = IdentifierStr;
588 if (!isascii(CurTok))
589 return ErrorP("Expected unary operator");
591 FnName += (char)CurTok;
597 if (!isascii(CurTok))
598 return ErrorP("Expected binary operator");
600 FnName += (char)CurTok;
604 // Read the precedence if present.
605 if (CurTok == tok_number) {
606 if (NumVal < 1 || NumVal > 100)
607 return ErrorP("Invalid precedecnce: must be 1..100");
608 BinaryPrecedence = (unsigned)NumVal;
615 return ErrorP("Expected '(' in prototype");
617 std::vector<std::string> ArgNames;
618 while (getNextToken() == tok_identifier)
619 ArgNames.push_back(IdentifierStr);
621 return ErrorP("Expected ')' in prototype");
624 getNextToken(); // eat ')'.
626 // Verify right number of names for operator.
627 if (Kind && ArgNames.size() != Kind)
628 return ErrorP("Invalid number of operands for operator");
630 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
634 /// definition ::= 'def' prototype expression
635 static std::unique_ptr<FunctionAST> ParseDefinition() {
636 getNextToken(); // eat def.
637 auto Proto = ParsePrototype();
641 if (auto E = ParseExpression())
642 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
646 /// toplevelexpr ::= expression
647 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
648 if (auto E = ParseExpression()) {
649 // Make an anonymous proto.
650 auto Proto = llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
651 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
656 /// external ::= 'extern' prototype
657 static std::unique_ptr<PrototypeAST> ParseExtern() {
658 getNextToken(); // eat extern.
659 return ParsePrototype();
662 //===----------------------------------------------------------------------===//
664 //===----------------------------------------------------------------------===//
666 static Module *TheModule;
667 static IRBuilder<> Builder(getGlobalContext());
668 static std::map<std::string, AllocaInst *> NamedValues;
669 static legacy::FunctionPassManager *TheFPM;
671 Value *ErrorV(const char *Str) {
676 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
677 /// the function. This is used for mutable variables etc.
678 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
679 const std::string &VarName) {
680 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
681 TheFunction->getEntryBlock().begin());
682 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
686 Value *NumberExprAST::Codegen() {
687 return ConstantFP::get(getGlobalContext(), APFloat(Val));
690 Value *VariableExprAST::Codegen() {
691 // Look this variable up in the function.
692 Value *V = NamedValues[Name];
694 return ErrorV("Unknown variable name");
697 return Builder.CreateLoad(V, Name.c_str());
700 Value *UnaryExprAST::Codegen() {
701 Value *OperandV = Operand->Codegen();
705 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
707 return ErrorV("Unknown unary operator");
709 return Builder.CreateCall(F, OperandV, "unop");
712 Value *BinaryExprAST::Codegen() {
713 // Special case '=' because we don't want to emit the LHS as an expression.
715 // Assignment requires the LHS to be an identifier.
716 // This assume we're building without RTTI because LLVM builds that way by
717 // default. If you build LLVM with RTTI this can be changed to a
718 // dynamic_cast for automatic error checking.
719 VariableExprAST *LHSE = static_cast<VariableExprAST*>(LHS.get());
721 return ErrorV("destination of '=' must be a variable");
723 Value *Val = RHS->Codegen();
728 Value *Variable = NamedValues[LHSE->getName()];
730 return ErrorV("Unknown variable name");
732 Builder.CreateStore(Val, Variable);
736 Value *L = LHS->Codegen();
737 Value *R = RHS->Codegen();
743 return Builder.CreateFAdd(L, R, "addtmp");
745 return Builder.CreateFSub(L, R, "subtmp");
747 return Builder.CreateFMul(L, R, "multmp");
749 L = Builder.CreateFCmpULT(L, R, "cmptmp");
750 // Convert bool 0/1 to double 0.0 or 1.0
751 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
757 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
759 Function *F = TheModule->getFunction(std::string("binary") + Op);
760 assert(F && "binary operator not found!");
762 Value *Ops[] = { L, R };
763 return Builder.CreateCall(F, Ops, "binop");
766 Value *CallExprAST::Codegen() {
767 // Look up the name in the global module table.
768 Function *CalleeF = TheModule->getFunction(Callee);
770 return ErrorV("Unknown function referenced");
772 // If argument mismatch error.
773 if (CalleeF->arg_size() != Args.size())
774 return ErrorV("Incorrect # arguments passed");
776 std::vector<Value *> ArgsV;
777 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
778 ArgsV.push_back(Args[i]->Codegen());
783 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
786 Value *IfExprAST::Codegen() {
787 Value *CondV = Cond->Codegen();
791 // Convert condition to a bool by comparing equal to 0.0.
792 CondV = Builder.CreateFCmpONE(
793 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
795 Function *TheFunction = Builder.GetInsertBlock()->getParent();
797 // Create blocks for the then and else cases. Insert the 'then' block at the
798 // end of the function.
800 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
801 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
802 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
804 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
807 Builder.SetInsertPoint(ThenBB);
809 Value *ThenV = Then->Codegen();
813 Builder.CreateBr(MergeBB);
814 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
815 ThenBB = Builder.GetInsertBlock();
818 TheFunction->getBasicBlockList().push_back(ElseBB);
819 Builder.SetInsertPoint(ElseBB);
821 Value *ElseV = Else->Codegen();
825 Builder.CreateBr(MergeBB);
826 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
827 ElseBB = Builder.GetInsertBlock();
830 TheFunction->getBasicBlockList().push_back(MergeBB);
831 Builder.SetInsertPoint(MergeBB);
833 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
835 PN->addIncoming(ThenV, ThenBB);
836 PN->addIncoming(ElseV, ElseBB);
840 Value *ForExprAST::Codegen() {
842 // var = alloca double
845 // store start -> var
856 // nextvar = curvar + step
857 // store nextvar -> var
858 // br endcond, loop, endloop
861 Function *TheFunction = Builder.GetInsertBlock()->getParent();
863 // Create an alloca for the variable in the entry block.
864 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
866 // Emit the start code first, without 'variable' in scope.
867 Value *StartVal = Start->Codegen();
871 // Store the value into the alloca.
872 Builder.CreateStore(StartVal, Alloca);
874 // Make the new basic block for the loop header, inserting after current
877 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
879 // Insert an explicit fall through from the current block to the LoopBB.
880 Builder.CreateBr(LoopBB);
882 // Start insertion in LoopBB.
883 Builder.SetInsertPoint(LoopBB);
885 // Within the loop, the variable is defined equal to the PHI node. If it
886 // shadows an existing variable, we have to restore it, so save it now.
887 AllocaInst *OldVal = NamedValues[VarName];
888 NamedValues[VarName] = Alloca;
890 // Emit the body of the loop. This, like any other expr, can change the
891 // current BB. Note that we ignore the value computed by the body, but don't
893 if (!Body->Codegen())
896 // Emit the step value.
899 StepVal = Step->Codegen();
903 // If not specified, use 1.0.
904 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
907 // Compute the end condition.
908 Value *EndCond = End->Codegen();
912 // Reload, increment, and restore the alloca. This handles the case where
913 // the body of the loop mutates the variable.
914 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
915 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
916 Builder.CreateStore(NextVar, Alloca);
918 // Convert condition to a bool by comparing equal to 0.0.
919 EndCond = Builder.CreateFCmpONE(
920 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
922 // Create the "after loop" block and insert it.
923 BasicBlock *AfterBB =
924 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
926 // Insert the conditional branch into the end of LoopEndBB.
927 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
929 // Any new code will be inserted in AfterBB.
930 Builder.SetInsertPoint(AfterBB);
932 // Restore the unshadowed variable.
934 NamedValues[VarName] = OldVal;
936 NamedValues.erase(VarName);
938 // for expr always returns 0.0.
939 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
942 Value *VarExprAST::Codegen() {
943 std::vector<AllocaInst *> OldBindings;
945 Function *TheFunction = Builder.GetInsertBlock()->getParent();
947 // Register all variables and emit their initializer.
948 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
949 const std::string &VarName = VarNames[i].first;
950 ExprAST *Init = VarNames[i].second.get();
952 // Emit the initializer before adding the variable to scope, this prevents
953 // the initializer from referencing the variable itself, and permits stuff
956 // var a = a in ... # refers to outer 'a'.
959 InitVal = Init->Codegen();
962 } else { // If not specified, use 0.0.
963 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
966 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
967 Builder.CreateStore(InitVal, Alloca);
969 // Remember the old variable binding so that we can restore the binding when
971 OldBindings.push_back(NamedValues[VarName]);
973 // Remember this binding.
974 NamedValues[VarName] = Alloca;
977 // Codegen the body, now that all vars are in scope.
978 Value *BodyVal = Body->Codegen();
982 // Pop all our variables from scope.
983 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
984 NamedValues[VarNames[i].first] = OldBindings[i];
986 // Return the body computation.
990 Function *PrototypeAST::Codegen() {
991 // Make the function type: double(double,double) etc.
992 std::vector<Type *> Doubles(Args.size(),
993 Type::getDoubleTy(getGlobalContext()));
995 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
998 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1000 // If F conflicted, there was already something named 'Name'. If it has a
1001 // body, don't allow redefinition or reextern.
1002 if (F->getName() != Name) {
1003 // Delete the one we just made and get the existing one.
1004 F->eraseFromParent();
1005 F = TheModule->getFunction(Name);
1007 // If F already has a body, reject this.
1009 ErrorF("redefinition of function");
1013 // If F took a different number of args, reject.
1014 if (F->arg_size() != Args.size()) {
1015 ErrorF("redefinition of function with different # args");
1020 // Set names for all arguments.
1022 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1024 AI->setName(Args[Idx]);
1029 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1030 /// argument in the symbol table so that references to it will succeed.
1031 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1032 Function::arg_iterator AI = F->arg_begin();
1033 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1034 // Create an alloca for this variable.
1035 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1037 // Store the initial value into the alloca.
1038 Builder.CreateStore(AI, Alloca);
1040 // Add arguments to variable symbol table.
1041 NamedValues[Args[Idx]] = Alloca;
1045 Function *FunctionAST::Codegen() {
1046 NamedValues.clear();
1048 Function *TheFunction = Proto->Codegen();
1052 // If this is an operator, install it.
1053 if (Proto->isBinaryOp())
1054 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1056 // Create a new basic block to start insertion into.
1057 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1058 Builder.SetInsertPoint(BB);
1060 // Add all arguments to the symbol table and create their allocas.
1061 Proto->CreateArgumentAllocas(TheFunction);
1063 if (Value *RetVal = Body->Codegen()) {
1064 // Finish off the function.
1065 Builder.CreateRet(RetVal);
1067 // Validate the generated code, checking for consistency.
1068 verifyFunction(*TheFunction);
1070 // Optimize the function.
1071 TheFPM->run(*TheFunction);
1076 // Error reading body, remove function.
1077 TheFunction->eraseFromParent();
1079 if (Proto->isBinaryOp())
1080 BinopPrecedence.erase(Proto->getOperatorName());
1084 //===----------------------------------------------------------------------===//
1085 // Top-Level parsing and JIT Driver
1086 //===----------------------------------------------------------------------===//
1088 static ExecutionEngine *TheExecutionEngine;
1090 static void HandleDefinition() {
1091 if (auto FnAST = ParseDefinition()) {
1092 if (auto *FnIR = FnAST->Codegen()) {
1093 fprintf(stderr, "Read function definition:");
1097 // Skip token for error recovery.
1102 static void HandleExtern() {
1103 if (auto ProtoAST = ParseExtern()) {
1104 if (auto *FnIR = ProtoAST->Codegen()) {
1105 fprintf(stderr, "Read extern: ");
1109 // Skip token for error recovery.
1114 static void HandleTopLevelExpression() {
1115 // Evaluate a top-level expression into an anonymous function.
1116 if (auto FnAST = ParseTopLevelExpr()) {
1117 if (auto *FnIR = FnAST->Codegen()) {
1118 TheExecutionEngine->finalizeObject();
1119 // JIT the function, returning a function pointer.
1120 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
1122 // Cast it to the right type (takes no arguments, returns a double) so we
1123 // can call it as a native function.
1124 double (*FP)() = (double (*)())(intptr_t)FPtr;
1125 fprintf(stderr, "Evaluated to %f\n", FP());
1128 // Skip token for error recovery.
1133 /// top ::= definition | external | expression | ';'
1134 static void MainLoop() {
1136 fprintf(stderr, "ready> ");
1142 break; // ignore top-level semicolons.
1150 HandleTopLevelExpression();
1156 //===----------------------------------------------------------------------===//
1157 // "Library" functions that can be "extern'd" from user code.
1158 //===----------------------------------------------------------------------===//
1160 /// putchard - putchar that takes a double and returns 0.
1161 extern "C" double putchard(double X) {
1166 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1167 extern "C" double printd(double X) {
1172 //===----------------------------------------------------------------------===//
1173 // Main driver code.
1174 //===----------------------------------------------------------------------===//
1177 InitializeNativeTarget();
1178 InitializeNativeTargetAsmPrinter();
1179 InitializeNativeTargetAsmParser();
1180 LLVMContext &Context = getGlobalContext();
1182 // Install standard binary operators.
1183 // 1 is lowest precedence.
1184 BinopPrecedence['='] = 2;
1185 BinopPrecedence['<'] = 10;
1186 BinopPrecedence['+'] = 20;
1187 BinopPrecedence['-'] = 20;
1188 BinopPrecedence['*'] = 40; // highest.
1190 // Prime the first token.
1191 fprintf(stderr, "ready> ");
1194 // Make the module, which holds all the code.
1195 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1196 TheModule = Owner.get();
1198 // Create the JIT. This takes ownership of the module.
1200 TheExecutionEngine =
1201 EngineBuilder(std::move(Owner))
1202 .setErrorStr(&ErrStr)
1203 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1205 if (!TheExecutionEngine) {
1206 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1210 legacy::FunctionPassManager OurFPM(TheModule);
1212 // Set up the optimizer pipeline. Start with registering info about how the
1213 // target lays out data structures.
1214 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1215 // Provide basic AliasAnalysis support for GVN.
1216 OurFPM.add(createBasicAliasAnalysisPass());
1217 // Promote allocas to registers.
1218 OurFPM.add(createPromoteMemoryToRegisterPass());
1219 // Do simple "peephole" optimizations and bit-twiddling optzns.
1220 OurFPM.add(createInstructionCombiningPass());
1221 // Reassociate expressions.
1222 OurFPM.add(createReassociatePass());
1223 // Eliminate Common SubExpressions.
1224 OurFPM.add(createGVNPass());
1225 // Simplify the control flow graph (deleting unreachable blocks, etc).
1226 OurFPM.add(createCFGSimplificationPass());
1228 OurFPM.doInitialization();
1230 // Set the global so the code gen can use this.
1233 // Run the main "interpreter loop" now.
1238 // Print out all of the generated code.