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