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