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