1 #define MINIMAL_STDERR_OUTPUT
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/Analysis/Verifier.h"
5 #include "llvm/ExecutionEngine/ExecutionEngine.h"
6 #include "llvm/ExecutionEngine/JIT.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/Module.h"
12 #include "llvm/IRReader/IRReader.h"
13 #include "llvm/PassManager.h"
14 #include "llvm/Support/CommandLine.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include "llvm/Support/SourceMgr.h"
17 #include "llvm/Support/TargetSelect.h"
18 #include "llvm/Transforms/Scalar.h"
27 //===----------------------------------------------------------------------===//
28 // Command-line options
29 //===----------------------------------------------------------------------===//
34 cl::desc("Specify the name of an IR file to load for function definitions"),
35 cl::value_desc("input IR file name"));
38 //===----------------------------------------------------------------------===//
40 //===----------------------------------------------------------------------===//
42 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
43 // of these for known things.
48 tok_def = -2, tok_extern = -3,
51 tok_identifier = -4, tok_number = -5,
54 tok_if = -6, tok_then = -7, tok_else = -8,
55 tok_for = -9, tok_in = -10,
58 tok_binary = -11, tok_unary = -12,
64 static std::string IdentifierStr; // Filled in if tok_identifier
65 static double NumVal; // Filled in if tok_number
67 /// gettok - Return the next token from standard input.
69 static int LastChar = ' ';
71 // Skip any whitespace.
72 while (isspace(LastChar))
75 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
76 IdentifierStr = LastChar;
77 while (isalnum((LastChar = getchar())))
78 IdentifierStr += LastChar;
80 if (IdentifierStr == "def") return tok_def;
81 if (IdentifierStr == "extern") return tok_extern;
82 if (IdentifierStr == "if") return tok_if;
83 if (IdentifierStr == "then") return tok_then;
84 if (IdentifierStr == "else") return tok_else;
85 if (IdentifierStr == "for") return tok_for;
86 if (IdentifierStr == "in") return tok_in;
87 if (IdentifierStr == "binary") return tok_binary;
88 if (IdentifierStr == "unary") return tok_unary;
89 if (IdentifierStr == "var") return tok_var;
90 return tok_identifier;
93 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
98 } while (isdigit(LastChar) || LastChar == '.');
100 NumVal = strtod(NumStr.c_str(), 0);
104 if (LastChar == '#') {
105 // Comment until end of line.
106 do 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 {
138 NumberExprAST(double val) : Val(val) {}
139 virtual Value *Codegen();
142 /// VariableExprAST - Expression class for referencing a variable, like "a".
143 class VariableExprAST : public ExprAST {
146 VariableExprAST(const std::string &name) : Name(name) {}
147 const std::string &getName() const { return Name; }
148 virtual Value *Codegen();
151 /// UnaryExprAST - Expression class for a unary operator.
152 class UnaryExprAST : public ExprAST {
156 UnaryExprAST(char opcode, ExprAST *operand)
157 : Opcode(opcode), Operand(operand) {}
158 virtual Value *Codegen();
161 /// BinaryExprAST - Expression class for a binary operator.
162 class BinaryExprAST : public ExprAST {
166 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
167 : Op(op), LHS(lhs), RHS(rhs) {}
168 virtual Value *Codegen();
171 /// CallExprAST - Expression class for function calls.
172 class CallExprAST : public ExprAST {
174 std::vector<ExprAST*> Args;
176 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
177 : Callee(callee), Args(args) {}
178 virtual Value *Codegen();
181 /// IfExprAST - Expression class for if/then/else.
182 class IfExprAST : public ExprAST {
183 ExprAST *Cond, *Then, *Else;
185 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
186 : Cond(cond), Then(then), Else(_else) {}
187 virtual Value *Codegen();
190 /// ForExprAST - Expression class for for/in.
191 class ForExprAST : public ExprAST {
193 ExprAST *Start, *End, *Step, *Body;
195 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
196 ExprAST *step, ExprAST *body)
197 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
198 virtual Value *Codegen();
201 /// VarExprAST - Expression class for var/in
202 class VarExprAST : public ExprAST {
203 std::vector<std::pair<std::string, ExprAST*> > VarNames;
206 VarExprAST(const std::vector<std::pair<std::string, ExprAST*> > &varnames,
208 : VarNames(varnames), Body(body) {}
210 virtual Value *Codegen();
213 /// PrototypeAST - This class represents the "prototype" for a function,
214 /// which captures its argument names as well as if it is an operator.
217 std::vector<std::string> Args;
219 unsigned Precedence; // Precedence if a binary op.
221 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
222 bool isoperator = false, unsigned prec = 0)
223 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
225 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
226 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
228 char getOperatorName() const {
229 assert(isUnaryOp() || isBinaryOp());
230 return Name[Name.size()-1];
233 unsigned getBinaryPrecedence() const { return Precedence; }
237 void CreateArgumentAllocas(Function *F);
240 /// FunctionAST - This class represents a function definition itself.
245 FunctionAST(PrototypeAST *proto, ExprAST *body)
246 : Proto(proto), Body(body) {}
251 //===----------------------------------------------------------------------===//
253 //===----------------------------------------------------------------------===//
255 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
256 /// token the parser is looking at. getNextToken reads another token from the
257 /// lexer and updates CurTok with its results.
259 static int getNextToken() {
260 return CurTok = gettok();
263 /// BinopPrecedence - This holds the precedence for each binary operator that is
265 static std::map<char, int> BinopPrecedence;
267 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
268 static int GetTokPrecedence() {
269 if (!isascii(CurTok))
272 // Make sure it's a declared binop.
273 int TokPrec = BinopPrecedence[CurTok];
274 if (TokPrec <= 0) return -1;
278 /// Error* - These are little helper functions for error handling.
279 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
280 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
281 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
283 static ExprAST *ParseExpression();
287 /// ::= identifier '(' expression* ')'
288 static ExprAST *ParseIdentifierExpr() {
289 std::string IdName = IdentifierStr;
291 getNextToken(); // eat identifier.
293 if (CurTok != '(') // Simple variable ref.
294 return new VariableExprAST(IdName);
297 getNextToken(); // eat (
298 std::vector<ExprAST*> Args;
301 ExprAST *Arg = ParseExpression();
305 if (CurTok == ')') break;
308 return Error("Expected ')' or ',' in argument list");
316 return new CallExprAST(IdName, Args);
319 /// numberexpr ::= number
320 static ExprAST *ParseNumberExpr() {
321 ExprAST *Result = new NumberExprAST(NumVal);
322 getNextToken(); // consume the number
326 /// parenexpr ::= '(' expression ')'
327 static ExprAST *ParseParenExpr() {
328 getNextToken(); // eat (.
329 ExprAST *V = ParseExpression();
333 return Error("expected ')'");
334 getNextToken(); // eat ).
338 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
339 static ExprAST *ParseIfExpr() {
340 getNextToken(); // eat the if.
343 ExprAST *Cond = ParseExpression();
346 if (CurTok != tok_then)
347 return Error("expected then");
348 getNextToken(); // eat the then
350 ExprAST *Then = ParseExpression();
351 if (Then == 0) return 0;
353 if (CurTok != tok_else)
354 return Error("expected else");
358 ExprAST *Else = ParseExpression();
361 return new IfExprAST(Cond, Then, Else);
364 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
365 static ExprAST *ParseForExpr() {
366 getNextToken(); // eat the for.
368 if (CurTok != tok_identifier)
369 return Error("expected identifier after for");
371 std::string IdName = IdentifierStr;
372 getNextToken(); // eat identifier.
375 return Error("expected '=' after for");
376 getNextToken(); // eat '='.
379 ExprAST *Start = ParseExpression();
380 if (Start == 0) return 0;
382 return Error("expected ',' after for start value");
385 ExprAST *End = ParseExpression();
386 if (End == 0) return 0;
388 // The step value is optional.
392 Step = ParseExpression();
393 if (Step == 0) return 0;
396 if (CurTok != tok_in)
397 return Error("expected 'in' after for");
398 getNextToken(); // eat 'in'.
400 ExprAST *Body = ParseExpression();
401 if (Body == 0) return 0;
403 return new ForExprAST(IdName, Start, End, Step, Body);
406 /// varexpr ::= 'var' identifier ('=' expression)?
407 // (',' identifier ('=' expression)?)* 'in' expression
408 static ExprAST *ParseVarExpr() {
409 getNextToken(); // eat the var.
411 std::vector<std::pair<std::string, ExprAST*> > VarNames;
413 // At least one variable name is required.
414 if (CurTok != tok_identifier)
415 return Error("expected identifier after var");
418 std::string Name = IdentifierStr;
419 getNextToken(); // eat identifier.
421 // Read the optional initializer.
424 getNextToken(); // eat the '='.
426 Init = ParseExpression();
427 if (Init == 0) return 0;
430 VarNames.push_back(std::make_pair(Name, Init));
432 // End of var list, exit loop.
433 if (CurTok != ',') break;
434 getNextToken(); // eat the ','.
436 if (CurTok != tok_identifier)
437 return Error("expected identifier list after var");
440 // At this point, we have to have 'in'.
441 if (CurTok != tok_in)
442 return Error("expected 'in' keyword after 'var'");
443 getNextToken(); // eat 'in'.
445 ExprAST *Body = ParseExpression();
446 if (Body == 0) return 0;
448 return new VarExprAST(VarNames, Body);
452 /// ::= identifierexpr
458 static ExprAST *ParsePrimary() {
460 default: return Error("unknown token when expecting an expression");
461 case tok_identifier: return ParseIdentifierExpr();
462 case tok_number: return ParseNumberExpr();
463 case '(': return ParseParenExpr();
464 case tok_if: return ParseIfExpr();
465 case tok_for: return ParseForExpr();
466 case tok_var: return ParseVarExpr();
473 static ExprAST *ParseUnary() {
474 // If the current token is not an operator, it must be a primary expr.
475 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
476 return ParsePrimary();
478 // If this is a unary operator, read it.
481 if (ExprAST *Operand = ParseUnary())
482 return new UnaryExprAST(Opc, Operand);
488 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
489 // If this is a binop, find its precedence.
491 int TokPrec = GetTokPrecedence();
493 // If this is a binop that binds at least as tightly as the current binop,
494 // consume it, otherwise we are done.
495 if (TokPrec < ExprPrec)
498 // Okay, we know this is a binop.
500 getNextToken(); // eat binop
502 // Parse the unary expression after the binary operator.
503 ExprAST *RHS = ParseUnary();
506 // If BinOp binds less tightly with RHS than the operator after RHS, let
507 // the pending operator take RHS as its LHS.
508 int NextPrec = GetTokPrecedence();
509 if (TokPrec < NextPrec) {
510 RHS = ParseBinOpRHS(TokPrec+1, RHS);
511 if (RHS == 0) return 0;
515 LHS = new BinaryExprAST(BinOp, LHS, RHS);
520 /// ::= unary binoprhs
522 static ExprAST *ParseExpression() {
523 ExprAST *LHS = ParseUnary();
526 return ParseBinOpRHS(0, LHS);
530 /// ::= id '(' id* ')'
531 /// ::= binary LETTER number? (id, id)
532 /// ::= unary LETTER (id)
533 static PrototypeAST *ParsePrototype() {
536 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
537 unsigned BinaryPrecedence = 30;
541 return ErrorP("Expected function name in prototype");
543 FnName = IdentifierStr;
549 if (!isascii(CurTok))
550 return ErrorP("Expected unary operator");
552 FnName += (char)CurTok;
558 if (!isascii(CurTok))
559 return ErrorP("Expected binary operator");
561 FnName += (char)CurTok;
565 // Read the precedence if present.
566 if (CurTok == tok_number) {
567 if (NumVal < 1 || NumVal > 100)
568 return ErrorP("Invalid precedecnce: must be 1..100");
569 BinaryPrecedence = (unsigned)NumVal;
576 return ErrorP("Expected '(' in prototype");
578 std::vector<std::string> ArgNames;
579 while (getNextToken() == tok_identifier)
580 ArgNames.push_back(IdentifierStr);
582 return ErrorP("Expected ')' in prototype");
585 getNextToken(); // eat ')'.
587 // Verify right number of names for operator.
588 if (Kind && ArgNames.size() != Kind)
589 return ErrorP("Invalid number of operands for operator");
591 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
594 /// definition ::= 'def' prototype expression
595 static FunctionAST *ParseDefinition() {
596 getNextToken(); // eat def.
597 PrototypeAST *Proto = ParsePrototype();
598 if (Proto == 0) return 0;
600 if (ExprAST *E = ParseExpression())
601 return new FunctionAST(Proto, E);
605 /// toplevelexpr ::= expression
606 static FunctionAST *ParseTopLevelExpr() {
607 if (ExprAST *E = ParseExpression()) {
608 // Make an anonymous proto.
609 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
610 return new FunctionAST(Proto, E);
615 /// external ::= 'extern' prototype
616 static PrototypeAST *ParseExtern() {
617 getNextToken(); // eat extern.
618 return ParsePrototype();
621 //===----------------------------------------------------------------------===//
623 //===----------------------------------------------------------------------===//
625 static Module *TheModule;
626 static FunctionPassManager *TheFPM;
627 static IRBuilder<> Builder(getGlobalContext());
628 static std::map<std::string, AllocaInst*> NamedValues;
630 Value *ErrorV(const char *Str) { Error(Str); return 0; }
632 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
633 /// the function. This is used for mutable variables etc.
634 static AllocaInst *CreateEntryBlockAlloca(Function *TheFunction,
635 const std::string &VarName) {
636 IRBuilder<> TmpB(&TheFunction->getEntryBlock(),
637 TheFunction->getEntryBlock().begin());
638 return TmpB.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
642 Value *NumberExprAST::Codegen() {
643 return ConstantFP::get(getGlobalContext(), APFloat(Val));
646 Value *VariableExprAST::Codegen() {
647 // Look this variable up in the function.
648 Value *V = NamedValues[Name];
649 if (V == 0) return ErrorV("Unknown variable name");
652 return Builder.CreateLoad(V, Name.c_str());
655 Value *UnaryExprAST::Codegen() {
656 Value *OperandV = Operand->Codegen();
657 if (OperandV == 0) return 0;
659 Function *F = TheHelper->getFunction(MakeLegalFunctionName(std::string("unary")+Opcode));
661 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
664 return ErrorV("Unknown unary operator");
666 return Builder.CreateCall(F, OperandV, "unop");
669 Value *BinaryExprAST::Codegen() {
670 // Special case '=' because we don't want to emit the LHS as an expression.
672 // Assignment requires the LHS to be an identifier.
673 // For now, I'm building without RTTI because LLVM builds that way by
674 // default and so we need to build that way to use the command line supprt.
675 // If you build LLVM with RTTI this can be changed back to a dynamic_cast.
676 VariableExprAST *LHSE = reinterpret_cast<VariableExprAST*>(LHS);
678 return ErrorV("destination of '=' must be a variable");
680 Value *Val = RHS->Codegen();
681 if (Val == 0) return 0;
684 Value *Variable = NamedValues[LHSE->getName()];
685 if (Variable == 0) return ErrorV("Unknown variable name");
687 Builder.CreateStore(Val, Variable);
691 Value *L = LHS->Codegen();
692 Value *R = RHS->Codegen();
693 if (L == 0 || R == 0) return 0;
696 case '+': return Builder.CreateFAdd(L, R, "addtmp");
697 case '-': return Builder.CreateFSub(L, R, "subtmp");
698 case '*': return Builder.CreateFMul(L, R, "multmp");
699 case '/': return Builder.CreateFDiv(L, R, "divtmp");
701 L = Builder.CreateFCmpULT(L, R, "cmptmp");
702 // Convert bool 0/1 to double 0.0 or 1.0
703 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
708 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
710 Function *F = TheModule->getFunction(std::string("binary")+Op);
711 assert(F && "binary operator not found!");
713 Value *Ops[] = { L, R };
714 return Builder.CreateCall(F, Ops, "binop");
717 Value *CallExprAST::Codegen() {
718 // Look up the name in the global module table.
719 Function *CalleeF = TheModule->getFunction(Callee);
722 sprintf(error_str, "Unknown function referenced %s", Callee.c_str());
723 return ErrorV(error_str);
726 // If argument mismatch error.
727 if (CalleeF->arg_size() != Args.size())
728 return ErrorV("Incorrect # arguments passed");
730 std::vector<Value*> ArgsV;
731 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
732 ArgsV.push_back(Args[i]->Codegen());
733 if (ArgsV.back() == 0) return 0;
736 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
739 Value *IfExprAST::Codegen() {
740 Value *CondV = Cond->Codegen();
741 if (CondV == 0) return 0;
743 // Convert condition to a bool by comparing equal to 0.0.
744 CondV = Builder.CreateFCmpONE(CondV,
745 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
748 Function *TheFunction = Builder.GetInsertBlock()->getParent();
750 // Create blocks for the then and else cases. Insert the 'then' block at the
751 // end of the function.
752 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
753 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
754 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
756 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
759 Builder.SetInsertPoint(ThenBB);
761 Value *ThenV = Then->Codegen();
762 if (ThenV == 0) return 0;
764 Builder.CreateBr(MergeBB);
765 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
766 ThenBB = Builder.GetInsertBlock();
769 TheFunction->getBasicBlockList().push_back(ElseBB);
770 Builder.SetInsertPoint(ElseBB);
772 Value *ElseV = Else->Codegen();
773 if (ElseV == 0) return 0;
775 Builder.CreateBr(MergeBB);
776 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
777 ElseBB = Builder.GetInsertBlock();
780 TheFunction->getBasicBlockList().push_back(MergeBB);
781 Builder.SetInsertPoint(MergeBB);
782 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
785 PN->addIncoming(ThenV, ThenBB);
786 PN->addIncoming(ElseV, ElseBB);
790 Value *ForExprAST::Codegen() {
792 // var = alloca double
795 // store start -> var
806 // nextvar = curvar + step
807 // store nextvar -> var
808 // br endcond, loop, endloop
811 Function *TheFunction = Builder.GetInsertBlock()->getParent();
813 // Create an alloca for the variable in the entry block.
814 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
816 // Emit the start code first, without 'variable' in scope.
817 Value *StartVal = Start->Codegen();
818 if (StartVal == 0) return 0;
820 // Store the value into the alloca.
821 Builder.CreateStore(StartVal, Alloca);
823 // Make the new basic block for the loop header, inserting after current
825 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
827 // Insert an explicit fall through from the current block to the LoopBB.
828 Builder.CreateBr(LoopBB);
830 // Start insertion in LoopBB.
831 Builder.SetInsertPoint(LoopBB);
833 // Within the loop, the variable is defined equal to the PHI node. If it
834 // shadows an existing variable, we have to restore it, so save it now.
835 AllocaInst *OldVal = NamedValues[VarName];
836 NamedValues[VarName] = Alloca;
838 // Emit the body of the loop. This, like any other expr, can change the
839 // current BB. Note that we ignore the value computed by the body, but don't
841 if (Body->Codegen() == 0)
844 // Emit the step value.
847 StepVal = Step->Codegen();
848 if (StepVal == 0) return 0;
850 // If not specified, use 1.0.
851 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
854 // Compute the end condition.
855 Value *EndCond = End->Codegen();
856 if (EndCond == 0) return EndCond;
858 // Reload, increment, and restore the alloca. This handles the case where
859 // the body of the loop mutates the variable.
860 Value *CurVar = Builder.CreateLoad(Alloca, VarName.c_str());
861 Value *NextVar = Builder.CreateFAdd(CurVar, StepVal, "nextvar");
862 Builder.CreateStore(NextVar, Alloca);
864 // Convert condition to a bool by comparing equal to 0.0.
865 EndCond = Builder.CreateFCmpONE(EndCond,
866 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
869 // Create the "after loop" block and insert it.
870 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
872 // Insert the conditional branch into the end of LoopEndBB.
873 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
875 // Any new code will be inserted in AfterBB.
876 Builder.SetInsertPoint(AfterBB);
878 // Restore the unshadowed variable.
880 NamedValues[VarName] = OldVal;
882 NamedValues.erase(VarName);
885 // for expr always returns 0.0.
886 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
889 Value *VarExprAST::Codegen() {
890 std::vector<AllocaInst *> OldBindings;
892 Function *TheFunction = Builder.GetInsertBlock()->getParent();
894 // Register all variables and emit their initializer.
895 for (unsigned i = 0, e = VarNames.size(); i != e; ++i) {
896 const std::string &VarName = VarNames[i].first;
897 ExprAST *Init = VarNames[i].second;
899 // Emit the initializer before adding the variable to scope, this prevents
900 // the initializer from referencing the variable itself, and permits stuff
903 // var a = a in ... # refers to outer 'a'.
906 InitVal = Init->Codegen();
907 if (InitVal == 0) return 0;
908 } else { // If not specified, use 0.0.
909 InitVal = ConstantFP::get(getGlobalContext(), APFloat(0.0));
912 AllocaInst *Alloca = CreateEntryBlockAlloca(TheFunction, VarName);
913 Builder.CreateStore(InitVal, Alloca);
915 // Remember the old variable binding so that we can restore the binding when
917 OldBindings.push_back(NamedValues[VarName]);
919 // Remember this binding.
920 NamedValues[VarName] = Alloca;
923 // Codegen the body, now that all vars are in scope.
924 Value *BodyVal = Body->Codegen();
925 if (BodyVal == 0) return 0;
927 // Pop all our variables from scope.
928 for (unsigned i = 0, e = VarNames.size(); i != e; ++i)
929 NamedValues[VarNames[i].first] = OldBindings[i];
931 // Return the body computation.
935 Function *PrototypeAST::Codegen() {
936 // Make the function type: double(double,double) etc.
937 std::vector<Type*> Doubles(Args.size(),
938 Type::getDoubleTy(getGlobalContext()));
939 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
942 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
943 // If F conflicted, there was already something named 'Name'. If it has a
944 // body, don't allow redefinition or reextern.
945 if (F->getName() != Name) {
946 // Delete the one we just made and get the existing one.
947 F->eraseFromParent();
948 F = TheModule->getFunction(Name);
949 // If F already has a body, reject this.
951 ErrorF("redefinition of function");
954 // If F took a different number of args, reject.
955 if (F->arg_size() != Args.size()) {
956 ErrorF("redefinition of function with different # args");
961 // Set names for all arguments.
963 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
965 AI->setName(Args[Idx]);
970 /// CreateArgumentAllocas - Create an alloca for each argument and register the
971 /// argument in the symbol table so that references to it will succeed.
972 void PrototypeAST::CreateArgumentAllocas(Function *F) {
973 Function::arg_iterator AI = F->arg_begin();
974 for (unsigned Idx = 0, e = Args.size(); Idx != e; ++Idx, ++AI) {
975 // Create an alloca for this variable.
976 AllocaInst *Alloca = CreateEntryBlockAlloca(F, Args[Idx]);
978 // Store the initial value into the alloca.
979 Builder.CreateStore(AI, Alloca);
981 // Add arguments to variable symbol table.
982 NamedValues[Args[Idx]] = Alloca;
986 Function *FunctionAST::Codegen() {
989 Function *TheFunction = Proto->Codegen();
990 if (TheFunction == 0)
993 // If this is an operator, install it.
994 if (Proto->isBinaryOp())
995 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
997 // Create a new basic block to start insertion into.
998 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
999 Builder.SetInsertPoint(BB);
1001 // Add all arguments to the symbol table and create their allocas.
1002 Proto->CreateArgumentAllocas(TheFunction);
1004 if (Value *RetVal = Body->Codegen()) {
1005 // Finish off the function.
1006 Builder.CreateRet(RetVal);
1008 // Validate the generated code, checking for consistency.
1009 verifyFunction(*TheFunction);
1011 // Optimize the function.
1012 TheFPM->run(*TheFunction);
1017 // Error reading body, remove function.
1018 TheFunction->eraseFromParent();
1020 if (Proto->isBinaryOp())
1021 BinopPrecedence.erase(Proto->getOperatorName());
1025 //===----------------------------------------------------------------------===//
1026 // Top-Level parsing and JIT Driver
1027 //===----------------------------------------------------------------------===//
1029 static ExecutionEngine *TheExecutionEngine;
1031 static void HandleDefinition() {
1032 if (FunctionAST *F = ParseDefinition()) {
1033 if (Function *LF = F->Codegen()) {
1034 #ifndef MINIMAL_STDERR_OUTPUT
1035 fprintf(stderr, "Read function definition:");
1040 // Skip token for error recovery.
1045 static void HandleExtern() {
1046 if (PrototypeAST *P = ParseExtern()) {
1047 if (Function *F = P->Codegen()) {
1048 #ifndef MINIMAL_STDERR_OUTPUT
1049 fprintf(stderr, "Read extern: ");
1054 // Skip token for error recovery.
1059 static void HandleTopLevelExpression() {
1060 // Evaluate a top-level expression into an anonymous function.
1061 if (FunctionAST *F = ParseTopLevelExpr()) {
1062 if (Function *LF = F->Codegen()) {
1063 // JIT the function, returning a function pointer.
1064 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
1065 // Cast it to the right type (takes no arguments, returns a double) so we
1066 // can call it as a native function.
1067 double (*FP)() = (double (*)())(intptr_t)FPtr;
1068 #ifdef MINIMAL_STDERR_OUTPUT
1071 fprintf(stderr, "Evaluated to %f\n", FP());
1075 // Skip token for error recovery.
1080 /// top ::= definition | external | expression | ';'
1081 static void MainLoop() {
1083 #ifndef MINIMAL_STDERR_OUTPUT
1084 fprintf(stderr, "ready> ");
1087 case tok_eof: return;
1088 case ';': getNextToken(); break; // ignore top-level semicolons.
1089 case tok_def: HandleDefinition(); break;
1090 case tok_extern: HandleExtern(); break;
1091 default: HandleTopLevelExpression(); break;
1096 //===----------------------------------------------------------------------===//
1097 // "Library" functions that can be "extern'd" from user code.
1098 //===----------------------------------------------------------------------===//
1100 /// putchard - putchar that takes a double and returns 0.
1102 double putchard(double X) {
1107 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1109 double printd(double X) {
1120 //===----------------------------------------------------------------------===//
1121 // Command line input file handlers
1122 //===----------------------------------------------------------------------===//
1124 Module* parseInputIR(std::string InputFile) {
1126 Module *M = ParseIRFile(InputFile, Err, getGlobalContext());
1128 Err.print("IR parsing failed: ", errs());
1135 //===----------------------------------------------------------------------===//
1136 // Main driver code.
1137 //===----------------------------------------------------------------------===//
1139 int main(int argc, char **argv) {
1140 InitializeNativeTarget();
1141 LLVMContext &Context = getGlobalContext();
1143 cl::ParseCommandLineOptions(argc, argv,
1144 "Kaleidoscope example program\n");
1146 // Install standard binary operators.
1147 // 1 is lowest precedence.
1148 BinopPrecedence['='] = 2;
1149 BinopPrecedence['<'] = 10;
1150 BinopPrecedence['+'] = 20;
1151 BinopPrecedence['-'] = 20;
1152 BinopPrecedence['/'] = 40;
1153 BinopPrecedence['*'] = 40; // highest.
1155 // Make the module, which holds all the code.
1156 if (!InputIR.empty()) {
1157 TheModule = parseInputIR(InputIR);
1159 TheModule = new Module("my cool jit", Context);
1162 // Create the JIT. This takes ownership of the module.
1164 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
1165 if (!TheExecutionEngine) {
1166 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1170 FunctionPassManager OurFPM(TheModule);
1172 // Set up the optimizer pipeline. Start with registering info about how the
1173 // target lays out data structures.
1174 OurFPM.add(new DataLayout(*TheExecutionEngine->getDataLayout()));
1175 // Provide basic AliasAnalysis support for GVN.
1176 OurFPM.add(createBasicAliasAnalysisPass());
1177 // Promote allocas to registers.
1178 OurFPM.add(createPromoteMemoryToRegisterPass());
1179 // Do simple "peephole" optimizations and bit-twiddling optzns.
1180 OurFPM.add(createInstructionCombiningPass());
1181 // Reassociate expressions.
1182 OurFPM.add(createReassociatePass());
1183 // Eliminate Common SubExpressions.
1184 OurFPM.add(createGVNPass());
1185 // Simplify the control flow graph (deleting unreachable blocks, etc).
1186 OurFPM.add(createCFGSimplificationPass());
1188 OurFPM.doInitialization();
1190 // Set the global so the code gen can use this.
1193 // Prime the first token.
1194 #ifndef MINIMAL_STDERR_OUTPUT
1195 fprintf(stderr, "ready> ");
1199 // Run the main "interpreter loop" now.
1202 // Print out all of the generated code.
1204 #if !defined(MINIMAL_STDERR_OUTPUT) || defined(DUMP_FINAL_MODULE)