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