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