llc.cpp revision 321369
11541Srgrimes//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
21541Srgrimes//
31541Srgrimes//                     The LLVM Compiler Infrastructure
41541Srgrimes//
51541Srgrimes// This file is distributed under the University of Illinois Open Source
61541Srgrimes// License. See LICENSE.TXT for details.
71541Srgrimes//
81541Srgrimes//===----------------------------------------------------------------------===//
91541Srgrimes//
101541Srgrimes// This is the llc code generator driver. It provides a convenient
111541Srgrimes// command-line interface for generating native assembly-language code
121541Srgrimes// or C code, given LLVM bitcode.
131541Srgrimes//
141541Srgrimes//===----------------------------------------------------------------------===//
151541Srgrimes
161541Srgrimes
171541Srgrimes#include "llvm/ADT/STLExtras.h"
181541Srgrimes#include "llvm/ADT/Triple.h"
191541Srgrimes#include "llvm/Analysis/TargetLibraryInfo.h"
201541Srgrimes#include "llvm/CodeGen/CommandFlags.h"
211541Srgrimes#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
221541Srgrimes#include "llvm/CodeGen/LinkAllCodegenComponents.h"
231541Srgrimes#include "llvm/CodeGen/MIRParser/MIRParser.h"
241541Srgrimes#include "llvm/CodeGen/MachineFunctionPass.h"
251541Srgrimes#include "llvm/CodeGen/MachineModuleInfo.h"
261541Srgrimes#include "llvm/CodeGen/TargetPassConfig.h"
271541Srgrimes#include "llvm/IR/DataLayout.h"
281541Srgrimes#include "llvm/IR/DiagnosticInfo.h"
291541Srgrimes#include "llvm/IR/DiagnosticPrinter.h"
301541Srgrimes#include "llvm/IR/IRPrintingPasses.h"
311541Srgrimes#include "llvm/IR/LLVMContext.h"
321541Srgrimes#include "llvm/IR/LegacyPassManager.h"
331541Srgrimes#include "llvm/IR/Module.h"
346348Swollman#include "llvm/IR/Verifier.h"
351541Srgrimes#include "llvm/IRReader/IRReader.h"
361541Srgrimes#include "llvm/MC/SubtargetFeature.h"
372169Spaul#include "llvm/Pass.h"
382169Spaul#include "llvm/Support/CommandLine.h"
392169Spaul#include "llvm/Support/Debug.h"
401541Srgrimes#include "llvm/Support/FileSystem.h"
416247Swollman#include "llvm/Support/FormattedStream.h"
426247Swollman#include "llvm/Support/Host.h"
431541Srgrimes#include "llvm/Support/ManagedStatic.h"
441541Srgrimes#include "llvm/Support/PluginLoader.h"
451541Srgrimes#include "llvm/Support/PrettyStackTrace.h"
461541Srgrimes#include "llvm/Support/Signals.h"
471541Srgrimes#include "llvm/Support/SourceMgr.h"
481541Srgrimes#include "llvm/Support/TargetRegistry.h"
491541Srgrimes#include "llvm/Support/TargetSelect.h"
501541Srgrimes#include "llvm/Support/ToolOutputFile.h"
511541Srgrimes#include "llvm/Target/TargetMachine.h"
521541Srgrimes#include "llvm/Target/TargetSubtargetInfo.h"
531541Srgrimes#include "llvm/Transforms/Utils/Cloning.h"
541541Srgrimes#include <memory>
551541Srgrimesusing namespace llvm;
561541Srgrimes
571541Srgrimes// General options for llc.  Other pass-specific options are specified
581541Srgrimes// within the corresponding llc passes, and target-specific options
591541Srgrimes// and back-end code generation options are specified with the target machine.
601541Srgrimes//
611541Srgrimesstatic cl::opt<std::string>
621541SrgrimesInputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
631541Srgrimes
641541Srgrimesstatic cl::opt<std::string>
651541SrgrimesInputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
661541Srgrimes
676247Swollmanstatic cl::opt<std::string>
686348SwollmanOutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
691541Srgrimes
701541Srgrimesstatic cl::opt<unsigned>
711541SrgrimesTimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
721541Srgrimes                 cl::value_desc("N"),
731541Srgrimes                 cl::desc("Repeat compilation N times for timing"));
741541Srgrimes
751541Srgrimesstatic cl::opt<bool>
761541SrgrimesNoIntegratedAssembler("no-integrated-as", cl::Hidden,
771541Srgrimes                      cl::desc("Disable integrated assembler"));
781541Srgrimes
791541Srgrimesstatic cl::opt<bool>
801541Srgrimes    PreserveComments("preserve-as-comments", cl::Hidden,
811541Srgrimes                     cl::desc("Preserve Comments in outputted assembly"),
821541Srgrimes                     cl::init(true));
831541Srgrimes
841541Srgrimes// Determine optimization level.
851541Srgrimesstatic cl::opt<char>
866247SwollmanOptLevel("O",
871541Srgrimes         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
881541Srgrimes                  "(default = '-O2')"),
896247Swollman         cl::Prefix,
906247Swollman         cl::ZeroOrMore,
916247Swollman         cl::init(' '));
926247Swollman
936247Swollmanstatic cl::opt<std::string>
946247SwollmanTargetTriple("mtriple", cl::desc("Override target triple for module"));
956247Swollman
966247Swollmanstatic cl::opt<std::string> SplitDwarfFile(
971541Srgrimes    "split-dwarf-file",
981541Srgrimes    cl::desc(
991541Srgrimes        "Specify the name of the .dwo file to encode in the DWARF output"));
1001541Srgrimes
1011541Srgrimesstatic cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
1021541Srgrimes                              cl::desc("Do not verify input module"));
1031541Srgrimes
1041541Srgrimesstatic cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
1051541Srgrimes                                             cl::desc("Disable simplify-libcalls"));
1066247Swollman
1071541Srgrimesstatic cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
1081541Srgrimes                                    cl::desc("Show encoding in .s output"));
1091541Srgrimes
1106247Swollmanstatic cl::opt<bool> EnableDwarfDirectory(
1116247Swollman    "enable-dwarf-directory", cl::Hidden,
1126247Swollman    cl::desc("Use .file directives with an explicit directory."));
1136247Swollman
1141541Srgrimesstatic cl::opt<bool> AsmVerbose("asm-verbose",
1151541Srgrimes                                cl::desc("Add comments to directives."),
1161541Srgrimes                                cl::init(true));
1171541Srgrimes
1181541Srgrimesstatic cl::opt<bool>
1196247Swollman    CompileTwice("compile-twice", cl::Hidden,
1206247Swollman                 cl::desc("Run everything twice, re-using the same pass "
1212169Spaul                          "manager and verify the result is the same."),
1222169Spaul                 cl::init(false));
123
124static 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
129static 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
133static 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
137static 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
141static 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
145static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
146
147static cl::opt<bool> PassRemarksWithHotness(
148    "pass-remarks-with-hotness",
149    cl::desc("With PGO, include profile count in optimization remarks"),
150    cl::Hidden);
151
152static 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
157static cl::opt<std::string>
158    RemarksFilename("pass-remarks-output",
159                    cl::desc("YAML output filename for pass remarks"),
160                    cl::value_desc("filename"));
161
162namespace {
163static ManagedStatic<std::vector<std::string>> RunPassNames;
164
165struct 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
177static RunPassOption RunPassOpt;
178
179static 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
184static int compileModule(char **, LLVMContext &);
185
186static std::unique_ptr<tool_output_file>
187GetOutputStream(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
254static 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
269static 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//
284int 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
366static 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
392static 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
406static 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}
649