Home | History | Annotate | Line # | Download | only in Driver
      1 //===- ToolChain.cpp - Collections of tools for one platform --------------===//
      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 #include "clang/Driver/ToolChain.h"
     10 #include "InputInfo.h"
     11 #include "ToolChains/Arch/ARM.h"
     12 #include "ToolChains/Clang.h"
     13 #include "ToolChains/InterfaceStubs.h"
     14 #include "ToolChains/Flang.h"
     15 #include "clang/Basic/ObjCRuntime.h"
     16 #include "clang/Basic/Sanitizers.h"
     17 #include "clang/Config/config.h"
     18 #include "clang/Driver/Action.h"
     19 #include "clang/Driver/Driver.h"
     20 #include "clang/Driver/DriverDiagnostic.h"
     21 #include "clang/Driver/Job.h"
     22 #include "clang/Driver/Options.h"
     23 #include "clang/Driver/SanitizerArgs.h"
     24 #include "clang/Driver/XRayArgs.h"
     25 #include "llvm/ADT/STLExtras.h"
     26 #include "llvm/ADT/SmallString.h"
     27 #include "llvm/ADT/StringRef.h"
     28 #include "llvm/ADT/Triple.h"
     29 #include "llvm/ADT/Twine.h"
     30 #include "llvm/Config/llvm-config.h"
     31 #include "llvm/MC/MCTargetOptions.h"
     32 #include "llvm/Option/Arg.h"
     33 #include "llvm/Option/ArgList.h"
     34 #include "llvm/Option/OptTable.h"
     35 #include "llvm/Option/Option.h"
     36 #include "llvm/Support/ErrorHandling.h"
     37 #include "llvm/Support/FileSystem.h"
     38 #include "llvm/Support/Path.h"
     39 #include "llvm/Support/TargetParser.h"
     40 #include "llvm/Support/TargetRegistry.h"
     41 #include "llvm/Support/VersionTuple.h"
     42 #include "llvm/Support/VirtualFileSystem.h"
     43 #include <cassert>
     44 #include <cstddef>
     45 #include <cstring>
     46 #include <string>
     47 
     48 using namespace clang;
     49 using namespace driver;
     50 using namespace tools;
     51 using namespace llvm;
     52 using namespace llvm::opt;
     53 
     54 static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
     55   return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
     56                          options::OPT_fno_rtti, options::OPT_frtti);
     57 }
     58 
     59 static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
     60                                              const llvm::Triple &Triple,
     61                                              const Arg *CachedRTTIArg) {
     62   // Explicit rtti/no-rtti args
     63   if (CachedRTTIArg) {
     64     if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
     65       return ToolChain::RM_Enabled;
     66     else
     67       return ToolChain::RM_Disabled;
     68   }
     69 
     70   // -frtti is default, except for the PS4 CPU.
     71   return (Triple.isPS4CPU()) ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
     72 }
     73 
     74 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
     75                      const ArgList &Args)
     76     : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
     77       CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
     78   std::string RuntimePath = getRuntimePath();
     79   if (getVFS().exists(RuntimePath))
     80     getLibraryPaths().push_back(RuntimePath);
     81 
     82   std::string StdlibPath = getStdlibPath();
     83   if (getVFS().exists(StdlibPath))
     84     getFilePaths().push_back(StdlibPath);
     85 
     86   std::string CandidateLibPath = getArchSpecificLibPath();
     87   if (getVFS().exists(CandidateLibPath))
     88     getFilePaths().push_back(CandidateLibPath);
     89 }
     90 
     91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
     92   Triple.setEnvironment(Env);
     93   if (EffectiveTriple != llvm::Triple())
     94     EffectiveTriple.setEnvironment(Env);
     95 }
     96 
     97 ToolChain::~ToolChain() = default;
     98 
     99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
    100   return getDriver().getVFS();
    101 }
    102 
    103 bool ToolChain::useIntegratedAs() const {
    104   return Args.hasFlag(options::OPT_fintegrated_as,
    105                       options::OPT_fno_integrated_as,
    106                       IsIntegratedAssemblerDefault());
    107 }
    108 
    109 bool ToolChain::useRelaxRelocations() const {
    110   return ENABLE_X86_RELAX_RELOCATIONS;
    111 }
    112 
    113 bool ToolChain::isNoExecStackDefault() const {
    114     return false;
    115 }
    116 
    117 const SanitizerArgs& ToolChain::getSanitizerArgs() const {
    118   if (!SanitizerArguments.get())
    119     SanitizerArguments.reset(new SanitizerArgs(*this, Args));
    120   return *SanitizerArguments.get();
    121 }
    122 
    123 const XRayArgs& ToolChain::getXRayArgs() const {
    124   if (!XRayArguments.get())
    125     XRayArguments.reset(new XRayArgs(*this, Args));
    126   return *XRayArguments.get();
    127 }
    128 
    129 namespace {
    130 
    131 struct DriverSuffix {
    132   const char *Suffix;
    133   const char *ModeFlag;
    134 };
    135 
    136 } // namespace
    137 
    138 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
    139   // A list of known driver suffixes. Suffixes are compared against the
    140   // program name in order. If there is a match, the frontend type is updated as
    141   // necessary by applying the ModeFlag.
    142   static const DriverSuffix DriverSuffixes[] = {
    143       {"clang", nullptr},
    144       {"clang++", "--driver-mode=g++"},
    145       {"clang-c++", "--driver-mode=g++"},
    146       {"clang-cc", nullptr},
    147       {"clang-cpp", "--driver-mode=cpp"},
    148       {"clang-g++", "--driver-mode=g++"},
    149       {"clang-gcc", nullptr},
    150       {"clang-cl", "--driver-mode=cl"},
    151       {"cc", nullptr},
    152       {"cpp", "--driver-mode=cpp"},
    153       {"cl", "--driver-mode=cl"},
    154       {"++", "--driver-mode=g++"},
    155       {"flang", "--driver-mode=flang"},
    156   };
    157 
    158   for (size_t i = 0; i < llvm::array_lengthof(DriverSuffixes); ++i) {
    159     StringRef Suffix(DriverSuffixes[i].Suffix);
    160     if (ProgName.endswith(Suffix)) {
    161       Pos = ProgName.size() - Suffix.size();
    162       return &DriverSuffixes[i];
    163     }
    164   }
    165   return nullptr;
    166 }
    167 
    168 /// Normalize the program name from argv[0] by stripping the file extension if
    169 /// present and lower-casing the string on Windows.
    170 static std::string normalizeProgramName(llvm::StringRef Argv0) {
    171   std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
    172 #ifdef _WIN32
    173   // Transform to lowercase for case insensitive file systems.
    174   std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(), ::tolower);
    175 #endif
    176   return ProgName;
    177 }
    178 
    179 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
    180   // Try to infer frontend type and default target from the program name by
    181   // comparing it against DriverSuffixes in order.
    182 
    183   // If there is a match, the function tries to identify a target as prefix.
    184   // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
    185   // prefix "x86_64-linux". If such a target prefix is found, it may be
    186   // added via -target as implicit first argument.
    187   const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
    188 
    189   if (!DS) {
    190     // Try again after stripping any trailing version number:
    191     // clang++3.5 -> clang++
    192     ProgName = ProgName.rtrim("0123456789.");
    193     DS = FindDriverSuffix(ProgName, Pos);
    194   }
    195 
    196   if (!DS) {
    197     // Try again after stripping trailing -component.
    198     // clang++-tot -> clang++
    199     ProgName = ProgName.slice(0, ProgName.rfind('-'));
    200     DS = FindDriverSuffix(ProgName, Pos);
    201   }
    202   return DS;
    203 }
    204 
    205 ParsedClangName
    206 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
    207   std::string ProgName = normalizeProgramName(PN);
    208   size_t SuffixPos;
    209   const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
    210   if (!DS)
    211     return {};
    212   size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
    213 
    214   size_t LastComponent = ProgName.rfind('-', SuffixPos);
    215   if (LastComponent == std::string::npos)
    216     return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
    217   std::string ModeSuffix = ProgName.substr(LastComponent + 1,
    218                                            SuffixEnd - LastComponent - 1);
    219 
    220   // Infer target from the prefix.
    221   StringRef Prefix(ProgName);
    222   Prefix = Prefix.slice(0, LastComponent);
    223   std::string IgnoredError;
    224   bool IsRegistered =
    225       llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
    226   return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
    227                          IsRegistered};
    228 }
    229 
    230 StringRef ToolChain::getDefaultUniversalArchName() const {
    231   // In universal driver terms, the arch name accepted by -arch isn't exactly
    232   // the same as the ones that appear in the triple. Roughly speaking, this is
    233   // an inverse of the darwin::getArchTypeForDarwinArchName() function.
    234   switch (Triple.getArch()) {
    235   case llvm::Triple::aarch64: {
    236     if (getTriple().isArm64e())
    237       return "arm64e";
    238     return "arm64";
    239   }
    240   case llvm::Triple::aarch64_32:
    241     return "arm64_32";
    242   case llvm::Triple::ppc:
    243     return "ppc";
    244   case llvm::Triple::ppcle:
    245     return "ppcle";
    246   case llvm::Triple::ppc64:
    247     return "ppc64";
    248   case llvm::Triple::ppc64le:
    249     return "ppc64le";
    250   default:
    251     return Triple.getArchName();
    252   }
    253 }
    254 
    255 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
    256   return Input.getFilename();
    257 }
    258 
    259 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
    260   return false;
    261 }
    262 
    263 Tool *ToolChain::getClang() const {
    264   if (!Clang)
    265     Clang.reset(new tools::Clang(*this));
    266   return Clang.get();
    267 }
    268 
    269 Tool *ToolChain::getFlang() const {
    270   if (!Flang)
    271     Flang.reset(new tools::Flang(*this));
    272   return Flang.get();
    273 }
    274 
    275 Tool *ToolChain::buildAssembler() const {
    276   return new tools::ClangAs(*this);
    277 }
    278 
    279 Tool *ToolChain::buildLinker() const {
    280   llvm_unreachable("Linking is not supported by this toolchain");
    281 }
    282 
    283 Tool *ToolChain::buildStaticLibTool() const {
    284   llvm_unreachable("Creating static lib is not supported by this toolchain");
    285 }
    286 
    287 Tool *ToolChain::getAssemble() const {
    288   if (!Assemble)
    289     Assemble.reset(buildAssembler());
    290   return Assemble.get();
    291 }
    292 
    293 Tool *ToolChain::getClangAs() const {
    294   if (!Assemble)
    295     Assemble.reset(new tools::ClangAs(*this));
    296   return Assemble.get();
    297 }
    298 
    299 Tool *ToolChain::getLink() const {
    300   if (!Link)
    301     Link.reset(buildLinker());
    302   return Link.get();
    303 }
    304 
    305 Tool *ToolChain::getStaticLibTool() const {
    306   if (!StaticLibTool)
    307     StaticLibTool.reset(buildStaticLibTool());
    308   return StaticLibTool.get();
    309 }
    310 
    311 Tool *ToolChain::getIfsMerge() const {
    312   if (!IfsMerge)
    313     IfsMerge.reset(new tools::ifstool::Merger(*this));
    314   return IfsMerge.get();
    315 }
    316 
    317 Tool *ToolChain::getOffloadBundler() const {
    318   if (!OffloadBundler)
    319     OffloadBundler.reset(new tools::OffloadBundler(*this));
    320   return OffloadBundler.get();
    321 }
    322 
    323 Tool *ToolChain::getOffloadWrapper() const {
    324   if (!OffloadWrapper)
    325     OffloadWrapper.reset(new tools::OffloadWrapper(*this));
    326   return OffloadWrapper.get();
    327 }
    328 
    329 Tool *ToolChain::getTool(Action::ActionClass AC) const {
    330   switch (AC) {
    331   case Action::AssembleJobClass:
    332     return getAssemble();
    333 
    334   case Action::IfsMergeJobClass:
    335     return getIfsMerge();
    336 
    337   case Action::LinkJobClass:
    338     return getLink();
    339 
    340   case Action::StaticLibJobClass:
    341     return getStaticLibTool();
    342 
    343   case Action::InputClass:
    344   case Action::BindArchClass:
    345   case Action::OffloadClass:
    346   case Action::LipoJobClass:
    347   case Action::DsymutilJobClass:
    348   case Action::VerifyDebugInfoJobClass:
    349     llvm_unreachable("Invalid tool kind.");
    350 
    351   case Action::CompileJobClass:
    352   case Action::PrecompileJobClass:
    353   case Action::HeaderModulePrecompileJobClass:
    354   case Action::PreprocessJobClass:
    355   case Action::AnalyzeJobClass:
    356   case Action::MigrateJobClass:
    357   case Action::VerifyPCHJobClass:
    358   case Action::BackendJobClass:
    359     return getClang();
    360 
    361   case Action::OffloadBundlingJobClass:
    362   case Action::OffloadUnbundlingJobClass:
    363     return getOffloadBundler();
    364 
    365   case Action::OffloadWrapperJobClass:
    366     return getOffloadWrapper();
    367   }
    368 
    369   llvm_unreachable("Invalid tool kind.");
    370 }
    371 
    372 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
    373                                              const ArgList &Args) {
    374   const llvm::Triple &Triple = TC.getTriple();
    375   bool IsWindows = Triple.isOSWindows();
    376 
    377   if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
    378     return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
    379                ? "armhf"
    380                : "arm";
    381 
    382   // For historic reasons, Android library is using i686 instead of i386.
    383   if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
    384     return "i686";
    385 
    386   return llvm::Triple::getArchTypeName(TC.getArch());
    387 }
    388 
    389 StringRef ToolChain::getOSLibName() const {
    390   if (Triple.isOSDarwin())
    391     return "darwin";
    392 
    393   switch (Triple.getOS()) {
    394   case llvm::Triple::FreeBSD:
    395     return "freebsd";
    396   case llvm::Triple::NetBSD:
    397     return "netbsd";
    398   case llvm::Triple::OpenBSD:
    399     return "openbsd";
    400   case llvm::Triple::Solaris:
    401     return "sunos";
    402   case llvm::Triple::AIX:
    403     return "aix";
    404   default:
    405     return getOS();
    406   }
    407 }
    408 
    409 std::string ToolChain::getCompilerRTPath() const {
    410   SmallString<128> Path(getDriver().ResourceDir);
    411   if (Triple.isOSUnknown()) {
    412     llvm::sys::path::append(Path, "lib");
    413   } else {
    414     llvm::sys::path::append(Path, "lib", getOSLibName());
    415   }
    416   return std::string(Path.str());
    417 }
    418 
    419 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
    420                                              StringRef Component,
    421                                              FileType Type) const {
    422   std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
    423   return llvm::sys::path::filename(CRTAbsolutePath).str();
    424 }
    425 
    426 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
    427                                                StringRef Component,
    428                                                FileType Type,
    429                                                bool AddArch) const {
    430   const llvm::Triple &TT = getTriple();
    431   bool IsITANMSVCWindows =
    432       TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
    433 
    434   const char *Prefix =
    435       IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
    436   const char *Suffix;
    437   switch (Type) {
    438   case ToolChain::FT_Object:
    439     Suffix = IsITANMSVCWindows ? ".obj" : ".o";
    440     break;
    441   case ToolChain::FT_Static:
    442     Suffix = IsITANMSVCWindows ? ".lib" : ".a";
    443     break;
    444   case ToolChain::FT_Shared:
    445     Suffix = TT.isOSWindows()
    446                  ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
    447                  : ".so";
    448     break;
    449   }
    450 
    451   std::string ArchAndEnv;
    452   if (AddArch) {
    453     StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
    454     const char *Env = TT.isAndroid() ? "-android" : "";
    455     ArchAndEnv = ("-" + Arch + Env).str();
    456   }
    457   return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
    458 }
    459 
    460 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
    461                                      FileType Type) const {
    462   // Check for runtime files in the new layout without the architecture first.
    463   std::string CRTBasename =
    464       buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
    465   for (const auto &LibPath : getLibraryPaths()) {
    466     SmallString<128> P(LibPath);
    467     llvm::sys::path::append(P, CRTBasename);
    468     if (getVFS().exists(P))
    469       return std::string(P.str());
    470   }
    471 
    472   // Fall back to the old expected compiler-rt name if the new one does not
    473   // exist.
    474   CRTBasename =
    475       buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
    476   SmallString<128> Path(getCompilerRTPath());
    477   llvm::sys::path::append(Path, CRTBasename);
    478   return std::string(Path.str());
    479 }
    480 
    481 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
    482                                               StringRef Component,
    483                                               FileType Type) const {
    484   return Args.MakeArgString(getCompilerRT(Args, Component, Type));
    485 }
    486 
    487 std::string ToolChain::getRuntimePath() const {
    488   SmallString<128> P(D.ResourceDir);
    489   llvm::sys::path::append(P, "lib", getTripleString());
    490   return std::string(P.str());
    491 }
    492 
    493 std::string ToolChain::getStdlibPath() const {
    494   SmallString<128> P(D.Dir);
    495   llvm::sys::path::append(P, "..", "lib", getTripleString());
    496   return std::string(P.str());
    497 }
    498 
    499 std::string ToolChain::getArchSpecificLibPath() const {
    500   SmallString<128> Path(getDriver().ResourceDir);
    501   llvm::sys::path::append(Path, "lib", getOSLibName(),
    502                           llvm::Triple::getArchTypeName(getArch()));
    503   return std::string(Path.str());
    504 }
    505 
    506 bool ToolChain::needsProfileRT(const ArgList &Args) {
    507   if (Args.hasArg(options::OPT_noprofilelib))
    508     return false;
    509 
    510   return Args.hasArg(options::OPT_fprofile_generate) ||
    511          Args.hasArg(options::OPT_fprofile_generate_EQ) ||
    512          Args.hasArg(options::OPT_fcs_profile_generate) ||
    513          Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
    514          Args.hasArg(options::OPT_fprofile_instr_generate) ||
    515          Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
    516          Args.hasArg(options::OPT_fcreate_profile) ||
    517          Args.hasArg(options::OPT_forder_file_instrumentation);
    518 }
    519 
    520 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
    521   return Args.hasArg(options::OPT_coverage) ||
    522          Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
    523                       false);
    524 }
    525 
    526 Tool *ToolChain::SelectTool(const JobAction &JA) const {
    527   if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
    528   if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
    529   Action::ActionClass AC = JA.getKind();
    530   if (AC == Action::AssembleJobClass && useIntegratedAs())
    531     return getClangAs();
    532   return getTool(AC);
    533 }
    534 
    535 std::string ToolChain::GetFilePath(const char *Name) const {
    536   return D.GetFilePath(Name, *this);
    537 }
    538 
    539 std::string ToolChain::GetProgramPath(const char *Name) const {
    540   return D.GetProgramPath(Name, *this);
    541 }
    542 
    543 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD,
    544                                      bool *LinkerIsLLDDarwinNew) const {
    545   if (LinkerIsLLD)
    546     *LinkerIsLLD = false;
    547   if (LinkerIsLLDDarwinNew)
    548     *LinkerIsLLDDarwinNew = false;
    549 
    550   // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
    551   // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
    552   const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
    553   StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
    554 
    555   // --ld-path= takes precedence over -fuse-ld= and specifies the executable
    556   // name. -B, COMPILER_PATH and PATH and consulted if the value does not
    557   // contain a path component separator.
    558   if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
    559     std::string Path(A->getValue());
    560     if (!Path.empty()) {
    561       if (llvm::sys::path::parent_path(Path).empty())
    562         Path = GetProgramPath(A->getValue());
    563       if (llvm::sys::fs::can_execute(Path))
    564         return std::string(Path);
    565     }
    566     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
    567     return GetProgramPath(getDefaultLinker());
    568   }
    569   // If we're passed -fuse-ld= with no argument, or with the argument ld,
    570   // then use whatever the default system linker is.
    571   if (UseLinker.empty() || UseLinker == "ld") {
    572     const char *DefaultLinker = getDefaultLinker();
    573     if (llvm::sys::path::is_absolute(DefaultLinker))
    574       return std::string(DefaultLinker);
    575     else
    576       return GetProgramPath(DefaultLinker);
    577   }
    578 
    579   // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
    580   // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
    581   // to a relative path is surprising. This is more complex due to priorities
    582   // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
    583   if (UseLinker.find('/') != StringRef::npos)
    584     getDriver().Diag(diag::warn_drv_fuse_ld_path);
    585 
    586   if (llvm::sys::path::is_absolute(UseLinker)) {
    587     // If we're passed what looks like an absolute path, don't attempt to
    588     // second-guess that.
    589     if (llvm::sys::fs::can_execute(UseLinker))
    590       return std::string(UseLinker);
    591   } else {
    592     llvm::SmallString<8> LinkerName;
    593     if (Triple.isOSDarwin())
    594       LinkerName.append("ld64.");
    595     else
    596       LinkerName.append("ld.");
    597     LinkerName.append(UseLinker);
    598 
    599     std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
    600     if (llvm::sys::fs::can_execute(LinkerPath)) {
    601       // FIXME: Remove LinkerIsLLDDarwinNew once there's only one MachO lld.
    602       if (LinkerIsLLD)
    603         *LinkerIsLLD = UseLinker == "lld" || UseLinker == "lld.darwinold";
    604       if (LinkerIsLLDDarwinNew)
    605         *LinkerIsLLDDarwinNew = UseLinker == "lld";
    606       return LinkerPath;
    607     }
    608   }
    609 
    610   if (A)
    611     getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
    612 
    613   return GetProgramPath(getDefaultLinker());
    614 }
    615 
    616 std::string ToolChain::GetStaticLibToolPath() const {
    617   // TODO: Add support for static lib archiving on Windows
    618   return GetProgramPath("llvm-ar");
    619 }
    620 
    621 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
    622   types::ID id = types::lookupTypeForExtension(Ext);
    623 
    624   // Flang always runs the preprocessor and has no notion of "preprocessed
    625   // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
    626   // them differently.
    627   if (D.IsFlangMode() && id == types::TY_PP_Fortran)
    628     id = types::TY_Fortran;
    629 
    630   return id;
    631 }
    632 
    633 bool ToolChain::HasNativeLLVMSupport() const {
    634   return false;
    635 }
    636 
    637 bool ToolChain::isCrossCompiling() const {
    638   llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
    639   switch (HostTriple.getArch()) {
    640   // The A32/T32/T16 instruction sets are not separate architectures in this
    641   // context.
    642   case llvm::Triple::arm:
    643   case llvm::Triple::armeb:
    644   case llvm::Triple::thumb:
    645   case llvm::Triple::thumbeb:
    646     return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
    647            getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
    648   default:
    649     return HostTriple.getArch() != getArch();
    650   }
    651 }
    652 
    653 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
    654   return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
    655                      VersionTuple());
    656 }
    657 
    658 llvm::ExceptionHandling
    659 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
    660   return llvm::ExceptionHandling::None;
    661 }
    662 
    663 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
    664   if (Model == "single") {
    665     // FIXME: 'single' is only supported on ARM and WebAssembly so far.
    666     return Triple.getArch() == llvm::Triple::arm ||
    667            Triple.getArch() == llvm::Triple::armeb ||
    668            Triple.getArch() == llvm::Triple::thumb ||
    669            Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
    670   } else if (Model == "posix")
    671     return true;
    672 
    673   return false;
    674 }
    675 
    676 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
    677                                          types::ID InputType) const {
    678   switch (getTriple().getArch()) {
    679   default:
    680     return getTripleString();
    681 
    682   case llvm::Triple::x86_64: {
    683     llvm::Triple Triple = getTriple();
    684     if (!Triple.isOSBinFormatMachO())
    685       return getTripleString();
    686 
    687     if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
    688       // x86_64h goes in the triple. Other -march options just use the
    689       // vanilla triple we already have.
    690       StringRef MArch = A->getValue();
    691       if (MArch == "x86_64h")
    692         Triple.setArchName(MArch);
    693     }
    694     return Triple.getTriple();
    695   }
    696   case llvm::Triple::aarch64: {
    697     llvm::Triple Triple = getTriple();
    698     if (!Triple.isOSBinFormatMachO())
    699       return getTripleString();
    700 
    701     if (Triple.isArm64e())
    702       return getTripleString();
    703 
    704     // FIXME: older versions of ld64 expect the "arm64" component in the actual
    705     // triple string and query it to determine whether an LTO file can be
    706     // handled. Remove this when we don't care any more.
    707     Triple.setArchName("arm64");
    708     return Triple.getTriple();
    709   }
    710   case llvm::Triple::aarch64_32:
    711     return getTripleString();
    712   case llvm::Triple::arm:
    713   case llvm::Triple::armeb:
    714   case llvm::Triple::thumb:
    715   case llvm::Triple::thumbeb: {
    716     llvm::Triple Triple = getTriple();
    717     tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
    718     tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
    719     return Triple.getTriple();
    720   }
    721   }
    722 }
    723 
    724 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
    725                                                    types::ID InputType) const {
    726   return ComputeLLVMTriple(Args, InputType);
    727 }
    728 
    729 std::string ToolChain::computeSysRoot() const {
    730   return D.SysRoot;
    731 }
    732 
    733 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
    734                                           ArgStringList &CC1Args) const {
    735   // Each toolchain should provide the appropriate include flags.
    736 }
    737 
    738 void ToolChain::addClangTargetOptions(
    739     const ArgList &DriverArgs, ArgStringList &CC1Args,
    740     Action::OffloadKind DeviceOffloadKind) const {}
    741 
    742 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
    743 
    744 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
    745                                  llvm::opt::ArgStringList &CmdArgs) const {
    746   if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
    747     return;
    748 
    749   CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
    750 }
    751 
    752 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
    753     const ArgList &Args) const {
    754   if (runtimeLibType)
    755     return *runtimeLibType;
    756 
    757   const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
    758   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
    759 
    760   // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
    761   if (LibName == "compiler-rt")
    762     runtimeLibType = ToolChain::RLT_CompilerRT;
    763   else if (LibName == "libgcc")
    764     runtimeLibType = ToolChain::RLT_Libgcc;
    765   else if (LibName == "platform")
    766     runtimeLibType = GetDefaultRuntimeLibType();
    767   else {
    768     if (A)
    769       getDriver().Diag(diag::err_drv_invalid_rtlib_name)
    770           << A->getAsString(Args);
    771 
    772     runtimeLibType = GetDefaultRuntimeLibType();
    773   }
    774 
    775   return *runtimeLibType;
    776 }
    777 
    778 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
    779     const ArgList &Args) const {
    780   if (unwindLibType)
    781     return *unwindLibType;
    782 
    783   const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
    784   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
    785 
    786   if (LibName == "none")
    787     unwindLibType = ToolChain::UNW_None;
    788   else if (LibName == "platform" || LibName == "") {
    789     ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
    790     if (RtLibType == ToolChain::RLT_CompilerRT) {
    791       if (getTriple().isAndroid())
    792         unwindLibType = ToolChain::UNW_CompilerRT;
    793       else
    794         unwindLibType = ToolChain::UNW_None;
    795     } else if (RtLibType == ToolChain::RLT_Libgcc)
    796       unwindLibType = ToolChain::UNW_Libgcc;
    797   } else if (LibName == "libunwind") {
    798     if (GetRuntimeLibType(Args) == RLT_Libgcc)
    799       getDriver().Diag(diag::err_drv_incompatible_unwindlib);
    800     unwindLibType = ToolChain::UNW_CompilerRT;
    801   } else if (LibName == "libgcc")
    802     unwindLibType = ToolChain::UNW_Libgcc;
    803   else {
    804     if (A)
    805       getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
    806           << A->getAsString(Args);
    807 
    808     unwindLibType = GetDefaultUnwindLibType();
    809   }
    810 
    811   return *unwindLibType;
    812 }
    813 
    814 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
    815   if (cxxStdlibType)
    816     return *cxxStdlibType;
    817 
    818   const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
    819   StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
    820 
    821   // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
    822   if (LibName == "libc++")
    823     cxxStdlibType = ToolChain::CST_Libcxx;
    824   else if (LibName == "libstdc++")
    825     cxxStdlibType = ToolChain::CST_Libstdcxx;
    826   else if (LibName == "platform")
    827     cxxStdlibType = GetDefaultCXXStdlibType();
    828   else {
    829     if (A)
    830       getDriver().Diag(diag::err_drv_invalid_stdlib_name)
    831           << A->getAsString(Args);
    832 
    833     cxxStdlibType = GetDefaultCXXStdlibType();
    834   }
    835 
    836   return *cxxStdlibType;
    837 }
    838 
    839 /// Utility function to add a system include directory to CC1 arguments.
    840 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
    841                                             ArgStringList &CC1Args,
    842                                             const Twine &Path) {
    843   CC1Args.push_back("-internal-isystem");
    844   CC1Args.push_back(DriverArgs.MakeArgString(Path));
    845 }
    846 
    847 /// Utility function to add a system include directory with extern "C"
    848 /// semantics to CC1 arguments.
    849 ///
    850 /// Note that this should be used rarely, and only for directories that
    851 /// historically and for legacy reasons are treated as having implicit extern
    852 /// "C" semantics. These semantics are *ignored* by and large today, but its
    853 /// important to preserve the preprocessor changes resulting from the
    854 /// classification.
    855 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
    856                                                    ArgStringList &CC1Args,
    857                                                    const Twine &Path) {
    858   CC1Args.push_back("-internal-externc-isystem");
    859   CC1Args.push_back(DriverArgs.MakeArgString(Path));
    860 }
    861 
    862 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
    863                                                 ArgStringList &CC1Args,
    864                                                 const Twine &Path) {
    865   if (llvm::sys::fs::exists(Path))
    866     addExternCSystemInclude(DriverArgs, CC1Args, Path);
    867 }
    868 
    869 /// Utility function to add a list of system include directories to CC1.
    870 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
    871                                              ArgStringList &CC1Args,
    872                                              ArrayRef<StringRef> Paths) {
    873   for (const auto &Path : Paths) {
    874     CC1Args.push_back("-internal-isystem");
    875     CC1Args.push_back(DriverArgs.MakeArgString(Path));
    876   }
    877 }
    878 
    879 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
    880   std::error_code EC;
    881   int MaxVersion = 0;
    882   std::string MaxVersionString;
    883   SmallString<128> Path(IncludePath);
    884   llvm::sys::path::append(Path, "c++");
    885   for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
    886        !EC && LI != LE; LI = LI.increment(EC)) {
    887     StringRef VersionText = llvm::sys::path::filename(LI->path());
    888     int Version;
    889     if (VersionText[0] == 'v' &&
    890         !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
    891       if (Version > MaxVersion) {
    892         MaxVersion = Version;
    893         MaxVersionString = std::string(VersionText);
    894       }
    895     }
    896   }
    897   if (!MaxVersion)
    898     return "";
    899   return MaxVersionString;
    900 }
    901 
    902 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
    903                                              ArgStringList &CC1Args) const {
    904   // Header search paths should be handled by each of the subclasses.
    905   // Historically, they have not been, and instead have been handled inside of
    906   // the CC1-layer frontend. As the logic is hoisted out, this generic function
    907   // will slowly stop being called.
    908   //
    909   // While it is being called, replicate a bit of a hack to propagate the
    910   // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
    911   // header search paths with it. Once all systems are overriding this
    912   // function, the CC1 flag and this line can be removed.
    913   DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
    914 }
    915 
    916 void ToolChain::AddClangCXXStdlibIsystemArgs(
    917     const llvm::opt::ArgList &DriverArgs,
    918     llvm::opt::ArgStringList &CC1Args) const {
    919   DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
    920   if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
    921                          options::OPT_nostdlibinc))
    922     for (const auto &P :
    923          DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
    924       addSystemInclude(DriverArgs, CC1Args, P);
    925 }
    926 
    927 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
    928   return getDriver().CCCIsCXX() &&
    929          !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
    930                       options::OPT_nostdlibxx);
    931 }
    932 
    933 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
    934                                     ArgStringList &CmdArgs) const {
    935   assert(!Args.hasArg(options::OPT_nostdlibxx) &&
    936          "should not have called this");
    937   CXXStdlibType Type = GetCXXStdlibType(Args);
    938 
    939   switch (Type) {
    940   case ToolChain::CST_Libcxx:
    941     CmdArgs.push_back("-lc++");
    942     break;
    943 
    944   case ToolChain::CST_Libstdcxx:
    945     CmdArgs.push_back("-lstdc++");
    946     break;
    947   }
    948 }
    949 
    950 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
    951                                    ArgStringList &CmdArgs) const {
    952   for (const auto &LibPath : getFilePaths())
    953     if(LibPath.length() > 0)
    954       CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
    955 }
    956 
    957 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
    958                                  ArgStringList &CmdArgs) const {
    959   CmdArgs.push_back("-lcc_kext");
    960 }
    961 
    962 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
    963                                            std::string &Path) const {
    964   // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
    965   // (to keep the linker options consistent with gcc and clang itself).
    966   if (!isOptimizationLevelFast(Args)) {
    967     // Check if -ffast-math or -funsafe-math.
    968     Arg *A =
    969       Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
    970                       options::OPT_funsafe_math_optimizations,
    971                       options::OPT_fno_unsafe_math_optimizations);
    972 
    973     if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
    974         A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
    975       return false;
    976   }
    977   // If crtfastmath.o exists add it to the arguments.
    978   Path = GetFilePath("crtfastmath.o");
    979   return (Path != "crtfastmath.o"); // Not found.
    980 }
    981 
    982 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
    983                                               ArgStringList &CmdArgs) const {
    984   std::string Path;
    985   if (isFastMathRuntimeAvailable(Args, Path)) {
    986     CmdArgs.push_back(Args.MakeArgString(Path));
    987     return true;
    988   }
    989 
    990   return false;
    991 }
    992 
    993 SanitizerMask ToolChain::getSupportedSanitizers() const {
    994   // Return sanitizers which don't require runtime support and are not
    995   // platform dependent.
    996 
    997   SanitizerMask Res =
    998       (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
    999        ~SanitizerKind::Function) |
   1000       (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
   1001       SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
   1002       SanitizerKind::UnsignedIntegerOverflow |
   1003       SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
   1004       SanitizerKind::Nullability | SanitizerKind::LocalBounds;
   1005   if (getTriple().getArch() == llvm::Triple::x86 ||
   1006       getTriple().getArch() == llvm::Triple::x86_64 ||
   1007       getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
   1008       getTriple().isAArch64())
   1009     Res |= SanitizerKind::CFIICall;
   1010   if (getTriple().getArch() == llvm::Triple::x86_64 ||
   1011       getTriple().isAArch64(64) || getTriple().isRISCV())
   1012     Res |= SanitizerKind::ShadowCallStack;
   1013   if (getTriple().isAArch64(64))
   1014     Res |= SanitizerKind::MemTag;
   1015   return Res;
   1016 }
   1017 
   1018 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
   1019                                    ArgStringList &CC1Args) const {}
   1020 
   1021 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
   1022                                   ArgStringList &CC1Args) const {}
   1023 
   1024 llvm::SmallVector<std::string, 12>
   1025 ToolChain::getHIPDeviceLibs(const ArgList &DriverArgs) const {
   1026   return {};
   1027 }
   1028 
   1029 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
   1030                                     ArgStringList &CC1Args) const {}
   1031 
   1032 static VersionTuple separateMSVCFullVersion(unsigned Version) {
   1033   if (Version < 100)
   1034     return VersionTuple(Version);
   1035 
   1036   if (Version < 10000)
   1037     return VersionTuple(Version / 100, Version % 100);
   1038 
   1039   unsigned Build = 0, Factor = 1;
   1040   for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
   1041     Build = Build + (Version % 10) * Factor;
   1042   return VersionTuple(Version / 100, Version % 100, Build);
   1043 }
   1044 
   1045 VersionTuple
   1046 ToolChain::computeMSVCVersion(const Driver *D,
   1047                               const llvm::opt::ArgList &Args) const {
   1048   const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
   1049   const Arg *MSCompatibilityVersion =
   1050       Args.getLastArg(options::OPT_fms_compatibility_version);
   1051 
   1052   if (MSCVersion && MSCompatibilityVersion) {
   1053     if (D)
   1054       D->Diag(diag::err_drv_argument_not_allowed_with)
   1055           << MSCVersion->getAsString(Args)
   1056           << MSCompatibilityVersion->getAsString(Args);
   1057     return VersionTuple();
   1058   }
   1059 
   1060   if (MSCompatibilityVersion) {
   1061     VersionTuple MSVT;
   1062     if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
   1063       if (D)
   1064         D->Diag(diag::err_drv_invalid_value)
   1065             << MSCompatibilityVersion->getAsString(Args)
   1066             << MSCompatibilityVersion->getValue();
   1067     } else {
   1068       return MSVT;
   1069     }
   1070   }
   1071 
   1072   if (MSCVersion) {
   1073     unsigned Version = 0;
   1074     if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
   1075       if (D)
   1076         D->Diag(diag::err_drv_invalid_value)
   1077             << MSCVersion->getAsString(Args) << MSCVersion->getValue();
   1078     } else {
   1079       return separateMSVCFullVersion(Version);
   1080     }
   1081   }
   1082 
   1083   return VersionTuple();
   1084 }
   1085 
   1086 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
   1087     const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
   1088     SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
   1089   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
   1090   const OptTable &Opts = getDriver().getOpts();
   1091   bool Modified = false;
   1092 
   1093   // Handle -Xopenmp-target flags
   1094   for (auto *A : Args) {
   1095     // Exclude flags which may only apply to the host toolchain.
   1096     // Do not exclude flags when the host triple (AuxTriple)
   1097     // matches the current toolchain triple. If it is not present
   1098     // at all, target and host share a toolchain.
   1099     if (A->getOption().matches(options::OPT_m_Group)) {
   1100       if (SameTripleAsHost)
   1101         DAL->append(A);
   1102       else
   1103         Modified = true;
   1104       continue;
   1105     }
   1106 
   1107     unsigned Index;
   1108     unsigned Prev;
   1109     bool XOpenMPTargetNoTriple =
   1110         A->getOption().matches(options::OPT_Xopenmp_target);
   1111 
   1112     if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
   1113       // Passing device args: -Xopenmp-target=<triple> -opt=val.
   1114       if (A->getValue(0) == getTripleString())
   1115         Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
   1116       else
   1117         continue;
   1118     } else if (XOpenMPTargetNoTriple) {
   1119       // Passing device args: -Xopenmp-target -opt=val.
   1120       Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
   1121     } else {
   1122       DAL->append(A);
   1123       continue;
   1124     }
   1125 
   1126     // Parse the argument to -Xopenmp-target.
   1127     Prev = Index;
   1128     std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
   1129     if (!XOpenMPTargetArg || Index > Prev + 1) {
   1130       getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
   1131           << A->getAsString(Args);
   1132       continue;
   1133     }
   1134     if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
   1135         Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
   1136       getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
   1137       continue;
   1138     }
   1139     XOpenMPTargetArg->setBaseArg(A);
   1140     A = XOpenMPTargetArg.release();
   1141     AllocatedArgs.push_back(A);
   1142     DAL->append(A);
   1143     Modified = true;
   1144   }
   1145 
   1146   if (Modified)
   1147     return DAL;
   1148 
   1149   delete DAL;
   1150   return nullptr;
   1151 }
   1152 
   1153 // TODO: Currently argument values separated by space e.g.
   1154 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
   1155 // fixed.
   1156 void ToolChain::TranslateXarchArgs(
   1157     const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
   1158     llvm::opt::DerivedArgList *DAL,
   1159     SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
   1160   const OptTable &Opts = getDriver().getOpts();
   1161   unsigned ValuePos = 1;
   1162   if (A->getOption().matches(options::OPT_Xarch_device) ||
   1163       A->getOption().matches(options::OPT_Xarch_host))
   1164     ValuePos = 0;
   1165 
   1166   unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
   1167   unsigned Prev = Index;
   1168   std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
   1169 
   1170   // If the argument parsing failed or more than one argument was
   1171   // consumed, the -Xarch_ argument's parameter tried to consume
   1172   // extra arguments. Emit an error and ignore.
   1173   //
   1174   // We also want to disallow any options which would alter the
   1175   // driver behavior; that isn't going to work in our model. We
   1176   // use options::NoXarchOption to control this.
   1177   if (!XarchArg || Index > Prev + 1) {
   1178     getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
   1179         << A->getAsString(Args);
   1180     return;
   1181   } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
   1182     auto &Diags = getDriver().getDiags();
   1183     unsigned DiagID =
   1184         Diags.getCustomDiagID(DiagnosticsEngine::Error,
   1185                               "invalid Xarch argument: '%0', not all driver "
   1186                               "options can be forwared via Xarch argument");
   1187     Diags.Report(DiagID) << A->getAsString(Args);
   1188     return;
   1189   }
   1190   XarchArg->setBaseArg(A);
   1191   A = XarchArg.release();
   1192   if (!AllocatedArgs)
   1193     DAL->AddSynthesizedArg(A);
   1194   else
   1195     AllocatedArgs->push_back(A);
   1196 }
   1197 
   1198 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
   1199     const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
   1200     Action::OffloadKind OFK,
   1201     SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
   1202   DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
   1203   bool Modified = false;
   1204 
   1205   bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
   1206   for (Arg *A : Args) {
   1207     bool NeedTrans = false;
   1208     bool Skip = false;
   1209     if (A->getOption().matches(options::OPT_Xarch_device)) {
   1210       NeedTrans = IsGPU;
   1211       Skip = !IsGPU;
   1212     } else if (A->getOption().matches(options::OPT_Xarch_host)) {
   1213       NeedTrans = !IsGPU;
   1214       Skip = IsGPU;
   1215     } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
   1216       // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
   1217       // they may need special translation.
   1218       // Skip this argument unless the architecture matches BoundArch
   1219       if (BoundArch.empty() || A->getValue(0) != BoundArch)
   1220         Skip = true;
   1221       else
   1222         NeedTrans = true;
   1223     }
   1224     if (NeedTrans || Skip)
   1225       Modified = true;
   1226     if (NeedTrans)
   1227       TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
   1228     if (!Skip)
   1229       DAL->append(A);
   1230   }
   1231 
   1232   if (Modified)
   1233     return DAL;
   1234 
   1235   delete DAL;
   1236   return nullptr;
   1237 }
   1238