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