1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Optimizations may be specified an arbitrary number of times on the command 11 // line, They are run in the order specified. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "BreakpointPrinter.h" 16 #include "NewPMDriver.h" 17 #include "PassPrinters.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Analysis/CallGraph.h" 20 #include "llvm/Analysis/CallGraphSCCPass.h" 21 #include "llvm/Analysis/LoopPass.h" 22 #include "llvm/Analysis/RegionPass.h" 23 #include "llvm/Bitcode/BitcodeWriterPass.h" 24 #include "llvm/CodeGen/CommandFlags.h" 25 #include "llvm/IR/DataLayout.h" 26 #include "llvm/IR/IRPrintingPasses.h" 27 #include "llvm/IR/LLVMContext.h" 28 #include "llvm/IR/LegacyPassNameParser.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/IRReader/IRReader.h" 32 #include "llvm/InitializePasses.h" 33 #include "llvm/LinkAllIR.h" 34 #include "llvm/LinkAllPasses.h" 35 #include "llvm/MC/SubtargetFeature.h" 36 #include "llvm/PassManager.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/FileSystem.h" 39 #include "llvm/Support/ManagedStatic.h" 40 #include "llvm/Support/PluginLoader.h" 41 #include "llvm/Support/PrettyStackTrace.h" 42 #include "llvm/Support/Signals.h" 43 #include "llvm/Support/SourceMgr.h" 44 #include "llvm/Support/SystemUtils.h" 45 #include "llvm/Support/TargetRegistry.h" 46 #include "llvm/Support/TargetSelect.h" 47 #include "llvm/Support/ToolOutputFile.h" 48 #include "llvm/Target/TargetLibraryInfo.h" 49 #include "llvm/Target/TargetMachine.h" 50 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 51 #include <algorithm> 52 #include <memory> 53 using namespace llvm; 54 using namespace opt_tool; 55 56 // The OptimizationList is automatically populated with registered Passes by the 57 // PassNameParser. 58 // 59 static cl::list<const PassInfo*, bool, PassNameParser> 60 PassList(cl::desc("Optimizations available:")); 61 62 // This flag specifies a textual description of the optimization pass pipeline 63 // to run over the module. This flag switches opt to use the new pass manager 64 // infrastructure, completely disabling all of the flags specific to the old 65 // pass management. 66 static cl::opt<std::string> PassPipeline( 67 "passes", 68 cl::desc("A textual description of the pass pipeline for optimizing"), 69 cl::Hidden); 70 71 // Other command line options... 72 // 73 static cl::opt<std::string> 74 InputFilename(cl::Positional, cl::desc("<input bitcode file>"), 75 cl::init("-"), cl::value_desc("filename")); 76 77 static cl::opt<std::string> 78 OutputFilename("o", cl::desc("Override output filename"), 79 cl::value_desc("filename")); 80 81 static cl::opt<bool> 82 Force("f", cl::desc("Enable binary output on terminals")); 83 84 static cl::opt<bool> 85 PrintEachXForm("p", cl::desc("Print module after each transformation")); 86 87 static cl::opt<bool> 88 NoOutput("disable-output", 89 cl::desc("Do not write result bitcode file"), cl::Hidden); 90 91 static cl::opt<bool> 92 OutputAssembly("S", cl::desc("Write output as LLVM assembly")); 93 94 static cl::opt<bool> 95 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden); 96 97 static cl::opt<bool> 98 VerifyEach("verify-each", cl::desc("Verify after each transform")); 99 100 static cl::opt<bool> 101 StripDebug("strip-debug", 102 cl::desc("Strip debugger symbol info from translation unit")); 103 104 static cl::opt<bool> 105 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass")); 106 107 static cl::opt<bool> 108 DisableOptimizations("disable-opt", 109 cl::desc("Do not run any optimization passes")); 110 111 static cl::opt<bool> 112 StandardCompileOpts("std-compile-opts", 113 cl::desc("Include the standard compile time optimizations")); 114 115 static cl::opt<bool> 116 StandardLinkOpts("std-link-opts", 117 cl::desc("Include the standard link time optimizations")); 118 119 static cl::opt<bool> 120 OptLevelO1("O1", 121 cl::desc("Optimization level 1. Similar to clang -O1")); 122 123 static cl::opt<bool> 124 OptLevelO2("O2", 125 cl::desc("Optimization level 2. Similar to clang -O2")); 126 127 static cl::opt<bool> 128 OptLevelOs("Os", 129 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os")); 130 131 static cl::opt<bool> 132 OptLevelOz("Oz", 133 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz")); 134 135 static cl::opt<bool> 136 OptLevelO3("O3", 137 cl::desc("Optimization level 3. Similar to clang -O3")); 138 139 static cl::opt<std::string> 140 TargetTriple("mtriple", cl::desc("Override target triple for module")); 141 142 static cl::opt<bool> 143 UnitAtATime("funit-at-a-time", 144 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"), 145 cl::init(true)); 146 147 static cl::opt<bool> 148 DisableLoopUnrolling("disable-loop-unrolling", 149 cl::desc("Disable loop unrolling in all relevant passes"), 150 cl::init(false)); 151 static cl::opt<bool> 152 DisableLoopVectorization("disable-loop-vectorization", 153 cl::desc("Disable the loop vectorization pass"), 154 cl::init(false)); 155 156 static cl::opt<bool> 157 DisableSLPVectorization("disable-slp-vectorization", 158 cl::desc("Disable the slp vectorization pass"), 159 cl::init(false)); 160 161 162 static cl::opt<bool> 163 DisableSimplifyLibCalls("disable-simplify-libcalls", 164 cl::desc("Disable simplify-libcalls")); 165 166 static cl::opt<bool> 167 Quiet("q", cl::desc("Obsolete option"), cl::Hidden); 168 169 static cl::alias 170 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet)); 171 172 static cl::opt<bool> 173 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization")); 174 175 static cl::opt<bool> 176 PrintBreakpoints("print-breakpoints-for-testing", 177 cl::desc("Print select breakpoints location for testing")); 178 179 static cl::opt<std::string> 180 DefaultDataLayout("default-data-layout", 181 cl::desc("data layout string to use if not specified by module"), 182 cl::value_desc("layout-string"), cl::init("")); 183 184 185 186 static inline void addPass(PassManagerBase &PM, Pass *P) { 187 // Add the pass to the pass manager... 188 PM.add(P); 189 190 // If we are verifying all of the intermediate steps, add the verifier... 191 if (VerifyEach) { 192 PM.add(createVerifierPass()); 193 PM.add(createDebugInfoVerifierPass()); 194 } 195 } 196 197 /// AddOptimizationPasses - This routine adds optimization passes 198 /// based on selected optimization level, OptLevel. This routine 199 /// duplicates llvm-gcc behaviour. 200 /// 201 /// OptLevel - Optimization Level 202 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM, 203 unsigned OptLevel, unsigned SizeLevel) { 204 FPM.add(createVerifierPass()); // Verify that input is correct 205 MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct 206 207 PassManagerBuilder Builder; 208 Builder.OptLevel = OptLevel; 209 Builder.SizeLevel = SizeLevel; 210 211 if (DisableInline) { 212 // No inlining pass 213 } else if (OptLevel > 1) { 214 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel); 215 } else { 216 Builder.Inliner = createAlwaysInlinerPass(); 217 } 218 Builder.DisableUnitAtATime = !UnitAtATime; 219 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ? 220 DisableLoopUnrolling : OptLevel == 0; 221 222 // This is final, unless there is a #pragma vectorize enable 223 if (DisableLoopVectorization) 224 Builder.LoopVectorize = false; 225 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize) 226 else if (!Builder.LoopVectorize) 227 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2; 228 229 // When #pragma vectorize is on for SLP, do the same as above 230 Builder.SLPVectorize = 231 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2; 232 233 Builder.populateFunctionPassManager(FPM); 234 Builder.populateModulePassManager(MPM); 235 } 236 237 static void AddStandardCompilePasses(PassManagerBase &PM) { 238 PM.add(createVerifierPass()); // Verify that input is correct 239 240 // If the -strip-debug command line option was specified, do it. 241 if (StripDebug) 242 addPass(PM, createStripSymbolsPass(true)); 243 244 // Verify debug info only after it's (possibly) stripped. 245 PM.add(createDebugInfoVerifierPass()); 246 247 if (DisableOptimizations) return; 248 249 // -std-compile-opts adds the same module passes as -O3. 250 PassManagerBuilder Builder; 251 if (!DisableInline) 252 Builder.Inliner = createFunctionInliningPass(); 253 Builder.OptLevel = 3; 254 Builder.populateModulePassManager(PM); 255 } 256 257 static void AddStandardLinkPasses(PassManagerBase &PM) { 258 PM.add(createVerifierPass()); // Verify that input is correct 259 260 // If the -strip-debug command line option was specified, do it. 261 if (StripDebug) 262 addPass(PM, createStripSymbolsPass(true)); 263 264 // Verify debug info only after it's (possibly) stripped. 265 PM.add(createDebugInfoVerifierPass()); 266 267 if (DisableOptimizations) return; 268 269 PassManagerBuilder Builder; 270 Builder.populateLTOPassManager(PM, /*RunInliner=*/!DisableInline, false); 271 } 272 273 //===----------------------------------------------------------------------===// 274 // CodeGen-related helper functions. 275 // 276 277 CodeGenOpt::Level GetCodeGenOptLevel() { 278 if (OptLevelO1) 279 return CodeGenOpt::Less; 280 if (OptLevelO2) 281 return CodeGenOpt::Default; 282 if (OptLevelO3) 283 return CodeGenOpt::Aggressive; 284 return CodeGenOpt::None; 285 } 286 287 // Returns the TargetMachine instance or zero if no triple is provided. 288 static TargetMachine* GetTargetMachine(Triple TheTriple) { 289 std::string Error; 290 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple, 291 Error); 292 // Some modules don't specify a triple, and this is okay. 293 if (!TheTarget) { 294 return nullptr; 295 } 296 297 // Package up features to be passed to target/subtarget 298 std::string FeaturesStr; 299 if (MAttrs.size()) { 300 SubtargetFeatures Features; 301 for (unsigned i = 0; i != MAttrs.size(); ++i) 302 Features.AddFeature(MAttrs[i]); 303 FeaturesStr = Features.getString(); 304 } 305 306 return TheTarget->createTargetMachine(TheTriple.getTriple(), 307 MCPU, FeaturesStr, 308 InitTargetOptionsFromCodeGenFlags(), 309 RelocModel, CMModel, 310 GetCodeGenOptLevel()); 311 } 312 313 #ifdef LINK_POLLY_INTO_TOOLS 314 namespace polly { 315 void initializePollyPasses(llvm::PassRegistry &Registry); 316 } 317 #endif 318 319 //===----------------------------------------------------------------------===// 320 // main for opt 321 // 322 int main(int argc, char **argv) { 323 sys::PrintStackTraceOnErrorSignal(); 324 llvm::PrettyStackTraceProgram X(argc, argv); 325 326 // Enable debug stream buffering. 327 EnableDebugBuffering = true; 328 329 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 330 LLVMContext &Context = getGlobalContext(); 331 332 InitializeAllTargets(); 333 InitializeAllTargetMCs(); 334 InitializeAllAsmPrinters(); 335 336 // Initialize passes 337 PassRegistry &Registry = *PassRegistry::getPassRegistry(); 338 initializeCore(Registry); 339 initializeDebugIRPass(Registry); 340 initializeScalarOpts(Registry); 341 initializeObjCARCOpts(Registry); 342 initializeVectorization(Registry); 343 initializeIPO(Registry); 344 initializeAnalysis(Registry); 345 initializeIPA(Registry); 346 initializeTransformUtils(Registry); 347 initializeInstCombine(Registry); 348 initializeInstrumentation(Registry); 349 initializeTarget(Registry); 350 // For codegen passes, only passes that do IR to IR transformation are 351 // supported. 352 initializeCodeGenPreparePass(Registry); 353 initializeAtomicExpandLoadLinkedPass(Registry); 354 355 #ifdef LINK_POLLY_INTO_TOOLS 356 polly::initializePollyPasses(Registry); 357 #endif 358 359 cl::ParseCommandLineOptions(argc, argv, 360 "llvm .bc -> .bc modular optimizer and analysis printer\n"); 361 362 if (AnalyzeOnly && NoOutput) { 363 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n"; 364 return 1; 365 } 366 367 SMDiagnostic Err; 368 369 // Load the input module... 370 std::unique_ptr<Module> M; 371 M.reset(ParseIRFile(InputFilename, Err, Context)); 372 373 if (!M.get()) { 374 Err.print(argv[0], errs()); 375 return 1; 376 } 377 378 // If we are supposed to override the target triple, do so now. 379 if (!TargetTriple.empty()) 380 M->setTargetTriple(Triple::normalize(TargetTriple)); 381 382 // Figure out what stream we are supposed to write to... 383 std::unique_ptr<tool_output_file> Out; 384 if (NoOutput) { 385 if (!OutputFilename.empty()) 386 errs() << "WARNING: The -o (output filename) option is ignored when\n" 387 "the --disable-output option is used.\n"; 388 } else { 389 // Default to standard output. 390 if (OutputFilename.empty()) 391 OutputFilename = "-"; 392 393 std::string ErrorInfo; 394 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 395 sys::fs::F_None)); 396 if (!ErrorInfo.empty()) { 397 errs() << ErrorInfo << '\n'; 398 return 1; 399 } 400 } 401 402 // If the output is set to be emitted to standard out, and standard out is a 403 // console, print out a warning message and refuse to do it. We don't 404 // impress anyone by spewing tons of binary goo to a terminal. 405 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly) 406 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet)) 407 NoOutput = true; 408 409 if (PassPipeline.getNumOccurrences() > 0) { 410 OutputKind OK = OK_NoOutput; 411 if (!NoOutput) 412 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode; 413 414 VerifierKind VK = VK_VerifyInAndOut; 415 if (NoVerify) 416 VK = VK_NoVerifier; 417 else if (VerifyEach) 418 VK = VK_VerifyEachPass; 419 420 // The user has asked to use the new pass manager and provided a pipeline 421 // string. Hand off the rest of the functionality to the new code for that 422 // layer. 423 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline, 424 OK, VK) 425 ? 0 426 : 1; 427 } 428 429 // Create a PassManager to hold and optimize the collection of passes we are 430 // about to build. 431 // 432 PassManager Passes; 433 434 // Add an appropriate TargetLibraryInfo pass for the module's triple. 435 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple())); 436 437 // The -disable-simplify-libcalls flag actually disables all builtin optzns. 438 if (DisableSimplifyLibCalls) 439 TLI->disableAllFunctions(); 440 Passes.add(TLI); 441 442 // Add an appropriate DataLayout instance for this module. 443 const DataLayout *DL = M.get()->getDataLayout(); 444 if (!DL && !DefaultDataLayout.empty()) { 445 M->setDataLayout(DefaultDataLayout); 446 DL = M.get()->getDataLayout(); 447 } 448 449 if (DL) 450 Passes.add(new DataLayoutPass(M.get())); 451 452 Triple ModuleTriple(M->getTargetTriple()); 453 TargetMachine *Machine = nullptr; 454 if (ModuleTriple.getArch()) 455 Machine = GetTargetMachine(Triple(ModuleTriple)); 456 std::unique_ptr<TargetMachine> TM(Machine); 457 458 // Add internal analysis passes from the target machine. 459 if (TM.get()) 460 TM->addAnalysisPasses(Passes); 461 462 std::unique_ptr<FunctionPassManager> FPasses; 463 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 464 FPasses.reset(new FunctionPassManager(M.get())); 465 if (DL) 466 FPasses->add(new DataLayoutPass(M.get())); 467 if (TM.get()) 468 TM->addAnalysisPasses(*FPasses); 469 470 } 471 472 if (PrintBreakpoints) { 473 // Default to standard output. 474 if (!Out) { 475 if (OutputFilename.empty()) 476 OutputFilename = "-"; 477 478 std::string ErrorInfo; 479 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo, 480 sys::fs::F_None)); 481 if (!ErrorInfo.empty()) { 482 errs() << ErrorInfo << '\n'; 483 return 1; 484 } 485 } 486 Passes.add(createBreakpointPrinter(Out->os())); 487 NoOutput = true; 488 } 489 490 // If the -strip-debug command line option was specified, add it. If 491 // -std-compile-opts was also specified, it will handle StripDebug. 492 if (StripDebug && !StandardCompileOpts) 493 addPass(Passes, createStripSymbolsPass(true)); 494 495 // Create a new optimization pass for each one specified on the command line 496 for (unsigned i = 0; i < PassList.size(); ++i) { 497 // Check to see if -std-compile-opts was specified before this option. If 498 // so, handle it. 499 if (StandardCompileOpts && 500 StandardCompileOpts.getPosition() < PassList.getPosition(i)) { 501 AddStandardCompilePasses(Passes); 502 StandardCompileOpts = false; 503 } 504 505 if (StandardLinkOpts && 506 StandardLinkOpts.getPosition() < PassList.getPosition(i)) { 507 AddStandardLinkPasses(Passes); 508 StandardLinkOpts = false; 509 } 510 511 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) { 512 AddOptimizationPasses(Passes, *FPasses, 1, 0); 513 OptLevelO1 = false; 514 } 515 516 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) { 517 AddOptimizationPasses(Passes, *FPasses, 2, 0); 518 OptLevelO2 = false; 519 } 520 521 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) { 522 AddOptimizationPasses(Passes, *FPasses, 2, 1); 523 OptLevelOs = false; 524 } 525 526 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) { 527 AddOptimizationPasses(Passes, *FPasses, 2, 2); 528 OptLevelOz = false; 529 } 530 531 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) { 532 AddOptimizationPasses(Passes, *FPasses, 3, 0); 533 OptLevelO3 = false; 534 } 535 536 const PassInfo *PassInf = PassList[i]; 537 Pass *P = nullptr; 538 if (PassInf->getTargetMachineCtor()) 539 P = PassInf->getTargetMachineCtor()(TM.get()); 540 else if (PassInf->getNormalCtor()) 541 P = PassInf->getNormalCtor()(); 542 else 543 errs() << argv[0] << ": cannot create pass: " 544 << PassInf->getPassName() << "\n"; 545 if (P) { 546 PassKind Kind = P->getPassKind(); 547 addPass(Passes, P); 548 549 if (AnalyzeOnly) { 550 switch (Kind) { 551 case PT_BasicBlock: 552 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet)); 553 break; 554 case PT_Region: 555 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet)); 556 break; 557 case PT_Loop: 558 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet)); 559 break; 560 case PT_Function: 561 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet)); 562 break; 563 case PT_CallGraphSCC: 564 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet)); 565 break; 566 default: 567 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet)); 568 break; 569 } 570 } 571 } 572 573 if (PrintEachXForm) 574 Passes.add(createPrintModulePass(errs())); 575 } 576 577 // If -std-compile-opts was specified at the end of the pass list, add them. 578 if (StandardCompileOpts) { 579 AddStandardCompilePasses(Passes); 580 StandardCompileOpts = false; 581 } 582 583 if (StandardLinkOpts) { 584 AddStandardLinkPasses(Passes); 585 StandardLinkOpts = false; 586 } 587 588 if (OptLevelO1) 589 AddOptimizationPasses(Passes, *FPasses, 1, 0); 590 591 if (OptLevelO2) 592 AddOptimizationPasses(Passes, *FPasses, 2, 0); 593 594 if (OptLevelOs) 595 AddOptimizationPasses(Passes, *FPasses, 2, 1); 596 597 if (OptLevelOz) 598 AddOptimizationPasses(Passes, *FPasses, 2, 2); 599 600 if (OptLevelO3) 601 AddOptimizationPasses(Passes, *FPasses, 3, 0); 602 603 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) { 604 FPasses->doInitialization(); 605 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F) 606 FPasses->run(*F); 607 FPasses->doFinalization(); 608 } 609 610 // Check that the module is well formed on completion of optimization 611 if (!NoVerify && !VerifyEach) { 612 Passes.add(createVerifierPass()); 613 Passes.add(createDebugInfoVerifierPass()); 614 } 615 616 // Write bitcode or assembly to the output as the last step... 617 if (!NoOutput && !AnalyzeOnly) { 618 if (OutputAssembly) 619 Passes.add(createPrintModulePass(Out->os())); 620 else 621 Passes.add(createBitcodeWriterPass(Out->os())); 622 } 623 624 // Before executing passes, print the final values of the LLVM options. 625 cl::PrintOptionValues(); 626 627 // Now that we have all of the passes ready, run them. 628 Passes.run(*M.get()); 629 630 // Declare success. 631 if (!NoOutput || PrintBreakpoints) 632 Out->keep(); 633 634 return 0; 635 } 636