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");
633 Value *UnaryExprAST::Codegen() {
634 Value *OperandV = Operand->Codegen();
638 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
640 return ErrorV("Unknown unary operator");
642 return Builder.CreateCall(F, OperandV, "unop");
645 Value *BinaryExprAST::Codegen() {
646 Value *L = LHS->Codegen();
647 Value *R = RHS->Codegen();
653 return Builder.CreateFAdd(L, R, "addtmp");
655 return Builder.CreateFSub(L, R, "subtmp");
657 return Builder.CreateFMul(L, R, "multmp");
659 L = Builder.CreateFCmpULT(L, R, "cmptmp");
660 // Convert bool 0/1 to double 0.0 or 1.0
661 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
667 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
669 Function *F = TheModule->getFunction(std::string("binary") + Op);
670 assert(F && "binary operator not found!");
672 Value *Ops[] = {L, R};
673 return Builder.CreateCall(F, Ops, "binop");
676 Value *CallExprAST::Codegen() {
677 // Look up the name in the global module table.
678 Function *CalleeF = TheModule->getFunction(Callee);
680 return ErrorV("Unknown function referenced");
682 // If argument mismatch error.
683 if (CalleeF->arg_size() != Args.size())
684 return ErrorV("Incorrect # arguments passed");
686 std::vector<Value *> ArgsV;
687 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
688 ArgsV.push_back(Args[i]->Codegen());
693 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
696 Value *IfExprAST::Codegen() {
697 Value *CondV = Cond->Codegen();
701 // Convert condition to a bool by comparing equal to 0.0.
702 CondV = Builder.CreateFCmpONE(
703 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
705 Function *TheFunction = Builder.GetInsertBlock()->getParent();
707 // Create blocks for the then and else cases. Insert the 'then' block at the
708 // end of the function.
710 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
711 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
712 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
714 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
717 Builder.SetInsertPoint(ThenBB);
719 Value *ThenV = Then->Codegen();
723 Builder.CreateBr(MergeBB);
724 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
725 ThenBB = Builder.GetInsertBlock();
728 TheFunction->getBasicBlockList().push_back(ElseBB);
729 Builder.SetInsertPoint(ElseBB);
731 Value *ElseV = Else->Codegen();
735 Builder.CreateBr(MergeBB);
736 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
737 ElseBB = Builder.GetInsertBlock();
740 TheFunction->getBasicBlockList().push_back(MergeBB);
741 Builder.SetInsertPoint(MergeBB);
743 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
745 PN->addIncoming(ThenV, ThenBB);
746 PN->addIncoming(ElseV, ElseBB);
750 // Output for-loop as:
755 // variable = phi [start, loopheader], [nextvariable, loopend]
761 // nextvariable = variable + step
763 // br endcond, loop, endloop
765 Value *ForExprAST::Codegen() {
766 // Emit the start code first, without 'variable' in scope.
767 Value *StartVal = Start->Codegen();
771 // Make the new basic block for the loop header, inserting after current
773 Function *TheFunction = Builder.GetInsertBlock()->getParent();
774 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
776 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
778 // Insert an explicit fall through from the current block to the LoopBB.
779 Builder.CreateBr(LoopBB);
781 // Start insertion in LoopBB.
782 Builder.SetInsertPoint(LoopBB);
784 // Start the PHI node with an entry for Start.
785 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
787 Variable->addIncoming(StartVal, PreheaderBB);
789 // Within the loop, the variable is defined equal to the PHI node. If it
790 // shadows an existing variable, we have to restore it, so save it now.
791 Value *OldVal = NamedValues[VarName];
792 NamedValues[VarName] = Variable;
794 // Emit the body of the loop. This, like any other expr, can change the
795 // current BB. Note that we ignore the value computed by the body, but don't
797 if (!Body->Codegen())
800 // Emit the step value.
801 Value *StepVal = nullptr;
803 StepVal = Step->Codegen();
807 // If not specified, use 1.0.
808 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
811 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
813 // Compute the end condition.
814 Value *EndCond = End->Codegen();
818 // Convert condition to a bool by comparing equal to 0.0.
819 EndCond = Builder.CreateFCmpONE(
820 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
822 // Create the "after loop" block and insert it.
823 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
824 BasicBlock *AfterBB =
825 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
827 // Insert the conditional branch into the end of LoopEndBB.
828 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
830 // Any new code will be inserted in AfterBB.
831 Builder.SetInsertPoint(AfterBB);
833 // Add a new entry to the PHI node for the backedge.
834 Variable->addIncoming(NextVar, LoopEndBB);
836 // Restore the unshadowed variable.
838 NamedValues[VarName] = OldVal;
840 NamedValues.erase(VarName);
842 // for expr always returns 0.0.
843 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
846 Function *PrototypeAST::Codegen() {
847 // Make the function type: double(double,double) etc.
848 std::vector<Type *> Doubles(Args.size(),
849 Type::getDoubleTy(getGlobalContext()));
851 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
854 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
856 // If F conflicted, there was already something named 'Name'. If it has a
857 // body, don't allow redefinition or reextern.
858 if (F->getName() != Name) {
859 // Delete the one we just made and get the existing one.
860 F->eraseFromParent();
861 F = TheModule->getFunction(Name);
863 // If F already has a body, reject this.
865 ErrorF("redefinition of function");
869 // If F took a different number of args, reject.
870 if (F->arg_size() != Args.size()) {
871 ErrorF("redefinition of function with different # args");
876 // Set names for all arguments.
878 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
880 AI->setName(Args[Idx]);
882 // Add arguments to variable symbol table.
883 NamedValues[Args[Idx]] = AI;
889 Function *FunctionAST::Codegen() {
892 Function *TheFunction = Proto->Codegen();
896 // If this is an operator, install it.
897 if (Proto->isBinaryOp())
898 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
900 // Create a new basic block to start insertion into.
901 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
902 Builder.SetInsertPoint(BB);
904 if (Value *RetVal = Body->Codegen()) {
905 // Finish off the function.
906 Builder.CreateRet(RetVal);
908 // Validate the generated code, checking for consistency.
909 verifyFunction(*TheFunction);
911 // Optimize the function.
912 TheFPM->run(*TheFunction);
917 // Error reading body, remove function.
918 TheFunction->eraseFromParent();
920 if (Proto->isBinaryOp())
921 BinopPrecedence.erase(Proto->getOperatorName());
925 //===----------------------------------------------------------------------===//
926 // Top-Level parsing and JIT Driver
927 //===----------------------------------------------------------------------===//
929 static ExecutionEngine *TheExecutionEngine;
931 static void HandleDefinition() {
932 if (auto FnAST = ParseDefinition()) {
933 if (auto *FnIR = FnAST->Codegen()) {
934 fprintf(stderr, "Read function definition:");
938 // Skip token for error recovery.
943 static void HandleExtern() {
944 if (auto ProtoAST = ParseExtern()) {
945 if (auto *FnIR = ProtoAST->Codegen()) {
946 fprintf(stderr, "Read extern: ");
950 // Skip token for error recovery.
955 static void HandleTopLevelExpression() {
956 // Evaluate a top-level expression into an anonymous function.
957 if (auto FnAST = ParseTopLevelExpr()) {
958 if (auto *FnIR = FnAST->Codegen()) {
959 TheExecutionEngine->finalizeObject();
960 // JIT the function, returning a function pointer.
961 void *FPtr = TheExecutionEngine->getPointerToFunction(FnIR);
963 // Cast it to the right type (takes no arguments, returns a double) so we
964 // can call it as a native function.
965 double (*FP)() = (double (*)())(intptr_t)FPtr;
966 fprintf(stderr, "Evaluated to %f\n", FP());
969 // Skip token for error recovery.
974 /// top ::= definition | external | expression | ';'
975 static void MainLoop() {
977 fprintf(stderr, "ready> ");
981 case ';': // ignore top-level semicolons.
991 HandleTopLevelExpression();
997 //===----------------------------------------------------------------------===//
998 // "Library" functions that can be "extern'd" from user code.
999 //===----------------------------------------------------------------------===//
1001 /// putchard - putchar that takes a double and returns 0.
1002 extern "C" double putchard(double X) {
1007 /// printd - printf that takes a double prints it as "%f\n", returning 0.
1008 extern "C" double printd(double X) {
1013 //===----------------------------------------------------------------------===//
1014 // Main driver code.
1015 //===----------------------------------------------------------------------===//
1018 InitializeNativeTarget();
1019 InitializeNativeTargetAsmPrinter();
1020 InitializeNativeTargetAsmParser();
1021 LLVMContext &Context = getGlobalContext();
1023 // Install standard binary operators.
1024 // 1 is lowest precedence.
1025 BinopPrecedence['<'] = 10;
1026 BinopPrecedence['+'] = 20;
1027 BinopPrecedence['-'] = 20;
1028 BinopPrecedence['*'] = 40; // highest.
1030 // Prime the first token.
1031 fprintf(stderr, "ready> ");
1034 // Make the module, which holds all the code.
1035 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1036 TheModule = Owner.get();
1038 // Create the JIT. This takes ownership of the module.
1040 TheExecutionEngine =
1041 EngineBuilder(std::move(Owner))
1042 .setErrorStr(&ErrStr)
1043 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1045 if (!TheExecutionEngine) {
1046 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1050 legacy::FunctionPassManager OurFPM(TheModule);
1052 // Set up the optimizer pipeline. Start with registering info about how the
1053 // target lays out data structures.
1054 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1055 // Provide basic AliasAnalysis support for GVN.
1056 OurFPM.add(createBasicAliasAnalysisPass());
1057 // Do simple "peephole" optimizations and bit-twiddling optzns.
1058 OurFPM.add(createInstructionCombiningPass());
1059 // Reassociate expressions.
1060 OurFPM.add(createReassociatePass());
1061 // Eliminate Common SubExpressions.
1062 OurFPM.add(createGVNPass());
1063 // Simplify the control flow graph (deleting unreachable blocks, etc).
1064 OurFPM.add(createCFGSimplificationPass());
1066 OurFPM.doInitialization();
1068 // Set the global so the code gen can use this.
1071 // Run the main "interpreter loop" now.
1076 // Print out all of the generated code.