1 #include "llvm/DerivedTypes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/Interpreter.h"
4 #include "llvm/ExecutionEngine/JIT.h"
5 #include "llvm/LLVMContext.h"
6 #include "llvm/Module.h"
7 #include "llvm/ModuleProvider.h"
8 #include "llvm/PassManager.h"
9 #include "llvm/Analysis/Verifier.h"
10 #include "llvm/Target/TargetData.h"
11 #include "llvm/Target/TargetSelect.h"
12 #include "llvm/Transforms/Scalar.h"
13 #include "llvm/Support/IRBuilder.h"
20 //===----------------------------------------------------------------------===//
22 //===----------------------------------------------------------------------===//
24 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
25 // of these for known things.
30 tok_def
= -2, tok_extern
= -3,
33 tok_identifier
= -4, tok_number
= -5,
36 tok_if
= -6, tok_then
= -7, tok_else
= -8,
37 tok_for
= -9, tok_in
= -10,
40 tok_binary
= -11, tok_unary
= -12,
46 static std::string IdentifierStr
; // Filled in if tok_identifier
47 static double NumVal
; // Filled in if tok_number
49 /// gettok - Return the next token from standard input.
51 static int LastChar
= ' ';
53 // Skip any whitespace.
54 while (isspace(LastChar
))
57 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
58 IdentifierStr
= LastChar
;
59 while (isalnum((LastChar
= getchar())))
60 IdentifierStr
+= LastChar
;
62 if (IdentifierStr
== "def") return tok_def
;
63 if (IdentifierStr
== "extern") return tok_extern
;
64 if (IdentifierStr
== "if") return tok_if
;
65 if (IdentifierStr
== "then") return tok_then
;
66 if (IdentifierStr
== "else") return tok_else
;
67 if (IdentifierStr
== "for") return tok_for
;
68 if (IdentifierStr
== "in") return tok_in
;
69 if (IdentifierStr
== "binary") return tok_binary
;
70 if (IdentifierStr
== "unary") return tok_unary
;
71 if (IdentifierStr
== "var") return tok_var
;
72 return tok_identifier
;
75 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
80 } while (isdigit(LastChar
) || LastChar
== '.');
82 NumVal
= strtod(NumStr
.c_str(), 0);
86 if (LastChar
== '#') {
87 // Comment until end of line.
88 do LastChar
= getchar();
89 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
95 // Check for end of file. Don't eat the EOF.
99 // Otherwise, just return the character as its ascii value.
100 int ThisChar
= LastChar
;
101 LastChar
= getchar();
105 //===----------------------------------------------------------------------===//
106 // Abstract Syntax Tree (aka Parse Tree)
107 //===----------------------------------------------------------------------===//
109 /// ExprAST - Base class for all expression nodes.
112 virtual ~ExprAST() {}
113 virtual Value
*Codegen() = 0;
116 /// NumberExprAST - Expression class for numeric literals like "1.0".
117 class NumberExprAST
: public ExprAST
{
120 NumberExprAST(double val
) : Val(val
) {}
121 virtual Value
*Codegen();
124 /// VariableExprAST - Expression class for referencing a variable, like "a".
125 class VariableExprAST
: public ExprAST
{
128 VariableExprAST(const std::string
&name
) : Name(name
) {}
129 const std::string
&getName() const { return Name
; }
130 virtual Value
*Codegen();
133 /// UnaryExprAST - Expression class for a unary operator.
134 class UnaryExprAST
: public ExprAST
{
138 UnaryExprAST(char opcode
, ExprAST
*operand
)
139 : Opcode(opcode
), Operand(operand
) {}
140 virtual Value
*Codegen();
143 /// BinaryExprAST - Expression class for a binary operator.
144 class BinaryExprAST
: public ExprAST
{
148 BinaryExprAST(char op
, ExprAST
*lhs
, ExprAST
*rhs
)
149 : Op(op
), LHS(lhs
), RHS(rhs
) {}
150 virtual Value
*Codegen();
153 /// CallExprAST - Expression class for function calls.
154 class CallExprAST
: public ExprAST
{
156 std::vector
<ExprAST
*> Args
;
158 CallExprAST(const std::string
&callee
, std::vector
<ExprAST
*> &args
)
159 : Callee(callee
), Args(args
) {}
160 virtual Value
*Codegen();
163 /// IfExprAST - Expression class for if/then/else.
164 class IfExprAST
: public ExprAST
{
165 ExprAST
*Cond
, *Then
, *Else
;
167 IfExprAST(ExprAST
*cond
, ExprAST
*then
, ExprAST
*_else
)
168 : Cond(cond
), Then(then
), Else(_else
) {}
169 virtual Value
*Codegen();
172 /// ForExprAST - Expression class for for/in.
173 class ForExprAST
: public ExprAST
{
175 ExprAST
*Start
, *End
, *Step
, *Body
;
177 ForExprAST(const std::string
&varname
, ExprAST
*start
, ExprAST
*end
,
178 ExprAST
*step
, ExprAST
*body
)
179 : VarName(varname
), Start(start
), End(end
), Step(step
), Body(body
) {}
180 virtual Value
*Codegen();
183 /// VarExprAST - Expression class for var/in
184 class VarExprAST
: public ExprAST
{
185 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
188 VarExprAST(const std::vector
<std::pair
<std::string
, ExprAST
*> > &varnames
,
190 : VarNames(varnames
), Body(body
) {}
192 virtual Value
*Codegen();
195 /// PrototypeAST - This class represents the "prototype" for a function,
196 /// which captures its argument names as well as if it is an operator.
199 std::vector
<std::string
> Args
;
201 unsigned Precedence
; // Precedence if a binary op.
203 PrototypeAST(const std::string
&name
, const std::vector
<std::string
> &args
,
204 bool isoperator
= false, unsigned prec
= 0)
205 : Name(name
), Args(args
), isOperator(isoperator
), Precedence(prec
) {}
207 bool isUnaryOp() const { return isOperator
&& Args
.size() == 1; }
208 bool isBinaryOp() const { return isOperator
&& Args
.size() == 2; }
210 char getOperatorName() const {
211 assert(isUnaryOp() || isBinaryOp());
212 return Name
[Name
.size()-1];
215 unsigned getBinaryPrecedence() const { return Precedence
; }
219 void CreateArgumentAllocas(Function
*F
);
222 /// FunctionAST - This class represents a function definition itself.
227 FunctionAST(PrototypeAST
*proto
, ExprAST
*body
)
228 : Proto(proto
), Body(body
) {}
233 //===----------------------------------------------------------------------===//
235 //===----------------------------------------------------------------------===//
237 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
238 /// token the parser it looking at. getNextToken reads another token from the
239 /// lexer and updates CurTok with its results.
241 static int getNextToken() {
242 return CurTok
= gettok();
245 /// BinopPrecedence - This holds the precedence for each binary operator that is
247 static std::map
<char, int> BinopPrecedence
;
249 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
250 static int GetTokPrecedence() {
251 if (!isascii(CurTok
))
254 // Make sure it's a declared binop.
255 int TokPrec
= BinopPrecedence
[CurTok
];
256 if (TokPrec
<= 0) return -1;
260 /// Error* - These are little helper functions for error handling.
261 ExprAST
*Error(const char *Str
) { fprintf(stderr
, "Error: %s\n", Str
);return 0;}
262 PrototypeAST
*ErrorP(const char *Str
) { Error(Str
); return 0; }
263 FunctionAST
*ErrorF(const char *Str
) { Error(Str
); return 0; }
265 static ExprAST
*ParseExpression();
269 /// ::= identifier '(' expression* ')'
270 static ExprAST
*ParseIdentifierExpr() {
271 std::string IdName
= IdentifierStr
;
273 getNextToken(); // eat identifier.
275 if (CurTok
!= '(') // Simple variable ref.
276 return new VariableExprAST(IdName
);
279 getNextToken(); // eat (
280 std::vector
<ExprAST
*> Args
;
283 ExprAST
*Arg
= ParseExpression();
287 if (CurTok
== ')') break;
290 return Error("Expected ')' or ',' in argument list");
298 return new CallExprAST(IdName
, Args
);
301 /// numberexpr ::= number
302 static ExprAST
*ParseNumberExpr() {
303 ExprAST
*Result
= new NumberExprAST(NumVal
);
304 getNextToken(); // consume the number
308 /// parenexpr ::= '(' expression ')'
309 static ExprAST
*ParseParenExpr() {
310 getNextToken(); // eat (.
311 ExprAST
*V
= ParseExpression();
315 return Error("expected ')'");
316 getNextToken(); // eat ).
320 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
321 static ExprAST
*ParseIfExpr() {
322 getNextToken(); // eat the if.
325 ExprAST
*Cond
= ParseExpression();
328 if (CurTok
!= tok_then
)
329 return Error("expected then");
330 getNextToken(); // eat the then
332 ExprAST
*Then
= ParseExpression();
333 if (Then
== 0) return 0;
335 if (CurTok
!= tok_else
)
336 return Error("expected else");
340 ExprAST
*Else
= ParseExpression();
343 return new IfExprAST(Cond
, Then
, Else
);
346 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
347 static ExprAST
*ParseForExpr() {
348 getNextToken(); // eat the for.
350 if (CurTok
!= tok_identifier
)
351 return Error("expected identifier after for");
353 std::string IdName
= IdentifierStr
;
354 getNextToken(); // eat identifier.
357 return Error("expected '=' after for");
358 getNextToken(); // eat '='.
361 ExprAST
*Start
= ParseExpression();
362 if (Start
== 0) return 0;
364 return Error("expected ',' after for start value");
367 ExprAST
*End
= ParseExpression();
368 if (End
== 0) return 0;
370 // The step value is optional.
374 Step
= ParseExpression();
375 if (Step
== 0) return 0;
378 if (CurTok
!= tok_in
)
379 return Error("expected 'in' after for");
380 getNextToken(); // eat 'in'.
382 ExprAST
*Body
= ParseExpression();
383 if (Body
== 0) return 0;
385 return new ForExprAST(IdName
, Start
, End
, Step
, Body
);
388 /// varexpr ::= 'var' identifier ('=' expression)?
389 // (',' identifier ('=' expression)?)* 'in' expression
390 static ExprAST
*ParseVarExpr() {
391 getNextToken(); // eat the var.
393 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
395 // At least one variable name is required.
396 if (CurTok
!= tok_identifier
)
397 return Error("expected identifier after var");
400 std::string Name
= IdentifierStr
;
401 getNextToken(); // eat identifier.
403 // Read the optional initializer.
406 getNextToken(); // eat the '='.
408 Init
= ParseExpression();
409 if (Init
== 0) return 0;
412 VarNames
.push_back(std::make_pair(Name
, Init
));
414 // End of var list, exit loop.
415 if (CurTok
!= ',') break;
416 getNextToken(); // eat the ','.
418 if (CurTok
!= tok_identifier
)
419 return Error("expected identifier list after var");
422 // At this point, we have to have 'in'.
423 if (CurTok
!= tok_in
)
424 return Error("expected 'in' keyword after 'var'");
425 getNextToken(); // eat 'in'.
427 ExprAST
*Body
= ParseExpression();
428 if (Body
== 0) return 0;
430 return new VarExprAST(VarNames
, Body
);
435 /// ::= identifierexpr
441 static ExprAST
*ParsePrimary() {
443 default: return Error("unknown token when expecting an expression");
444 case tok_identifier
: return ParseIdentifierExpr();
445 case tok_number
: return ParseNumberExpr();
446 case '(': return ParseParenExpr();
447 case tok_if
: return ParseIfExpr();
448 case tok_for
: return ParseForExpr();
449 case tok_var
: return ParseVarExpr();
456 static ExprAST
*ParseUnary() {
457 // If the current token is not an operator, it must be a primary expr.
458 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
459 return ParsePrimary();
461 // If this is a unary operator, read it.
464 if (ExprAST
*Operand
= ParseUnary())
465 return new UnaryExprAST(Opc
, Operand
);
471 static ExprAST
*ParseBinOpRHS(int ExprPrec
, ExprAST
*LHS
) {
472 // If this is a binop, find its precedence.
474 int TokPrec
= GetTokPrecedence();
476 // If this is a binop that binds at least as tightly as the current binop,
477 // consume it, otherwise we are done.
478 if (TokPrec
< ExprPrec
)
481 // Okay, we know this is a binop.
483 getNextToken(); // eat binop
485 // Parse the unary expression after the binary operator.
486 ExprAST
*RHS
= ParseUnary();
489 // If BinOp binds less tightly with RHS than the operator after RHS, let
490 // the pending operator take RHS as its LHS.
491 int NextPrec
= GetTokPrecedence();
492 if (TokPrec
< NextPrec
) {
493 RHS
= ParseBinOpRHS(TokPrec
+1, RHS
);
494 if (RHS
== 0) return 0;
498 LHS
= new BinaryExprAST(BinOp
, LHS
, RHS
);
503 /// ::= unary binoprhs
505 static ExprAST
*ParseExpression() {
506 ExprAST
*LHS
= ParseUnary();
509 return ParseBinOpRHS(0, LHS
);
513 /// ::= id '(' id* ')'
514 /// ::= binary LETTER number? (id, id)
515 /// ::= unary LETTER (id)
516 static PrototypeAST
*ParsePrototype() {
519 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
520 unsigned BinaryPrecedence
= 30;
524 return ErrorP("Expected function name in prototype");
526 FnName
= IdentifierStr
;
532 if (!isascii(CurTok
))
533 return ErrorP("Expected unary operator");
535 FnName
+= (char)CurTok
;
541 if (!isascii(CurTok
))
542 return ErrorP("Expected binary operator");
544 FnName
+= (char)CurTok
;
548 // Read the precedence if present.
549 if (CurTok
== tok_number
) {
550 if (NumVal
< 1 || NumVal
> 100)
551 return ErrorP("Invalid precedecnce: must be 1..100");
552 BinaryPrecedence
= (unsigned)NumVal
;
559 return ErrorP("Expected '(' in prototype");
561 std::vector
<std::string
> ArgNames
;
562 while (getNextToken() == tok_identifier
)
563 ArgNames
.push_back(IdentifierStr
);
565 return ErrorP("Expected ')' in prototype");
568 getNextToken(); // eat ')'.
570 // Verify right number of names for operator.
571 if (Kind
&& ArgNames
.size() != Kind
)
572 return ErrorP("Invalid number of operands for operator");
574 return new PrototypeAST(FnName
, ArgNames
, Kind
!= 0, BinaryPrecedence
);
577 /// definition ::= 'def' prototype expression
578 static FunctionAST
*ParseDefinition() {
579 getNextToken(); // eat def.
580 PrototypeAST
*Proto
= ParsePrototype();
581 if (Proto
== 0) return 0;
583 if (ExprAST
*E
= ParseExpression())
584 return new FunctionAST(Proto
, E
);
588 /// toplevelexpr ::= expression
589 static FunctionAST
*ParseTopLevelExpr() {
590 if (ExprAST
*E
= ParseExpression()) {
591 // Make an anonymous proto.
592 PrototypeAST
*Proto
= new PrototypeAST("", std::vector
<std::string
>());
593 return new FunctionAST(Proto
, E
);
598 /// external ::= 'extern' prototype
599 static PrototypeAST
*ParseExtern() {
600 getNextToken(); // eat extern.
601 return ParsePrototype();
604 //===----------------------------------------------------------------------===//
606 //===----------------------------------------------------------------------===//
608 static Module
*TheModule
;
609 static IRBuilder
<> Builder(getGlobalContext());
610 static std::map
<std::string
, AllocaInst
*> NamedValues
;
611 static FunctionPassManager
*TheFPM
;
613 Value
*ErrorV(const char *Str
) { Error(Str
); return 0; }
615 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
616 /// the function. This is used for mutable variables etc.
617 static AllocaInst
*CreateEntryBlockAlloca(Function
*TheFunction
,
618 const std::string
&VarName
) {
619 IRBuilder
<> TmpB(&TheFunction
->getEntryBlock(),
620 TheFunction
->getEntryBlock().begin());
621 return TmpB
.CreateAlloca(Type::getDoubleTy(getGlobalContext()), 0,
626 Value
*NumberExprAST::Codegen() {
627 return ConstantFP::get(getGlobalContext(), APFloat(Val
));
630 Value
*VariableExprAST::Codegen() {
631 // Look this variable up in the function.
632 Value
*V
= NamedValues
[Name
];
633 if (V
== 0) return ErrorV("Unknown variable name");
636 return Builder
.CreateLoad(V
, Name
.c_str());
639 Value
*UnaryExprAST::Codegen() {
640 Value
*OperandV
= Operand
->Codegen();
641 if (OperandV
== 0) return 0;
643 Function
*F
= TheModule
->getFunction(std::string("unary")+Opcode
);
645 return ErrorV("Unknown unary operator");
647 return Builder
.CreateCall(F
, OperandV
, "unop");
651 Value
*BinaryExprAST::Codegen() {
652 // Special case '=' because we don't want to emit the LHS as an expression.
654 // Assignment requires the LHS to be an identifier.
655 VariableExprAST
*LHSE
= dynamic_cast<VariableExprAST
*>(LHS
);
657 return ErrorV("destination of '=' must be a variable");
659 Value
*Val
= RHS
->Codegen();
660 if (Val
== 0) return 0;
663 Value
*Variable
= NamedValues
[LHSE
->getName()];
664 if (Variable
== 0) return ErrorV("Unknown variable name");
666 Builder
.CreateStore(Val
, Variable
);
671 Value
*L
= LHS
->Codegen();
672 Value
*R
= RHS
->Codegen();
673 if (L
== 0 || R
== 0) return 0;
676 case '+': return Builder
.CreateAdd(L
, R
, "addtmp");
677 case '-': return Builder
.CreateSub(L
, R
, "subtmp");
678 case '*': return Builder
.CreateMul(L
, R
, "multmp");
680 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
681 // Convert bool 0/1 to double 0.0 or 1.0
682 return Builder
.CreateUIToFP(L
, Type::getDoubleTy(getGlobalContext()),
687 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
689 Function
*F
= TheModule
->getFunction(std::string("binary")+Op
);
690 assert(F
&& "binary operator not found!");
692 Value
*Ops
[] = { L
, R
};
693 return Builder
.CreateCall(F
, Ops
, Ops
+2, "binop");
696 Value
*CallExprAST::Codegen() {
697 // Look up the name in the global module table.
698 Function
*CalleeF
= TheModule
->getFunction(Callee
);
700 return ErrorV("Unknown function referenced");
702 // If argument mismatch error.
703 if (CalleeF
->arg_size() != Args
.size())
704 return ErrorV("Incorrect # arguments passed");
706 std::vector
<Value
*> ArgsV
;
707 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
708 ArgsV
.push_back(Args
[i
]->Codegen());
709 if (ArgsV
.back() == 0) return 0;
712 return Builder
.CreateCall(CalleeF
, ArgsV
.begin(), ArgsV
.end(), "calltmp");
715 Value
*IfExprAST::Codegen() {
716 Value
*CondV
= Cond
->Codegen();
717 if (CondV
== 0) return 0;
719 // Convert condition to a bool by comparing equal to 0.0.
720 CondV
= Builder
.CreateFCmpONE(CondV
,
721 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
724 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
726 // Create blocks for the then and else cases. Insert the 'then' block at the
727 // end of the function.
728 BasicBlock
*ThenBB
= BasicBlock::Create(getGlobalContext(), "then", TheFunction
);
729 BasicBlock
*ElseBB
= BasicBlock::Create(getGlobalContext(), "else");
730 BasicBlock
*MergeBB
= BasicBlock::Create(getGlobalContext(), "ifcont");
732 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
735 Builder
.SetInsertPoint(ThenBB
);
737 Value
*ThenV
= Then
->Codegen();
738 if (ThenV
== 0) return 0;
740 Builder
.CreateBr(MergeBB
);
741 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
742 ThenBB
= Builder
.GetInsertBlock();
745 TheFunction
->getBasicBlockList().push_back(ElseBB
);
746 Builder
.SetInsertPoint(ElseBB
);
748 Value
*ElseV
= Else
->Codegen();
749 if (ElseV
== 0) return 0;
751 Builder
.CreateBr(MergeBB
);
752 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
753 ElseBB
= Builder
.GetInsertBlock();
756 TheFunction
->getBasicBlockList().push_back(MergeBB
);
757 Builder
.SetInsertPoint(MergeBB
);
758 PHINode
*PN
= Builder
.CreatePHI(Type::getDoubleTy(getGlobalContext()),
761 PN
->addIncoming(ThenV
, ThenBB
);
762 PN
->addIncoming(ElseV
, ElseBB
);
766 Value
*ForExprAST::Codegen() {
768 // var = alloca double
771 // store start -> var
782 // nextvar = curvar + step
783 // store nextvar -> var
784 // br endcond, loop, endloop
787 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
789 // Create an alloca for the variable in the entry block.
790 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
792 // Emit the start code first, without 'variable' in scope.
793 Value
*StartVal
= Start
->Codegen();
794 if (StartVal
== 0) return 0;
796 // Store the value into the alloca.
797 Builder
.CreateStore(StartVal
, Alloca
);
799 // Make the new basic block for the loop header, inserting after current
801 BasicBlock
*LoopBB
= BasicBlock::Create(getGlobalContext(), "loop", TheFunction
);
803 // Insert an explicit fall through from the current block to the LoopBB.
804 Builder
.CreateBr(LoopBB
);
806 // Start insertion in LoopBB.
807 Builder
.SetInsertPoint(LoopBB
);
809 // Within the loop, the variable is defined equal to the PHI node. If it
810 // shadows an existing variable, we have to restore it, so save it now.
811 AllocaInst
*OldVal
= NamedValues
[VarName
];
812 NamedValues
[VarName
] = Alloca
;
814 // Emit the body of the loop. This, like any other expr, can change the
815 // current BB. Note that we ignore the value computed by the body, but don't
817 if (Body
->Codegen() == 0)
820 // Emit the step value.
823 StepVal
= Step
->Codegen();
824 if (StepVal
== 0) return 0;
826 // If not specified, use 1.0.
827 StepVal
= ConstantFP::get(getGlobalContext(), APFloat(1.0));
830 // Compute the end condition.
831 Value
*EndCond
= End
->Codegen();
832 if (EndCond
== 0) return EndCond
;
834 // Reload, increment, and restore the alloca. This handles the case where
835 // the body of the loop mutates the variable.
836 Value
*CurVar
= Builder
.CreateLoad(Alloca
, VarName
.c_str());
837 Value
*NextVar
= Builder
.CreateAdd(CurVar
, StepVal
, "nextvar");
838 Builder
.CreateStore(NextVar
, Alloca
);
840 // Convert condition to a bool by comparing equal to 0.0.
841 EndCond
= Builder
.CreateFCmpONE(EndCond
,
842 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
845 // Create the "after loop" block and insert it.
846 BasicBlock
*AfterBB
= BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction
);
848 // Insert the conditional branch into the end of LoopEndBB.
849 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
851 // Any new code will be inserted in AfterBB.
852 Builder
.SetInsertPoint(AfterBB
);
854 // Restore the unshadowed variable.
856 NamedValues
[VarName
] = OldVal
;
858 NamedValues
.erase(VarName
);
861 // for expr always returns 0.0.
862 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
865 Value
*VarExprAST::Codegen() {
866 std::vector
<AllocaInst
*> OldBindings
;
868 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
870 // Register all variables and emit their initializer.
871 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
) {
872 const std::string
&VarName
= VarNames
[i
].first
;
873 ExprAST
*Init
= VarNames
[i
].second
;
875 // Emit the initializer before adding the variable to scope, this prevents
876 // the initializer from referencing the variable itself, and permits stuff
879 // var a = a in ... # refers to outer 'a'.
882 InitVal
= Init
->Codegen();
883 if (InitVal
== 0) return 0;
884 } else { // If not specified, use 0.0.
885 InitVal
= ConstantFP::get(getGlobalContext(), APFloat(0.0));
888 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
889 Builder
.CreateStore(InitVal
, Alloca
);
891 // Remember the old variable binding so that we can restore the binding when
893 OldBindings
.push_back(NamedValues
[VarName
]);
895 // Remember this binding.
896 NamedValues
[VarName
] = Alloca
;
899 // Codegen the body, now that all vars are in scope.
900 Value
*BodyVal
= Body
->Codegen();
901 if (BodyVal
== 0) return 0;
903 // Pop all our variables from scope.
904 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
)
905 NamedValues
[VarNames
[i
].first
] = OldBindings
[i
];
907 // Return the body computation.
912 Function
*PrototypeAST::Codegen() {
913 // Make the function type: double(double,double) etc.
914 std::vector
<const Type
*> Doubles(Args
.size(),
915 Type::getDoubleTy(getGlobalContext()));
916 FunctionType
*FT
= FunctionType::get(Type::getDoubleTy(getGlobalContext()),
919 Function
*F
= Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
);
921 // If F conflicted, there was already something named 'Name'. If it has a
922 // body, don't allow redefinition or reextern.
923 if (F
->getName() != Name
) {
924 // Delete the one we just made and get the existing one.
925 F
->eraseFromParent();
926 F
= TheModule
->getFunction(Name
);
928 // If F already has a body, reject this.
930 ErrorF("redefinition of function");
934 // If F took a different number of args, reject.
935 if (F
->arg_size() != Args
.size()) {
936 ErrorF("redefinition of function with different # args");
941 // Set names for all arguments.
943 for (Function::arg_iterator AI
= F
->arg_begin(); Idx
!= Args
.size();
945 AI
->setName(Args
[Idx
]);
950 /// CreateArgumentAllocas - Create an alloca for each argument and register the
951 /// argument in the symbol table so that references to it will succeed.
952 void PrototypeAST::CreateArgumentAllocas(Function
*F
) {
953 Function::arg_iterator AI
= F
->arg_begin();
954 for (unsigned Idx
= 0, e
= Args
.size(); Idx
!= e
; ++Idx
, ++AI
) {
955 // Create an alloca for this variable.
956 AllocaInst
*Alloca
= CreateEntryBlockAlloca(F
, Args
[Idx
]);
958 // Store the initial value into the alloca.
959 Builder
.CreateStore(AI
, Alloca
);
961 // Add arguments to variable symbol table.
962 NamedValues
[Args
[Idx
]] = Alloca
;
967 Function
*FunctionAST::Codegen() {
970 Function
*TheFunction
= Proto
->Codegen();
971 if (TheFunction
== 0)
974 // If this is an operator, install it.
975 if (Proto
->isBinaryOp())
976 BinopPrecedence
[Proto
->getOperatorName()] = Proto
->getBinaryPrecedence();
978 // Create a new basic block to start insertion into.
979 BasicBlock
*BB
= BasicBlock::Create(getGlobalContext(), "entry", TheFunction
);
980 Builder
.SetInsertPoint(BB
);
982 // Add all arguments to the symbol table and create their allocas.
983 Proto
->CreateArgumentAllocas(TheFunction
);
985 if (Value
*RetVal
= Body
->Codegen()) {
986 // Finish off the function.
987 Builder
.CreateRet(RetVal
);
989 // Validate the generated code, checking for consistency.
990 verifyFunction(*TheFunction
);
992 // Optimize the function.
993 TheFPM
->run(*TheFunction
);
998 // Error reading body, remove function.
999 TheFunction
->eraseFromParent();
1001 if (Proto
->isBinaryOp())
1002 BinopPrecedence
.erase(Proto
->getOperatorName());
1006 //===----------------------------------------------------------------------===//
1007 // Top-Level parsing and JIT Driver
1008 //===----------------------------------------------------------------------===//
1010 static ExecutionEngine
*TheExecutionEngine
;
1012 static void HandleDefinition() {
1013 if (FunctionAST
*F
= ParseDefinition()) {
1014 if (Function
*LF
= F
->Codegen()) {
1015 fprintf(stderr
, "Read function definition:");
1019 // Skip token for error recovery.
1024 static void HandleExtern() {
1025 if (PrototypeAST
*P
= ParseExtern()) {
1026 if (Function
*F
= P
->Codegen()) {
1027 fprintf(stderr
, "Read extern: ");
1031 // Skip token for error recovery.
1036 static void HandleTopLevelExpression() {
1037 // Evaluate a top level expression into an anonymous function.
1038 if (FunctionAST
*F
= ParseTopLevelExpr()) {
1039 if (Function
*LF
= F
->Codegen()) {
1040 // JIT the function, returning a function pointer.
1041 void *FPtr
= TheExecutionEngine
->getPointerToFunction(LF
);
1043 // Cast it to the right type (takes no arguments, returns a double) so we
1044 // can call it as a native function.
1045 double (*FP
)() = (double (*)())(intptr_t)FPtr
;
1046 fprintf(stderr
, "Evaluated to %f\n", FP());
1049 // Skip token for error recovery.
1054 /// top ::= definition | external | expression | ';'
1055 static void MainLoop() {
1057 fprintf(stderr
, "ready> ");
1059 case tok_eof
: return;
1060 case ';': getNextToken(); break; // ignore top level semicolons.
1061 case tok_def
: HandleDefinition(); break;
1062 case tok_extern
: HandleExtern(); break;
1063 default: HandleTopLevelExpression(); break;
1070 //===----------------------------------------------------------------------===//
1071 // "Library" functions that can be "extern'd" from user code.
1072 //===----------------------------------------------------------------------===//
1074 /// putchard - putchar that takes a double and returns 0.
1076 double putchard(double X
) {
1081 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1083 double printd(double X
) {
1088 //===----------------------------------------------------------------------===//
1089 // Main driver code.
1090 //===----------------------------------------------------------------------===//
1093 InitializeNativeTarget();
1094 LLVMContext
&Context
= getGlobalContext();
1096 // Install standard binary operators.
1097 // 1 is lowest precedence.
1098 BinopPrecedence
['='] = 2;
1099 BinopPrecedence
['<'] = 10;
1100 BinopPrecedence
['+'] = 20;
1101 BinopPrecedence
['-'] = 20;
1102 BinopPrecedence
['*'] = 40; // highest.
1104 // Prime the first token.
1105 fprintf(stderr
, "ready> ");
1108 // Make the module, which holds all the code.
1109 TheModule
= new Module("my cool jit", Context
);
1111 ExistingModuleProvider
*OurModuleProvider
=
1112 new ExistingModuleProvider(TheModule
);
1114 // Create the JIT. This takes ownership of the module and module provider.
1115 TheExecutionEngine
= EngineBuilder(OurModuleProvider
).create();
1117 FunctionPassManager
OurFPM(OurModuleProvider
);
1119 // Set up the optimizer pipeline. Start with registering info about how the
1120 // target lays out data structures.
1121 OurFPM
.add(new TargetData(*TheExecutionEngine
->getTargetData()));
1122 // Promote allocas to registers.
1123 OurFPM
.add(createPromoteMemoryToRegisterPass());
1124 // Do simple "peephole" optimizations and bit-twiddling optzns.
1125 OurFPM
.add(createInstructionCombiningPass());
1126 // Reassociate expressions.
1127 OurFPM
.add(createReassociatePass());
1128 // Eliminate Common SubExpressions.
1129 OurFPM
.add(createGVNPass());
1130 // Simplify the control flow graph (deleting unreachable blocks, etc).
1131 OurFPM
.add(createCFGSimplificationPass());
1133 OurFPM
.doInitialization();
1135 // Set the global so the code gen can use this.
1138 // Run the main "interpreter loop" now.
1143 // Print out all of the generated code.