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