1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Optimizations may be specified an arbitrary number of times on the command 11 // line, They are run in the order specified. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/IR/LLVMContext.h" 16 #include "llvm/ADT/StringSet.h" 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/Analysis/CallGraph.h" 19 #include "llvm/Analysis/CallGraphSCCPass.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/RegionPass.h" 22 #include "llvm/Analysis/Verifier.h" 23 #include "llvm/Assembly/PrintModulePass.h" 24 #include "llvm/Bitcode/ReaderWriter.h" 25 #include "llvm/CodeGen/CommandFlags.h" 26 #include "llvm/DebugInfo.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Module.h" 29 #include "llvm/LinkAllPasses.h" 30 #include "llvm/LinkAllIR.h" 31 #include "llvm/MC/SubtargetFeature.h" 32 #include "llvm/PassManager.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/IRReader.h" 35 #include "llvm/Support/ManagedStatic.h" 36 #include "llvm/Support/PassNameParser.h" 37 #include "llvm/Support/PluginLoader.h" 38 #include "llvm/Support/PrettyStackTrace.h" 39 #include "llvm/Support/Signals.h" 40 #include "llvm/Support/SystemUtils.h" 41 #include "llvm/Support/TargetRegistry.h" 42 #include "llvm/Support/TargetSelect.h" 43 #include "llvm/Support/ToolOutputFile.h" 44 #include "llvm/Target/TargetLibraryInfo.h" 45 #include "llvm/Target/TargetMachine.h" 46 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 47 #include <algorithm> 48 #include <memory> 49 using namespace llvm; 50 51 // The OptimizationList is automatically populated with registered Passes by the 52 // PassNameParser. 53 // 54 static cl::list<const PassInfo*, bool, PassNameParser> 55 PassList(cl::desc("Optimizations available:")); 56 57 // Other command line options... 58 // 59 static cl::opt<std::string> 60 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 61 cl::init("-"), cl::value_desc("filename")); 62 63 static cl::opt<std::string> 64 OutputFilename("o", cl::desc("Override output filename"), 65 cl::value_desc("filename")); 66 67 static cl::opt<bool> 68 Force("f", cl::desc("Enable binary output on terminals")); 69 70 static cl::opt<bool> 71 PrintEachXForm("p", cl::desc("Print module after each transformation")); 72 73 static cl::opt<bool> 74 NoOutput("disable-output", 75 cl::desc("Do not write result bitcode file"), cl::Hidden); 76 77 static cl::opt<bool> 78 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 79 80 static cl::opt<bool> 81 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden); 82 83 static cl::opt<bool> 84 VerifyEach("verify-each", cl::desc("Verify after each transform")); 85 86 static cl::opt<bool> 87 StripDebug("strip-debug", 88 cl::desc("Strip debugger symbol info from translation unit")); 89 90 static cl::opt<bool> 91 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); 92 93 static cl::opt<bool> 94 DisableOptimizations("disable-opt", 95 cl::desc("Do not run any optimization passes")); 96 97 static cl::opt<bool> 98 DisableInternalize("disable-internalize", 99 cl::desc("Do not mark all symbols as internal")); 100 101 static cl::opt<bool> 102 StandardCompileOpts("std-compile-opts", 103 cl::desc("Include the standard compile time optimizations")); 104 105 static cl::opt<bool> 106 StandardLinkOpts("std-link-opts", 107 cl::desc("Include the standard link time optimizations")); 108 109 static cl::opt<bool> 110 OptLevelO1("O1", 111 cl::desc("Optimization level 1. Similar to clang -O1")); 112 113 static cl::opt<bool> 114 OptLevelO2("O2", 115 cl::desc("Optimization level 2. Similar to clang -O2")); 116 117 static cl::opt<bool> 118 OptLevelOs("Os", 119 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 120 121 static cl::opt<bool> 122 OptLevelOz("Oz", 123 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 124 125 static cl::opt<bool> 126 OptLevelO3("O3", 127 cl::desc("Optimization level 3. Similar to clang -O3")); 128 129 static cl::opt<std::string> 130 TargetTriple("mtriple", cl::desc("Override target triple for module")); 131 132 static cl::opt<bool> 133 UnitAtATime("funit-at-a-time", 134 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"), 135 cl::init(true)); 136 137 static cl::opt<bool> 138 DisableSimplifyLibCalls("disable-simplify-libcalls", 139 cl::desc("Disable simplify-libcalls")); 140 141 static cl::opt<bool> 142 Quiet("q", cl::desc("Obsolete option"), cl::Hidden); 143 144 static cl::alias 145 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); 146 147 static cl::opt<bool> 148 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 149 150 static cl::opt<bool> 151 PrintBreakpoints("print-breakpoints-for-testing", 152 cl::desc("Print select breakpoints location for testing")); 153 154 static cl::opt<std::string> 155 DefaultDataLayout("default-data-layout", 156 cl::desc("data layout string to use if not specified by module"), 157 cl::value_desc("layout-string"), cl::init("")); 158 159 // ---------- Define Printers for module and function passes ------------ 160 namespace { 161 162 struct CallGraphSCCPassPrinter : public CallGraphSCCPass { 163 static char ID; 164 const PassInfo *PassToPrint; 165 raw_ostream &Out; 166 std::string PassName; 167 168 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) : 169 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) { 170 std::string PassToPrintName = PassToPrint->getPassName(); 171 PassName = "CallGraphSCCPass Printer: " + PassToPrintName; 172 } 173 174 virtual bool runOnSCC(CallGraphSCC &SCC) { 175 if (!Quiet) 176 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; 177 178 // Get and print pass... 179 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) { 180 Function *F = (*I)->getFunction(); 181 if (F) 182 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 183 F->getParent()); 184 } 185 return false; 186 } 187 188 virtual const char *getPassName() const { return PassName.c_str(); } 189 190 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 191 AU.addRequiredID(PassToPrint->getTypeInfo()); 192 AU.setPreservesAll(); 193 } 194 }; 195 196 char CallGraphSCCPassPrinter::ID = 0; 197 198 struct ModulePassPrinter : public ModulePass { 199 static char ID; 200 const PassInfo *PassToPrint; 201 raw_ostream &Out; 202 std::string PassName; 203 204 ModulePassPrinter(const PassInfo *PI, raw_ostream &out) 205 : ModulePass(ID), PassToPrint(PI), Out(out) { 206 std::string PassToPrintName = PassToPrint->getPassName(); 207 PassName = "ModulePass Printer: " + PassToPrintName; 208 } 209 210 virtual bool runOnModule(Module &M) { 211 if (!Quiet) 212 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; 213 214 // Get and print pass... 215 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M); 216 return false; 217 } 218 219 virtual const char *getPassName() const { return PassName.c_str(); } 220 221 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 222 AU.addRequiredID(PassToPrint->getTypeInfo()); 223 AU.setPreservesAll(); 224 } 225 }; 226 227 char ModulePassPrinter::ID = 0; 228 struct FunctionPassPrinter : public FunctionPass { 229 const PassInfo *PassToPrint; 230 raw_ostream &Out; 231 static char ID; 232 std::string PassName; 233 234 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out) 235 : FunctionPass(ID), PassToPrint(PI), Out(out) { 236 std::string PassToPrintName = PassToPrint->getPassName(); 237 PassName = "FunctionPass Printer: " + PassToPrintName; 238 } 239 240 virtual bool runOnFunction(Function &F) { 241 if (!Quiet) 242 Out << "Printing analysis '" << PassToPrint->getPassName() 243 << "' for function '" << F.getName() << "':\n"; 244 245 // Get and print pass... 246 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 247 F.getParent()); 248 return false; 249 } 250 251 virtual const char *getPassName() const { return PassName.c_str(); } 252 253 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 254 AU.addRequiredID(PassToPrint->getTypeInfo()); 255 AU.setPreservesAll(); 256 } 257 }; 258 259 char FunctionPassPrinter::ID = 0; 260 261 struct LoopPassPrinter : public LoopPass { 262 static char ID; 263 const PassInfo *PassToPrint; 264 raw_ostream &Out; 265 std::string PassName; 266 267 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) : 268 LoopPass(ID), PassToPrint(PI), Out(out) { 269 std::string PassToPrintName = PassToPrint->getPassName(); 270 PassName = "LoopPass Printer: " + PassToPrintName; 271 } 272 273 274 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) { 275 if (!Quiet) 276 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n"; 277 278 // Get and print pass... 279 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 280 L->getHeader()->getParent()->getParent()); 281 return false; 282 } 283 284 virtual const char *getPassName() const { return PassName.c_str(); } 285 286 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 287 AU.addRequiredID(PassToPrint->getTypeInfo()); 288 AU.setPreservesAll(); 289 } 290 }; 291 292 char LoopPassPrinter::ID = 0; 293 294 struct RegionPassPrinter : public RegionPass { 295 static char ID; 296 const PassInfo *PassToPrint; 297 raw_ostream &Out; 298 std::string PassName; 299 300 RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID), 301 PassToPrint(PI), Out(out) { 302 std::string PassToPrintName = PassToPrint->getPassName(); 303 PassName = "RegionPass Printer: " + PassToPrintName; 304 } 305 306 virtual bool runOnRegion(Region *R, RGPassManager &RGM) { 307 if (!Quiet) { 308 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for " 309 << "region: '" << R->getNameStr() << "' in function '" 310 << R->getEntry()->getParent()->getName() << "':\n"; 311 } 312 // Get and print pass... 313 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 314 R->getEntry()->getParent()->getParent()); 315 return false; 316 } 317 318 virtual const char *getPassName() const { return PassName.c_str(); } 319 320 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 321 AU.addRequiredID(PassToPrint->getTypeInfo()); 322 AU.setPreservesAll(); 323 } 324 }; 325 326 char RegionPassPrinter::ID = 0; 327 328 struct BasicBlockPassPrinter : public BasicBlockPass { 329 const PassInfo *PassToPrint; 330 raw_ostream &Out; 331 static char ID; 332 std::string PassName; 333 334 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out) 335 : BasicBlockPass(ID), PassToPrint(PI), Out(out) { 336 std::string PassToPrintName = PassToPrint->getPassName(); 337 PassName = "BasicBlockPass Printer: " + PassToPrintName; 338 } 339 340 virtual bool runOnBasicBlock(BasicBlock &BB) { 341 if (!Quiet) 342 Out << "Printing Analysis info for BasicBlock '" << BB.getName() 343 << "': Pass " << PassToPrint->getPassName() << ":\n"; 344 345 // Get and print pass... 346 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, 347 BB.getParent()->getParent()); 348 return false; 349 } 350 351 virtual const char *getPassName() const { return PassName.c_str(); } 352 353 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 354 AU.addRequiredID(PassToPrint->getTypeInfo()); 355 AU.setPreservesAll(); 356 } 357 }; 358 359 char BasicBlockPassPrinter::ID = 0; 360 361 struct BreakpointPrinter : public ModulePass { 362 raw_ostream &Out; 363 static char ID; 364 365 BreakpointPrinter(raw_ostream &out) 366 : ModulePass(ID), Out(out) { 367 } 368 369 void getContextName(DIDescriptor Context, std::string &N) { 370 if (Context.isNameSpace()) { 371 DINameSpace NS(Context); 372 if (!NS.getName().empty()) { 373 getContextName(NS.getContext(), N); 374 N = N + NS.getName().str() + "::"; 375 } 376 } else if (Context.isType()) { 377 DIType TY(Context); 378 if (!TY.getName().empty()) { 379 getContextName(TY.getContext(), N); 380 N = N + TY.getName().str() + "::"; 381 } 382 } 383 } 384 385 virtual bool runOnModule(Module &M) { 386 StringSet<> Processed; 387 if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp")) 388 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 389 std::string Name; 390 DISubprogram SP(NMD->getOperand(i)); 391 if (SP.Verify()) 392 getContextName(SP.getContext(), Name); 393 Name = Name + SP.getDisplayName().str(); 394 if (!Name.empty() && Processed.insert(Name)) { 395 Out << Name << "\n"; 396 } 397 } 398 return false; 399 } 400 401 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 402 AU.setPreservesAll(); 403 } 404 }; 405 406 } // anonymous namespace 407 408 char BreakpointPrinter::ID = 0; 409 410 static inline void addPass(PassManagerBase &PM, Pass *P) { 411 // Add the pass to the pass manager... 412 PM.add(P); 413 414 // If we are verifying all of the intermediate steps, add the verifier... 415 if (VerifyEach) PM.add(createVerifierPass()); 416 } 417 418 /// AddOptimizationPasses - This routine adds optimization passes 419 /// based on selected optimization level, OptLevel. This routine 420 /// duplicates llvm-gcc behaviour. 421 /// 422 /// OptLevel - Optimization Level 423 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM, 424 unsigned OptLevel, unsigned SizeLevel) { 425 FPM.add(createVerifierPass()); // Verify that input is correct 426 427 PassManagerBuilder Builder; 428 Builder.OptLevel = OptLevel; 429 Builder.SizeLevel = SizeLevel; 430 431 if (DisableInline) { 432 // No inlining pass 433 } else if (OptLevel > 1) { 434 unsigned Threshold = 225; 435 if (SizeLevel == 1) // -Os 436 Threshold = 75; 437 else if (SizeLevel == 2) // -Oz 438 Threshold = 25; 439 if (OptLevel > 2) 440 Threshold = 275; 441 Builder.Inliner = createFunctionInliningPass(Threshold); 442 } else { 443 Builder.Inliner = createAlwaysInlinerPass(); 444 } 445 Builder.DisableUnitAtATime = !UnitAtATime; 446 Builder.DisableUnrollLoops = OptLevel == 0; 447 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls; 448 449 Builder.populateFunctionPassManager(FPM); 450 Builder.populateModulePassManager(MPM); 451 } 452 453 static void AddStandardCompilePasses(PassManagerBase &PM) { 454 PM.add(createVerifierPass()); // Verify that input is correct 455 456 // If the -strip-debug command line option was specified, do it. 457 if (StripDebug) 458 addPass(PM, createStripSymbolsPass(true)); 459 460 if (DisableOptimizations) return; 461 462 // -std-compile-opts adds the same module passes as -O3. 463 PassManagerBuilder Builder; 464 if (!DisableInline) 465 Builder.Inliner = createFunctionInliningPass(); 466 Builder.OptLevel = 3; 467 Builder.DisableSimplifyLibCalls = DisableSimplifyLibCalls; 468 Builder.populateModulePassManager(PM); 469 } 470 471 static void AddStandardLinkPasses(PassManagerBase &PM) { 472 PM.add(createVerifierPass()); // Verify that input is correct 473 474 // If the -strip-debug command line option was specified, do it. 475 if (StripDebug) 476 addPass(PM, createStripSymbolsPass(true)); 477 478 if (DisableOptimizations) return; 479 480 PassManagerBuilder Builder; 481 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize, 482 /*RunInliner=*/ !DisableInline); 483 } 484 485 //===----------------------------------------------------------------------===// 486 // CodeGen-related helper functions. 487 // 488 static TargetOptions GetTargetOptions() { 489 TargetOptions Options; 490 Options.LessPreciseFPMADOption = EnableFPMAD; 491 Options.NoFramePointerElim = DisableFPElim; 492 Options.NoFramePointerElimNonLeaf = DisableFPElimNonLeaf; 493 Options.AllowFPOpFusion = FuseFPOps; 494 Options.UnsafeFPMath = EnableUnsafeFPMath; 495 Options.NoInfsFPMath = EnableNoInfsFPMath; 496 Options.NoNaNsFPMath = EnableNoNaNsFPMath; 497 Options.HonorSignDependentRoundingFPMathOption = 498 EnableHonorSignDependentRoundingFPMath; 499 Options.UseSoftFloat = GenerateSoftFloatCalls; 500 if (FloatABIForCalls != FloatABI::Default) 501 Options.FloatABIType = FloatABIForCalls; 502 Options.NoZerosInBSS = DontPlaceZerosInBSS; 503 Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt; 504 Options.DisableTailCalls = DisableTailCalls; 505 Options.StackAlignmentOverride = OverrideStackAlignment; 506 Options.RealignStack = EnableRealignStack; 507 Options.TrapFuncName = TrapFuncName; 508 Options.PositionIndependentExecutable = EnablePIE; 509 Options.EnableSegmentedStacks = SegmentedStacks; 510 Options.UseInitArray = UseInitArray; 511 Options.SSPBufferSize = SSPBufferSize; 512 return Options; 513 } 514 515 CodeGenOpt::Level GetCodeGenOptLevel() { 516 if (OptLevelO1) 517 return CodeGenOpt::Less; 518 if (OptLevelO2) 519 return CodeGenOpt::Default; 520 if (OptLevelO3) 521 return CodeGenOpt::Aggressive; 522 return CodeGenOpt::None; 523 } 524 525 // Returns the TargetMachine instance or zero if no triple is provided. 526 static TargetMachine* GetTargetMachine(Triple TheTriple) { 527 std::string Error; 528 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 529 Error); 530 // Some modules don't specify a triple, and this is okay. 531 if (!TheTarget) { 532 return 0; 533 } 534 535 // Package up features to be passed to target/subtarget 536 std::string FeaturesStr; 537 if (MAttrs.size()) { 538 SubtargetFeatures Features; 539 for (unsigned i = 0; i != MAttrs.size(); ++i) 540 Features.AddFeature(MAttrs[i]); 541 FeaturesStr = Features.getString(); 542 } 543 544 return TheTarget->createTargetMachine(TheTriple.getTriple(), 545 MCPU, FeaturesStr, GetTargetOptions(), 546 RelocModel, CMModel, 547 GetCodeGenOptLevel()); 548 } 549 550 //===----------------------------------------------------------------------===// 551 // main for opt 552 // 553 int main(int argc, char **argv) { 554 sys::PrintStackTraceOnErrorSignal(); 555 llvm::PrettyStackTraceProgram X(argc, argv); 556 557 // Enable debug stream buffering. 558 EnableDebugBuffering = true; 559 560 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 561 LLVMContext &Context = getGlobalContext(); 562 563 InitializeAllTargets(); 564 InitializeAllTargetMCs(); 565 566 // Initialize passes 567 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 568 initializeCore(Registry); 569 initializeScalarOpts(Registry); 570 initializeVectorization(Registry); 571 initializeIPO(Registry); 572 initializeAnalysis(Registry); 573 initializeIPA(Registry); 574 initializeTransformUtils(Registry); 575 initializeInstCombine(Registry); 576 initializeInstrumentation(Registry); 577 initializeTarget(Registry); 578 579 cl::ParseCommandLineOptions(argc, argv, 580 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 581 582 if (AnalyzeOnly && NoOutput) { 583 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 584 return 1; 585 } 586 587 SMDiagnostic Err; 588 589 // Load the input module... 590 std::auto_ptr<Module> M; 591 M.reset(ParseIRFile(InputFilename, Err, Context)); 592 593 if (M.get() == 0) { 594 Err.print(argv[0], errs()); 595 return 1; 596 } 597 598 // If we are supposed to override the target triple, do so now. 599 if (!TargetTriple.empty()) 600 M->setTargetTriple(Triple::normalize(TargetTriple)); 601 602 // Figure out what stream we are supposed to write to... 603 OwningPtr<tool_output_file> Out; 604 if (NoOutput) { 605 if (!OutputFilename.empty()) 606 errs() << "WARNING: The -o (output filename) option is ignored when\n" 607 "the --disable-output option is used.\n"; 608 } else { 609 // Default to standard output. 610 if (OutputFilename.empty()) 611 OutputFilename = "-"; 612 613 std::string ErrorInfo; 614 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 615 raw_fd_ostream::F_Binary)); 616 if (!ErrorInfo.empty()) { 617 errs() << ErrorInfo << '\n'; 618 return 1; 619 } 620 } 621 622 // If the output is set to be emitted to standard out, and standard out is a 623 // console, print out a warning message and refuse to do it. We don't 624 // impress anyone by spewing tons of binary goo to a terminal. 625 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 626 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 627 NoOutput = true; 628 629 // Create a PassManager to hold and optimize the collection of passes we are 630 // about to build. 631 // 632 PassManager Passes; 633 634 // Add an appropriate TargetLibraryInfo pass for the module's triple. 635 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple())); 636 637 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 638 if (DisableSimplifyLibCalls) 639 TLI->disableAllFunctions(); 640 Passes.add(TLI); 641 642 // Add an appropriate DataLayout instance for this module. 643 DataLayout *TD = 0; 644 const std::string &ModuleDataLayout = M.get()->getDataLayout(); 645 if (!ModuleDataLayout.empty()) 646 TD = new DataLayout(ModuleDataLayout); 647 else if (!DefaultDataLayout.empty()) 648 TD = new DataLayout(DefaultDataLayout); 649 650 if (TD) 651 Passes.add(TD); 652 653 Triple ModuleTriple(M->getTargetTriple()); 654 TargetMachine *Machine = 0; 655 if (ModuleTriple.getArch()) 656 Machine = GetTargetMachine(Triple(ModuleTriple)); 657 std::auto_ptr<TargetMachine> TM(Machine); 658 659 // Add internal analysis passes from the target machine. 660 if (TM.get()) 661 TM->addAnalysisPasses(Passes); 662 663 OwningPtr<FunctionPassManager> FPasses; 664 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 665 FPasses.reset(new FunctionPassManager(M.get())); 666 if (TD) 667 FPasses->add(new DataLayout(*TD)); 668 } 669 670 if (PrintBreakpoints) { 671 // Default to standard output. 672 if (!Out) { 673 if (OutputFilename.empty()) 674 OutputFilename = "-"; 675 676 std::string ErrorInfo; 677 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 678 raw_fd_ostream::F_Binary)); 679 if (!ErrorInfo.empty()) { 680 errs() << ErrorInfo << '\n'; 681 return 1; 682 } 683 } 684 Passes.add(new BreakpointPrinter(Out->os())); 685 NoOutput = true; 686 } 687 688 // If the -strip-debug command line option was specified, add it. If 689 // -std-compile-opts was also specified, it will handle StripDebug. 690 if (StripDebug && !StandardCompileOpts) 691 addPass(Passes, createStripSymbolsPass(true)); 692 693 // Create a new optimization pass for each one specified on the command line 694 for (unsigned i = 0; i < PassList.size(); ++i) { 695 // Check to see if -std-compile-opts was specified before this option. If 696 // so, handle it. 697 if (StandardCompileOpts && 698 StandardCompileOpts.getPosition() < PassList.getPosition(i)) { 699 AddStandardCompilePasses(Passes); 700 StandardCompileOpts = false; 701 } 702 703 if (StandardLinkOpts && 704 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 705 AddStandardLinkPasses(Passes); 706 StandardLinkOpts = false; 707 } 708 709 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 710 AddOptimizationPasses(Passes, *FPasses, 1, 0); 711 OptLevelO1 = false; 712 } 713 714 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 715 AddOptimizationPasses(Passes, *FPasses, 2, 0); 716 OptLevelO2 = false; 717 } 718 719 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 720 AddOptimizationPasses(Passes, *FPasses, 2, 1); 721 OptLevelOs = false; 722 } 723 724 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 725 AddOptimizationPasses(Passes, *FPasses, 2, 2); 726 OptLevelOz = false; 727 } 728 729 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 730 AddOptimizationPasses(Passes, *FPasses, 3, 0); 731 OptLevelO3 = false; 732 } 733 734 const PassInfo *PassInf = PassList[i]; 735 Pass *P = 0; 736 if (PassInf->getNormalCtor()) 737 P = PassInf->getNormalCtor()(); 738 else 739 errs() << argv[0] << ": cannot create pass: " 740 << PassInf->getPassName() << "\n"; 741 if (P) { 742 PassKind Kind = P->getPassKind(); 743 addPass(Passes, P); 744 745 if (AnalyzeOnly) { 746 switch (Kind) { 747 case PT_BasicBlock: 748 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os())); 749 break; 750 case PT_Region: 751 Passes.add(new RegionPassPrinter(PassInf, Out->os())); 752 break; 753 case PT_Loop: 754 Passes.add(new LoopPassPrinter(PassInf, Out->os())); 755 break; 756 case PT_Function: 757 Passes.add(new FunctionPassPrinter(PassInf, Out->os())); 758 break; 759 case PT_CallGraphSCC: 760 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os())); 761 break; 762 default: 763 Passes.add(new ModulePassPrinter(PassInf, Out->os())); 764 break; 765 } 766 } 767 } 768 769 if (PrintEachXForm) 770 Passes.add(createPrintModulePass(&errs())); 771 } 772 773 // If -std-compile-opts was specified at the end of the pass list, add them. 774 if (StandardCompileOpts) { 775 AddStandardCompilePasses(Passes); 776 StandardCompileOpts = false; 777 } 778 779 if (StandardLinkOpts) { 780 AddStandardLinkPasses(Passes); 781 StandardLinkOpts = false; 782 } 783 784 if (OptLevelO1) 785 AddOptimizationPasses(Passes, *FPasses, 1, 0); 786 787 if (OptLevelO2) 788 AddOptimizationPasses(Passes, *FPasses, 2, 0); 789 790 if (OptLevelOs) 791 AddOptimizationPasses(Passes, *FPasses, 2, 1); 792 793 if (OptLevelOz) 794 AddOptimizationPasses(Passes, *FPasses, 2, 2); 795 796 if (OptLevelO3) 797 AddOptimizationPasses(Passes, *FPasses, 3, 0); 798 799 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 800 FPasses->doInitialization(); 801 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F) 802 FPasses->run(*F); 803 FPasses->doFinalization(); 804 } 805 806 // Check that the module is well formed on completion of optimization 807 if (!NoVerify && !VerifyEach) 808 Passes.add(createVerifierPass()); 809 810 // Write bitcode or assembly to the output as the last step... 811 if (!NoOutput && !AnalyzeOnly) { 812 if (OutputAssembly) 813 Passes.add(createPrintModulePass(&Out->os())); 814 else 815 Passes.add(createBitcodeWriterPass(Out->os())); 816 } 817 818 // Before executing passes, print the final values of the LLVM options. 819 cl::PrintOptionValues(); 820 821 // Now that we have all of the passes ready, run them. 822 Passes.run(*M.get()); 823 824 // Declare success. 825 if (!NoOutput || PrintBreakpoints) 826 Out->keep(); 827 828 return 0; 829 } 830