brintos

brintos / llvm-project-archived public Read only

0
0
Text · 31.1 KiB · ad31a0e Raw
877 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This is the llc code generator driver. It provides a convenient10// command-line interface for generating an assembly file or a relocatable file,11// given LLVM bitcode.12//13//===----------------------------------------------------------------------===//14 15#include "NewPMDriver.h"16#include "llvm/ADT/STLExtras.h"17#include "llvm/ADT/ScopeExit.h"18#include "llvm/ADT/Statistic.h"19#include "llvm/Analysis/TargetLibraryInfo.h"20#include "llvm/CodeGen/CommandFlags.h"21#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"22#include "llvm/CodeGen/LinkAllCodegenComponents.h"23#include "llvm/CodeGen/MIRParser/MIRParser.h"24#include "llvm/CodeGen/MachineFunctionPass.h"25#include "llvm/CodeGen/MachineModuleInfo.h"26#include "llvm/CodeGen/TargetPassConfig.h"27#include "llvm/CodeGen/TargetSubtargetInfo.h"28#include "llvm/IR/AutoUpgrade.h"29#include "llvm/IR/DataLayout.h"30#include "llvm/IR/DiagnosticInfo.h"31#include "llvm/IR/DiagnosticPrinter.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/TargetRegistry.h"41#include "llvm/Pass.h"42#include "llvm/Remarks/HotnessThresholdParser.h"43#include "llvm/Support/CommandLine.h"44#include "llvm/Support/Debug.h"45#include "llvm/Support/FileSystem.h"46#include "llvm/Support/FormattedStream.h"47#include "llvm/Support/InitLLVM.h"48#include "llvm/Support/PGOOptions.h"49#include "llvm/Support/Path.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/TargetParser/Host.h"59#include "llvm/TargetParser/SubtargetFeature.h"60#include "llvm/TargetParser/Triple.h"61#include "llvm/Transforms/Utils/Cloning.h"62#include <cassert>63#include <memory>64#include <optional>65using namespace llvm;66 67static codegen::RegisterCodeGenFlags CGF;68static codegen::RegisterSaveStatsFlag SSF;69 70// General options for llc.  Other pass-specific options are specified71// within the corresponding llc passes, and target-specific options72// and back-end code generation options are specified with the target machine.73//74static cl::opt<std::string>75    InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));76 77static cl::list<std::string>78    InstPrinterOptions("M", cl::desc("InstPrinter options"));79 80static cl::opt<std::string>81    InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));82 83static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),84                                           cl::value_desc("filename"));85 86static cl::opt<std::string>87    SplitDwarfOutputFile("split-dwarf-output", cl::desc(".dwo output filename"),88                         cl::value_desc("filename"));89 90static cl::opt<unsigned>91    TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),92                     cl::value_desc("N"),93                     cl::desc("Repeat compilation N times for timing"));94 95static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));96 97static cl::opt<unsigned> TimeTraceGranularity(98    "time-trace-granularity",99    cl::desc(100        "Minimum time granularity (in microseconds) traced by time profiler"),101    cl::init(500), cl::Hidden);102 103static cl::opt<std::string>104    TimeTraceFile("time-trace-file",105                  cl::desc("Specify time trace file destination"),106                  cl::value_desc("filename"));107 108static cl::opt<std::string>109    BinutilsVersion("binutils-version", cl::Hidden,110                    cl::desc("Produced object files can use all ELF features "111                             "supported by this binutils version and newer."112                             "If -no-integrated-as is specified, the generated "113                             "assembly will consider GNU as support."114                             "'none' means that all ELF features can be used, "115                             "regardless of binutils support"));116 117static cl::opt<bool>118    PreserveComments("preserve-as-comments", cl::Hidden,119                     cl::desc("Preserve Comments in outputted assembly"),120                     cl::init(true));121 122// Determine optimization level.123static cl::opt<char>124    OptLevel("O",125             cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "126                      "(default = '-O2')"),127             cl::Prefix, cl::init('2'));128 129static cl::opt<std::string>130    TargetTriple("mtriple", cl::desc("Override target triple for module"));131 132static cl::opt<std::string> SplitDwarfFile(133    "split-dwarf-file",134    cl::desc(135        "Specify the name of the .dwo file to encode in the DWARF output"));136 137static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,138                              cl::desc("Do not verify input module"));139 140static cl::opt<bool> VerifyEach("verify-each",141                                cl::desc("Verify after each transform"));142 143static cl::opt<bool>144    DisableSimplifyLibCalls("disable-simplify-libcalls",145                            cl::desc("Disable simplify-libcalls"));146 147static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,148                                    cl::desc("Show encoding in .s output"));149 150static cl::opt<unsigned>151    OutputAsmVariant("output-asm-variant",152                     cl::desc("Syntax variant to use for output printing"));153 154static cl::opt<bool>155    DwarfDirectory("dwarf-directory", cl::Hidden,156                   cl::desc("Use .file directives with an explicit directory"),157                   cl::init(true));158 159static cl::opt<bool> AsmVerbose("asm-verbose",160                                cl::desc("Add comments to directives."),161                                cl::init(true));162 163static cl::opt<bool>164    CompileTwice("compile-twice", cl::Hidden,165                 cl::desc("Run everything twice, re-using the same pass "166                          "manager and verify the result is the same."),167                 cl::init(false));168 169static cl::opt<bool> DiscardValueNames(170    "discard-value-names",171    cl::desc("Discard names from Value (other than GlobalValue)."),172    cl::init(false), cl::Hidden);173 174static cl::opt<bool>175    PrintMIR2VecVocab("print-mir2vec-vocab", cl::Hidden,176                      cl::desc("Print MIR2Vec vocabulary contents"),177                      cl::init(false));178 179static cl::opt<bool>180    PrintMIR2Vec("print-mir2vec", cl::Hidden,181                 cl::desc("Print MIR2Vec embeddings for functions"),182                 cl::init(false));183 184static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));185 186static cl::opt<bool> RemarksWithHotness(187    "pass-remarks-with-hotness",188    cl::desc("With PGO, include profile count in optimization remarks"),189    cl::Hidden);190 191static cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>192    RemarksHotnessThreshold(193        "pass-remarks-hotness-threshold",194        cl::desc("Minimum profile count required for "195                 "an optimization remark to be output. "196                 "Use 'auto' to apply the threshold from profile summary."),197        cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);198 199static cl::opt<std::string>200    RemarksFilename("pass-remarks-output",201                    cl::desc("Output filename for pass remarks"),202                    cl::value_desc("filename"));203 204static cl::opt<std::string>205    RemarksPasses("pass-remarks-filter",206                  cl::desc("Only record optimization remarks from passes whose "207                           "names match the given regular expression"),208                  cl::value_desc("regex"));209 210static cl::opt<std::string> RemarksFormat(211    "pass-remarks-format",212    cl::desc("The format used for serializing remarks (default: YAML)"),213    cl::value_desc("format"), cl::init("yaml"));214 215static cl::opt<bool> EnableNewPassManager(216    "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(false));217 218// This flag specifies a textual description of the optimization pass pipeline219// to run over the module. This flag switches opt to use the new pass manager220// infrastructure, completely disabling all of the flags specific to the old221// pass management.222static cl::opt<std::string> PassPipeline(223    "passes",224    cl::desc(225        "A textual description of the pass pipeline. To have analysis passes "226        "available before a certain pass, add 'require<foo-analysis>'."));227static cl::alias PassPipeline2("p", cl::aliasopt(PassPipeline),228                               cl::desc("Alias for -passes"));229 230static std::vector<std::string> &getRunPassNames() {231  static std::vector<std::string> RunPassNames;232  return RunPassNames;233}234 235namespace {236struct RunPassOption {237  void operator=(const std::string &Val) const {238    if (Val.empty())239      return;240    SmallVector<StringRef, 8> PassNames;241    StringRef(Val).split(PassNames, ',', -1, false);242    for (auto PassName : PassNames)243      getRunPassNames().push_back(std::string(PassName));244  }245};246} // namespace247 248static RunPassOption RunPassOpt;249 250static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(251    "run-pass",252    cl::desc("Run compiler only for specified passes (comma separated list)"),253    cl::value_desc("pass-name"), cl::location(RunPassOpt));254 255// PGO command line options256enum PGOKind {257  NoPGO,258  SampleUse,259};260 261static cl::opt<PGOKind>262    PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,263                cl::desc("The kind of profile guided optimization"),264                cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),265                           clEnumValN(SampleUse, "pgo-sample-use-pipeline",266                                      "Use sampled profile to guide PGO.")));267 268// Function to set PGO options on TargetMachine based on command line flags.269static void setPGOOptions(TargetMachine &TM) {270  std::optional<PGOOptions> PGOOpt;271 272  switch (PGOKindFlag) {273  case SampleUse:274    // Use default values for other PGOOptions parameters. This parameter275    // is used to test that PGO data is preserved at -O0.276    PGOOpt = PGOOptions("", "", "", "", PGOOptions::SampleUse,277                        PGOOptions::NoCSAction);278    break;279  case NoPGO:280    PGOOpt = std::nullopt;281    break;282  }283 284  if (PGOOpt)285    TM.setPGOOption(PGOOpt);286}287 288static int compileModule(char **argv, LLVMContext &Context,289                         std::string &OutputFilename);290 291[[noreturn]] static void reportError(Twine Msg, StringRef Filename = "") {292  SmallString<256> Prefix;293  if (!Filename.empty()) {294    if (Filename == "-")295      Filename = "<stdin>";296    ("'" + Twine(Filename) + "': ").toStringRef(Prefix);297  }298  WithColor::error(errs(), "llc") << Prefix << Msg << "\n";299  exit(1);300}301 302[[noreturn]] static void reportError(Error Err, StringRef Filename) {303  assert(Err);304  handleAllErrors(createFileError(Filename, std::move(Err)),305                  [&](const ErrorInfoBase &EI) { reportError(EI.message()); });306  llvm_unreachable("reportError() should not return");307}308 309static std::unique_ptr<ToolOutputFile> GetOutputStream(Triple::OSType OS) {310  // If we don't yet have an output filename, make one.311  if (OutputFilename.empty()) {312    if (InputFilename == "-")313      OutputFilename = "-";314    else {315      // If InputFilename ends in .bc or .ll, remove it.316      StringRef IFN = InputFilename;317      if (IFN.ends_with(".bc") || IFN.ends_with(".ll"))318        OutputFilename = std::string(IFN.drop_back(3));319      else if (IFN.ends_with(".mir"))320        OutputFilename = std::string(IFN.drop_back(4));321      else322        OutputFilename = std::string(IFN);323 324      switch (codegen::getFileType()) {325      case CodeGenFileType::AssemblyFile:326        OutputFilename += ".s";327        break;328      case CodeGenFileType::ObjectFile:329        if (OS == Triple::Win32)330          OutputFilename += ".obj";331        else332          OutputFilename += ".o";333        break;334      case CodeGenFileType::Null:335        OutputFilename = "-";336        break;337      }338    }339  }340 341  // Decide if we need "binary" output.342  bool Binary = false;343  switch (codegen::getFileType()) {344  case CodeGenFileType::AssemblyFile:345    break;346  case CodeGenFileType::ObjectFile:347  case CodeGenFileType::Null:348    Binary = true;349    break;350  }351 352  // Open the file.353  std::error_code EC;354  sys::fs::OpenFlags OpenFlags = sys::fs::OF_None;355  if (!Binary)356    OpenFlags |= sys::fs::OF_TextWithCRLF;357  auto FDOut = std::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);358  if (EC)359    reportError(EC.message());360  return FDOut;361}362 363// main - Entry point for the llc compiler.364//365int main(int argc, char **argv) {366  InitLLVM X(argc, argv);367 368  // Enable debug stream buffering.369  EnableDebugBuffering = true;370 371  // Initialize targets first, so that --version shows registered targets.372  InitializeAllTargets();373  InitializeAllTargetMCs();374  InitializeAllAsmPrinters();375  InitializeAllAsmParsers();376 377  // Initialize codegen and IR passes used by llc so that the -print-after,378  // -print-before, and -stop-after options work.379  PassRegistry *Registry = PassRegistry::getPassRegistry();380  initializeCore(*Registry);381  initializeCodeGen(*Registry);382  initializeLoopStrengthReducePass(*Registry);383  initializeLowerIntrinsicsPass(*Registry);384  initializePostInlineEntryExitInstrumenterPass(*Registry);385  initializeUnreachableBlockElimLegacyPassPass(*Registry);386  initializeConstantHoistingLegacyPassPass(*Registry);387  initializeScalarOpts(*Registry);388  initializeVectorization(*Registry);389  initializeScalarizeMaskedMemIntrinLegacyPassPass(*Registry);390  initializeExpandReductionsPass(*Registry);391  initializeHardwareLoopsLegacyPass(*Registry);392  initializeTransformUtils(*Registry);393  initializeReplaceWithVeclibLegacyPass(*Registry);394 395  // Initialize debugging passes.396  initializeScavengerTestPass(*Registry);397 398  // Register the Target and CPU printer for --version.399  cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);400  // Register the target printer for --version.401  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);402 403  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");404 405  if (!PassPipeline.empty() && !getRunPassNames().empty()) {406    errs() << "The `llc -run-pass=...` syntax for the new pass manager is "407              "not supported, please use `llc -passes=<pipeline>` (or the `-p` "408              "alias for a more concise version).\n";409    return 1;410  }411 412  if (TimeTrace)413    timeTraceProfilerInitialize(TimeTraceGranularity, argv[0]);414  auto TimeTraceScopeExit = make_scope_exit([]() {415    if (TimeTrace) {416      if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {417        handleAllErrors(std::move(E), [&](const StringError &SE) {418          errs() << SE.getMessage() << "\n";419        });420        return;421      }422      timeTraceProfilerCleanup();423    }424  });425 426  LLVMContext Context;427  Context.setDiscardValueNames(DiscardValueNames);428 429  // Set a diagnostic handler that doesn't exit on the first error430  Context.setDiagnosticHandler(std::make_unique<LLCDiagnosticHandler>());431 432  Expected<LLVMRemarkFileHandle> RemarksFileOrErr =433      setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,434                                   RemarksFormat, RemarksWithHotness,435                                   RemarksHotnessThreshold);436  if (Error E = RemarksFileOrErr.takeError())437    reportError(std::move(E), RemarksFilename);438  LLVMRemarkFileHandle RemarksFile = std::move(*RemarksFileOrErr);439 440  codegen::MaybeEnableStatistics();441  std::string OutputFilename;442 443  if (InputLanguage != "" && InputLanguage != "ir" && InputLanguage != "mir")444    reportError("input language must be '', 'IR' or 'MIR'");445 446  // Compile the module TimeCompilations times to give better compile time447  // metrics.448  for (unsigned I = TimeCompilations; I; --I)449    if (int RetVal = compileModule(argv, Context, OutputFilename))450      return RetVal;451 452  if (RemarksFile)453    RemarksFile->keep();454 455  return codegen::MaybeSaveStatistics(OutputFilename, "llc");456}457 458static bool addPass(PassManagerBase &PM, const char *argv0, StringRef PassName,459                    TargetPassConfig &TPC) {460  if (PassName == "none")461    return false;462 463  const PassRegistry *PR = PassRegistry::getPassRegistry();464  const PassInfo *PI = PR->getPassInfo(PassName);465  if (!PI) {466    WithColor::error(errs(), argv0)467        << "run-pass " << PassName << " is not registered.\n";468    return true;469  }470 471  Pass *P;472  if (PI->getNormalCtor())473    P = PI->getNormalCtor()();474  else {475    WithColor::error(errs(), argv0)476        << "cannot create pass: " << PI->getPassName() << "\n";477    return true;478  }479  std::string Banner = std::string("After ") + std::string(P->getPassName());480  TPC.addMachinePrePasses();481  PM.add(P);482  TPC.addMachinePostPasses(Banner);483 484  return false;485}486 487static int compileModule(char **argv, LLVMContext &Context,488                         std::string &OutputFilename) {489  // Load the module to be compiled...490  SMDiagnostic Err;491  std::unique_ptr<Module> M;492  std::unique_ptr<MIRParser> MIR;493  Triple TheTriple;494  std::string CPUStr = codegen::getCPUStr(),495              FeaturesStr = codegen::getFeaturesStr();496 497  // Set attributes on functions as loaded from MIR from command line arguments.498  auto setMIRFunctionAttributes = [&CPUStr, &FeaturesStr](Function &F) {499    codegen::setFunctionAttributes(CPUStr, FeaturesStr, F);500  };501 502  auto MAttrs = codegen::getMAttrs();503  bool SkipModule =504      CPUStr == "help" || (!MAttrs.empty() && MAttrs.front() == "help");505 506  CodeGenOptLevel OLvl;507  if (auto Level = CodeGenOpt::parseLevel(OptLevel)) {508    OLvl = *Level;509  } else {510    WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";511    return 1;512  }513 514  // Parse 'none' or '$major.$minor'. Disallow -binutils-version=0 because we515  // use that to indicate the MC default.516  if (!BinutilsVersion.empty() && BinutilsVersion != "none") {517    StringRef V = BinutilsVersion.getValue();518    unsigned Num;519    if (V.consumeInteger(10, Num) || Num == 0 ||520        !(V.empty() ||521          (V.consume_front(".") && !V.consumeInteger(10, Num) && V.empty()))) {522      WithColor::error(errs(), argv[0])523          << "invalid -binutils-version, accepting 'none' or major.minor\n";524      return 1;525    }526  }527  TargetOptions Options;528  auto InitializeOptions = [&](const Triple &TheTriple) {529    Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);530 531    if (Options.XCOFFReadOnlyPointers) {532      if (!TheTriple.isOSAIX())533        reportError("-mxcoff-roptr option is only supported on AIX",534                    InputFilename);535 536      // Since the storage mapping class is specified per csect,537      // without using data sections, it is less effective to use read-only538      // pointers. Using read-only pointers may cause other RO variables in the539      // same csect to become RW when the linker acts upon `-bforceimprw`;540      // therefore, we require that separate data sections are used in the541      // presence of ReadOnlyPointers. We respect the setting of data-sections542      // since we have not found reasons to do otherwise that overcome the user543      // surprise of not respecting the setting.544      if (!Options.DataSections)545        reportError("-mxcoff-roptr option must be used with -data-sections",546                    InputFilename);547    }548 549    if (TheTriple.isX86() &&550        codegen::getFuseFPOps() != FPOpFusion::FPOpFusionMode::Standard)551      WithColor::warning(errs(), argv[0])552          << "X86 backend ignores --fp-contract setting; use IR fast-math "553             "flags instead.";554 555    Options.BinutilsVersion =556        TargetMachine::parseBinutilsVersion(BinutilsVersion);557    Options.MCOptions.ShowMCEncoding = ShowMCEncoding;558    Options.MCOptions.AsmVerbose = AsmVerbose;559    Options.MCOptions.PreserveAsmComments = PreserveComments;560    if (OutputAsmVariant.getNumOccurrences())561      Options.MCOptions.OutputAsmVariant = OutputAsmVariant;562    Options.MCOptions.IASSearchPaths = IncludeDirs;563    Options.MCOptions.InstPrinterOptions = InstPrinterOptions;564    Options.MCOptions.SplitDwarfFile = SplitDwarfFile;565    if (DwarfDirectory.getPosition()) {566      Options.MCOptions.MCUseDwarfDirectory =567          DwarfDirectory ? MCTargetOptions::EnableDwarfDirectory568                         : MCTargetOptions::DisableDwarfDirectory;569    } else {570      // -dwarf-directory is not set explicitly. Some assemblers571      // (e.g. GNU as or ptxas) do not support `.file directory'572      // syntax prior to DWARFv5. Let the target decide the default573      // value.574      Options.MCOptions.MCUseDwarfDirectory =575          MCTargetOptions::DefaultDwarfDirectory;576    }577  };578 579  std::optional<Reloc::Model> RM = codegen::getExplicitRelocModel();580  std::optional<CodeModel::Model> CM = codegen::getExplicitCodeModel();581 582  const Target *TheTarget = nullptr;583  std::unique_ptr<TargetMachine> Target;584 585  // If user just wants to list available options, skip module loading586  if (!SkipModule) {587    auto SetDataLayout = [&](StringRef DataLayoutTargetTriple,588                             StringRef OldDLStr) -> std::optional<std::string> {589      // If we are supposed to override the target triple, do so now.590      std::string IRTargetTriple = DataLayoutTargetTriple.str();591      if (!TargetTriple.empty())592        IRTargetTriple = Triple::normalize(TargetTriple);593      TheTriple = Triple(IRTargetTriple);594      if (TheTriple.getTriple().empty())595        TheTriple.setTriple(sys::getDefaultTargetTriple());596 597      std::string Error;598      TheTarget =599          TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);600      if (!TheTarget) {601        WithColor::error(errs(), argv[0]) << Error << "\n";602        exit(1);603      }604 605      InitializeOptions(TheTriple);606      Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(607          TheTriple, CPUStr, FeaturesStr, Options, RM, CM, OLvl));608      assert(Target && "Could not allocate target machine!");609 610      // Set PGO options based on command line flags611      setPGOOptions(*Target);612 613      return Target->createDataLayout().getStringRepresentation();614    };615    if (InputLanguage == "mir" ||616        (InputLanguage == "" && StringRef(InputFilename).ends_with(".mir"))) {617      MIR = createMIRParserFromFile(InputFilename, Err, Context,618                                    setMIRFunctionAttributes);619      if (MIR)620        M = MIR->parseIRModule(SetDataLayout);621    } else {622      M = parseIRFile(InputFilename, Err, Context,623                      ParserCallbacks(SetDataLayout));624    }625    if (!M) {626      Err.print(argv[0], WithColor::error(errs(), argv[0]));627      return 1;628    }629    if (!TargetTriple.empty())630      M->setTargetTriple(Triple(Triple::normalize(TargetTriple)));631 632    std::optional<CodeModel::Model> CM_IR = M->getCodeModel();633    if (!CM && CM_IR)634      Target->setCodeModel(*CM_IR);635    if (std::optional<uint64_t> LDT = codegen::getExplicitLargeDataThreshold())636      Target->setLargeDataThreshold(*LDT);637  } else {638    TheTriple = Triple(Triple::normalize(TargetTriple));639    if (TheTriple.getTriple().empty())640      TheTriple.setTriple(sys::getDefaultTargetTriple());641 642    // Get the target specific parser.643    std::string Error;644    TheTarget =645        TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);646    if (!TheTarget) {647      WithColor::error(errs(), argv[0]) << Error << "\n";648      return 1;649    }650 651    InitializeOptions(TheTriple);652    Target = std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(653        TheTriple, CPUStr, FeaturesStr, Options, RM, CM, OLvl));654    assert(Target && "Could not allocate target machine!");655 656    // Set PGO options based on command line flags657    setPGOOptions(*Target);658 659    // If we don't have a module then just exit now. We do this down660    // here since the CPU/Feature help is underneath the target machine661    // creation.662    return 0;663  }664 665  assert(M && "Should have exited if we didn't have a module!");666  if (codegen::getFloatABIForCalls() != FloatABI::Default)667    Target->Options.FloatABIType = codegen::getFloatABIForCalls();668 669  // Figure out where we are going to send the output.670  std::unique_ptr<ToolOutputFile> Out = GetOutputStream(TheTriple.getOS());671  if (!Out)672    return 1;673 674  // Ensure the filename is passed down to CodeViewDebug.675  Target->Options.ObjectFilenameForDebug = Out->outputFilename();676 677  // Return a copy of the output filename via the output param678  OutputFilename = Out->outputFilename();679 680  // Tell target that this tool is not necessarily used with argument ABI681  // compliance (i.e. narrow integer argument extensions).682  Target->Options.VerifyArgABICompliance = 0;683 684  std::unique_ptr<ToolOutputFile> DwoOut;685  if (!SplitDwarfOutputFile.empty()) {686    std::error_code EC;687    DwoOut = std::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,688                                              sys::fs::OF_None);689    if (EC)690      reportError(EC.message(), SplitDwarfOutputFile);691  }692 693  // Add an appropriate TargetLibraryInfo pass for the module's triple.694  TargetLibraryInfoImpl TLII(M->getTargetTriple(), Target->Options.VecLib);695 696  // The -disable-simplify-libcalls flag actually disables all builtin optzns.697  if (DisableSimplifyLibCalls)698    TLII.disableAllFunctions();699 700  // Verify module immediately to catch problems before doInitialization() is701  // called on any passes.702  if (!NoVerify && verifyModule(*M, &errs()))703    reportError("input module cannot be verified", InputFilename);704 705  // Override function attributes based on CPUStr, FeaturesStr, and command line706  // flags.707  codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);708 709  if (mc::getExplicitRelaxAll() &&710      codegen::getFileType() != CodeGenFileType::ObjectFile)711    WithColor::warning(errs(), argv[0])712        << ": warning: ignoring -mc-relax-all because filetype != obj";713 714  VerifierKind VK = VerifierKind::InputOutput;715  if (NoVerify)716    VK = VerifierKind::None;717  else if (VerifyEach)718    VK = VerifierKind::EachPass;719 720  if (EnableNewPassManager || !PassPipeline.empty()) {721    return compileModuleWithNewPM(argv[0], std::move(M), std::move(MIR),722                                  std::move(Target), std::move(Out),723                                  std::move(DwoOut), Context, TLII, VK,724                                  PassPipeline, codegen::getFileType());725  }726 727  // Build up all of the passes that we want to do to the module.728  legacy::PassManager PM;729  PM.add(new TargetLibraryInfoWrapperPass(TLII));730 731  {732    raw_pwrite_stream *OS = &Out->os();733 734    // Manually do the buffering rather than using buffer_ostream,735    // so we can memcmp the contents in CompileTwice mode736    SmallVector<char, 0> Buffer;737    std::unique_ptr<raw_svector_ostream> BOS;738    if ((codegen::getFileType() != CodeGenFileType::AssemblyFile &&739         !Out->os().supportsSeeking()) ||740        CompileTwice) {741      BOS = std::make_unique<raw_svector_ostream>(Buffer);742      OS = BOS.get();743    }744 745    const char *argv0 = argv[0];746    MachineModuleInfoWrapperPass *MMIWP =747        new MachineModuleInfoWrapperPass(Target.get());748 749    // Set a temporary diagnostic handler. This is used before750    // MachineModuleInfoWrapperPass::doInitialization for features like -M.751    bool HasMCErrors = false;752    MCContext &MCCtx = MMIWP->getMMI().getContext();753    MCCtx.setDiagnosticHandler([&](const SMDiagnostic &SMD, bool IsInlineAsm,754                                   const SourceMgr &SrcMgr,755                                   std::vector<const MDNode *> &LocInfos) {756      WithColor::error(errs(), argv0) << SMD.getMessage() << '\n';757      HasMCErrors = true;758    });759 760    // Construct a custom pass pipeline that starts after instruction761    // selection.762    if (!getRunPassNames().empty()) {763      if (!MIR) {764        WithColor::error(errs(), argv[0])765            << "run-pass is for .mir file only.\n";766        delete MMIWP;767        return 1;768      }769      TargetPassConfig *PTPC = Target->createPassConfig(PM);770      TargetPassConfig &TPC = *PTPC;771      if (TPC.hasLimitedCodeGenPipeline()) {772        WithColor::error(errs(), argv[0])773            << "run-pass cannot be used with "774            << TPC.getLimitedCodeGenPipelineReason() << ".\n";775        delete PTPC;776        delete MMIWP;777        return 1;778      }779 780      TPC.setDisableVerify(NoVerify);781      PM.add(&TPC);782      PM.add(MMIWP);783      TPC.printAndVerify("");784      for (const std::string &RunPassName : getRunPassNames()) {785        if (addPass(PM, argv0, RunPassName, TPC))786          return 1;787      }788      TPC.setInitialized();789      PM.add(createPrintMIRPass(*OS));790 791      // Add MIR2Vec vocabulary printer if requested792      if (PrintMIR2VecVocab) {793        PM.add(createMIR2VecVocabPrinterLegacyPass(errs()));794      }795 796      // Add MIR2Vec printer if requested797      if (PrintMIR2Vec) {798        PM.add(createMIR2VecPrinterLegacyPass(errs()));799      }800 801      PM.add(createFreeMachineFunctionPass());802    } else {803      if (Target->addPassesToEmitFile(PM, *OS, DwoOut ? &DwoOut->os() : nullptr,804                                      codegen::getFileType(), NoVerify,805                                      MMIWP)) {806        if (!HasMCErrors)807          reportError("target does not support generation of this file type");808      }809 810      // Add MIR2Vec vocabulary printer if requested811      if (PrintMIR2VecVocab) {812        PM.add(createMIR2VecVocabPrinterLegacyPass(errs()));813      }814 815      // Add MIR2Vec printer if requested816      if (PrintMIR2Vec) {817        PM.add(createMIR2VecPrinterLegacyPass(errs()));818      }819    }820 821    Target->getObjFileLowering()->Initialize(MMIWP->getMMI().getContext(),822                                             *Target);823    if (MIR) {824      assert(MMIWP && "Forgot to create MMIWP?");825      if (MIR->parseMachineFunctions(*M, MMIWP->getMMI()))826        return 1;827    }828 829    // Before executing passes, print the final values of the LLVM options.830    cl::PrintOptionValues();831 832    // If requested, run the pass manager over the same module again,833    // to catch any bugs due to persistent state in the passes. Note that834    // opt has the same functionality, so it may be worth abstracting this out835    // in the future.836    SmallVector<char, 0> CompileTwiceBuffer;837    if (CompileTwice) {838      std::unique_ptr<Module> M2(llvm::CloneModule(*M));839      PM.run(*M2);840      CompileTwiceBuffer = Buffer;841      Buffer.clear();842    }843 844    PM.run(*M);845 846    if (Context.getDiagHandlerPtr()->HasErrors || HasMCErrors)847      return 1;848 849    // Compare the two outputs and make sure they're the same850    if (CompileTwice) {851      if (Buffer.size() != CompileTwiceBuffer.size() ||852          (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=853           0)) {854        errs()855            << "Running the pass manager twice changed the output.\n"856               "Writing the result of the second run to the specified output\n"857               "To generate the one-run comparison binary, just run without\n"858               "the compile-twice option\n";859        Out->os() << Buffer;860        Out->keep();861        return 1;862      }863    }864 865    if (BOS) {866      Out->os() << Buffer;867    }868  }869 870  // Declare success.871  Out->keep();872  if (DwoOut)873    DwoOut->keep();874 875  return 0;876}877