1 #include "llvm/ADT/STLExtras.h"
2 #include "llvm/Analysis/BasicAliasAnalysis.h"
3 #include "llvm/Analysis/Passes.h"
4 #include "llvm/ExecutionEngine/ExecutionEngine.h"
5 #include "llvm/ExecutionEngine/MCJIT.h"
6 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
7 #include "llvm/IR/DataLayout.h"
8 #include "llvm/IR/DerivedTypes.h"
9 #include "llvm/IR/IRBuilder.h"
10 #include "llvm/IR/LLVMContext.h"
11 #include "llvm/IR/LegacyPassManager.h"
12 #include "llvm/IR/Module.h"
13 #include "llvm/IR/Verifier.h"
14 #include "llvm/Support/TargetSelect.h"
15 #include "llvm/Transforms/Scalar.h"
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
28 // of these for known things.
52 static std::string IdentifierStr; // Filled in if tok_identifier
53 static double NumVal; // Filled in if tok_number
55 /// gettok - Return the next token from standard input.
57 static int LastChar = ' ';
59 // Skip any whitespace.
60 while (isspace(LastChar))
63 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
64 IdentifierStr = LastChar;
65 while (isalnum((LastChar = getchar())))
66 IdentifierStr += LastChar;
68 if (IdentifierStr == "def")
70 if (IdentifierStr == "extern")
72 if (IdentifierStr == "if")
74 if (IdentifierStr == "then")
76 if (IdentifierStr == "else")
78 if (IdentifierStr == "for")
80 if (IdentifierStr == "in")
82 if (IdentifierStr == "binary")
84 if (IdentifierStr == "unary")
86 return tok_identifier;
89 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
94 } while (isdigit(LastChar) || LastChar == '.');
96 NumVal = strtod(NumStr.c_str(), 0);
100 if (LastChar == '#') {
101 // Comment until end of line.
103 LastChar = getchar();
104 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
110 // Check for end of file. Don't eat the EOF.
114 // Otherwise, just return the character as its ascii value.
115 int ThisChar = LastChar;
116 LastChar = getchar();
120 //===----------------------------------------------------------------------===//
121 // Abstract Syntax Tree (aka Parse Tree)
122 //===----------------------------------------------------------------------===//
124 /// ExprAST - Base class for all expression nodes.
127 virtual ~ExprAST() {}
128 virtual Value *Codegen() = 0;
131 /// NumberExprAST - Expression class for numeric literals like "1.0".
132 class NumberExprAST : public ExprAST {
136 NumberExprAST(double Val) : Val(Val) {}
137 Value *Codegen() override;
140 /// VariableExprAST - Expression class for referencing a variable, like "a".
141 class VariableExprAST : public ExprAST {
145 VariableExprAST(const std::string &Name) : Name(Name) {}
146 Value *Codegen() override;
149 /// UnaryExprAST - Expression class for a unary operator.
150 class UnaryExprAST : public ExprAST {
152 std::unique_ptr<ExprAST> Operand;
155 UnaryExprAST(char Opcode, std::unique_ptr<ExprAST> Operand)
156 : Opcode(Opcode), Operand(std::move(Operand)) {}
157 Value *Codegen() override;
160 /// BinaryExprAST - Expression class for a binary operator.
161 class BinaryExprAST : public ExprAST {
163 std::unique_ptr<ExprAST> LHS, RHS;
166 BinaryExprAST(char Op, std::unique_ptr<ExprAST> LHS,
167 std::unique_ptr<ExprAST> RHS)
168 : Op(Op), LHS(std::move(LHS)), RHS(std::move(RHS)) {}
169 Value *Codegen() override;
172 /// CallExprAST - Expression class for function calls.
173 class CallExprAST : public ExprAST {
175 std::vector<std::unique_ptr<ExprAST>> Args;
178 CallExprAST(const std::string &Callee,
179 std::vector<std::unique_ptr<ExprAST>> Args)
180 : Callee(Callee), Args(std::move(Args)) {}
181 Value *Codegen() override;
184 /// IfExprAST - Expression class for if/then/else.
185 class IfExprAST : public ExprAST {
186 std::unique_ptr<ExprAST> Cond, Then, Else;
189 IfExprAST(std::unique_ptr<ExprAST> Cond, std::unique_ptr<ExprAST> Then,
190 std::unique_ptr<ExprAST> Else)
191 : Cond(std::move(Cond)), Then(std::move(Then)), Else(std::move(Else)) {}
192 Value *Codegen() override;
195 /// ForExprAST - Expression class for for/in.
196 class ForExprAST : public ExprAST {
198 std::unique_ptr<ExprAST> Start, End, Step, Body;
201 ForExprAST(const std::string &VarName, std::unique_ptr<ExprAST> Start,
202 std::unique_ptr<ExprAST> End, std::unique_ptr<ExprAST> Step,
203 std::unique_ptr<ExprAST> Body)
204 : VarName(VarName), Start(std::move(Start)), End(std::move(End)),
205 Step(std::move(Step)), Body(std::move(Body)) {}
206 Value *Codegen() override;
209 /// PrototypeAST - This class represents the "prototype" for a function,
210 /// which captures its name, and its argument names (thus implicitly the number
211 /// of arguments the function takes), as well as if it is an operator.
214 std::vector<std::string> Args;
216 unsigned Precedence; // Precedence if a binary op.
219 PrototypeAST(const std::string &Name, std::vector<std::string> Args,
220 bool IsOperator = false, unsigned Prec = 0)
221 : Name(Name), Args(std::move(Args)), IsOperator(IsOperator),
224 bool isUnaryOp() const { return IsOperator && Args.size() == 1; }
225 bool isBinaryOp() const { return IsOperator && Args.size() == 2; }
227 char getOperatorName() const {
228 assert(isUnaryOp() || isBinaryOp());
229 return Name[Name.size() - 1];
232 unsigned getBinaryPrecedence() const { return Precedence; }
237 /// FunctionAST - This class represents a function definition itself.
239 std::unique_ptr<PrototypeAST> Proto;
240 std::unique_ptr<ExprAST> Body;
243 FunctionAST(std::unique_ptr<PrototypeAST> Proto,
244 std::unique_ptr<ExprAST> Body)
245 : Proto(std::move(Proto)), Body(std::move(Body)) {}
248 } // end anonymous namespace
250 //===----------------------------------------------------------------------===//
252 //===----------------------------------------------------------------------===//
254 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
255 /// token the parser is looking at. getNextToken reads another token from the
256 /// lexer and updates CurTok with its results.
258 static int getNextToken() { return CurTok = gettok(); }
260 /// BinopPrecedence - This holds the precedence for each binary operator that is
262 static std::map<char, int> BinopPrecedence;
264 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
265 static int GetTokPrecedence() {
266 if (!isascii(CurTok))
269 // Make sure it's a declared binop.
270 int TokPrec = BinopPrecedence[CurTok];
276 /// Error* - These are little helper functions for error handling.
277 std::unique_ptr<ExprAST> Error(const char *Str) {
278 fprintf(stderr, "Error: %s\n", Str);
281 std::unique_ptr<PrototypeAST> ErrorP(const char *Str) {
285 std::unique_ptr<FunctionAST> ErrorF(const char *Str) {
290 static std::unique_ptr<ExprAST> ParseExpression();
292 /// numberexpr ::= number
293 static std::unique_ptr<ExprAST> ParseNumberExpr() {
294 auto Result = llvm::make_unique<NumberExprAST>(NumVal);
295 getNextToken(); // consume the number
296 return std::move(Result);
299 /// parenexpr ::= '(' expression ')'
300 static std::unique_ptr<ExprAST> ParseParenExpr() {
301 getNextToken(); // eat (.
302 auto V = ParseExpression();
307 return Error("expected ')'");
308 getNextToken(); // eat ).
314 /// ::= identifier '(' expression* ')'
315 static std::unique_ptr<ExprAST> ParseIdentifierExpr() {
316 std::string IdName = IdentifierStr;
318 getNextToken(); // eat identifier.
320 if (CurTok != '(') // Simple variable ref.
321 return llvm::make_unique<VariableExprAST>(IdName);
324 getNextToken(); // eat (
325 std::vector<std::unique_ptr<ExprAST>> Args;
328 if (auto Arg = ParseExpression())
329 Args.push_back(std::move(Arg));
337 return Error("Expected ')' or ',' in argument list");
345 return llvm::make_unique<CallExprAST>(IdName, std::move(Args));
348 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
349 static std::unique_ptr<ExprAST> ParseIfExpr() {
350 getNextToken(); // eat the if.
353 auto Cond = ParseExpression();
357 if (CurTok != tok_then)
358 return Error("expected then");
359 getNextToken(); // eat the then
361 auto Then = ParseExpression();
365 if (CurTok != tok_else)
366 return Error("expected else");
370 auto Else = ParseExpression();
374 return llvm::make_unique<IfExprAST>(std::move(Cond), std::move(Then),
378 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
379 static std::unique_ptr<ExprAST> ParseForExpr() {
380 getNextToken(); // eat the for.
382 if (CurTok != tok_identifier)
383 return Error("expected identifier after for");
385 std::string IdName = IdentifierStr;
386 getNextToken(); // eat identifier.
389 return Error("expected '=' after for");
390 getNextToken(); // eat '='.
392 auto Start = ParseExpression();
396 return Error("expected ',' after for start value");
399 auto End = ParseExpression();
403 // The step value is optional.
404 std::unique_ptr<ExprAST> Step;
407 Step = ParseExpression();
412 if (CurTok != tok_in)
413 return Error("expected 'in' after for");
414 getNextToken(); // eat 'in'.
416 auto Body = ParseExpression();
420 return llvm::make_unique<ForExprAST>(IdName, std::move(Start), std::move(End),
421 std::move(Step), std::move(Body));
425 /// ::= identifierexpr
430 static std::unique_ptr<ExprAST> ParsePrimary() {
433 return Error("unknown token when expecting an expression");
435 return ParseIdentifierExpr();
437 return ParseNumberExpr();
439 return ParseParenExpr();
441 return ParseIfExpr();
443 return ParseForExpr();
450 static std::unique_ptr<ExprAST> ParseUnary() {
451 // If the current token is not an operator, it must be a primary expr.
452 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
453 return ParsePrimary();
455 // If this is a unary operator, read it.
458 if (auto Operand = ParseUnary())
459 return llvm::make_unique<UnaryExprAST>(Opc, std::move(Operand));
465 static std::unique_ptr<ExprAST> ParseBinOpRHS(int ExprPrec,
466 std::unique_ptr<ExprAST> LHS) {
467 // If this is a binop, find its precedence.
469 int TokPrec = GetTokPrecedence();
471 // If this is a binop that binds at least as tightly as the current binop,
472 // consume it, otherwise we are done.
473 if (TokPrec < ExprPrec)
476 // Okay, we know this is a binop.
478 getNextToken(); // eat binop
480 // Parse the unary expression after the binary operator.
481 auto 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, std::move(RHS));
496 llvm::make_unique<BinaryExprAST>(BinOp, std::move(LHS), std::move(RHS));
501 /// ::= unary binoprhs
503 static std::unique_ptr<ExprAST> ParseExpression() {
504 auto LHS = ParseUnary();
508 return ParseBinOpRHS(0, std::move(LHS));
512 /// ::= id '(' id* ')'
513 /// ::= binary LETTER number? (id, id)
514 /// ::= unary LETTER (id)
515 static std::unique_ptr<PrototypeAST> ParsePrototype() {
518 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
519 unsigned BinaryPrecedence = 30;
523 return ErrorP("Expected function name in prototype");
525 FnName = IdentifierStr;
531 if (!isascii(CurTok))
532 return ErrorP("Expected unary operator");
534 FnName += (char)CurTok;
540 if (!isascii(CurTok))
541 return ErrorP("Expected binary operator");
543 FnName += (char)CurTok;
547 // Read the precedence if present.
548 if (CurTok == tok_number) {
549 if (NumVal < 1 || NumVal > 100)
550 return ErrorP("Invalid precedecnce: must be 1..100");
551 BinaryPrecedence = (unsigned)NumVal;
558 return ErrorP("Expected '(' in prototype");
560 std::vector<std::string> ArgNames;
561 while (getNextToken() == tok_identifier)
562 ArgNames.push_back(IdentifierStr);
564 return ErrorP("Expected ')' in prototype");
567 getNextToken(); // eat ')'.
569 // Verify right number of names for operator.
570 if (Kind && ArgNames.size() != Kind)
571 return ErrorP("Invalid number of operands for operator");
573 return llvm::make_unique<PrototypeAST>(FnName, ArgNames, Kind != 0,
577 /// definition ::= 'def' prototype expression
578 static std::unique_ptr<FunctionAST> ParseDefinition() {
579 getNextToken(); // eat def.
580 auto Proto = ParsePrototype();
584 if (auto E = ParseExpression())
585 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
589 /// toplevelexpr ::= expression
590 static std::unique_ptr<FunctionAST> ParseTopLevelExpr() {
591 if (auto E = ParseExpression()) {
592 // Make an anonymous proto.
594 llvm::make_unique<PrototypeAST>("", std::vector<std::string>());
595 return llvm::make_unique<FunctionAST>(std::move(Proto), std::move(E));
600 /// external ::= 'extern' prototype
601 static std::unique_ptr<PrototypeAST> ParseExtern() {
602 getNextToken(); // eat extern.
603 return ParsePrototype();
606 //===----------------------------------------------------------------------===//
608 //===----------------------------------------------------------------------===//
610 static Module *TheModule;
611 static IRBuilder<> Builder(getGlobalContext());
612 static std::map<std::string, Value *> NamedValues;
613 static legacy::FunctionPassManager *TheFPM;
615 Value *ErrorV(const char *Str) {
620 Value *NumberExprAST::Codegen() {
621 return ConstantFP::get(getGlobalContext(), APFloat(Val));
624 Value *VariableExprAST::Codegen() {
625 // Look this variable up in the function.
626 Value *V = NamedValues[Name];
628 return ErrorV("Unknown variable name");
632 Value *UnaryExprAST::Codegen() {
633 Value *OperandV = Operand->Codegen();
637 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
639 return ErrorV("Unknown unary operator");
641 return Builder.CreateCall(F, OperandV, "unop");
644 Value *BinaryExprAST::Codegen() {
645 Value *L = LHS->Codegen();
646 Value *R = RHS->Codegen();
652 return Builder.CreateFAdd(L, R, "addtmp");
654 return Builder.CreateFSub(L, R, "subtmp");
656 return Builder.CreateFMul(L, R, "multmp");
658 L = Builder.CreateFCmpULT(L, R, "cmptmp");
659 // Convert bool 0/1 to double 0.0 or 1.0
660 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
666 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
668 Function *F = TheModule->getFunction(std::string("binary") + Op);
669 assert(F && "binary operator not found!");
671 Value *Ops[] = {L, R};
672 return Builder.CreateCall(F, Ops, "binop");
675 Value *CallExprAST::Codegen() {
676 // Look up the name in the global module table.
677 Function *CalleeF = TheModule->getFunction(Callee);
679 return ErrorV("Unknown function referenced");
681 // If argument mismatch error.
682 if (CalleeF->arg_size() != Args.size())
683 return ErrorV("Incorrect # arguments passed");
685 std::vector<Value *> ArgsV;
686 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
687 ArgsV.push_back(Args[i]->Codegen());
692 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
695 Value *IfExprAST::Codegen() {
696 Value *CondV = Cond->Codegen();
700 // Convert condition to a bool by comparing equal to 0.0.
701 CondV = Builder.CreateFCmpONE(
702 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
704 Function *TheFunction = Builder.GetInsertBlock()->getParent();
706 // Create blocks for the then and else cases. Insert the 'then' block at the
707 // end of the function.
709 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
710 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
711 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
713 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
716 Builder.SetInsertPoint(ThenBB);
718 Value *ThenV = Then->Codegen();
722 Builder.CreateBr(MergeBB);
723 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
724 ThenBB = Builder.GetInsertBlock();
727 TheFunction->getBasicBlockList().push_back(ElseBB);
728 Builder.SetInsertPoint(ElseBB);
730 Value *ElseV = Else->Codegen();
734 Builder.CreateBr(MergeBB);
735 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
736 ElseBB = Builder.GetInsertBlock();
739 TheFunction->getBasicBlockList().push_back(MergeBB);
740 Builder.SetInsertPoint(MergeBB);
742 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
744 PN->addIncoming(ThenV, ThenBB);
745 PN->addIncoming(ElseV, ElseBB);
749 // Output for-loop as:
754 // variable = phi [start, loopheader], [nextvariable, loopend]
760 // nextvariable = variable + step
762 // br endcond, loop, endloop
764 Value *ForExprAST::Codegen() {
765 // Emit the start code first, without 'variable' in scope.
766 Value *StartVal = Start->Codegen();
770 // Make the new basic block for the loop header, inserting after current
772 Function *TheFunction = Builder.GetInsertBlock()->getParent();
773 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
775 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
777 // Insert an explicit fall through from the current block to the LoopBB.
778 Builder.CreateBr(LoopBB);
780 // Start insertion in LoopBB.
781 Builder.SetInsertPoint(LoopBB);
783 // Start the PHI node with an entry for Start.
784 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
786 Variable->addIncoming(StartVal, PreheaderBB);
788 // Within the loop, the variable is defined equal to the PHI node. If it
789 // shadows an existing variable, we have to restore it, so save it now.
790 Value *OldVal = NamedValues[VarName];
791 NamedValues[VarName] = Variable;
793 // Emit the body of the loop. This, like any other expr, can change the
794 // current BB. Note that we ignore the value computed by the body, but don't
796 if (!Body->Codegen())
799 // Emit the step value.
800 Value *StepVal = nullptr;
802 StepVal = Step->Codegen();
806 // If not specified, use 1.0.
807 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
810 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
812 // Compute the end condition.
813 Value *EndCond = End->Codegen();
817 // Convert condition to a bool by comparing equal to 0.0.
818 EndCond = Builder.CreateFCmpONE(
819 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
821 // Create the "after loop" block and insert it.
822 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
823 BasicBlock *AfterBB =
824 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
826 // Insert the conditional branch into the end of LoopEndBB.
827 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
829 // Any new code will be inserted in AfterBB.
830 Builder.SetInsertPoint(AfterBB);
832 // Add a new entry to the PHI node for the backedge.
833 Variable->addIncoming(NextVar, LoopEndBB);
835 // Restore the unshadowed variable.
837 NamedValues[VarName] = OldVal;
839 NamedValues.erase(VarName);
841 // for expr always returns 0.0.
842 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
845 Function *PrototypeAST::Codegen() {
846 // Make the function type: double(double,double) etc.
847 std::vector<Type *> Doubles(Args.size(),
848 Type::getDoubleTy(getGlobalContext()));
850 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
853 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
855 // If F conflicted, there was already something named 'Name'. If it has a
856 // body, don't allow redefinition or reextern.
857 if (F->getName() != Name) {
858 // Delete the one we just made and get the existing one.
859 F->eraseFromParent();
860 F = TheModule->getFunction(Name);
862 // If F already has a body, reject this.
864 ErrorF("redefinition of function");
868 // If F took a different number of args, reject.
869 if (F->arg_size() != Args.size()) {
870 ErrorF("redefinition of function with different # args");
875 // Set names for all arguments.
877 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
879 AI->setName(Args[Idx]);
881 // Add arguments to variable symbol table.
882 NamedValues[Args[Idx]] = AI;
888 Function *FunctionAST::Codegen() {
891 Function *TheFunction = Proto->Codegen();
895 // If this is an operator, install it.
896 if (Proto->isBinaryOp())
897 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
899 // Create a new basic block to start insertion into.
900 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
901 Builder.SetInsertPoint(BB);
903 if (Value *RetVal = Body->Codegen()) {
904 // Finish off the function.
905 Builder.CreateRet(RetVal);
907 // Validate the generated code, checking for consistency.
908 verifyFunction(*TheFunction);
910 // Optimize the function.
911 TheFPM->run(*TheFunction);
916 // Error reading body, remove function.
917 TheFunction->eraseFromParent();
919 if (Proto->isBinaryOp())
920 BinopPrecedence.erase(Proto->getOperatorName());
924 //===----------------------------------------------------------------------===//
925 // Top-Level parsing and JIT Driver
926 //===----------------------------------------------------------------------===//
928 static ExecutionEngine *TheExecutionEngine;
930 static void HandleDefinition() {
931 if (auto FnAST = ParseDefinition()) {
932 if (auto *FnIR = FnAST->Codegen()) {
933 fprintf(stderr, "Read function definition:");
937 // Skip token for error recovery.
942 static void HandleExtern() {
943 if (auto ProtoAST = ParseExtern()) {
944 if (auto *FnIR = ProtoAST->Codegen()) {
945 fprintf(stderr, "Read extern: ");
949 // Skip token for error recovery.
954 static void HandleTopLevelExpression() {
955 // Evaluate a top-level expression into an anonymous function.
956 if (auto FnAST = ParseTopLevelExpr()) {
957 if (auto *FnIR = FnAST->Codegen()) {
958 TheExecutionEngine->finalizeObject();
959 // JIT the function, returning a function pointer.
960 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
962 // Cast it to the right type (takes no arguments, returns a double) so we
963 // can call it as a native function.
964 double (*FP)() = (double (*)())(intptr_t)FPtr;
965 fprintf(stderr, "Evaluated to %f\n", FP());
968 // Skip token for error recovery.
973 /// top ::= definition | external | expression | ';'
974 static void MainLoop() {
976 fprintf(stderr, "ready> ");
980 case ';': // ignore top-level semicolons.
990 HandleTopLevelExpression();
996 //===----------------------------------------------------------------------===//
997 // "Library" functions that can be "extern'd" from user code.
998 //===----------------------------------------------------------------------===//
1000 /// putchard - putchar that takes a double and returns 0.
1001 extern "C" double putchard(double X) {
1006 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1007 extern "C" double printd(double X) {
1012 //===----------------------------------------------------------------------===//
1013 // Main driver code.
1014 //===----------------------------------------------------------------------===//
1017 InitializeNativeTarget();
1018 InitializeNativeTargetAsmPrinter();
1019 InitializeNativeTargetAsmParser();
1020 LLVMContext &Context = getGlobalContext();
1022 // Install standard binary operators.
1023 // 1 is lowest precedence.
1024 BinopPrecedence['<'] = 10;
1025 BinopPrecedence['+'] = 20;
1026 BinopPrecedence['-'] = 20;
1027 BinopPrecedence['*'] = 40; // highest.
1029 // Prime the first token.
1030 fprintf(stderr, "ready> ");
1033 // Make the module, which holds all the code.
1034 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1035 TheModule = Owner.get();
1037 // Create the JIT. This takes ownership of the module.
1039 TheExecutionEngine =
1040 EngineBuilder(std::move(Owner))
1041 .setErrorStr(&ErrStr)
1042 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1044 if (!TheExecutionEngine) {
1045 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1049 legacy::FunctionPassManager OurFPM(TheModule);
1051 // Set up the optimizer pipeline. Start with registering info about how the
1052 // target lays out data structures.
1053 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1054 // Provide basic AliasAnalysis support for GVN.
1055 OurFPM.add(createBasicAliasAnalysisPass());
1056 // Do simple "peephole" optimizations and bit-twiddling optzns.
1057 OurFPM.add(createInstructionCombiningPass());
1058 // Reassociate expressions.
1059 OurFPM.add(createReassociatePass());
1060 // Eliminate Common SubExpressions.
1061 OurFPM.add(createGVNPass());
1062 // Simplify the control flow graph (deleting unreachable blocks, etc).
1063 OurFPM.add(createCFGSimplificationPass());
1065 OurFPM.doInitialization();
1067 // Set the global so the code gen can use this.
1070 // Run the main "interpreter loop" now.
1075 // Print out all of the generated code.