]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/opt/opt.cpp
Merge ^/head r318964 through r319164.
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/CodeGen/TargetPassConfig.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/LegacyPassNameParser.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Verifier.h"
36 #include "llvm/IRReader/IRReader.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/LinkAllIR.h"
39 #include "llvm/LinkAllPasses.h"
40 #include "llvm/MC/SubtargetFeature.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/Support/YAMLTraits.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Transforms/Coroutines.h"
56 #include "llvm/Transforms/IPO/AlwaysInliner.h"
57 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include <algorithm>
60 #include <memory>
61 using namespace llvm;
62 using namespace opt_tool;
63
64 // The OptimizationList is automatically populated with registered Passes by the
65 // PassNameParser.
66 //
67 static cl::list<const PassInfo*, bool, PassNameParser>
68 PassList(cl::desc("Optimizations available:"));
69
70 // This flag specifies a textual description of the optimization pass pipeline
71 // to run over the module. This flag switches opt to use the new pass manager
72 // infrastructure, completely disabling all of the flags specific to the old
73 // pass management.
74 static cl::opt<std::string> PassPipeline(
75     "passes",
76     cl::desc("A textual description of the pass pipeline for optimizing"),
77     cl::Hidden);
78
79 // Other command line options...
80 //
81 static cl::opt<std::string>
82 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
83     cl::init("-"), cl::value_desc("filename"));
84
85 static cl::opt<std::string>
86 OutputFilename("o", cl::desc("Override output filename"),
87                cl::value_desc("filename"));
88
89 static cl::opt<bool>
90 Force("f", cl::desc("Enable binary output on terminals"));
91
92 static cl::opt<bool>
93 PrintEachXForm("p", cl::desc("Print module after each transformation"));
94
95 static cl::opt<bool>
96 NoOutput("disable-output",
97          cl::desc("Do not write result bitcode file"), cl::Hidden);
98
99 static cl::opt<bool>
100 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
101
102 static cl::opt<bool>
103     OutputThinLTOBC("thinlto-bc",
104                     cl::desc("Write output as ThinLTO-ready bitcode"));
105
106 static cl::opt<std::string> ThinLinkBitcodeFile(
107     "thin-link-bitcode-file", cl::value_desc("filename"),
108     cl::desc(
109         "A file in which to write minimized bitcode for the thin link only"));
110
111 static cl::opt<bool>
112 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
113
114 static cl::opt<bool>
115 VerifyEach("verify-each", cl::desc("Verify after each transform"));
116
117 static cl::opt<bool>
118     DisableDITypeMap("disable-debug-info-type-map",
119                      cl::desc("Don't use a uniquing type map for debug info"));
120
121 static cl::opt<bool>
122 StripDebug("strip-debug",
123            cl::desc("Strip debugger symbol info from translation unit"));
124
125 static cl::opt<bool>
126 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
127
128 static cl::opt<bool>
129 DisableOptimizations("disable-opt",
130                      cl::desc("Do not run any optimization passes"));
131
132 static cl::opt<bool>
133 StandardLinkOpts("std-link-opts",
134                  cl::desc("Include the standard link time optimizations"));
135
136 static cl::opt<bool>
137 OptLevelO0("O0",
138   cl::desc("Optimization level 0. Similar to clang -O0"));
139
140 static cl::opt<bool>
141 OptLevelO1("O1",
142            cl::desc("Optimization level 1. Similar to clang -O1"));
143
144 static cl::opt<bool>
145 OptLevelO2("O2",
146            cl::desc("Optimization level 2. Similar to clang -O2"));
147
148 static cl::opt<bool>
149 OptLevelOs("Os",
150            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
151
152 static cl::opt<bool>
153 OptLevelOz("Oz",
154            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
155
156 static cl::opt<bool>
157 OptLevelO3("O3",
158            cl::desc("Optimization level 3. Similar to clang -O3"));
159
160 static cl::opt<unsigned>
161 CodeGenOptLevel("codegen-opt-level",
162                 cl::desc("Override optimization level for codegen hooks"));
163
164 static cl::opt<std::string>
165 TargetTriple("mtriple", cl::desc("Override target triple for module"));
166
167 static cl::opt<bool>
168 UnitAtATime("funit-at-a-time",
169             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
170             cl::init(true));
171
172 static cl::opt<bool>
173 DisableLoopUnrolling("disable-loop-unrolling",
174                      cl::desc("Disable loop unrolling in all relevant passes"),
175                      cl::init(false));
176 static cl::opt<bool>
177 DisableLoopVectorization("disable-loop-vectorization",
178                      cl::desc("Disable the loop vectorization pass"),
179                      cl::init(false));
180
181 static cl::opt<bool>
182 DisableSLPVectorization("disable-slp-vectorization",
183                         cl::desc("Disable the slp vectorization pass"),
184                         cl::init(false));
185
186 static cl::opt<bool> EmitSummaryIndex("module-summary",
187                                       cl::desc("Emit module summary index"),
188                                       cl::init(false));
189
190 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
191                                     cl::init(false));
192
193 static cl::opt<bool>
194 DisableSimplifyLibCalls("disable-simplify-libcalls",
195                         cl::desc("Disable simplify-libcalls"));
196
197 static cl::opt<bool>
198 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
199
200 static cl::alias
201 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
202
203 static cl::opt<bool>
204 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
205
206 static cl::opt<bool>
207 PrintBreakpoints("print-breakpoints-for-testing",
208                  cl::desc("Print select breakpoints location for testing"));
209
210 static cl::opt<std::string> ClDataLayout("data-layout",
211                                          cl::desc("data layout string to use"),
212                                          cl::value_desc("layout-string"),
213                                          cl::init(""));
214
215 static cl::opt<bool> PreserveBitcodeUseListOrder(
216     "preserve-bc-uselistorder",
217     cl::desc("Preserve use-list order when writing LLVM bitcode."),
218     cl::init(true), cl::Hidden);
219
220 static cl::opt<bool> PreserveAssemblyUseListOrder(
221     "preserve-ll-uselistorder",
222     cl::desc("Preserve use-list order when writing LLVM assembly."),
223     cl::init(false), cl::Hidden);
224
225 static cl::opt<bool>
226     RunTwice("run-twice",
227              cl::desc("Run all passes twice, re-using the same pass manager."),
228              cl::init(false), cl::Hidden);
229
230 static cl::opt<bool> DiscardValueNames(
231     "discard-value-names",
232     cl::desc("Discard names from Value (other than GlobalValue)."),
233     cl::init(false), cl::Hidden);
234
235 static cl::opt<bool> Coroutines(
236   "enable-coroutines",
237   cl::desc("Enable coroutine passes."),
238   cl::init(false), cl::Hidden);
239
240 static cl::opt<bool> PassRemarksWithHotness(
241     "pass-remarks-with-hotness",
242     cl::desc("With PGO, include profile count in optimization remarks"),
243     cl::Hidden);
244
245 static cl::opt<std::string>
246     RemarksFilename("pass-remarks-output",
247                     cl::desc("YAML output filename for pass remarks"),
248                     cl::value_desc("filename"));
249
250 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
251   // Add the pass to the pass manager...
252   PM.add(P);
253
254   // If we are verifying all of the intermediate steps, add the verifier...
255   if (VerifyEach)
256     PM.add(createVerifierPass());
257 }
258
259 /// This routine adds optimization passes based on selected optimization level,
260 /// OptLevel.
261 ///
262 /// OptLevel - Optimization Level
263 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
264                                   legacy::FunctionPassManager &FPM,
265                                   TargetMachine *TM, unsigned OptLevel,
266                                   unsigned SizeLevel) {
267   if (!NoVerify || VerifyEach)
268     FPM.add(createVerifierPass()); // Verify that input is correct
269
270   PassManagerBuilder Builder;
271   Builder.OptLevel = OptLevel;
272   Builder.SizeLevel = SizeLevel;
273
274   if (DisableInline) {
275     // No inlining pass
276   } else if (OptLevel > 1) {
277     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
278   } else {
279     Builder.Inliner = createAlwaysInlinerLegacyPass();
280   }
281   Builder.DisableUnitAtATime = !UnitAtATime;
282   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
283                                DisableLoopUnrolling : OptLevel == 0;
284
285   // This is final, unless there is a #pragma vectorize enable
286   if (DisableLoopVectorization)
287     Builder.LoopVectorize = false;
288   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
289   else if (!Builder.LoopVectorize)
290     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
291
292   // When #pragma vectorize is on for SLP, do the same as above
293   Builder.SLPVectorize =
294       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
295
296   if (TM)
297     TM->adjustPassManager(Builder);
298
299   if (Coroutines)
300     addCoroutinePassesToExtensionPoints(Builder);
301
302   Builder.populateFunctionPassManager(FPM);
303   Builder.populateModulePassManager(MPM);
304 }
305
306 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
307   PassManagerBuilder Builder;
308   Builder.VerifyInput = true;
309   if (DisableOptimizations)
310     Builder.OptLevel = 0;
311
312   if (!DisableInline)
313     Builder.Inliner = createFunctionInliningPass();
314   Builder.populateLTOPassManager(PM);
315 }
316
317 //===----------------------------------------------------------------------===//
318 // CodeGen-related helper functions.
319 //
320
321 static CodeGenOpt::Level GetCodeGenOptLevel() {
322   if (CodeGenOptLevel.getNumOccurrences())
323     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
324   if (OptLevelO1)
325     return CodeGenOpt::Less;
326   if (OptLevelO2)
327     return CodeGenOpt::Default;
328   if (OptLevelO3)
329     return CodeGenOpt::Aggressive;
330   return CodeGenOpt::None;
331 }
332
333 // Returns the TargetMachine instance or zero if no triple is provided.
334 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
335                                        StringRef FeaturesStr,
336                                        const TargetOptions &Options) {
337   std::string Error;
338   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
339                                                          Error);
340   // Some modules don't specify a triple, and this is okay.
341   if (!TheTarget) {
342     return nullptr;
343   }
344
345   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
346                                         FeaturesStr, Options, getRelocModel(),
347                                         CMModel, GetCodeGenOptLevel());
348 }
349
350 #ifdef LINK_POLLY_INTO_TOOLS
351 namespace polly {
352 void initializePollyPasses(llvm::PassRegistry &Registry);
353 }
354 #endif
355
356 //===----------------------------------------------------------------------===//
357 // main for opt
358 //
359 int main(int argc, char **argv) {
360   sys::PrintStackTraceOnErrorSignal(argv[0]);
361   llvm::PrettyStackTraceProgram X(argc, argv);
362
363   // Enable debug stream buffering.
364   EnableDebugBuffering = true;
365
366   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
367   LLVMContext Context;
368
369   InitializeAllTargets();
370   InitializeAllTargetMCs();
371   InitializeAllAsmPrinters();
372   InitializeAllAsmParsers();
373
374   // Initialize passes
375   PassRegistry &Registry = *PassRegistry::getPassRegistry();
376   initializeCore(Registry);
377   initializeCoroutines(Registry);
378   initializeScalarOpts(Registry);
379   initializeObjCARCOpts(Registry);
380   initializeVectorization(Registry);
381   initializeIPO(Registry);
382   initializeAnalysis(Registry);
383   initializeTransformUtils(Registry);
384   initializeInstCombine(Registry);
385   initializeInstrumentation(Registry);
386   initializeTarget(Registry);
387   // For codegen passes, only passes that do IR to IR transformation are
388   // supported.
389   initializeScalarizeMaskedMemIntrinPass(Registry);
390   initializeCodeGenPreparePass(Registry);
391   initializeAtomicExpandPass(Registry);
392   initializeRewriteSymbolsLegacyPassPass(Registry);
393   initializeWinEHPreparePass(Registry);
394   initializeDwarfEHPreparePass(Registry);
395   initializeSafeStackLegacyPassPass(Registry);
396   initializeSjLjEHPreparePass(Registry);
397   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
398   initializeGlobalMergePass(Registry);
399   initializeInterleavedAccessPass(Registry);
400   initializeCountingFunctionInserterPass(Registry);
401   initializeUnreachableBlockElimLegacyPassPass(Registry);
402   initializeExpandReductionsPass(Registry);
403
404 #ifdef LINK_POLLY_INTO_TOOLS
405   polly::initializePollyPasses(Registry);
406 #endif
407
408   cl::ParseCommandLineOptions(argc, argv,
409     "llvm .bc -> .bc modular optimizer and analysis printer\n");
410
411   if (AnalyzeOnly && NoOutput) {
412     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
413     return 1;
414   }
415
416   SMDiagnostic Err;
417
418   Context.setDiscardValueNames(DiscardValueNames);
419   if (!DisableDITypeMap)
420     Context.enableDebugTypeODRUniquing();
421
422   if (PassRemarksWithHotness)
423     Context.setDiagnosticHotnessRequested(true);
424
425   std::unique_ptr<tool_output_file> YamlFile;
426   if (RemarksFilename != "") {
427     std::error_code EC;
428     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
429                                                    sys::fs::F_None);
430     if (EC) {
431       errs() << EC.message() << '\n';
432       return 1;
433     }
434     Context.setDiagnosticsOutputFile(
435         llvm::make_unique<yaml::Output>(YamlFile->os()));
436   }
437
438   // Load the input module...
439   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
440
441   if (!M) {
442     Err.print(argv[0], errs());
443     return 1;
444   }
445
446   // Strip debug info before running the verifier.
447   if (StripDebug)
448     StripDebugInfo(*M);
449
450   // Immediately run the verifier to catch any problems before starting up the
451   // pass pipelines.  Otherwise we can crash on broken code during
452   // doInitialization().
453   if (!NoVerify && verifyModule(*M, &errs())) {
454     errs() << argv[0] << ": " << InputFilename
455            << ": error: input module is broken!\n";
456     return 1;
457   }
458
459   // If we are supposed to override the target triple or data layout, do so now.
460   if (!TargetTriple.empty())
461     M->setTargetTriple(Triple::normalize(TargetTriple));
462   if (!ClDataLayout.empty())
463     M->setDataLayout(ClDataLayout);
464
465   // Figure out what stream we are supposed to write to...
466   std::unique_ptr<tool_output_file> Out;
467   std::unique_ptr<tool_output_file> ThinLinkOut;
468   if (NoOutput) {
469     if (!OutputFilename.empty())
470       errs() << "WARNING: The -o (output filename) option is ignored when\n"
471                 "the --disable-output option is used.\n";
472   } else {
473     // Default to standard output.
474     if (OutputFilename.empty())
475       OutputFilename = "-";
476
477     std::error_code EC;
478     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
479     if (EC) {
480       errs() << EC.message() << '\n';
481       return 1;
482     }
483
484     if (!ThinLinkBitcodeFile.empty()) {
485       ThinLinkOut.reset(
486           new tool_output_file(ThinLinkBitcodeFile, EC, sys::fs::F_None));
487       if (EC) {
488         errs() << EC.message() << '\n';
489         return 1;
490       }
491     }
492   }
493
494   Triple ModuleTriple(M->getTargetTriple());
495   std::string CPUStr, FeaturesStr;
496   TargetMachine *Machine = nullptr;
497   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
498
499   if (ModuleTriple.getArch()) {
500     CPUStr = getCPUStr();
501     FeaturesStr = getFeaturesStr();
502     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
503   }
504
505   std::unique_ptr<TargetMachine> TM(Machine);
506
507   // Override function attributes based on CPUStr, FeaturesStr, and command line
508   // flags.
509   setFunctionAttributes(CPUStr, FeaturesStr, *M);
510
511   // If the output is set to be emitted to standard out, and standard out is a
512   // console, print out a warning message and refuse to do it.  We don't
513   // impress anyone by spewing tons of binary goo to a terminal.
514   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
515     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
516       NoOutput = true;
517
518   if (PassPipeline.getNumOccurrences() > 0) {
519     OutputKind OK = OK_NoOutput;
520     if (!NoOutput)
521       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
522
523     VerifierKind VK = VK_VerifyInAndOut;
524     if (NoVerify)
525       VK = VK_NoVerifier;
526     else if (VerifyEach)
527       VK = VK_VerifyEachPass;
528
529     // The user has asked to use the new pass manager and provided a pipeline
530     // string. Hand off the rest of the functionality to the new code for that
531     // layer.
532     return runPassPipeline(argv[0], *M, TM.get(), Out.get(),
533                            PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
534                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
535                            EmitModuleHash)
536                ? 0
537                : 1;
538   }
539
540   // Create a PassManager to hold and optimize the collection of passes we are
541   // about to build.
542   //
543   legacy::PassManager Passes;
544
545   // Add an appropriate TargetLibraryInfo pass for the module's triple.
546   TargetLibraryInfoImpl TLII(ModuleTriple);
547
548   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
549   if (DisableSimplifyLibCalls)
550     TLII.disableAllFunctions();
551   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
552
553   // Add internal analysis passes from the target machine.
554   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
555                                                      : TargetIRAnalysis()));
556
557   std::unique_ptr<legacy::FunctionPassManager> FPasses;
558   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
559       OptLevelO3) {
560     FPasses.reset(new legacy::FunctionPassManager(M.get()));
561     FPasses->add(createTargetTransformInfoWrapperPass(
562         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
563   }
564
565   if (PrintBreakpoints) {
566     // Default to standard output.
567     if (!Out) {
568       if (OutputFilename.empty())
569         OutputFilename = "-";
570
571       std::error_code EC;
572       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
573                                                 sys::fs::F_None);
574       if (EC) {
575         errs() << EC.message() << '\n';
576         return 1;
577       }
578     }
579     Passes.add(createBreakpointPrinter(Out->os()));
580     NoOutput = true;
581   }
582
583   if (TM) {
584     // FIXME: We should dyn_cast this when supported.
585     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
586     Pass *TPC = LTM.createPassConfig(Passes);
587     Passes.add(TPC);
588   }
589
590   // Create a new optimization pass for each one specified on the command line
591   for (unsigned i = 0; i < PassList.size(); ++i) {
592     if (StandardLinkOpts &&
593         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
594       AddStandardLinkPasses(Passes);
595       StandardLinkOpts = false;
596     }
597
598     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
599       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
600       OptLevelO0 = false;
601     }
602
603     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
604       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
605       OptLevelO1 = false;
606     }
607
608     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
609       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
610       OptLevelO2 = false;
611     }
612
613     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
614       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
615       OptLevelOs = false;
616     }
617
618     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
619       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
620       OptLevelOz = false;
621     }
622
623     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
624       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
625       OptLevelO3 = false;
626     }
627
628     const PassInfo *PassInf = PassList[i];
629     Pass *P = nullptr;
630     if (PassInf->getNormalCtor())
631       P = PassInf->getNormalCtor()();
632     else
633       errs() << argv[0] << ": cannot create pass: "
634              << PassInf->getPassName() << "\n";
635     if (P) {
636       PassKind Kind = P->getPassKind();
637       addPass(Passes, P);
638
639       if (AnalyzeOnly) {
640         switch (Kind) {
641         case PT_BasicBlock:
642           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
643           break;
644         case PT_Region:
645           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
646           break;
647         case PT_Loop:
648           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
649           break;
650         case PT_Function:
651           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
652           break;
653         case PT_CallGraphSCC:
654           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
655           break;
656         default:
657           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
658           break;
659         }
660       }
661     }
662
663     if (PrintEachXForm)
664       Passes.add(
665           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
666   }
667
668   if (StandardLinkOpts) {
669     AddStandardLinkPasses(Passes);
670     StandardLinkOpts = false;
671   }
672
673   if (OptLevelO0)
674     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
675
676   if (OptLevelO1)
677     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
678
679   if (OptLevelO2)
680     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
681
682   if (OptLevelOs)
683     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
684
685   if (OptLevelOz)
686     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
687
688   if (OptLevelO3)
689     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
690
691   if (FPasses) {
692     FPasses->doInitialization();
693     for (Function &F : *M)
694       FPasses->run(F);
695     FPasses->doFinalization();
696   }
697
698   // Check that the module is well formed on completion of optimization
699   if (!NoVerify && !VerifyEach)
700     Passes.add(createVerifierPass());
701
702   // In run twice mode, we want to make sure the output is bit-by-bit
703   // equivalent if we run the pass manager again, so setup two buffers and
704   // a stream to write to them. Note that llc does something similar and it
705   // may be worth to abstract this out in the future.
706   SmallVector<char, 0> Buffer;
707   SmallVector<char, 0> CompileTwiceBuffer;
708   std::unique_ptr<raw_svector_ostream> BOS;
709   raw_ostream *OS = nullptr;
710
711   // Write bitcode or assembly to the output as the last step...
712   if (!NoOutput && !AnalyzeOnly) {
713     assert(Out);
714     OS = &Out->os();
715     if (RunTwice) {
716       BOS = make_unique<raw_svector_ostream>(Buffer);
717       OS = BOS.get();
718     }
719     if (OutputAssembly) {
720       if (EmitSummaryIndex)
721         report_fatal_error("Text output is incompatible with -module-summary");
722       if (EmitModuleHash)
723         report_fatal_error("Text output is incompatible with -module-hash");
724       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
725     } else if (OutputThinLTOBC)
726       Passes.add(createWriteThinLTOBitcodePass(
727           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
728     else
729       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
730                                          EmitSummaryIndex, EmitModuleHash));
731   }
732
733   // Before executing passes, print the final values of the LLVM options.
734   cl::PrintOptionValues();
735
736   // If requested, run all passes again with the same pass manager to catch
737   // bugs caused by persistent state in the passes
738   if (RunTwice) {
739       std::unique_ptr<Module> M2(CloneModule(M.get()));
740       Passes.run(*M2);
741       CompileTwiceBuffer = Buffer;
742       Buffer.clear();
743   }
744
745   // Now that we have all of the passes ready, run them.
746   Passes.run(*M);
747
748   // Compare the two outputs and make sure they're the same
749   if (RunTwice) {
750     assert(Out);
751     if (Buffer.size() != CompileTwiceBuffer.size() ||
752         (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
753          0)) {
754       errs() << "Running the pass manager twice changed the output.\n"
755                 "Writing the result of the second run to the specified output.\n"
756                 "To generate the one-run comparison binary, just run without\n"
757                 "the compile-twice option\n";
758       Out->os() << BOS->str();
759       Out->keep();
760       if (YamlFile)
761         YamlFile->keep();
762       return 1;
763     }
764     Out->os() << BOS->str();
765   }
766
767   // Declare success.
768   if (!NoOutput || PrintBreakpoints)
769     Out->keep();
770
771   if (YamlFile)
772     YamlFile->keep();
773
774   if (ThinLinkOut)
775     ThinLinkOut->keep();
776
777   return 0;
778 }