]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llc/llc.cpp
MFV r316877: 7571 non-present readonly numeric ZFS props do not have default value
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llc / llc.cpp
1 //===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 // This is the llc code generator driver. It provides a convenient
11 // command-line interface for generating native assembly-language code
12 // or C code, given LLVM bitcode.
13 //
14 //===----------------------------------------------------------------------===//
15
16
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/CodeGen/CommandFlags.h"
21 #include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
22 #include "llvm/CodeGen/LinkAllCodegenComponents.h"
23 #include "llvm/CodeGen/MIRParser/MIRParser.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DiagnosticInfo.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/FormattedStream.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/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetSubtargetInfo.h"
53 #include "llvm/Transforms/Utils/Cloning.h"
54 #include <memory>
55 using namespace llvm;
56
57 // General options for llc.  Other pass-specific options are specified
58 // within the corresponding llc passes, and target-specific options
59 // and back-end code generation options are specified with the target machine.
60 //
61 static cl::opt<std::string>
62 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
63
64 static cl::opt<std::string>
65 InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
66
67 static cl::opt<std::string>
68 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
69
70 static cl::opt<unsigned>
71 TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
72                  cl::value_desc("N"),
73                  cl::desc("Repeat compilation N times for timing"));
74
75 static cl::opt<bool>
76 NoIntegratedAssembler("no-integrated-as", cl::Hidden,
77                       cl::desc("Disable integrated assembler"));
78
79 static cl::opt<bool>
80     PreserveComments("preserve-as-comments", cl::Hidden,
81                      cl::desc("Preserve Comments in outputted assembly"),
82                      cl::init(true));
83
84 // Determine optimization level.
85 static cl::opt<char>
86 OptLevel("O",
87          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
88                   "(default = '-O2')"),
89          cl::Prefix,
90          cl::ZeroOrMore,
91          cl::init(' '));
92
93 static cl::opt<std::string>
94 TargetTriple("mtriple", cl::desc("Override target triple for module"));
95
96 static cl::opt<std::string> SplitDwarfFile(
97     "split-dwarf-file",
98     cl::desc(
99         "Specify the name of the .dwo file to encode in the DWARF output"));
100
101 static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
102                               cl::desc("Do not verify input module"));
103
104 static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
105                                              cl::desc("Disable simplify-libcalls"));
106
107 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
108                                     cl::desc("Show encoding in .s output"));
109
110 static cl::opt<bool> EnableDwarfDirectory(
111     "enable-dwarf-directory", cl::Hidden,
112     cl::desc("Use .file directives with an explicit directory."));
113
114 static cl::opt<bool> AsmVerbose("asm-verbose",
115                                 cl::desc("Add comments to directives."),
116                                 cl::init(true));
117
118 static cl::opt<bool>
119     CompileTwice("compile-twice", cl::Hidden,
120                  cl::desc("Run everything twice, re-using the same pass "
121                           "manager and verify the result is the same."),
122                  cl::init(false));
123
124 static cl::opt<bool> DiscardValueNames(
125     "discard-value-names",
126     cl::desc("Discard names from Value (other than GlobalValue)."),
127     cl::init(false), cl::Hidden);
128
129 static cl::opt<std::string> StopBefore("stop-before",
130     cl::desc("Stop compilation before a specific pass"),
131     cl::value_desc("pass-name"), cl::init(""));
132
133 static cl::opt<std::string> StopAfter("stop-after",
134     cl::desc("Stop compilation after a specific pass"),
135     cl::value_desc("pass-name"), cl::init(""));
136
137 static cl::opt<std::string> StartBefore("start-before",
138     cl::desc("Resume compilation before a specific pass"),
139     cl::value_desc("pass-name"), cl::init(""));
140
141 static cl::opt<std::string> StartAfter("start-after",
142     cl::desc("Resume compilation after a specific pass"),
143     cl::value_desc("pass-name"), cl::init(""));
144
145 static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
146
147 static cl::opt<bool> PassRemarksWithHotness(
148     "pass-remarks-with-hotness",
149     cl::desc("With PGO, include profile count in optimization remarks"),
150     cl::Hidden);
151
152 static cl::opt<unsigned> PassRemarksHotnessThreshold(
153     "pass-remarks-hotness-threshold",
154     cl::desc("Minimum profile count required for an optimization remark to be output"),
155     cl::Hidden);
156
157 static cl::opt<std::string>
158     RemarksFilename("pass-remarks-output",
159                     cl::desc("YAML output filename for pass remarks"),
160                     cl::value_desc("filename"));
161
162 namespace {
163 static ManagedStatic<std::vector<std::string>> RunPassNames;
164
165 struct RunPassOption {
166   void operator=(const std::string &Val) const {
167     if (Val.empty())
168       return;
169     SmallVector<StringRef, 8> PassNames;
170     StringRef(Val).split(PassNames, ',', -1, false);
171     for (auto PassName : PassNames)
172       RunPassNames->push_back(PassName);
173   }
174 };
175 }
176
177 static RunPassOption RunPassOpt;
178
179 static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
180     "run-pass",
181     cl::desc("Run compiler only for specified passes (comma separated list)"),
182     cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
183
184 static int compileModule(char **, LLVMContext &);
185
186 static std::unique_ptr<tool_output_file>
187 GetOutputStream(const char *TargetName, Triple::OSType OS,
188                 const char *ProgName) {
189   // If we don't yet have an output filename, make one.
190   if (OutputFilename.empty()) {
191     if (InputFilename == "-")
192       OutputFilename = "-";
193     else {
194       // If InputFilename ends in .bc or .ll, remove it.
195       StringRef IFN = InputFilename;
196       if (IFN.endswith(".bc") || IFN.endswith(".ll"))
197         OutputFilename = IFN.drop_back(3);
198       else if (IFN.endswith(".mir"))
199         OutputFilename = IFN.drop_back(4);
200       else
201         OutputFilename = IFN;
202
203       switch (FileType) {
204       case TargetMachine::CGFT_AssemblyFile:
205         if (TargetName[0] == 'c') {
206           if (TargetName[1] == 0)
207             OutputFilename += ".cbe.c";
208           else if (TargetName[1] == 'p' && TargetName[2] == 'p')
209             OutputFilename += ".cpp";
210           else
211             OutputFilename += ".s";
212         } else
213           OutputFilename += ".s";
214         break;
215       case TargetMachine::CGFT_ObjectFile:
216         if (OS == Triple::Win32)
217           OutputFilename += ".obj";
218         else
219           OutputFilename += ".o";
220         break;
221       case TargetMachine::CGFT_Null:
222         OutputFilename += ".null";
223         break;
224       }
225     }
226   }
227
228   // Decide if we need "binary" output.
229   bool Binary = false;
230   switch (FileType) {
231   case TargetMachine::CGFT_AssemblyFile:
232     break;
233   case TargetMachine::CGFT_ObjectFile:
234   case TargetMachine::CGFT_Null:
235     Binary = true;
236     break;
237   }
238
239   // Open the file.
240   std::error_code EC;
241   sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
242   if (!Binary)
243     OpenFlags |= sys::fs::F_Text;
244   auto FDOut = llvm::make_unique<tool_output_file>(OutputFilename, EC,
245                                                    OpenFlags);
246   if (EC) {
247     errs() << EC.message() << '\n';
248     return nullptr;
249   }
250
251   return FDOut;
252 }
253
254 static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
255   bool *HasError = static_cast<bool *>(Context);
256   if (DI.getSeverity() == DS_Error)
257     *HasError = true;
258
259   if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
260     if (!Remark->isEnabled())
261       return;
262
263   DiagnosticPrinterRawOStream DP(errs());
264   errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
265   DI.print(DP);
266   errs() << "\n";
267 }
268
269 static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
270                                  unsigned LocCookie) {
271   bool *HasError = static_cast<bool *>(Context);
272   if (SMD.getKind() == SourceMgr::DK_Error)
273     *HasError = true;
274
275   SMD.print(nullptr, errs());
276
277   // For testing purposes, we print the LocCookie here.
278   if (LocCookie)
279     errs() << "note: !srcloc = " << LocCookie << "\n";
280 }
281
282 // main - Entry point for the llc compiler.
283 //
284 int main(int argc, char **argv) {
285   sys::PrintStackTraceOnErrorSignal(argv[0]);
286   PrettyStackTraceProgram X(argc, argv);
287
288   // Enable debug stream buffering.
289   EnableDebugBuffering = true;
290
291   LLVMContext Context;
292   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
293
294   // Initialize targets first, so that --version shows registered targets.
295   InitializeAllTargets();
296   InitializeAllTargetMCs();
297   InitializeAllAsmPrinters();
298   InitializeAllAsmParsers();
299
300   // Initialize codegen and IR passes used by llc so that the -print-after,
301   // -print-before, and -stop-after options work.
302   PassRegistry *Registry = PassRegistry::getPassRegistry();
303   initializeCore(*Registry);
304   initializeCodeGen(*Registry);
305   initializeLoopStrengthReducePass(*Registry);
306   initializeLowerIntrinsicsPass(*Registry);
307   initializeCountingFunctionInserterPass(*Registry);
308   initializeUnreachableBlockElimLegacyPassPass(*Registry);
309   initializeConstantHoistingLegacyPassPass(*Registry);
310   initializeScalarOpts(*Registry);
311   initializeVectorization(*Registry);
312   initializeScalarizeMaskedMemIntrinPass(*Registry);
313   initializeExpandReductionsPass(*Registry);
314
315   // Initialize debugging passes.
316   initializeScavengerTestPass(*Registry);
317
318   // Register the target printer for --version.
319   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
320
321   cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
322
323   Context.setDiscardValueNames(DiscardValueNames);
324
325   // Set a diagnostic handler that doesn't exit on the first error
326   bool HasError = false;
327   Context.setDiagnosticHandler(DiagnosticHandler, &HasError);
328   Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
329
330   if (PassRemarksWithHotness)
331     Context.setDiagnosticsHotnessRequested(true);
332
333   if (PassRemarksHotnessThreshold)
334     Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
335
336   std::unique_ptr<tool_output_file> YamlFile;
337   if (RemarksFilename != "") {
338     std::error_code EC;
339     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
340                                                    sys::fs::F_None);
341     if (EC) {
342       errs() << EC.message() << '\n';
343       return 1;
344     }
345     Context.setDiagnosticsOutputFile(
346         llvm::make_unique<yaml::Output>(YamlFile->os()));
347   }
348
349   if (InputLanguage != "" && InputLanguage != "ir" &&
350       InputLanguage != "mir") {
351     errs() << argv[0] << "Input language must be '', 'IR' or 'MIR'\n";
352     return 1;
353   }
354
355   // Compile the module TimeCompilations times to give better compile time
356   // metrics.
357   for (unsigned I = TimeCompilations; I; --I)
358     if (int RetVal = compileModule(argv, Context))
359       return RetVal;
360
361   if (YamlFile)
362     YamlFile->keep();
363   return 0;
364 }
365
366 static bool addPass(PassManagerBase &PM, const char *argv0,
367                     StringRef PassName, TargetPassConfig &TPC) {
368   if (PassName == "none")
369     return false;
370
371   const PassRegistry *PR = PassRegistry::getPassRegistry();
372   const PassInfo *PI = PR->getPassInfo(PassName);
373   if (!PI) {
374     errs() << argv0 << ": run-pass " << PassName << " is not registered.\n";
375     return true;
376   }
377
378   Pass *P;
379   if (PI->getNormalCtor())
380     P = PI->getNormalCtor()();
381   else {
382     errs() << argv0 << ": cannot create pass: " << PI->getPassName() << "\n";
383     return true;
384   }
385   std::string Banner = std::string("After ") + std::string(P->getPassName());
386   PM.add(P);
387   TPC.printAndVerify(Banner);
388
389   return false;
390 }
391
392 static AnalysisID getPassID(const char *argv0, const char *OptionName,
393                             StringRef PassName) {
394   if (PassName.empty())
395     return nullptr;
396
397   const PassRegistry &PR = *PassRegistry::getPassRegistry();
398   const PassInfo *PI = PR.getPassInfo(PassName);
399   if (!PI) {
400     errs() << argv0 << ": " << OptionName << " pass is not registered.\n";
401     exit(1);
402   }
403   return PI->getTypeInfo();
404 }
405
406 static int compileModule(char **argv, LLVMContext &Context) {
407   // Load the module to be compiled...
408   SMDiagnostic Err;
409   std::unique_ptr<Module> M;
410   std::unique_ptr<MIRParser> MIR;
411   Triple TheTriple;
412
413   bool SkipModule = MCPU == "help" ||
414                     (!MAttrs.empty() && MAttrs.front() == "help");
415
416   // If user just wants to list available options, skip module loading
417   if (!SkipModule) {
418     if (InputLanguage == "mir" ||
419         (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
420       MIR = createMIRParserFromFile(InputFilename, Err, Context);
421       if (MIR)
422         M = MIR->parseIRModule();
423     } else
424       M = parseIRFile(InputFilename, Err, Context);
425     if (!M) {
426       Err.print(argv[0], errs());
427       return 1;
428     }
429
430     // Verify module immediately to catch problems before doInitialization() is
431     // called on any passes.
432     if (!NoVerify && verifyModule(*M, &errs())) {
433       errs() << argv[0] << ": " << InputFilename
434              << ": error: input module is broken!\n";
435       return 1;
436     }
437
438     // If we are supposed to override the target triple, do so now.
439     if (!TargetTriple.empty())
440       M->setTargetTriple(Triple::normalize(TargetTriple));
441     TheTriple = Triple(M->getTargetTriple());
442   } else {
443     TheTriple = Triple(Triple::normalize(TargetTriple));
444   }
445
446   if (TheTriple.getTriple().empty())
447     TheTriple.setTriple(sys::getDefaultTargetTriple());
448
449   // Get the target specific parser.
450   std::string Error;
451   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
452                                                          Error);
453   if (!TheTarget) {
454     errs() << argv[0] << ": " << Error;
455     return 1;
456   }
457
458   std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
459
460   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
461   switch (OptLevel) {
462   default:
463     errs() << argv[0] << ": invalid optimization level.\n";
464     return 1;
465   case ' ': break;
466   case '0': OLvl = CodeGenOpt::None; break;
467   case '1': OLvl = CodeGenOpt::Less; break;
468   case '2': OLvl = CodeGenOpt::Default; break;
469   case '3': OLvl = CodeGenOpt::Aggressive; break;
470   }
471
472   TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
473   Options.DisableIntegratedAS = NoIntegratedAssembler;
474   Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
475   Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
476   Options.MCOptions.AsmVerbose = AsmVerbose;
477   Options.MCOptions.PreserveAsmComments = PreserveComments;
478   Options.MCOptions.IASSearchPaths = IncludeDirs;
479   Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
480
481   std::unique_ptr<TargetMachine> Target(
482       TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr, FeaturesStr,
483                                      Options, getRelocModel(), CMModel, OLvl));
484
485   assert(Target && "Could not allocate target machine!");
486
487   // If we don't have a module then just exit now. We do this down
488   // here since the CPU/Feature help is underneath the target machine
489   // creation.
490   if (SkipModule)
491     return 0;
492
493   assert(M && "Should have exited if we didn't have a module!");
494   if (FloatABIForCalls != FloatABI::Default)
495     Options.FloatABIType = FloatABIForCalls;
496
497   // Figure out where we are going to send the output.
498   std::unique_ptr<tool_output_file> Out =
499       GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
500   if (!Out) return 1;
501
502   // Build up all of the passes that we want to do to the module.
503   legacy::PassManager PM;
504
505   // Add an appropriate TargetLibraryInfo pass for the module's triple.
506   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
507
508   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
509   if (DisableSimplifyLibCalls)
510     TLII.disableAllFunctions();
511   PM.add(new TargetLibraryInfoWrapperPass(TLII));
512
513   // Add the target data from the target machine, if it exists, or the module.
514   M->setDataLayout(Target->createDataLayout());
515
516   // Override function attributes based on CPUStr, FeaturesStr, and command line
517   // flags.
518   setFunctionAttributes(CPUStr, FeaturesStr, *M);
519
520   if (RelaxAll.getNumOccurrences() > 0 &&
521       FileType != TargetMachine::CGFT_ObjectFile)
522     errs() << argv[0]
523              << ": warning: ignoring -mc-relax-all because filetype != obj";
524
525   {
526     raw_pwrite_stream *OS = &Out->os();
527
528     // Manually do the buffering rather than using buffer_ostream,
529     // so we can memcmp the contents in CompileTwice mode
530     SmallVector<char, 0> Buffer;
531     std::unique_ptr<raw_svector_ostream> BOS;
532     if ((FileType != TargetMachine::CGFT_AssemblyFile &&
533          !Out->os().supportsSeeking()) ||
534         CompileTwice) {
535       BOS = make_unique<raw_svector_ostream>(Buffer);
536       OS = BOS.get();
537     }
538
539     const char *argv0 = argv[0];
540     AnalysisID StartBeforeID = getPassID(argv0, "start-before", StartBefore);
541     AnalysisID StartAfterID = getPassID(argv0, "start-after", StartAfter);
542     AnalysisID StopAfterID = getPassID(argv0, "stop-after", StopAfter);
543     AnalysisID StopBeforeID = getPassID(argv0, "stop-before", StopBefore);
544     if (StartBeforeID && StartAfterID) {
545       errs() << argv0 << ": -start-before and -start-after specified!\n";
546       return 1;
547     }
548     if (StopBeforeID && StopAfterID) {
549       errs() << argv0 << ": -stop-before and -stop-after specified!\n";
550       return 1;
551     }
552
553     if (MIR) {
554       // Construct a custom pass pipeline that starts after instruction
555       // selection.
556       LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
557       TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
558       TPC.setDisableVerify(NoVerify);
559       PM.add(&TPC);
560       MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
561       if (MIR->parseMachineFunctions(*M, *MMI))
562         return 1;
563       PM.add(MMI);
564       TPC.printAndVerify("");
565
566       if (!RunPassNames->empty()) {
567         if (!StartAfter.empty() || !StopAfter.empty() || !StartBefore.empty() ||
568             !StopBefore.empty()) {
569           errs() << argv0 << ": start-after and/or stop-after passes are "
570                                "redundant when run-pass is specified.\n";
571           return 1;
572         }
573
574         for (const std::string &RunPassName : *RunPassNames) {
575           if (addPass(PM, argv0, RunPassName, TPC))
576             return 1;
577         }
578       } else {
579         TPC.setStartStopPasses(StartBeforeID, StartAfterID, StopBeforeID,
580                                StopAfterID);
581         TPC.addISelPasses();
582         TPC.addMachinePasses();
583       }
584       TPC.setInitialized();
585
586       if (!StopBefore.empty() || !StopAfter.empty() || !RunPassNames->empty()) {
587         PM.add(createPrintMIRPass(*OS));
588       } else if (LLVMTM.addAsmPrinter(PM, *OS, FileType, MMI->getContext())) {
589         errs() << argv0 << ": target does not support generation of this"
590                << " file type!\n";
591         return 1;
592       }
593       PM.add(createFreeMachineFunctionPass());
594     } else if (Target->addPassesToEmitFile(PM, *OS, FileType, NoVerify,
595                                            StartBeforeID, StartAfterID,
596                                            StopBeforeID, StopAfterID)) {
597       errs() << argv0 << ": target does not support generation of this"
598         << " file type!\n";
599       return 1;
600     }
601
602     // Before executing passes, print the final values of the LLVM options.
603     cl::PrintOptionValues();
604
605     // If requested, run the pass manager over the same module again,
606     // to catch any bugs due to persistent state in the passes. Note that
607     // opt has the same functionality, so it may be worth abstracting this out
608     // in the future.
609     SmallVector<char, 0> CompileTwiceBuffer;
610     if (CompileTwice) {
611       std::unique_ptr<Module> M2(llvm::CloneModule(M.get()));
612       PM.run(*M2);
613       CompileTwiceBuffer = Buffer;
614       Buffer.clear();
615     }
616
617     PM.run(*M);
618
619     auto HasError = *static_cast<bool *>(Context.getDiagnosticContext());
620     if (HasError)
621       return 1;
622
623     // Compare the two outputs and make sure they're the same
624     if (CompileTwice) {
625       if (Buffer.size() != CompileTwiceBuffer.size() ||
626           (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
627            0)) {
628         errs()
629             << "Running the pass manager twice changed the output.\n"
630                "Writing the result of the second run to the specified output\n"
631                "To generate the one-run comparison binary, just run without\n"
632                "the compile-twice option\n";
633         Out->os() << Buffer;
634         Out->keep();
635         return 1;
636       }
637     }
638
639     if (BOS) {
640       Out->os() << Buffer;
641     }
642   }
643
644   // Declare success.
645   Out->keep();
646
647   return 0;
648 }