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