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