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 = {"safe-stack", 513 "cost-model", 514 "codegenprepare", 515 "interleaved-load-combine", 516 "unreachableblockelim", 517 "verify-safepoint-ir", 518 "atomic-expand", 519 "hardware-loops", 520 "type-promotion", 521 "mve-tail-predication", 522 "interleaved-access", 523 "global-merge", 524 "pre-isel-intrinsic-lowering", 525 "expand-reductions", 526 "indirectbr-expand", 527 "generic-to-nvvm", 528 "expandmemcmp", 529 "loop-reduce", 530 "lower-amx-type", 531 "pre-amx-config", 532 "lower-amx-intrinsics", 533 "polyhedral-info", 534 "replace-with-veclib"}; 535 for (const auto &P : PassNamePrefix) 536 if (Pass.startswith(P)) 537 return true; 538 for (const auto &P : PassNameContain) 539 if (Pass.contains(P)) 540 return true; 541 return llvm::is_contained(PassNameExact, Pass); 542 } 543 544 // For use in NPM transition. 545 static bool shouldForceLegacyPM() { 546 for (const auto &P : PassList) { 547 StringRef Arg = P->getPassArgument(); 548 if (shouldPinPassToLegacyPM(Arg)) 549 return true; 550 } 551 return false; 552 } 553 554 //===----------------------------------------------------------------------===// 555 // main for opt 556 // 557 int main(int argc, char **argv) { 558 InitLLVM X(argc, argv); 559 560 // Enable debug stream buffering. 561 EnableDebugBuffering = true; 562 563 LLVMContext Context; 564 565 InitializeAllTargets(); 566 InitializeAllTargetMCs(); 567 InitializeAllAsmPrinters(); 568 InitializeAllAsmParsers(); 569 570 // Initialize passes 571 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 572 initializeCore(Registry); 573 initializeCoroutines(Registry); 574 initializeScalarOpts(Registry); 575 initializeObjCARCOpts(Registry); 576 initializeVectorization(Registry); 577 initializeIPO(Registry); 578 initializeAnalysis(Registry); 579 initializeTransformUtils(Registry); 580 initializeInstCombine(Registry); 581 initializeAggressiveInstCombine(Registry); 582 initializeInstrumentation(Registry); 583 initializeTarget(Registry); 584 // For codegen passes, only passes that do IR to IR transformation are 585 // supported. 586 initializeExpandMemCmpPassPass(Registry); 587 initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry); 588 initializeCodeGenPreparePass(Registry); 589 initializeAtomicExpandPass(Registry); 590 initializeRewriteSymbolsLegacyPassPass(Registry); 591 initializeWinEHPreparePass(Registry); 592 initializeDwarfEHPrepareLegacyPassPass(Registry); 593 initializeSafeStackLegacyPassPass(Registry); 594 initializeSjLjEHPreparePass(Registry); 595 initializePreISelIntrinsicLoweringLegacyPassPass(Registry); 596 initializeGlobalMergePass(Registry); 597 initializeIndirectBrExpandPassPass(Registry); 598 initializeInterleavedLoadCombinePass(Registry); 599 initializeInterleavedAccessPass(Registry); 600 initializeEntryExitInstrumenterPass(Registry); 601 initializePostInlineEntryExitInstrumenterPass(Registry); 602 initializeUnreachableBlockElimLegacyPassPass(Registry); 603 initializeExpandReductionsPass(Registry); 604 initializeWasmEHPreparePass(Registry); 605 initializeWriteBitcodePassPass(Registry); 606 initializeHardwareLoopsPass(Registry); 607 initializeTypePromotionPass(Registry); 608 initializeReplaceWithVeclibLegacyPass(Registry); 609 610 #ifdef BUILD_EXAMPLES 611 initializeExampleIRTransforms(Registry); 612 #endif 613 614 cl::ParseCommandLineOptions(argc, argv, 615 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 616 617 if (AnalyzeOnly && NoOutput) { 618 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 619 return 1; 620 } 621 622 // FIXME: once the legacy PM code is deleted, move runPassPipeline() here and 623 // construct the PassBuilder before parsing IR so we can reuse the same 624 // PassBuilder for print passes. 625 if (PrintPasses) { 626 printPasses(outs()); 627 return 0; 628 } 629 630 TimeTracerRAII TimeTracer(argv[0]); 631 632 SMDiagnostic Err; 633 634 Context.setDiscardValueNames(DiscardValueNames); 635 if (!DisableDITypeMap) 636 Context.enableDebugTypeODRUniquing(); 637 638 Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr = 639 setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses, 640 RemarksFormat, RemarksWithHotness, 641 RemarksHotnessThreshold); 642 if (Error E = RemarksFileOrErr.takeError()) { 643 errs() << toString(std::move(E)) << '\n'; 644 return 1; 645 } 646 std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr); 647 648 // Load the input module... 649 auto SetDataLayout = [](StringRef) -> Optional<std::string> { 650 if (ClDataLayout.empty()) 651 return None; 652 return ClDataLayout; 653 }; 654 std::unique_ptr<Module> M; 655 if (NoUpgradeDebugInfo) 656 M = parseAssemblyFileWithIndexNoUpgradeDebugInfo( 657 InputFilename, Err, Context, nullptr, SetDataLayout) 658 .Mod; 659 else 660 M = parseIRFile(InputFilename, Err, Context, SetDataLayout); 661 662 if (!M) { 663 Err.print(argv[0], errs()); 664 return 1; 665 } 666 667 // Strip debug info before running the verifier. 668 if (StripDebug) 669 StripDebugInfo(*M); 670 671 // Erase module-level named metadata, if requested. 672 if (StripNamedMetadata) { 673 while (!M->named_metadata_empty()) { 674 NamedMDNode *NMD = &*M->named_metadata_begin(); 675 M->eraseNamedMetadata(NMD); 676 } 677 } 678 679 // If we are supposed to override the target triple or data layout, do so now. 680 if (!TargetTriple.empty()) 681 M->setTargetTriple(Triple::normalize(TargetTriple)); 682 683 // Immediately run the verifier to catch any problems before starting up the 684 // pass pipelines. Otherwise we can crash on broken code during 685 // doInitialization(). 686 if (!NoVerify && verifyModule(*M, &errs())) { 687 errs() << argv[0] << ": " << InputFilename 688 << ": error: input module is broken!\n"; 689 return 1; 690 } 691 692 // Enable testing of whole program devirtualization on this module by invoking 693 // the facility for updating public visibility to linkage unit visibility when 694 // specified by an internal option. This is normally done during LTO which is 695 // not performed via opt. 696 updateVCallVisibilityInModule(*M, 697 /* WholeProgramVisibilityEnabledInLTO */ false, 698 /* DynamicExportSymbols */ {}); 699 700 // Figure out what stream we are supposed to write to... 701 std::unique_ptr<ToolOutputFile> Out; 702 std::unique_ptr<ToolOutputFile> ThinLinkOut; 703 if (NoOutput) { 704 if (!OutputFilename.empty()) 705 errs() << "WARNING: The -o (output filename) option is ignored when\n" 706 "the --disable-output option is used.\n"; 707 } else { 708 // Default to standard output. 709 if (OutputFilename.empty()) 710 OutputFilename = "-"; 711 712 std::error_code EC; 713 sys::fs::OpenFlags Flags = 714 OutputAssembly ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None; 715 Out.reset(new ToolOutputFile(OutputFilename, EC, Flags)); 716 if (EC) { 717 errs() << EC.message() << '\n'; 718 return 1; 719 } 720 721 if (!ThinLinkBitcodeFile.empty()) { 722 ThinLinkOut.reset( 723 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None)); 724 if (EC) { 725 errs() << EC.message() << '\n'; 726 return 1; 727 } 728 } 729 } 730 731 Triple ModuleTriple(M->getTargetTriple()); 732 std::string CPUStr, FeaturesStr; 733 TargetMachine *Machine = nullptr; 734 const TargetOptions Options = 735 codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple); 736 737 if (ModuleTriple.getArch()) { 738 CPUStr = codegen::getCPUStr(); 739 FeaturesStr = codegen::getFeaturesStr(); 740 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options); 741 } else if (ModuleTriple.getArchName() != "unknown" && 742 ModuleTriple.getArchName() != "") { 743 errs() << argv[0] << ": unrecognized architecture '" 744 << ModuleTriple.getArchName() << "' provided.\n"; 745 return 1; 746 } 747 748 std::unique_ptr<TargetMachine> TM(Machine); 749 750 // Override function attributes based on CPUStr, FeaturesStr, and command line 751 // flags. 752 codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M); 753 754 // If the output is set to be emitted to standard out, and standard out is a 755 // console, print out a warning message and refuse to do it. We don't 756 // impress anyone by spewing tons of binary goo to a terminal. 757 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 758 if (CheckBitcodeOutputToConsole(Out->os())) 759 NoOutput = true; 760 761 if (OutputThinLTOBC) 762 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit); 763 764 // Add an appropriate TargetLibraryInfo pass for the module's triple. 765 TargetLibraryInfoImpl TLII(ModuleTriple); 766 767 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 768 if (DisableSimplifyLibCalls) 769 TLII.disableAllFunctions(); 770 else { 771 // Disable individual builtin functions in TargetLibraryInfo. 772 LibFunc F; 773 for (auto &FuncName : DisableBuiltins) 774 if (TLII.getLibFunc(FuncName, F)) 775 TLII.setUnavailable(F); 776 else { 777 errs() << argv[0] << ": cannot disable nonexistent builtin function " 778 << FuncName << '\n'; 779 return 1; 780 } 781 } 782 783 // If `-passes=` is specified, use NPM. 784 // If `-enable-new-pm` is specified and there are no codegen passes, use NPM. 785 // e.g. `-enable-new-pm -sroa` will use NPM. 786 // but `-enable-new-pm -codegenprepare` will still revert to legacy PM. 787 if ((EnableNewPassManager && !shouldForceLegacyPM()) || 788 PassPipeline.getNumOccurrences() > 0) { 789 if (AnalyzeOnly) { 790 errs() << "Cannot specify -analyze under new pass manager, either " 791 "specify '-enable-new-pm=0', or use the corresponding new pass " 792 "manager pass, e.g. '-passes=print<scalar-evolution>'. For a " 793 "full list of passes, see the '--print-passes' flag.\n"; 794 return 1; 795 } 796 if (legacy::debugPassSpecified()) { 797 errs() 798 << "-debug-pass does not work with the new PM, either use " 799 "-debug-pass-manager, or use the legacy PM (-enable-new-pm=0)\n"; 800 return 1; 801 } 802 if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) { 803 errs() 804 << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n"; 805 return 1; 806 } 807 SmallVector<StringRef, 4> Passes; 808 if (OptLevelO0) 809 Passes.push_back("default<O0>"); 810 if (OptLevelO1) 811 Passes.push_back("default<O1>"); 812 if (OptLevelO2) 813 Passes.push_back("default<O2>"); 814 if (OptLevelO3) 815 Passes.push_back("default<O3>"); 816 if (OptLevelOs) 817 Passes.push_back("default<Os>"); 818 if (OptLevelOz) 819 Passes.push_back("default<Oz>"); 820 for (const auto &P : PassList) 821 Passes.push_back(P->getPassArgument()); 822 OutputKind OK = OK_NoOutput; 823 if (!NoOutput) 824 OK = OutputAssembly 825 ? OK_OutputAssembly 826 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode); 827 828 VerifierKind VK = VK_VerifyInAndOut; 829 if (NoVerify) 830 VK = VK_NoVerifier; 831 else if (VerifyEach) 832 VK = VK_VerifyEachPass; 833 834 // The user has asked to use the new pass manager and provided a pipeline 835 // string. Hand off the rest of the functionality to the new code for that 836 // layer. 837 return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(), 838 ThinLinkOut.get(), RemarksFile.get(), PassPipeline, 839 Passes, OK, VK, PreserveAssemblyUseListOrder, 840 PreserveBitcodeUseListOrder, EmitSummaryIndex, 841 EmitModuleHash, EnableDebugify, Coroutines) 842 ? 0 843 : 1; 844 } 845 846 // Create a PassManager to hold and optimize the collection of passes we are 847 // about to build. If the -debugify-each option is set, wrap each pass with 848 // the (-check)-debugify passes. 849 DebugifyCustomPassManager Passes; 850 DebugifyStatsMap DIStatsMap; 851 DebugInfoPerPassMap DIPreservationMap; 852 if (DebugifyEach) { 853 Passes.setDebugifyMode(DebugifyMode::SyntheticDebugInfo); 854 Passes.setDIStatsMap(DIStatsMap); 855 } else if (VerifyEachDebugInfoPreserve) { 856 Passes.setDebugifyMode(DebugifyMode::OriginalDebugInfo); 857 Passes.setDIPreservationMap(DIPreservationMap); 858 if (!VerifyDIPreserveExport.empty()) 859 Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport); 860 } 861 862 bool AddOneTimeDebugifyPasses = 863 (EnableDebugify && !DebugifyEach) || 864 (VerifyDebugInfoPreserve && !VerifyEachDebugInfoPreserve); 865 866 Passes.add(new TargetLibraryInfoWrapperPass(TLII)); 867 868 // Add internal analysis passes from the target machine. 869 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis() 870 : TargetIRAnalysis())); 871 872 if (AddOneTimeDebugifyPasses) { 873 if (EnableDebugify) { 874 Passes.setDIStatsMap(DIStatsMap); 875 Passes.add(createDebugifyModulePass()); 876 } else if (VerifyDebugInfoPreserve) { 877 Passes.setDIPreservationMap(DIPreservationMap); 878 Passes.add(createDebugifyModulePass( 879 DebugifyMode::OriginalDebugInfo, "", 880 &(Passes.getDebugInfoPerPassMap()))); 881 } 882 } 883 884 std::unique_ptr<legacy::FunctionPassManager> FPasses; 885 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || 886 OptLevelO3) { 887 FPasses.reset(new legacy::FunctionPassManager(M.get())); 888 FPasses->add(createTargetTransformInfoWrapperPass( 889 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis())); 890 } 891 892 if (PrintBreakpoints) { 893 // Default to standard output. 894 if (!Out) { 895 if (OutputFilename.empty()) 896 OutputFilename = "-"; 897 898 std::error_code EC; 899 Out = std::make_unique<ToolOutputFile>(OutputFilename, EC, 900 sys::fs::OF_None); 901 if (EC) { 902 errs() << EC.message() << '\n'; 903 return 1; 904 } 905 } 906 Passes.add(createBreakpointPrinter(Out->os())); 907 NoOutput = true; 908 } 909 910 if (TM) { 911 // FIXME: We should dyn_cast this when supported. 912 auto <M = static_cast<LLVMTargetMachine &>(*TM); 913 Pass *TPC = LTM.createPassConfig(Passes); 914 Passes.add(TPC); 915 } 916 917 // Create a new optimization pass for each one specified on the command line 918 for (unsigned i = 0; i < PassList.size(); ++i) { 919 if (StandardLinkOpts && 920 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 921 AddStandardLinkPasses(Passes); 922 StandardLinkOpts = false; 923 } 924 925 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) { 926 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 927 OptLevelO0 = false; 928 } 929 930 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 931 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 932 OptLevelO1 = false; 933 } 934 935 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 936 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 937 OptLevelO2 = false; 938 } 939 940 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 941 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 942 OptLevelOs = false; 943 } 944 945 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 946 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 947 OptLevelOz = false; 948 } 949 950 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 951 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 952 OptLevelO3 = false; 953 } 954 955 const PassInfo *PassInf = PassList[i]; 956 Pass *P = nullptr; 957 if (PassInf->getNormalCtor()) 958 P = PassInf->getNormalCtor()(); 959 else 960 errs() << argv[0] << ": cannot create pass: " 961 << PassInf->getPassName() << "\n"; 962 if (P) { 963 PassKind Kind = P->getPassKind(); 964 addPass(Passes, P); 965 966 if (AnalyzeOnly) { 967 switch (Kind) { 968 case PT_Region: 969 Passes.add(createRegionPassPrinter(PassInf, Out->os())); 970 break; 971 case PT_Loop: 972 Passes.add(createLoopPassPrinter(PassInf, Out->os())); 973 break; 974 case PT_Function: 975 Passes.add(createFunctionPassPrinter(PassInf, Out->os())); 976 break; 977 case PT_CallGraphSCC: 978 Passes.add(createCallGraphPassPrinter(PassInf, Out->os())); 979 break; 980 default: 981 Passes.add(createModulePassPrinter(PassInf, Out->os())); 982 break; 983 } 984 } 985 } 986 987 if (PrintEachXForm) 988 Passes.add( 989 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder)); 990 } 991 992 if (StandardLinkOpts) { 993 AddStandardLinkPasses(Passes); 994 StandardLinkOpts = false; 995 } 996 997 if (OptLevelO0) 998 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0); 999 1000 if (OptLevelO1) 1001 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0); 1002 1003 if (OptLevelO2) 1004 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0); 1005 1006 if (OptLevelOs) 1007 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1); 1008 1009 if (OptLevelOz) 1010 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2); 1011 1012 if (OptLevelO3) 1013 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0); 1014 1015 if (FPasses) { 1016 FPasses->doInitialization(); 1017 for (Function &F : *M) 1018 FPasses->run(F); 1019 FPasses->doFinalization(); 1020 } 1021 1022 // Check that the module is well formed on completion of optimization 1023 if (!NoVerify && !VerifyEach) 1024 Passes.add(createVerifierPass()); 1025 1026 if (AddOneTimeDebugifyPasses) { 1027 if (EnableDebugify) 1028 Passes.add(createCheckDebugifyModulePass(false)); 1029 else if (VerifyDebugInfoPreserve) { 1030 if (!VerifyDIPreserveExport.empty()) 1031 Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport); 1032 Passes.add(createCheckDebugifyModulePass( 1033 false, "", nullptr, DebugifyMode::OriginalDebugInfo, 1034 &(Passes.getDebugInfoPerPassMap()), VerifyDIPreserveExport)); 1035 } 1036 } 1037 1038 // In run twice mode, we want to make sure the output is bit-by-bit 1039 // equivalent if we run the pass manager again, so setup two buffers and 1040 // a stream to write to them. Note that llc does something similar and it 1041 // may be worth to abstract this out in the future. 1042 SmallVector<char, 0> Buffer; 1043 SmallVector<char, 0> FirstRunBuffer; 1044 std::unique_ptr<raw_svector_ostream> BOS; 1045 raw_ostream *OS = nullptr; 1046 1047 const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly; 1048 1049 // Write bitcode or assembly to the output as the last step... 1050 if (ShouldEmitOutput || RunTwice) { 1051 assert(Out); 1052 OS = &Out->os(); 1053 if (RunTwice) { 1054 BOS = std::make_unique<raw_svector_ostream>(Buffer); 1055 OS = BOS.get(); 1056 } 1057 if (OutputAssembly) { 1058 if (EmitSummaryIndex) 1059 report_fatal_error("Text output is incompatible with -module-summary"); 1060 if (EmitModuleHash) 1061 report_fatal_error("Text output is incompatible with -module-hash"); 1062 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder)); 1063 } else if (OutputThinLTOBC) 1064 Passes.add(createWriteThinLTOBitcodePass( 1065 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr)); 1066 else 1067 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder, 1068 EmitSummaryIndex, EmitModuleHash)); 1069 } 1070 1071 // Before executing passes, print the final values of the LLVM options. 1072 cl::PrintOptionValues(); 1073 1074 if (!RunTwice) { 1075 // Now that we have all of the passes ready, run them. 1076 Passes.run(*M); 1077 } else { 1078 // If requested, run all passes twice with the same pass manager to catch 1079 // bugs caused by persistent state in the passes. 1080 std::unique_ptr<Module> M2(CloneModule(*M)); 1081 // Run all passes on the original module first, so the second run processes 1082 // the clone to catch CloneModule bugs. 1083 Passes.run(*M); 1084 FirstRunBuffer = Buffer; 1085 Buffer.clear(); 1086 1087 Passes.run(*M2); 1088 1089 // Compare the two outputs and make sure they're the same 1090 assert(Out); 1091 if (Buffer.size() != FirstRunBuffer.size() || 1092 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) { 1093 errs() 1094 << "Running the pass manager twice changed the output.\n" 1095 "Writing the result of the second run to the specified output.\n" 1096 "To generate the one-run comparison binary, just run without\n" 1097 "the compile-twice option\n"; 1098 if (ShouldEmitOutput) { 1099 Out->os() << BOS->str(); 1100 Out->keep(); 1101 } 1102 if (RemarksFile) 1103 RemarksFile->keep(); 1104 return 1; 1105 } 1106 if (ShouldEmitOutput) 1107 Out->os() << BOS->str(); 1108 } 1109 1110 if (DebugifyEach && !DebugifyExport.empty()) 1111 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap()); 1112 1113 // Declare success. 1114 if (!NoOutput || PrintBreakpoints) 1115 Out->keep(); 1116 1117 if (RemarksFile) 1118 RemarksFile->keep(); 1119 1120 if (ThinLinkOut) 1121 ThinLinkOut->keep(); 1122 1123 return 0; 1124 } 1125