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