1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Optimizations may be specified an arbitrary number of times on the command 10 // line, They are run in the order specified. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "BreakpointPrinter.h" 15 #include "NewPMDriver.h" 16 #include "PassPrinters.h" 17 #include "llvm/ADT/Triple.h" 18 #include "llvm/Analysis/CallGraph.h" 19 #include "llvm/Analysis/CallGraphSCCPass.h" 20 #include "llvm/Analysis/LoopPass.h" 21 #include "llvm/Analysis/RegionPass.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/AsmParser/Parser.h" 25 #include "llvm/CodeGen/CommandFlags.h" 26 #include "llvm/CodeGen/TargetPassConfig.h" 27 #include "llvm/Config/llvm-config.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DebugInfo.h" 30 #include "llvm/IR/LLVMContext.h" 31 #include "llvm/IR/LLVMRemarkStreamer.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/InitLLVM.h" 45 #include "llvm/Support/PluginLoader.h" 46 #include "llvm/Support/SourceMgr.h" 47 #include "llvm/Support/SystemUtils.h" 48 #include "llvm/Support/TargetRegistry.h" 49 #include "llvm/Support/TargetSelect.h" 50 #include "llvm/Support/ToolOutputFile.h" 51 #include "llvm/Support/YAMLTraits.h" 52 #include "llvm/Target/TargetMachine.h" 53 #include "llvm/Transforms/Coroutines.h" 54 #include "llvm/Transforms/IPO/AlwaysInliner.h" 55 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 57 #include "llvm/Transforms/Utils/Cloning.h" 58 #include "llvm/Transforms/Utils/Debugify.h" 59 #include <algorithm> 60 #include <memory> 61 using namespace llvm; 62 using namespace opt_tool; 63 64 static codegen::RegisterCodeGenFlags CFG; 65 66 // The OptimizationList is automatically populated with registered Passes by the 67 // PassNameParser. 68 // 69 static cl::list<const PassInfo*, bool, PassNameParser> 70 PassList(cl::desc("Optimizations available:")); 71 72 static cl::opt<bool> EnableNewPassManager( 73 "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(false)); 74 75 // This flag specifies a textual description of the optimization pass pipeline 76 // to run over the module. This flag switches opt to use the new pass manager 77 // infrastructure, completely disabling all of the flags specific to the old 78 // pass management. 79 static cl::opt<std::string> PassPipeline( 80 "passes", 81 cl::desc("A textual description of the pass pipeline for optimizing"), 82 cl::Hidden); 83 84 // Other command line options... 85 // 86 static cl::opt<std::string> 87 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 88 cl::init("-"), cl::value_desc("filename")); 89 90 static cl::opt<std::string> 91 OutputFilename("o", cl::desc("Override output filename"), 92 cl::value_desc("filename")); 93 94 static cl::opt<bool> 95 Force("f", cl::desc("Enable binary output on terminals")); 96 97 static cl::opt<bool> 98 PrintEachXForm("p", cl::desc("Print module after each transformation")); 99 100 static cl::opt<bool> 101 NoOutput("disable-output", 102 cl::desc("Do not write result bitcode file"), cl::Hidden); 103 104 static cl::opt<bool> 105 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 106 107 static cl::opt<bool> 108 OutputThinLTOBC("thinlto-bc", 109 cl::desc("Write output as ThinLTO-ready bitcode")); 110 111 static cl::opt<bool> 112 SplitLTOUnit("thinlto-split-lto-unit", 113 cl::desc("Enable splitting of a ThinLTO LTOUnit")); 114 115 static cl::opt<std::string> ThinLinkBitcodeFile( 116 "thin-link-bitcode-file", cl::value_desc("filename"), 117 cl::desc( 118 "A file in which to write minimized bitcode for the thin link only")); 119 120 static cl::opt<bool> 121 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden); 122 123 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info", 124 cl::desc("Generate invalid output"), 125 cl::ReallyHidden); 126 127 static cl::opt<bool> VerifyEach("verify-each", 128 cl::desc("Verify after each transform")); 129 130 static cl::opt<bool> 131 DisableDITypeMap("disable-debug-info-type-map", 132 cl::desc("Don't use a uniquing type map for debug info")); 133 134 static cl::opt<bool> 135 StripDebug("strip-debug", 136 cl::desc("Strip debugger symbol info from translation unit")); 137 138 static cl::opt<bool> 139 StripNamedMetadata("strip-named-metadata", 140 cl::desc("Strip module-level named metadata")); 141 142 static cl::opt<bool> DisableInline("disable-inlining", 143 cl::desc("Do not run the inliner pass")); 144 145 static cl::opt<bool> 146 DisableOptimizations("disable-opt", 147 cl::desc("Do not run any optimization passes")); 148 149 static cl::opt<bool> 150 StandardLinkOpts("std-link-opts", 151 cl::desc("Include the standard link time optimizations")); 152 153 static cl::opt<bool> 154 OptLevelO0("O0", 155 cl::desc("Optimization level 0. Similar to clang -O0")); 156 157 static cl::opt<bool> 158 OptLevelO1("O1", 159 cl::desc("Optimization level 1. Similar to clang -O1")); 160 161 static cl::opt<bool> 162 OptLevelO2("O2", 163 cl::desc("Optimization level 2. Similar to clang -O2")); 164 165 static cl::opt<bool> 166 OptLevelOs("Os", 167 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 168 169 static cl::opt<bool> 170 OptLevelOz("Oz", 171 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 172 173 static cl::opt<bool> 174 OptLevelO3("O3", 175 cl::desc("Optimization level 3. Similar to clang -O3")); 176 177 static cl::opt<unsigned> 178 CodeGenOptLevel("codegen-opt-level", 179 cl::desc("Override optimization level for codegen hooks")); 180 181 static cl::opt<std::string> 182 TargetTriple("mtriple", cl::desc("Override target triple for module")); 183 184 cl::opt<bool> DisableLoopUnrolling( 185 "disable-loop-unrolling", 186 cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false)); 187 188 static cl::opt<bool> EmitSummaryIndex("module-summary", 189 cl::desc("Emit module summary index"), 190 cl::init(false)); 191 192 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"), 193 cl::init(false)); 194 195 static cl::opt<bool> 196 DisableSimplifyLibCalls("disable-simplify-libcalls", 197 cl::desc("Disable simplify-libcalls")); 198 199 static cl::list<std::string> 200 DisableBuiltins("disable-builtin", 201 cl::desc("Disable specific target library builtin function"), 202 cl::ZeroOrMore); 203 204 static cl::opt<bool> 205 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 206 207 static cl::opt<bool> EnableDebugify( 208 "enable-debugify", 209 cl::desc( 210 "Start the pipeline with debugify and end it with check-debugify")); 211 212 static cl::opt<bool> DebugifyEach( 213 "debugify-each", 214 cl::desc( 215 "Start each pass with debugify and end it with check-debugify")); 216 217 static cl::opt<std::string> 218 DebugifyExport("debugify-export", 219 cl::desc("Export per-pass debugify statistics to this file"), 220 cl::value_desc("filename"), cl::init("")); 221 222 static cl::opt<bool> 223 PrintBreakpoints("print-breakpoints-for-testing", 224 cl::desc("Print select breakpoints location for testing")); 225 226 static cl::opt<std::string> ClDataLayout("data-layout", 227 cl::desc("data layout string to use"), 228 cl::value_desc("layout-string"), 229 cl::init("")); 230 231 static cl::opt<bool> PreserveBitcodeUseListOrder( 232 "preserve-bc-uselistorder", 233 cl::desc("Preserve use-list order when writing LLVM bitcode."), 234 cl::init(true), cl::Hidden); 235 236 static cl::opt<bool> PreserveAssemblyUseListOrder( 237 "preserve-ll-uselistorder", 238 cl::desc("Preserve use-list order when writing LLVM assembly."), 239 cl::init(false), cl::Hidden); 240 241 static cl::opt<bool> 242 RunTwice("run-twice", 243 cl::desc("Run all passes twice, re-using the same pass manager."), 244 cl::init(false), cl::Hidden); 245 246 static cl::opt<bool> DiscardValueNames( 247 "discard-value-names", 248 cl::desc("Discard names from Value (other than GlobalValue)."), 249 cl::init(false), cl::Hidden); 250 251 static cl::opt<bool> Coroutines( 252 "enable-coroutines", 253 cl::desc("Enable coroutine passes."), 254 cl::init(false), cl::Hidden); 255 256 static cl::opt<bool> TimeTrace( 257 "time-trace", 258 cl::desc("Record time trace")); 259 260 static cl::opt<unsigned> TimeTraceGranularity( 261 "time-trace-granularity", 262 cl::desc("Minimum time granularity (in microseconds) traced by time profiler"), 263 cl::init(500), cl::Hidden); 264 265 static cl::opt<std::string> 266 TimeTraceFile("time-trace-file", 267 cl::desc("Specify time trace file destination"), 268 cl::value_desc("filename")); 269 270 static cl::opt<bool> RemarksWithHotness( 271 "pass-remarks-with-hotness", 272 cl::desc("With PGO, include profile count in optimization remarks"), 273 cl::Hidden); 274 275 static cl::opt<unsigned> 276 RemarksHotnessThreshold("pass-remarks-hotness-threshold", 277 cl::desc("Minimum profile count required for " 278 "an optimization remark to be output"), 279 cl::Hidden); 280 281 static cl::opt<std::string> 282 RemarksFilename("pass-remarks-output", 283 cl::desc("Output filename for pass remarks"), 284 cl::value_desc("filename")); 285 286 static cl::opt<std::string> 287 RemarksPasses("pass-remarks-filter", 288 cl::desc("Only record optimization remarks from passes whose " 289 "names match the given regular expression"), 290 cl::value_desc("regex")); 291 292 static cl::opt<std::string> RemarksFormat( 293 "pass-remarks-format", 294 cl::desc("The format used for serializing remarks (default: YAML)"), 295 cl::value_desc("format"), cl::init("yaml")); 296 297 cl::opt<PGOKind> 298 PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden, 299 cl::desc("The kind of profile guided optimization"), 300 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."), 301 clEnumValN(InstrGen, "pgo-instr-gen-pipeline", 302 "Instrument the IR to generate profile."), 303 clEnumValN(InstrUse, "pgo-instr-use-pipeline", 304 "Use instrumented profile to guide PGO."), 305 clEnumValN(SampleUse, "pgo-sample-use-pipeline", 306 "Use sampled profile to guide PGO."))); 307 cl::opt<std::string> ProfileFile("profile-file", 308 cl::desc("Path to the profile."), cl::Hidden); 309 310 cl::opt<CSPGOKind> CSPGOKindFlag( 311 "cspgo-kind", cl::init(NoCSPGO), cl::Hidden, 312 cl::desc("The kind of context sensitive profile guided optimization"), 313 cl::values( 314 clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."), 315 clEnumValN( 316 CSInstrGen, "cspgo-instr-gen-pipeline", 317 "Instrument (context sensitive) the IR to generate profile."), 318 clEnumValN( 319 CSInstrUse, "cspgo-instr-use-pipeline", 320 "Use instrumented (context sensitive) profile to guide PGO."))); 321 cl::opt<std::string> CSProfileGenFile( 322 "cs-profilegen-file", 323 cl::desc("Path to the instrumented context sensitive profile."), 324 cl::Hidden); 325 326 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) { 327 // Add the pass to the pass manager... 328 PM.add(P); 329 330 // If we are verifying all of the intermediate steps, add the verifier... 331 if (VerifyEach) 332 PM.add(createVerifierPass()); 333 } 334 335 /// This routine adds optimization passes based on selected optimization level, 336 /// OptLevel. 337 /// 338 /// OptLevel - Optimization Level 339 static void AddOptimizationPasses(legacy::PassManagerBase &MPM, 340 legacy::FunctionPassManager &FPM, 341 TargetMachine *TM, unsigned OptLevel, 342 unsigned SizeLevel) { 343 if (!NoVerify || VerifyEach) 344 FPM.add(createVerifierPass()); // Verify that input is correct 345 346 PassManagerBuilder Builder; 347 Builder.OptLevel = OptLevel; 348 Builder.SizeLevel = SizeLevel; 349 350 if (DisableInline) { 351 // No inlining pass 352 } else if (OptLevel > 1) { 353 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false); 354 } else { 355 Builder.Inliner = createAlwaysInlinerLegacyPass(); 356 } 357 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 358 DisableLoopUnrolling : OptLevel == 0; 359 360 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 361 362 Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2; 363 364 if (TM) 365 TM->adjustPassManager(Builder); 366 367 if (Coroutines) 368 addCoroutinePassesToExtensionPoints(Builder); 369 370 switch (PGOKindFlag) { 371 case InstrGen: 372 Builder.EnablePGOInstrGen = true; 373 Builder.PGOInstrGen = ProfileFile; 374 break; 375 case InstrUse: 376 Builder.PGOInstrUse = ProfileFile; 377 break; 378 case SampleUse: 379 Builder.PGOSampleUse = ProfileFile; 380 break; 381 default: 382 break; 383 } 384 385 switch (CSPGOKindFlag) { 386 case CSInstrGen: 387 Builder.EnablePGOCSInstrGen = true; 388 break; 389 case CSInstrUse: 390 Builder.EnablePGOCSInstrUse = true; 391 break; 392 default: 393 break; 394 } 395 396 Builder.populateFunctionPassManager(FPM); 397 Builder.populateModulePassManager(MPM); 398 } 399 400 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) { 401 PassManagerBuilder Builder; 402 Builder.VerifyInput = true; 403 if (DisableOptimizations) 404 Builder.OptLevel = 0; 405 406 if (!DisableInline) 407 Builder.Inliner = createFunctionInliningPass(); 408 Builder.populateLTOPassManager(PM); 409 } 410 411 //===----------------------------------------------------------------------===// 412 // CodeGen-related helper functions. 413 // 414 415 static CodeGenOpt::Level GetCodeGenOptLevel() { 416 if (CodeGenOptLevel.getNumOccurrences()) 417 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel)); 418 if (OptLevelO1) 419 return CodeGenOpt::Less; 420 if (OptLevelO2) 421 return CodeGenOpt::Default; 422 if (OptLevelO3) 423 return CodeGenOpt::Aggressive; 424 return CodeGenOpt::None; 425 } 426 427 // Returns the TargetMachine instance or zero if no triple is provided. 428 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr, 429 StringRef FeaturesStr, 430 const TargetOptions &Options) { 431 std::string Error; 432 const Target *TheTarget = 433 TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error); 434 // Some modules don't specify a triple, and this is okay. 435 if (!TheTarget) { 436 return nullptr; 437 } 438 439 return TheTarget->createTargetMachine( 440 TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(), 441 Options, codegen::getExplicitRelocModel(), 442 codegen::getExplicitCodeModel(), GetCodeGenOptLevel()); 443 } 444 445 #ifdef BUILD_EXAMPLES 446 void initializeExampleIRTransforms(llvm::PassRegistry &Registry); 447 #endif 448 449 450 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) { 451 std::error_code EC; 452 raw_fd_ostream OS{Path, EC}; 453 if (EC) { 454 errs() << "Could not open file: " << EC.message() << ", " << Path << '\n'; 455 return; 456 } 457 458 OS << "Pass Name" << ',' << "# of missing debug values" << ',' 459 << "# of missing locations" << ',' << "Missing/Expected value ratio" << ',' 460 << "Missing/Expected location ratio" << '\n'; 461 for (const auto &Entry : Map) { 462 StringRef Pass = Entry.first; 463 DebugifyStatistics Stats = Entry.second; 464 465 OS << Pass << ',' << Stats.NumDbgValuesMissing << ',' 466 << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ',' 467 << Stats.getEmptyLocationRatio() << '\n'; 468 } 469 } 470 471 struct TimeTracerRAII { 472 TimeTracerRAII(StringRef ProgramName) { 473 if (TimeTrace) 474 timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName); 475 } 476 ~TimeTracerRAII() { 477 if (TimeTrace) { 478 if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) { 479 handleAllErrors(std::move(E), [&](const StringError &SE) { 480 errs() << SE.getMessage() << "\n"; 481 }); 482 return; 483 } 484 timeTraceProfilerCleanup(); 485 } 486 } 487 }; 488 489 // For use in NPM transition. 490 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once 491 // it exists. 492 static bool IsCodegenPass(StringRef Pass) { 493 std::vector<StringRef> PassNamePrefix = { 494 "x86-", "xcore-", "wasm-", "systemz-", "ppc-", "nvvm-", 495 "nvptx-", "mips-", "lanai-", "hexagon-", "bpf-", "avr-", 496 "thumb2-", "arm-", "si-", "gcn-", "amdgpu-", "aarch64-"}; 497 std::vector<StringRef> PassNameContain = {"ehprepare"}; 498 std::vector<StringRef> PassNameExact = { 499 "safe-stack", "cost-model", 500 "codegenprepare", "interleaved-load-combine", 501 "unreachableblockelim", "sclaraized-masked-mem-intrin"}; 502 for (const auto &P : PassNamePrefix) 503 if (Pass.startswith(P)) 504 return true; 505 for (const auto &P : PassNameContain) 506 if (Pass.contains(P)) 507 return true; 508 for (const auto &P : PassNameExact) 509 if (Pass == P) 510 return true; 511 return false; 512 } 513 514 // For use in NPM transition. 515 static bool CodegenPassSpecifiedInPassList() { 516 for (const auto &P : PassList) { 517 StringRef Arg = P->getPassArgument(); 518 if (IsCodegenPass(Arg)) 519 return true; 520 } 521 return false; 522 } 523 524 //===----------------------------------------------------------------------===// 525 // main for opt 526 // 527 int main(int argc, char **argv) { 528 InitLLVM X(argc, argv); 529 530 // Enable debug stream buffering. 531 EnableDebugBuffering = true; 532 533 LLVMContext Context; 534 535 InitializeAllTargets(); 536 InitializeAllTargetMCs(); 537 InitializeAllAsmPrinters(); 538 InitializeAllAsmParsers(); 539 540 // Initialize passes 541 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 542 initializeCore(Registry); 543 initializeCoroutines(Registry); 544 initializeScalarOpts(Registry); 545 initializeObjCARCOpts(Registry); 546 initializeVectorization(Registry); 547 initializeIPO(Registry); 548 initializeAnalysis(Registry); 549 initializeTransformUtils(Registry); 550 initializeInstCombine(Registry); 551 initializeAggressiveInstCombine(Registry); 552 initializeInstrumentation(Registry); 553 initializeTarget(Registry); 554 // For codegen passes, only passes that do IR to IR transformation are 555 // supported. 556 initializeExpandMemCmpPassPass(Registry); 557 initializeScalarizeMaskedMemIntrinPass(Registry); 558 initializeCodeGenPreparePass(Registry); 559 initializeAtomicExpandPass(Registry); 560 initializeRewriteSymbolsLegacyPassPass(Registry); 561 initializeWinEHPreparePass(Registry); 562 initializeDwarfEHPreparePass(Registry); 563 initializeSafeStackLegacyPassPass(Registry); 564 initializeSjLjEHPreparePass(Registry); 565 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 566 initializeGlobalMergePass(Registry); 567 initializeIndirectBrExpandPassPass(Registry); 568 initializeInterleavedLoadCombinePass(Registry); 569 initializeInterleavedAccessPass(Registry); 570 initializeEntryExitInstrumenterPass(Registry); 571 initializePostInlineEntryExitInstrumenterPass(Registry); 572 initializeUnreachableBlockElimLegacyPassPass(Registry); 573 initializeExpandReductionsPass(Registry); 574 initializeWasmEHPreparePass(Registry); 575 initializeWriteBitcodePassPass(Registry); 576 initializeHardwareLoopsPass(Registry); 577 initializeTypePromotionPass(Registry); 578 579 #ifdef BUILD_EXAMPLES 580 initializeExampleIRTransforms(Registry); 581 #endif 582 583 cl::ParseCommandLineOptions(argc, argv, 584 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 585 586 if (AnalyzeOnly && NoOutput) { 587 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 588 return 1; 589 } 590 591 TimeTracerRAII TimeTracer(argv[0]); 592 593 SMDiagnostic Err; 594 595 Context.setDiscardValueNames(DiscardValueNames); 596 if (!DisableDITypeMap) 597 Context.enableDebugTypeODRUniquing(); 598 599 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 600 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 601 RemarksFormat, RemarksWithHotness, 602 RemarksHotnessThreshold); 603 if (Error E = RemarksFileOrErr.takeError()) { 604 errs() << toString(std::move(E)) << '\n'; 605 return 1; 606 } 607 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 608 609 // Load the input module... 610 auto SetDataLayout = [](StringRef) -> Optional<std::string> { 611 if (ClDataLayout.empty()) 612 return None; 613 return ClDataLayout; 614 }; 615 std::unique_ptr<Module> M; 616 if (NoUpgradeDebugInfo) 617 M = parseAssemblyFileWithIndexNoUpgradeDebugInfo( 618 InputFilename, Err, Context, nullptr, SetDataLayout) 619 .Mod; 620 else 621 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 622 623 if (!M) { 624 Err.print(argv[0], errs()); 625 return 1; 626 } 627 628 // Strip debug info before running the verifier. 629 if (StripDebug) 630 StripDebugInfo(*M); 631 632 // Erase module-level named metadata, if requested. 633 if (StripNamedMetadata) { 634 while (!M->named_metadata_empty()) { 635 NamedMDNode *NMD = &*M->named_metadata_begin(); 636 M->eraseNamedMetadata(NMD); 637 } 638 } 639 640 // If we are supposed to override the target triple or data layout, do so now. 641 if (!TargetTriple.empty()) 642 M->setTargetTriple(Triple::normalize(TargetTriple)); 643 644 // Immediately run the verifier to catch any problems before starting up the 645 // pass pipelines. Otherwise we can crash on broken code during 646 // doInitialization(). 647 if (!NoVerify && verifyModule(*M, &errs())) { 648 errs() << argv[0] << ": " << InputFilename 649 << ": error: input module is broken!\n"; 650 return 1; 651 } 652 653 // Enable testing of whole program devirtualization on this module by invoking 654 // the facility for updating public visibility to linkage unit visibility when 655 // specified by an internal option. This is normally done during LTO which is 656 // not performed via opt. 657 updateVCallVisibilityInModule(*M, 658 /* WholeProgramVisibilityEnabledInLTO */ false); 659 660 // Figure out what stream we are supposed to write to... 661 std::unique_ptr<ToolOutputFile> Out; 662 std::unique_ptr<ToolOutputFile> ThinLinkOut; 663 if (NoOutput) { 664 if (!OutputFilename.empty()) 665 errs() << "WARNING: The -o (output filename) option is ignored when\n" 666 "the --disable-output option is used.\n"; 667 } else { 668 // Default to standard output. 669 if (OutputFilename.empty()) 670 OutputFilename = "-"; 671 672 std::error_code EC; 673 sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text 674 : sys::fs::OF_None; 675 Out.reset(new ToolOutputFile(OutputFilename, EC, Flags)); 676 if (EC) { 677 errs() << EC.message() << '\n'; 678 return 1; 679 } 680 681 if (!ThinLinkBitcodeFile.empty()) { 682 ThinLinkOut.reset( 683 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None)); 684 if (EC) { 685 errs() << EC.message() << '\n'; 686 return 1; 687 } 688 } 689 } 690 691 Triple ModuleTriple(M->getTargetTriple()); 692 std::string CPUStr, FeaturesStr; 693 TargetMachine *Machine = nullptr; 694 const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(); 695 696 if (ModuleTriple.getArch()) { 697 CPUStr = codegen::getCPUStr(); 698 FeaturesStr = codegen::getFeaturesStr(); 699 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 700 } else if (ModuleTriple.getArchName() != "unknown" && 701 ModuleTriple.getArchName() != "") { 702 errs() << argv[0] << ": unrecognized architecture '" 703 << ModuleTriple.getArchName() << "' provided.\n"; 704 return 1; 705 } 706 707 std::unique_ptr<TargetMachine> TM(Machine); 708 709 // Override function attributes based on CPUStr, FeaturesStr, and command line 710 // flags. 711 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 712 713 // If the output is set to be emitted to standard out, and standard out is a 714 // console, print out a warning message and refuse to do it. We don't 715 // impress anyone by spewing tons of binary goo to a terminal. 716 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 717 if (CheckBitcodeOutputToConsole(Out->os())) 718 NoOutput = true; 719 720 if (OutputThinLTOBC) 721 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit); 722 723 // If `-passes=` is specified, use NPM. 724 // If `-enable-new-pm` is specified and there are no codegen passes, use NPM. 725 // e.g. `-enable-new-pm -sroa` will use NPM. 726 // but `-enable-new-pm -codegenprepare` will still revert to legacy PM. 727 if ((EnableNewPassManager && !CodegenPassSpecifiedInPassList()) || 728 PassPipeline.getNumOccurrences() > 0) { 729 if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) { 730 errs() 731 << "Cannot specify passes via both -foo-pass and --passes=foo-pass"; 732 return 1; 733 } 734 SmallVector<StringRef, 4> Passes; 735 for (const auto &P : PassList) { 736 Passes.push_back(P->getPassArgument()); 737 } 738 if (OptLevelO0) 739 Passes.push_back("default<O0>"); 740 if (OptLevelO1) 741 Passes.push_back("default<O1>"); 742 if (OptLevelO2) 743 Passes.push_back("default<O2>"); 744 if (OptLevelO3) 745 Passes.push_back("default<O3>"); 746 if (OptLevelOs) 747 Passes.push_back("default<Os>"); 748 if (OptLevelOz) 749 Passes.push_back("default<Oz>"); 750 OutputKind OK = OK_NoOutput; 751 if (!NoOutput) 752 OK = OutputAssembly 753 ? OK_OutputAssembly 754 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode); 755 756 VerifierKind VK = VK_VerifyInAndOut; 757 if (NoVerify) 758 VK = VK_NoVerifier; 759 else if (VerifyEach) 760 VK = VK_VerifyEachPass; 761 762 // The user has asked to use the new pass manager and provided a pipeline 763 // string. Hand off the rest of the functionality to the new code for that 764 // layer. 765 return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(), 766 RemarksFile.get(), PassPipeline, Passes, OK, VK, 767 PreserveAssemblyUseListOrder, 768 PreserveBitcodeUseListOrder, EmitSummaryIndex, 769 EmitModuleHash, EnableDebugify, Coroutines) 770 ? 0 771 : 1; 772 } 773 774 // Create a PassManager to hold and optimize the collection of passes we are 775 // about to build. If the -debugify-each option is set, wrap each pass with 776 // the (-check)-debugify passes. 777 DebugifyCustomPassManager Passes; 778 if (DebugifyEach) 779 Passes.enableDebugifyEach(); 780 781 bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach; 782 783 // Add an appropriate TargetLibraryInfo pass for the module's triple. 784 TargetLibraryInfoImpl TLII(ModuleTriple); 785 786 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 787 if (DisableSimplifyLibCalls) 788 TLII.disableAllFunctions(); 789 else { 790 // Disable individual builtin functions in TargetLibraryInfo. 791 LibFunc F; 792 for (auto &FuncName : DisableBuiltins) 793 if (TLII.getLibFunc(FuncName, F)) 794 TLII.setUnavailable(F); 795 else { 796 errs() << argv[0] << ": cannot disable nonexistent builtin function " 797 << FuncName << '\n'; 798 return 1; 799 } 800 } 801 802 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 803 804 // Add internal analysis passes from the target machine. 805 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 806 : TargetIRAnalysis())); 807 808 if (AddOneTimeDebugifyPasses) 809 Passes.add(createDebugifyModulePass()); 810 811 std::unique_ptr<legacy::FunctionPassManager> FPasses; 812 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 813 OptLevelO3) { 814 FPasses.reset(new legacy::FunctionPassManager(M.get())); 815 FPasses->add(createTargetTransformInfoWrapperPass( 816 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 817 } 818 819 if (PrintBreakpoints) { 820 // Default to standard output. 821 if (!Out) { 822 if (OutputFilename.empty()) 823 OutputFilename = "-"; 824 825 std::error_code EC; 826 Out = std::make_unique<ToolOutputFile>(OutputFilename, EC, 827 sys::fs::OF_None); 828 if (EC) { 829 errs() << EC.message() << '\n'; 830 return 1; 831 } 832 } 833 Passes.add(createBreakpointPrinter(Out->os())); 834 NoOutput = true; 835 } 836 837 if (TM) { 838 // FIXME: We should dyn_cast this when supported. 839 auto <M = static_cast<LLVMTargetMachine &>(*TM); 840 Pass *TPC = LTM.createPassConfig(Passes); 841 Passes.add(TPC); 842 } 843 844 // Create a new optimization pass for each one specified on the command line 845 for (unsigned i = 0; i < PassList.size(); ++i) { 846 if (StandardLinkOpts && 847 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 848 AddStandardLinkPasses(Passes); 849 StandardLinkOpts = false; 850 } 851 852 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 853 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 854 OptLevelO0 = false; 855 } 856 857 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 858 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 859 OptLevelO1 = false; 860 } 861 862 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 863 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 864 OptLevelO2 = false; 865 } 866 867 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 868 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 869 OptLevelOs = false; 870 } 871 872 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 873 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 874 OptLevelOz = false; 875 } 876 877 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 878 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 879 OptLevelO3 = false; 880 } 881 882 const PassInfo *PassInf = PassList[i]; 883 Pass *P = nullptr; 884 if (PassInf->getNormalCtor()) 885 P = PassInf->getNormalCtor()(); 886 else 887 errs() << argv[0] << ": cannot create pass: " 888 << PassInf->getPassName() << "\n"; 889 if (P) { 890 PassKind Kind = P->getPassKind(); 891 addPass(Passes, P); 892 893 if (AnalyzeOnly) { 894 switch (Kind) { 895 case PT_Region: 896 Passes.add(createRegionPassPrinter(PassInf, Out->os())); 897 break; 898 case PT_Loop: 899 Passes.add(createLoopPassPrinter(PassInf, Out->os())); 900 break; 901 case PT_Function: 902 Passes.add(createFunctionPassPrinter(PassInf, Out->os())); 903 break; 904 case PT_CallGraphSCC: 905 Passes.add(createCallGraphPassPrinter(PassInf, Out->os())); 906 break; 907 default: 908 Passes.add(createModulePassPrinter(PassInf, Out->os())); 909 break; 910 } 911 } 912 } 913 914 if (PrintEachXForm) 915 Passes.add( 916 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 917 } 918 919 if (StandardLinkOpts) { 920 AddStandardLinkPasses(Passes); 921 StandardLinkOpts = false; 922 } 923 924 if (OptLevelO0) 925 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 926 927 if (OptLevelO1) 928 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 929 930 if (OptLevelO2) 931 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 932 933 if (OptLevelOs) 934 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 935 936 if (OptLevelOz) 937 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 938 939 if (OptLevelO3) 940 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 941 942 if (FPasses) { 943 FPasses->doInitialization(); 944 for (Function &F : *M) 945 FPasses->run(F); 946 FPasses->doFinalization(); 947 } 948 949 // Check that the module is well formed on completion of optimization 950 if (!NoVerify && !VerifyEach) 951 Passes.add(createVerifierPass()); 952 953 if (AddOneTimeDebugifyPasses) 954 Passes.add(createCheckDebugifyModulePass(false)); 955 956 // In run twice mode, we want to make sure the output is bit-by-bit 957 // equivalent if we run the pass manager again, so setup two buffers and 958 // a stream to write to them. Note that llc does something similar and it 959 // may be worth to abstract this out in the future. 960 SmallVector<char, 0> Buffer; 961 SmallVector<char, 0> FirstRunBuffer; 962 std::unique_ptr<raw_svector_ostream> BOS; 963 raw_ostream *OS = nullptr; 964 965 const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly; 966 967 // Write bitcode or assembly to the output as the last step... 968 if (ShouldEmitOutput || RunTwice) { 969 assert(Out); 970 OS = &Out->os(); 971 if (RunTwice) { 972 BOS = std::make_unique<raw_svector_ostream>(Buffer); 973 OS = BOS.get(); 974 } 975 if (OutputAssembly) { 976 if (EmitSummaryIndex) 977 report_fatal_error("Text output is incompatible with -module-summary"); 978 if (EmitModuleHash) 979 report_fatal_error("Text output is incompatible with -module-hash"); 980 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 981 } else if (OutputThinLTOBC) 982 Passes.add(createWriteThinLTOBitcodePass( 983 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr)); 984 else 985 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 986 EmitSummaryIndex, EmitModuleHash)); 987 } 988 989 // Before executing passes, print the final values of the LLVM options. 990 cl::PrintOptionValues(); 991 992 if (!RunTwice) { 993 // Now that we have all of the passes ready, run them. 994 Passes.run(*M); 995 } else { 996 // If requested, run all passes twice with the same pass manager to catch 997 // bugs caused by persistent state in the passes. 998 std::unique_ptr<Module> M2(CloneModule(*M)); 999 // Run all passes on the original module first, so the second run processes 1000 // the clone to catch CloneModule bugs. 1001 Passes.run(*M); 1002 FirstRunBuffer = Buffer; 1003 Buffer.clear(); 1004 1005 Passes.run(*M2); 1006 1007 // Compare the two outputs and make sure they're the same 1008 assert(Out); 1009 if (Buffer.size() != FirstRunBuffer.size() || 1010 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) { 1011 errs() 1012 << "Running the pass manager twice changed the output.\n" 1013 "Writing the result of the second run to the specified output.\n" 1014 "To generate the one-run comparison binary, just run without\n" 1015 "the compile-twice option\n"; 1016 if (ShouldEmitOutput) { 1017 Out->os() << BOS->str(); 1018 Out->keep(); 1019 } 1020 if (RemarksFile) 1021 RemarksFile->keep(); 1022 return 1; 1023 } 1024 if (ShouldEmitOutput) 1025 Out->os() << BOS->str(); 1026 } 1027 1028 if (DebugifyEach && !DebugifyExport.empty()) 1029 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap()); 1030 1031 // Declare success. 1032 if (!NoOutput || PrintBreakpoints) 1033 Out->keep(); 1034 1035 if (RemarksFile) 1036 RemarksFile->keep(); 1037 1038 if (ThinLinkOut) 1039 ThinLinkOut->keep(); 1040 1041 return 0; 1042 } 1043