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