c1e120af5407762f2526f0121ffe4da9fd1855cc
[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/IR/LegacyPassManager.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(legacy::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 }
191
192 /// This routine adds optimization passes based on selected optimization level,
193 /// OptLevel.
194 ///
195 /// OptLevel - Optimization Level
196 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
197                                   legacy::FunctionPassManager &FPM,
198                                   unsigned OptLevel, unsigned SizeLevel) {
199   FPM.add(createVerifierPass()); // Verify that input is correct
200
201   PassManagerBuilder Builder;
202   Builder.OptLevel = OptLevel;
203   Builder.SizeLevel = SizeLevel;
204
205   if (DisableInline) {
206     // No inlining pass
207   } else if (OptLevel > 1) {
208     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
209   } else {
210     Builder.Inliner = createAlwaysInlinerPass();
211   }
212   Builder.DisableUnitAtATime = !UnitAtATime;
213   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
214                                DisableLoopUnrolling : OptLevel == 0;
215
216   // This is final, unless there is a #pragma vectorize enable
217   if (DisableLoopVectorization)
218     Builder.LoopVectorize = false;
219   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
220   else if (!Builder.LoopVectorize)
221     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
222
223   // When #pragma vectorize is on for SLP, do the same as above
224   Builder.SLPVectorize =
225       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
226
227   Builder.populateFunctionPassManager(FPM);
228   Builder.populateModulePassManager(MPM);
229 }
230
231 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
232   PassManagerBuilder Builder;
233   Builder.VerifyInput = true;
234   if (DisableOptimizations)
235     Builder.OptLevel = 0;
236
237   if (!DisableInline)
238     Builder.Inliner = createFunctionInliningPass();
239   Builder.populateLTOPassManager(PM);
240 }
241
242 //===----------------------------------------------------------------------===//
243 // CodeGen-related helper functions.
244 //
245
246 static CodeGenOpt::Level GetCodeGenOptLevel() {
247   if (OptLevelO1)
248     return CodeGenOpt::Less;
249   if (OptLevelO2)
250     return CodeGenOpt::Default;
251   if (OptLevelO3)
252     return CodeGenOpt::Aggressive;
253   return CodeGenOpt::None;
254 }
255
256 // Returns the TargetMachine instance or zero if no triple is provided.
257 static TargetMachine* GetTargetMachine(Triple TheTriple) {
258   std::string Error;
259   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
260                                                          Error);
261   // Some modules don't specify a triple, and this is okay.
262   if (!TheTarget) {
263     return nullptr;
264   }
265
266   // Package up features to be passed to target/subtarget
267   std::string FeaturesStr;
268   if (MAttrs.size()) {
269     SubtargetFeatures Features;
270     for (unsigned i = 0; i != MAttrs.size(); ++i)
271       Features.AddFeature(MAttrs[i]);
272     FeaturesStr = Features.getString();
273   }
274
275   return TheTarget->createTargetMachine(TheTriple.getTriple(),
276                                         MCPU, FeaturesStr,
277                                         InitTargetOptionsFromCodeGenFlags(),
278                                         RelocModel, CMModel,
279                                         GetCodeGenOptLevel());
280 }
281
282 #ifdef LINK_POLLY_INTO_TOOLS
283 namespace polly {
284 void initializePollyPasses(llvm::PassRegistry &Registry);
285 }
286 #endif
287
288 //===----------------------------------------------------------------------===//
289 // main for opt
290 //
291 int main(int argc, char **argv) {
292   sys::PrintStackTraceOnErrorSignal();
293   llvm::PrettyStackTraceProgram X(argc, argv);
294
295   // Enable debug stream buffering.
296   EnableDebugBuffering = true;
297
298   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
299   LLVMContext &Context = getGlobalContext();
300
301   InitializeAllTargets();
302   InitializeAllTargetMCs();
303   InitializeAllAsmPrinters();
304
305   // Initialize passes
306   PassRegistry &Registry = *PassRegistry::getPassRegistry();
307   initializeCore(Registry);
308   initializeScalarOpts(Registry);
309   initializeObjCARCOpts(Registry);
310   initializeVectorization(Registry);
311   initializeIPO(Registry);
312   initializeAnalysis(Registry);
313   initializeIPA(Registry);
314   initializeTransformUtils(Registry);
315   initializeInstCombine(Registry);
316   initializeInstrumentation(Registry);
317   initializeTarget(Registry);
318   // For codegen passes, only passes that do IR to IR transformation are
319   // supported.
320   initializeCodeGenPreparePass(Registry);
321   initializeAtomicExpandPass(Registry);
322   initializeRewriteSymbolsPass(Registry);
323   initializeWinEHPreparePass(Registry);
324   initializeDwarfEHPreparePass(Registry);
325
326 #ifdef LINK_POLLY_INTO_TOOLS
327   polly::initializePollyPasses(Registry);
328 #endif
329
330   cl::ParseCommandLineOptions(argc, argv,
331     "llvm .bc -> .bc modular optimizer and analysis printer\n");
332
333   if (AnalyzeOnly && NoOutput) {
334     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
335     return 1;
336   }
337
338   SMDiagnostic Err;
339
340   // Load the input module...
341   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
342
343   if (!M) {
344     Err.print(argv[0], errs());
345     return 1;
346   }
347
348   // If we are supposed to override the target triple, do so now.
349   if (!TargetTriple.empty())
350     M->setTargetTriple(Triple::normalize(TargetTriple));
351
352   // Figure out what stream we are supposed to write to...
353   std::unique_ptr<tool_output_file> Out;
354   if (NoOutput) {
355     if (!OutputFilename.empty())
356       errs() << "WARNING: The -o (output filename) option is ignored when\n"
357                 "the --disable-output option is used.\n";
358   } else {
359     // Default to standard output.
360     if (OutputFilename.empty())
361       OutputFilename = "-";
362
363     std::error_code EC;
364     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
365     if (EC) {
366       errs() << EC.message() << '\n';
367       return 1;
368     }
369   }
370
371   Triple ModuleTriple(M->getTargetTriple());
372   TargetMachine *Machine = nullptr;
373   if (ModuleTriple.getArch())
374     Machine = GetTargetMachine(ModuleTriple);
375   std::unique_ptr<TargetMachine> TM(Machine);
376
377   // If the output is set to be emitted to standard out, and standard out is a
378   // console, print out a warning message and refuse to do it.  We don't
379   // impress anyone by spewing tons of binary goo to a terminal.
380   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
381     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
382       NoOutput = true;
383
384   if (PassPipeline.getNumOccurrences() > 0) {
385     OutputKind OK = OK_NoOutput;
386     if (!NoOutput)
387       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
388
389     VerifierKind VK = VK_VerifyInAndOut;
390     if (NoVerify)
391       VK = VK_NoVerifier;
392     else if (VerifyEach)
393       VK = VK_VerifyEachPass;
394
395     // The user has asked to use the new pass manager and provided a pipeline
396     // string. Hand off the rest of the functionality to the new code for that
397     // layer.
398     return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
399                            PassPipeline, OK, VK)
400                ? 0
401                : 1;
402   }
403
404   // Create a PassManager to hold and optimize the collection of passes we are
405   // about to build.
406   //
407   legacy::PassManager Passes;
408
409   // Add an appropriate TargetLibraryInfo pass for the module's triple.
410   TargetLibraryInfoImpl TLII(ModuleTriple);
411
412   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
413   if (DisableSimplifyLibCalls)
414     TLII.disableAllFunctions();
415   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
416
417   // Add an appropriate DataLayout instance for this module.
418   const DataLayout &DL = M->getDataLayout();
419   if (DL.isDefault() && !DefaultDataLayout.empty()) {
420     M->setDataLayout(DefaultDataLayout);
421   }
422
423   // Add internal analysis passes from the target machine.
424   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
425                                                      : TargetIRAnalysis()));
426
427   std::unique_ptr<legacy::FunctionPassManager> FPasses;
428   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
429     FPasses.reset(new legacy::FunctionPassManager(M.get()));
430     FPasses->add(createTargetTransformInfoWrapperPass(
431         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
432   }
433
434   if (PrintBreakpoints) {
435     // Default to standard output.
436     if (!Out) {
437       if (OutputFilename.empty())
438         OutputFilename = "-";
439
440       std::error_code EC;
441       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
442                                                 sys::fs::F_None);
443       if (EC) {
444         errs() << EC.message() << '\n';
445         return 1;
446       }
447     }
448     Passes.add(createBreakpointPrinter(Out->os()));
449     NoOutput = true;
450   }
451
452   // If the -strip-debug command line option was specified, add it.
453   if (StripDebug)
454     addPass(Passes, createStripSymbolsPass(true));
455
456   // Create a new optimization pass for each one specified on the command line
457   for (unsigned i = 0; i < PassList.size(); ++i) {
458     if (StandardLinkOpts &&
459         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
460       AddStandardLinkPasses(Passes);
461       StandardLinkOpts = false;
462     }
463
464     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
465       AddOptimizationPasses(Passes, *FPasses, 1, 0);
466       OptLevelO1 = false;
467     }
468
469     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
470       AddOptimizationPasses(Passes, *FPasses, 2, 0);
471       OptLevelO2 = false;
472     }
473
474     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
475       AddOptimizationPasses(Passes, *FPasses, 2, 1);
476       OptLevelOs = false;
477     }
478
479     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
480       AddOptimizationPasses(Passes, *FPasses, 2, 2);
481       OptLevelOz = false;
482     }
483
484     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
485       AddOptimizationPasses(Passes, *FPasses, 3, 0);
486       OptLevelO3 = false;
487     }
488
489     const PassInfo *PassInf = PassList[i];
490     Pass *P = nullptr;
491     if (PassInf->getTargetMachineCtor())
492       P = PassInf->getTargetMachineCtor()(TM.get());
493     else if (PassInf->getNormalCtor())
494       P = PassInf->getNormalCtor()();
495     else
496       errs() << argv[0] << ": cannot create pass: "
497              << PassInf->getPassName() << "\n";
498     if (P) {
499       PassKind Kind = P->getPassKind();
500       addPass(Passes, P);
501
502       if (AnalyzeOnly) {
503         switch (Kind) {
504         case PT_BasicBlock:
505           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
506           break;
507         case PT_Region:
508           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
509           break;
510         case PT_Loop:
511           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
512           break;
513         case PT_Function:
514           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
515           break;
516         case PT_CallGraphSCC:
517           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
518           break;
519         default:
520           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
521           break;
522         }
523       }
524     }
525
526     if (PrintEachXForm)
527       Passes.add(createPrintModulePass(errs()));
528   }
529
530   if (StandardLinkOpts) {
531     AddStandardLinkPasses(Passes);
532     StandardLinkOpts = false;
533   }
534
535   if (OptLevelO1)
536     AddOptimizationPasses(Passes, *FPasses, 1, 0);
537
538   if (OptLevelO2)
539     AddOptimizationPasses(Passes, *FPasses, 2, 0);
540
541   if (OptLevelOs)
542     AddOptimizationPasses(Passes, *FPasses, 2, 1);
543
544   if (OptLevelOz)
545     AddOptimizationPasses(Passes, *FPasses, 2, 2);
546
547   if (OptLevelO3)
548     AddOptimizationPasses(Passes, *FPasses, 3, 0);
549
550   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
551     FPasses->doInitialization();
552     for (Function &F : *M)
553       FPasses->run(F);
554     FPasses->doFinalization();
555   }
556
557   // Check that the module is well formed on completion of optimization
558   if (!NoVerify && !VerifyEach)
559     Passes.add(createVerifierPass());
560
561   // Write bitcode or assembly to the output as the last step...
562   if (!NoOutput && !AnalyzeOnly) {
563     if (OutputAssembly)
564       Passes.add(createPrintModulePass(Out->os()));
565     else
566       Passes.add(createBitcodeWriterPass(Out->os()));
567   }
568
569   // Before executing passes, print the final values of the LLVM options.
570   cl::PrintOptionValues();
571
572   // Now that we have all of the passes ready, run them.
573   Passes.run(*M);
574
575   // Declare success.
576   if (!NoOutput || PrintBreakpoints)
577     Out->keep();
578
579   return 0;
580 }