00337ded99a14bad5149d60a974d4d8121da7ff5
[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   Triple ModuleTriple(M->getTargetTriple());
374   TargetMachine *Machine = nullptr;
375   if (ModuleTriple.getArch())
376     Machine = GetTargetMachine(ModuleTriple);
377   std::unique_ptr<TargetMachine> TM(Machine);
378
379   // If the output is set to be emitted to standard out, and standard out is a
380   // console, print out a warning message and refuse to do it.  We don't
381   // impress anyone by spewing tons of binary goo to a terminal.
382   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
383     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
384       NoOutput = true;
385
386   if (PassPipeline.getNumOccurrences() > 0) {
387     OutputKind OK = OK_NoOutput;
388     if (!NoOutput)
389       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
390
391     VerifierKind VK = VK_VerifyInAndOut;
392     if (NoVerify)
393       VK = VK_NoVerifier;
394     else if (VerifyEach)
395       VK = VK_VerifyEachPass;
396
397     // The user has asked to use the new pass manager and provided a pipeline
398     // string. Hand off the rest of the functionality to the new code for that
399     // layer.
400     return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
401                            PassPipeline, OK, VK)
402                ? 0
403                : 1;
404   }
405
406   // Create a PassManager to hold and optimize the collection of passes we are
407   // about to build.
408   //
409   PassManager Passes;
410
411   // Add an appropriate TargetLibraryInfo pass for the module's triple.
412   TargetLibraryInfoImpl TLII(ModuleTriple);
413
414   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
415   if (DisableSimplifyLibCalls)
416     TLII.disableAllFunctions();
417   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
418
419   // Add an appropriate DataLayout instance for this module.
420   const DataLayout *DL = M->getDataLayout();
421   if (!DL && !DefaultDataLayout.empty()) {
422     M->setDataLayout(DefaultDataLayout);
423     DL = M->getDataLayout();
424   }
425
426   if (DL)
427     Passes.add(new DataLayoutPass());
428
429   // Add internal analysis passes from the target machine.
430   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
431                                                      : TargetIRAnalysis()));
432
433   std::unique_ptr<FunctionPassManager> FPasses;
434   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
435     FPasses.reset(new FunctionPassManager(M.get()));
436     if (DL)
437       FPasses->add(new DataLayoutPass());
438     FPasses->add(createTargetTransformInfoWrapperPass(
439         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
440   }
441
442   if (PrintBreakpoints) {
443     // Default to standard output.
444     if (!Out) {
445       if (OutputFilename.empty())
446         OutputFilename = "-";
447
448       std::error_code EC;
449       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
450                                                 sys::fs::F_None);
451       if (EC) {
452         errs() << EC.message() << '\n';
453         return 1;
454       }
455     }
456     Passes.add(createBreakpointPrinter(Out->os()));
457     NoOutput = true;
458   }
459
460   // If the -strip-debug command line option was specified, add it.
461   if (StripDebug)
462     addPass(Passes, createStripSymbolsPass(true));
463
464   // Create a new optimization pass for each one specified on the command line
465   for (unsigned i = 0; i < PassList.size(); ++i) {
466     if (StandardLinkOpts &&
467         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
468       AddStandardLinkPasses(Passes);
469       StandardLinkOpts = false;
470     }
471
472     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
473       AddOptimizationPasses(Passes, *FPasses, 1, 0);
474       OptLevelO1 = false;
475     }
476
477     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
478       AddOptimizationPasses(Passes, *FPasses, 2, 0);
479       OptLevelO2 = false;
480     }
481
482     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
483       AddOptimizationPasses(Passes, *FPasses, 2, 1);
484       OptLevelOs = false;
485     }
486
487     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
488       AddOptimizationPasses(Passes, *FPasses, 2, 2);
489       OptLevelOz = false;
490     }
491
492     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
493       AddOptimizationPasses(Passes, *FPasses, 3, 0);
494       OptLevelO3 = false;
495     }
496
497     const PassInfo *PassInf = PassList[i];
498     Pass *P = nullptr;
499     if (PassInf->getTargetMachineCtor())
500       P = PassInf->getTargetMachineCtor()(TM.get());
501     else if (PassInf->getNormalCtor())
502       P = PassInf->getNormalCtor()();
503     else
504       errs() << argv[0] << ": cannot create pass: "
505              << PassInf->getPassName() << "\n";
506     if (P) {
507       PassKind Kind = P->getPassKind();
508       addPass(Passes, P);
509
510       if (AnalyzeOnly) {
511         switch (Kind) {
512         case PT_BasicBlock:
513           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
514           break;
515         case PT_Region:
516           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
517           break;
518         case PT_Loop:
519           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
520           break;
521         case PT_Function:
522           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
523           break;
524         case PT_CallGraphSCC:
525           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
526           break;
527         default:
528           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
529           break;
530         }
531       }
532     }
533
534     if (PrintEachXForm)
535       Passes.add(createPrintModulePass(errs()));
536   }
537
538   if (StandardLinkOpts) {
539     AddStandardLinkPasses(Passes);
540     StandardLinkOpts = false;
541   }
542
543   if (OptLevelO1)
544     AddOptimizationPasses(Passes, *FPasses, 1, 0);
545
546   if (OptLevelO2)
547     AddOptimizationPasses(Passes, *FPasses, 2, 0);
548
549   if (OptLevelOs)
550     AddOptimizationPasses(Passes, *FPasses, 2, 1);
551
552   if (OptLevelOz)
553     AddOptimizationPasses(Passes, *FPasses, 2, 2);
554
555   if (OptLevelO3)
556     AddOptimizationPasses(Passes, *FPasses, 3, 0);
557
558   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
559     FPasses->doInitialization();
560     for (Function &F : *M)
561       FPasses->run(F);
562     FPasses->doFinalization();
563   }
564
565   // Check that the module is well formed on completion of optimization
566   if (!NoVerify && !VerifyEach) {
567     Passes.add(createVerifierPass());
568     Passes.add(createDebugInfoVerifierPass());
569   }
570
571   // Write bitcode or assembly to the output as the last step...
572   if (!NoOutput && !AnalyzeOnly) {
573     if (OutputAssembly)
574       Passes.add(createPrintModulePass(Out->os()));
575     else
576       Passes.add(createBitcodeWriterPass(Out->os()));
577   }
578
579   // Before executing passes, print the final values of the LLVM options.
580   cl::PrintOptionValues();
581
582   // Now that we have all of the passes ready, run them.
583   Passes.run(*M);
584
585   // Declare success.
586   if (!NoOutput || PrintBreakpoints)
587     Out->keep();
588
589   return 0;
590 }