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