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