1 #include "llvm/ADT/APFloat.h"
2 #include "llvm/ADT/STLExtras.h"
3 #include "llvm/IR/BasicBlock.h"
4 #include "llvm/IR/Constants.h"
5 #include "llvm/IR/DerivedTypes.h"
6 #include "llvm/IR/Function.h"
7 #include "llvm/IR/Instructions.h"
8 #include "llvm/IR/IRBuilder.h"
9 #include "llvm/IR/LLVMContext.h"
10 #include "llvm/IR/Module.h"
11 #include "llvm/IR/Type.h"
12 #include "llvm/IR/Verifier.h"
13 #include "llvm/Support/TargetSelect.h"
14 #include "llvm/Target/TargetMachine.h"
15 #include "KaleidoscopeJIT.h"
29 using namespace llvm::orc
;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
36 // of these for known things.
63 static std::string IdentifierStr
; // Filled in if tok_identifier
64 static double NumVal
; // Filled in if tok_number
66 /// gettok - Return the next token from standard input.
68 static int LastChar
= ' ';
70 // Skip any whitespace.
71 while (isspace(LastChar
))
74 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
75 IdentifierStr
= LastChar
;
76 while (isalnum((LastChar
= getchar())))
77 IdentifierStr
+= LastChar
;
79 if (IdentifierStr
== "def")
81 if (IdentifierStr
== "extern")
83 if (IdentifierStr
== "if")
85 if (IdentifierStr
== "then")
87 if (IdentifierStr
== "else")
89 if (IdentifierStr
== "for")
91 if (IdentifierStr
== "in")
93 if (IdentifierStr
== "binary")
95 if (IdentifierStr
== "unary")
97 if (IdentifierStr
== "var")
99 return tok_identifier
;
102 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
106 LastChar
= getchar();
107 } while (isdigit(LastChar
) || LastChar
== '.');
109 NumVal
= strtod(NumStr
.c_str(), nullptr);
113 if (LastChar
== '#') {
114 // Comment until end of line.
116 LastChar
= getchar();
117 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
123 // Check for end of file. Don't eat the EOF.
127 // Otherwise, just return the character as its ascii value.
128 int ThisChar
= LastChar
;
129 LastChar
= getchar();
133 //===----------------------------------------------------------------------===//
134 // Abstract Syntax Tree (aka Parse Tree)
135 //===----------------------------------------------------------------------===//
137 /// ExprAST - Base class for all expression nodes.
140 virtual ~ExprAST() = default;
142 virtual Value
*codegen() = 0;
145 /// NumberExprAST - Expression class for numeric literals like "1.0".
146 class NumberExprAST
: public ExprAST
{
150 NumberExprAST(double Val
) : Val(Val
) {}
152 Value
*codegen() override
;
155 /// VariableExprAST - Expression class for referencing a variable, like "a".
156 class VariableExprAST
: public ExprAST
{
160 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
162 Value
*codegen() override
;
163 const std::string
&getName() const { return Name
; }
166 /// UnaryExprAST - Expression class for a unary operator.
167 class UnaryExprAST
: public ExprAST
{
169 std::unique_ptr
<ExprAST
> Operand
;
172 UnaryExprAST(char Opcode
, std::unique_ptr
<ExprAST
> Operand
)
173 : Opcode(Opcode
), Operand(std::move(Operand
)) {}
175 Value
*codegen() override
;
178 /// BinaryExprAST - Expression class for a binary operator.
179 class BinaryExprAST
: public ExprAST
{
181 std::unique_ptr
<ExprAST
> LHS
, RHS
;
184 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
185 std::unique_ptr
<ExprAST
> RHS
)
186 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
188 Value
*codegen() override
;
191 /// CallExprAST - Expression class for function calls.
192 class CallExprAST
: public ExprAST
{
194 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
197 CallExprAST(const std::string
&Callee
,
198 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
199 : Callee(Callee
), Args(std::move(Args
)) {}
201 Value
*codegen() override
;
204 /// IfExprAST - Expression class for if/then/else.
205 class IfExprAST
: public ExprAST
{
206 std::unique_ptr
<ExprAST
> Cond
, Then
, Else
;
209 IfExprAST(std::unique_ptr
<ExprAST
> Cond
, std::unique_ptr
<ExprAST
> Then
,
210 std::unique_ptr
<ExprAST
> Else
)
211 : Cond(std::move(Cond
)), Then(std::move(Then
)), Else(std::move(Else
)) {}
213 Value
*codegen() override
;
216 /// ForExprAST - Expression class for for/in.
217 class ForExprAST
: public ExprAST
{
219 std::unique_ptr
<ExprAST
> Start
, End
, Step
, Body
;
222 ForExprAST(const std::string
&VarName
, std::unique_ptr
<ExprAST
> Start
,
223 std::unique_ptr
<ExprAST
> End
, std::unique_ptr
<ExprAST
> Step
,
224 std::unique_ptr
<ExprAST
> Body
)
225 : VarName(VarName
), Start(std::move(Start
)), End(std::move(End
)),
226 Step(std::move(Step
)), Body(std::move(Body
)) {}
228 Value
*codegen() override
;
231 /// VarExprAST - Expression class for var/in
232 class VarExprAST
: public ExprAST
{
233 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
;
234 std::unique_ptr
<ExprAST
> Body
;
238 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
,
239 std::unique_ptr
<ExprAST
> Body
)
240 : VarNames(std::move(VarNames
)), Body(std::move(Body
)) {}
242 Value
*codegen() override
;
245 /// PrototypeAST - This class represents the "prototype" for a function,
246 /// which captures its name, and its argument names (thus implicitly the number
247 /// of arguments the function takes), as well as if it is an operator.
250 std::vector
<std::string
> Args
;
252 unsigned Precedence
; // Precedence if a binary op.
255 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
,
256 bool IsOperator
= false, unsigned Prec
= 0)
257 : Name(Name
), Args(std::move(Args
)), IsOperator(IsOperator
),
261 const std::string
&getName() const { return Name
; }
263 bool isUnaryOp() const { return IsOperator
&& Args
.size() == 1; }
264 bool isBinaryOp() const { return IsOperator
&& Args
.size() == 2; }
266 char getOperatorName() const {
267 assert(isUnaryOp() || isBinaryOp());
268 return Name
[Name
.size() - 1];
271 unsigned getBinaryPrecedence() const { return Precedence
; }
274 //===----------------------------------------------------------------------===//
276 //===----------------------------------------------------------------------===//
278 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
279 /// token the parser is looking at. getNextToken reads another token from the
280 /// lexer and updates CurTok with its results.
282 static int getNextToken() { return CurTok
= gettok(); }
284 /// BinopPrecedence - This holds the precedence for each binary operator that is
286 static std::map
<char, int> BinopPrecedence
;
288 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
289 static int GetTokPrecedence() {
290 if (!isascii(CurTok
))
293 // Make sure it's a declared binop.
294 int TokPrec
= BinopPrecedence
[CurTok
];
300 /// LogError* - These are little helper functions for error handling.
301 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
302 fprintf(stderr
, "Error: %s\n", Str
);
306 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
311 static std::unique_ptr
<ExprAST
> ParseExpression();
313 /// numberexpr ::= number
314 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
315 auto Result
= std::make_unique
<NumberExprAST
>(NumVal
);
316 getNextToken(); // consume the number
317 return std::move(Result
);
320 /// parenexpr ::= '(' expression ')'
321 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
322 getNextToken(); // eat (.
323 auto V
= ParseExpression();
328 return LogError("expected ')'");
329 getNextToken(); // eat ).
335 /// ::= identifier '(' expression* ')'
336 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
337 std::string IdName
= IdentifierStr
;
339 getNextToken(); // eat identifier.
341 if (CurTok
!= '(') // Simple variable ref.
342 return std::make_unique
<VariableExprAST
>(IdName
);
345 getNextToken(); // eat (
346 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
349 if (auto Arg
= ParseExpression())
350 Args
.push_back(std::move(Arg
));
358 return LogError("Expected ')' or ',' in argument list");
366 return std::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
369 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
370 static std::unique_ptr
<ExprAST
> ParseIfExpr() {
371 getNextToken(); // eat the if.
374 auto Cond
= ParseExpression();
378 if (CurTok
!= tok_then
)
379 return LogError("expected then");
380 getNextToken(); // eat the then
382 auto Then
= ParseExpression();
386 if (CurTok
!= tok_else
)
387 return LogError("expected else");
391 auto Else
= ParseExpression();
395 return std::make_unique
<IfExprAST
>(std::move(Cond
), std::move(Then
),
399 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
400 static std::unique_ptr
<ExprAST
> ParseForExpr() {
401 getNextToken(); // eat the for.
403 if (CurTok
!= tok_identifier
)
404 return LogError("expected identifier after for");
406 std::string IdName
= IdentifierStr
;
407 getNextToken(); // eat identifier.
410 return LogError("expected '=' after for");
411 getNextToken(); // eat '='.
413 auto Start
= ParseExpression();
417 return LogError("expected ',' after for start value");
420 auto End
= ParseExpression();
424 // The step value is optional.
425 std::unique_ptr
<ExprAST
> Step
;
428 Step
= ParseExpression();
433 if (CurTok
!= tok_in
)
434 return LogError("expected 'in' after for");
435 getNextToken(); // eat 'in'.
437 auto Body
= ParseExpression();
441 return std::make_unique
<ForExprAST
>(IdName
, std::move(Start
), std::move(End
),
442 std::move(Step
), std::move(Body
));
445 /// varexpr ::= 'var' identifier ('=' expression)?
446 // (',' identifier ('=' expression)?)* 'in' expression
447 static std::unique_ptr
<ExprAST
> ParseVarExpr() {
448 getNextToken(); // eat the var.
450 std::vector
<std::pair
<std::string
, std::unique_ptr
<ExprAST
>>> VarNames
;
452 // At least one variable name is required.
453 if (CurTok
!= tok_identifier
)
454 return LogError("expected identifier after var");
457 std::string Name
= IdentifierStr
;
458 getNextToken(); // eat identifier.
460 // Read the optional initializer.
461 std::unique_ptr
<ExprAST
> Init
= nullptr;
463 getNextToken(); // eat the '='.
465 Init
= ParseExpression();
470 VarNames
.push_back(std::make_pair(Name
, std::move(Init
)));
472 // End of var list, exit loop.
475 getNextToken(); // eat the ','.
477 if (CurTok
!= tok_identifier
)
478 return LogError("expected identifier list after var");
481 // At this point, we have to have 'in'.
482 if (CurTok
!= tok_in
)
483 return LogError("expected 'in' keyword after 'var'");
484 getNextToken(); // eat 'in'.
486 auto Body
= ParseExpression();
490 return std::make_unique
<VarExprAST
>(std::move(VarNames
), std::move(Body
));
494 /// ::= identifierexpr
500 static std::unique_ptr
<ExprAST
> ParsePrimary() {
503 return LogError("unknown token when expecting an expression");
505 return ParseIdentifierExpr();
507 return ParseNumberExpr();
509 return ParseParenExpr();
511 return ParseIfExpr();
513 return ParseForExpr();
515 return ParseVarExpr();
522 static std::unique_ptr
<ExprAST
> ParseUnary() {
523 // If the current token is not an operator, it must be a primary expr.
524 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
525 return ParsePrimary();
527 // If this is a unary operator, read it.
530 if (auto Operand
= ParseUnary())
531 return std::make_unique
<UnaryExprAST
>(Opc
, std::move(Operand
));
537 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
538 std::unique_ptr
<ExprAST
> LHS
) {
539 // If this is a binop, find its precedence.
541 int TokPrec
= GetTokPrecedence();
543 // If this is a binop that binds at least as tightly as the current binop,
544 // consume it, otherwise we are done.
545 if (TokPrec
< ExprPrec
)
548 // Okay, we know this is a binop.
550 getNextToken(); // eat binop
552 // Parse the unary expression after the binary operator.
553 auto RHS
= ParseUnary();
557 // If BinOp binds less tightly with RHS than the operator after RHS, let
558 // the pending operator take RHS as its LHS.
559 int NextPrec
= GetTokPrecedence();
560 if (TokPrec
< NextPrec
) {
561 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
568 std::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
), std::move(RHS
));
573 /// ::= unary binoprhs
575 static std::unique_ptr
<ExprAST
> ParseExpression() {
576 auto LHS
= ParseUnary();
580 return ParseBinOpRHS(0, std::move(LHS
));
584 /// ::= id '(' id* ')'
585 /// ::= binary LETTER number? (id, id)
586 /// ::= unary LETTER (id)
587 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
590 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
591 unsigned BinaryPrecedence
= 30;
595 return LogErrorP("Expected function name in prototype");
597 FnName
= IdentifierStr
;
603 if (!isascii(CurTok
))
604 return LogErrorP("Expected unary operator");
606 FnName
+= (char)CurTok
;
612 if (!isascii(CurTok
))
613 return LogErrorP("Expected binary operator");
615 FnName
+= (char)CurTok
;
619 // Read the precedence if present.
620 if (CurTok
== tok_number
) {
621 if (NumVal
< 1 || NumVal
> 100)
622 return LogErrorP("Invalid precedecnce: must be 1..100");
623 BinaryPrecedence
= (unsigned)NumVal
;
630 return LogErrorP("Expected '(' in prototype");
632 std::vector
<std::string
> ArgNames
;
633 while (getNextToken() == tok_identifier
)
634 ArgNames
.push_back(IdentifierStr
);
636 return LogErrorP("Expected ')' in prototype");
639 getNextToken(); // eat ')'.
641 // Verify right number of names for operator.
642 if (Kind
&& ArgNames
.size() != Kind
)
643 return LogErrorP("Invalid number of operands for operator");
645 return std::make_unique
<PrototypeAST
>(FnName
, ArgNames
, Kind
!= 0,
649 /// definition ::= 'def' prototype expression
650 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
651 getNextToken(); // eat def.
652 auto Proto
= ParsePrototype();
656 if (auto E
= ParseExpression())
657 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
661 /// toplevelexpr ::= expression
662 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
663 if (auto E
= ParseExpression()) {
664 // Make an anonymous proto.
665 auto Proto
= std::make_unique
<PrototypeAST
>("__anon_expr",
666 std::vector
<std::string
>());
667 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
672 /// external ::= 'extern' prototype
673 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
674 getNextToken(); // eat extern.
675 return ParsePrototype();
678 //===----------------------------------------------------------------------===//
680 //===----------------------------------------------------------------------===//
682 static std::unique_ptr
<KaleidoscopeJIT
> TheJIT
;
683 static std::unique_ptr
<LLVMContext
> TheContext
;
684 static std::unique_ptr
<IRBuilder
<>> Builder
;
685 static std::unique_ptr
<Module
> TheModule
;
686 static std::map
<std::string
, AllocaInst
*> NamedValues
;
687 static std::map
<std::string
, std::unique_ptr
<PrototypeAST
>> FunctionProtos
;
688 static ExitOnError ExitOnErr
;
690 Value
*LogErrorV(const char *Str
) {
695 Function
*getFunction(std::string Name
) {
696 // First, see if the function has already been added to the current module.
697 if (auto *F
= TheModule
->getFunction(Name
))
700 // If not, check whether we can codegen the declaration from some existing
702 auto FI
= FunctionProtos
.find(Name
);
703 if (FI
!= FunctionProtos
.end())
704 return FI
->second
->codegen();
706 // If no existing prototype exists, return null.
710 /// CreateEntryBlockAlloca - Create an alloca instruction in the entry block of
711 /// the function. This is used for mutable variables etc.
712 static AllocaInst
*CreateEntryBlockAlloca(Function
*TheFunction
,
714 IRBuilder
<> TmpB(&TheFunction
->getEntryBlock(),
715 TheFunction
->getEntryBlock().begin());
716 return TmpB
.CreateAlloca(Type::getDoubleTy(*TheContext
), nullptr, VarName
);
719 Value
*NumberExprAST::codegen() {
720 return ConstantFP::get(*TheContext
, APFloat(Val
));
723 Value
*VariableExprAST::codegen() {
724 // Look this variable up in the function.
725 Value
*V
= NamedValues
[Name
];
727 return LogErrorV("Unknown variable name");
730 return Builder
->CreateLoad(Type::getDoubleTy(*TheContext
), V
, Name
.c_str());
733 Value
*UnaryExprAST::codegen() {
734 Value
*OperandV
= Operand
->codegen();
738 Function
*F
= getFunction(std::string("unary") + Opcode
);
740 return LogErrorV("Unknown unary operator");
742 return Builder
->CreateCall(F
, OperandV
, "unop");
745 Value
*BinaryExprAST::codegen() {
746 // Special case '=' because we don't want to emit the LHS as an expression.
748 // Assignment requires the LHS to be an identifier.
749 // This assume we're building without RTTI because LLVM builds that way by
750 // default. If you build LLVM with RTTI this can be changed to a
751 // dynamic_cast for automatic error checking.
752 VariableExprAST
*LHSE
= static_cast<VariableExprAST
*>(LHS
.get());
754 return LogErrorV("destination of '=' must be a variable");
756 Value
*Val
= RHS
->codegen();
761 Value
*Variable
= NamedValues
[LHSE
->getName()];
763 return LogErrorV("Unknown variable name");
765 Builder
->CreateStore(Val
, Variable
);
769 Value
*L
= LHS
->codegen();
770 Value
*R
= RHS
->codegen();
776 return Builder
->CreateFAdd(L
, R
, "addtmp");
778 return Builder
->CreateFSub(L
, R
, "subtmp");
780 return Builder
->CreateFMul(L
, R
, "multmp");
782 L
= Builder
->CreateFCmpULT(L
, R
, "cmptmp");
783 // Convert bool 0/1 to double 0.0 or 1.0
784 return Builder
->CreateUIToFP(L
, Type::getDoubleTy(*TheContext
), "booltmp");
789 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
791 Function
*F
= getFunction(std::string("binary") + Op
);
792 assert(F
&& "binary operator not found!");
794 Value
*Ops
[] = {L
, R
};
795 return Builder
->CreateCall(F
, Ops
, "binop");
798 Value
*CallExprAST::codegen() {
799 // Look up the name in the global module table.
800 Function
*CalleeF
= getFunction(Callee
);
802 return LogErrorV("Unknown function referenced");
804 // If argument mismatch error.
805 if (CalleeF
->arg_size() != Args
.size())
806 return LogErrorV("Incorrect # arguments passed");
808 std::vector
<Value
*> ArgsV
;
809 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
810 ArgsV
.push_back(Args
[i
]->codegen());
815 return Builder
->CreateCall(CalleeF
, ArgsV
, "calltmp");
818 Value
*IfExprAST::codegen() {
819 Value
*CondV
= Cond
->codegen();
823 // Convert condition to a bool by comparing equal to 0.0.
824 CondV
= Builder
->CreateFCmpONE(
825 CondV
, ConstantFP::get(*TheContext
, APFloat(0.0)), "ifcond");
827 Function
*TheFunction
= Builder
->GetInsertBlock()->getParent();
829 // Create blocks for the then and else cases. Insert the 'then' block at the
830 // end of the function.
831 BasicBlock
*ThenBB
= BasicBlock::Create(*TheContext
, "then", TheFunction
);
832 BasicBlock
*ElseBB
= BasicBlock::Create(*TheContext
, "else");
833 BasicBlock
*MergeBB
= BasicBlock::Create(*TheContext
, "ifcont");
835 Builder
->CreateCondBr(CondV
, ThenBB
, ElseBB
);
838 Builder
->SetInsertPoint(ThenBB
);
840 Value
*ThenV
= Then
->codegen();
844 Builder
->CreateBr(MergeBB
);
845 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
846 ThenBB
= Builder
->GetInsertBlock();
849 TheFunction
->getBasicBlockList().push_back(ElseBB
);
850 Builder
->SetInsertPoint(ElseBB
);
852 Value
*ElseV
= Else
->codegen();
856 Builder
->CreateBr(MergeBB
);
857 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
858 ElseBB
= Builder
->GetInsertBlock();
861 TheFunction
->getBasicBlockList().push_back(MergeBB
);
862 Builder
->SetInsertPoint(MergeBB
);
863 PHINode
*PN
= Builder
->CreatePHI(Type::getDoubleTy(*TheContext
), 2, "iftmp");
865 PN
->addIncoming(ThenV
, ThenBB
);
866 PN
->addIncoming(ElseV
, ElseBB
);
870 // Output for-loop as:
871 // var = alloca double
874 // store start -> var
885 // nextvar = curvar + step
886 // store nextvar -> var
887 // br endcond, loop, endloop
889 Value
*ForExprAST::codegen() {
890 Function
*TheFunction
= Builder
->GetInsertBlock()->getParent();
892 // Create an alloca for the variable in the entry block.
893 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
895 // Emit the start code first, without 'variable' in scope.
896 Value
*StartVal
= Start
->codegen();
900 // Store the value into the alloca.
901 Builder
->CreateStore(StartVal
, Alloca
);
903 // Make the new basic block for the loop header, inserting after current
905 BasicBlock
*LoopBB
= BasicBlock::Create(*TheContext
, "loop", TheFunction
);
907 // Insert an explicit fall through from the current block to the LoopBB.
908 Builder
->CreateBr(LoopBB
);
910 // Start insertion in LoopBB.
911 Builder
->SetInsertPoint(LoopBB
);
913 // Within the loop, the variable is defined equal to the PHI node. If it
914 // shadows an existing variable, we have to restore it, so save it now.
915 AllocaInst
*OldVal
= NamedValues
[VarName
];
916 NamedValues
[VarName
] = Alloca
;
918 // Emit the body of the loop. This, like any other expr, can change the
919 // current BB. Note that we ignore the value computed by the body, but don't
921 if (!Body
->codegen())
924 // Emit the step value.
925 Value
*StepVal
= nullptr;
927 StepVal
= Step
->codegen();
931 // If not specified, use 1.0.
932 StepVal
= ConstantFP::get(*TheContext
, APFloat(1.0));
935 // Compute the end condition.
936 Value
*EndCond
= End
->codegen();
940 // Reload, increment, and restore the alloca. This handles the case where
941 // the body of the loop mutates the variable.
942 Value
*CurVar
= Builder
->CreateLoad(Type::getDoubleTy(*TheContext
), Alloca
,
944 Value
*NextVar
= Builder
->CreateFAdd(CurVar
, StepVal
, "nextvar");
945 Builder
->CreateStore(NextVar
, Alloca
);
947 // Convert condition to a bool by comparing equal to 0.0.
948 EndCond
= Builder
->CreateFCmpONE(
949 EndCond
, ConstantFP::get(*TheContext
, APFloat(0.0)), "loopcond");
951 // Create the "after loop" block and insert it.
952 BasicBlock
*AfterBB
=
953 BasicBlock::Create(*TheContext
, "afterloop", TheFunction
);
955 // Insert the conditional branch into the end of LoopEndBB.
956 Builder
->CreateCondBr(EndCond
, LoopBB
, AfterBB
);
958 // Any new code will be inserted in AfterBB.
959 Builder
->SetInsertPoint(AfterBB
);
961 // Restore the unshadowed variable.
963 NamedValues
[VarName
] = OldVal
;
965 NamedValues
.erase(VarName
);
967 // for expr always returns 0.0.
968 return Constant::getNullValue(Type::getDoubleTy(*TheContext
));
971 Value
*VarExprAST::codegen() {
972 std::vector
<AllocaInst
*> OldBindings
;
974 Function
*TheFunction
= Builder
->GetInsertBlock()->getParent();
976 // Register all variables and emit their initializer.
977 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
) {
978 const std::string
&VarName
= VarNames
[i
].first
;
979 ExprAST
*Init
= VarNames
[i
].second
.get();
981 // Emit the initializer before adding the variable to scope, this prevents
982 // the initializer from referencing the variable itself, and permits stuff
985 // var a = a in ... # refers to outer 'a'.
988 InitVal
= Init
->codegen();
991 } else { // If not specified, use 0.0.
992 InitVal
= ConstantFP::get(*TheContext
, APFloat(0.0));
995 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, VarName
);
996 Builder
->CreateStore(InitVal
, Alloca
);
998 // Remember the old variable binding so that we can restore the binding when
1000 OldBindings
.push_back(NamedValues
[VarName
]);
1002 // Remember this binding.
1003 NamedValues
[VarName
] = Alloca
;
1006 // Codegen the body, now that all vars are in scope.
1007 Value
*BodyVal
= Body
->codegen();
1011 // Pop all our variables from scope.
1012 for (unsigned i
= 0, e
= VarNames
.size(); i
!= e
; ++i
)
1013 NamedValues
[VarNames
[i
].first
] = OldBindings
[i
];
1015 // Return the body computation.
1019 Function
*PrototypeAST::codegen() {
1020 // Make the function type: double(double,double) etc.
1021 std::vector
<Type
*> Doubles(Args
.size(), Type::getDoubleTy(*TheContext
));
1023 FunctionType::get(Type::getDoubleTy(*TheContext
), Doubles
, false);
1026 Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
.get());
1028 // Set names for all arguments.
1030 for (auto &Arg
: F
->args())
1031 Arg
.setName(Args
[Idx
++]);
1036 const PrototypeAST
& FunctionAST::getProto() const {
1040 const std::string
& FunctionAST::getName() const {
1041 return Proto
->getName();
1044 Function
*FunctionAST::codegen() {
1045 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
1046 // reference to it for use below.
1048 FunctionProtos
[Proto
->getName()] = std::move(Proto
);
1049 Function
*TheFunction
= getFunction(P
.getName());
1053 // If this is an operator, install it.
1055 BinopPrecedence
[P
.getOperatorName()] = P
.getBinaryPrecedence();
1057 // Create a new basic block to start insertion into.
1058 BasicBlock
*BB
= BasicBlock::Create(*TheContext
, "entry", TheFunction
);
1059 Builder
->SetInsertPoint(BB
);
1061 // Record the function arguments in the NamedValues map.
1062 NamedValues
.clear();
1063 for (auto &Arg
: TheFunction
->args()) {
1064 // Create an alloca for this variable.
1065 AllocaInst
*Alloca
= CreateEntryBlockAlloca(TheFunction
, Arg
.getName());
1067 // Store the initial value into the alloca.
1068 Builder
->CreateStore(&Arg
, Alloca
);
1070 // Add arguments to variable symbol table.
1071 NamedValues
[std::string(Arg
.getName())] = Alloca
;
1074 if (Value
*RetVal
= Body
->codegen()) {
1075 // Finish off the function.
1076 Builder
->CreateRet(RetVal
);
1078 // Validate the generated code, checking for consistency.
1079 verifyFunction(*TheFunction
);
1084 // Error reading body, remove function.
1085 TheFunction
->eraseFromParent();
1088 BinopPrecedence
.erase(P
.getOperatorName());
1092 //===----------------------------------------------------------------------===//
1093 // Top-Level parsing and JIT Driver
1094 //===----------------------------------------------------------------------===//
1096 static void InitializeModule() {
1097 // Open a new context and module.
1098 TheContext
= std::make_unique
<LLVMContext
>();
1099 TheModule
= std::make_unique
<Module
>("my cool jit", *TheContext
);
1100 TheModule
->setDataLayout(TheJIT
->getDataLayout());
1102 // Create a new builder for the module.
1103 Builder
= std::make_unique
<IRBuilder
<>>(*TheContext
);
1106 ThreadSafeModule
irgenAndTakeOwnership(FunctionAST
&FnAST
,
1107 const std::string
&Suffix
) {
1108 if (auto *F
= FnAST
.codegen()) {
1109 F
->setName(F
->getName() + Suffix
);
1110 auto TSM
= ThreadSafeModule(std::move(TheModule
), std::move(TheContext
));
1111 // Start a new module.
1115 report_fatal_error("Couldn't compile lazily JIT'd function");
1118 static void HandleDefinition() {
1119 if (auto FnAST
= ParseDefinition()) {
1120 FunctionProtos
[FnAST
->getProto().getName()] =
1121 std::make_unique
<PrototypeAST
>(FnAST
->getProto());
1122 ExitOnErr(TheJIT
->addAST(std::move(FnAST
)));
1124 // Skip token for error recovery.
1129 static void HandleExtern() {
1130 if (auto ProtoAST
= ParseExtern()) {
1131 if (auto *FnIR
= ProtoAST
->codegen()) {
1132 fprintf(stderr
, "Read extern: ");
1133 FnIR
->print(errs());
1134 fprintf(stderr
, "\n");
1135 FunctionProtos
[ProtoAST
->getName()] = std::move(ProtoAST
);
1138 // Skip token for error recovery.
1143 static void HandleTopLevelExpression() {
1144 // Evaluate a top-level expression into an anonymous function.
1145 if (auto FnAST
= ParseTopLevelExpr()) {
1146 if (FnAST
->codegen()) {
1147 // Create a ResourceTracker to track JIT'd memory allocated to our
1148 // anonymous expression -- that way we can free it after executing.
1149 auto RT
= TheJIT
->getMainJITDylib().createResourceTracker();
1151 auto TSM
= ThreadSafeModule(std::move(TheModule
), std::move(TheContext
));
1152 ExitOnErr(TheJIT
->addModule(std::move(TSM
), RT
));
1155 // Get the anonymous expression's JITSymbol.
1156 auto Sym
= ExitOnErr(TheJIT
->lookup("__anon_expr"));
1158 // Get the symbol's address and cast it to the right type (takes no
1159 // arguments, returns a double) so we can call it as a native function.
1160 auto *FP
= (double (*)())(intptr_t)Sym
.getAddress();
1161 fprintf(stderr
, "Evaluated to %f\n", FP());
1163 // Delete the anonymous expression module from the JIT.
1164 ExitOnErr(RT
->remove());
1167 // Skip token for error recovery.
1172 /// top ::= definition | external | expression | ';'
1173 static void MainLoop() {
1175 fprintf(stderr
, "ready> ");
1179 case ';': // ignore top-level semicolons.
1189 HandleTopLevelExpression();
1195 //===----------------------------------------------------------------------===//
1196 // "Library" functions that can be "extern'd" from user code.
1197 //===----------------------------------------------------------------------===//
1199 /// putchard - putchar that takes a double and returns 0.
1200 extern "C" double putchard(double X
) {
1201 fputc((char)X
, stderr
);
1205 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1206 extern "C" double printd(double X
) {
1207 fprintf(stderr
, "%f\n", X
);
1211 //===----------------------------------------------------------------------===//
1212 // Main driver code.
1213 //===----------------------------------------------------------------------===//
1216 InitializeNativeTarget();
1217 InitializeNativeTargetAsmPrinter();
1218 InitializeNativeTargetAsmParser();
1220 // Install standard binary operators.
1221 // 1 is lowest precedence.
1222 BinopPrecedence
['='] = 2;
1223 BinopPrecedence
['<'] = 10;
1224 BinopPrecedence
['+'] = 20;
1225 BinopPrecedence
['-'] = 20;
1226 BinopPrecedence
['*'] = 40; // highest.
1228 // Prime the first token.
1229 fprintf(stderr
, "ready> ");
1232 TheJIT
= ExitOnErr(KaleidoscopeJIT::Create());
1235 // Run the main "interpreter loop" now.