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