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 {
161 UnaryExprAST(char opcode, ExprAST *operand)
162 : Opcode(opcode), Operand(operand) {}
163 Value *Codegen() override;
166 /// BinaryExprAST - Expression class for a binary operator.
167 class BinaryExprAST : public ExprAST {
172 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
173 : Op(op), LHS(lhs), RHS(rhs) {}
174 Value *Codegen() override;
177 /// CallExprAST - Expression class for function calls.
178 class CallExprAST : public ExprAST {
180 std::vector<ExprAST *> Args;
183 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
184 : Callee(callee), Args(args) {}
185 Value *Codegen() override;
188 /// IfExprAST - Expression class for if/then/else.
189 class IfExprAST : public ExprAST {
190 ExprAST *Cond, *Then, *Else;
193 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
194 : Cond(cond), Then(then), Else(_else) {}
195 Value *Codegen() override;
198 /// ForExprAST - Expression class for for/in.
199 class ForExprAST : public ExprAST {
201 ExprAST *Start, *End, *Step, *Body;
204 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
205 ExprAST *step, ExprAST *body)
206 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
207 Value *Codegen() override;
210 /// VarExprAST - Expression class for var/in
211 class VarExprAST : public ExprAST {
212 std::vector<std::pair<std::string, ExprAST *> > VarNames;
216 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
218 : VarNames(varnames), Body(body) {}
220 Value *Codegen() override;
223 /// PrototypeAST - This class represents the "prototype" for a function,
224 /// which captures its argument names as well as if it is an operator.
227 std::vector<std::string> Args;
229 unsigned Precedence; // Precedence if a binary op.
231 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
232 bool isoperator = false, unsigned prec = 0)
233 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
235 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
236 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
238 char getOperatorName() const {
239 assert(isUnaryOp() || isBinaryOp());
240 return Name[Name.size() - 1];
243 unsigned getBinaryPrecedence() const { return Precedence; }
247 void CreateArgumentAllocas(Function *F);
250 /// FunctionAST - This class represents a function definition itself.
256 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
260 } // end anonymous namespace
262 //===----------------------------------------------------------------------===//
264 //===----------------------------------------------------------------------===//
266 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
267 /// token the parser is looking at. getNextToken reads another token from the
268 /// lexer and updates CurTok with its results.
270 static int getNextToken() { return CurTok = gettok(); }
272 /// BinopPrecedence - This holds the precedence for each binary operator that is
274 static std::map<char, int> BinopPrecedence;
276 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
277 static int GetTokPrecedence() {
278 if (!isascii(CurTok))
281 // Make sure it's a declared binop.
282 int TokPrec = BinopPrecedence[CurTok];
288 /// Error* - These are little helper functions for error handling.
289 ExprAST *Error(const char *Str) {
290 fprintf(stderr, "Error: %s\n", Str);
293 PrototypeAST *ErrorP(const char *Str) {
297 FunctionAST *ErrorF(const char *Str) {
302 static ExprAST *ParseExpression();
306 /// ::= identifier '(' expression* ')'
307 static ExprAST *ParseIdentifierExpr() {
308 std::string IdName = IdentifierStr;
310 getNextToken(); // eat identifier.
312 if (CurTok != '(') // Simple variable ref.
313 return new VariableExprAST(IdName);
316 getNextToken(); // eat (
317 std::vector<ExprAST *> Args;
320 ExprAST *Arg = ParseExpression();
329 return Error("Expected ')' or ',' in argument list");
337 return new CallExprAST(IdName, Args);
340 /// numberexpr ::= number
341 static ExprAST *ParseNumberExpr() {
342 ExprAST *Result = new NumberExprAST(NumVal);
343 getNextToken(); // consume the number
347 /// parenexpr ::= '(' expression ')'
348 static ExprAST *ParseParenExpr() {
349 getNextToken(); // eat (.
350 ExprAST *V = ParseExpression();
355 return Error("expected ')'");
356 getNextToken(); // eat ).
360 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
361 static ExprAST *ParseIfExpr() {
362 getNextToken(); // eat the if.
365 ExprAST *Cond = ParseExpression();
369 if (CurTok != tok_then)
370 return Error("expected then");
371 getNextToken(); // eat the then
373 ExprAST *Then = ParseExpression();
377 if (CurTok != tok_else)
378 return Error("expected else");
382 ExprAST *Else = ParseExpression();
386 return new IfExprAST(Cond, Then, Else);
389 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
390 static ExprAST *ParseForExpr() {
391 getNextToken(); // eat the for.
393 if (CurTok != tok_identifier)
394 return Error("expected identifier after for");
396 std::string IdName = IdentifierStr;
397 getNextToken(); // eat identifier.
400 return Error("expected '=' after for");
401 getNextToken(); // eat '='.
403 ExprAST *Start = ParseExpression();
407 return Error("expected ',' after for start value");
410 ExprAST *End = ParseExpression();
414 // The step value is optional.
418 Step = ParseExpression();
423 if (CurTok != tok_in)
424 return Error("expected 'in' after for");
425 getNextToken(); // eat 'in'.
427 ExprAST *Body = ParseExpression();
431 return new ForExprAST(IdName, Start, End, Step, Body);
434 /// varexpr ::= 'var' identifier ('=' expression)?
435 // (',' identifier ('=' expression)?)* 'in' expression
436 static ExprAST *ParseVarExpr() {
437 getNextToken(); // eat the var.
439 std::vector<std::pair<std::string, ExprAST *> > VarNames;
441 // At least one variable name is required.
442 if (CurTok != tok_identifier)
443 return Error("expected identifier after var");
446 std::string Name = IdentifierStr;
447 getNextToken(); // eat identifier.
449 // Read the optional initializer.
452 getNextToken(); // eat the '='.
454 Init = ParseExpression();
459 VarNames.push_back(std::make_pair(Name, Init));
461 // End of var list, exit loop.
464 getNextToken(); // eat the ','.
466 if (CurTok != tok_identifier)
467 return Error("expected identifier list after var");
470 // At this point, we have to have 'in'.
471 if (CurTok != tok_in)
472 return Error("expected 'in' keyword after 'var'");
473 getNextToken(); // eat 'in'.
475 ExprAST *Body = ParseExpression();
479 return new VarExprAST(VarNames, Body);
483 /// ::= identifierexpr
489 static ExprAST *ParsePrimary() {
492 return Error("unknown token when expecting an expression");
494 return ParseIdentifierExpr();
496 return ParseNumberExpr();
498 return ParseParenExpr();
500 return ParseIfExpr();
502 return ParseForExpr();
504 return ParseVarExpr();
511 static ExprAST *ParseUnary() {
512 // If the current token is not an operator, it must be a primary expr.
513 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
514 return ParsePrimary();
516 // If this is a unary operator, read it.
519 if (ExprAST *Operand = ParseUnary())
520 return new UnaryExprAST(Opc, Operand);
526 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
527 // If this is a binop, find its precedence.
529 int TokPrec = GetTokPrecedence();
531 // If this is a binop that binds at least as tightly as the current binop,
532 // consume it, otherwise we are done.
533 if (TokPrec < ExprPrec)
536 // Okay, we know this is a binop.
538 getNextToken(); // eat binop
540 // Parse the unary expression after the binary operator.
541 ExprAST *RHS = ParseUnary();
545 // If BinOp binds less tightly with RHS than the operator after RHS, let
546 // the pending operator take RHS as its LHS.
547 int NextPrec = GetTokPrecedence();
548 if (TokPrec < NextPrec) {
549 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
555 LHS = new BinaryExprAST(BinOp, LHS, RHS);
560 /// ::= unary binoprhs
562 static ExprAST *ParseExpression() {
563 ExprAST *LHS = ParseUnary();
567 return ParseBinOpRHS(0, LHS);
571 /// ::= id '(' id* ')'
572 /// ::= binary LETTER number? (id, id)
573 /// ::= unary LETTER (id)
574 static PrototypeAST *ParsePrototype() {
577 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
578 unsigned BinaryPrecedence = 30;
582 return ErrorP("Expected function name in prototype");
584 FnName = IdentifierStr;
590 if (!isascii(CurTok))
591 return ErrorP("Expected unary operator");
593 FnName += (char)CurTok;
599 if (!isascii(CurTok))
600 return ErrorP("Expected binary operator");
602 FnName += (char)CurTok;
606 // Read the precedence if present.
607 if (CurTok == tok_number) {
608 if (NumVal < 1 || NumVal > 100)
609 return ErrorP("Invalid precedecnce: must be 1..100");
610 BinaryPrecedence = (unsigned)NumVal;
617 return ErrorP("Expected '(' in prototype");
619 std::vector<std::string> ArgNames;
620 while (getNextToken() == tok_identifier)
621 ArgNames.push_back(IdentifierStr);
623 return ErrorP("Expected ')' in prototype");
626 getNextToken(); // eat ')'.
628 // Verify right number of names for operator.
629 if (Kind && ArgNames.size() != Kind)
630 return ErrorP("Invalid number of operands for operator");
632 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
635 /// definition ::= 'def' prototype expression
636 static FunctionAST *ParseDefinition() {
637 getNextToken(); // eat def.
638 PrototypeAST *Proto = ParsePrototype();
642 if (ExprAST *E = ParseExpression())
643 return new FunctionAST(Proto, E);
647 /// toplevelexpr ::= expression
648 static FunctionAST *ParseTopLevelExpr() {
649 if (ExprAST *E = ParseExpression()) {
650 // Make an anonymous proto.
651 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
652 return new FunctionAST(Proto, E);
657 /// external ::= 'extern' prototype
658 static PrototypeAST *ParseExtern() {
659 getNextToken(); // eat extern.
660 return ParsePrototype();
663 //===----------------------------------------------------------------------===//
665 //===----------------------------------------------------------------------===//
667 static Module *TheModule;
668 static IRBuilder<> Builder(getGlobalContext());
669 static std::map<std::string, AllocaInst *> NamedValues;
670 static legacy::FunctionPassManager *TheFPM;
672 Value *ErrorV(const char *Str) {
677 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
678 /// the function. This is used for mutable variables etc.
679 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
680 const std::string &VarName) {
681 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
682 TheFunction->getEntryBlock().begin());
683 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
687 Value *NumberExprAST::Codegen() {
688 return ConstantFP::get(getGlobalContext(), APFloat(Val));
691 Value *VariableExprAST::Codegen() {
692 // Look this variable up in the function.
693 Value *V = NamedValues[Name];
695 return ErrorV("Unknown variable name");
698 return Builder.CreateLoad(V, Name.c_str());
701 Value *UnaryExprAST::Codegen() {
702 Value *OperandV = Operand->Codegen();
706 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
708 return ErrorV("Unknown unary operator");
710 return Builder.CreateCall(F, OperandV, "unop");
713 Value *BinaryExprAST::Codegen() {
714 // Special case '=' because we don't want to emit the LHS as an expression.
716 // Assignment requires the LHS to be an identifier.
717 // This assume we're building without RTTI because LLVM builds that way by
718 // default. If you build LLVM with RTTI this can be changed to a
719 // dynamic_cast for automatic error checking.
720 VariableExprAST *LHSE = static_cast<VariableExprAST *>(LHS);
722 return ErrorV("destination of '=' must be a variable");
724 Value *Val = RHS->Codegen();
729 Value *Variable = NamedValues[LHSE->getName()];
731 return ErrorV("Unknown variable name");
733 Builder.CreateStore(Val, Variable);
737 Value *L = LHS->Codegen();
738 Value *R = RHS->Codegen();
739 if (L == 0 || R == 0)
744 return Builder.CreateFAdd(L, R, "addtmp");
746 return Builder.CreateFSub(L, R, "subtmp");
748 return Builder.CreateFMul(L, R, "multmp");
750 L = Builder.CreateFCmpULT(L, R, "cmptmp");
751 // Convert bool 0/1 to double 0.0 or 1.0
752 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
758 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
760 Function *F = TheModule->getFunction(std::string("binary") + Op);
761 assert(F && "binary operator not found!");
763 Value *Ops[] = { L, R };
764 return Builder.CreateCall(F, Ops, "binop");
767 Value *CallExprAST::Codegen() {
768 // Look up the name in the global module table.
769 Function *CalleeF = TheModule->getFunction(Callee);
771 return ErrorV("Unknown function referenced");
773 // If argument mismatch error.
774 if (CalleeF->arg_size() != Args.size())
775 return ErrorV("Incorrect # arguments passed");
777 std::vector<Value *> ArgsV;
778 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
779 ArgsV.push_back(Args[i]->Codegen());
780 if (ArgsV.back() == 0)
784 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
787 Value *IfExprAST::Codegen() {
788 Value *CondV = Cond->Codegen();
792 // Convert condition to a bool by comparing equal to 0.0.
793 CondV = Builder.CreateFCmpONE(
794 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
796 Function *TheFunction = Builder.GetInsertBlock()->getParent();
798 // Create blocks for the then and else cases. Insert the 'then' block at the
799 // end of the function.
801 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
802 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
803 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
805 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
808 Builder.SetInsertPoint(ThenBB);
810 Value *ThenV = Then->Codegen();
814 Builder.CreateBr(MergeBB);
815 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
816 ThenBB = Builder.GetInsertBlock();
819 TheFunction->getBasicBlockList().push_back(ElseBB);
820 Builder.SetInsertPoint(ElseBB);
822 Value *ElseV = Else->Codegen();
826 Builder.CreateBr(MergeBB);
827 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
828 ElseBB = Builder.GetInsertBlock();
831 TheFunction->getBasicBlockList().push_back(MergeBB);
832 Builder.SetInsertPoint(MergeBB);
834 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
836 PN->addIncoming(ThenV, ThenBB);
837 PN->addIncoming(ElseV, ElseBB);
841 Value *ForExprAST::Codegen() {
843 // var = alloca double
846 // store start -> var
857 // nextvar = curvar + step
858 // store nextvar -> var
859 // br endcond, loop, endloop
862 Function *TheFunction = Builder.GetInsertBlock()->getParent();
864 // Create an alloca for the variable in the entry block.
865 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
867 // Emit the start code first, without 'variable' in scope.
868 Value *StartVal = Start->Codegen();
872 // Store the value into the alloca.
873 Builder.CreateStore(StartVal, Alloca);
875 // Make the new basic block for the loop header, inserting after current
878 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
880 // Insert an explicit fall through from the current block to the LoopBB.
881 Builder.CreateBr(LoopBB);
883 // Start insertion in LoopBB.
884 Builder.SetInsertPoint(LoopBB);
886 // Within the loop, the variable is defined equal to the PHI node. If it
887 // shadows an existing variable, we have to restore it, so save it now.
888 AllocaInst *OldVal = NamedValues[VarName];
889 NamedValues[VarName] = Alloca;
891 // Emit the body of the loop. This, like any other expr, can change the
892 // current BB. Note that we ignore the value computed by the body, but don't
894 if (Body->Codegen() == 0)
897 // Emit the step value.
900 StepVal = Step->Codegen();
904 // If not specified, use 1.0.
905 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
908 // Compute the end condition.
909 Value *EndCond = End->Codegen();
913 // Reload, increment, and restore the alloca. This handles the case where
914 // the body of the loop mutates the variable.
915 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
916 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
917 Builder.CreateStore(NextVar, Alloca);
919 // Convert condition to a bool by comparing equal to 0.0.
920 EndCond = Builder.CreateFCmpONE(
921 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
923 // Create the "after loop" block and insert it.
924 BasicBlock *AfterBB =
925 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
927 // Insert the conditional branch into the end of LoopEndBB.
928 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
930 // Any new code will be inserted in AfterBB.
931 Builder.SetInsertPoint(AfterBB);
933 // Restore the unshadowed variable.
935 NamedValues[VarName] = OldVal;
937 NamedValues.erase(VarName);
939 // for expr always returns 0.0.
940 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
943 Value *VarExprAST::Codegen() {
944 std::vector<AllocaInst *> OldBindings;
946 Function *TheFunction = Builder.GetInsertBlock()->getParent();
948 // Register all variables and emit their initializer.
949 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
950 const std::string &VarName = VarNames[i].first;
951 ExprAST *Init = VarNames[i].second;
953 // Emit the initializer before adding the variable to scope, this prevents
954 // the initializer from referencing the variable itself, and permits stuff
957 // var a = a in ... # refers to outer 'a'.
960 InitVal = Init->Codegen();
963 } else { // If not specified, use 0.0.
964 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
967 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
968 Builder.CreateStore(InitVal, Alloca);
970 // Remember the old variable binding so that we can restore the binding when
972 OldBindings.push_back(NamedValues[VarName]);
974 // Remember this binding.
975 NamedValues[VarName] = Alloca;
978 // Codegen the body, now that all vars are in scope.
979 Value *BodyVal = Body->Codegen();
983 // Pop all our variables from scope.
984 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
985 NamedValues[VarNames[i].first] = OldBindings[i];
987 // Return the body computation.
991 Function *PrototypeAST::Codegen() {
992 // Make the function type: double(double,double) etc.
993 std::vector<Type *> Doubles(Args.size(),
994 Type::getDoubleTy(getGlobalContext()));
996 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
999 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
1001 // If F conflicted, there was already something named 'Name'. If it has a
1002 // body, don't allow redefinition or reextern.
1003 if (F->getName() != Name) {
1004 // Delete the one we just made and get the existing one.
1005 F->eraseFromParent();
1006 F = TheModule->getFunction(Name);
1008 // If F already has a body, reject this.
1010 ErrorF("redefinition of function");
1014 // If F took a different number of args, reject.
1015 if (F->arg_size() != Args.size()) {
1016 ErrorF("redefinition of function with different # args");
1021 // Set names for all arguments.
1023 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1025 AI->setName(Args[Idx]);
1030 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1031 /// argument in the symbol table so that references to it will succeed.
1032 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1033 Function::arg_iterator AI = F->arg_begin();
1034 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1035 // Create an alloca for this variable.
1036 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1038 // Store the initial value into the alloca.
1039 Builder.CreateStore(AI, Alloca);
1041 // Add arguments to variable symbol table.
1042 NamedValues[Args[Idx]] = Alloca;
1046 Function *FunctionAST::Codegen() {
1047 NamedValues.clear();
1049 Function *TheFunction = Proto->Codegen();
1050 if (TheFunction == 0)
1053 // If this is an operator, install it.
1054 if (Proto->isBinaryOp())
1055 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1057 // Create a new basic block to start insertion into.
1058 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1059 Builder.SetInsertPoint(BB);
1061 // Add all arguments to the symbol table and create their allocas.
1062 Proto->CreateArgumentAllocas(TheFunction);
1064 if (Value *RetVal = Body->Codegen()) {
1065 // Finish off the function.
1066 Builder.CreateRet(RetVal);
1068 // Validate the generated code, checking for consistency.
1069 verifyFunction(*TheFunction);
1071 // Optimize the function.
1072 TheFPM->run(*TheFunction);
1077 // Error reading body, remove function.
1078 TheFunction->eraseFromParent();
1080 if (Proto->isBinaryOp())
1081 BinopPrecedence.erase(Proto->getOperatorName());
1085 //===----------------------------------------------------------------------===//
1086 // Top-Level parsing and JIT Driver
1087 //===----------------------------------------------------------------------===//
1089 static ExecutionEngine *TheExecutionEngine;
1091 static void HandleDefinition() {
1092 if (FunctionAST *F = ParseDefinition()) {
1093 if (Function *LF = F->Codegen()) {
1094 fprintf(stderr, "Read function definition:");
1098 // Skip token for error recovery.
1103 static void HandleExtern() {
1104 if (PrototypeAST *P = ParseExtern()) {
1105 if (Function *F = P->Codegen()) {
1106 fprintf(stderr, "Read extern: ");
1110 // Skip token for error recovery.
1115 static void HandleTopLevelExpression() {
1116 // Evaluate a top-level expression into an anonymous function.
1117 if (FunctionAST *F = ParseTopLevelExpr()) {
1118 if (Function *LF = F->Codegen()) {
1119 TheExecutionEngine->finalizeObject();
1120 // JIT the function, returning a function pointer.
1121 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1123 // Cast it to the right type (takes no arguments, returns a double) so we
1124 // can call it as a native function.
1125 double (*FP)() = (double (*)())(intptr_t)FPtr;
1126 fprintf(stderr, "Evaluated to %f\n", FP());
1129 // Skip token for error recovery.
1134 /// top ::= definition | external | expression | ';'
1135 static void MainLoop() {
1137 fprintf(stderr, "ready> ");
1143 break; // ignore top-level semicolons.
1151 HandleTopLevelExpression();
1157 //===----------------------------------------------------------------------===//
1158 // "Library" functions that can be "extern'd" from user code.
1159 //===----------------------------------------------------------------------===//
1161 /// putchard - putchar that takes a double and returns 0.
1162 extern "C" double putchard(double X) {
1167 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1168 extern "C" double printd(double X) {
1173 //===----------------------------------------------------------------------===//
1174 // Main driver code.
1175 //===----------------------------------------------------------------------===//
1178 InitializeNativeTarget();
1179 InitializeNativeTargetAsmPrinter();
1180 InitializeNativeTargetAsmParser();
1181 LLVMContext &Context = getGlobalContext();
1183 // Install standard binary operators.
1184 // 1 is lowest precedence.
1185 BinopPrecedence['='] = 2;
1186 BinopPrecedence['<'] = 10;
1187 BinopPrecedence['+'] = 20;
1188 BinopPrecedence['-'] = 20;
1189 BinopPrecedence['*'] = 40; // highest.
1191 // Prime the first token.
1192 fprintf(stderr, "ready> ");
1195 // Make the module, which holds all the code.
1196 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1197 TheModule = Owner.get();
1199 // Create the JIT. This takes ownership of the module.
1201 TheExecutionEngine =
1202 EngineBuilder(std::move(Owner))
1203 .setErrorStr(&ErrStr)
1204 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1206 if (!TheExecutionEngine) {
1207 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1211 legacy::FunctionPassManager OurFPM(TheModule);
1213 // Set up the optimizer pipeline. Start with registering info about how the
1214 // target lays out data structures.
1215 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1216 // Provide basic AliasAnalysis support for GVN.
1217 OurFPM.add(createBasicAliasAnalysisPass());
1218 // Promote allocas to registers.
1219 OurFPM.add(createPromoteMemoryToRegisterPass());
1220 // Do simple "peephole" optimizations and bit-twiddling optzns.
1221 OurFPM.add(createInstructionCombiningPass());
1222 // Reassociate expressions.
1223 OurFPM.add(createReassociatePass());
1224 // Eliminate Common SubExpressions.
1225 OurFPM.add(createGVNPass());
1226 // Simplify the control flow graph (deleting unreachable blocks, etc).
1227 OurFPM.add(createCFGSimplificationPass());
1229 OurFPM.doInitialization();
1231 // Set the global so the code gen can use this.
1234 // Run the main "interpreter loop" now.
1239 // Print out all of the generated code.