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