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