1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/MCJIT.h"
4 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/IR/Verifier.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Support/TargetSelect.h"
13 #include "llvm/Transforms/Scalar.h"
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 virtual Value *Codegen();
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 virtual Value *Codegen();
153 /// UnaryExprAST - Expression class for a unary operator.
154 class UnaryExprAST : public ExprAST {
159 UnaryExprAST(char opcode, ExprAST *operand)
160 : Opcode(opcode), Operand(operand) {}
161 virtual Value *Codegen();
164 /// BinaryExprAST - Expression class for a binary operator.
165 class BinaryExprAST : public ExprAST {
170 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
171 : Op(op), LHS(lhs), RHS(rhs) {}
172 virtual Value *Codegen();
175 /// CallExprAST - Expression class for function calls.
176 class CallExprAST : public ExprAST {
178 std::vector<ExprAST *> Args;
181 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
182 : Callee(callee), Args(args) {}
183 virtual Value *Codegen();
186 /// IfExprAST - Expression class for if/then/else.
187 class IfExprAST : public ExprAST {
188 ExprAST *Cond, *Then, *Else;
191 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
192 : Cond(cond), Then(then), Else(_else) {}
193 virtual Value *Codegen();
196 /// ForExprAST - Expression class for for/in.
197 class ForExprAST : public ExprAST {
199 ExprAST *Start, *End, *Step, *Body;
202 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
203 ExprAST *step, ExprAST *body)
204 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
205 virtual Value *Codegen();
208 /// VarExprAST - Expression class for var/in
209 class VarExprAST : public ExprAST {
210 std::vector<std::pair<std::string, ExprAST *> > VarNames;
214 VarExprAST(const std::vector<std::pair<std::string, ExprAST *> > &varnames,
216 : VarNames(varnames), Body(body) {}
218 virtual Value *Codegen();
221 /// PrototypeAST - This class represents the "prototype" for a function,
222 /// which captures its argument names as well as if it is an operator.
225 std::vector<std::string> Args;
227 unsigned Precedence; // Precedence if a binary op.
229 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
230 bool isoperator = false, unsigned prec = 0)
231 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
233 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
234 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
236 char getOperatorName() const {
237 assert(isUnaryOp() || isBinaryOp());
238 return Name[Name.size() - 1];
241 unsigned getBinaryPrecedence() const { return Precedence; }
245 void CreateArgumentAllocas(Function *F);
248 /// FunctionAST - This class represents a function definition itself.
254 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
258 } // end anonymous namespace
260 //===----------------------------------------------------------------------===//
262 //===----------------------------------------------------------------------===//
264 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
265 /// token the parser is looking at. getNextToken reads another token from the
266 /// lexer and updates CurTok with its results.
268 static int getNextToken() { return CurTok = gettok(); }
270 /// BinopPrecedence - This holds the precedence for each binary operator that is
272 static std::map<char, int> BinopPrecedence;
274 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
275 static int GetTokPrecedence() {
276 if (!isascii(CurTok))
279 // Make sure it's a declared binop.
280 int TokPrec = BinopPrecedence[CurTok];
286 /// Error* - These are little helper functions for error handling.
287 ExprAST *Error(const char *Str) {
288 fprintf(stderr, "Error: %s\n", Str);
291 PrototypeAST *ErrorP(const char *Str) {
295 FunctionAST *ErrorF(const char *Str) {
300 static ExprAST *ParseExpression();
304 /// ::= identifier '(' expression* ')'
305 static ExprAST *ParseIdentifierExpr() {
306 std::string IdName = IdentifierStr;
308 getNextToken(); // eat identifier.
310 if (CurTok != '(') // Simple variable ref.
311 return new VariableExprAST(IdName);
314 getNextToken(); // eat (
315 std::vector<ExprAST *> Args;
318 ExprAST *Arg = ParseExpression();
327 return Error("Expected ')' or ',' in argument list");
335 return new CallExprAST(IdName, Args);
338 /// numberexpr ::= number
339 static ExprAST *ParseNumberExpr() {
340 ExprAST *Result = new NumberExprAST(NumVal);
341 getNextToken(); // consume the number
345 /// parenexpr ::= '(' expression ')'
346 static ExprAST *ParseParenExpr() {
347 getNextToken(); // eat (.
348 ExprAST *V = ParseExpression();
353 return Error("expected ')'");
354 getNextToken(); // eat ).
358 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
359 static ExprAST *ParseIfExpr() {
360 getNextToken(); // eat the if.
363 ExprAST *Cond = ParseExpression();
367 if (CurTok != tok_then)
368 return Error("expected then");
369 getNextToken(); // eat the then
371 ExprAST *Then = ParseExpression();
375 if (CurTok != tok_else)
376 return Error("expected else");
380 ExprAST *Else = ParseExpression();
384 return new IfExprAST(Cond, Then, Else);
387 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
388 static ExprAST *ParseForExpr() {
389 getNextToken(); // eat the for.
391 if (CurTok != tok_identifier)
392 return Error("expected identifier after for");
394 std::string IdName = IdentifierStr;
395 getNextToken(); // eat identifier.
398 return Error("expected '=' after for");
399 getNextToken(); // eat '='.
401 ExprAST *Start = ParseExpression();
405 return Error("expected ',' after for start value");
408 ExprAST *End = ParseExpression();
412 // The step value is optional.
416 Step = ParseExpression();
421 if (CurTok != tok_in)
422 return Error("expected 'in' after for");
423 getNextToken(); // eat 'in'.
425 ExprAST *Body = ParseExpression();
429 return new ForExprAST(IdName, Start, End, Step, Body);
432 /// varexpr ::= 'var' identifier ('=' expression)?
433 // (',' identifier ('=' expression)?)* 'in' expression
434 static ExprAST *ParseVarExpr() {
435 getNextToken(); // eat the var.
437 std::vector<std::pair<std::string, 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.
450 getNextToken(); // eat the '='.
452 Init = ParseExpression();
457 VarNames.push_back(std::make_pair(Name, 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 ExprAST *Body = ParseExpression();
477 return new VarExprAST(VarNames, Body);
481 /// ::= identifierexpr
487 static 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 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 (ExprAST *Operand = ParseUnary())
518 return new UnaryExprAST(Opc, Operand);
524 static ExprAST *ParseBinOpRHS(int ExprPrec, 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 ExprAST *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, RHS);
553 LHS = new BinaryExprAST(BinOp, LHS, RHS);
558 /// ::= unary binoprhs
560 static ExprAST *ParseExpression() {
561 ExprAST *LHS = ParseUnary();
565 return ParseBinOpRHS(0, LHS);
569 /// ::= id '(' id* ')'
570 /// ::= binary LETTER number? (id, id)
571 /// ::= unary LETTER (id)
572 static 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 new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
633 /// definition ::= 'def' prototype expression
634 static FunctionAST *ParseDefinition() {
635 getNextToken(); // eat def.
636 PrototypeAST *Proto = ParsePrototype();
640 if (ExprAST *E = ParseExpression())
641 return new FunctionAST(Proto, E);
645 /// toplevelexpr ::= expression
646 static FunctionAST *ParseTopLevelExpr() {
647 if (ExprAST *E = ParseExpression()) {
648 // Make an anonymous proto.
649 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
650 return new FunctionAST(Proto, E);
655 /// external ::= 'extern' prototype
656 static PrototypeAST *ParseExtern() {
657 getNextToken(); // eat extern.
658 return ParsePrototype();
661 //===----------------------------------------------------------------------===//
663 //===----------------------------------------------------------------------===//
665 static Module *TheModule;
666 static IRBuilder<> Builder(getGlobalContext());
667 static std::map<std::string, AllocaInst *> NamedValues;
668 static FunctionPassManager *TheFPM;
670 Value *ErrorV(const char *Str) {
675 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
676 /// the function. This is used for mutable variables etc.
677 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
678 const std::string &VarName) {
679 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
680 TheFunction->getEntryBlock().begin());
681 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
685 Value *NumberExprAST::Codegen() {
686 return ConstantFP::get(getGlobalContext(), APFloat(Val));
689 Value *VariableExprAST::Codegen() {
690 // Look this variable up in the function.
691 Value *V = NamedValues[Name];
693 return ErrorV("Unknown variable name");
696 return Builder.CreateLoad(V, Name.c_str());
699 Value *UnaryExprAST::Codegen() {
700 Value *OperandV = Operand->Codegen();
704 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
706 return ErrorV("Unknown unary operator");
708 return Builder.CreateCall(F, OperandV, "unop");
711 Value *BinaryExprAST::Codegen() {
712 // Special case '=' because we don't want to emit the LHS as an expression.
714 // Assignment requires the LHS to be an identifier.
715 VariableExprAST *LHSE = dynamic_cast<VariableExprAST *>(LHS);
717 return ErrorV("destination of '=' must be a variable");
719 Value *Val = RHS->Codegen();
724 Value *Variable = NamedValues[LHSE->getName()];
726 return ErrorV("Unknown variable name");
728 Builder.CreateStore(Val, Variable);
732 Value *L = LHS->Codegen();
733 Value *R = RHS->Codegen();
734 if (L == 0 || R == 0)
739 return Builder.CreateFAdd(L, R, "addtmp");
741 return Builder.CreateFSub(L, R, "subtmp");
743 return Builder.CreateFMul(L, R, "multmp");
745 L = Builder.CreateFCmpULT(L, R, "cmptmp");
746 // Convert bool 0/1 to double 0.0 or 1.0
747 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
753 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
755 Function *F = TheModule->getFunction(std::string("binary") + Op);
756 assert(F && "binary operator not found!");
758 Value *Ops[] = { L, R };
759 return Builder.CreateCall(F, Ops, "binop");
762 Value *CallExprAST::Codegen() {
763 // Look up the name in the global module table.
764 Function *CalleeF = TheModule->getFunction(Callee);
766 return ErrorV("Unknown function referenced");
768 // If argument mismatch error.
769 if (CalleeF->arg_size() != Args.size())
770 return ErrorV("Incorrect # arguments passed");
772 std::vector<Value *> ArgsV;
773 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
774 ArgsV.push_back(Args[i]->Codegen());
775 if (ArgsV.back() == 0)
779 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
782 Value *IfExprAST::Codegen() {
783 Value *CondV = Cond->Codegen();
787 // Convert condition to a bool by comparing equal to 0.0.
788 CondV = Builder.CreateFCmpONE(
789 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
791 Function *TheFunction = Builder.GetInsertBlock()->getParent();
793 // Create blocks for the then and else cases. Insert the 'then' block at the
794 // end of the function.
796 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
797 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
798 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
800 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
803 Builder.SetInsertPoint(ThenBB);
805 Value *ThenV = Then->Codegen();
809 Builder.CreateBr(MergeBB);
810 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
811 ThenBB = Builder.GetInsertBlock();
814 TheFunction->getBasicBlockList().push_back(ElseBB);
815 Builder.SetInsertPoint(ElseBB);
817 Value *ElseV = Else->Codegen();
821 Builder.CreateBr(MergeBB);
822 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
823 ElseBB = Builder.GetInsertBlock();
826 TheFunction->getBasicBlockList().push_back(MergeBB);
827 Builder.SetInsertPoint(MergeBB);
829 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
831 PN->addIncoming(ThenV, ThenBB);
832 PN->addIncoming(ElseV, ElseBB);
836 Value *ForExprAST::Codegen() {
838 // var = alloca double
841 // store start -> var
852 // nextvar = curvar + step
853 // store nextvar -> var
854 // br endcond, loop, endloop
857 Function *TheFunction = Builder.GetInsertBlock()->getParent();
859 // Create an alloca for the variable in the entry block.
860 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
862 // Emit the start code first, without 'variable' in scope.
863 Value *StartVal = Start->Codegen();
867 // Store the value into the alloca.
868 Builder.CreateStore(StartVal, Alloca);
870 // Make the new basic block for the loop header, inserting after current
873 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
875 // Insert an explicit fall through from the current block to the LoopBB.
876 Builder.CreateBr(LoopBB);
878 // Start insertion in LoopBB.
879 Builder.SetInsertPoint(LoopBB);
881 // Within the loop, the variable is defined equal to the PHI node. If it
882 // shadows an existing variable, we have to restore it, so save it now.
883 AllocaInst *OldVal = NamedValues[VarName];
884 NamedValues[VarName] = Alloca;
886 // Emit the body of the loop. This, like any other expr, can change the
887 // current BB. Note that we ignore the value computed by the body, but don't
889 if (Body->Codegen() == 0)
892 // Emit the step value.
895 StepVal = Step->Codegen();
899 // If not specified, use 1.0.
900 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
903 // Compute the end condition.
904 Value *EndCond = End->Codegen();
908 // Reload, increment, and restore the alloca. This handles the case where
909 // the body of the loop mutates the variable.
910 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
911 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
912 Builder.CreateStore(NextVar, Alloca);
914 // Convert condition to a bool by comparing equal to 0.0.
915 EndCond = Builder.CreateFCmpONE(
916 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
918 // Create the "after loop" block and insert it.
919 BasicBlock *AfterBB =
920 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
922 // Insert the conditional branch into the end of LoopEndBB.
923 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
925 // Any new code will be inserted in AfterBB.
926 Builder.SetInsertPoint(AfterBB);
928 // Restore the unshadowed variable.
930 NamedValues[VarName] = OldVal;
932 NamedValues.erase(VarName);
934 // for expr always returns 0.0.
935 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
938 Value *VarExprAST::Codegen() {
939 std::vector<AllocaInst *> OldBindings;
941 Function *TheFunction = Builder.GetInsertBlock()->getParent();
943 // Register all variables and emit their initializer.
944 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
945 const std::string &VarName = VarNames[i].first;
946 ExprAST *Init = VarNames[i].second;
948 // Emit the initializer before adding the variable to scope, this prevents
949 // the initializer from referencing the variable itself, and permits stuff
952 // var a = a in ... # refers to outer 'a'.
955 InitVal = Init->Codegen();
958 } else { // If not specified, use 0.0.
959 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
962 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
963 Builder.CreateStore(InitVal, Alloca);
965 // Remember the old variable binding so that we can restore the binding when
967 OldBindings.push_back(NamedValues[VarName]);
969 // Remember this binding.
970 NamedValues[VarName] = Alloca;
973 // Codegen the body, now that all vars are in scope.
974 Value *BodyVal = Body->Codegen();
978 // Pop all our variables from scope.
979 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
980 NamedValues[VarNames[i].first] = OldBindings[i];
982 // Return the body computation.
986 Function *PrototypeAST::Codegen() {
987 // Make the function type: double(double,double) etc.
988 std::vector<Type *> Doubles(Args.size(),
989 Type::getDoubleTy(getGlobalContext()));
991 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
994 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
996 // If F conflicted, there was already something named 'Name'. If it has a
997 // body, don't allow redefinition or reextern.
998 if (F->getName() != Name) {
999 // Delete the one we just made and get the existing one.
1000 F->eraseFromParent();
1001 F = TheModule->getFunction(Name);
1003 // If F already has a body, reject this.
1005 ErrorF("redefinition of function");
1009 // If F took a different number of args, reject.
1010 if (F->arg_size() != Args.size()) {
1011 ErrorF("redefinition of function with different # args");
1016 // Set names for all arguments.
1018 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
1020 AI->setName(Args[Idx]);
1025 /// CreateArgumentAllocas - Create an alloca for each argument and register the
1026 /// argument in the symbol table so that references to it will succeed.
1027 void PrototypeAST::CreateArgumentAllocas(Function *F) {
1028 Function::arg_iterator AI = F->arg_begin();
1029 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
1030 // Create an alloca for this variable.
1031 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
1033 // Store the initial value into the alloca.
1034 Builder.CreateStore(AI, Alloca);
1036 // Add arguments to variable symbol table.
1037 NamedValues[Args[Idx]] = Alloca;
1041 Function *FunctionAST::Codegen() {
1042 NamedValues.clear();
1044 Function *TheFunction = Proto->Codegen();
1045 if (TheFunction == 0)
1048 // If this is an operator, install it.
1049 if (Proto->isBinaryOp())
1050 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
1052 // Create a new basic block to start insertion into.
1053 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
1054 Builder.SetInsertPoint(BB);
1056 // Add all arguments to the symbol table and create their allocas.
1057 Proto->CreateArgumentAllocas(TheFunction);
1059 if (Value *RetVal = Body->Codegen()) {
1060 // Finish off the function.
1061 Builder.CreateRet(RetVal);
1063 // Validate the generated code, checking for consistency.
1064 verifyFunction(*TheFunction);
1066 // Optimize the function.
1067 TheFPM->run(*TheFunction);
1072 // Error reading body, remove function.
1073 TheFunction->eraseFromParent();
1075 if (Proto->isBinaryOp())
1076 BinopPrecedence.erase(Proto->getOperatorName());
1080 //===----------------------------------------------------------------------===//
1081 // Top-Level parsing and JIT Driver
1082 //===----------------------------------------------------------------------===//
1084 static ExecutionEngine *TheExecutionEngine;
1086 static void HandleDefinition() {
1087 if (FunctionAST *F = ParseDefinition()) {
1088 if (Function *LF = F->Codegen()) {
1089 fprintf(stderr, "Read function definition:");
1093 // Skip token for error recovery.
1098 static void HandleExtern() {
1099 if (PrototypeAST *P = ParseExtern()) {
1100 if (Function *F = P->Codegen()) {
1101 fprintf(stderr, "Read extern: ");
1105 // Skip token for error recovery.
1110 static void HandleTopLevelExpression() {
1111 // Evaluate a top-level expression into an anonymous function.
1112 if (FunctionAST *F = ParseTopLevelExpr()) {
1113 if (Function *LF = F->Codegen()) {
1114 TheExecutionEngine->finalizeObject();
1115 // JIT the function, returning a function pointer.
1116 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1118 // Cast it to the right type (takes no arguments, returns a double) so we
1119 // can call it as a native function.
1120 double (*FP)() = (double (*)())(intptr_t)FPtr;
1121 fprintf(stderr, "Evaluated to %f\n", FP());
1124 // Skip token for error recovery.
1129 /// top ::= definition | external | expression | ';'
1130 static void MainLoop() {
1132 fprintf(stderr, "ready> ");
1138 break; // ignore top-level semicolons.
1146 HandleTopLevelExpression();
1152 //===----------------------------------------------------------------------===//
1153 // "Library" functions that can be "extern'd" from user code.
1154 //===----------------------------------------------------------------------===//
1156 /// putchard - putchar that takes a double and returns 0.
1157 extern "C" double putchard(double X) {
1162 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1163 extern "C" double printd(double X) {
1168 //===----------------------------------------------------------------------===//
1169 // Main driver code.
1170 //===----------------------------------------------------------------------===//
1173 InitializeNativeTarget();
1174 InitializeNativeTargetAsmPrinter();
1175 InitializeNativeTargetAsmParser();
1176 LLVMContext &Context = getGlobalContext();
1178 // Install standard binary operators.
1179 // 1 is lowest precedence.
1180 BinopPrecedence['='] = 2;
1181 BinopPrecedence['<'] = 10;
1182 BinopPrecedence['+'] = 20;
1183 BinopPrecedence['-'] = 20;
1184 BinopPrecedence['*'] = 40; // highest.
1186 // Prime the first token.
1187 fprintf(stderr, "ready> ");
1190 // Make the module, which holds all the code.
1191 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1192 TheModule = Owner.get();
1194 // Create the JIT. This takes ownership of the module.
1196 TheExecutionEngine =
1197 EngineBuilder(std::move(Owner))
1198 .setErrorStr(&ErrStr)
1199 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1201 if (!TheExecutionEngine) {
1202 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1206 FunctionPassManager OurFPM(TheModule);
1208 // Set up the optimizer pipeline. Start with registering info about how the
1209 // target lays out data structures.
1210 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1211 OurFPM.add(new DataLayoutPass());
1212 // Provide basic AliasAnalysis support for GVN.
1213 OurFPM.add(createBasicAliasAnalysisPass());
1214 // Promote allocas to registers.
1215 OurFPM.add(createPromoteMemoryToRegisterPass());
1216 // Do simple "peephole" optimizations and bit-twiddling optzns.
1217 OurFPM.add(createInstructionCombiningPass());
1218 // Reassociate expressions.
1219 OurFPM.add(createReassociatePass());
1220 // Eliminate Common SubExpressions.
1221 OurFPM.add(createGVNPass());
1222 // Simplify the control flow graph (deleting unreachable blocks, etc).
1223 OurFPM.add(createCFGSimplificationPass());
1225 OurFPM.doInitialization();
1227 // Set the global so the code gen can use this.
1230 // Run the main "interpreter loop" now.
1235 // Print out all of the generated code.