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