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