1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
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"
54 using namespace opt_tool;
56 // The OptimizationList is automatically populated with registered Passes by the
59 static cl::list<const PassInfo*, bool, PassNameParser>
60 PassList(cl::desc("Optimizations available:"));
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
66 static cl::opt<std::string> PassPipeline(
68 cl::desc("A textual description of the pass pipeline for optimizing"),
71 // Other command line options...
73 static cl::opt<std::string>
74 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
75 cl::init("-"), cl::value_desc("filename"));
77 static cl::opt<std::string>
78 OutputFilename("o", cl::desc("Override output filename"),
79 cl::value_desc("filename"));
82 Force("f", cl::desc("Enable binary output on terminals"));
85 PrintEachXForm("p", cl::desc("Print module after each transformation"));
88 NoOutput("disable-output",
89 cl::desc("Do not write result bitcode file"), cl::Hidden);
92 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
95 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
98 VerifyEach("verify-each", cl::desc("Verify after each transform"));
101 StripDebug("strip-debug",
102 cl::desc("Strip debugger symbol info from translation unit"));
105 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
108 DisableOptimizations("disable-opt",
109 cl::desc("Do not run any optimization passes"));
112 DisableInternalize("disable-internalize",
113 cl::desc("Do not mark all symbols as internal"));
116 StandardCompileOpts("std-compile-opts",
117 cl::desc("Include the standard compile time optimizations"));
120 StandardLinkOpts("std-link-opts",
121 cl::desc("Include the standard link time optimizations"));
125 cl::desc("Optimization level 1. Similar to clang -O1"));
129 cl::desc("Optimization level 2. Similar to clang -O2"));
133 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
137 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
141 cl::desc("Optimization level 3. Similar to clang -O3"));
143 static cl::opt<std::string>
144 TargetTriple("mtriple", cl::desc("Override target triple for module"));
147 UnitAtATime("funit-at-a-time",
148 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
152 DisableLoopUnrolling("disable-loop-unrolling",
153 cl::desc("Disable loop unrolling in all relevant passes"),
156 DisableLoopVectorization("disable-loop-vectorization",
157 cl::desc("Disable the loop vectorization pass"),
161 DisableSLPVectorization("disable-slp-vectorization",
162 cl::desc("Disable the slp vectorization pass"),
167 DisableSimplifyLibCalls("disable-simplify-libcalls",
168 cl::desc("Disable simplify-libcalls"));
171 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
174 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
177 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
180 PrintBreakpoints("print-breakpoints-for-testing",
181 cl::desc("Print select breakpoints location for testing"));
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(""));
190 static inline void addPass(PassManagerBase &PM, Pass *P) {
191 // Add the pass to the pass manager...
194 // If we are verifying all of the intermediate steps, add the verifier...
196 PM.add(createVerifierPass());
197 PM.add(createDebugInfoVerifierPass());
201 /// AddOptimizationPasses - This routine adds optimization passes
202 /// based on selected optimization level, OptLevel. This routine
203 /// duplicates llvm-gcc behaviour.
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
211 PassManagerBuilder Builder;
212 Builder.OptLevel = OptLevel;
213 Builder.SizeLevel = SizeLevel;
217 } else if (OptLevel > 1) {
218 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
220 Builder.Inliner = createAlwaysInlinerPass();
222 Builder.DisableUnitAtATime = !UnitAtATime;
223 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
224 DisableLoopUnrolling : OptLevel == 0;
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;
233 // When #pragma vectorize is on for SLP, do the same as above
234 Builder.SLPVectorize =
235 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
237 Builder.populateFunctionPassManager(FPM);
238 Builder.populateModulePassManager(MPM);
241 static void AddStandardCompilePasses(PassManagerBase &PM) {
242 PM.add(createVerifierPass()); // Verify that input is correct
244 // If the -strip-debug command line option was specified, do it.
246 addPass(PM, createStripSymbolsPass(true));
248 // Verify debug info only after it's (possibly) stripped.
249 PM.add(createDebugInfoVerifierPass());
251 if (DisableOptimizations) return;
253 // -std-compile-opts adds the same module passes as -O3.
254 PassManagerBuilder Builder;
256 Builder.Inliner = createFunctionInliningPass();
257 Builder.OptLevel = 3;
258 Builder.populateModulePassManager(PM);
261 static void AddStandardLinkPasses(PassManagerBase &PM) {
262 PM.add(createVerifierPass()); // Verify that input is correct
264 // If the -strip-debug command line option was specified, do it.
266 addPass(PM, createStripSymbolsPass(true));
268 // Verify debug info only after it's (possibly) stripped.
269 PM.add(createDebugInfoVerifierPass());
271 if (DisableOptimizations) return;
273 PassManagerBuilder Builder;
274 Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
275 /*RunInliner=*/ !DisableInline);
278 //===----------------------------------------------------------------------===//
279 // CodeGen-related helper functions.
282 CodeGenOpt::Level GetCodeGenOptLevel() {
284 return CodeGenOpt::Less;
286 return CodeGenOpt::Default;
288 return CodeGenOpt::Aggressive;
289 return CodeGenOpt::None;
292 // Returns the TargetMachine instance or zero if no triple is provided.
293 static TargetMachine* GetTargetMachine(Triple TheTriple) {
295 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
297 // Some modules don't specify a triple, and this is okay.
302 // Package up features to be passed to target/subtarget
303 std::string FeaturesStr;
305 SubtargetFeatures Features;
306 for (unsigned i = 0; i != MAttrs.size(); ++i)
307 Features.AddFeature(MAttrs[i]);
308 FeaturesStr = Features.getString();
311 return TheTarget->createTargetMachine(TheTriple.getTriple(),
313 InitTargetOptionsFromCodeGenFlags(),
315 GetCodeGenOptLevel());
318 #ifdef LINK_POLLY_INTO_TOOLS
320 void initializePollyPasses(llvm::PassRegistry &Registry);
324 //===----------------------------------------------------------------------===//
327 int main(int argc, char **argv) {
328 sys::PrintStackTraceOnErrorSignal();
329 llvm::PrettyStackTraceProgram X(argc, argv);
331 // Enable debug stream buffering.
332 EnableDebugBuffering = true;
334 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
335 LLVMContext &Context = getGlobalContext();
337 InitializeAllTargets();
338 InitializeAllTargetMCs();
341 PassRegistry &Registry = *PassRegistry::getPassRegistry();
342 initializeCore(Registry);
343 initializeDebugIRPass(Registry);
344 initializeScalarOpts(Registry);
345 initializeObjCARCOpts(Registry);
346 initializeVectorization(Registry);
347 initializeIPO(Registry);
348 initializeAnalysis(Registry);
349 initializeIPA(Registry);
350 initializeTransformUtils(Registry);
351 initializeInstCombine(Registry);
352 initializeInstrumentation(Registry);
353 initializeTarget(Registry);
354 // For codegen passes, only passes that do IR to IR transformation are
356 initializeCodeGenPreparePass(Registry);
357 initializeAtomicExpandLoadLinkedPass(Registry);
359 #ifdef LINK_POLLY_INTO_TOOLS
360 polly::initializePollyPasses(Registry);
363 cl::ParseCommandLineOptions(argc, argv,
364 "llvm .bc -> .bc modular optimizer and analysis printer\n");
366 if (AnalyzeOnly && NoOutput) {
367 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
373 // Load the input module...
374 std::unique_ptr<Module> M;
375 M.reset(ParseIRFile(InputFilename, Err, Context));
378 Err.print(argv[0], errs());
382 // If we are supposed to override the target triple, do so now.
383 if (!TargetTriple.empty())
384 M->setTargetTriple(Triple::normalize(TargetTriple));
386 // Figure out what stream we are supposed to write to...
387 std::unique_ptr<tool_output_file> Out;
389 if (!OutputFilename.empty())
390 errs() << "WARNING: The -o (output filename) option is ignored when\n"
391 "the --disable-output option is used.\n";
393 // Default to standard output.
394 if (OutputFilename.empty())
395 OutputFilename = "-";
397 std::string ErrorInfo;
398 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
400 if (!ErrorInfo.empty()) {
401 errs() << ErrorInfo << '\n';
406 // If the output is set to be emitted to standard out, and standard out is a
407 // console, print out a warning message and refuse to do it. We don't
408 // impress anyone by spewing tons of binary goo to a terminal.
409 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
410 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
413 if (PassPipeline.getNumOccurrences() > 0) {
414 OutputKind OK = OK_NoOutput;
416 OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
418 VerifierKind VK = VK_VerifyInAndOut;
422 VK = VK_VerifyEachPass;
424 // The user has asked to use the new pass manager and provided a pipeline
425 // string. Hand off the rest of the functionality to the new code for that
427 return runPassPipeline(argv[0], Context, *M.get(), Out.get(), PassPipeline,
433 // Create a PassManager to hold and optimize the collection of passes we are
438 // Add an appropriate TargetLibraryInfo pass for the module's triple.
439 TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
441 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
442 if (DisableSimplifyLibCalls)
443 TLI->disableAllFunctions();
446 // Add an appropriate DataLayout instance for this module.
447 const DataLayout *DL = M.get()->getDataLayout();
448 if (!DL && !DefaultDataLayout.empty()) {
449 M->setDataLayout(DefaultDataLayout);
450 DL = M.get()->getDataLayout();
454 Passes.add(new DataLayoutPass(M.get()));
456 Triple ModuleTriple(M->getTargetTriple());
457 TargetMachine *Machine = nullptr;
458 if (ModuleTriple.getArch())
459 Machine = GetTargetMachine(Triple(ModuleTriple));
460 std::unique_ptr<TargetMachine> TM(Machine);
462 // Add internal analysis passes from the target machine.
464 TM->addAnalysisPasses(Passes);
466 std::unique_ptr<FunctionPassManager> FPasses;
467 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
468 FPasses.reset(new FunctionPassManager(M.get()));
470 FPasses->add(new DataLayoutPass(M.get()));
472 TM->addAnalysisPasses(*FPasses);
476 if (PrintBreakpoints) {
477 // Default to standard output.
479 if (OutputFilename.empty())
480 OutputFilename = "-";
482 std::string ErrorInfo;
483 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
485 if (!ErrorInfo.empty()) {
486 errs() << ErrorInfo << '\n';
490 Passes.add(createBreakpointPrinter(Out->os()));
494 // If the -strip-debug command line option was specified, add it. If
495 // -std-compile-opts was also specified, it will handle StripDebug.
496 if (StripDebug && !StandardCompileOpts)
497 addPass(Passes, createStripSymbolsPass(true));
499 // Create a new optimization pass for each one specified on the command line
500 for (unsigned i = 0; i < PassList.size(); ++i) {
501 // Check to see if -std-compile-opts was specified before this option. If
503 if (StandardCompileOpts &&
504 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
505 AddStandardCompilePasses(Passes);
506 StandardCompileOpts = false;
509 if (StandardLinkOpts &&
510 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
511 AddStandardLinkPasses(Passes);
512 StandardLinkOpts = false;
515 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
516 AddOptimizationPasses(Passes, *FPasses, 1, 0);
520 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
521 AddOptimizationPasses(Passes, *FPasses, 2, 0);
525 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
526 AddOptimizationPasses(Passes, *FPasses, 2, 1);
530 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
531 AddOptimizationPasses(Passes, *FPasses, 2, 2);
535 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
536 AddOptimizationPasses(Passes, *FPasses, 3, 0);
540 const PassInfo *PassInf = PassList[i];
542 if (PassInf->getTargetMachineCtor())
543 P = PassInf->getTargetMachineCtor()(TM.get());
544 else if (PassInf->getNormalCtor())
545 P = PassInf->getNormalCtor()();
547 errs() << argv[0] << ": cannot create pass: "
548 << PassInf->getPassName() << "\n";
550 PassKind Kind = P->getPassKind();
556 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
559 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
562 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
565 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
567 case PT_CallGraphSCC:
568 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
571 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
578 Passes.add(createPrintModulePass(errs()));
581 // If -std-compile-opts was specified at the end of the pass list, add them.
582 if (StandardCompileOpts) {
583 AddStandardCompilePasses(Passes);
584 StandardCompileOpts = false;
587 if (StandardLinkOpts) {
588 AddStandardLinkPasses(Passes);
589 StandardLinkOpts = false;
593 AddOptimizationPasses(Passes, *FPasses, 1, 0);
596 AddOptimizationPasses(Passes, *FPasses, 2, 0);
599 AddOptimizationPasses(Passes, *FPasses, 2, 1);
602 AddOptimizationPasses(Passes, *FPasses, 2, 2);
605 AddOptimizationPasses(Passes, *FPasses, 3, 0);
607 if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
608 FPasses->doInitialization();
609 for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
611 FPasses->doFinalization();
614 // Check that the module is well formed on completion of optimization
615 if (!NoVerify && !VerifyEach) {
616 Passes.add(createVerifierPass());
617 Passes.add(createDebugInfoVerifierPass());
620 // Write bitcode or assembly to the output as the last step...
621 if (!NoOutput && !AnalyzeOnly) {
623 Passes.add(createPrintModulePass(Out->os()));
625 Passes.add(createBitcodeWriterPass(Out->os()));
628 // Before executing passes, print the final values of the LLVM options.
629 cl::PrintOptionValues();
631 // Now that we have all of the passes ready, run them.
632 Passes.run(*M.get());
635 if (!NoOutput || PrintBreakpoints)