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