[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Driver / ToolChain.cpp
blob26c5087b4ac2555da5cde9d0b32e7a5ba8da25f5
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 //===----------------------------------------------------------------------===//
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>
48 using namespace clang;
49 using namespace driver;
50 using namespace tools;
51 using namespace llvm;
52 using namespace llvm::opt;
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);
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;
70 // -frtti is default, except for the PS4/PS5 and DriverKit.
71 bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
72 return NoRTTI ? ToolChain::RM_Disabled : ToolChain::RM_Enabled;
75 ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
76 const ArgList &Args)
77 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
78 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)) {
79 auto addIfExists = [this](path_list &List, const std::string &Path) {
80 if (getVFS().exists(Path))
81 List.push_back(Path);
84 for (const auto &Path : getRuntimePaths())
85 addIfExists(getLibraryPaths(), Path);
86 for (const auto &Path : getStdlibPaths())
87 addIfExists(getFilePaths(), Path);
88 addIfExists(getFilePaths(), getArchSpecificLibPath());
91 void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
92 Triple.setEnvironment(Env);
93 if (EffectiveTriple != llvm::Triple())
94 EffectiveTriple.setEnvironment(Env);
97 ToolChain::~ToolChain() = default;
99 llvm::vfs::FileSystem &ToolChain::getVFS() const {
100 return getDriver().getVFS();
103 bool ToolChain::useIntegratedAs() const {
104 return Args.hasFlag(options::OPT_fintegrated_as,
105 options::OPT_fno_integrated_as,
106 IsIntegratedAssemblerDefault());
109 bool ToolChain::useIntegratedBackend() const {
110 assert(
111 ((IsIntegratedBackendDefault() && IsIntegratedBackendSupported()) ||
112 (!IsIntegratedBackendDefault() || IsNonIntegratedBackendSupported())) &&
113 "(Non-)integrated backend set incorrectly!");
115 bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
116 options::OPT_fno_integrated_objemitter,
117 IsIntegratedBackendDefault());
119 // Diagnose when integrated-objemitter options are not supported by this
120 // toolchain.
121 unsigned DiagID;
122 if ((IBackend && !IsIntegratedBackendSupported()) ||
123 (!IBackend && !IsNonIntegratedBackendSupported()))
124 DiagID = clang::diag::err_drv_unsupported_opt_for_target;
125 else
126 DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
127 Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
128 if (A && !IsNonIntegratedBackendSupported())
129 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
130 A = Args.getLastArg(options::OPT_fintegrated_objemitter);
131 if (A && !IsIntegratedBackendSupported())
132 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
134 return IBackend;
137 bool ToolChain::useRelaxRelocations() const {
138 return ENABLE_X86_RELAX_RELOCATIONS;
141 bool ToolChain::defaultToIEEELongDouble() const {
142 return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
145 SanitizerArgs
146 ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const {
147 SanitizerArgs SanArgs(*this, JobArgs, !SanitizerArgsChecked);
148 SanitizerArgsChecked = true;
149 return SanArgs;
152 const XRayArgs& ToolChain::getXRayArgs() const {
153 if (!XRayArguments.get())
154 XRayArguments.reset(new XRayArgs(*this, Args));
155 return *XRayArguments.get();
158 namespace {
160 struct DriverSuffix {
161 const char *Suffix;
162 const char *ModeFlag;
165 } // namespace
167 static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
168 // A list of known driver suffixes. Suffixes are compared against the
169 // program name in order. If there is a match, the frontend type is updated as
170 // necessary by applying the ModeFlag.
171 static const DriverSuffix DriverSuffixes[] = {
172 {"clang", nullptr},
173 {"clang++", "--driver-mode=g++"},
174 {"clang-c++", "--driver-mode=g++"},
175 {"clang-cc", nullptr},
176 {"clang-cpp", "--driver-mode=cpp"},
177 {"clang-g++", "--driver-mode=g++"},
178 {"clang-gcc", nullptr},
179 {"clang-cl", "--driver-mode=cl"},
180 {"cc", nullptr},
181 {"cpp", "--driver-mode=cpp"},
182 {"cl", "--driver-mode=cl"},
183 {"++", "--driver-mode=g++"},
184 {"flang", "--driver-mode=flang"},
185 {"clang-dxc", "--driver-mode=dxc"},
188 for (const auto &DS : DriverSuffixes) {
189 StringRef Suffix(DS.Suffix);
190 if (ProgName.endswith(Suffix)) {
191 Pos = ProgName.size() - Suffix.size();
192 return &DS;
195 return nullptr;
198 /// Normalize the program name from argv[0] by stripping the file extension if
199 /// present and lower-casing the string on Windows.
200 static std::string normalizeProgramName(llvm::StringRef Argv0) {
201 std::string ProgName = std::string(llvm::sys::path::stem(Argv0));
202 if (is_style_windows(llvm::sys::path::Style::native)) {
203 // Transform to lowercase for case insensitive file systems.
204 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
205 ::tolower);
207 return ProgName;
210 static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
211 // Try to infer frontend type and default target from the program name by
212 // comparing it against DriverSuffixes in order.
214 // If there is a match, the function tries to identify a target as prefix.
215 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
216 // prefix "x86_64-linux". If such a target prefix is found, it may be
217 // added via -target as implicit first argument.
218 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
220 if (!DS) {
221 // Try again after stripping any trailing version number:
222 // clang++3.5 -> clang++
223 ProgName = ProgName.rtrim("0123456789.");
224 DS = FindDriverSuffix(ProgName, Pos);
227 if (!DS) {
228 // Try again after stripping trailing -component.
229 // clang++-tot -> clang++
230 ProgName = ProgName.slice(0, ProgName.rfind('-'));
231 DS = FindDriverSuffix(ProgName, Pos);
233 return DS;
236 ParsedClangName
237 ToolChain::getTargetAndModeFromProgramName(StringRef PN) {
238 std::string ProgName = normalizeProgramName(PN);
239 size_t SuffixPos;
240 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
241 if (!DS)
242 return {};
243 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
245 size_t LastComponent = ProgName.rfind('-', SuffixPos);
246 if (LastComponent == std::string::npos)
247 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
248 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
249 SuffixEnd - LastComponent - 1);
251 // Infer target from the prefix.
252 StringRef Prefix(ProgName);
253 Prefix = Prefix.slice(0, LastComponent);
254 std::string IgnoredError;
255 bool IsRegistered =
256 llvm::TargetRegistry::lookupTarget(std::string(Prefix), IgnoredError);
257 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
258 IsRegistered};
261 StringRef ToolChain::getDefaultUniversalArchName() const {
262 // In universal driver terms, the arch name accepted by -arch isn't exactly
263 // the same as the ones that appear in the triple. Roughly speaking, this is
264 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
265 switch (Triple.getArch()) {
266 case llvm::Triple::aarch64: {
267 if (getTriple().isArm64e())
268 return "arm64e";
269 return "arm64";
271 case llvm::Triple::aarch64_32:
272 return "arm64_32";
273 case llvm::Triple::ppc:
274 return "ppc";
275 case llvm::Triple::ppcle:
276 return "ppcle";
277 case llvm::Triple::ppc64:
278 return "ppc64";
279 case llvm::Triple::ppc64le:
280 return "ppc64le";
281 default:
282 return Triple.getArchName();
286 std::string ToolChain::getInputFilename(const InputInfo &Input) const {
287 return Input.getFilename();
290 bool ToolChain::IsUnwindTablesDefault(const ArgList &Args) const {
291 return false;
294 Tool *ToolChain::getClang() const {
295 if (!Clang)
296 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
297 return Clang.get();
300 Tool *ToolChain::getFlang() const {
301 if (!Flang)
302 Flang.reset(new tools::Flang(*this));
303 return Flang.get();
306 Tool *ToolChain::buildAssembler() const {
307 return new tools::ClangAs(*this);
310 Tool *ToolChain::buildLinker() const {
311 llvm_unreachable("Linking is not supported by this toolchain");
314 Tool *ToolChain::buildStaticLibTool() const {
315 llvm_unreachable("Creating static lib is not supported by this toolchain");
318 Tool *ToolChain::getAssemble() const {
319 if (!Assemble)
320 Assemble.reset(buildAssembler());
321 return Assemble.get();
324 Tool *ToolChain::getClangAs() const {
325 if (!Assemble)
326 Assemble.reset(new tools::ClangAs(*this));
327 return Assemble.get();
330 Tool *ToolChain::getLink() const {
331 if (!Link)
332 Link.reset(buildLinker());
333 return Link.get();
336 Tool *ToolChain::getStaticLibTool() const {
337 if (!StaticLibTool)
338 StaticLibTool.reset(buildStaticLibTool());
339 return StaticLibTool.get();
342 Tool *ToolChain::getIfsMerge() const {
343 if (!IfsMerge)
344 IfsMerge.reset(new tools::ifstool::Merger(*this));
345 return IfsMerge.get();
348 Tool *ToolChain::getOffloadBundler() const {
349 if (!OffloadBundler)
350 OffloadBundler.reset(new tools::OffloadBundler(*this));
351 return OffloadBundler.get();
354 Tool *ToolChain::getOffloadPackager() const {
355 if (!OffloadPackager)
356 OffloadPackager.reset(new tools::OffloadPackager(*this));
357 return OffloadPackager.get();
360 Tool *ToolChain::getLinkerWrapper() const {
361 if (!LinkerWrapper)
362 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
363 return LinkerWrapper.get();
366 Tool *ToolChain::getTool(Action::ActionClass AC) const {
367 switch (AC) {
368 case Action::AssembleJobClass:
369 return getAssemble();
371 case Action::IfsMergeJobClass:
372 return getIfsMerge();
374 case Action::LinkJobClass:
375 return getLink();
377 case Action::StaticLibJobClass:
378 return getStaticLibTool();
380 case Action::InputClass:
381 case Action::BindArchClass:
382 case Action::OffloadClass:
383 case Action::LipoJobClass:
384 case Action::DsymutilJobClass:
385 case Action::VerifyDebugInfoJobClass:
386 llvm_unreachable("Invalid tool kind.");
388 case Action::CompileJobClass:
389 case Action::PrecompileJobClass:
390 case Action::HeaderModulePrecompileJobClass:
391 case Action::PreprocessJobClass:
392 case Action::ExtractAPIJobClass:
393 case Action::AnalyzeJobClass:
394 case Action::MigrateJobClass:
395 case Action::VerifyPCHJobClass:
396 case Action::BackendJobClass:
397 return getClang();
399 case Action::OffloadBundlingJobClass:
400 case Action::OffloadUnbundlingJobClass:
401 return getOffloadBundler();
403 case Action::OffloadPackagerJobClass:
404 return getOffloadPackager();
405 case Action::LinkerWrapperJobClass:
406 return getLinkerWrapper();
409 llvm_unreachable("Invalid tool kind.");
412 static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
413 const ArgList &Args) {
414 const llvm::Triple &Triple = TC.getTriple();
415 bool IsWindows = Triple.isOSWindows();
417 if (TC.isBareMetal())
418 return Triple.getArchName();
420 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
421 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
422 ? "armhf"
423 : "arm";
425 // For historic reasons, Android library is using i686 instead of i386.
426 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
427 return "i686";
429 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
430 return "x32";
432 return llvm::Triple::getArchTypeName(TC.getArch());
435 StringRef ToolChain::getOSLibName() const {
436 if (Triple.isOSDarwin())
437 return "darwin";
439 switch (Triple.getOS()) {
440 case llvm::Triple::FreeBSD:
441 return "freebsd";
442 case llvm::Triple::NetBSD:
443 return "netbsd";
444 case llvm::Triple::OpenBSD:
445 return "openbsd";
446 case llvm::Triple::Solaris:
447 return "sunos";
448 case llvm::Triple::AIX:
449 return "aix";
450 default:
451 return getOS();
455 std::string ToolChain::getCompilerRTPath() const {
456 SmallString<128> Path(getDriver().ResourceDir);
457 if (isBareMetal()) {
458 llvm::sys::path::append(Path, "lib", getOSLibName());
459 Path += SelectedMultilib.gccSuffix();
460 } else if (Triple.isOSUnknown()) {
461 llvm::sys::path::append(Path, "lib");
462 } else {
463 llvm::sys::path::append(Path, "lib", getOSLibName());
465 return std::string(Path.str());
468 std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
469 StringRef Component,
470 FileType Type) const {
471 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
472 return llvm::sys::path::filename(CRTAbsolutePath).str();
475 std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
476 StringRef Component,
477 FileType Type,
478 bool AddArch) const {
479 const llvm::Triple &TT = getTriple();
480 bool IsITANMSVCWindows =
481 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
483 const char *Prefix =
484 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
485 const char *Suffix;
486 switch (Type) {
487 case ToolChain::FT_Object:
488 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
489 break;
490 case ToolChain::FT_Static:
491 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
492 break;
493 case ToolChain::FT_Shared:
494 Suffix = TT.isOSWindows()
495 ? (TT.isWindowsGNUEnvironment() ? ".dll.a" : ".lib")
496 : ".so";
497 break;
500 std::string ArchAndEnv;
501 if (AddArch) {
502 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
503 const char *Env = TT.isAndroid() ? "-android" : "";
504 ArchAndEnv = ("-" + Arch + Env).str();
506 return (Prefix + Twine("clang_rt.") + Component + ArchAndEnv + Suffix).str();
509 std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
510 FileType Type) const {
511 // Check for runtime files in the new layout without the architecture first.
512 std::string CRTBasename =
513 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
514 for (const auto &LibPath : getLibraryPaths()) {
515 SmallString<128> P(LibPath);
516 llvm::sys::path::append(P, CRTBasename);
517 if (getVFS().exists(P))
518 return std::string(P.str());
521 // Fall back to the old expected compiler-rt name if the new one does not
522 // exist.
523 CRTBasename =
524 buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/true);
525 SmallString<128> Path(getCompilerRTPath());
526 llvm::sys::path::append(Path, CRTBasename);
527 return std::string(Path.str());
530 const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
531 StringRef Component,
532 FileType Type) const {
533 return Args.MakeArgString(getCompilerRT(Args, Component, Type));
536 ToolChain::path_list ToolChain::getRuntimePaths() const {
537 path_list Paths;
538 auto addPathForTriple = [this, &Paths](const llvm::Triple &Triple) {
539 SmallString<128> P(D.ResourceDir);
540 llvm::sys::path::append(P, "lib", Triple.str());
541 Paths.push_back(std::string(P.str()));
544 addPathForTriple(getTriple());
546 // Android targets may include an API level at the end. We still want to fall
547 // back on a path without the API level.
548 if (getTriple().isAndroid() &&
549 getTriple().getEnvironmentName() != "android") {
550 llvm::Triple TripleWithoutLevel = getTriple();
551 TripleWithoutLevel.setEnvironmentName("android");
552 addPathForTriple(TripleWithoutLevel);
555 return Paths;
558 ToolChain::path_list ToolChain::getStdlibPaths() const {
559 path_list Paths;
560 SmallString<128> P(D.Dir);
561 llvm::sys::path::append(P, "..", "lib", getTripleString());
562 Paths.push_back(std::string(P.str()));
564 return Paths;
567 std::string ToolChain::getArchSpecificLibPath() const {
568 SmallString<128> Path(getDriver().ResourceDir);
569 llvm::sys::path::append(Path, "lib", getOSLibName(),
570 llvm::Triple::getArchTypeName(getArch()));
571 return std::string(Path.str());
574 bool ToolChain::needsProfileRT(const ArgList &Args) {
575 if (Args.hasArg(options::OPT_noprofilelib))
576 return false;
578 return Args.hasArg(options::OPT_fprofile_generate) ||
579 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
580 Args.hasArg(options::OPT_fcs_profile_generate) ||
581 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
582 Args.hasArg(options::OPT_fprofile_instr_generate) ||
583 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
584 Args.hasArg(options::OPT_fcreate_profile) ||
585 Args.hasArg(options::OPT_forder_file_instrumentation);
588 bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
589 return Args.hasArg(options::OPT_coverage) ||
590 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
591 false);
594 Tool *ToolChain::SelectTool(const JobAction &JA) const {
595 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
596 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
597 Action::ActionClass AC = JA.getKind();
598 if (AC == Action::AssembleJobClass && useIntegratedAs())
599 return getClangAs();
600 return getTool(AC);
603 std::string ToolChain::GetFilePath(const char *Name) const {
604 return D.GetFilePath(Name, *this);
607 std::string ToolChain::GetProgramPath(const char *Name) const {
608 return D.GetProgramPath(Name, *this);
611 std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
612 if (LinkerIsLLD)
613 *LinkerIsLLD = false;
615 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
616 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
617 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
618 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
620 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
621 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
622 // contain a path component separator.
623 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
624 std::string Path(A->getValue());
625 if (!Path.empty()) {
626 if (llvm::sys::path::parent_path(Path).empty())
627 Path = GetProgramPath(A->getValue());
628 if (llvm::sys::fs::can_execute(Path))
629 return std::string(Path);
631 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
632 return GetProgramPath(getDefaultLinker());
634 // If we're passed -fuse-ld= with no argument, or with the argument ld,
635 // then use whatever the default system linker is.
636 if (UseLinker.empty() || UseLinker == "ld") {
637 const char *DefaultLinker = getDefaultLinker();
638 if (llvm::sys::path::is_absolute(DefaultLinker))
639 return std::string(DefaultLinker);
640 else
641 return GetProgramPath(DefaultLinker);
644 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
645 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
646 // to a relative path is surprising. This is more complex due to priorities
647 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
648 if (UseLinker.contains('/'))
649 getDriver().Diag(diag::warn_drv_fuse_ld_path);
651 if (llvm::sys::path::is_absolute(UseLinker)) {
652 // If we're passed what looks like an absolute path, don't attempt to
653 // second-guess that.
654 if (llvm::sys::fs::can_execute(UseLinker))
655 return std::string(UseLinker);
656 } else {
657 llvm::SmallString<8> LinkerName;
658 if (Triple.isOSDarwin())
659 LinkerName.append("ld64.");
660 else
661 LinkerName.append("ld.");
662 LinkerName.append(UseLinker);
664 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
665 if (llvm::sys::fs::can_execute(LinkerPath)) {
666 if (LinkerIsLLD)
667 *LinkerIsLLD = UseLinker == "lld";
668 return LinkerPath;
672 if (A)
673 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
675 return GetProgramPath(getDefaultLinker());
678 std::string ToolChain::GetStaticLibToolPath() const {
679 // TODO: Add support for static lib archiving on Windows
680 if (Triple.isOSDarwin())
681 return GetProgramPath("libtool");
682 return GetProgramPath("llvm-ar");
685 types::ID ToolChain::LookupTypeForExtension(StringRef Ext) const {
686 types::ID id = types::lookupTypeForExtension(Ext);
688 // Flang always runs the preprocessor and has no notion of "preprocessed
689 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
690 // them differently.
691 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
692 id = types::TY_Fortran;
694 return id;
697 bool ToolChain::HasNativeLLVMSupport() const {
698 return false;
701 bool ToolChain::isCrossCompiling() const {
702 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
703 switch (HostTriple.getArch()) {
704 // The A32/T32/T16 instruction sets are not separate architectures in this
705 // context.
706 case llvm::Triple::arm:
707 case llvm::Triple::armeb:
708 case llvm::Triple::thumb:
709 case llvm::Triple::thumbeb:
710 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
711 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
712 default:
713 return HostTriple.getArch() != getArch();
717 ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
718 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
719 VersionTuple());
722 llvm::ExceptionHandling
723 ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
724 return llvm::ExceptionHandling::None;
727 bool ToolChain::isThreadModelSupported(const StringRef Model) const {
728 if (Model == "single") {
729 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
730 return Triple.getArch() == llvm::Triple::arm ||
731 Triple.getArch() == llvm::Triple::armeb ||
732 Triple.getArch() == llvm::Triple::thumb ||
733 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
734 } else if (Model == "posix")
735 return true;
737 return false;
740 std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
741 types::ID InputType) const {
742 switch (getTriple().getArch()) {
743 default:
744 return getTripleString();
746 case llvm::Triple::x86_64: {
747 llvm::Triple Triple = getTriple();
748 if (!Triple.isOSBinFormatMachO())
749 return getTripleString();
751 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
752 // x86_64h goes in the triple. Other -march options just use the
753 // vanilla triple we already have.
754 StringRef MArch = A->getValue();
755 if (MArch == "x86_64h")
756 Triple.setArchName(MArch);
758 return Triple.getTriple();
760 case llvm::Triple::aarch64: {
761 llvm::Triple Triple = getTriple();
762 if (!Triple.isOSBinFormatMachO())
763 return getTripleString();
765 if (Triple.isArm64e())
766 return getTripleString();
768 // FIXME: older versions of ld64 expect the "arm64" component in the actual
769 // triple string and query it to determine whether an LTO file can be
770 // handled. Remove this when we don't care any more.
771 Triple.setArchName("arm64");
772 return Triple.getTriple();
774 case llvm::Triple::aarch64_32:
775 return getTripleString();
776 case llvm::Triple::arm:
777 case llvm::Triple::armeb:
778 case llvm::Triple::thumb:
779 case llvm::Triple::thumbeb: {
780 llvm::Triple Triple = getTriple();
781 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
782 tools::arm::setFloatABIInTriple(getDriver(), Args, Triple);
783 return Triple.getTriple();
788 std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
789 types::ID InputType) const {
790 return ComputeLLVMTriple(Args, InputType);
793 std::string ToolChain::computeSysRoot() const {
794 return D.SysRoot;
797 void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
798 ArgStringList &CC1Args) const {
799 // Each toolchain should provide the appropriate include flags.
802 void ToolChain::addClangTargetOptions(
803 const ArgList &DriverArgs, ArgStringList &CC1Args,
804 Action::OffloadKind DeviceOffloadKind) const {}
806 void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
808 void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
809 llvm::opt::ArgStringList &CmdArgs) const {
810 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
811 return;
813 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
816 ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
817 const ArgList &Args) const {
818 if (runtimeLibType)
819 return *runtimeLibType;
821 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
822 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
824 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
825 if (LibName == "compiler-rt")
826 runtimeLibType = ToolChain::RLT_CompilerRT;
827 else if (LibName == "libgcc")
828 runtimeLibType = ToolChain::RLT_Libgcc;
829 else if (LibName == "platform")
830 runtimeLibType = GetDefaultRuntimeLibType();
831 else {
832 if (A)
833 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
834 << A->getAsString(Args);
836 runtimeLibType = GetDefaultRuntimeLibType();
839 return *runtimeLibType;
842 ToolChain::UnwindLibType ToolChain::GetUnwindLibType(
843 const ArgList &Args) const {
844 if (unwindLibType)
845 return *unwindLibType;
847 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
848 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
850 if (LibName == "none")
851 unwindLibType = ToolChain::UNW_None;
852 else if (LibName == "platform" || LibName == "") {
853 ToolChain::RuntimeLibType RtLibType = GetRuntimeLibType(Args);
854 if (RtLibType == ToolChain::RLT_CompilerRT) {
855 if (getTriple().isAndroid() || getTriple().isOSAIX())
856 unwindLibType = ToolChain::UNW_CompilerRT;
857 else
858 unwindLibType = ToolChain::UNW_None;
859 } else if (RtLibType == ToolChain::RLT_Libgcc)
860 unwindLibType = ToolChain::UNW_Libgcc;
861 } else if (LibName == "libunwind") {
862 if (GetRuntimeLibType(Args) == RLT_Libgcc)
863 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
864 unwindLibType = ToolChain::UNW_CompilerRT;
865 } else if (LibName == "libgcc")
866 unwindLibType = ToolChain::UNW_Libgcc;
867 else {
868 if (A)
869 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
870 << A->getAsString(Args);
872 unwindLibType = GetDefaultUnwindLibType();
875 return *unwindLibType;
878 ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
879 if (cxxStdlibType)
880 return *cxxStdlibType;
882 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
883 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
885 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
886 if (LibName == "libc++")
887 cxxStdlibType = ToolChain::CST_Libcxx;
888 else if (LibName == "libstdc++")
889 cxxStdlibType = ToolChain::CST_Libstdcxx;
890 else if (LibName == "platform")
891 cxxStdlibType = GetDefaultCXXStdlibType();
892 else {
893 if (A)
894 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
895 << A->getAsString(Args);
897 cxxStdlibType = GetDefaultCXXStdlibType();
900 return *cxxStdlibType;
903 /// Utility function to add a system include directory to CC1 arguments.
904 /*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
905 ArgStringList &CC1Args,
906 const Twine &Path) {
907 CC1Args.push_back("-internal-isystem");
908 CC1Args.push_back(DriverArgs.MakeArgString(Path));
911 /// Utility function to add a system include directory with extern "C"
912 /// semantics to CC1 arguments.
914 /// Note that this should be used rarely, and only for directories that
915 /// historically and for legacy reasons are treated as having implicit extern
916 /// "C" semantics. These semantics are *ignored* by and large today, but its
917 /// important to preserve the preprocessor changes resulting from the
918 /// classification.
919 /*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
920 ArgStringList &CC1Args,
921 const Twine &Path) {
922 CC1Args.push_back("-internal-externc-isystem");
923 CC1Args.push_back(DriverArgs.MakeArgString(Path));
926 void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
927 ArgStringList &CC1Args,
928 const Twine &Path) {
929 if (llvm::sys::fs::exists(Path))
930 addExternCSystemInclude(DriverArgs, CC1Args, Path);
933 /// Utility function to add a list of system include directories to CC1.
934 /*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
935 ArgStringList &CC1Args,
936 ArrayRef<StringRef> Paths) {
937 for (const auto &Path : Paths) {
938 CC1Args.push_back("-internal-isystem");
939 CC1Args.push_back(DriverArgs.MakeArgString(Path));
943 /*static*/ std::string ToolChain::concat(StringRef Path, const Twine &A,
944 const Twine &B, const Twine &C,
945 const Twine &D) {
946 SmallString<128> Result(Path);
947 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
948 return std::string(Result);
951 std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
952 std::error_code EC;
953 int MaxVersion = 0;
954 std::string MaxVersionString;
955 SmallString<128> Path(IncludePath);
956 llvm::sys::path::append(Path, "c++");
957 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
958 !EC && LI != LE; LI = LI.increment(EC)) {
959 StringRef VersionText = llvm::sys::path::filename(LI->path());
960 int Version;
961 if (VersionText[0] == 'v' &&
962 !VersionText.slice(1, StringRef::npos).getAsInteger(10, Version)) {
963 if (Version > MaxVersion) {
964 MaxVersion = Version;
965 MaxVersionString = std::string(VersionText);
969 if (!MaxVersion)
970 return "";
971 return MaxVersionString;
974 void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
975 ArgStringList &CC1Args) const {
976 // Header search paths should be handled by each of the subclasses.
977 // Historically, they have not been, and instead have been handled inside of
978 // the CC1-layer frontend. As the logic is hoisted out, this generic function
979 // will slowly stop being called.
981 // While it is being called, replicate a bit of a hack to propagate the
982 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
983 // header search paths with it. Once all systems are overriding this
984 // function, the CC1 flag and this line can be removed.
985 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
988 void ToolChain::AddClangCXXStdlibIsystemArgs(
989 const llvm::opt::ArgList &DriverArgs,
990 llvm::opt::ArgStringList &CC1Args) const {
991 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
992 if (!DriverArgs.hasArg(options::OPT_nostdinc, options::OPT_nostdincxx,
993 options::OPT_nostdlibinc))
994 for (const auto &P :
995 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
996 addSystemInclude(DriverArgs, CC1Args, P);
999 bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1000 return getDriver().CCCIsCXX() &&
1001 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1002 options::OPT_nostdlibxx);
1005 void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1006 ArgStringList &CmdArgs) const {
1007 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1008 "should not have called this");
1009 CXXStdlibType Type = GetCXXStdlibType(Args);
1011 switch (Type) {
1012 case ToolChain::CST_Libcxx:
1013 CmdArgs.push_back("-lc++");
1014 if (Args.hasArg(options::OPT_fexperimental_library))
1015 CmdArgs.push_back("-lc++experimental");
1016 break;
1018 case ToolChain::CST_Libstdcxx:
1019 CmdArgs.push_back("-lstdc++");
1020 break;
1024 void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1025 ArgStringList &CmdArgs) const {
1026 for (const auto &LibPath : getFilePaths())
1027 if(LibPath.length() > 0)
1028 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1031 void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1032 ArgStringList &CmdArgs) const {
1033 CmdArgs.push_back("-lcc_kext");
1036 bool ToolChain::isFastMathRuntimeAvailable(const ArgList &Args,
1037 std::string &Path) const {
1038 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1039 // (to keep the linker options consistent with gcc and clang itself).
1040 if (!isOptimizationLevelFast(Args)) {
1041 // Check if -ffast-math or -funsafe-math.
1042 Arg *A =
1043 Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math,
1044 options::OPT_funsafe_math_optimizations,
1045 options::OPT_fno_unsafe_math_optimizations);
1047 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1048 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1049 return false;
1051 // If crtfastmath.o exists add it to the arguments.
1052 Path = GetFilePath("crtfastmath.o");
1053 return (Path != "crtfastmath.o"); // Not found.
1056 bool ToolChain::addFastMathRuntimeIfAvailable(const ArgList &Args,
1057 ArgStringList &CmdArgs) const {
1058 std::string Path;
1059 if (isFastMathRuntimeAvailable(Args, Path)) {
1060 CmdArgs.push_back(Args.MakeArgString(Path));
1061 return true;
1064 return false;
1067 SanitizerMask ToolChain::getSupportedSanitizers() const {
1068 // Return sanitizers which don't require runtime support and are not
1069 // platform dependent.
1071 SanitizerMask Res =
1072 (SanitizerKind::Undefined & ~SanitizerKind::Vptr &
1073 ~SanitizerKind::Function) |
1074 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1075 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1076 SanitizerKind::UnsignedIntegerOverflow |
1077 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1078 SanitizerKind::Nullability | SanitizerKind::LocalBounds;
1079 if (getTriple().getArch() == llvm::Triple::x86 ||
1080 getTriple().getArch() == llvm::Triple::x86_64 ||
1081 getTriple().getArch() == llvm::Triple::arm || getTriple().isWasm() ||
1082 getTriple().isAArch64() || getTriple().isRISCV())
1083 Res |= SanitizerKind::CFIICall;
1084 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1085 getTriple().isAArch64(64))
1086 Res |= SanitizerKind::KCFI;
1087 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1088 getTriple().isAArch64(64) || getTriple().isRISCV())
1089 Res |= SanitizerKind::ShadowCallStack;
1090 if (getTriple().isAArch64(64))
1091 Res |= SanitizerKind::MemTag;
1092 return Res;
1095 void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1096 ArgStringList &CC1Args) const {}
1098 void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1099 ArgStringList &CC1Args) const {}
1101 llvm::SmallVector<ToolChain::BitCodeLibraryInfo, 12>
1102 ToolChain::getDeviceLibs(const ArgList &DriverArgs) const {
1103 return {};
1106 void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1107 ArgStringList &CC1Args) const {}
1109 static VersionTuple separateMSVCFullVersion(unsigned Version) {
1110 if (Version < 100)
1111 return VersionTuple(Version);
1113 if (Version < 10000)
1114 return VersionTuple(Version / 100, Version % 100);
1116 unsigned Build = 0, Factor = 1;
1117 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1118 Build = Build + (Version % 10) * Factor;
1119 return VersionTuple(Version / 100, Version % 100, Build);
1122 VersionTuple
1123 ToolChain::computeMSVCVersion(const Driver *D,
1124 const llvm::opt::ArgList &Args) const {
1125 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1126 const Arg *MSCompatibilityVersion =
1127 Args.getLastArg(options::OPT_fms_compatibility_version);
1129 if (MSCVersion && MSCompatibilityVersion) {
1130 if (D)
1131 D->Diag(diag::err_drv_argument_not_allowed_with)
1132 << MSCVersion->getAsString(Args)
1133 << MSCompatibilityVersion->getAsString(Args);
1134 return VersionTuple();
1137 if (MSCompatibilityVersion) {
1138 VersionTuple MSVT;
1139 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
1140 if (D)
1141 D->Diag(diag::err_drv_invalid_value)
1142 << MSCompatibilityVersion->getAsString(Args)
1143 << MSCompatibilityVersion->getValue();
1144 } else {
1145 return MSVT;
1149 if (MSCVersion) {
1150 unsigned Version = 0;
1151 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
1152 if (D)
1153 D->Diag(diag::err_drv_invalid_value)
1154 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
1155 } else {
1156 return separateMSVCFullVersion(Version);
1160 return VersionTuple();
1163 llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
1164 const llvm::opt::DerivedArgList &Args, bool SameTripleAsHost,
1165 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
1166 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1167 const OptTable &Opts = getDriver().getOpts();
1168 bool Modified = false;
1170 // Handle -Xopenmp-target flags
1171 for (auto *A : Args) {
1172 // Exclude flags which may only apply to the host toolchain.
1173 // Do not exclude flags when the host triple (AuxTriple)
1174 // matches the current toolchain triple. If it is not present
1175 // at all, target and host share a toolchain.
1176 if (A->getOption().matches(options::OPT_m_Group)) {
1177 if (SameTripleAsHost)
1178 DAL->append(A);
1179 else
1180 Modified = true;
1181 continue;
1184 unsigned Index;
1185 unsigned Prev;
1186 bool XOpenMPTargetNoTriple =
1187 A->getOption().matches(options::OPT_Xopenmp_target);
1189 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
1190 llvm::Triple TT(getOpenMPTriple(A->getValue(0)));
1192 // Passing device args: -Xopenmp-target=<triple> -opt=val.
1193 if (TT.getTriple() == getTripleString())
1194 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
1195 else
1196 continue;
1197 } else if (XOpenMPTargetNoTriple) {
1198 // Passing device args: -Xopenmp-target -opt=val.
1199 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
1200 } else {
1201 DAL->append(A);
1202 continue;
1205 // Parse the argument to -Xopenmp-target.
1206 Prev = Index;
1207 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
1208 if (!XOpenMPTargetArg || Index > Prev + 1) {
1209 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
1210 << A->getAsString(Args);
1211 continue;
1213 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
1214 Args.getAllArgValues(options::OPT_fopenmp_targets_EQ).size() != 1) {
1215 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
1216 continue;
1218 XOpenMPTargetArg->setBaseArg(A);
1219 A = XOpenMPTargetArg.release();
1220 AllocatedArgs.push_back(A);
1221 DAL->append(A);
1222 Modified = true;
1225 if (Modified)
1226 return DAL;
1228 delete DAL;
1229 return nullptr;
1232 // TODO: Currently argument values separated by space e.g.
1233 // -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
1234 // fixed.
1235 void ToolChain::TranslateXarchArgs(
1236 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
1237 llvm::opt::DerivedArgList *DAL,
1238 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1239 const OptTable &Opts = getDriver().getOpts();
1240 unsigned ValuePos = 1;
1241 if (A->getOption().matches(options::OPT_Xarch_device) ||
1242 A->getOption().matches(options::OPT_Xarch_host))
1243 ValuePos = 0;
1245 unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(ValuePos));
1246 unsigned Prev = Index;
1247 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(Args, Index));
1249 // If the argument parsing failed or more than one argument was
1250 // consumed, the -Xarch_ argument's parameter tried to consume
1251 // extra arguments. Emit an error and ignore.
1253 // We also want to disallow any options which would alter the
1254 // driver behavior; that isn't going to work in our model. We
1255 // use options::NoXarchOption to control this.
1256 if (!XarchArg || Index > Prev + 1) {
1257 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
1258 << A->getAsString(Args);
1259 return;
1260 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
1261 auto &Diags = getDriver().getDiags();
1262 unsigned DiagID =
1263 Diags.getCustomDiagID(DiagnosticsEngine::Error,
1264 "invalid Xarch argument: '%0', not all driver "
1265 "options can be forwared via Xarch argument");
1266 Diags.Report(DiagID) << A->getAsString(Args);
1267 return;
1269 XarchArg->setBaseArg(A);
1270 A = XarchArg.release();
1271 if (!AllocatedArgs)
1272 DAL->AddSynthesizedArg(A);
1273 else
1274 AllocatedArgs->push_back(A);
1277 llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
1278 const llvm::opt::DerivedArgList &Args, StringRef BoundArch,
1279 Action::OffloadKind OFK,
1280 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
1281 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
1282 bool Modified = false;
1284 bool IsGPU = OFK == Action::OFK_Cuda || OFK == Action::OFK_HIP;
1285 for (Arg *A : Args) {
1286 bool NeedTrans = false;
1287 bool Skip = false;
1288 if (A->getOption().matches(options::OPT_Xarch_device)) {
1289 NeedTrans = IsGPU;
1290 Skip = !IsGPU;
1291 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
1292 NeedTrans = !IsGPU;
1293 Skip = IsGPU;
1294 } else if (A->getOption().matches(options::OPT_Xarch__) && IsGPU) {
1295 // Do not translate -Xarch_ options for non CUDA/HIP toolchain since
1296 // they may need special translation.
1297 // Skip this argument unless the architecture matches BoundArch
1298 if (BoundArch.empty() || A->getValue(0) != BoundArch)
1299 Skip = true;
1300 else
1301 NeedTrans = true;
1303 if (NeedTrans || Skip)
1304 Modified = true;
1305 if (NeedTrans)
1306 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
1307 if (!Skip)
1308 DAL->append(A);
1311 if (Modified)
1312 return DAL;
1314 delete DAL;
1315 return nullptr;