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 "BreakpointPrinter.h" 16 #include "NewPMDriver.h" 17 #include "PassPrinters.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Analysis/CallGraph.h" 20 #include "llvm/Analysis/CallGraphSCCPass.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/RegionPass.h" 23 #include "llvm/Analysis/TargetLibraryInfo.h" 24 #include "llvm/Analysis/TargetTransformInfo.h" 25 #include "llvm/Bitcode/BitcodeWriterPass.h" 26 #include "llvm/CodeGen/CommandFlags.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/DebugInfo.h" 29 #include "llvm/IR/IRPrintingPasses.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/LegacyPassManager.h" 32 #include "llvm/IR/LegacyPassNameParser.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Verifier.h" 35 #include "llvm/IRReader/IRReader.h" 36 #include "llvm/InitializePasses.h" 37 #include "llvm/LinkAllIR.h" 38 #include "llvm/LinkAllPasses.h" 39 #include "llvm/MC/SubtargetFeature.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/FileSystem.h" 42 #include "llvm/Support/Host.h" 43 #include "llvm/Support/ManagedStatic.h" 44 #include "llvm/Support/PluginLoader.h" 45 #include "llvm/Support/PrettyStackTrace.h" 46 #include "llvm/Support/Signals.h" 47 #include "llvm/Support/SourceMgr.h" 48 #include "llvm/Support/SystemUtils.h" 49 #include "llvm/Support/TargetRegistry.h" 50 #include "llvm/Support/TargetSelect.h" 51 #include "llvm/Support/ToolOutputFile.h" 52 #include "llvm/Target/TargetMachine.h" 53 #include "llvm/Transforms/Coroutines.h" 54 #include "llvm/Transforms/IPO/AlwaysInliner.h" 55 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 56 #include "llvm/Transforms/Utils/Cloning.h" 57 #include <algorithm> 58 #include <memory> 59 using namespace llvm; 60 using namespace opt_tool; 61 62 // The OptimizationList is automatically populated with registered Passes by the 63 // PassNameParser. 64 // 65 static cl::list<const PassInfo*, bool, PassNameParser> 66 PassList(cl::desc("Optimizations available:")); 67 68 // This flag specifies a textual description of the optimization pass pipeline 69 // to run over the module. This flag switches opt to use the new pass manager 70 // infrastructure, completely disabling all of the flags specific to the old 71 // pass management. 72 static cl::opt<std::string> PassPipeline( 73 "passes", 74 cl::desc("A textual description of the pass pipeline for optimizing"), 75 cl::Hidden); 76 77 // Other command line options... 78 // 79 static cl::opt<std::string> 80 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 81 cl::init("-"), cl::value_desc("filename")); 82 83 static cl::opt<std::string> 84 OutputFilename("o", cl::desc("Override output filename"), 85 cl::value_desc("filename")); 86 87 static cl::opt<bool> 88 Force("f", cl::desc("Enable binary output on terminals")); 89 90 static cl::opt<bool> 91 PrintEachXForm("p", cl::desc("Print module after each transformation")); 92 93 static cl::opt<bool> 94 NoOutput("disable-output", 95 cl::desc("Do not write result bitcode file"), cl::Hidden); 96 97 static cl::opt<bool> 98 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 99 100 static cl::opt<bool> 101 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden); 102 103 static cl::opt<bool> 104 VerifyEach("verify-each", cl::desc("Verify after each transform")); 105 106 static cl::opt<bool> 107 DisableDITypeMap("disable-debug-info-type-map", 108 cl::desc("Don't use a uniquing type map for debug info")); 109 110 static cl::opt<bool> 111 StripDebug("strip-debug", 112 cl::desc("Strip debugger symbol info from translation unit")); 113 114 static cl::opt<bool> 115 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); 116 117 static cl::opt<bool> 118 DisableOptimizations("disable-opt", 119 cl::desc("Do not run any optimization passes")); 120 121 static cl::opt<bool> 122 StandardLinkOpts("std-link-opts", 123 cl::desc("Include the standard link time optimizations")); 124 125 static cl::opt<bool> 126 OptLevelO0("O0", 127 cl::desc("Optimization level 0. Similar to clang -O0")); 128 129 static cl::opt<bool> 130 OptLevelO1("O1", 131 cl::desc("Optimization level 1. Similar to clang -O1")); 132 133 static cl::opt<bool> 134 OptLevelO2("O2", 135 cl::desc("Optimization level 2. Similar to clang -O2")); 136 137 static cl::opt<bool> 138 OptLevelOs("Os", 139 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 140 141 static cl::opt<bool> 142 OptLevelOz("Oz", 143 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 144 145 static cl::opt<bool> 146 OptLevelO3("O3", 147 cl::desc("Optimization level 3. Similar to clang -O3")); 148 149 static cl::opt<unsigned> 150 CodeGenOptLevel("codegen-opt-level", 151 cl::desc("Override optimization level for codegen hooks")); 152 153 static cl::opt<std::string> 154 TargetTriple("mtriple", cl::desc("Override target triple for module")); 155 156 static cl::opt<bool> 157 UnitAtATime("funit-at-a-time", 158 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"), 159 cl::init(true)); 160 161 static cl::opt<bool> 162 DisableLoopUnrolling("disable-loop-unrolling", 163 cl::desc("Disable loop unrolling in all relevant passes"), 164 cl::init(false)); 165 static cl::opt<bool> 166 DisableLoopVectorization("disable-loop-vectorization", 167 cl::desc("Disable the loop vectorization pass"), 168 cl::init(false)); 169 170 static cl::opt<bool> 171 DisableSLPVectorization("disable-slp-vectorization", 172 cl::desc("Disable the slp vectorization pass"), 173 cl::init(false)); 174 175 static cl::opt<bool> EmitSummaryIndex("module-summary", 176 cl::desc("Emit module summary index"), 177 cl::init(false)); 178 179 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"), 180 cl::init(false)); 181 182 static cl::opt<bool> 183 DisableSimplifyLibCalls("disable-simplify-libcalls", 184 cl::desc("Disable simplify-libcalls")); 185 186 static cl::opt<bool> 187 Quiet("q", cl::desc("Obsolete option"), cl::Hidden); 188 189 static cl::alias 190 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); 191 192 static cl::opt<bool> 193 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 194 195 static cl::opt<bool> 196 PrintBreakpoints("print-breakpoints-for-testing", 197 cl::desc("Print select breakpoints location for testing")); 198 199 static cl::opt<std::string> 200 DefaultDataLayout("default-data-layout", 201 cl::desc("data layout string to use if not specified by module"), 202 cl::value_desc("layout-string"), cl::init("")); 203 204 static cl::opt<bool> PreserveBitcodeUseListOrder( 205 "preserve-bc-uselistorder", 206 cl::desc("Preserve use-list order when writing LLVM bitcode."), 207 cl::init(true), cl::Hidden); 208 209 static cl::opt<bool> PreserveAssemblyUseListOrder( 210 "preserve-ll-uselistorder", 211 cl::desc("Preserve use-list order when writing LLVM assembly."), 212 cl::init(false), cl::Hidden); 213 214 static cl::opt<bool> 215 RunTwice("run-twice", 216 cl::desc("Run all passes twice, re-using the same pass manager."), 217 cl::init(false), cl::Hidden); 218 219 static cl::opt<bool> DiscardValueNames( 220 "discard-value-names", 221 cl::desc("Discard names from Value (other than GlobalValue)."), 222 cl::init(false), cl::Hidden); 223 224 static cl::opt<bool> Coroutines( 225 "enable-coroutines", 226 cl::desc("Enable coroutine passes."), 227 cl::init(false), cl::Hidden); 228 229 static cl::opt<bool> PassRemarksWithHotness( 230 "pass-remarks-with-hotness", 231 cl::desc("With PGO, include profile count in optimization remarks"), 232 cl::Hidden); 233 234 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) { 235 // Add the pass to the pass manager... 236 PM.add(P); 237 238 // If we are verifying all of the intermediate steps, add the verifier... 239 if (VerifyEach) 240 PM.add(createVerifierPass()); 241 } 242 243 /// This routine adds optimization passes based on selected optimization level, 244 /// OptLevel. 245 /// 246 /// OptLevel - Optimization Level 247 static void AddOptimizationPasses(legacy::PassManagerBase &MPM, 248 legacy::FunctionPassManager &FPM, 249 TargetMachine *TM, unsigned OptLevel, 250 unsigned SizeLevel) { 251 if (!NoVerify || VerifyEach) 252 FPM.add(createVerifierPass()); // Verify that input is correct 253 254 PassManagerBuilder Builder; 255 Builder.OptLevel = OptLevel; 256 Builder.SizeLevel = SizeLevel; 257 258 if (DisableInline) { 259 // No inlining pass 260 } else if (OptLevel > 1) { 261 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel); 262 } else { 263 Builder.Inliner = createAlwaysInlinerLegacyPass(); 264 } 265 Builder.DisableUnitAtATime = !UnitAtATime; 266 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 267 DisableLoopUnrolling : OptLevel == 0; 268 269 // This is final, unless there is a #pragma vectorize enable 270 if (DisableLoopVectorization) 271 Builder.LoopVectorize = false; 272 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) 273 else if (!Builder.LoopVectorize) 274 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 275 276 // When #pragma vectorize is on for SLP, do the same as above 277 Builder.SLPVectorize = 278 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2; 279 280 // Add target-specific passes that need to run as early as possible. 281 if (TM) 282 Builder.addExtension( 283 PassManagerBuilder::EP_EarlyAsPossible, 284 [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) { 285 TM->addEarlyAsPossiblePasses(PM); 286 }); 287 288 if (Coroutines) 289 addCoroutinePassesToExtensionPoints(Builder); 290 291 Builder.populateFunctionPassManager(FPM); 292 Builder.populateModulePassManager(MPM); 293 } 294 295 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { 296 PassManagerBuilder Builder; 297 Builder.VerifyInput = true; 298 if (DisableOptimizations) 299 Builder.OptLevel = 0; 300 301 if (!DisableInline) 302 Builder.Inliner = createFunctionInliningPass(); 303 Builder.populateLTOPassManager(PM); 304 } 305 306 //===----------------------------------------------------------------------===// 307 // CodeGen-related helper functions. 308 // 309 310 static CodeGenOpt::Level GetCodeGenOptLevel() { 311 if (CodeGenOptLevel.getNumOccurrences()) 312 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel)); 313 if (OptLevelO1) 314 return CodeGenOpt::Less; 315 if (OptLevelO2) 316 return CodeGenOpt::Default; 317 if (OptLevelO3) 318 return CodeGenOpt::Aggressive; 319 return CodeGenOpt::None; 320 } 321 322 // Returns the TargetMachine instance or zero if no triple is provided. 323 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, 324 StringRef FeaturesStr, 325 const TargetOptions &Options) { 326 std::string Error; 327 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 328 Error); 329 // Some modules don't specify a triple, and this is okay. 330 if (!TheTarget) { 331 return nullptr; 332 } 333 334 return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, 335 FeaturesStr, Options, getRelocModel(), 336 CMModel, GetCodeGenOptLevel()); 337 } 338 339 #ifdef LINK_POLLY_INTO_TOOLS 340 namespace polly { 341 void initializePollyPasses(llvm::PassRegistry &Registry); 342 } 343 #endif 344 345 //===----------------------------------------------------------------------===// 346 // main for opt 347 // 348 int main(int argc, char **argv) { 349 sys::PrintStackTraceOnErrorSignal(argv[0]); 350 llvm::PrettyStackTraceProgram X(argc, argv); 351 352 // Enable debug stream buffering. 353 EnableDebugBuffering = true; 354 355 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 356 LLVMContext Context; 357 358 InitializeAllTargets(); 359 InitializeAllTargetMCs(); 360 InitializeAllAsmPrinters(); 361 362 // Initialize passes 363 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 364 initializeCore(Registry); 365 initializeCoroutines(Registry); 366 initializeScalarOpts(Registry); 367 initializeObjCARCOpts(Registry); 368 initializeVectorization(Registry); 369 initializeIPO(Registry); 370 initializeAnalysis(Registry); 371 initializeTransformUtils(Registry); 372 initializeInstCombine(Registry); 373 initializeInstrumentation(Registry); 374 initializeTarget(Registry); 375 // For codegen passes, only passes that do IR to IR transformation are 376 // supported. 377 initializeCodeGenPreparePass(Registry); 378 initializeAtomicExpandPass(Registry); 379 initializeRewriteSymbolsLegacyPassPass(Registry); 380 initializeWinEHPreparePass(Registry); 381 initializeDwarfEHPreparePass(Registry); 382 initializeSafeStackPass(Registry); 383 initializeSjLjEHPreparePass(Registry); 384 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 385 initializeGlobalMergePass(Registry); 386 initializeInterleavedAccessPass(Registry); 387 initializeCountingFunctionInserterPass(Registry); 388 initializeUnreachableBlockElimLegacyPassPass(Registry); 389 390 #ifdef LINK_POLLY_INTO_TOOLS 391 polly::initializePollyPasses(Registry); 392 #endif 393 394 cl::ParseCommandLineOptions(argc, argv, 395 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 396 397 if (AnalyzeOnly && NoOutput) { 398 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 399 return 1; 400 } 401 402 SMDiagnostic Err; 403 404 Context.setDiscardValueNames(DiscardValueNames); 405 if (!DisableDITypeMap) 406 Context.enableDebugTypeODRUniquing(); 407 408 if (PassRemarksWithHotness) 409 Context.setDiagnosticHotnessRequested(true); 410 411 // Load the input module... 412 std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context); 413 414 if (!M) { 415 Err.print(argv[0], errs()); 416 return 1; 417 } 418 419 // Strip debug info before running the verifier. 420 if (StripDebug) 421 StripDebugInfo(*M); 422 423 // Immediately run the verifier to catch any problems before starting up the 424 // pass pipelines. Otherwise we can crash on broken code during 425 // doInitialization(). 426 if (!NoVerify && verifyModule(*M, &errs())) { 427 errs() << argv[0] << ": " << InputFilename 428 << ": error: input module is broken!\n"; 429 return 1; 430 } 431 432 // If we are supposed to override the target triple, do so now. 433 if (!TargetTriple.empty()) 434 M->setTargetTriple(Triple::normalize(TargetTriple)); 435 436 // Figure out what stream we are supposed to write to... 437 std::unique_ptr<tool_output_file> Out; 438 if (NoOutput) { 439 if (!OutputFilename.empty()) 440 errs() << "WARNING: The -o (output filename) option is ignored when\n" 441 "the --disable-output option is used.\n"; 442 } else { 443 // Default to standard output. 444 if (OutputFilename.empty()) 445 OutputFilename = "-"; 446 447 std::error_code EC; 448 Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None)); 449 if (EC) { 450 errs() << EC.message() << '\n'; 451 return 1; 452 } 453 } 454 455 Triple ModuleTriple(M->getTargetTriple()); 456 std::string CPUStr, FeaturesStr; 457 TargetMachine *Machine = nullptr; 458 const TargetOptions Options = InitTargetOptionsFromCodeGenFlags(); 459 460 if (ModuleTriple.getArch()) { 461 CPUStr = getCPUStr(); 462 FeaturesStr = getFeaturesStr(); 463 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 464 } 465 466 std::unique_ptr<TargetMachine> TM(Machine); 467 468 // Override function attributes based on CPUStr, FeaturesStr, and command line 469 // flags. 470 setFunctionAttributes(CPUStr, FeaturesStr, *M); 471 472 // If the output is set to be emitted to standard out, and standard out is a 473 // console, print out a warning message and refuse to do it. We don't 474 // impress anyone by spewing tons of binary goo to a terminal. 475 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 476 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 477 NoOutput = true; 478 479 if (PassPipeline.getNumOccurrences() > 0) { 480 OutputKind OK = OK_NoOutput; 481 if (!NoOutput) 482 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode; 483 484 VerifierKind VK = VK_VerifyInAndOut; 485 if (NoVerify) 486 VK = VK_NoVerifier; 487 else if (VerifyEach) 488 VK = VK_VerifyEachPass; 489 490 // The user has asked to use the new pass manager and provided a pipeline 491 // string. Hand off the rest of the functionality to the new code for that 492 // layer. 493 return runPassPipeline(argv[0], *M, TM.get(), Out.get(), 494 PassPipeline, OK, VK, PreserveAssemblyUseListOrder, 495 PreserveBitcodeUseListOrder, EmitSummaryIndex, 496 EmitModuleHash) 497 ? 0 498 : 1; 499 } 500 501 // Create a PassManager to hold and optimize the collection of passes we are 502 // about to build. 503 // 504 legacy::PassManager Passes; 505 506 // Add an appropriate TargetLibraryInfo pass for the module's triple. 507 TargetLibraryInfoImpl TLII(ModuleTriple); 508 509 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 510 if (DisableSimplifyLibCalls) 511 TLII.disableAllFunctions(); 512 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 513 514 // Add an appropriate DataLayout instance for this module. 515 const DataLayout &DL = M->getDataLayout(); 516 if (DL.isDefault() && !DefaultDataLayout.empty()) { 517 M->setDataLayout(DefaultDataLayout); 518 } 519 520 // Add internal analysis passes from the target machine. 521 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 522 : TargetIRAnalysis())); 523 524 std::unique_ptr<legacy::FunctionPassManager> FPasses; 525 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 526 OptLevelO3) { 527 FPasses.reset(new legacy::FunctionPassManager(M.get())); 528 FPasses->add(createTargetTransformInfoWrapperPass( 529 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 530 } 531 532 if (PrintBreakpoints) { 533 // Default to standard output. 534 if (!Out) { 535 if (OutputFilename.empty()) 536 OutputFilename = "-"; 537 538 std::error_code EC; 539 Out = llvm::make_unique<tool_output_file>(OutputFilename, EC, 540 sys::fs::F_None); 541 if (EC) { 542 errs() << EC.message() << '\n'; 543 return 1; 544 } 545 } 546 Passes.add(createBreakpointPrinter(Out->os())); 547 NoOutput = true; 548 } 549 550 // Create a new optimization pass for each one specified on the command line 551 for (unsigned i = 0; i < PassList.size(); ++i) { 552 if (StandardLinkOpts && 553 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 554 AddStandardLinkPasses(Passes); 555 StandardLinkOpts = false; 556 } 557 558 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 559 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 560 OptLevelO0 = false; 561 } 562 563 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 564 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 565 OptLevelO1 = false; 566 } 567 568 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 569 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 570 OptLevelO2 = false; 571 } 572 573 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 574 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 575 OptLevelOs = false; 576 } 577 578 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 579 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 580 OptLevelOz = false; 581 } 582 583 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 584 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 585 OptLevelO3 = false; 586 } 587 588 const PassInfo *PassInf = PassList[i]; 589 Pass *P = nullptr; 590 if (PassInf->getTargetMachineCtor()) 591 P = PassInf->getTargetMachineCtor()(TM.get()); 592 else if (PassInf->getNormalCtor()) 593 P = PassInf->getNormalCtor()(); 594 else 595 errs() << argv[0] << ": cannot create pass: " 596 << PassInf->getPassName() << "\n"; 597 if (P) { 598 PassKind Kind = P->getPassKind(); 599 addPass(Passes, P); 600 601 if (AnalyzeOnly) { 602 switch (Kind) { 603 case PT_BasicBlock: 604 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet)); 605 break; 606 case PT_Region: 607 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); 608 break; 609 case PT_Loop: 610 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); 611 break; 612 case PT_Function: 613 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); 614 break; 615 case PT_CallGraphSCC: 616 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); 617 break; 618 default: 619 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); 620 break; 621 } 622 } 623 } 624 625 if (PrintEachXForm) 626 Passes.add( 627 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 628 } 629 630 if (StandardLinkOpts) { 631 AddStandardLinkPasses(Passes); 632 StandardLinkOpts = false; 633 } 634 635 if (OptLevelO0) 636 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 637 638 if (OptLevelO1) 639 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 640 641 if (OptLevelO2) 642 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 643 644 if (OptLevelOs) 645 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 646 647 if (OptLevelOz) 648 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 649 650 if (OptLevelO3) 651 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 652 653 if (FPasses) { 654 FPasses->doInitialization(); 655 for (Function &F : *M) 656 FPasses->run(F); 657 FPasses->doFinalization(); 658 } 659 660 // Check that the module is well formed on completion of optimization 661 if (!NoVerify && !VerifyEach) 662 Passes.add(createVerifierPass()); 663 664 // In run twice mode, we want to make sure the output is bit-by-bit 665 // equivalent if we run the pass manager again, so setup two buffers and 666 // a stream to write to them. Note that llc does something similar and it 667 // may be worth to abstract this out in the future. 668 SmallVector<char, 0> Buffer; 669 SmallVector<char, 0> CompileTwiceBuffer; 670 std::unique_ptr<raw_svector_ostream> BOS; 671 raw_ostream *OS = nullptr; 672 673 // Write bitcode or assembly to the output as the last step... 674 if (!NoOutput && !AnalyzeOnly) { 675 assert(Out); 676 OS = &Out->os(); 677 if (RunTwice) { 678 BOS = make_unique<raw_svector_ostream>(Buffer); 679 OS = BOS.get(); 680 } 681 if (OutputAssembly) { 682 if (EmitSummaryIndex) 683 report_fatal_error("Text output is incompatible with -module-summary"); 684 if (EmitModuleHash) 685 report_fatal_error("Text output is incompatible with -module-hash"); 686 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 687 } else 688 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 689 EmitSummaryIndex, EmitModuleHash)); 690 } 691 692 // Before executing passes, print the final values of the LLVM options. 693 cl::PrintOptionValues(); 694 695 // If requested, run all passes again with the same pass manager to catch 696 // bugs caused by persistent state in the passes 697 if (RunTwice) { 698 std::unique_ptr<Module> M2(CloneModule(M.get())); 699 Passes.run(*M2); 700 CompileTwiceBuffer = Buffer; 701 Buffer.clear(); 702 } 703 704 // Now that we have all of the passes ready, run them. 705 Passes.run(*M); 706 707 // Compare the two outputs and make sure they're the same 708 if (RunTwice) { 709 assert(Out); 710 if (Buffer.size() != CompileTwiceBuffer.size() || 711 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) != 712 0)) { 713 errs() << "Running the pass manager twice changed the output.\n" 714 "Writing the result of the second run to the specified output.\n" 715 "To generate the one-run comparison binary, just run without\n" 716 "the compile-twice option\n"; 717 Out->os() << BOS->str(); 718 Out->keep(); 719 return 1; 720 } 721 Out->os() << BOS->str(); 722 } 723 724 // Declare success. 725 if (!NoOutput || PrintBreakpoints) 726 Out->keep(); 727 728 return 0; 729 } 730