1 #include "../include/KaleidoscopeJIT.h"
2 #include "llvm/ADT/APFloat.h"
3 #include "llvm/ADT/STLExtras.h"
4 #include "llvm/Analysis/AssumptionCache.h"
5 #include "llvm/Analysis/BasicAliasAnalysis.h"
6 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
7 #include "llvm/Analysis/MemorySSA.h"
8 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
9 #include "llvm/Analysis/ProfileSummaryInfo.h"
10 #include "llvm/Analysis/TargetTransformInfo.h"
11 #include "llvm/IR/BasicBlock.h"
12 #include "llvm/IR/Constants.h"
13 #include "llvm/IR/DerivedTypes.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/IRBuilder.h"
16 #include "llvm/IR/Instructions.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/PassManager.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/Passes/PassBuilder.h"
23 #include "llvm/Passes/StandardInstrumentations.h"
24 #include "llvm/Support/TargetSelect.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Transforms/InstCombine/InstCombine.h"
27 #include "llvm/Transforms/Scalar.h"
28 #include "llvm/Transforms/Scalar/GVN.h"
29 #include "llvm/Transforms/Scalar/Reassociate.h"
30 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
43 using namespace llvm::orc
;
45 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
50 // of these for known things.
74 static std::string IdentifierStr
; // Filled in if tok_identifier
75 static double NumVal
; // Filled in if tok_number
77 /// gettok - Return the next token from standard input.
79 static int LastChar
= ' ';
81 // Skip any whitespace.
82 while (isspace(LastChar
))
85 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
86 IdentifierStr
= LastChar
;
87 while (isalnum((LastChar
= getchar())))
88 IdentifierStr
+= LastChar
;
90 if (IdentifierStr
== "def")
92 if (IdentifierStr
== "extern")
94 if (IdentifierStr
== "if")
96 if (IdentifierStr
== "then")
98 if (IdentifierStr
== "else")
100 if (IdentifierStr
== "for")
102 if (IdentifierStr
== "in")
104 if (IdentifierStr
== "binary")
106 if (IdentifierStr
== "unary")
108 return tok_identifier
;
111 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
115 LastChar
= getchar();
116 } while (isdigit(LastChar
) || LastChar
== '.');
118 NumVal
= strtod(NumStr
.c_str(), nullptr);
122 if (LastChar
== '#') {
123 // Comment until end of line.
125 LastChar
= getchar();
126 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
132 // Check for end of file. Don't eat the EOF.
136 // Otherwise, just return the character as its ascii value.
137 int ThisChar
= LastChar
;
138 LastChar
= getchar();
142 //===----------------------------------------------------------------------===//
143 // Abstract Syntax Tree (aka Parse Tree)
144 //===----------------------------------------------------------------------===//
148 /// ExprAST - Base class for all expression nodes.
151 virtual ~ExprAST() = default;
153 virtual Value
*codegen() = 0;
156 /// NumberExprAST - Expression class for numeric literals like "1.0".
157 class NumberExprAST
: public ExprAST
{
161 NumberExprAST(double Val
) : Val(Val
) {}
163 Value
*codegen() override
;
166 /// VariableExprAST - Expression class for referencing a variable, like "a".
167 class VariableExprAST
: public ExprAST
{
171 VariableExprAST(const std::string
&Name
) : Name(Name
) {}
173 Value
*codegen() override
;
176 /// UnaryExprAST - Expression class for a unary operator.
177 class UnaryExprAST
: public ExprAST
{
179 std::unique_ptr
<ExprAST
> Operand
;
182 UnaryExprAST(char Opcode
, std::unique_ptr
<ExprAST
> Operand
)
183 : Opcode(Opcode
), Operand(std::move(Operand
)) {}
185 Value
*codegen() override
;
188 /// BinaryExprAST - Expression class for a binary operator.
189 class BinaryExprAST
: public ExprAST
{
191 std::unique_ptr
<ExprAST
> LHS
, RHS
;
194 BinaryExprAST(char Op
, std::unique_ptr
<ExprAST
> LHS
,
195 std::unique_ptr
<ExprAST
> RHS
)
196 : Op(Op
), LHS(std::move(LHS
)), RHS(std::move(RHS
)) {}
198 Value
*codegen() override
;
201 /// CallExprAST - Expression class for function calls.
202 class CallExprAST
: public ExprAST
{
204 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
207 CallExprAST(const std::string
&Callee
,
208 std::vector
<std::unique_ptr
<ExprAST
>> Args
)
209 : Callee(Callee
), Args(std::move(Args
)) {}
211 Value
*codegen() override
;
214 /// IfExprAST - Expression class for if/then/else.
215 class IfExprAST
: public ExprAST
{
216 std::unique_ptr
<ExprAST
> Cond
, Then
, Else
;
219 IfExprAST(std::unique_ptr
<ExprAST
> Cond
, std::unique_ptr
<ExprAST
> Then
,
220 std::unique_ptr
<ExprAST
> Else
)
221 : Cond(std::move(Cond
)), Then(std::move(Then
)), Else(std::move(Else
)) {}
223 Value
*codegen() override
;
226 /// ForExprAST - Expression class for for/in.
227 class ForExprAST
: public ExprAST
{
229 std::unique_ptr
<ExprAST
> Start
, End
, Step
, Body
;
232 ForExprAST(const std::string
&VarName
, std::unique_ptr
<ExprAST
> Start
,
233 std::unique_ptr
<ExprAST
> End
, std::unique_ptr
<ExprAST
> Step
,
234 std::unique_ptr
<ExprAST
> Body
)
235 : VarName(VarName
), Start(std::move(Start
)), End(std::move(End
)),
236 Step(std::move(Step
)), Body(std::move(Body
)) {}
238 Value
*codegen() override
;
241 /// PrototypeAST - This class represents the "prototype" for a function,
242 /// which captures its name, and its argument names (thus implicitly the number
243 /// of arguments the function takes), as well as if it is an operator.
246 std::vector
<std::string
> Args
;
248 unsigned Precedence
; // Precedence if a binary op.
251 PrototypeAST(const std::string
&Name
, std::vector
<std::string
> Args
,
252 bool IsOperator
= false, unsigned Prec
= 0)
253 : Name(Name
), Args(std::move(Args
)), IsOperator(IsOperator
),
257 const std::string
&getName() const { return Name
; }
259 bool isUnaryOp() const { return IsOperator
&& Args
.size() == 1; }
260 bool isBinaryOp() const { return IsOperator
&& Args
.size() == 2; }
262 char getOperatorName() const {
263 assert(isUnaryOp() || isBinaryOp());
264 return Name
[Name
.size() - 1];
267 unsigned getBinaryPrecedence() const { return Precedence
; }
270 /// FunctionAST - This class represents a function definition itself.
272 std::unique_ptr
<PrototypeAST
> Proto
;
273 std::unique_ptr
<ExprAST
> Body
;
276 FunctionAST(std::unique_ptr
<PrototypeAST
> Proto
,
277 std::unique_ptr
<ExprAST
> Body
)
278 : Proto(std::move(Proto
)), Body(std::move(Body
)) {}
283 } // end anonymous namespace
285 //===----------------------------------------------------------------------===//
287 //===----------------------------------------------------------------------===//
289 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
290 /// token the parser is looking at. getNextToken reads another token from the
291 /// lexer and updates CurTok with its results.
293 static int getNextToken() { return CurTok
= gettok(); }
295 /// BinopPrecedence - This holds the precedence for each binary operator that is
297 static std::map
<char, int> BinopPrecedence
;
299 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
300 static int GetTokPrecedence() {
301 if (!isascii(CurTok
))
304 // Make sure it's a declared binop.
305 int TokPrec
= BinopPrecedence
[CurTok
];
311 /// Error* - These are little helper functions for error handling.
312 std::unique_ptr
<ExprAST
> LogError(const char *Str
) {
313 fprintf(stderr
, "Error: %s\n", Str
);
317 std::unique_ptr
<PrototypeAST
> LogErrorP(const char *Str
) {
322 static std::unique_ptr
<ExprAST
> ParseExpression();
324 /// numberexpr ::= number
325 static std::unique_ptr
<ExprAST
> ParseNumberExpr() {
326 auto Result
= std::make_unique
<NumberExprAST
>(NumVal
);
327 getNextToken(); // consume the number
328 return std::move(Result
);
331 /// parenexpr ::= '(' expression ')'
332 static std::unique_ptr
<ExprAST
> ParseParenExpr() {
333 getNextToken(); // eat (.
334 auto V
= ParseExpression();
339 return LogError("expected ')'");
340 getNextToken(); // eat ).
346 /// ::= identifier '(' expression* ')'
347 static std::unique_ptr
<ExprAST
> ParseIdentifierExpr() {
348 std::string IdName
= IdentifierStr
;
350 getNextToken(); // eat identifier.
352 if (CurTok
!= '(') // Simple variable ref.
353 return std::make_unique
<VariableExprAST
>(IdName
);
356 getNextToken(); // eat (
357 std::vector
<std::unique_ptr
<ExprAST
>> Args
;
360 if (auto Arg
= ParseExpression())
361 Args
.push_back(std::move(Arg
));
369 return LogError("Expected ')' or ',' in argument list");
377 return std::make_unique
<CallExprAST
>(IdName
, std::move(Args
));
380 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
381 static std::unique_ptr
<ExprAST
> ParseIfExpr() {
382 getNextToken(); // eat the if.
385 auto Cond
= ParseExpression();
389 if (CurTok
!= tok_then
)
390 return LogError("expected then");
391 getNextToken(); // eat the then
393 auto Then
= ParseExpression();
397 if (CurTok
!= tok_else
)
398 return LogError("expected else");
402 auto Else
= ParseExpression();
406 return std::make_unique
<IfExprAST
>(std::move(Cond
), std::move(Then
),
410 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
411 static std::unique_ptr
<ExprAST
> ParseForExpr() {
412 getNextToken(); // eat the for.
414 if (CurTok
!= tok_identifier
)
415 return LogError("expected identifier after for");
417 std::string IdName
= IdentifierStr
;
418 getNextToken(); // eat identifier.
421 return LogError("expected '=' after for");
422 getNextToken(); // eat '='.
424 auto Start
= ParseExpression();
428 return LogError("expected ',' after for start value");
431 auto End
= ParseExpression();
435 // The step value is optional.
436 std::unique_ptr
<ExprAST
> Step
;
439 Step
= ParseExpression();
444 if (CurTok
!= tok_in
)
445 return LogError("expected 'in' after for");
446 getNextToken(); // eat 'in'.
448 auto Body
= ParseExpression();
452 return std::make_unique
<ForExprAST
>(IdName
, std::move(Start
), std::move(End
),
453 std::move(Step
), std::move(Body
));
457 /// ::= identifierexpr
462 static std::unique_ptr
<ExprAST
> ParsePrimary() {
465 return LogError("unknown token when expecting an expression");
467 return ParseIdentifierExpr();
469 return ParseNumberExpr();
471 return ParseParenExpr();
473 return ParseIfExpr();
475 return ParseForExpr();
482 static std::unique_ptr
<ExprAST
> ParseUnary() {
483 // If the current token is not an operator, it must be a primary expr.
484 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
485 return ParsePrimary();
487 // If this is a unary operator, read it.
490 if (auto Operand
= ParseUnary())
491 return std::make_unique
<UnaryExprAST
>(Opc
, std::move(Operand
));
497 static std::unique_ptr
<ExprAST
> ParseBinOpRHS(int ExprPrec
,
498 std::unique_ptr
<ExprAST
> LHS
) {
499 // If this is a binop, find its precedence.
501 int TokPrec
= GetTokPrecedence();
503 // If this is a binop that binds at least as tightly as the current binop,
504 // consume it, otherwise we are done.
505 if (TokPrec
< ExprPrec
)
508 // Okay, we know this is a binop.
510 getNextToken(); // eat binop
512 // Parse the unary expression after the binary operator.
513 auto RHS
= ParseUnary();
517 // If BinOp binds less tightly with RHS than the operator after RHS, let
518 // the pending operator take RHS as its LHS.
519 int NextPrec
= GetTokPrecedence();
520 if (TokPrec
< NextPrec
) {
521 RHS
= ParseBinOpRHS(TokPrec
+ 1, std::move(RHS
));
528 std::make_unique
<BinaryExprAST
>(BinOp
, std::move(LHS
), std::move(RHS
));
533 /// ::= unary binoprhs
535 static std::unique_ptr
<ExprAST
> ParseExpression() {
536 auto LHS
= ParseUnary();
540 return ParseBinOpRHS(0, std::move(LHS
));
544 /// ::= id '(' id* ')'
545 /// ::= binary LETTER number? (id, id)
546 /// ::= unary LETTER (id)
547 static std::unique_ptr
<PrototypeAST
> ParsePrototype() {
550 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
551 unsigned BinaryPrecedence
= 30;
555 return LogErrorP("Expected function name in prototype");
557 FnName
= IdentifierStr
;
563 if (!isascii(CurTok
))
564 return LogErrorP("Expected unary operator");
566 FnName
+= (char)CurTok
;
572 if (!isascii(CurTok
))
573 return LogErrorP("Expected binary operator");
575 FnName
+= (char)CurTok
;
579 // Read the precedence if present.
580 if (CurTok
== tok_number
) {
581 if (NumVal
< 1 || NumVal
> 100)
582 return LogErrorP("Invalid precedence: must be 1..100");
583 BinaryPrecedence
= (unsigned)NumVal
;
590 return LogErrorP("Expected '(' in prototype");
592 std::vector
<std::string
> ArgNames
;
593 while (getNextToken() == tok_identifier
)
594 ArgNames
.push_back(IdentifierStr
);
596 return LogErrorP("Expected ')' in prototype");
599 getNextToken(); // eat ')'.
601 // Verify right number of names for operator.
602 if (Kind
&& ArgNames
.size() != Kind
)
603 return LogErrorP("Invalid number of operands for operator");
605 return std::make_unique
<PrototypeAST
>(FnName
, ArgNames
, Kind
!= 0,
609 /// definition ::= 'def' prototype expression
610 static std::unique_ptr
<FunctionAST
> ParseDefinition() {
611 getNextToken(); // eat def.
612 auto Proto
= ParsePrototype();
616 if (auto E
= ParseExpression())
617 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
621 /// toplevelexpr ::= expression
622 static std::unique_ptr
<FunctionAST
> ParseTopLevelExpr() {
623 if (auto E
= ParseExpression()) {
624 // Make an anonymous proto.
625 auto Proto
= std::make_unique
<PrototypeAST
>("__anon_expr",
626 std::vector
<std::string
>());
627 return std::make_unique
<FunctionAST
>(std::move(Proto
), std::move(E
));
632 /// external ::= 'extern' prototype
633 static std::unique_ptr
<PrototypeAST
> ParseExtern() {
634 getNextToken(); // eat extern.
635 return ParsePrototype();
638 //===----------------------------------------------------------------------===//
640 //===----------------------------------------------------------------------===//
642 static std::unique_ptr
<LLVMContext
> TheContext
;
643 static std::unique_ptr
<Module
> TheModule
;
644 static std::unique_ptr
<IRBuilder
<>> Builder
;
645 static std::map
<std::string
, Value
*> NamedValues
;
646 static std::unique_ptr
<KaleidoscopeJIT
> TheJIT
;
647 static std::unique_ptr
<FunctionPassManager
> TheFPM
;
648 static std::unique_ptr
<FunctionAnalysisManager
> TheFAM
;
649 static std::unique_ptr
<ModuleAnalysisManager
> TheMAM
;
650 static std::unique_ptr
<PassInstrumentationCallbacks
> ThePIC
;
651 static std::unique_ptr
<StandardInstrumentations
> TheSI
;
652 static std::map
<std::string
, std::unique_ptr
<PrototypeAST
>> FunctionProtos
;
653 static ExitOnError ExitOnErr
;
655 Value
*LogErrorV(const char *Str
) {
660 Function
*getFunction(std::string Name
) {
661 // First, see if the function has already been added to the current module.
662 if (auto *F
= TheModule
->getFunction(Name
))
665 // If not, check whether we can codegen the declaration from some existing
667 auto FI
= FunctionProtos
.find(Name
);
668 if (FI
!= FunctionProtos
.end())
669 return FI
->second
->codegen();
671 // If no existing prototype exists, return null.
675 Value
*NumberExprAST::codegen() {
676 return ConstantFP::get(*TheContext
, APFloat(Val
));
679 Value
*VariableExprAST::codegen() {
680 // Look this variable up in the function.
681 Value
*V
= NamedValues
[Name
];
683 return LogErrorV("Unknown variable name");
687 Value
*UnaryExprAST::codegen() {
688 Value
*OperandV
= Operand
->codegen();
692 Function
*F
= getFunction(std::string("unary") + Opcode
);
694 return LogErrorV("Unknown unary operator");
696 return Builder
->CreateCall(F
, OperandV
, "unop");
699 Value
*BinaryExprAST::codegen() {
700 Value
*L
= LHS
->codegen();
701 Value
*R
= RHS
->codegen();
707 return Builder
->CreateFAdd(L
, R
, "addtmp");
709 return Builder
->CreateFSub(L
, R
, "subtmp");
711 return Builder
->CreateFMul(L
, R
, "multmp");
713 L
= Builder
->CreateFCmpULT(L
, R
, "cmptmp");
714 // Convert bool 0/1 to double 0.0 or 1.0
715 return Builder
->CreateUIToFP(L
, Type::getDoubleTy(*TheContext
), "booltmp");
720 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
722 Function
*F
= getFunction(std::string("binary") + Op
);
723 assert(F
&& "binary operator not found!");
725 Value
*Ops
[] = {L
, R
};
726 return Builder
->CreateCall(F
, Ops
, "binop");
729 Value
*CallExprAST::codegen() {
730 // Look up the name in the global module table.
731 Function
*CalleeF
= getFunction(Callee
);
733 return LogErrorV("Unknown function referenced");
735 // If argument mismatch error.
736 if (CalleeF
->arg_size() != Args
.size())
737 return LogErrorV("Incorrect # arguments passed");
739 std::vector
<Value
*> ArgsV
;
740 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
741 ArgsV
.push_back(Args
[i
]->codegen());
746 return Builder
->CreateCall(CalleeF
, ArgsV
, "calltmp");
749 Value
*IfExprAST::codegen() {
750 Value
*CondV
= Cond
->codegen();
754 // Convert condition to a bool by comparing non-equal to 0.0.
755 CondV
= Builder
->CreateFCmpONE(
756 CondV
, ConstantFP::get(*TheContext
, APFloat(0.0)), "ifcond");
758 Function
*TheFunction
= Builder
->GetInsertBlock()->getParent();
760 // Create blocks for the then and else cases. Insert the 'then' block at the
761 // end of the function.
762 BasicBlock
*ThenBB
= BasicBlock::Create(*TheContext
, "then", TheFunction
);
763 BasicBlock
*ElseBB
= BasicBlock::Create(*TheContext
, "else");
764 BasicBlock
*MergeBB
= BasicBlock::Create(*TheContext
, "ifcont");
766 Builder
->CreateCondBr(CondV
, ThenBB
, ElseBB
);
769 Builder
->SetInsertPoint(ThenBB
);
771 Value
*ThenV
= Then
->codegen();
775 Builder
->CreateBr(MergeBB
);
776 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
777 ThenBB
= Builder
->GetInsertBlock();
780 TheFunction
->insert(TheFunction
->end(), ElseBB
);
781 Builder
->SetInsertPoint(ElseBB
);
783 Value
*ElseV
= Else
->codegen();
787 Builder
->CreateBr(MergeBB
);
788 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
789 ElseBB
= Builder
->GetInsertBlock();
792 TheFunction
->insert(TheFunction
->end(), MergeBB
);
793 Builder
->SetInsertPoint(MergeBB
);
794 PHINode
*PN
= Builder
->CreatePHI(Type::getDoubleTy(*TheContext
), 2, "iftmp");
796 PN
->addIncoming(ThenV
, ThenBB
);
797 PN
->addIncoming(ElseV
, ElseBB
);
801 // Output for-loop as:
806 // variable = phi [start, loopheader], [nextvariable, loopend]
812 // nextvariable = variable + step
814 // br endcond, loop, endloop
816 Value
*ForExprAST::codegen() {
817 // Emit the start code first, without 'variable' in scope.
818 Value
*StartVal
= Start
->codegen();
822 // Make the new basic block for the loop header, inserting after current
824 Function
*TheFunction
= Builder
->GetInsertBlock()->getParent();
825 BasicBlock
*PreheaderBB
= Builder
->GetInsertBlock();
826 BasicBlock
*LoopBB
= BasicBlock::Create(*TheContext
, "loop", TheFunction
);
828 // Insert an explicit fall through from the current block to the LoopBB.
829 Builder
->CreateBr(LoopBB
);
831 // Start insertion in LoopBB.
832 Builder
->SetInsertPoint(LoopBB
);
834 // Start the PHI node with an entry for Start.
836 Builder
->CreatePHI(Type::getDoubleTy(*TheContext
), 2, VarName
);
837 Variable
->addIncoming(StartVal
, PreheaderBB
);
839 // Within the loop, the variable is defined equal to the PHI node. If it
840 // shadows an existing variable, we have to restore it, so save it now.
841 Value
*OldVal
= NamedValues
[VarName
];
842 NamedValues
[VarName
] = Variable
;
844 // Emit the body of the loop. This, like any other expr, can change the
845 // current BB. Note that we ignore the value computed by the body, but don't
847 if (!Body
->codegen())
850 // Emit the step value.
851 Value
*StepVal
= nullptr;
853 StepVal
= Step
->codegen();
857 // If not specified, use 1.0.
858 StepVal
= ConstantFP::get(*TheContext
, APFloat(1.0));
861 Value
*NextVar
= Builder
->CreateFAdd(Variable
, StepVal
, "nextvar");
863 // Compute the end condition.
864 Value
*EndCond
= End
->codegen();
868 // Convert condition to a bool by comparing non-equal to 0.0.
869 EndCond
= Builder
->CreateFCmpONE(
870 EndCond
, ConstantFP::get(*TheContext
, APFloat(0.0)), "loopcond");
872 // Create the "after loop" block and insert it.
873 BasicBlock
*LoopEndBB
= Builder
->GetInsertBlock();
874 BasicBlock
*AfterBB
=
875 BasicBlock::Create(*TheContext
, "afterloop", TheFunction
);
877 // Insert the conditional branch into the end of LoopEndBB.
878 Builder
->CreateCondBr(EndCond
, LoopBB
, AfterBB
);
880 // Any new code will be inserted in AfterBB.
881 Builder
->SetInsertPoint(AfterBB
);
883 // Add a new entry to the PHI node for the backedge.
884 Variable
->addIncoming(NextVar
, LoopEndBB
);
886 // Restore the unshadowed variable.
888 NamedValues
[VarName
] = OldVal
;
890 NamedValues
.erase(VarName
);
892 // for expr always returns 0.0.
893 return Constant::getNullValue(Type::getDoubleTy(*TheContext
));
896 Function
*PrototypeAST::codegen() {
897 // Make the function type: double(double,double) etc.
898 std::vector
<Type
*> Doubles(Args
.size(), Type::getDoubleTy(*TheContext
));
900 FunctionType::get(Type::getDoubleTy(*TheContext
), Doubles
, false);
903 Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
.get());
905 // Set names for all arguments.
907 for (auto &Arg
: F
->args())
908 Arg
.setName(Args
[Idx
++]);
913 Function
*FunctionAST::codegen() {
914 // Transfer ownership of the prototype to the FunctionProtos map, but keep a
915 // reference to it for use below.
917 FunctionProtos
[Proto
->getName()] = std::move(Proto
);
918 Function
*TheFunction
= getFunction(P
.getName());
922 // If this is an operator, install it.
924 BinopPrecedence
[P
.getOperatorName()] = P
.getBinaryPrecedence();
926 // Create a new basic block to start insertion into.
927 BasicBlock
*BB
= BasicBlock::Create(*TheContext
, "entry", TheFunction
);
928 Builder
->SetInsertPoint(BB
);
930 // Record the function arguments in the NamedValues map.
932 for (auto &Arg
: TheFunction
->args())
933 NamedValues
[std::string(Arg
.getName())] = &Arg
;
935 if (Value
*RetVal
= Body
->codegen()) {
936 // Finish off the function.
937 Builder
->CreateRet(RetVal
);
939 // Validate the generated code, checking for consistency.
940 verifyFunction(*TheFunction
);
942 // Run the optimizer on the function.
943 TheFPM
->run(*TheFunction
, *TheFAM
);
948 // Error reading body, remove function.
949 TheFunction
->eraseFromParent();
952 BinopPrecedence
.erase(P
.getOperatorName());
956 //===----------------------------------------------------------------------===//
957 // Top-Level parsing and JIT Driver
958 //===----------------------------------------------------------------------===//
960 static void InitializeModuleAndManagers() {
961 // Open a new context and module.
962 TheContext
= std::make_unique
<LLVMContext
>();
963 TheModule
= std::make_unique
<Module
>("KaleidoscopeJIT", *TheContext
);
964 TheModule
->setDataLayout(TheJIT
->getDataLayout());
966 // Create a new builder for the module.
967 Builder
= std::make_unique
<IRBuilder
<>>(*TheContext
);
969 // Create new pass and analysis managers.
970 TheFPM
= std::make_unique
<FunctionPassManager
>();
971 TheFAM
= std::make_unique
<FunctionAnalysisManager
>();
972 TheMAM
= std::make_unique
<ModuleAnalysisManager
>();
973 ThePIC
= std::make_unique
<PassInstrumentationCallbacks
>();
974 TheSI
= std::make_unique
<StandardInstrumentations
>(*TheContext
,
975 /*DebugLogging*/ true);
976 TheSI
->registerCallbacks(*ThePIC
, TheMAM
.get());
978 // Add transform passes.
979 // Do simple "peephole" optimizations and bit-twiddling optzns.
980 TheFPM
->addPass(InstCombinePass());
981 // Reassociate expressions.
982 TheFPM
->addPass(ReassociatePass());
983 // Eliminate Common SubExpressions.
984 TheFPM
->addPass(GVNPass());
985 // Simplify the control flow graph (deleting unreachable blocks, etc).
986 TheFPM
->addPass(SimplifyCFGPass());
988 // Register analysis passes used in these transform passes.
989 TheFAM
->registerPass([&] { return AAManager(); });
990 TheFAM
->registerPass([&] { return AssumptionAnalysis(); });
991 TheFAM
->registerPass([&] { return DominatorTreeAnalysis(); });
992 TheFAM
->registerPass([&] { return LoopAnalysis(); });
993 TheFAM
->registerPass([&] { return MemoryDependenceAnalysis(); });
994 TheFAM
->registerPass([&] { return MemorySSAAnalysis(); });
995 TheFAM
->registerPass([&] { return OptimizationRemarkEmitterAnalysis(); });
996 TheFAM
->registerPass([&] {
997 return OuterAnalysisManagerProxy
<ModuleAnalysisManager
, Function
>(*TheMAM
);
999 TheFAM
->registerPass(
1000 [&] { return PassInstrumentationAnalysis(ThePIC
.get()); });
1001 TheFAM
->registerPass([&] { return TargetIRAnalysis(); });
1002 TheFAM
->registerPass([&] { return TargetLibraryAnalysis(); });
1004 TheMAM
->registerPass([&] { return ProfileSummaryAnalysis(); });
1007 static void HandleDefinition() {
1008 if (auto FnAST
= ParseDefinition()) {
1009 if (auto *FnIR
= FnAST
->codegen()) {
1010 fprintf(stderr
, "Read function definition:");
1011 FnIR
->print(errs());
1012 fprintf(stderr
, "\n");
1013 ExitOnErr(TheJIT
->addModule(
1014 ThreadSafeModule(std::move(TheModule
), std::move(TheContext
))));
1015 InitializeModuleAndManagers();
1018 // Skip token for error recovery.
1023 static void HandleExtern() {
1024 if (auto ProtoAST
= ParseExtern()) {
1025 if (auto *FnIR
= ProtoAST
->codegen()) {
1026 fprintf(stderr
, "Read extern: ");
1027 FnIR
->print(errs());
1028 fprintf(stderr
, "\n");
1029 FunctionProtos
[ProtoAST
->getName()] = std::move(ProtoAST
);
1032 // Skip token for error recovery.
1037 static void HandleTopLevelExpression() {
1038 // Evaluate a top-level expression into an anonymous function.
1039 if (auto FnAST
= ParseTopLevelExpr()) {
1040 if (FnAST
->codegen()) {
1041 // Create a ResourceTracker to track JIT'd memory allocated to our
1042 // anonymous expression -- that way we can free it after executing.
1043 auto RT
= TheJIT
->getMainJITDylib().createResourceTracker();
1045 auto TSM
= ThreadSafeModule(std::move(TheModule
), std::move(TheContext
));
1046 ExitOnErr(TheJIT
->addModule(std::move(TSM
), RT
));
1047 InitializeModuleAndManagers();
1049 // Search the JIT for the __anon_expr symbol.
1050 auto ExprSymbol
= ExitOnErr(TheJIT
->lookup("__anon_expr"));
1052 // Get the symbol's address and cast it to the right type (takes no
1053 // arguments, returns a double) so we can call it as a native function.
1054 double (*FP
)() = ExprSymbol
.getAddress().toPtr
<double (*)()>();
1055 fprintf(stderr
, "Evaluated to %f\n", FP());
1057 // Delete the anonymous expression module from the JIT.
1058 ExitOnErr(RT
->remove());
1061 // Skip token for error recovery.
1066 /// top ::= definition | external | expression | ';'
1067 static void MainLoop() {
1069 fprintf(stderr
, "ready> ");
1073 case ';': // ignore top-level semicolons.
1083 HandleTopLevelExpression();
1089 //===----------------------------------------------------------------------===//
1090 // "Library" functions that can be "extern'd" from user code.
1091 //===----------------------------------------------------------------------===//
1094 #define DLLEXPORT __declspec(dllexport)
1099 /// putchard - putchar that takes a double and returns 0.
1100 extern "C" DLLEXPORT
double putchard(double X
) {
1101 fputc((char)X
, stderr
);
1105 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1106 extern "C" DLLEXPORT
double printd(double X
) {
1107 fprintf(stderr
, "%f\n", X
);
1111 //===----------------------------------------------------------------------===//
1112 // Main driver code.
1113 //===----------------------------------------------------------------------===//
1116 InitializeNativeTarget();
1117 InitializeNativeTargetAsmPrinter();
1118 InitializeNativeTargetAsmParser();
1120 // Install standard binary operators.
1121 // 1 is lowest precedence.
1122 BinopPrecedence
['<'] = 10;
1123 BinopPrecedence
['+'] = 20;
1124 BinopPrecedence
['-'] = 20;
1125 BinopPrecedence
['*'] = 40; // highest.
1127 // Prime the first token.
1128 fprintf(stderr
, "ready> ");
1131 TheJIT
= ExitOnErr(KaleidoscopeJIT::Create());
1133 InitializeModuleAndManagers();
1135 // Run the main "interpreter loop" now.