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