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