1 #include "llvm/DerivedTypes.h"
2 #include "llvm/ExecutionEngine/ExecutionEngine.h"
3 #include "llvm/ExecutionEngine/JIT.h"
4 #include "llvm/LLVMContext.h"
5 #include "llvm/Module.h"
6 #include "llvm/PassManager.h"
7 #include "llvm/Analysis/Verifier.h"
8 #include "llvm/Target/TargetData.h"
9 #include "llvm/Target/TargetSelect.h"
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/Support/IRBuilder.h"
18 //===----------------------------------------------------------------------===//
20 //===----------------------------------------------------------------------===//
22 // The lexer returns tokens [0-255] if it is an unknown character, otherwise one
23 // of these for known things.
28 tok_def = -2, tok_extern = -3,
31 tok_identifier = -4, tok_number = -5,
34 tok_if = -6, tok_then = -7, tok_else = -8,
35 tok_for = -9, tok_in = -10,
38 tok_binary = -11, tok_unary = -12
41 static std::string IdentifierStr; // Filled in if tok_identifier
42 static double NumVal; // Filled in if tok_number
44 /// gettok - Return the next token from standard input.
46 static int LastChar = ' ';
48 // Skip any whitespace.
49 while (isspace(LastChar))
52 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
53 IdentifierStr = LastChar;
54 while (isalnum((LastChar = getchar())))
55 IdentifierStr += LastChar;
57 if (IdentifierStr == "def") return tok_def;
58 if (IdentifierStr == "extern") return tok_extern;
59 if (IdentifierStr == "if") return tok_if;
60 if (IdentifierStr == "then") return tok_then;
61 if (IdentifierStr == "else") return tok_else;
62 if (IdentifierStr == "for") return tok_for;
63 if (IdentifierStr == "in") return tok_in;
64 if (IdentifierStr == "binary") return tok_binary;
65 if (IdentifierStr == "unary") return tok_unary;
66 return tok_identifier;
69 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
74 } while (isdigit(LastChar) || LastChar == '.');
76 NumVal = strtod(NumStr.c_str(), 0);
80 if (LastChar == '#') {
81 // Comment until end of line.
82 do LastChar = getchar();
83 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
89 // Check for end of file. Don't eat the EOF.
93 // Otherwise, just return the character as its ascii value.
94 int ThisChar = LastChar;
99 //===----------------------------------------------------------------------===//
100 // Abstract Syntax Tree (aka Parse Tree)
101 //===----------------------------------------------------------------------===//
103 /// ExprAST - Base class for all expression nodes.
106 virtual ~ExprAST() {}
107 virtual Value *Codegen() = 0;
110 /// NumberExprAST - Expression class for numeric literals like "1.0".
111 class NumberExprAST : public ExprAST {
114 NumberExprAST(double val) : Val(val) {}
115 virtual Value *Codegen();
118 /// VariableExprAST - Expression class for referencing a variable, like "a".
119 class VariableExprAST : public ExprAST {
122 VariableExprAST(const std::string &name) : Name(name) {}
123 virtual Value *Codegen();
126 /// UnaryExprAST - Expression class for a unary operator.
127 class UnaryExprAST : public ExprAST {
131 UnaryExprAST(char opcode, ExprAST *operand)
132 : Opcode(opcode), Operand(operand) {}
133 virtual Value *Codegen();
136 /// BinaryExprAST - Expression class for a binary operator.
137 class BinaryExprAST : public ExprAST {
141 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
142 : Op(op), LHS(lhs), RHS(rhs) {}
143 virtual Value *Codegen();
146 /// CallExprAST - Expression class for function calls.
147 class CallExprAST : public ExprAST {
149 std::vector<ExprAST*> Args;
151 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
152 : Callee(callee), Args(args) {}
153 virtual Value *Codegen();
156 /// IfExprAST - Expression class for if/then/else.
157 class IfExprAST : public ExprAST {
158 ExprAST *Cond, *Then, *Else;
160 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
161 : Cond(cond), Then(then), Else(_else) {}
162 virtual Value *Codegen();
165 /// ForExprAST - Expression class for for/in.
166 class ForExprAST : public ExprAST {
168 ExprAST *Start, *End, *Step, *Body;
170 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
171 ExprAST *step, ExprAST *body)
172 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
173 virtual Value *Codegen();
176 /// PrototypeAST - This class represents the "prototype" for a function,
177 /// which captures its name, and its argument names (thus implicitly the number
178 /// of arguments the function takes), as well as if it is an operator.
181 std::vector<std::string> Args;
183 unsigned Precedence; // Precedence if a binary op.
185 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
186 bool isoperator = false, unsigned prec = 0)
187 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
189 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
190 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
192 char getOperatorName() const {
193 assert(isUnaryOp() || isBinaryOp());
194 return Name[Name.size()-1];
197 unsigned getBinaryPrecedence() const { return Precedence; }
202 /// FunctionAST - This class represents a function definition itself.
207 FunctionAST(PrototypeAST *proto, ExprAST *body)
208 : Proto(proto), Body(body) {}
213 //===----------------------------------------------------------------------===//
215 //===----------------------------------------------------------------------===//
217 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
218 /// token the parser is looking at. getNextToken reads another token from the
219 /// lexer and updates CurTok with its results.
221 static int getNextToken() {
222 return CurTok = gettok();
225 /// BinopPrecedence - This holds the precedence for each binary operator that is
227 static std::map<char, int> BinopPrecedence;
229 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
230 static int GetTokPrecedence() {
231 if (!isascii(CurTok))
234 // Make sure it's a declared binop.
235 int TokPrec = BinopPrecedence[CurTok];
236 if (TokPrec <= 0) return -1;
240 /// Error* - These are little helper functions for error handling.
241 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
242 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
243 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
245 static ExprAST *ParseExpression();
249 /// ::= identifier '(' expression* ')'
250 static ExprAST *ParseIdentifierExpr() {
251 std::string IdName = IdentifierStr;
253 getNextToken(); // eat identifier.
255 if (CurTok != '(') // Simple variable ref.
256 return new VariableExprAST(IdName);
259 getNextToken(); // eat (
260 std::vector<ExprAST*> Args;
263 ExprAST *Arg = ParseExpression();
267 if (CurTok == ')') break;
270 return Error("Expected ')' or ',' in argument list");
278 return new CallExprAST(IdName, Args);
281 /// numberexpr ::= number
282 static ExprAST *ParseNumberExpr() {
283 ExprAST *Result = new NumberExprAST(NumVal);
284 getNextToken(); // consume the number
288 /// parenexpr ::= '(' expression ')'
289 static ExprAST *ParseParenExpr() {
290 getNextToken(); // eat (.
291 ExprAST *V = ParseExpression();
295 return Error("expected ')'");
296 getNextToken(); // eat ).
300 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
301 static ExprAST *ParseIfExpr() {
302 getNextToken(); // eat the if.
305 ExprAST *Cond = ParseExpression();
308 if (CurTok != tok_then)
309 return Error("expected then");
310 getNextToken(); // eat the then
312 ExprAST *Then = ParseExpression();
313 if (Then == 0) return 0;
315 if (CurTok != tok_else)
316 return Error("expected else");
320 ExprAST *Else = ParseExpression();
323 return new IfExprAST(Cond, Then, Else);
326 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
327 static ExprAST *ParseForExpr() {
328 getNextToken(); // eat the for.
330 if (CurTok != tok_identifier)
331 return Error("expected identifier after for");
333 std::string IdName = IdentifierStr;
334 getNextToken(); // eat identifier.
337 return Error("expected '=' after for");
338 getNextToken(); // eat '='.
341 ExprAST *Start = ParseExpression();
342 if (Start == 0) return 0;
344 return Error("expected ',' after for start value");
347 ExprAST *End = ParseExpression();
348 if (End == 0) return 0;
350 // The step value is optional.
354 Step = ParseExpression();
355 if (Step == 0) return 0;
358 if (CurTok != tok_in)
359 return Error("expected 'in' after for");
360 getNextToken(); // eat 'in'.
362 ExprAST *Body = ParseExpression();
363 if (Body == 0) return 0;
365 return new ForExprAST(IdName, Start, End, Step, Body);
369 /// ::= identifierexpr
374 static ExprAST *ParsePrimary() {
376 default: return Error("unknown token when expecting an expression");
377 case tok_identifier: return ParseIdentifierExpr();
378 case tok_number: return ParseNumberExpr();
379 case '(': return ParseParenExpr();
380 case tok_if: return ParseIfExpr();
381 case tok_for: return ParseForExpr();
388 static ExprAST *ParseUnary() {
389 // If the current token is not an operator, it must be a primary expr.
390 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
391 return ParsePrimary();
393 // If this is a unary operator, read it.
396 if (ExprAST *Operand = ParseUnary())
397 return new UnaryExprAST(Opc, Operand);
403 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
404 // If this is a binop, find its precedence.
406 int TokPrec = GetTokPrecedence();
408 // If this is a binop that binds at least as tightly as the current binop,
409 // consume it, otherwise we are done.
410 if (TokPrec < ExprPrec)
413 // Okay, we know this is a binop.
415 getNextToken(); // eat binop
417 // Parse the unary expression after the binary operator.
418 ExprAST *RHS = ParseUnary();
421 // If BinOp binds less tightly with RHS than the operator after RHS, let
422 // the pending operator take RHS as its LHS.
423 int NextPrec = GetTokPrecedence();
424 if (TokPrec < NextPrec) {
425 RHS = ParseBinOpRHS(TokPrec+1, RHS);
426 if (RHS == 0) return 0;
430 LHS = new BinaryExprAST(BinOp, LHS, RHS);
435 /// ::= unary binoprhs
437 static ExprAST *ParseExpression() {
438 ExprAST *LHS = ParseUnary();
441 return ParseBinOpRHS(0, LHS);
445 /// ::= id '(' id* ')'
446 /// ::= binary LETTER number? (id, id)
447 /// ::= unary LETTER (id)
448 static PrototypeAST *ParsePrototype() {
451 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
452 unsigned BinaryPrecedence = 30;
456 return ErrorP("Expected function name in prototype");
458 FnName = IdentifierStr;
464 if (!isascii(CurTok))
465 return ErrorP("Expected unary operator");
467 FnName += (char)CurTok;
473 if (!isascii(CurTok))
474 return ErrorP("Expected binary operator");
476 FnName += (char)CurTok;
480 // Read the precedence if present.
481 if (CurTok == tok_number) {
482 if (NumVal < 1 || NumVal > 100)
483 return ErrorP("Invalid precedecnce: must be 1..100");
484 BinaryPrecedence = (unsigned)NumVal;
491 return ErrorP("Expected '(' in prototype");
493 std::vector<std::string> ArgNames;
494 while (getNextToken() == tok_identifier)
495 ArgNames.push_back(IdentifierStr);
497 return ErrorP("Expected ')' in prototype");
500 getNextToken(); // eat ')'.
502 // Verify right number of names for operator.
503 if (Kind && ArgNames.size() != Kind)
504 return ErrorP("Invalid number of operands for operator");
506 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
509 /// definition ::= 'def' prototype expression
510 static FunctionAST *ParseDefinition() {
511 getNextToken(); // eat def.
512 PrototypeAST *Proto = ParsePrototype();
513 if (Proto == 0) return 0;
515 if (ExprAST *E = ParseExpression())
516 return new FunctionAST(Proto, E);
520 /// toplevelexpr ::= expression
521 static FunctionAST *ParseTopLevelExpr() {
522 if (ExprAST *E = ParseExpression()) {
523 // Make an anonymous proto.
524 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
525 return new FunctionAST(Proto, E);
530 /// external ::= 'extern' prototype
531 static PrototypeAST *ParseExtern() {
532 getNextToken(); // eat extern.
533 return ParsePrototype();
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
540 static Module *TheModule;
541 static IRBuilder<> Builder(getGlobalContext());
542 static std::map<std::string, Value*> NamedValues;
543 static FunctionPassManager *TheFPM;
545 Value *ErrorV(const char *Str) { Error(Str); return 0; }
547 Value *NumberExprAST::Codegen() {
548 return ConstantFP::get(getGlobalContext(), APFloat(Val));
551 Value *VariableExprAST::Codegen() {
552 // Look this variable up in the function.
553 Value *V = NamedValues[Name];
554 return V ? V : ErrorV("Unknown variable name");
557 Value *UnaryExprAST::Codegen() {
558 Value *OperandV = Operand->Codegen();
559 if (OperandV == 0) return 0;
561 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
563 return ErrorV("Unknown unary operator");
565 return Builder.CreateCall(F, OperandV, "unop");
568 Value *BinaryExprAST::Codegen() {
569 Value *L = LHS->Codegen();
570 Value *R = RHS->Codegen();
571 if (L == 0 || R == 0) return 0;
574 case '+': return Builder.CreateAdd(L, R, "addtmp");
575 case '-': return Builder.CreateSub(L, R, "subtmp");
576 case '*': return Builder.CreateMul(L, R, "multmp");
578 L = Builder.CreateFCmpULT(L, R, "cmptmp");
579 // Convert bool 0/1 to double 0.0 or 1.0
580 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
585 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
587 Function *F = TheModule->getFunction(std::string("binary")+Op);
588 assert(F && "binary operator not found!");
590 Value *Ops[] = { L, R };
591 return Builder.CreateCall(F, Ops, Ops+2, "binop");
594 Value *CallExprAST::Codegen() {
595 // Look up the name in the global module table.
596 Function *CalleeF = TheModule->getFunction(Callee);
598 return ErrorV("Unknown function referenced");
600 // If argument mismatch error.
601 if (CalleeF->arg_size() != Args.size())
602 return ErrorV("Incorrect # arguments passed");
604 std::vector<Value*> ArgsV;
605 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
606 ArgsV.push_back(Args[i]->Codegen());
607 if (ArgsV.back() == 0) return 0;
610 return Builder.CreateCall(CalleeF, ArgsV.begin(), ArgsV.end(), "calltmp");
613 Value *IfExprAST::Codegen() {
614 Value *CondV = Cond->Codegen();
615 if (CondV == 0) return 0;
617 // Convert condition to a bool by comparing equal to 0.0.
618 CondV = Builder.CreateFCmpONE(CondV,
619 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
622 Function *TheFunction = Builder.GetInsertBlock()->getParent();
624 // Create blocks for the then and else cases. Insert the 'then' block at the
625 // end of the function.
626 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
627 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
628 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
630 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
633 Builder.SetInsertPoint(ThenBB);
635 Value *ThenV = Then->Codegen();
636 if (ThenV == 0) return 0;
638 Builder.CreateBr(MergeBB);
639 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
640 ThenBB = Builder.GetInsertBlock();
643 TheFunction->getBasicBlockList().push_back(ElseBB);
644 Builder.SetInsertPoint(ElseBB);
646 Value *ElseV = Else->Codegen();
647 if (ElseV == 0) return 0;
649 Builder.CreateBr(MergeBB);
650 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
651 ElseBB = Builder.GetInsertBlock();
654 TheFunction->getBasicBlockList().push_back(MergeBB);
655 Builder.SetInsertPoint(MergeBB);
656 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
659 PN->addIncoming(ThenV, ThenBB);
660 PN->addIncoming(ElseV, ElseBB);
664 Value *ForExprAST::Codegen() {
670 // variable = phi [start, loopheader], [nextvariable, loopend]
676 // nextvariable = variable + step
678 // br endcond, loop, endloop
681 // Emit the start code first, without 'variable' in scope.
682 Value *StartVal = Start->Codegen();
683 if (StartVal == 0) return 0;
685 // Make the new basic block for the loop header, inserting after current
687 Function *TheFunction = Builder.GetInsertBlock()->getParent();
688 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
689 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
691 // Insert an explicit fall through from the current block to the LoopBB.
692 Builder.CreateBr(LoopBB);
694 // Start insertion in LoopBB.
695 Builder.SetInsertPoint(LoopBB);
697 // Start the PHI node with an entry for Start.
698 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), VarName.c_str());
699 Variable->addIncoming(StartVal, PreheaderBB);
701 // Within the loop, the variable is defined equal to the PHI node. If it
702 // shadows an existing variable, we have to restore it, so save it now.
703 Value *OldVal = NamedValues[VarName];
704 NamedValues[VarName] = Variable;
706 // Emit the body of the loop. This, like any other expr, can change the
707 // current BB. Note that we ignore the value computed by the body, but don't
709 if (Body->Codegen() == 0)
712 // Emit the step value.
715 StepVal = Step->Codegen();
716 if (StepVal == 0) return 0;
718 // If not specified, use 1.0.
719 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
722 Value *NextVar = Builder.CreateAdd(Variable, StepVal, "nextvar");
724 // Compute the end condition.
725 Value *EndCond = End->Codegen();
726 if (EndCond == 0) return EndCond;
728 // Convert condition to a bool by comparing equal to 0.0.
729 EndCond = Builder.CreateFCmpONE(EndCond,
730 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
733 // Create the "after loop" block and insert it.
734 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
735 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
737 // Insert the conditional branch into the end of LoopEndBB.
738 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
740 // Any new code will be inserted in AfterBB.
741 Builder.SetInsertPoint(AfterBB);
743 // Add a new entry to the PHI node for the backedge.
744 Variable->addIncoming(NextVar, LoopEndBB);
746 // Restore the unshadowed variable.
748 NamedValues[VarName] = OldVal;
750 NamedValues.erase(VarName);
753 // for expr always returns 0.0.
754 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
757 Function *PrototypeAST::Codegen() {
758 // Make the function type: double(double,double) etc.
759 std::vector<const Type*> Doubles(Args.size(),
760 Type::getDoubleTy(getGlobalContext()));
761 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
764 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
766 // If F conflicted, there was already something named 'Name'. If it has a
767 // body, don't allow redefinition or reextern.
768 if (F->getName() != Name) {
769 // Delete the one we just made and get the existing one.
770 F->eraseFromParent();
771 F = TheModule->getFunction(Name);
773 // If F already has a body, reject this.
775 ErrorF("redefinition of function");
779 // If F took a different number of args, reject.
780 if (F->arg_size() != Args.size()) {
781 ErrorF("redefinition of function with different # args");
786 // Set names for all arguments.
788 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
790 AI->setName(Args[Idx]);
792 // Add arguments to variable symbol table.
793 NamedValues[Args[Idx]] = AI;
799 Function *FunctionAST::Codegen() {
802 Function *TheFunction = Proto->Codegen();
803 if (TheFunction == 0)
806 // If this is an operator, install it.
807 if (Proto->isBinaryOp())
808 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
810 // Create a new basic block to start insertion into.
811 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
812 Builder.SetInsertPoint(BB);
814 if (Value *RetVal = Body->Codegen()) {
815 // Finish off the function.
816 Builder.CreateRet(RetVal);
818 // Validate the generated code, checking for consistency.
819 verifyFunction(*TheFunction);
821 // Optimize the function.
822 TheFPM->run(*TheFunction);
827 // Error reading body, remove function.
828 TheFunction->eraseFromParent();
830 if (Proto->isBinaryOp())
831 BinopPrecedence.erase(Proto->getOperatorName());
835 //===----------------------------------------------------------------------===//
836 // Top-Level parsing and JIT Driver
837 //===----------------------------------------------------------------------===//
839 static ExecutionEngine *TheExecutionEngine;
841 static void HandleDefinition() {
842 if (FunctionAST *F = ParseDefinition()) {
843 if (Function *LF = F->Codegen()) {
844 fprintf(stderr, "Read function definition:");
848 // Skip token for error recovery.
853 static void HandleExtern() {
854 if (PrototypeAST *P = ParseExtern()) {
855 if (Function *F = P->Codegen()) {
856 fprintf(stderr, "Read extern: ");
860 // Skip token for error recovery.
865 static void HandleTopLevelExpression() {
866 // Evaluate a top-level expression into an anonymous function.
867 if (FunctionAST *F = ParseTopLevelExpr()) {
868 if (Function *LF = F->Codegen()) {
869 // JIT the function, returning a function pointer.
870 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
872 // Cast it to the right type (takes no arguments, returns a double) so we
873 // can call it as a native function.
874 double (*FP)() = (double (*)())(intptr_t)FPtr;
875 fprintf(stderr, "Evaluated to %f\n", FP());
878 // Skip token for error recovery.
883 /// top ::= definition | external | expression | ';'
884 static void MainLoop() {
886 fprintf(stderr, "ready> ");
888 case tok_eof: return;
889 case ';': getNextToken(); break; // ignore top-level semicolons.
890 case tok_def: HandleDefinition(); break;
891 case tok_extern: HandleExtern(); break;
892 default: HandleTopLevelExpression(); break;
897 //===----------------------------------------------------------------------===//
898 // "Library" functions that can be "extern'd" from user code.
899 //===----------------------------------------------------------------------===//
901 /// putchard - putchar that takes a double and returns 0.
903 double putchard(double X) {
908 /// printd - printf that takes a double prints it as "%f\n", returning 0.
910 double printd(double X) {
915 //===----------------------------------------------------------------------===//
917 //===----------------------------------------------------------------------===//
920 InitializeNativeTarget();
921 LLVMContext &Context = getGlobalContext();
923 // Install standard binary operators.
924 // 1 is lowest precedence.
925 BinopPrecedence['<'] = 10;
926 BinopPrecedence['+'] = 20;
927 BinopPrecedence['-'] = 20;
928 BinopPrecedence['*'] = 40; // highest.
930 // Prime the first token.
931 fprintf(stderr, "ready> ");
934 // Make the module, which holds all the code.
935 TheModule = new Module("my cool jit", Context);
937 // Create the JIT. This takes ownership of the module.
939 TheExecutionEngine = EngineBuilder(TheModule).setErrorStr(&ErrStr).create();
940 if (!TheExecutionEngine) {
941 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
945 FunctionPassManager OurFPM(TheModule);
947 // Set up the optimizer pipeline. Start with registering info about how the
948 // target lays out data structures.
949 OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
950 // Do simple "peephole" optimizations and bit-twiddling optzns.
951 OurFPM.add(createInstructionCombiningPass());
952 // Reassociate expressions.
953 OurFPM.add(createReassociatePass());
954 // Eliminate Common SubExpressions.
955 OurFPM.add(createGVNPass());
956 // Simplify the control flow graph (deleting unreachable blocks, etc).
957 OurFPM.add(createCFGSimplificationPass());
959 OurFPM.doInitialization();
961 // Set the global so the code gen can use this.
964 // Run the main "interpreter loop" now.
969 // Print out all of the generated code.