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