1 #include "llvm/DerivedTypes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/Module.h"
4 #include "llvm/ModuleProvider.h"
5 #include "llvm/PassManager.h"
6 #include "llvm/Analysis/Verifier.h"
7 #include "llvm/Target/TargetData.h"
8 #include "llvm/Transforms/Scalar.h"
9 #include "llvm/Support/IRBuilder.h"
16 //===----------------------------------------------------------------------===//
18 //===----------------------------------------------------------------------===//
20 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
21 // of these for known things.
26 tok_def
= -2, tok_extern
= -3,
29 tok_identifier
= -4, tok_number
= -5,
32 tok_if
= -6, tok_then
= -7, tok_else
= -8,
33 tok_for
= -9, tok_in
= -10,
36 tok_binary
= -11, tok_unary
= -12,
42 static std::string IdentifierStr
; // Filled in if tok_identifier
43 static double NumVal
; // Filled in if tok_number
45 /// gettok - Return the next token from standard input.
47 static int LastChar
= ' ';
49 // Skip any whitespace.
50 while (isspace(LastChar
))
53 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
54 IdentifierStr
= LastChar
;
55 while (isalnum((LastChar
= getchar())))
56 IdentifierStr
+= LastChar
;
58 if (IdentifierStr
== "def") return tok_def
;
59 if (IdentifierStr
== "extern") return tok_extern
;
60 if (IdentifierStr
== "if") return tok_if
;
61 if (IdentifierStr
== "then") return tok_then
;
62 if (IdentifierStr
== "else") return tok_else
;
63 if (IdentifierStr
== "for") return tok_for
;
64 if (IdentifierStr
== "in") return tok_in
;
65 if (IdentifierStr
== "binary") return tok_binary
;
66 if (IdentifierStr
== "unary") return tok_unary
;
67 if (IdentifierStr
== "var") return tok_var
;
68 return tok_identifier
;
71 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
76 } while (isdigit(LastChar
) || LastChar
== '.');
78 NumVal
= strtod(NumStr
.c_str(), 0);
82 if (LastChar
== '#') {
83 // Comment until end of line.
84 do LastChar
= getchar();
85 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
91 // Check for end of file. Don't eat the EOF.
95 // Otherwise, just return the character as its ascii value.
96 int ThisChar
= LastChar
;
101 //===----------------------------------------------------------------------===//
102 // Abstract Syntax Tree (aka Parse Tree)
103 //===----------------------------------------------------------------------===//
105 /// ExprAST - Base class for all expression nodes.
108 virtual ~ExprAST() {}
109 virtual Value
*Codegen() = 0;
112 /// NumberExprAST - Expression class for numeric literals like "1.0".
113 class NumberExprAST
: public ExprAST
{
116 NumberExprAST(double val
) : Val(val
) {}
117 virtual Value
*Codegen();
120 /// VariableExprAST - Expression class for referencing a variable, like "a".
121 class VariableExprAST
: public ExprAST
{
124 VariableExprAST(const std::string
&name
) : Name(name
) {}
125 const std::string
&getName() const { return Name
; }
126 virtual Value
*Codegen();
129 /// UnaryExprAST - Expression class for a unary operator.
130 class UnaryExprAST
: public ExprAST
{
134 UnaryExprAST(char opcode
, ExprAST
*operand
)
135 : Opcode(opcode
), Operand(operand
) {}
136 virtual Value
*Codegen();
139 /// BinaryExprAST - Expression class for a binary operator.
140 class BinaryExprAST
: public ExprAST
{
144 BinaryExprAST(char op
, ExprAST
*lhs
, ExprAST
*rhs
)
145 : Op(op
), LHS(lhs
), RHS(rhs
) {}
146 virtual Value
*Codegen();
149 /// CallExprAST - Expression class for function calls.
150 class CallExprAST
: public ExprAST
{
152 std::vector
<ExprAST
*> Args
;
154 CallExprAST(const std::string
&callee
, std::vector
<ExprAST
*> &args
)
155 : Callee(callee
), Args(args
) {}
156 virtual Value
*Codegen();
159 /// IfExprAST - Expression class for if/then/else.
160 class IfExprAST
: public ExprAST
{
161 ExprAST
*Cond
, *Then
, *Else
;
163 IfExprAST(ExprAST
*cond
, ExprAST
*then
, ExprAST
*_else
)
164 : Cond(cond
), Then(then
), Else(_else
) {}
165 virtual Value
*Codegen();
168 /// ForExprAST - Expression class for for/in.
169 class ForExprAST
: public ExprAST
{
171 ExprAST
*Start
, *End
, *Step
, *Body
;
173 ForExprAST(const std::string
&varname
, ExprAST
*start
, ExprAST
*end
,
174 ExprAST
*step
, ExprAST
*body
)
175 : VarName(varname
), Start(start
), End(end
), Step(step
), Body(body
) {}
176 virtual Value
*Codegen();
179 /// VarExprAST - Expression class for var/in
180 class VarExprAST
: public ExprAST
{
181 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
184 VarExprAST(const std::vector
<std::pair
<std::string
, ExprAST
*> > &varnames
,
186 : VarNames(varnames
), Body(body
) {}
188 virtual Value
*Codegen();
191 /// PrototypeAST - This class represents the "prototype" for a function,
192 /// which captures its argument names as well as if it is an operator.
195 std::vector
<std::string
> Args
;
197 unsigned Precedence
; // Precedence if a binary op.
199 PrototypeAST(const std::string
&name
, const std::vector
<std::string
> &args
,
200 bool isoperator
= false, unsigned prec
= 0)
201 : Name(name
), Args(args
), isOperator(isoperator
), Precedence(prec
) {}
203 bool isUnaryOp() const { return isOperator
&& Args
.size() == 1; }
204 bool isBinaryOp() const { return isOperator
&& Args
.size() == 2; }
206 char getOperatorName() const {
207 assert(isUnaryOp() || isBinaryOp());
208 return Name
[Name
.size()-1];
211 unsigned getBinaryPrecedence() const { return Precedence
; }
215 void CreateArgumentAllocas(Function
*F
);
218 /// FunctionAST - This class represents a function definition itself.
223 FunctionAST(PrototypeAST
*proto
, ExprAST
*body
)
224 : Proto(proto
), Body(body
) {}
229 //===----------------------------------------------------------------------===//
231 //===----------------------------------------------------------------------===//
233 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
234 /// token the parser it looking at. getNextToken reads another token from the
235 /// lexer and updates CurTok with its results.
237 static int getNextToken() {
238 return CurTok
= gettok();
241 /// BinopPrecedence - This holds the precedence for each binary operator that is
243 static std::map
<char, int> BinopPrecedence
;
245 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
246 static int GetTokPrecedence() {
247 if (!isascii(CurTok
))
250 // Make sure it's a declared binop.
251 int TokPrec
= BinopPrecedence
[CurTok
];
252 if (TokPrec
<= 0) return -1;
256 /// Error* - These are little helper functions for error handling.
257 ExprAST
*Error(const char *Str
) { fprintf(stderr
, "Error: %s\n", Str
);return 0;}
258 PrototypeAST
*ErrorP(const char *Str
) { Error(Str
); return 0; }
259 FunctionAST
*ErrorF(const char *Str
) { Error(Str
); return 0; }
261 static ExprAST
*ParseExpression();
265 /// ::= identifier '(' expression* ')'
266 static ExprAST
*ParseIdentifierExpr() {
267 std::string IdName
= IdentifierStr
;
269 getNextToken(); // eat identifier.
271 if (CurTok
!= '(') // Simple variable ref.
272 return new VariableExprAST(IdName
);
275 getNextToken(); // eat (
276 std::vector
<ExprAST
*> Args
;
279 ExprAST
*Arg
= ParseExpression();
283 if (CurTok
== ')') break;
286 return Error("Expected ')' or ',' in argument list");
294 return new CallExprAST(IdName
, Args
);
297 /// numberexpr ::= number
298 static ExprAST
*ParseNumberExpr() {
299 ExprAST
*Result
= new NumberExprAST(NumVal
);
300 getNextToken(); // consume the number
304 /// parenexpr ::= '(' expression ')'
305 static ExprAST
*ParseParenExpr() {
306 getNextToken(); // eat (.
307 ExprAST
*V
= ParseExpression();
311 return Error("expected ')'");
312 getNextToken(); // eat ).
316 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
317 static ExprAST
*ParseIfExpr() {
318 getNextToken(); // eat the if.
321 ExprAST
*Cond
= ParseExpression();
324 if (CurTok
!= tok_then
)
325 return Error("expected then");
326 getNextToken(); // eat the then
328 ExprAST
*Then
= ParseExpression();
329 if (Then
== 0) return 0;
331 if (CurTok
!= tok_else
)
332 return Error("expected else");
336 ExprAST
*Else
= ParseExpression();
339 return new IfExprAST(Cond
, Then
, Else
);
342 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
343 static ExprAST
*ParseForExpr() {
344 getNextToken(); // eat the for.
346 if (CurTok
!= tok_identifier
)
347 return Error("expected identifier after for");
349 std::string IdName
= IdentifierStr
;
350 getNextToken(); // eat identifier.
353 return Error("expected '=' after for");
354 getNextToken(); // eat '='.
357 ExprAST
*Start
= ParseExpression();
358 if (Start
== 0) return 0;
360 return Error("expected ',' after for start value");
363 ExprAST
*End
= ParseExpression();
364 if (End
== 0) return 0;
366 // The step value is optional.
370 Step
= ParseExpression();
371 if (Step
== 0) return 0;
374 if (CurTok
!= tok_in
)
375 return Error("expected 'in' after for");
376 getNextToken(); // eat 'in'.
378 ExprAST
*Body
= ParseExpression();
379 if (Body
== 0) return 0;
381 return new ForExprAST(IdName
, Start
, End
, Step
, Body
);
384 /// varexpr ::= 'var' identifier ('=' expression)?
385 // (',' identifier ('=' expression)?)* 'in' expression
386 static ExprAST
*ParseVarExpr() {
387 getNextToken(); // eat the var.
389 std::vector
<std::pair
<std::string
, ExprAST
*> > VarNames
;
391 // At least one variable name is required.
392 if (CurTok
!= tok_identifier
)
393 return Error("expected identifier after var");
396 std::string Name
= IdentifierStr
;
397 getNextToken(); // eat identifier.
399 // Read the optional initializer.
402 getNextToken(); // eat the '='.
404 Init
= ParseExpression();
405 if (Init
== 0) return 0;
408 VarNames
.push_back(std::make_pair(Name
, Init
));
410 // End of var list, exit loop.
411 if (CurTok
!= ',') break;
412 getNextToken(); // eat the ','.
414 if (CurTok
!= tok_identifier
)
415 return Error("expected identifier list after var");
418 // At this point, we have to have 'in'.
419 if (CurTok
!= tok_in
)
420 return Error("expected 'in' keyword after 'var'");
421 getNextToken(); // eat 'in'.
423 ExprAST
*Body
= ParseExpression();
424 if (Body
== 0) return 0;
426 return new VarExprAST(VarNames
, Body
);
431 /// ::= identifierexpr
437 static ExprAST
*ParsePrimary() {
439 default: return Error("unknown token when expecting an expression");
440 case tok_identifier
: return ParseIdentifierExpr();
441 case tok_number
: return ParseNumberExpr();
442 case '(': return ParseParenExpr();
443 case tok_if
: return ParseIfExpr();
444 case tok_for
: return ParseForExpr();
445 case tok_var
: return ParseVarExpr();
452 static ExprAST
*ParseUnary() {
453 // If the current token is not an operator, it must be a primary expr.
454 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
455 return ParsePrimary();
457 // If this is a unary operator, read it.
460 if (ExprAST
*Operand
= ParseUnary())
461 return new UnaryExprAST(Opc
, Operand
);
467 static ExprAST
*ParseBinOpRHS(int ExprPrec
, ExprAST
*LHS
) {
468 // If this is a binop, find its precedence.
470 int TokPrec
= GetTokPrecedence();
472 // If this is a binop that binds at least as tightly as the current binop,
473 // consume it, otherwise we are done.
474 if (TokPrec
< ExprPrec
)
477 // Okay, we know this is a binop.
479 getNextToken(); // eat binop
481 // Parse the unary expression after the binary operator.
482 ExprAST
*RHS
= ParseUnary();
485 // If BinOp binds less tightly with RHS than the operator after RHS, let
486 // the pending operator take RHS as its LHS.
487 int NextPrec
= GetTokPrecedence();
488 if (TokPrec
< NextPrec
) {
489 RHS
= ParseBinOpRHS(TokPrec
+1, RHS
);
490 if (RHS
== 0) return 0;
494 LHS
= new BinaryExprAST(BinOp
, LHS
, RHS
);
499 /// ::= unary binoprhs
501 static ExprAST
*ParseExpression() {
502 ExprAST
*LHS
= ParseUnary();
505 return ParseBinOpRHS(0, LHS
);
509 /// ::= id '(' id* ')'
510 /// ::= binary LETTER number? (id, id)
511 /// ::= unary LETTER (id)
512 static PrototypeAST
*ParsePrototype() {
515 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
516 unsigned BinaryPrecedence
= 30;
520 return ErrorP("Expected function name in prototype");
522 FnName
= IdentifierStr
;
528 if (!isascii(CurTok
))
529 return ErrorP("Expected unary operator");
531 FnName
+= (char)CurTok
;
537 if (!isascii(CurTok
))
538 return ErrorP("Expected binary operator");
540 FnName
+= (char)CurTok
;
544 // Read the precedence if present.
545 if (CurTok
== tok_number
) {
546 if (NumVal
< 1 || NumVal
> 100)
547 return ErrorP("Invalid precedecnce: must be 1..100");
548 BinaryPrecedence
= (unsigned)NumVal
;
555 return ErrorP("Expected '(' in prototype");
557 std::vector
<std::string
> ArgNames
;
558 while (getNextToken() == tok_identifier
)
559 ArgNames
.push_back(IdentifierStr
);
561 return ErrorP("Expected ')' in prototype");
564 getNextToken(); // eat ')'.
566 // Verify right number of names for operator.
567 if (Kind
&& ArgNames
.size() != Kind
)
568 return ErrorP("Invalid number of operands for operator");
570 return new PrototypeAST(FnName
, ArgNames
, Kind
!= 0, BinaryPrecedence
);
573 /// definition ::= 'def' prototype expression
574 static FunctionAST
*ParseDefinition() {
575 getNextToken(); // eat def.
576 PrototypeAST
*Proto
= ParsePrototype();
577 if (Proto
== 0) return 0;
579 if (ExprAST
*E
= ParseExpression())
580 return new FunctionAST(Proto
, E
);
584 /// toplevelexpr ::= expression
585 static FunctionAST
*ParseTopLevelExpr() {
586 if (ExprAST
*E
= ParseExpression()) {
587 // Make an anonymous proto.
588 PrototypeAST
*Proto
= new PrototypeAST("", std::vector
<std::string
>());
589 return new FunctionAST(Proto
, E
);
594 /// external ::= 'extern' prototype
595 static PrototypeAST
*ParseExtern() {
596 getNextToken(); // eat extern.
597 return ParsePrototype();
600 //===----------------------------------------------------------------------===//
602 //===----------------------------------------------------------------------===//
604 static Module
*TheModule
;
605 static IRBuilder
<> Builder
;
606 static std::map
<std::string
, AllocaInst
*> NamedValues
;
607 static FunctionPassManager
*TheFPM
;
609 Value
*ErrorV(const char *Str
) { Error(Str
); return 0; }
611 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
612 /// the function. This is used for mutable variables etc.
613 static AllocaInst
*CreateEntryBlockAlloca(Function
*TheFunction
,
614 const std::string
&VarName
) {
615 IRBuilder
<> TmpB(&TheFunction
->getEntryBlock(),
616 TheFunction
->getEntryBlock().begin());
617 return TmpB
.CreateAlloca(Type::DoubleTy
, 0, VarName
.c_str());
621 Value
*NumberExprAST::Codegen() {
622 return ConstantFP::get(APFloat(Val
));
625 Value
*VariableExprAST::Codegen() {
626 // Look this variable up in the function.
627 Value
*V
= NamedValues
[Name
];
628 if (V
== 0) return ErrorV("Unknown variable name");
631 return Builder
.CreateLoad(V
, Name
.c_str());
634 Value
*UnaryExprAST::Codegen() {
635 Value
*OperandV
= Operand
->Codegen();
636 if (OperandV
== 0) return 0;
638 Function
*F
= TheModule
->getFunction(std::string("unary")+Opcode
);
640 return ErrorV("Unknown unary operator");
642 return Builder
.CreateCall(F
, OperandV
, "unop");
646 Value
*BinaryExprAST::Codegen() {
647 // Special case '=' because we don't want to emit the LHS as an expression.
649 // Assignment requires the LHS to be an identifier.
650 VariableExprAST
*LHSE
= dynamic_cast<VariableExprAST
*>(LHS
);
652 return ErrorV("destination of '=' must be a variable");
654 Value
*Val
= RHS
->Codegen();
655 if (Val
== 0) return 0;
658 Value
*Variable
= NamedValues
[LHSE
->getName()];
659 if (Variable
== 0) return ErrorV("Unknown variable name");
661 Builder
.CreateStore(Val
, Variable
);
666 Value
*L
= LHS
->Codegen();
667 Value
*R
= RHS
->Codegen();
668 if (L
== 0 || R
== 0) return 0;
671 case '+': return Builder
.CreateAdd(L
, R
, "addtmp");
672 case '-': return Builder
.CreateSub(L
, R
, "subtmp");
673 case '*': return Builder
.CreateMul(L
, R
, "multmp");
675 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
676 // Convert bool 0/1 to double 0.0 or 1.0
677 return Builder
.CreateUIToFP(L
, Type::DoubleTy
, "booltmp");
681 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
683 Function
*F
= TheModule
->getFunction(std::string("binary")+Op
);
684 assert(F
&& "binary operator not found!");
686 Value
*Ops
[] = { L
, R
};
687 return Builder
.CreateCall(F
, Ops
, Ops
+2, "binop");
690 Value
*CallExprAST::Codegen() {
691 // Look up the name in the global module table.
692 Function
*CalleeF
= TheModule
->getFunction(Callee
);
694 return ErrorV("Unknown function referenced");
696 // If argument mismatch error.
697 if (CalleeF
->arg_size() != Args
.size())
698 return ErrorV("Incorrect # arguments passed");
700 std::vector
<Value
*> ArgsV
;
701 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
702 ArgsV
.push_back(Args
[i
]->Codegen());
703 if (ArgsV
.back() == 0) return 0;
706 return Builder
.CreateCall(CalleeF
, ArgsV
.begin(), ArgsV
.end(), "calltmp");
709 Value
*IfExprAST::Codegen() {
710 Value
*CondV
= Cond
->Codegen();
711 if (CondV
== 0) return 0;
713 // Convert condition to a bool by comparing equal to 0.0.
714 CondV
= Builder
.CreateFCmpONE(CondV
,
715 ConstantFP::get(APFloat(0.0)),
718 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
720 // Create blocks for the then and else cases. Insert the 'then' block at the
721 // end of the function.
722 BasicBlock
*ThenBB
= BasicBlock::Create("then", TheFunction
);
723 BasicBlock
*ElseBB
= BasicBlock::Create("else");
724 BasicBlock
*MergeBB
= BasicBlock::Create("ifcont");
726 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
729 Builder
.SetInsertPoint(ThenBB
);
731 Value
*ThenV
= Then
->Codegen();
732 if (ThenV
== 0) return 0;
734 Builder
.CreateBr(MergeBB
);
735 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
736 ThenBB
= Builder
.GetInsertBlock();
739 TheFunction
->getBasicBlockList().push_back(ElseBB
);
740 Builder
.SetInsertPoint(ElseBB
);
742 Value
*ElseV
= Else
->Codegen();
743 if (ElseV
== 0) return 0;
745 Builder
.CreateBr(MergeBB
);
746 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
747 ElseBB
= Builder
.GetInsertBlock();
750 TheFunction
->getBasicBlockList().push_back(MergeBB
);
751 Builder
.SetInsertPoint(MergeBB
);
752 PHINode
*PN
= Builder
.CreatePHI(Type::DoubleTy
, "iftmp");
754 PN
->addIncoming(ThenV
, ThenBB
);
755 PN
->addIncoming(ElseV
, ElseBB
);
759 Value
*ForExprAST::Codegen() {
761 // var = alloca double
764 // store start -> var
775 // nextvar = curvar + step
776 // store nextvar -> var
777 // br endcond, loop, endloop
780 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
782 // Create an alloca for the variable in the entry block.
783 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
785 // Emit the start code first, without 'variable' in scope.
786 Value
*StartVal
= Start
->Codegen();
787 if (StartVal
== 0) return 0;
789 // Store the value into the alloca.
790 Builder
.CreateStore(StartVal
, Alloca
);
792 // Make the new basic block for the loop header, inserting after current
794 BasicBlock
*LoopBB
= BasicBlock::Create("loop", TheFunction
);
796 // Insert an explicit fall through from the current block to the LoopBB.
797 Builder
.CreateBr(LoopBB
);
799 // Start insertion in LoopBB.
800 Builder
.SetInsertPoint(LoopBB
);
802 // Within the loop, the variable is defined equal to the PHI node. If it
803 // shadows an existing variable, we have to restore it, so save it now.
804 AllocaInst
*OldVal
= NamedValues
[VarName
];
805 NamedValues
[VarName
] = Alloca
;
807 // Emit the body of the loop. This, like any other expr, can change the
808 // current BB. Note that we ignore the value computed by the body, but don't
810 if (Body
->Codegen() == 0)
813 // Emit the step value.
816 StepVal
= Step
->Codegen();
817 if (StepVal
== 0) return 0;
819 // If not specified, use 1.0.
820 StepVal
= ConstantFP::get(APFloat(1.0));
823 // Compute the end condition.
824 Value
*EndCond
= End
->Codegen();
825 if (EndCond
== 0) return EndCond
;
827 // Reload, increment, and restore the alloca. This handles the case where
828 // the body of the loop mutates the variable.
829 Value
*CurVar
= Builder
.CreateLoad(Alloca
, VarName
.c_str());
830 Value
*NextVar
= Builder
.CreateAdd(CurVar
, StepVal
, "nextvar");
831 Builder
.CreateStore(NextVar
, Alloca
);
833 // Convert condition to a bool by comparing equal to 0.0.
834 EndCond
= Builder
.CreateFCmpONE(EndCond
,
835 ConstantFP::get(APFloat(0.0)),
838 // Create the "after loop" block and insert it.
839 BasicBlock
*AfterBB
= BasicBlock::Create("afterloop", TheFunction
);
841 // Insert the conditional branch into the end of LoopEndBB.
842 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
844 // Any new code will be inserted in AfterBB.
845 Builder
.SetInsertPoint(AfterBB
);
847 // Restore the unshadowed variable.
849 NamedValues
[VarName
] = OldVal
;
851 NamedValues
.erase(VarName
);
854 // for expr always returns 0.0.
855 return Constant::getNullValue(Type::DoubleTy
);
858 Value
*VarExprAST::Codegen() {
859 std::vector
<AllocaInst
*> OldBindings
;
861 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
863 // Register all variables and emit their initializer.
864 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
) {
865 const std::string
&VarName
= VarNames
[i
].first
;
866 ExprAST
*Init
= VarNames
[i
].second
;
868 // Emit the initializer before adding the variable to scope, this prevents
869 // the initializer from referencing the variable itself, and permits stuff
872 // var a = a in ... # refers to outer 'a'.
875 InitVal
= Init
->Codegen();
876 if (InitVal
== 0) return 0;
877 } else { // If not specified, use 0.0.
878 InitVal
= ConstantFP::get(APFloat(0.0));
881 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
882 Builder
.CreateStore(InitVal
, Alloca
);
884 // Remember the old variable binding so that we can restore the binding when
886 OldBindings
.push_back(NamedValues
[VarName
]);
888 // Remember this binding.
889 NamedValues
[VarName
] = Alloca
;
892 // Codegen the body, now that all vars are in scope.
893 Value
*BodyVal
= Body
->Codegen();
894 if (BodyVal
== 0) return 0;
896 // Pop all our variables from scope.
897 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
)
898 NamedValues
[VarNames
[i
].first
] = OldBindings
[i
];
900 // Return the body computation.
905 Function
*PrototypeAST::Codegen() {
906 // Make the function type: double(double,double) etc.
907 std::vector
<const Type
*> Doubles(Args
.size(), Type::DoubleTy
);
908 FunctionType
*FT
= FunctionType::get(Type::DoubleTy
, Doubles
, false);
910 Function
*F
= Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
);
912 // If F conflicted, there was already something named 'Name'. If it has a
913 // body, don't allow redefinition or reextern.
914 if (F
->getName() != Name
) {
915 // Delete the one we just made and get the existing one.
916 F
->eraseFromParent();
917 F
= TheModule
->getFunction(Name
);
919 // If F already has a body, reject this.
921 ErrorF("redefinition of function");
925 // If F took a different number of args, reject.
926 if (F
->arg_size() != Args
.size()) {
927 ErrorF("redefinition of function with different # args");
932 // Set names for all arguments.
934 for (Function::arg_iterator AI
= F
->arg_begin(); Idx
!= Args
.size();
936 AI
->setName(Args
[Idx
]);
941 /// CreateArgumentAllocas - Create an alloca for each argument and register the
942 /// argument in the symbol table so that references to it will succeed.
943 void PrototypeAST::CreateArgumentAllocas(Function
*F
) {
944 Function::arg_iterator AI
= F
->arg_begin();
945 for (unsigned Idx
= 0, e
= Args
.size(); Idx
!= e
; ++Idx
, ++AI
) {
946 // Create an alloca for this variable.
947 AllocaInst
*Alloca
= CreateEntryBlockAlloca(F
, Args
[Idx
]);
949 // Store the initial value into the alloca.
950 Builder
.CreateStore(AI
, Alloca
);
952 // Add arguments to variable symbol table.
953 NamedValues
[Args
[Idx
]] = Alloca
;
958 Function
*FunctionAST::Codegen() {
961 Function
*TheFunction
= Proto
->Codegen();
962 if (TheFunction
== 0)
965 // If this is an operator, install it.
966 if (Proto
->isBinaryOp())
967 BinopPrecedence
[Proto
->getOperatorName()] = Proto
->getBinaryPrecedence();
969 // Create a new basic block to start insertion into.
970 BasicBlock
*BB
= BasicBlock::Create("entry", TheFunction
);
971 Builder
.SetInsertPoint(BB
);
973 // Add all arguments to the symbol table and create their allocas.
974 Proto
->CreateArgumentAllocas(TheFunction
);
976 if (Value
*RetVal
= Body
->Codegen()) {
977 // Finish off the function.
978 Builder
.CreateRet(RetVal
);
980 // Validate the generated code, checking for consistency.
981 verifyFunction(*TheFunction
);
983 // Optimize the function.
984 TheFPM
->run(*TheFunction
);
989 // Error reading body, remove function.
990 TheFunction
->eraseFromParent();
992 if (Proto
->isBinaryOp())
993 BinopPrecedence
.erase(Proto
->getOperatorName());
997 //===----------------------------------------------------------------------===//
998 // Top-Level parsing and JIT Driver
999 //===----------------------------------------------------------------------===//
1001 static ExecutionEngine
*TheExecutionEngine
;
1003 static void HandleDefinition() {
1004 if (FunctionAST
*F
= ParseDefinition()) {
1005 if (Function
*LF
= F
->Codegen()) {
1006 fprintf(stderr
, "Read function definition:");
1010 // Skip token for error recovery.
1015 static void HandleExtern() {
1016 if (PrototypeAST
*P
= ParseExtern()) {
1017 if (Function
*F
= P
->Codegen()) {
1018 fprintf(stderr
, "Read extern: ");
1022 // Skip token for error recovery.
1027 static void HandleTopLevelExpression() {
1028 // Evaluate a top level expression into an anonymous function.
1029 if (FunctionAST
*F
= ParseTopLevelExpr()) {
1030 if (Function
*LF
= F
->Codegen()) {
1031 // JIT the function, returning a function pointer.
1032 void *FPtr
= TheExecutionEngine
->getPointerToFunction(LF
);
1034 // Cast it to the right type (takes no arguments, returns a double) so we
1035 // can call it as a native function.
1036 double (*FP
)() = (double (*)())(intptr_t)FPtr
;
1037 fprintf(stderr
, "Evaluated to %f\n", FP());
1040 // Skip token for error recovery.
1045 /// top ::= definition | external | expression | ';'
1046 static void MainLoop() {
1048 fprintf(stderr
, "ready> ");
1050 case tok_eof
: return;
1051 case ';': getNextToken(); break; // ignore top level semicolons.
1052 case tok_def
: HandleDefinition(); break;
1053 case tok_extern
: HandleExtern(); break;
1054 default: HandleTopLevelExpression(); break;
1061 //===----------------------------------------------------------------------===//
1062 // "Library" functions that can be "extern'd" from user code.
1063 //===----------------------------------------------------------------------===//
1065 /// putchard - putchar that takes a double and returns 0.
1067 double putchard(double X
) {
1072 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1074 double printd(double X
) {
1079 //===----------------------------------------------------------------------===//
1080 // Main driver code.
1081 //===----------------------------------------------------------------------===//
1084 // Install standard binary operators.
1085 // 1 is lowest precedence.
1086 BinopPrecedence
['='] = 2;
1087 BinopPrecedence
['<'] = 10;
1088 BinopPrecedence
['+'] = 20;
1089 BinopPrecedence
['-'] = 20;
1090 BinopPrecedence
['*'] = 40; // highest.
1092 // Prime the first token.
1093 fprintf(stderr
, "ready> ");
1096 // Make the module, which holds all the code.
1097 TheModule
= new Module("my cool jit");
1100 TheExecutionEngine
= ExecutionEngine::create(TheModule
);
1103 ExistingModuleProvider
OurModuleProvider(TheModule
);
1104 FunctionPassManager
OurFPM(&OurModuleProvider
);
1106 // Set up the optimizer pipeline. Start with registering info about how the
1107 // target lays out data structures.
1108 OurFPM
.add(new TargetData(*TheExecutionEngine
->getTargetData()));
1109 // Promote allocas to registers.
1110 OurFPM
.add(createPromoteMemoryToRegisterPass());
1111 // Do simple "peephole" optimizations and bit-twiddling optzns.
1112 OurFPM
.add(createInstructionCombiningPass());
1113 // Reassociate expressions.
1114 OurFPM
.add(createReassociatePass());
1115 // Eliminate Common SubExpressions.
1116 OurFPM
.add(createGVNPass());
1117 // Simplify the control flow graph (deleting unreachable blocks, etc).
1118 OurFPM
.add(createCFGSimplificationPass());
1120 // Set the global so the code gen can use this.
1123 // Run the main "interpreter loop" now.
1128 // Print out all of the generated code.
1131 } // Free module provider (and thus the module) and pass manager.