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 {
155 UnaryExprAST(char opcode, ExprAST *operand)
156 : Opcode(opcode), Operand(operand) {}
157 Value *Codegen() override;
160 /// BinaryExprAST - Expression class for a binary operator.
161 class BinaryExprAST : public ExprAST {
166 BinaryExprAST(char op, ExprAST *lhs, ExprAST *rhs)
167 : Op(op), LHS(lhs), RHS(rhs) {}
168 Value *Codegen() override;
171 /// CallExprAST - Expression class for function calls.
172 class CallExprAST : public ExprAST {
174 std::vector<ExprAST *> Args;
177 CallExprAST(const std::string &callee, std::vector<ExprAST *> &args)
178 : Callee(callee), Args(args) {}
179 Value *Codegen() override;
182 /// IfExprAST - Expression class for if/then/else.
183 class IfExprAST : public ExprAST {
184 ExprAST *Cond, *Then, *Else;
187 IfExprAST(ExprAST *cond, ExprAST *then, ExprAST *_else)
188 : Cond(cond), Then(then), Else(_else) {}
189 Value *Codegen() override;
192 /// ForExprAST - Expression class for for/in.
193 class ForExprAST : public ExprAST {
195 ExprAST *Start, *End, *Step, *Body;
198 ForExprAST(const std::string &varname, ExprAST *start, ExprAST *end,
199 ExprAST *step, ExprAST *body)
200 : VarName(varname), Start(start), End(end), Step(step), Body(body) {}
201 Value *Codegen() override;
204 /// PrototypeAST - This class represents the "prototype" for a function,
205 /// which captures its name, and its argument names (thus implicitly the number
206 /// of arguments the function takes), as well as if it is an operator.
209 std::vector<std::string> Args;
211 unsigned Precedence; // Precedence if a binary op.
213 PrototypeAST(const std::string &name, const std::vector<std::string> &args,
214 bool isoperator = false, unsigned prec = 0)
215 : Name(name), Args(args), isOperator(isoperator), Precedence(prec) {}
217 bool isUnaryOp() const { return isOperator && Args.size() == 1; }
218 bool isBinaryOp() const { return isOperator && Args.size() == 2; }
220 char getOperatorName() const {
221 assert(isUnaryOp() || isBinaryOp());
222 return Name[Name.size() - 1];
225 unsigned getBinaryPrecedence() const { return Precedence; }
230 /// FunctionAST - This class represents a function definition itself.
236 FunctionAST(PrototypeAST *proto, ExprAST *body) : Proto(proto), Body(body) {}
240 } // end anonymous namespace
242 //===----------------------------------------------------------------------===//
244 //===----------------------------------------------------------------------===//
246 /// CurTok/getNextToken - Provide a simple token buffer. CurTok is the current
247 /// token the parser is looking at. getNextToken reads another token from the
248 /// lexer and updates CurTok with its results.
250 static int getNextToken() { return CurTok = gettok(); }
252 /// BinopPrecedence - This holds the precedence for each binary operator that is
254 static std::map<char, int> BinopPrecedence;
256 /// GetTokPrecedence - Get the precedence of the pending binary operator token.
257 static int GetTokPrecedence() {
258 if (!isascii(CurTok))
261 // Make sure it's a declared binop.
262 int TokPrec = BinopPrecedence[CurTok];
268 /// Error* - These are little helper functions for error handling.
269 ExprAST *Error(const char *Str) {
270 fprintf(stderr, "Error: %s\n", Str);
273 PrototypeAST *ErrorP(const char *Str) {
277 FunctionAST *ErrorF(const char *Str) {
282 static ExprAST *ParseExpression();
286 /// ::= identifier '(' expression* ')'
287 static ExprAST *ParseIdentifierExpr() {
288 std::string IdName = IdentifierStr;
290 getNextToken(); // eat identifier.
292 if (CurTok != '(') // Simple variable ref.
293 return new VariableExprAST(IdName);
296 getNextToken(); // eat (
297 std::vector<ExprAST *> Args;
300 ExprAST *Arg = ParseExpression();
309 return Error("Expected ')' or ',' in argument list");
317 return new CallExprAST(IdName, Args);
320 /// numberexpr ::= number
321 static ExprAST *ParseNumberExpr() {
322 ExprAST *Result = new NumberExprAST(NumVal);
323 getNextToken(); // consume the number
327 /// parenexpr ::= '(' expression ')'
328 static ExprAST *ParseParenExpr() {
329 getNextToken(); // eat (.
330 ExprAST *V = ParseExpression();
335 return Error("expected ')'");
336 getNextToken(); // eat ).
340 /// ifexpr ::= 'if' expression 'then' expression 'else' expression
341 static ExprAST *ParseIfExpr() {
342 getNextToken(); // eat the if.
345 ExprAST *Cond = ParseExpression();
349 if (CurTok != tok_then)
350 return Error("expected then");
351 getNextToken(); // eat the then
353 ExprAST *Then = ParseExpression();
357 if (CurTok != tok_else)
358 return Error("expected else");
362 ExprAST *Else = ParseExpression();
366 return new IfExprAST(Cond, Then, Else);
369 /// forexpr ::= 'for' identifier '=' expr ',' expr (',' expr)? 'in' expression
370 static ExprAST *ParseForExpr() {
371 getNextToken(); // eat the for.
373 if (CurTok != tok_identifier)
374 return Error("expected identifier after for");
376 std::string IdName = IdentifierStr;
377 getNextToken(); // eat identifier.
380 return Error("expected '=' after for");
381 getNextToken(); // eat '='.
383 ExprAST *Start = ParseExpression();
387 return Error("expected ',' after for start value");
390 ExprAST *End = ParseExpression();
394 // The step value is optional.
398 Step = ParseExpression();
403 if (CurTok != tok_in)
404 return Error("expected 'in' after for");
405 getNextToken(); // eat 'in'.
407 ExprAST *Body = ParseExpression();
411 return new ForExprAST(IdName, Start, End, Step, Body);
415 /// ::= identifierexpr
420 static ExprAST *ParsePrimary() {
423 return Error("unknown token when expecting an expression");
425 return ParseIdentifierExpr();
427 return ParseNumberExpr();
429 return ParseParenExpr();
431 return ParseIfExpr();
433 return ParseForExpr();
440 static ExprAST *ParseUnary() {
441 // If the current token is not an operator, it must be a primary expr.
442 if (!isascii(CurTok) || CurTok == '(' || CurTok == ',')
443 return ParsePrimary();
445 // If this is a unary operator, read it.
448 if (ExprAST *Operand = ParseUnary())
449 return new UnaryExprAST(Opc, Operand);
455 static ExprAST *ParseBinOpRHS(int ExprPrec, ExprAST *LHS) {
456 // If this is a binop, find its precedence.
458 int TokPrec = GetTokPrecedence();
460 // If this is a binop that binds at least as tightly as the current binop,
461 // consume it, otherwise we are done.
462 if (TokPrec < ExprPrec)
465 // Okay, we know this is a binop.
467 getNextToken(); // eat binop
469 // Parse the unary expression after the binary operator.
470 ExprAST *RHS = ParseUnary();
474 // If BinOp binds less tightly with RHS than the operator after RHS, let
475 // the pending operator take RHS as its LHS.
476 int NextPrec = GetTokPrecedence();
477 if (TokPrec < NextPrec) {
478 RHS = ParseBinOpRHS(TokPrec + 1, RHS);
484 LHS = new BinaryExprAST(BinOp, LHS, RHS);
489 /// ::= unary binoprhs
491 static ExprAST *ParseExpression() {
492 ExprAST *LHS = ParseUnary();
496 return ParseBinOpRHS(0, LHS);
500 /// ::= id '(' id* ')'
501 /// ::= binary LETTER number? (id, id)
502 /// ::= unary LETTER (id)
503 static PrototypeAST *ParsePrototype() {
506 unsigned Kind = 0; // 0 = identifier, 1 = unary, 2 = binary.
507 unsigned BinaryPrecedence = 30;
511 return ErrorP("Expected function name in prototype");
513 FnName = IdentifierStr;
519 if (!isascii(CurTok))
520 return ErrorP("Expected unary operator");
522 FnName += (char)CurTok;
528 if (!isascii(CurTok))
529 return ErrorP("Expected binary operator");
531 FnName += (char)CurTok;
535 // Read the precedence if present.
536 if (CurTok == tok_number) {
537 if (NumVal < 1 || NumVal > 100)
538 return ErrorP("Invalid precedecnce: must be 1..100");
539 BinaryPrecedence = (unsigned)NumVal;
546 return ErrorP("Expected '(' in prototype");
548 std::vector<std::string> ArgNames;
549 while (getNextToken() == tok_identifier)
550 ArgNames.push_back(IdentifierStr);
552 return ErrorP("Expected ')' in prototype");
555 getNextToken(); // eat ')'.
557 // Verify right number of names for operator.
558 if (Kind && ArgNames.size() != Kind)
559 return ErrorP("Invalid number of operands for operator");
561 return new PrototypeAST(FnName, ArgNames, Kind != 0, BinaryPrecedence);
564 /// definition ::= 'def' prototype expression
565 static FunctionAST *ParseDefinition() {
566 getNextToken(); // eat def.
567 PrototypeAST *Proto = ParsePrototype();
571 if (ExprAST *E = ParseExpression())
572 return new FunctionAST(Proto, E);
576 /// toplevelexpr ::= expression
577 static FunctionAST *ParseTopLevelExpr() {
578 if (ExprAST *E = ParseExpression()) {
579 // Make an anonymous proto.
580 PrototypeAST *Proto = new PrototypeAST("", std::vector<std::string>());
581 return new FunctionAST(Proto, E);
586 /// external ::= 'extern' prototype
587 static PrototypeAST *ParseExtern() {
588 getNextToken(); // eat extern.
589 return ParsePrototype();
592 //===----------------------------------------------------------------------===//
594 //===----------------------------------------------------------------------===//
596 static Module *TheModule;
597 static IRBuilder<> Builder(getGlobalContext());
598 static std::map<std::string, Value *> NamedValues;
599 static legacy::FunctionPassManager *TheFPM;
601 Value *ErrorV(const char *Str) {
606 Value *NumberExprAST::Codegen() {
607 return ConstantFP::get(getGlobalContext(), APFloat(Val));
610 Value *VariableExprAST::Codegen() {
611 // Look this variable up in the function.
612 Value *V = NamedValues[Name];
613 return V ? V : ErrorV("Unknown variable name");
616 Value *UnaryExprAST::Codegen() {
617 Value *OperandV = Operand->Codegen();
621 Function *F = TheModule->getFunction(std::string("unary") + Opcode);
623 return ErrorV("Unknown unary operator");
625 return Builder.CreateCall(F, OperandV, "unop");
628 Value *BinaryExprAST::Codegen() {
629 Value *L = LHS->Codegen();
630 Value *R = RHS->Codegen();
631 if (L == 0 || R == 0)
636 return Builder.CreateFAdd(L, R, "addtmp");
638 return Builder.CreateFSub(L, R, "subtmp");
640 return Builder.CreateFMul(L, R, "multmp");
642 L = Builder.CreateFCmpULT(L, R, "cmptmp");
643 // Convert bool 0/1 to double 0.0 or 1.0
644 return Builder.CreateUIToFP(L, Type::getDoubleTy(getGlobalContext()),
650 // If it wasn't a builtin binary operator, it must be a user defined one. Emit
652 Function *F = TheModule->getFunction(std::string("binary") + Op);
653 assert(F && "binary operator not found!");
655 Value *Ops[] = { L, R };
656 return Builder.CreateCall(F, Ops, "binop");
659 Value *CallExprAST::Codegen() {
660 // Look up the name in the global module table.
661 Function *CalleeF = TheModule->getFunction(Callee);
663 return ErrorV("Unknown function referenced");
665 // If argument mismatch error.
666 if (CalleeF->arg_size() != Args.size())
667 return ErrorV("Incorrect # arguments passed");
669 std::vector<Value *> ArgsV;
670 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
671 ArgsV.push_back(Args[i]->Codegen());
672 if (ArgsV.back() == 0)
676 return Builder.CreateCall(CalleeF, ArgsV, "calltmp");
679 Value *IfExprAST::Codegen() {
680 Value *CondV = Cond->Codegen();
684 // Convert condition to a bool by comparing equal to 0.0.
685 CondV = Builder.CreateFCmpONE(
686 CondV, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "ifcond");
688 Function *TheFunction = Builder.GetInsertBlock()->getParent();
690 // Create blocks for the then and else cases. Insert the 'then' block at the
691 // end of the function.
693 BasicBlock::Create(getGlobalContext(), "then", TheFunction);
694 BasicBlock *ElseBB = BasicBlock::Create(getGlobalContext(), "else");
695 BasicBlock *MergeBB = BasicBlock::Create(getGlobalContext(), "ifcont");
697 Builder.CreateCondBr(CondV, ThenBB, ElseBB);
700 Builder.SetInsertPoint(ThenBB);
702 Value *ThenV = Then->Codegen();
706 Builder.CreateBr(MergeBB);
707 // Codegen of 'Then' can change the current block, update ThenBB for the PHI.
708 ThenBB = Builder.GetInsertBlock();
711 TheFunction->getBasicBlockList().push_back(ElseBB);
712 Builder.SetInsertPoint(ElseBB);
714 Value *ElseV = Else->Codegen();
718 Builder.CreateBr(MergeBB);
719 // Codegen of 'Else' can change the current block, update ElseBB for the PHI.
720 ElseBB = Builder.GetInsertBlock();
723 TheFunction->getBasicBlockList().push_back(MergeBB);
724 Builder.SetInsertPoint(MergeBB);
726 Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()), 2, "iftmp");
728 PN->addIncoming(ThenV, ThenBB);
729 PN->addIncoming(ElseV, ElseBB);
733 Value *ForExprAST::Codegen() {
739 // variable = phi [start, loopheader], [nextvariable, loopend]
745 // nextvariable = variable + step
747 // br endcond, loop, endloop
750 // Emit the start code first, without 'variable' in scope.
751 Value *StartVal = Start->Codegen();
755 // Make the new basic block for the loop header, inserting after current
757 Function *TheFunction = Builder.GetInsertBlock()->getParent();
758 BasicBlock *PreheaderBB = Builder.GetInsertBlock();
760 BasicBlock::Create(getGlobalContext(), "loop", TheFunction);
762 // Insert an explicit fall through from the current block to the LoopBB.
763 Builder.CreateBr(LoopBB);
765 // Start insertion in LoopBB.
766 Builder.SetInsertPoint(LoopBB);
768 // Start the PHI node with an entry for Start.
769 PHINode *Variable = Builder.CreatePHI(Type::getDoubleTy(getGlobalContext()),
771 Variable->addIncoming(StartVal, PreheaderBB);
773 // Within the loop, the variable is defined equal to the PHI node. If it
774 // shadows an existing variable, we have to restore it, so save it now.
775 Value *OldVal = NamedValues[VarName];
776 NamedValues[VarName] = Variable;
778 // Emit the body of the loop. This, like any other expr, can change the
779 // current BB. Note that we ignore the value computed by the body, but don't
781 if (Body->Codegen() == 0)
784 // Emit the step value.
787 StepVal = Step->Codegen();
791 // If not specified, use 1.0.
792 StepVal = ConstantFP::get(getGlobalContext(), APFloat(1.0));
795 Value *NextVar = Builder.CreateFAdd(Variable, StepVal, "nextvar");
797 // Compute the end condition.
798 Value *EndCond = End->Codegen();
802 // Convert condition to a bool by comparing equal to 0.0.
803 EndCond = Builder.CreateFCmpONE(
804 EndCond, ConstantFP::get(getGlobalContext(), APFloat(0.0)), "loopcond");
806 // Create the "after loop" block and insert it.
807 BasicBlock *LoopEndBB = Builder.GetInsertBlock();
808 BasicBlock *AfterBB =
809 BasicBlock::Create(getGlobalContext(), "afterloop", TheFunction);
811 // Insert the conditional branch into the end of LoopEndBB.
812 Builder.CreateCondBr(EndCond, LoopBB, AfterBB);
814 // Any new code will be inserted in AfterBB.
815 Builder.SetInsertPoint(AfterBB);
817 // Add a new entry to the PHI node for the backedge.
818 Variable->addIncoming(NextVar, LoopEndBB);
820 // Restore the unshadowed variable.
822 NamedValues[VarName] = OldVal;
824 NamedValues.erase(VarName);
826 // for expr always returns 0.0.
827 return Constant::getNullValue(Type::getDoubleTy(getGlobalContext()));
830 Function *PrototypeAST::Codegen() {
831 // Make the function type: double(double,double) etc.
832 std::vector<Type *> Doubles(Args.size(),
833 Type::getDoubleTy(getGlobalContext()));
835 FunctionType::get(Type::getDoubleTy(getGlobalContext()), Doubles, false);
838 Function::Create(FT, Function::ExternalLinkage, Name, TheModule);
840 // If F conflicted, there was already something named 'Name'. If it has a
841 // body, don't allow redefinition or reextern.
842 if (F->getName() != Name) {
843 // Delete the one we just made and get the existing one.
844 F->eraseFromParent();
845 F = TheModule->getFunction(Name);
847 // If F already has a body, reject this.
849 ErrorF("redefinition of function");
853 // If F took a different number of args, reject.
854 if (F->arg_size() != Args.size()) {
855 ErrorF("redefinition of function with different # args");
860 // Set names for all arguments.
862 for (Function::arg_iterator AI = F->arg_begin(); Idx != Args.size();
864 AI->setName(Args[Idx]);
866 // Add arguments to variable symbol table.
867 NamedValues[Args[Idx]] = AI;
873 Function *FunctionAST::Codegen() {
876 Function *TheFunction = Proto->Codegen();
877 if (TheFunction == 0)
880 // If this is an operator, install it.
881 if (Proto->isBinaryOp())
882 BinopPrecedence[Proto->getOperatorName()] = Proto->getBinaryPrecedence();
884 // Create a new basic block to start insertion into.
885 BasicBlock *BB = BasicBlock::Create(getGlobalContext(), "entry", TheFunction);
886 Builder.SetInsertPoint(BB);
888 if (Value *RetVal = Body->Codegen()) {
889 // Finish off the function.
890 Builder.CreateRet(RetVal);
892 // Validate the generated code, checking for consistency.
893 verifyFunction(*TheFunction);
895 // Optimize the function.
896 TheFPM->run(*TheFunction);
901 // Error reading body, remove function.
902 TheFunction->eraseFromParent();
904 if (Proto->isBinaryOp())
905 BinopPrecedence.erase(Proto->getOperatorName());
909 //===----------------------------------------------------------------------===//
910 // Top-Level parsing and JIT Driver
911 //===----------------------------------------------------------------------===//
913 static ExecutionEngine *TheExecutionEngine;
915 static void HandleDefinition() {
916 if (FunctionAST *F = ParseDefinition()) {
917 if (Function *LF = F->Codegen()) {
918 fprintf(stderr, "Read function definition:");
922 // Skip token for error recovery.
927 static void HandleExtern() {
928 if (PrototypeAST *P = ParseExtern()) {
929 if (Function *F = P->Codegen()) {
930 fprintf(stderr, "Read extern: ");
934 // Skip token for error recovery.
939 static void HandleTopLevelExpression() {
940 // Evaluate a top-level expression into an anonymous function.
941 if (FunctionAST *F = ParseTopLevelExpr()) {
942 if (Function *LF = F->Codegen()) {
943 TheExecutionEngine->finalizeObject();
944 // JIT the function, returning a function pointer.
945 void *FPtr = TheExecutionEngine->getPointerToFunction(LF);
947 // Cast it to the right type (takes no arguments, returns a double) so we
948 // can call it as a native function.
949 double (*FP)() = (double (*)())(intptr_t)FPtr;
950 fprintf(stderr, "Evaluated to %f\n", FP());
953 // Skip token for error recovery.
958 /// top ::= definition | external | expression | ';'
959 static void MainLoop() {
961 fprintf(stderr, "ready> ");
967 break; // ignore top-level semicolons.
975 HandleTopLevelExpression();
981 //===----------------------------------------------------------------------===//
982 // "Library" functions that can be "extern'd" from user code.
983 //===----------------------------------------------------------------------===//
985 /// putchard - putchar that takes a double and returns 0.
986 extern "C" double putchard(double X) {
991 /// printd - printf that takes a double prints it as "%f\n", returning 0.
992 extern "C" double printd(double X) {
997 //===----------------------------------------------------------------------===//
999 //===----------------------------------------------------------------------===//
1002 InitializeNativeTarget();
1003 InitializeNativeTargetAsmPrinter();
1004 InitializeNativeTargetAsmParser();
1005 LLVMContext &Context = getGlobalContext();
1007 // Install standard binary operators.
1008 // 1 is lowest precedence.
1009 BinopPrecedence['<'] = 10;
1010 BinopPrecedence['+'] = 20;
1011 BinopPrecedence['-'] = 20;
1012 BinopPrecedence['*'] = 40; // highest.
1014 // Prime the first token.
1015 fprintf(stderr, "ready> ");
1018 // Make the module, which holds all the code.
1019 std::unique_ptr<Module> Owner = make_unique<Module>("my cool jit", Context);
1020 TheModule = Owner.get();
1022 // Create the JIT. This takes ownership of the module.
1024 TheExecutionEngine =
1025 EngineBuilder(std::move(Owner))
1026 .setErrorStr(&ErrStr)
1027 .setMCJITMemoryManager(llvm::make_unique<SectionMemoryManager>())
1029 if (!TheExecutionEngine) {
1030 fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
1034 legacy::FunctionPassManager OurFPM(TheModule);
1036 // Set up the optimizer pipeline. Start with registering info about how the
1037 // target lays out data structures.
1038 TheModule->setDataLayout(TheExecutionEngine->getDataLayout());
1039 // Provide basic AliasAnalysis support for GVN.
1040 OurFPM.add(createBasicAliasAnalysisPass());
1041 // Do simple "peephole" optimizations and bit-twiddling optzns.
1042 OurFPM.add(createInstructionCombiningPass());
1043 // Reassociate expressions.
1044 OurFPM.add(createReassociatePass());
1045 // Eliminate Common SubExpressions.
1046 OurFPM.add(createGVNPass());
1047 // Simplify the control flow graph (deleting unreachable blocks, etc).
1048 OurFPM.add(createCFGSimplificationPass());
1050 OurFPM.doInitialization();
1052 // Set the global so the code gen can use this.
1055 // Run the main "interpreter loop" now.
1060 // Print out all of the generated code.