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.
31 tok_def = -2, tok_extern = -3,
34 tok_identifier = -4, tok_number = -5,
37 tok_if = -6, tok_then = -7, tok_else = -8,
38 tok_for = -9, tok_in = -10,
41 tok_binary = -11, tok_unary = -12
44 static std::string IdentifierStr; // Filled in if tok_identifier
45 static double NumVal; // Filled in if tok_number
47 /// gettok - Return the next token from standard input.
49 static int LastChar = ' ';
51 // Skip any whitespace.
52 while (isspace(LastChar))
55 if (isalpha(LastChar)) { // identifier: [a-zA-Z][a-zA-Z0-9]*
56 IdentifierStr = LastChar;
57 while (isalnum((LastChar = getchar())))
58 IdentifierStr += LastChar;
60 if (IdentifierStr == "def") return tok_def;
61 if (IdentifierStr == "extern") return tok_extern;
62 if (IdentifierStr == "if") return tok_if;
63 if (IdentifierStr == "then") return tok_then;
64 if (IdentifierStr == "else") return tok_else;
65 if (IdentifierStr == "for") return tok_for;
66 if (IdentifierStr == "in") return tok_in;
67 if (IdentifierStr == "binary") return tok_binary;
68 if (IdentifierStr == "unary") return tok_unary;
69 return tok_identifier;
72 if (isdigit(LastChar) || LastChar == '.') { // Number: [0-9.]+
77 } while (isdigit(LastChar) || LastChar == '.');
79 NumVal = strtod(NumStr.c_str(), 0);
83 if (LastChar == '#') {
84 // Comment until end of line.
85 do LastChar = getchar();
86 while (LastChar != EOF && LastChar != '\n' && LastChar != '\r');
92 // Check for end of file. Don't eat the EOF.
96 // Otherwise, just return the character as its ascii value.
97 int ThisChar = LastChar;
102 //===----------------------------------------------------------------------===//
103 // Abstract Syntax Tree (aka Parse Tree)
104 //===----------------------------------------------------------------------===//
106 /// ExprAST - Base class for all expression nodes.
109 virtual ~ExprAST() {}
110 virtual Value *Codegen() = 0;
113 /// NumberExprAST - Expression class for numeric literals like "1.0".
114 class NumberExprAST : public ExprAST {
117 NumberExprAST(double val) : Val(val) {}
118 virtual Value *Codegen();
121 /// VariableExprAST - Expression class for referencing a variable, like "a".
122 class VariableExprAST : public ExprAST {
125 VariableExprAST(const std::string &name) : Name(name) {}
126 virtual Value *Codegen();
129 /// UnaryExprAST - Expression class for a unary operator.
130 class UnaryExprAST : public ExprAST {
134 UnaryExprAST(char opcode, ExprAST *operand)
135 : Opcode(opcode), Operand(operand) {}
136 virtual Value *Codegen();
139 /// BinaryExprAST - Expression class for a binary operator.
140 class BinaryExprAST : public ExprAST {
144 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
145 : Op(op), LHS(lhs), RHS(rhs) {}
146 virtual Value *Codegen();
149 /// CallExprAST - Expression class for function calls.
150 class CallExprAST : public ExprAST {
152 std::vector<ExprAST*> Args;
154 CallExprAST(const std::string &callee, std::vector<ExprAST*> &args)
155 : Callee(callee), Args(args) {}
156 virtual Value *Codegen();
159 /// IfExprAST - Expression class for if/then/else.
160 class IfExprAST : public ExprAST {
161 ExprAST *Cond, *Then, *Else;
163 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
164 : Cond(cond), Then(then), Else(_else) {}
165 virtual Value *Codegen();
168 /// ForExprAST - Expression class for for/in.
169 class ForExprAST : public ExprAST {
171 ExprAST *Start, *End, *Step, *Body;
173 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
174 ExprAST *step, ExprAST *body)
175 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
176 virtual Value *Codegen();
179 /// PrototypeAST - This class represents the "prototype" for a function,
180 /// which captures its name, and its argument names (thus implicitly the number
181 /// of arguments the function takes), as well as if it is an operator.
184 std::vector<std::string> Args;
186 unsigned Precedence; // Precedence if a binary op.
188 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
189 bool isoperator = false, unsigned prec = 0)
190 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
192 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
193 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
195 char getOperatorName() const {
196 assert(isUnaryOp() || isBinaryOp());
197 return Name[Name.size()-1];
200 unsigned getBinaryPrecedence() const { return Precedence; }
205 /// FunctionAST - This class represents a function definition itself.
210 FunctionAST(PrototypeAST *proto, ExprAST *body)
211 : Proto(proto), Body(body) {}
215 } // end anonymous namespace
217 //===----------------------------------------------------------------------===//
219 //===----------------------------------------------------------------------===//
221 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
222 /// token the parser is looking at. getNextToken reads another token from the
223 /// lexer and updates CurTok with its results.
225 static int getNextToken() {
226 return CurTok = gettok();
229 /// BinopPrecedence - This holds the precedence for each binary operator that is
231 static std::map<char, int> BinopPrecedence;
233 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
234 static int GetTokPrecedence() {
235 if (!isascii(CurTok))
238 // Make sure it's a declared binop.
239 int TokPrec = BinopPrecedence[CurTok];
240 if (TokPrec <= 0) return -1;
244 /// Error* - These are little helper functions for error handling.
245 ExprAST *Error(const char *Str) { fprintf(stderr, "Error: %s\n", Str);return 0;}
246 PrototypeAST *ErrorP(const char *Str) { Error(Str); return 0; }
247 FunctionAST *ErrorF(const char *Str) { Error(Str); return 0; }
249 static ExprAST *ParseExpression();
253 /// ::= identifier '(' expression* ')'
254 static ExprAST *ParseIdentifierExpr() {
255 std::string IdName = IdentifierStr;
257 getNextToken(); // eat identifier.
259 if (CurTok != '(') // Simple variable ref.
260 return new VariableExprAST(IdName);
263 getNextToken(); // eat (
264 std::vector<ExprAST*> Args;
267 ExprAST *Arg = ParseExpression();
271 if (CurTok == ')') break;
274 return Error("Expected ')' or ',' in argument list");
282 return new CallExprAST(IdName, Args);
285 /// numberexpr ::= number
286 static ExprAST *ParseNumberExpr() {
287 ExprAST *Result = new NumberExprAST(NumVal);
288 getNextToken(); // consume the number
292 /// parenexpr ::= '(' expression ')'
293 static ExprAST *ParseParenExpr() {
294 getNextToken(); // eat (.
295 ExprAST *V = ParseExpression();
299 return Error("expected ')'");
300 getNextToken(); // eat ).
304 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
305 static ExprAST *ParseIfExpr() {
306 getNextToken(); // eat the if.
309 ExprAST *Cond = ParseExpression();
312 if (CurTok != tok_then)
313 return Error("expected then");
314 getNextToken(); // eat the then
316 ExprAST *Then = ParseExpression();
317 if (Then == 0) return 0;
319 if (CurTok != tok_else)
320 return Error("expected else");
324 ExprAST *Else = ParseExpression();
327 return new IfExprAST(Cond, Then, Else);
330 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
331 static ExprAST *ParseForExpr() {
332 getNextToken(); // eat the for.
334 if (CurTok != tok_identifier)
335 return Error("expected identifier after for");
337 std::string IdName = IdentifierStr;
338 getNextToken(); // eat identifier.
341 return Error("expected '=' after for");
342 getNextToken(); // eat '='.
345 ExprAST *Start = ParseExpression();
346 if (Start == 0) return 0;
348 return Error("expected ',' after for start value");
351 ExprAST *End = ParseExpression();
352 if (End == 0) return 0;
354 // The step value is optional.
358 Step = ParseExpression();
359 if (Step == 0) return 0;
362 if (CurTok != tok_in)
363 return Error("expected 'in' after for");
364 getNextToken(); // eat 'in'.
366 ExprAST *Body = ParseExpression();
367 if (Body == 0) return 0;
369 return new ForExprAST(IdName, Start, End, Step, Body);
373 /// ::= identifierexpr
378 static ExprAST *ParsePrimary() {
380 default: return Error("unknown token when expecting an expression");
381 case tok_identifier: return ParseIdentifierExpr();
382 case tok_number: return ParseNumberExpr();
383 case '(': return ParseParenExpr();
384 case tok_if: return ParseIfExpr();
385 case tok_for: return ParseForExpr();
392 static ExprAST *ParseUnary() {
393 // If the current token is not an operator, it must be a primary expr.
394 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
395 return ParsePrimary();
397 // If this is a unary operator, read it.
400 if (ExprAST *Operand = ParseUnary())
401 return new UnaryExprAST(Opc, Operand);
407 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
408 // If this is a binop, find its precedence.
410 int TokPrec = GetTokPrecedence();
412 // If this is a binop that binds at least as tightly as the current binop,
413 // consume it, otherwise we are done.
414 if (TokPrec < ExprPrec)
417 // Okay, we know this is a binop.
419 getNextToken(); // eat binop
421 // Parse the unary expression after the binary operator.
422 ExprAST *RHS = ParseUnary();
425 // If BinOp binds less tightly with RHS than the operator after RHS, let
426 // the pending operator take RHS as its LHS.
427 int NextPrec = GetTokPrecedence();
428 if (TokPrec < NextPrec) {
429 RHS = ParseBinOpRHS(TokPrec+1, RHS);
430 if (RHS == 0) return 0;
434 LHS = new BinaryExprAST(BinOp, LHS, RHS);
439 /// ::= unary binoprhs
441 static ExprAST *ParseExpression() {
442 ExprAST *LHS = ParseUnary();
445 return ParseBinOpRHS(0, LHS);
449 /// ::= id '(' id* ')'
450 /// ::= binary LETTER number? (id, id)
451 /// ::= unary LETTER (id)
452 static PrototypeAST *ParsePrototype() {
455 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
456 unsigned BinaryPrecedence = 30;
460 return ErrorP("Expected function name in prototype");
462 FnName = IdentifierStr;
468 if (!isascii(CurTok))
469 return ErrorP("Expected unary operator");
471 FnName += (char)CurTok;
477 if (!isascii(CurTok))
478 return ErrorP("Expected binary operator");
480 FnName += (char)CurTok;
484 // Read the precedence if present.
485 if (CurTok == tok_number) {
486 if (NumVal < 1 || NumVal > 100)
487 return ErrorP("Invalid precedecnce: must be 1..100");
488 BinaryPrecedence = (unsigned)NumVal;
495 return ErrorP("Expected '(' in prototype");
497 std::vector<std::string> ArgNames;
498 while (getNextToken() == tok_identifier)
499 ArgNames.push_back(IdentifierStr);
501 return ErrorP("Expected ')' in prototype");
504 getNextToken(); // eat ')'.
506 // Verify right number of names for operator.
507 if (Kind && ArgNames.size() != Kind)
508 return ErrorP("Invalid number of operands for operator");
510 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
513 /// definition ::= 'def' prototype expression
514 static FunctionAST *ParseDefinition() {
515 getNextToken(); // eat def.
516 PrototypeAST *Proto = ParsePrototype();
517 if (Proto == 0) return 0;
519 if (ExprAST *E = ParseExpression())
520 return new FunctionAST(Proto, E);
524 /// toplevelexpr ::= expression
525 static FunctionAST *ParseTopLevelExpr() {
526 if (ExprAST *E = ParseExpression()) {
527 // Make an anonymous proto.
528 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
529 return new FunctionAST(Proto, E);
534 /// external ::= 'extern' prototype
535 static PrototypeAST *ParseExtern() {
536 getNextToken(); // eat extern.
537 return ParsePrototype();
540 //===----------------------------------------------------------------------===//
542 //===----------------------------------------------------------------------===//
544 static Module *TheModule;
545 static IRBuilder<> Builder(getGlobalContext());
546 static std::map<std::string, Value*> NamedValues;
547 static FunctionPassManager *TheFPM;
549 Value *ErrorV(const char *Str) { Error(Str); return 0; }
551 Value *NumberExprAST::Codegen() {
552 return ConstantFP::get(getGlobalContext(), APFloat(Val));
555 Value *VariableExprAST::Codegen() {
556 // Look this variable up in the function.
557 Value *V = NamedValues[Name];
558 return V ? V : ErrorV("Unknown variable name");
561 Value *UnaryExprAST::Codegen() {
562 Value *OperandV = Operand->Codegen();
563 if (OperandV == 0) return 0;
565 Function *F = TheModule->getFunction(std::string("unary")+Opcode);
567 return ErrorV("Unknown unary operator");
569 return Builder.CreateCall(F, OperandV, "unop");
572 Value *BinaryExprAST::Codegen() {
573 Value *L = LHS->Codegen();
574 Value *R = RHS->Codegen();
575 if (L == 0 || R == 0) return 0;
578 case '+': return Builder.CreateFAdd(L, R, "addtmp");
579 case '-': return Builder.CreateFSub(L, R, "subtmp");
580 case '*': return Builder.CreateFMul(L, R, "multmp");
582 L = Builder.CreateFCmpULT(L, R, "cmptmp");
583 // Convert bool 0/1 to double 0.0 or 1.0
584 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
589 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
591 Function *F = TheModule->getFunction(std::string("binary")+Op);
592 assert(F && "binary operator not found!");
594 Value *Ops[] = { L, R };
595 return Builder.CreateCall(F, Ops, "binop");
598 Value *CallExprAST::Codegen() {
599 // Look up the name in the global module table.
600 Function *CalleeF = TheModule->getFunction(Callee);
602 return ErrorV("Unknown function referenced");
604 // If argument mismatch error.
605 if (CalleeF->arg_size() != Args.size())
606 return ErrorV("Incorrect # arguments passed");
608 std::vector<Value*> ArgsV;
609 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
610 ArgsV.push_back(Args[i]->Codegen());
611 if (ArgsV.back() == 0) return 0;
614 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
617 Value *IfExprAST::Codegen() {
618 Value *CondV = Cond->Codegen();
619 if (CondV == 0) return 0;
621 // Convert condition to a bool by comparing equal to 0.0.
622 CondV = Builder.CreateFCmpONE(CondV,
623 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
626 Function *TheFunction = Builder.GetInsertBlock()->getParent();
628 // Create blocks for the then and else cases. Insert the 'then' block at the
629 // end of the function.
630 BasicBlock *ThenBB = BasicBlock::Create(getGlobalContext(), "then", TheFunction);
631 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
632 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
634 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
637 Builder.SetInsertPoint(ThenBB);
639 Value *ThenV = Then->Codegen();
640 if (ThenV == 0) return 0;
642 Builder.CreateBr(MergeBB);
643 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
644 ThenBB = Builder.GetInsertBlock();
647 TheFunction->getBasicBlockList().push_back(ElseBB);
648 Builder.SetInsertPoint(ElseBB);
650 Value *ElseV = Else->Codegen();
651 if (ElseV == 0) return 0;
653 Builder.CreateBr(MergeBB);
654 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
655 ElseBB = Builder.GetInsertBlock();
658 TheFunction->getBasicBlockList().push_back(MergeBB);
659 Builder.SetInsertPoint(MergeBB);
660 PHINode *PN = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2,
663 PN->addIncoming(ThenV, ThenBB);
664 PN->addIncoming(ElseV, ElseBB);
668 Value *ForExprAST::Codegen() {
674 // variable = phi [start, loopheader], [nextvariable, loopend]
680 // nextvariable = variable + step
682 // br endcond, loop, endloop
685 // Emit the start code first, without 'variable' in scope.
686 Value *StartVal = Start->Codegen();
687 if (StartVal == 0) return 0;
689 // Make the new basic block for the loop header, inserting after current
691 Function *TheFunction = Builder.GetInsertBlock()->getParent();
692 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
693 BasicBlock *LoopBB = BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
695 // Insert an explicit fall through from the current block to the LoopBB.
696 Builder.CreateBr(LoopBB);
698 // Start insertion in LoopBB.
699 Builder.SetInsertPoint(LoopBB);
701 // Start the PHI node with an entry for Start.
702 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, VarName.c_str());
703 Variable->addIncoming(StartVal, PreheaderBB);
705 // Within the loop, the variable is defined equal to the PHI node. If it
706 // shadows an existing variable, we have to restore it, so save it now.
707 Value *OldVal = NamedValues[VarName];
708 NamedValues[VarName] = Variable;
710 // Emit the body of the loop. This, like any other expr, can change the
711 // current BB. Note that we ignore the value computed by the body, but don't
713 if (Body->Codegen() == 0)
716 // Emit the step value.
719 StepVal = Step->Codegen();
720 if (StepVal == 0) return 0;
722 // If not specified, use 1.0.
723 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
726 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
728 // Compute the end condition.
729 Value *EndCond = End->Codegen();
730 if (EndCond == 0) return EndCond;
732 // Convert condition to a bool by comparing equal to 0.0.
733 EndCond = Builder.CreateFCmpONE(EndCond,
734 ConstantFP::get(getGlobalContext(), APFloat(0.0)),
737 // Create the "after loop" block and insert it.
738 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
739 BasicBlock *AfterBB = BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
741 // Insert the conditional branch into the end of LoopEndBB.
742 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
744 // Any new code will be inserted in AfterBB.
745 Builder.SetInsertPoint(AfterBB);
747 // Add a new entry to the PHI node for the backedge.
748 Variable->addIncoming(NextVar, LoopEndBB);
750 // Restore the unshadowed variable.
752 NamedValues[VarName] = OldVal;
754 NamedValues.erase(VarName);
757 // for expr always returns 0.0.
758 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
761 Function *PrototypeAST::Codegen() {
762 // Make the function type: double(double,double) etc.
763 std::vector<Type*> Doubles(Args.size(),
764 Type::getDoubleTy(getGlobalContext()));
765 FunctionType *FT = FunctionType::get(Type::getDoubleTy(getGlobalContext()),
768 Function *F = Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
770 // If F conflicted, there was already something named 'Name'. If it has a
771 // body, don't allow redefinition or reextern.
772 if (F->getName() != Name) {
773 // Delete the one we just made and get the existing one.
774 F->eraseFromParent();
775 F = TheModule->getFunction(Name);
777 // If F already has a body, reject this.
779 ErrorF("redefinition of function");
783 // If F took a different number of args, reject.
784 if (F->arg_size() != Args.size()) {
785 ErrorF("redefinition of function with different # args");
790 // Set names for all arguments.
792 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
794 AI->setName(Args[Idx]);
796 // Add arguments to variable symbol table.
797 NamedValues[Args[Idx]] = AI;
803 Function *FunctionAST::Codegen() {
806 Function *TheFunction = Proto->Codegen();
807 if (TheFunction == 0)
810 // If this is an operator, install it.
811 if (Proto->isBinaryOp())
812 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
814 // Create a new basic block to start insertion into.
815 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
816 Builder.SetInsertPoint(BB);
818 if (Value *RetVal = Body->Codegen()) {
819 // Finish off the function.
820 Builder.CreateRet(RetVal);
822 // Validate the generated code, checking for consistency.
823 verifyFunction(*TheFunction);
825 // Optimize the function.
826 TheFPM->run(*TheFunction);
831 // Error reading body, remove function.
832 TheFunction->eraseFromParent();
834 if (Proto->isBinaryOp())
835 BinopPrecedence.erase(Proto->getOperatorName());
839 //===----------------------------------------------------------------------===//
840 // Top-Level parsing and JIT Driver
841 //===----------------------------------------------------------------------===//
843 static ExecutionEngine *TheExecutionEngine;
845 static void HandleDefinition() {
846 if (FunctionAST *F = ParseDefinition()) {
847 if (Function *LF = F->Codegen()) {
848 fprintf(stderr, "Read function definition:");
852 // Skip token for error recovery.
857 static void HandleExtern() {
858 if (PrototypeAST *P = ParseExtern()) {
859 if (Function *F = P->Codegen()) {
860 fprintf(stderr, "Read extern: ");
864 // Skip token for error recovery.
869 static void HandleTopLevelExpression() {
870 // Evaluate a top-level expression into an anonymous function.
871 if (FunctionAST *F = ParseTopLevelExpr()) {
872 if (Function *LF = F->Codegen()) {
873 TheExecutionEngine->finalizeObject();
874 // JIT the function, returning a function pointer.
875 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
877 // Cast it to the right type (takes no arguments, returns a double) so we
878 // can call it as a native function.
879 double (*FP)() = (double (*)())(intptr_t)FPtr;
880 fprintf(stderr, "Evaluated to %f\n", FP());
883 // Skip token for error recovery.
888 /// top ::= definition | external | expression | ';'
889 static void MainLoop() {
891 fprintf(stderr, "ready> ");
893 case tok_eof: return;
894 case ';': getNextToken(); break; // ignore top-level semicolons.
895 case tok_def: HandleDefinition(); break;
896 case tok_extern: HandleExtern(); break;
897 default: HandleTopLevelExpression(); break;
902 //===----------------------------------------------------------------------===//
903 // "Library" functions that can be "extern'd" from user code.
904 //===----------------------------------------------------------------------===//
906 /// putchard - putchar that takes a double and returns 0.
908 double putchard(double X) {
913 /// printd - printf that takes a double prints it as "%f\n", returning 0.
915 double printd(double X) {
920 //===----------------------------------------------------------------------===//
922 //===----------------------------------------------------------------------===//
925 InitializeNativeTarget();
926 InitializeNativeTargetAsmPrinter();
927 InitializeNativeTargetAsmParser();
928 LLVMContext &Context = getGlobalContext();
930 // Install standard binary operators.
931 // 1 is lowest precedence.
932 BinopPrecedence['<'] = 10;
933 BinopPrecedence['+'] = 20;
934 BinopPrecedence['-'] = 20;
935 BinopPrecedence['*'] = 40; // highest.
937 // Prime the first token.
938 fprintf(stderr, "ready> ");
941 // Make the module, which holds all the code.
942 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
943 TheModule = Owner.get();
945 // Create the JIT. This takes ownership of the module.
947 TheExecutionEngine = EngineBuilder(std::move(Owner))
948 .setErrorStr(&ErrStr)
949 .setMCJITMemoryManager(new SectionMemoryManager())
951 if (!TheExecutionEngine) {
952 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
956 FunctionPassManager OurFPM(TheModule);
958 // Set up the optimizer pipeline. Start with registering info about how the
959 // target lays out data structures.
960 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
961 OurFPM.add(new DataLayoutPass());
962 // Provide basic AliasAnalysis support for GVN.
963 OurFPM.add(createBasicAliasAnalysisPass());
964 // Do simple "peephole" optimizations and bit-twiddling optzns.
965 OurFPM.add(createInstructionCombiningPass());
966 // Reassociate expressions.
967 OurFPM.add(createReassociatePass());
968 // Eliminate Common SubExpressions.
969 OurFPM.add(createGVNPass());
970 // Simplify the control flow graph (deleting unreachable blocks, etc).
971 OurFPM.add(createCFGSimplificationPass());
973 OurFPM.doInitialization();
975 // Set the global so the code gen can use this.
978 // Run the main "interpreter loop" now.
983 // Print out all of the generated code.