]>
git.proxmox.com Git - rustc.git/blob - src/llvm/examples/Kaleidoscope/Chapter6/toy.cpp
1 #include "llvm/Analysis/Passes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/MCJIT.h"
4 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/DerivedTypes.h"
7 #include "llvm/IR/IRBuilder.h"
8 #include "llvm/IR/LLVMContext.h"
9 #include "llvm/IR/Module.h"
10 #include "llvm/IR/Verifier.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Support/TargetSelect.h"
13 #include "llvm/Transforms/Scalar.h"
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
26 // of these for known things.
50 static std::string IdentifierStr
; // Filled in if tok_identifier
51 static double NumVal
; // Filled in if tok_number
53 /// gettok - Return the next token from standard input.
55 static int LastChar
= ' ';
57 // Skip any whitespace.
58 while (isspace(LastChar
))
61 if (isalpha(LastChar
)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
62 IdentifierStr
= LastChar
;
63 while (isalnum((LastChar
= getchar())))
64 IdentifierStr
+= LastChar
;
66 if (IdentifierStr
== "def")
68 if (IdentifierStr
== "extern")
70 if (IdentifierStr
== "if")
72 if (IdentifierStr
== "then")
74 if (IdentifierStr
== "else")
76 if (IdentifierStr
== "for")
78 if (IdentifierStr
== "in")
80 if (IdentifierStr
== "binary")
82 if (IdentifierStr
== "unary")
84 return tok_identifier
;
87 if (isdigit(LastChar
) || LastChar
== '.') { // Number: [0-9.]+
92 } while (isdigit(LastChar
) || LastChar
== '.');
94 NumVal
= strtod(NumStr
.c_str(), 0);
98 if (LastChar
== '#') {
99 // Comment until end of line.
101 LastChar
= getchar();
102 while (LastChar
!= EOF
&& LastChar
!= '\n' && LastChar
!= '\r');
108 // Check for end of file. Don't eat the EOF.
112 // Otherwise, just return the character as its ascii value.
113 int ThisChar
= LastChar
;
114 LastChar
= getchar();
118 //===----------------------------------------------------------------------===//
119 // Abstract Syntax Tree (aka Parse Tree)
120 //===----------------------------------------------------------------------===//
122 /// ExprAST - Base class for all expression nodes.
125 virtual ~ExprAST() {}
126 virtual Value
*Codegen() = 0;
129 /// NumberExprAST - Expression class for numeric literals like "1.0".
130 class NumberExprAST
: public ExprAST
{
134 NumberExprAST(double val
) : Val(val
) {}
135 virtual Value
*Codegen();
138 /// VariableExprAST - Expression class for referencing a variable, like "a".
139 class VariableExprAST
: public ExprAST
{
143 VariableExprAST(const std::string
&name
) : Name(name
) {}
144 virtual Value
*Codegen();
147 /// UnaryExprAST - Expression class for a unary operator.
148 class UnaryExprAST
: public ExprAST
{
153 UnaryExprAST(char opcode
, ExprAST
*operand
)
154 : Opcode(opcode
), Operand(operand
) {}
155 virtual Value
*Codegen();
158 /// BinaryExprAST - Expression class for a binary operator.
159 class BinaryExprAST
: public ExprAST
{
164 BinaryExprAST(char op
, ExprAST
*lhs
, ExprAST
*rhs
)
165 : Op(op
), LHS(lhs
), RHS(rhs
) {}
166 virtual Value
*Codegen();
169 /// CallExprAST - Expression class for function calls.
170 class CallExprAST
: public ExprAST
{
172 std::vector
<ExprAST
*> Args
;
175 CallExprAST(const std::string
&callee
, std::vector
<ExprAST
*> &args
)
176 : Callee(callee
), Args(args
) {}
177 virtual Value
*Codegen();
180 /// IfExprAST - Expression class for if/then/else.
181 class IfExprAST
: public ExprAST
{
182 ExprAST
*Cond
, *Then
, *Else
;
185 IfExprAST(ExprAST
*cond
, ExprAST
*then
, ExprAST
*_else
)
186 : Cond(cond
), Then(then
), Else(_else
) {}
187 virtual Value
*Codegen();
190 /// ForExprAST - Expression class for for/in.
191 class ForExprAST
: public ExprAST
{
193 ExprAST
*Start
, *End
, *Step
, *Body
;
196 ForExprAST(const std::string
&varname
, ExprAST
*start
, ExprAST
*end
,
197 ExprAST
*step
, ExprAST
*body
)
198 : VarName(varname
), Start(start
), End(end
), Step(step
), Body(body
) {}
199 virtual Value
*Codegen();
202 /// PrototypeAST - This class represents the "prototype" for a function,
203 /// which captures its name, and its argument names (thus implicitly the number
204 /// of arguments the function takes), as well as if it is an operator.
207 std::vector
<std::string
> Args
;
209 unsigned Precedence
; // Precedence if a binary op.
211 PrototypeAST(const std::string
&name
, const std::vector
<std::string
> &args
,
212 bool isoperator
= false, unsigned prec
= 0)
213 : Name(name
), Args(args
), isOperator(isoperator
), Precedence(prec
) {}
215 bool isUnaryOp() const { return isOperator
&& Args
.size() == 1; }
216 bool isBinaryOp() const { return isOperator
&& Args
.size() == 2; }
218 char getOperatorName() const {
219 assert(isUnaryOp() || isBinaryOp());
220 return Name
[Name
.size() - 1];
223 unsigned getBinaryPrecedence() const { return Precedence
; }
228 /// FunctionAST - This class represents a function definition itself.
234 FunctionAST(PrototypeAST
*proto
, ExprAST
*body
) : Proto(proto
), Body(body
) {}
238 } // end anonymous namespace
240 //===----------------------------------------------------------------------===//
242 //===----------------------------------------------------------------------===//
244 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
245 /// token the parser is looking at. getNextToken reads another token from the
246 /// lexer and updates CurTok with its results.
248 static int getNextToken() { return CurTok
= gettok(); }
250 /// BinopPrecedence - This holds the precedence for each binary operator that is
252 static std::map
<char, int> BinopPrecedence
;
254 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
255 static int GetTokPrecedence() {
256 if (!isascii(CurTok
))
259 // Make sure it's a declared binop.
260 int TokPrec
= BinopPrecedence
[CurTok
];
266 /// Error* - These are little helper functions for error handling.
267 ExprAST
*Error(const char *Str
) {
268 fprintf(stderr
, "Error: %s\n", Str
);
271 PrototypeAST
*ErrorP(const char *Str
) {
275 FunctionAST
*ErrorF(const char *Str
) {
280 static ExprAST
*ParseExpression();
284 /// ::= identifier '(' expression* ')'
285 static ExprAST
*ParseIdentifierExpr() {
286 std::string IdName
= IdentifierStr
;
288 getNextToken(); // eat identifier.
290 if (CurTok
!= '(') // Simple variable ref.
291 return new VariableExprAST(IdName
);
294 getNextToken(); // eat (
295 std::vector
<ExprAST
*> Args
;
298 ExprAST
*Arg
= ParseExpression();
307 return Error("Expected ')' or ',' in argument list");
315 return new CallExprAST(IdName
, Args
);
318 /// numberexpr ::= number
319 static ExprAST
*ParseNumberExpr() {
320 ExprAST
*Result
= new NumberExprAST(NumVal
);
321 getNextToken(); // consume the number
325 /// parenexpr ::= '(' expression ')'
326 static ExprAST
*ParseParenExpr() {
327 getNextToken(); // eat (.
328 ExprAST
*V
= ParseExpression();
333 return Error("expected ')'");
334 getNextToken(); // eat ).
338 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
339 static ExprAST
*ParseIfExpr() {
340 getNextToken(); // eat the if.
343 ExprAST
*Cond
= ParseExpression();
347 if (CurTok
!= tok_then
)
348 return Error("expected then");
349 getNextToken(); // eat the then
351 ExprAST
*Then
= ParseExpression();
355 if (CurTok
!= tok_else
)
356 return Error("expected else");
360 ExprAST
*Else
= ParseExpression();
364 return new IfExprAST(Cond
, Then
, Else
);
367 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
368 static ExprAST
*ParseForExpr() {
369 getNextToken(); // eat the for.
371 if (CurTok
!= tok_identifier
)
372 return Error("expected identifier after for");
374 std::string IdName
= IdentifierStr
;
375 getNextToken(); // eat identifier.
378 return Error("expected '=' after for");
379 getNextToken(); // eat '='.
381 ExprAST
*Start
= ParseExpression();
385 return Error("expected ',' after for start value");
388 ExprAST
*End
= ParseExpression();
392 // The step value is optional.
396 Step
= ParseExpression();
401 if (CurTok
!= tok_in
)
402 return Error("expected 'in' after for");
403 getNextToken(); // eat 'in'.
405 ExprAST
*Body
= ParseExpression();
409 return new ForExprAST(IdName
, Start
, End
, Step
, Body
);
413 /// ::= identifierexpr
418 static ExprAST
*ParsePrimary() {
421 return Error("unknown token when expecting an expression");
423 return ParseIdentifierExpr();
425 return ParseNumberExpr();
427 return ParseParenExpr();
429 return ParseIfExpr();
431 return ParseForExpr();
438 static ExprAST
*ParseUnary() {
439 // If the current token is not an operator, it must be a primary expr.
440 if (!isascii(CurTok
) || CurTok
== '(' || CurTok
== ',')
441 return ParsePrimary();
443 // If this is a unary operator, read it.
446 if (ExprAST
*Operand
= ParseUnary())
447 return new UnaryExprAST(Opc
, Operand
);
453 static ExprAST
*ParseBinOpRHS(int ExprPrec
, ExprAST
*LHS
) {
454 // If this is a binop, find its precedence.
456 int TokPrec
= GetTokPrecedence();
458 // If this is a binop that binds at least as tightly as the current binop,
459 // consume it, otherwise we are done.
460 if (TokPrec
< ExprPrec
)
463 // Okay, we know this is a binop.
465 getNextToken(); // eat binop
467 // Parse the unary expression after the binary operator.
468 ExprAST
*RHS
= ParseUnary();
472 // If BinOp binds less tightly with RHS than the operator after RHS, let
473 // the pending operator take RHS as its LHS.
474 int NextPrec
= GetTokPrecedence();
475 if (TokPrec
< NextPrec
) {
476 RHS
= ParseBinOpRHS(TokPrec
+ 1, RHS
);
482 LHS
= new BinaryExprAST(BinOp
, LHS
, RHS
);
487 /// ::= unary binoprhs
489 static ExprAST
*ParseExpression() {
490 ExprAST
*LHS
= ParseUnary();
494 return ParseBinOpRHS(0, LHS
);
498 /// ::= id '(' id* ')'
499 /// ::= binary LETTER number? (id, id)
500 /// ::= unary LETTER (id)
501 static PrototypeAST
*ParsePrototype() {
504 unsigned Kind
= 0; // 0 = identifier, 1 = unary, 2 = binary.
505 unsigned BinaryPrecedence
= 30;
509 return ErrorP("Expected function name in prototype");
511 FnName
= IdentifierStr
;
517 if (!isascii(CurTok
))
518 return ErrorP("Expected unary operator");
520 FnName
+= (char)CurTok
;
526 if (!isascii(CurTok
))
527 return ErrorP("Expected binary operator");
529 FnName
+= (char)CurTok
;
533 // Read the precedence if present.
534 if (CurTok
== tok_number
) {
535 if (NumVal
< 1 || NumVal
> 100)
536 return ErrorP("Invalid precedecnce: must be 1..100");
537 BinaryPrecedence
= (unsigned)NumVal
;
544 return ErrorP("Expected '(' in prototype");
546 std::vector
<std::string
> ArgNames
;
547 while (getNextToken() == tok_identifier
)
548 ArgNames
.push_back(IdentifierStr
);
550 return ErrorP("Expected ')' in prototype");
553 getNextToken(); // eat ')'.
555 // Verify right number of names for operator.
556 if (Kind
&& ArgNames
.size() != Kind
)
557 return ErrorP("Invalid number of operands for operator");
559 return new PrototypeAST(FnName
, ArgNames
, Kind
!= 0, BinaryPrecedence
);
562 /// definition ::= 'def' prototype expression
563 static FunctionAST
*ParseDefinition() {
564 getNextToken(); // eat def.
565 PrototypeAST
*Proto
= ParsePrototype();
569 if (ExprAST
*E
= ParseExpression())
570 return new FunctionAST(Proto
, E
);
574 /// toplevelexpr ::= expression
575 static FunctionAST
*ParseTopLevelExpr() {
576 if (ExprAST
*E
= ParseExpression()) {
577 // Make an anonymous proto.
578 PrototypeAST
*Proto
= new PrototypeAST("", std::vector
<std::string
>());
579 return new FunctionAST(Proto
, E
);
584 /// external ::= 'extern' prototype
585 static PrototypeAST
*ParseExtern() {
586 getNextToken(); // eat extern.
587 return ParsePrototype();
590 //===----------------------------------------------------------------------===//
592 //===----------------------------------------------------------------------===//
594 static Module
*TheModule
;
595 static IRBuilder
<> Builder(getGlobalContext());
596 static std::map
<std::string
, Value
*> NamedValues
;
597 static FunctionPassManager
*TheFPM
;
599 Value
*ErrorV(const char *Str
) {
604 Value
*NumberExprAST::Codegen() {
605 return ConstantFP::get(getGlobalContext(), APFloat(Val
));
608 Value
*VariableExprAST::Codegen() {
609 // Look this variable up in the function.
610 Value
*V
= NamedValues
[Name
];
611 return V
? V
: ErrorV("Unknown variable name");
614 Value
*UnaryExprAST::Codegen() {
615 Value
*OperandV
= Operand
->Codegen();
619 Function
*F
= TheModule
->getFunction(std::string("unary") + Opcode
);
621 return ErrorV("Unknown unary operator");
623 return Builder
.CreateCall(F
, OperandV
, "unop");
626 Value
*BinaryExprAST::Codegen() {
627 Value
*L
= LHS
->Codegen();
628 Value
*R
= RHS
->Codegen();
629 if (L
== 0 || R
== 0)
634 return Builder
.CreateFAdd(L
, R
, "addtmp");
636 return Builder
.CreateFSub(L
, R
, "subtmp");
638 return Builder
.CreateFMul(L
, R
, "multmp");
640 L
= Builder
.CreateFCmpULT(L
, R
, "cmptmp");
641 // Convert bool 0/1 to double 0.0 or 1.0
642 return Builder
.CreateUIToFP(L
, Type::getDoubleTy(getGlobalContext()),
648 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
650 Function
*F
= TheModule
->getFunction(std::string("binary") + Op
);
651 assert(F
&& "binary operator not found!");
653 Value
*Ops
[] = { L
, R
};
654 return Builder
.CreateCall(F
, Ops
, "binop");
657 Value
*CallExprAST::Codegen() {
658 // Look up the name in the global module table.
659 Function
*CalleeF
= TheModule
->getFunction(Callee
);
661 return ErrorV("Unknown function referenced");
663 // If argument mismatch error.
664 if (CalleeF
->arg_size() != Args
.size())
665 return ErrorV("Incorrect # arguments passed");
667 std::vector
<Value
*> ArgsV
;
668 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; ++i
) {
669 ArgsV
.push_back(Args
[i
]->Codegen());
670 if (ArgsV
.back() == 0)
674 return Builder
.CreateCall(CalleeF
, ArgsV
, "calltmp");
677 Value
*IfExprAST::Codegen() {
678 Value
*CondV
= Cond
->Codegen();
682 // Convert condition to a bool by comparing equal to 0.0.
683 CondV
= Builder
.CreateFCmpONE(
684 CondV
, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
686 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
688 // Create blocks for the then and else cases. Insert the 'then' block at the
689 // end of the function.
691 BasicBlock::Create(getGlobalContext(), "then", TheFunction
);
692 BasicBlock
*ElseBB
= BasicBlock::Create(getGlobalContext(), "else");
693 BasicBlock
*MergeBB
= BasicBlock::Create(getGlobalContext(), "ifcont");
695 Builder
.CreateCondBr(CondV
, ThenBB
, ElseBB
);
698 Builder
.SetInsertPoint(ThenBB
);
700 Value
*ThenV
= Then
->Codegen();
704 Builder
.CreateBr(MergeBB
);
705 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
706 ThenBB
= Builder
.GetInsertBlock();
709 TheFunction
->getBasicBlockList().push_back(ElseBB
);
710 Builder
.SetInsertPoint(ElseBB
);
712 Value
*ElseV
= Else
->Codegen();
716 Builder
.CreateBr(MergeBB
);
717 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
718 ElseBB
= Builder
.GetInsertBlock();
721 TheFunction
->getBasicBlockList().push_back(MergeBB
);
722 Builder
.SetInsertPoint(MergeBB
);
724 Builder
.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
726 PN
->addIncoming(ThenV
, ThenBB
);
727 PN
->addIncoming(ElseV
, ElseBB
);
731 Value
*ForExprAST::Codegen() {
737 // variable = phi [start, loopheader], [nextvariable, loopend]
743 // nextvariable = variable + step
745 // br endcond, loop, endloop
748 // Emit the start code first, without 'variable' in scope.
749 Value
*StartVal
= Start
->Codegen();
753 // Make the new basic block for the loop header, inserting after current
755 Function
*TheFunction
= Builder
.GetInsertBlock()->getParent();
756 BasicBlock
*PreheaderBB
= Builder
.GetInsertBlock();
758 BasicBlock::Create(getGlobalContext(), "loop", TheFunction
);
760 // Insert an explicit fall through from the current block to the LoopBB.
761 Builder
.CreateBr(LoopBB
);
763 // Start insertion in LoopBB.
764 Builder
.SetInsertPoint(LoopBB
);
766 // Start the PHI node with an entry for Start.
767 PHINode
*Variable
= Builder
.CreatePHI(Type::getDoubleTy(getGlobalContext()),
769 Variable
->addIncoming(StartVal
, PreheaderBB
);
771 // Within the loop, the variable is defined equal to the PHI node. If it
772 // shadows an existing variable, we have to restore it, so save it now.
773 Value
*OldVal
= NamedValues
[VarName
];
774 NamedValues
[VarName
] = Variable
;
776 // Emit the body of the loop. This, like any other expr, can change the
777 // current BB. Note that we ignore the value computed by the body, but don't
779 if (Body
->Codegen() == 0)
782 // Emit the step value.
785 StepVal
= Step
->Codegen();
789 // If not specified, use 1.0.
790 StepVal
= ConstantFP::get(getGlobalContext(), APFloat(1.0));
793 Value
*NextVar
= Builder
.CreateFAdd(Variable
, StepVal
, "nextvar");
795 // Compute the end condition.
796 Value
*EndCond
= End
->Codegen();
800 // Convert condition to a bool by comparing equal to 0.0.
801 EndCond
= Builder
.CreateFCmpONE(
802 EndCond
, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
804 // Create the "after loop" block and insert it.
805 BasicBlock
*LoopEndBB
= Builder
.GetInsertBlock();
806 BasicBlock
*AfterBB
=
807 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction
);
809 // Insert the conditional branch into the end of LoopEndBB.
810 Builder
.CreateCondBr(EndCond
, LoopBB
, AfterBB
);
812 // Any new code will be inserted in AfterBB.
813 Builder
.SetInsertPoint(AfterBB
);
815 // Add a new entry to the PHI node for the backedge.
816 Variable
->addIncoming(NextVar
, LoopEndBB
);
818 // Restore the unshadowed variable.
820 NamedValues
[VarName
] = OldVal
;
822 NamedValues
.erase(VarName
);
824 // for expr always returns 0.0.
825 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
828 Function
*PrototypeAST::Codegen() {
829 // Make the function type: double(double,double) etc.
830 std::vector
<Type
*> Doubles(Args
.size(),
831 Type::getDoubleTy(getGlobalContext()));
833 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles
, false);
836 Function::Create(FT
, Function::ExternalLinkage
, Name
, TheModule
);
838 // If F conflicted, there was already something named 'Name'. If it has a
839 // body, don't allow redefinition or reextern.
840 if (F
->getName() != Name
) {
841 // Delete the one we just made and get the existing one.
842 F
->eraseFromParent();
843 F
= TheModule
->getFunction(Name
);
845 // If F already has a body, reject this.
847 ErrorF("redefinition of function");
851 // If F took a different number of args, reject.
852 if (F
->arg_size() != Args
.size()) {
853 ErrorF("redefinition of function with different # args");
858 // Set names for all arguments.
860 for (Function::arg_iterator AI
= F
->arg_begin(); Idx
!= Args
.size();
862 AI
->setName(Args
[Idx
]);
864 // Add arguments to variable symbol table.
865 NamedValues
[Args
[Idx
]] = AI
;
871 Function
*FunctionAST::Codegen() {
874 Function
*TheFunction
= Proto
->Codegen();
875 if (TheFunction
== 0)
878 // If this is an operator, install it.
879 if (Proto
->isBinaryOp())
880 BinopPrecedence
[Proto
->getOperatorName()] = Proto
->getBinaryPrecedence();
882 // Create a new basic block to start insertion into.
883 BasicBlock
*BB
= BasicBlock::Create(getGlobalContext(), "entry", TheFunction
);
884 Builder
.SetInsertPoint(BB
);
886 if (Value
*RetVal
= Body
->Codegen()) {
887 // Finish off the function.
888 Builder
.CreateRet(RetVal
);
890 // Validate the generated code, checking for consistency.
891 verifyFunction(*TheFunction
);
893 // Optimize the function.
894 TheFPM
->run(*TheFunction
);
899 // Error reading body, remove function.
900 TheFunction
->eraseFromParent();
902 if (Proto
->isBinaryOp())
903 BinopPrecedence
.erase(Proto
->getOperatorName());
907 //===----------------------------------------------------------------------===//
908 // Top-Level parsing and JIT Driver
909 //===----------------------------------------------------------------------===//
911 static ExecutionEngine
*TheExecutionEngine
;
913 static void HandleDefinition() {
914 if (FunctionAST
*F
= ParseDefinition()) {
915 if (Function
*LF
= F
->Codegen()) {
916 fprintf(stderr
, "Read function definition:");
920 // Skip token for error recovery.
925 static void HandleExtern() {
926 if (PrototypeAST
*P
= ParseExtern()) {
927 if (Function
*F
= P
->Codegen()) {
928 fprintf(stderr
, "Read extern: ");
932 // Skip token for error recovery.
937 static void HandleTopLevelExpression() {
938 // Evaluate a top-level expression into an anonymous function.
939 if (FunctionAST
*F
= ParseTopLevelExpr()) {
940 if (Function
*LF
= F
->Codegen()) {
941 TheExecutionEngine
->finalizeObject();
942 // JIT the function, returning a function pointer.
943 void *FPtr
= TheExecutionEngine
->getPointerToFunction(LF
);
945 // Cast it to the right type (takes no arguments, returns a double) so we
946 // can call it as a native function.
947 double (*FP
)() = (double (*)())(intptr_t)FPtr
;
948 fprintf(stderr
, "Evaluated to %f\n", FP());
951 // Skip token for error recovery.
956 /// top ::= definition | external | expression | ';'
957 static void MainLoop() {
959 fprintf(stderr
, "ready> ");
965 break; // ignore top-level semicolons.
973 HandleTopLevelExpression();
979 //===----------------------------------------------------------------------===//
980 // "Library" functions that can be "extern'd" from user code.
981 //===----------------------------------------------------------------------===//
983 /// putchard - putchar that takes a double and returns 0.
984 extern "C" double putchard(double X
) {
989 /// printd - printf that takes a double prints it as "%f\n", returning 0.
990 extern "C" double printd(double X
) {
995 //===----------------------------------------------------------------------===//
997 //===----------------------------------------------------------------------===//
1000 InitializeNativeTarget();
1001 InitializeNativeTargetAsmPrinter();
1002 InitializeNativeTargetAsmParser();
1003 LLVMContext
&Context
= getGlobalContext();
1005 // Install standard binary operators.
1006 // 1 is lowest precedence.
1007 BinopPrecedence
['<'] = 10;
1008 BinopPrecedence
['+'] = 20;
1009 BinopPrecedence
['-'] = 20;
1010 BinopPrecedence
['*'] = 40; // highest.
1012 // Prime the first token.
1013 fprintf(stderr
, "ready> ");
1016 // Make the module, which holds all the code.
1017 std::unique_ptr
<Module
> Owner
= make_unique
<Module
>("my cool jit", Context
);
1018 TheModule
= Owner
.get();
1020 // Create the JIT. This takes ownership of the module.
1022 TheExecutionEngine
=
1023 EngineBuilder(std::move(Owner
))
1024 .setErrorStr(&ErrStr
)
1025 .setMCJITMemoryManager(llvm::make_unique
<SectionMemoryManager
>())
1027 if (!TheExecutionEngine
) {
1028 fprintf(stderr
, "Could not create ExecutionEngine: %s\n", ErrStr
.c_str());
1032 FunctionPassManager
OurFPM(TheModule
);
1034 // Set up the optimizer pipeline. Start with registering info about how the
1035 // target lays out data structures.
1036 TheModule
->setDataLayout(TheExecutionEngine
->getDataLayout());
1037 OurFPM
.add(new DataLayoutPass());
1038 // Provide basic AliasAnalysis support for GVN.
1039 OurFPM
.add(createBasicAliasAnalysisPass());
1040 // Do simple "peephole" optimizations and bit-twiddling optzns.
1041 OurFPM
.add(createInstructionCombiningPass());
1042 // Reassociate expressions.
1043 OurFPM
.add(createReassociatePass());
1044 // Eliminate Common SubExpressions.
1045 OurFPM
.add(createGVNPass());
1046 // Simplify the control flow graph (deleting unreachable blocks, etc).
1047 OurFPM
.add(createCFGSimplificationPass());
1049 OurFPM
.doInitialization();
1051 // Set the global so the code gen can use this.
1054 // Run the main "interpreter loop" now.
1059 // Print out all of the generated code.