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