xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision ca5793ea)
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/Target/TargetMachine.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/Utils/Cloning.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 run the verifier"), 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<unsigned>
140 CodeGenOptLevel("codegen-opt-level",
141                 cl::desc("Override optimization level for codegen hooks"));
142 
143 static cl::opt<std::string>
144 TargetTriple("mtriple", cl::desc("Override target triple for module"));
145 
146 static cl::opt<bool>
147 UnitAtATime("funit-at-a-time",
148             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
149             cl::init(true));
150 
151 static cl::opt<bool>
152 DisableLoopUnrolling("disable-loop-unrolling",
153                      cl::desc("Disable loop unrolling in all relevant passes"),
154                      cl::init(false));
155 static cl::opt<bool>
156 DisableLoopVectorization("disable-loop-vectorization",
157                      cl::desc("Disable the loop vectorization pass"),
158                      cl::init(false));
159 
160 static cl::opt<bool>
161 DisableSLPVectorization("disable-slp-vectorization",
162                         cl::desc("Disable the slp vectorization pass"),
163                         cl::init(false));
164 
165 static cl::opt<bool> EmitSummaryIndex("module-summary",
166                                       cl::desc("Emit module summary index"),
167                                       cl::init(false));
168 
169 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
170                                     cl::init(false));
171 
172 static cl::opt<bool>
173 DisableSimplifyLibCalls("disable-simplify-libcalls",
174                         cl::desc("Disable simplify-libcalls"));
175 
176 static cl::opt<bool>
177 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
178 
179 static cl::alias
180 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
181 
182 static cl::opt<bool>
183 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
184 
185 static cl::opt<bool>
186 PrintBreakpoints("print-breakpoints-for-testing",
187                  cl::desc("Print select breakpoints location for testing"));
188 
189 static cl::opt<std::string>
190 DefaultDataLayout("default-data-layout",
191           cl::desc("data layout string to use if not specified by module"),
192           cl::value_desc("layout-string"), cl::init(""));
193 
194 static cl::opt<bool> PreserveBitcodeUseListOrder(
195     "preserve-bc-uselistorder",
196     cl::desc("Preserve use-list order when writing LLVM bitcode."),
197     cl::init(true), cl::Hidden);
198 
199 static cl::opt<bool> PreserveAssemblyUseListOrder(
200     "preserve-ll-uselistorder",
201     cl::desc("Preserve use-list order when writing LLVM assembly."),
202     cl::init(false), cl::Hidden);
203 
204 static cl::opt<bool>
205     RunTwice("run-twice",
206              cl::desc("Run all passes twice, re-using the same pass manager."),
207              cl::init(false), cl::Hidden);
208 
209 static cl::opt<bool> DiscardValueNames(
210     "discard-value-names",
211     cl::desc("Discard names from Value (other than GlobalValue)."),
212     cl::init(false), cl::Hidden);
213 
214 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
215   // Add the pass to the pass manager...
216   PM.add(P);
217 
218   // If we are verifying all of the intermediate steps, add the verifier...
219   if (VerifyEach)
220     PM.add(createVerifierPass());
221 }
222 
223 /// This routine adds optimization passes based on selected optimization level,
224 /// OptLevel.
225 ///
226 /// OptLevel - Optimization Level
227 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
228                                   legacy::FunctionPassManager &FPM,
229                                   unsigned OptLevel, unsigned SizeLevel) {
230   if (!NoVerify || VerifyEach)
231     FPM.add(createVerifierPass()); // Verify that input is correct
232 
233   PassManagerBuilder Builder;
234   Builder.OptLevel = OptLevel;
235   Builder.SizeLevel = SizeLevel;
236 
237   if (DisableInline) {
238     // No inlining pass
239   } else if (OptLevel > 1) {
240     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
241   } else {
242     Builder.Inliner = createAlwaysInlinerPass();
243   }
244   Builder.DisableUnitAtATime = !UnitAtATime;
245   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
246                                DisableLoopUnrolling : OptLevel == 0;
247 
248   // This is final, unless there is a #pragma vectorize enable
249   if (DisableLoopVectorization)
250     Builder.LoopVectorize = false;
251   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
252   else if (!Builder.LoopVectorize)
253     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
254 
255   // When #pragma vectorize is on for SLP, do the same as above
256   Builder.SLPVectorize =
257       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
258 
259   Builder.populateFunctionPassManager(FPM);
260   Builder.populateModulePassManager(MPM);
261 }
262 
263 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
264   PassManagerBuilder Builder;
265   Builder.VerifyInput = true;
266   if (DisableOptimizations)
267     Builder.OptLevel = 0;
268 
269   if (!DisableInline)
270     Builder.Inliner = createFunctionInliningPass();
271   Builder.populateLTOPassManager(PM);
272 }
273 
274 //===----------------------------------------------------------------------===//
275 // CodeGen-related helper functions.
276 //
277 
278 static CodeGenOpt::Level GetCodeGenOptLevel() {
279   if (CodeGenOptLevel.getNumOccurrences())
280     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
281   if (OptLevelO1)
282     return CodeGenOpt::Less;
283   if (OptLevelO2)
284     return CodeGenOpt::Default;
285   if (OptLevelO3)
286     return CodeGenOpt::Aggressive;
287   return CodeGenOpt::None;
288 }
289 
290 // Returns the TargetMachine instance or zero if no triple is provided.
291 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
292                                        StringRef FeaturesStr,
293                                        const TargetOptions &Options) {
294   std::string Error;
295   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
296                                                          Error);
297   // Some modules don't specify a triple, and this is okay.
298   if (!TheTarget) {
299     return nullptr;
300   }
301 
302   return TheTarget->createTargetMachine(TheTriple.getTriple(),
303                                         CPUStr, FeaturesStr, Options,
304                                         RelocModel, CMModel,
305                                         GetCodeGenOptLevel());
306 }
307 
308 #ifdef LINK_POLLY_INTO_TOOLS
309 namespace polly {
310 void initializePollyPasses(llvm::PassRegistry &Registry);
311 }
312 #endif
313 
314 //===----------------------------------------------------------------------===//
315 // main for opt
316 //
317 int main(int argc, char **argv) {
318   sys::PrintStackTraceOnErrorSignal();
319   llvm::PrettyStackTraceProgram X(argc, argv);
320 
321   // Enable debug stream buffering.
322   EnableDebugBuffering = true;
323 
324   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
325   LLVMContext Context;
326 
327   InitializeAllTargets();
328   InitializeAllTargetMCs();
329   InitializeAllAsmPrinters();
330 
331   // Initialize passes
332   PassRegistry &Registry = *PassRegistry::getPassRegistry();
333   initializeCore(Registry);
334   initializeScalarOpts(Registry);
335   initializeObjCARCOpts(Registry);
336   initializeVectorization(Registry);
337   initializeIPO(Registry);
338   initializeAnalysis(Registry);
339   initializeTransformUtils(Registry);
340   initializeInstCombine(Registry);
341   initializeInstrumentation(Registry);
342   initializeTarget(Registry);
343   // For codegen passes, only passes that do IR to IR transformation are
344   // supported.
345   initializeCodeGenPreparePass(Registry);
346   initializeAtomicExpandPass(Registry);
347   initializeRewriteSymbolsPass(Registry);
348   initializeWinEHPreparePass(Registry);
349   initializeDwarfEHPreparePass(Registry);
350   initializeSafeStackPass(Registry);
351   initializeSjLjEHPreparePass(Registry);
352 
353 #ifdef LINK_POLLY_INTO_TOOLS
354   polly::initializePollyPasses(Registry);
355 #endif
356 
357   cl::ParseCommandLineOptions(argc, argv,
358     "llvm .bc -> .bc modular optimizer and analysis printer\n");
359 
360   if (AnalyzeOnly && NoOutput) {
361     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
362     return 1;
363   }
364 
365   SMDiagnostic Err;
366 
367   Context.setDiscardValueNames(DiscardValueNames);
368 
369   // Load the input module...
370   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
371 
372   if (!M) {
373     Err.print(argv[0], errs());
374     return 1;
375   }
376 
377   // Strip debug info before running the verifier.
378   if (StripDebug)
379     StripDebugInfo(*M);
380 
381   // Immediately run the verifier to catch any problems before starting up the
382   // pass pipelines.  Otherwise we can crash on broken code during
383   // doInitialization().
384   if (!NoVerify && verifyModule(*M, &errs())) {
385     errs() << argv[0] << ": " << InputFilename
386            << ": error: input module is broken!\n";
387     return 1;
388   }
389 
390   // If we are supposed to override the target triple, do so now.
391   if (!TargetTriple.empty())
392     M->setTargetTriple(Triple::normalize(TargetTriple));
393 
394   // Figure out what stream we are supposed to write to...
395   std::unique_ptr<tool_output_file> Out;
396   if (NoOutput) {
397     if (!OutputFilename.empty())
398       errs() << "WARNING: The -o (output filename) option is ignored when\n"
399                 "the --disable-output option is used.\n";
400   } else {
401     // Default to standard output.
402     if (OutputFilename.empty())
403       OutputFilename = "-";
404 
405     std::error_code EC;
406     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
407     if (EC) {
408       errs() << EC.message() << '\n';
409       return 1;
410     }
411   }
412 
413   Triple ModuleTriple(M->getTargetTriple());
414   std::string CPUStr, FeaturesStr;
415   TargetMachine *Machine = nullptr;
416   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
417 
418   if (ModuleTriple.getArch()) {
419     CPUStr = getCPUStr();
420     FeaturesStr = getFeaturesStr();
421     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
422   }
423 
424   std::unique_ptr<TargetMachine> TM(Machine);
425 
426   // Override function attributes based on CPUStr, FeaturesStr, and command line
427   // flags.
428   setFunctionAttributes(CPUStr, FeaturesStr, *M);
429 
430   // If the output is set to be emitted to standard out, and standard out is a
431   // console, print out a warning message and refuse to do it.  We don't
432   // impress anyone by spewing tons of binary goo to a terminal.
433   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
434     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
435       NoOutput = true;
436 
437   if (PassPipeline.getNumOccurrences() > 0) {
438     OutputKind OK = OK_NoOutput;
439     if (!NoOutput)
440       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
441 
442     VerifierKind VK = VK_VerifyInAndOut;
443     if (NoVerify)
444       VK = VK_NoVerifier;
445     else if (VerifyEach)
446       VK = VK_VerifyEachPass;
447 
448     // The user has asked to use the new pass manager and provided a pipeline
449     // string. Hand off the rest of the functionality to the new code for that
450     // layer.
451     return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
452                            PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
453                            PreserveBitcodeUseListOrder)
454                ? 0
455                : 1;
456   }
457 
458   // Create a PassManager to hold and optimize the collection of passes we are
459   // about to build.
460   //
461   legacy::PassManager Passes;
462 
463   // Add an appropriate TargetLibraryInfo pass for the module's triple.
464   TargetLibraryInfoImpl TLII(ModuleTriple);
465 
466   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
467   if (DisableSimplifyLibCalls)
468     TLII.disableAllFunctions();
469   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
470 
471   // Add an appropriate DataLayout instance for this module.
472   const DataLayout &DL = M->getDataLayout();
473   if (DL.isDefault() && !DefaultDataLayout.empty()) {
474     M->setDataLayout(DefaultDataLayout);
475   }
476 
477   // Add internal analysis passes from the target machine.
478   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
479                                                      : TargetIRAnalysis()));
480 
481   std::unique_ptr<legacy::FunctionPassManager> FPasses;
482   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
483     FPasses.reset(new legacy::FunctionPassManager(M.get()));
484     FPasses->add(createTargetTransformInfoWrapperPass(
485         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
486   }
487 
488   if (PrintBreakpoints) {
489     // Default to standard output.
490     if (!Out) {
491       if (OutputFilename.empty())
492         OutputFilename = "-";
493 
494       std::error_code EC;
495       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
496                                                 sys::fs::F_None);
497       if (EC) {
498         errs() << EC.message() << '\n';
499         return 1;
500       }
501     }
502     Passes.add(createBreakpointPrinter(Out->os()));
503     NoOutput = true;
504   }
505 
506   // Create a new optimization pass for each one specified on the command line
507   for (unsigned i = 0; i < PassList.size(); ++i) {
508     if (StandardLinkOpts &&
509         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
510       AddStandardLinkPasses(Passes);
511       StandardLinkOpts = false;
512     }
513 
514     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
515       AddOptimizationPasses(Passes, *FPasses, 1, 0);
516       OptLevelO1 = false;
517     }
518 
519     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
520       AddOptimizationPasses(Passes, *FPasses, 2, 0);
521       OptLevelO2 = false;
522     }
523 
524     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
525       AddOptimizationPasses(Passes, *FPasses, 2, 1);
526       OptLevelOs = false;
527     }
528 
529     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
530       AddOptimizationPasses(Passes, *FPasses, 2, 2);
531       OptLevelOz = false;
532     }
533 
534     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
535       AddOptimizationPasses(Passes, *FPasses, 3, 0);
536       OptLevelO3 = false;
537     }
538 
539     const PassInfo *PassInf = PassList[i];
540     Pass *P = nullptr;
541     if (PassInf->getTargetMachineCtor())
542       P = PassInf->getTargetMachineCtor()(TM.get());
543     else if (PassInf->getNormalCtor())
544       P = PassInf->getNormalCtor()();
545     else
546       errs() << argv[0] << ": cannot create pass: "
547              << PassInf->getPassName() << "\n";
548     if (P) {
549       PassKind Kind = P->getPassKind();
550       addPass(Passes, P);
551 
552       if (AnalyzeOnly) {
553         switch (Kind) {
554         case PT_BasicBlock:
555           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
556           break;
557         case PT_Region:
558           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
559           break;
560         case PT_Loop:
561           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
562           break;
563         case PT_Function:
564           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
565           break;
566         case PT_CallGraphSCC:
567           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
568           break;
569         default:
570           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
571           break;
572         }
573       }
574     }
575 
576     if (PrintEachXForm)
577       Passes.add(
578           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
579   }
580 
581   if (StandardLinkOpts) {
582     AddStandardLinkPasses(Passes);
583     StandardLinkOpts = false;
584   }
585 
586   if (OptLevelO1)
587     AddOptimizationPasses(Passes, *FPasses, 1, 0);
588 
589   if (OptLevelO2)
590     AddOptimizationPasses(Passes, *FPasses, 2, 0);
591 
592   if (OptLevelOs)
593     AddOptimizationPasses(Passes, *FPasses, 2, 1);
594 
595   if (OptLevelOz)
596     AddOptimizationPasses(Passes, *FPasses, 2, 2);
597 
598   if (OptLevelO3)
599     AddOptimizationPasses(Passes, *FPasses, 3, 0);
600 
601   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
602     FPasses->doInitialization();
603     for (Function &F : *M)
604       FPasses->run(F);
605     FPasses->doFinalization();
606   }
607 
608   // Check that the module is well formed on completion of optimization
609   if (!NoVerify && !VerifyEach)
610     Passes.add(createVerifierPass());
611 
612   // In run twice mode, we want to make sure the output is bit-by-bit
613   // equivalent if we run the pass manager again, so setup two buffers and
614   // a stream to write to them. Note that llc does something similar and it
615   // may be worth to abstract this out in the future.
616   SmallVector<char, 0> Buffer;
617   SmallVector<char, 0> CompileTwiceBuffer;
618   std::unique_ptr<raw_svector_ostream> BOS;
619   raw_ostream *OS = nullptr;
620 
621   // Write bitcode or assembly to the output as the last step...
622   if (!NoOutput && !AnalyzeOnly) {
623     assert(Out);
624     OS = &Out->os();
625     if (RunTwice) {
626       BOS = make_unique<raw_svector_ostream>(Buffer);
627       OS = BOS.get();
628     }
629     if (OutputAssembly) {
630       if (EmitSummaryIndex)
631         report_fatal_error("Text output is incompatible with -module-summary");
632       if (EmitModuleHash)
633         report_fatal_error("Text output is incompatible with -module-hash");
634       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
635     } else
636       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
637                                          EmitSummaryIndex, EmitModuleHash));
638   }
639 
640   // Before executing passes, print the final values of the LLVM options.
641   cl::PrintOptionValues();
642 
643   // If requested, run all passes again with the same pass manager to catch
644   // bugs caused by persistent state in the passes
645   if (RunTwice) {
646       std::unique_ptr<Module> M2(CloneModule(M.get()));
647       Passes.run(*M2);
648       CompileTwiceBuffer = Buffer;
649       Buffer.clear();
650   }
651 
652   // Now that we have all of the passes ready, run them.
653   Passes.run(*M);
654 
655   // Compare the two outputs and make sure they're the same
656   if (RunTwice) {
657     assert(Out);
658     if (Buffer.size() != CompileTwiceBuffer.size() ||
659         (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
660          0)) {
661       errs() << "Running the pass manager twice changed the output.\n"
662                 "Writing the result of the second run to the specified output.\n"
663                 "To generate the one-run comparison binary, just run without\n"
664                 "the compile-twice option\n";
665       Out->os() << BOS->str();
666       Out->keep();
667       return 1;
668     }
669     Out->os() << BOS->str();
670   }
671 
672   // Declare success.
673   if (!NoOutput || PrintBreakpoints)
674     Out->keep();
675 
676   return 0;
677 }
678