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