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