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