clang 24.0.0git
ToolChain.cpp
Go to the documentation of this file.
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
10#include "ClangCLArgs.h"
13#include "ToolChains/Arch/ARM.h"
15#include "ToolChains/Clang.h"
16#include "ToolChains/Flang.h"
20#include "clang/Config/config.h"
21#include "clang/Driver/Action.h"
23#include "clang/Driver/Driver.h"
25#include "clang/Driver/Job.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/Twine.h"
33#include "llvm/Config/llvm-config.h"
34#include "llvm/MC/MCTargetOptions.h"
35#include "llvm/MC/TargetRegistry.h"
36#include "llvm/Option/Arg.h"
37#include "llvm/Option/ArgList.h"
38#include "llvm/Option/OptTable.h"
39#include "llvm/Option/Option.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/FileSystem.h"
42#include "llvm/Support/FileUtilities.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/Process.h"
46#include "llvm/Support/VersionTuple.h"
47#include "llvm/Support/VirtualFileSystem.h"
48#include "llvm/TargetParser/AArch64TargetParser.h"
49#include "llvm/TargetParser/AMDGPUTargetParser.h"
50#include "llvm/TargetParser/RISCVISAInfo.h"
51#include "llvm/TargetParser/TargetParser.h"
52#include "llvm/TargetParser/Triple.h"
53#include <cassert>
54#include <cstddef>
55#include <cstring>
56#include <string>
57
58using namespace clang;
59using namespace driver;
60using namespace tools;
61using namespace llvm;
62using namespace llvm::opt;
63
64static llvm::opt::Arg *GetRTTIArgument(const ArgList &Args) {
65 return Args.getLastArg(options::OPT_mkernel, options::OPT_fapple_kext,
66 options::OPT_fno_rtti, options::OPT_frtti);
67}
68
69static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args,
70 const llvm::Triple &Triple,
71 const Arg *CachedRTTIArg) {
72 // Explicit rtti/no-rtti args
73 if (CachedRTTIArg) {
74 if (CachedRTTIArg->getOption().matches(options::OPT_frtti))
76 else
78 }
79
80 // -frtti is default, except for the PS4/PS5 and DriverKit.
81 bool NoRTTI = Triple.isPS() || Triple.isDriverKit();
83}
84
86 if (Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
87 true)) {
89 }
91}
92
93ToolChain::ToolChain(const Driver &D, const llvm::Triple &T,
94 const ArgList &Args)
95 : D(D), Triple(T), Args(Args), CachedRTTIArg(GetRTTIArgument(Args)),
96 CachedRTTIMode(CalculateRTTIMode(Args, Triple, CachedRTTIArg)),
97 CachedExceptionsMode(CalculateExceptionsMode(Args)) {
98 assert(T.str() == T.normalize() && "triple should be normalized");
99 auto addIfExists = [this](path_list &List, const std::string &Path) {
100 if (getVFS().exists(Path))
101 List.push_back(Path);
102 };
103
104 if (std::optional<std::string> Path = getRuntimePath())
105 getLibraryPaths().push_back(*Path);
106 if (std::optional<std::string> Path = getStdlibPath())
107 getFilePaths().push_back(*Path);
108 for (const auto &Path : getArchSpecificLibPaths())
109 addIfExists(getFilePaths(), Path);
110}
111
113 if (!SelectedMultilibs.empty())
114 return llvm::reverse(SelectedMultilibs);
115
117 return llvm::reverse(Default);
118}
119
120bool ToolChain::loadMultilibsFromYAML(const llvm::opt::ArgList &Args,
121 const Driver &D, StringRef Fallback) {
122 std::optional<std::string> MultilibPath =
123 findMultilibsYAML(Args, D, Fallback);
124 if (!MultilibPath)
125 return false;
126 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB =
127 D.getVFS().getBufferForFile(*MultilibPath);
128 if (!MB)
129 return false;
130
132 llvm::ErrorOr<MultilibSet> ErrorOrMultilibSet =
133 MultilibSet::parseYaml(*MB.get());
134 if (ErrorOrMultilibSet.getError())
135 return false;
136
137 Multilibs = std::move(ErrorOrMultilibSet.get());
138
139 SmallVector<StringRef> CustomFlagMacroDefines;
140 bool Result =
141 Multilibs.select(D, Flags, SelectedMultilibs, &CustomFlagMacroDefines);
142
143 // Custom flag macro defines are set by processCustomFlags regardless of
144 // whether variant selection succeeds.
145 MultilibMacroDefines.clear();
146 for (StringRef Define : CustomFlagMacroDefines)
147 MultilibMacroDefines.push_back(Define.str());
148
149 if (!Result) {
150 D.Diag(clang::diag::warn_drv_missing_multilib) << llvm::join(Flags, " ");
152 raw_svector_ostream OS(Data);
153 for (const Multilib &M : Multilibs)
154 if (!M.isError())
155 OS << "\n" << llvm::join(M.flags(), " ");
156 D.Diag(clang::diag::note_drv_available_multilibs) << OS.str();
157
158 for (const Multilib &M : SelectedMultilibs)
159 if (M.isError())
160 D.Diag(clang::diag::err_drv_multilib_custom_error)
161 << M.getErrorMessage();
162
163 SelectedMultilibs.clear();
164 return false;
165 }
166
167 // Prepend variant-specific library paths. The YAML's parent directory is
168 // the base for file paths; getRuntimePath() is the base for runtime paths.
169 StringRef YAMLBase = llvm::sys::path::parent_path(*MultilibPath);
170 std::optional<std::string> RuntimeDir = getRuntimePath();
171 size_t FileInsertPos = 0;
172 size_t LibInsertPos = 0;
173 for (const Multilib &M : getOrderedMultilibs()) {
174 if (M.isDefault())
175 continue;
176 SmallString<128> FilePath(YAMLBase);
177 llvm::sys::path::append(FilePath, M.gccSuffix());
178 getFilePaths().insert(getFilePaths().begin() + FileInsertPos,
179 std::string(FilePath));
180 ++FileInsertPos;
181 if (RuntimeDir) {
182 // The builtin runtime directories include the multilib path, as the
183 // compiler-rt library files come from a runtimes build.
184 SmallString<128> LibPath(*RuntimeDir);
185 llvm::sys::path::append(LibPath, M.gccSuffix());
186 getLibraryPaths().insert(getLibraryPaths().begin() + LibInsertPos,
187 std::string(LibPath));
188 ++LibInsertPos;
189 }
190 }
191
192 return true;
193}
194
195std::optional<std::string>
196ToolChain::findMultilibsYAML(const llvm::opt::ArgList &Args, const Driver &D,
197 StringRef FallbackDir) {
198 if (Arg *A = Args.getLastArg(options::OPT_multi_lib_config)) {
199 SmallString<128> MultilibPath(A->getValue());
200 if (!D.getVFS().exists(MultilibPath)) {
201 D.Diag(clang::diag::err_drv_no_such_file) << MultilibPath.str();
202 return std::nullopt;
203 }
204 return std::string(MultilibPath);
205 }
206
207 SmallString<128> MultilibPath;
208 if (!FallbackDir.empty())
209 MultilibPath = FallbackDir;
210 else if (std::optional<std::string> StdlibDir = getStdlibPath())
211 MultilibPath = *StdlibDir;
212 else
213 return std::nullopt;
214 llvm::sys::path::append(MultilibPath, "multilib.yaml");
215 if (!D.getVFS().exists(MultilibPath))
216 return std::nullopt;
217 return std::string(MultilibPath);
218}
219
220void ToolChain::setTripleEnvironment(llvm::Triple::EnvironmentType Env) {
221 Triple.setEnvironment(Env);
222 if (EffectiveTriple != llvm::Triple())
223 EffectiveTriple.setEnvironment(Env);
224}
225
226ToolChain::~ToolChain() = default;
227
228llvm::vfs::FileSystem &ToolChain::getVFS() const {
229 return getDriver().getVFS();
230}
231
233 return Args.hasFlag(options::OPT_fintegrated_as,
234 options::OPT_fno_integrated_as,
236}
237
239 assert(
242 "(Non-)integrated backend set incorrectly!");
243
244 bool IBackend = Args.hasFlag(options::OPT_fintegrated_objemitter,
245 options::OPT_fno_integrated_objemitter,
247
248 // Diagnose when integrated-objemitter options are not supported by this
249 // toolchain.
250 unsigned DiagID;
251 if ((IBackend && !IsIntegratedBackendSupported()) ||
252 (!IBackend && !IsNonIntegratedBackendSupported()))
253 DiagID = clang::diag::err_drv_unsupported_opt_for_target;
254 else
255 DiagID = clang::diag::warn_drv_unsupported_opt_for_target;
256 Arg *A = Args.getLastArg(options::OPT_fno_integrated_objemitter);
258 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
259 A = Args.getLastArg(options::OPT_fintegrated_objemitter);
261 D.Diag(DiagID) << A->getAsString(Args) << Triple.getTriple();
262
263 return IBackend;
264}
265
267 return ENABLE_X86_RELAX_RELOCATIONS;
268}
269
271 return PPC_LINUX_DEFAULT_IEEELONGDOUBLE && getTriple().isOSLinux();
272}
273
275 const llvm::opt::ArgList &Args) {
276 for (const Arg *MultilibFlagArg :
277 Args.filtered(options::OPT_fmultilib_flag)) {
278 List.push_back(MultilibFlagArg->getAsString(Args));
279 MultilibFlagArg->claim();
280 }
281}
282
283static void getAArch64MultilibFlags(const Driver &D,
284 const llvm::Triple &Triple,
285 const llvm::opt::ArgList &Args,
287 std::vector<StringRef> Features;
288 tools::aarch64::getAArch64TargetFeatures(D, Triple, Args, Features,
289 /*ForAS=*/false,
290 /*ForMultilib=*/true);
291 const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
292 llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
293 UnifiedFeatures.end());
294 std::vector<std::string> MArch;
295 for (const auto &Ext : AArch64::Extensions)
296 if (Ext.UserVisibleName.value())
297 if (FeatureSet.contains(AArch64::StrTab[Ext.PosTargetFeature]))
298 MArch.push_back(AArch64::StrTab[Ext.UserVisibleName].str());
299 for (const auto &Ext : AArch64::Extensions)
300 if (Ext.UserVisibleName.value())
301 if (FeatureSet.contains(AArch64::StrTab[Ext.NegTargetFeature]))
302 MArch.push_back(("no" + AArch64::StrTab[Ext.UserVisibleName]).str());
303 StringRef ArchName;
304 for (const auto &ArchInfo : AArch64::ArchInfos)
305 if (FeatureSet.contains(AArch64::StrTab[ArchInfo.ArchFeature]))
306 ArchName = AArch64::StrTab[ArchInfo.Name];
307 if (!ArchName.empty()) {
308 MArch.insert(MArch.begin(), ("-march=" + ArchName).str());
309 Result.push_back(llvm::join(MArch, "+"));
310 }
311
312 const Arg *BranchProtectionArg =
313 Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ);
314 if (BranchProtectionArg) {
315 Result.push_back(BranchProtectionArg->getAsString(Args));
316 }
317
318 if (FeatureSet.contains("+strict-align"))
319 Result.push_back("-mno-unaligned-access");
320 else
321 Result.push_back("-munaligned-access");
322
323 if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian,
324 options::OPT_mlittle_endian)) {
325 if (Endian->getOption().matches(options::OPT_mbig_endian))
326 Result.push_back(Endian->getAsString(Args));
327 }
328
329 const Arg *ABIArg = Args.getLastArgNoClaim(options::OPT_mabi_EQ);
330 if (ABIArg) {
331 Result.push_back(ABIArg->getAsString(Args));
332 }
333
334 if (const Arg *A = Args.getLastArg(options::OPT_O_Group);
335 A && A->getOption().matches(options::OPT_O)) {
336 switch (A->getValue()[0]) {
337 case 's':
338 Result.push_back("-Os");
339 break;
340 case 'z':
341 Result.push_back("-Oz");
342 break;
343 }
344 }
345}
346
347static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple,
348 llvm::Reloc::Model RelocationModel,
349 const llvm::opt::ArgList &Args,
351 std::vector<StringRef> Features;
352 llvm::ARM::FPUKind FPUKind = tools::arm::getARMTargetFeatures(
353 D, Triple, Args, Features, false /*ForAs*/, true /*ForMultilib*/);
354 const auto UnifiedFeatures = tools::unifyTargetFeatures(Features);
355 llvm::DenseSet<StringRef> FeatureSet(UnifiedFeatures.begin(),
356 UnifiedFeatures.end());
357 std::vector<std::string> MArch;
358 for (const auto &Ext : ARM::ARCHExtNames)
359 if (!Ext.Name.empty())
360 if (FeatureSet.contains(Ext.Feature))
361 MArch.push_back(Ext.Name.str());
362 for (const auto &Ext : ARM::ARCHExtNames)
363 if (!Ext.Name.empty())
364 if (FeatureSet.contains(Ext.NegFeature))
365 MArch.push_back(("no" + Ext.Name).str());
366 MArch.insert(MArch.begin(), ("-march=" + Triple.getArchName()).str());
367 Result.push_back(llvm::join(MArch, "+"));
368
369 switch (FPUKind) {
370#define ARM_FPU(NAME, KIND, VERSION, NEON_SUPPORT, RESTRICTION) \
371 case llvm::ARM::KIND: \
372 Result.push_back("-mfpu=" NAME); \
373 break;
374#include "llvm/TargetParser/ARMTargetParser.def"
375 default:
376 llvm_unreachable("Invalid FPUKind");
377 }
378
379 switch (arm::getARMFloatABI(D, Triple, Args)) {
380 case arm::FloatABI::Soft:
381 Result.push_back("-mfloat-abi=soft");
382 break;
383 case arm::FloatABI::SoftFP:
384 Result.push_back("-mfloat-abi=softfp");
385 break;
386 case arm::FloatABI::Hard:
387 Result.push_back("-mfloat-abi=hard");
388 break;
389 case arm::FloatABI::Invalid:
390 llvm_unreachable("Invalid float ABI");
391 }
392
393 if (RelocationModel == llvm::Reloc::ROPI ||
394 RelocationModel == llvm::Reloc::ROPI_RWPI)
395 Result.push_back("-fropi");
396 else
397 Result.push_back("-fno-ropi");
398
399 if (RelocationModel == llvm::Reloc::RWPI ||
400 RelocationModel == llvm::Reloc::ROPI_RWPI)
401 Result.push_back("-frwpi");
402 else
403 Result.push_back("-fno-rwpi");
404
405 const Arg *BranchProtectionArg =
406 Args.getLastArgNoClaim(options::OPT_mbranch_protection_EQ);
407 if (BranchProtectionArg) {
408 Result.push_back(BranchProtectionArg->getAsString(Args));
409 }
410
411 if (FeatureSet.contains("+strict-align"))
412 Result.push_back("-mno-unaligned-access");
413 else
414 Result.push_back("-munaligned-access");
415
416 if (Arg *Endian = Args.getLastArg(options::OPT_mbig_endian,
417 options::OPT_mlittle_endian)) {
418 if (Endian->getOption().matches(options::OPT_mbig_endian))
419 Result.push_back(Endian->getAsString(Args));
420 }
421
422 if (const Arg *A = Args.getLastArg(options::OPT_O_Group);
423 A && A->getOption().matches(options::OPT_O)) {
424 switch (A->getValue()[0]) {
425 case 's':
426 Result.push_back("-Os");
427 break;
428 case 'z':
429 Result.push_back("-Oz");
430 break;
431 }
432 }
433}
434
435static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple,
436 const llvm::opt::ArgList &Args,
438 bool hasShadowCallStack) {
439 std::string Arch = riscv::getRISCVArch(Args, Triple);
440 // Canonicalize arch for easier matching
441 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
442 Arch, /*EnableExperimentalExtensions*/ true);
443 if (!llvm::errorToBool(ISAInfo.takeError()))
444 Result.push_back("-march=" + (*ISAInfo)->toString());
445
446 Result.push_back(("-mabi=" + riscv::getRISCVABI(Args, Triple)).str());
447
448 if (hasShadowCallStack)
449 Result.push_back("-fsanitize=shadow-call-stack");
450 else
451 Result.push_back("-fno-sanitize=shadow-call-stack");
452
453 const Arg *CFProtectionArg =
454 Args.getLastArgNoClaim(options::OPT_fcf_protection_EQ);
455 StringRef CFProtectionVal =
456 CFProtectionArg ? CFProtectionArg->getValue() : "none";
457 Result.push_back(("-fcf-protection=" + CFProtectionVal).str());
458
459 if (CFProtectionVal == "branch" || CFProtectionVal == "full") {
460 if (const Arg *SchemeArg =
461 Args.getLastArgNoClaim(options::OPT_mcf_branch_label_scheme_EQ))
462 Result.push_back(SchemeArg->getAsString(Args));
463 }
464}
465
467ToolChain::getMultilibFlags(const llvm::opt::ArgList &Args) const {
468 using namespace clang::options;
469
470 std::vector<std::string> Result;
471 const llvm::Triple Triple(ComputeEffectiveClangTriple(Args));
472 Result.push_back("--target=" + Triple.str());
473
474 // A difference of relocation model (absolutely addressed data, PIC, Arm
475 // ROPI/RWPI) is likely to change whether a particular multilib variant is
476 // compatible with a given link. Determine the relocation model of the
477 // current link, so as to add appropriate multilib flags.
478 llvm::Reloc::Model RelocationModel;
479 unsigned PICLevel;
480 bool IsPIE;
481 {
482 RegisterEffectiveTriple TripleRAII(*this, Triple);
483 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(*this, Args);
484 }
485
486 switch (Triple.getArch()) {
487 case llvm::Triple::aarch64:
488 case llvm::Triple::aarch64_32:
489 case llvm::Triple::aarch64_be:
490 getAArch64MultilibFlags(D, Triple, Args, Result);
491 break;
492 case llvm::Triple::arm:
493 case llvm::Triple::armeb:
494 case llvm::Triple::thumb:
495 case llvm::Triple::thumbeb:
496 getARMMultilibFlags(D, Triple, RelocationModel, Args, Result);
497 break;
498 case llvm::Triple::riscv32:
499 case llvm::Triple::riscv64:
500 case llvm::Triple::riscv32be:
501 case llvm::Triple::riscv64be:
502 getRISCVMultilibFlags(D, Triple, Args, Result,
503 getSanitizerArgs(Args).hasShadowCallStack());
504 break;
505 default:
506 break;
507 }
508
510
511 if (Arg *CStdLibArg = Args.getLastArg(options::OPT_cstdlib_EQ))
512 Result.push_back(std::string(CStdLibArg->getOption().getPrefixedName()) +
513 CStdLibArg->getValue());
514
515 // Include fno-exceptions and fno-rtti
516 // to improve multilib selection
518 Result.push_back("-fno-rtti");
519 else
520 Result.push_back("-frtti");
521
523 Result.push_back("-fno-exceptions");
524 else
525 Result.push_back("-fexceptions");
526
527 if (RelocationModel == llvm::Reloc::PIC_)
528 Result.push_back(IsPIE ? (PICLevel > 1 ? "-fPIE" : "-fpie")
529 : (PICLevel > 1 ? "-fPIC" : "-fpic"));
530 else
531 Result.push_back("-fno-pic");
532
533 // Sort and remove duplicates.
534 std::sort(Result.begin(), Result.end());
535 Result.erase(llvm::unique(Result), Result.end());
536 return Result;
537}
538
540ToolChain::getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA,
541 Action::OffloadKind DeviceOffloadKind) const {
542 // When -fno-gpu-sanitize is specified for GPU targets, don't emit
543 // diagnostics about unsupported sanitizers for specific GPU arches,
544 // since sanitizers are disabled for the GPU anyway.
545 bool DiagnoseBoundArchErrors =
546 BoundArchSanitizerArgsChecked.insert(BA.ArchName).second;
547 if (BA && getTriple().isGPU() &&
548 !JobArgs.hasFlag(options::OPT_fgpu_sanitize,
549 options::OPT_fno_gpu_sanitize, true)) {
550 DiagnoseBoundArchErrors = false;
551 }
552
553 SanitizerArgs SanArgs(*this, JobArgs,
554 /*DiagnoseErrors=*/!SanitizerArgsChecked,
555 DiagnoseBoundArchErrors, BA, DeviceOffloadKind);
556
557 SanitizerArgsChecked = true;
558 return SanArgs;
559}
560
561const XRayArgs ToolChain::getXRayArgs(const llvm::opt::ArgList &JobArgs) const {
562 XRayArgs XRayArguments(*this, JobArgs);
563 return XRayArguments;
564}
565
566namespace {
567
568struct DriverSuffix {
569 const char *Suffix;
570 const char *ModeFlag;
571};
572
573} // namespace
574
575static const DriverSuffix *FindDriverSuffix(StringRef ProgName, size_t &Pos) {
576 // A list of known driver suffixes. Suffixes are compared against the
577 // program name in order. If there is a match, the frontend type is updated as
578 // necessary by applying the ModeFlag.
579 static const DriverSuffix DriverSuffixes[] = {
580 {"clang", nullptr},
581 {"clang++", "--driver-mode=g++"},
582 {"clang-c++", "--driver-mode=g++"},
583 {"clang-cc", nullptr},
584 {"clang-cpp", "--driver-mode=cpp"},
585 {"clang-g++", "--driver-mode=g++"},
586 {"clang-gcc", nullptr},
587 {"clang-cl", "--driver-mode=cl"},
588 {"cc", nullptr},
589 {"cpp", "--driver-mode=cpp"},
590 {"cl", "--driver-mode=cl"},
591 {"++", "--driver-mode=g++"},
592 {"flang", "--driver-mode=flang"},
593 // For backwards compatibility, we create a symlink for `flang` called
594 // `flang-new`. This will be removed in the future.
595 {"flang-new", "--driver-mode=flang"},
596 {"clang-dxc", "--driver-mode=dxc"},
597 };
598
599 for (const auto &DS : DriverSuffixes) {
600 StringRef Suffix(DS.Suffix);
601 if (ProgName.ends_with(Suffix)) {
602 Pos = ProgName.size() - Suffix.size();
603 return &DS;
604 }
605 }
606 return nullptr;
607}
608
609/// Normalize the program name from argv[0] by stripping the file extension if
610/// present and lower-casing the string on Windows.
611static std::string normalizeProgramName(llvm::StringRef Argv0) {
612 std::string ProgName = std::string(llvm::sys::path::filename(Argv0));
613 if (is_style_windows(llvm::sys::path::Style::native)) {
614 // Transform to lowercase for case insensitive file systems.
615 std::transform(ProgName.begin(), ProgName.end(), ProgName.begin(),
616 ::tolower);
617 }
618 return ProgName;
619}
620
621static const DriverSuffix *parseDriverSuffix(StringRef ProgName, size_t &Pos) {
622 // Try to infer frontend type and default target from the program name by
623 // comparing it against DriverSuffixes in order.
624
625 // If there is a match, the function tries to identify a target as prefix.
626 // E.g. "x86_64-linux-clang" as interpreted as suffix "clang" with target
627 // prefix "x86_64-linux". If such a target prefix is found, it may be
628 // added via -target as implicit first argument.
629 const DriverSuffix *DS = FindDriverSuffix(ProgName, Pos);
630
631 if (!DS && ProgName.ends_with(".exe")) {
632 // Try again after stripping the executable suffix:
633 // clang++.exe -> clang++
634 ProgName = ProgName.drop_back(StringRef(".exe").size());
635 DS = FindDriverSuffix(ProgName, Pos);
636 }
637
638 if (!DS) {
639 // Try again after stripping any trailing version number:
640 // clang++3.5 -> clang++
641 ProgName = ProgName.rtrim("0123456789.");
642 DS = FindDriverSuffix(ProgName, Pos);
643 }
644
645 if (!DS) {
646 // Try again after stripping trailing -component.
647 // clang++-tot -> clang++
648 ProgName = ProgName.slice(0, ProgName.rfind('-'));
649 DS = FindDriverSuffix(ProgName, Pos);
650 }
651 return DS;
652}
653
656 std::string ProgName = normalizeProgramName(PN);
657 size_t SuffixPos;
658 const DriverSuffix *DS = parseDriverSuffix(ProgName, SuffixPos);
659 if (!DS)
660 return {};
661 size_t SuffixEnd = SuffixPos + strlen(DS->Suffix);
662
663 size_t LastComponent = ProgName.rfind('-', SuffixPos);
664 if (LastComponent == std::string::npos)
665 return ParsedClangName(ProgName.substr(0, SuffixEnd), DS->ModeFlag);
666 std::string ModeSuffix = ProgName.substr(LastComponent + 1,
667 SuffixEnd - LastComponent - 1);
668
669 // Infer target from the prefix.
670 StringRef Prefix(ProgName);
671 Prefix = Prefix.slice(0, LastComponent);
672 std::string IgnoredError;
673
674 llvm::Triple Triple(Prefix);
675 bool IsRegistered = llvm::TargetRegistry::lookupTarget(Triple, IgnoredError);
676 return ParsedClangName{std::string(Prefix), ModeSuffix, DS->ModeFlag,
677 IsRegistered};
678}
679
681 // In universal driver terms, the arch name accepted by -arch isn't exactly
682 // the same as the ones that appear in the triple. Roughly speaking, this is
683 // an inverse of the darwin::getArchTypeForDarwinArchName() function.
684 switch (Triple.getArch()) {
685 case llvm::Triple::aarch64: {
686 if (getTriple().isArm64e())
687 return "arm64e";
688 return "arm64";
689 }
690 case llvm::Triple::aarch64_32:
691 return "arm64_32";
692 case llvm::Triple::ppc:
693 return "ppc";
694 case llvm::Triple::ppcle:
695 return "ppcle";
696 case llvm::Triple::ppc64:
697 return "ppc64";
698 case llvm::Triple::ppc64le:
699 return "ppc64le";
700 default:
701 return Triple.getArchName();
702 }
703}
704
705std::string ToolChain::getInputFilename(const InputInfo &Input) const {
706 return Input.getFilename();
707}
708
710ToolChain::getDefaultUnwindTableLevel(const ArgList &Args) const {
712}
713
714Tool *ToolChain::getClang() const {
715 if (!Clang)
716 Clang.reset(new tools::Clang(*this, useIntegratedBackend()));
717 return Clang.get();
718}
719
720Tool *ToolChain::getFlang() const {
721 if (!Flang)
722 Flang.reset(new tools::Flang(*this));
723 return Flang.get();
724}
725
727 return new tools::ClangAs(*this);
728}
729
731 llvm_unreachable("Linking is not supported by this toolchain");
732}
733
735 llvm_unreachable("Creating static lib is not supported by this toolchain");
736}
737
738Tool *ToolChain::getAssemble() const {
739 if (!Assemble)
740 Assemble.reset(buildAssembler());
741 return Assemble.get();
742}
743
744Tool *ToolChain::getClangAs() const {
745 if (!Assemble)
746 Assemble.reset(new tools::ClangAs(*this));
747 return Assemble.get();
748}
749
750Tool *ToolChain::getLink() const {
751 if (!Link)
752 Link.reset(buildLinker());
753 return Link.get();
754}
755
756Tool *ToolChain::getStaticLibTool() const {
757 if (!StaticLibTool)
758 StaticLibTool.reset(buildStaticLibTool());
759 return StaticLibTool.get();
760}
761
762Tool *ToolChain::getIfsMerge() const {
763 if (!IfsMerge)
764 IfsMerge.reset(new tools::ifstool::Merger(*this));
765 return IfsMerge.get();
766}
767
768Tool *ToolChain::getOffloadBundler() const {
769 if (!OffloadBundler)
770 OffloadBundler.reset(new tools::OffloadBundler(*this));
771 return OffloadBundler.get();
772}
773
774Tool *ToolChain::getOffloadPackager() const {
775 if (!OffloadPackager)
776 OffloadPackager.reset(new tools::OffloadPackager(*this));
777 return OffloadPackager.get();
778}
779
780Tool *ToolChain::getLinkerWrapper() const {
781 if (!LinkerWrapper)
782 LinkerWrapper.reset(new tools::LinkerWrapper(*this, getLink()));
783 return LinkerWrapper.get();
784}
785
787 switch (AC) {
789 return getAssemble();
790
792 return getIfsMerge();
793
795 return getLink();
796
798 return getStaticLibTool();
799
809 llvm_unreachable("Invalid tool kind.");
810
818 return getClang();
819
821 return getOffloadBundler();
822
824 return getOffloadPackager();
826 return getLinkerWrapper();
827 }
828
829 llvm_unreachable("Invalid tool kind.");
830}
831
832static StringRef getArchNameForCompilerRTLib(const ToolChain &TC,
833 const ArgList &Args) {
834 const llvm::Triple &Triple = TC.getTriple();
835 bool IsWindows = Triple.isOSWindows();
836
837 if (TC.isBareMetal())
838 return Triple.getArchName();
839
840 if (TC.getArch() == llvm::Triple::arm || TC.getArch() == llvm::Triple::armeb)
841 return (arm::getARMFloatABI(TC, Args) == arm::FloatABI::Hard && !IsWindows)
842 ? "armhf"
843 : "arm";
844
845 // For historic reasons, Android library is using i686 instead of i386.
846 if (TC.getArch() == llvm::Triple::x86 && Triple.isAndroid())
847 return "i686";
848
849 if (TC.getArch() == llvm::Triple::x86_64 && Triple.isX32())
850 return "x32";
851
852 return llvm::Triple::getArchTypeName(TC.getArch());
853}
854
855StringRef ToolChain::getOSLibName() const {
856 if (Triple.isOSDarwin())
857 return "darwin";
858 if (Triple.isWindowsCygwinEnvironment())
859 return "cygwin";
860
861 switch (Triple.getOS()) {
862 case llvm::Triple::FreeBSD:
863 return "freebsd";
864 case llvm::Triple::NetBSD:
865 return "netbsd";
866 case llvm::Triple::OpenBSD:
867 return "openbsd";
868 case llvm::Triple::Solaris:
869 return "sunos";
870 case llvm::Triple::AIX:
871 return "aix";
872 case llvm::Triple::Serenity:
873 return "serenity";
874 default:
875 return getOS();
876 }
877}
878
879std::string ToolChain::getCompilerRTPath() const {
880 SmallString<128> Path(getDriver().ResourceDir);
881 if (isBareMetal()) {
882 // The builtin compiler-rt directories include the multilib path, as the
883 // compiler-rt library files come from a runtimes build.
884 llvm::sys::path::append(Path, "lib", getOSLibName());
885 if (!SelectedMultilibs.empty()) {
886 Path += SelectedMultilibs.back().gccSuffix();
887 }
888 } else if (Triple.isOSUnknown()) {
889 llvm::sys::path::append(Path, "lib");
890 } else {
891 llvm::sys::path::append(Path, "lib", getOSLibName());
892 }
893 return std::string(Path);
894}
895
896std::string ToolChain::getCompilerRTBasename(const ArgList &Args,
897 StringRef Component,
898 FileType Type) const {
899 std::string CRTAbsolutePath = getCompilerRT(Args, Component, Type);
900 return llvm::sys::path::filename(CRTAbsolutePath).str();
901}
902
903std::string ToolChain::buildCompilerRTBasename(const llvm::opt::ArgList &Args,
904 StringRef Component,
905 FileType Type, bool AddArch,
906 bool IsFortran) const {
907 const llvm::Triple &TT = getTriple();
908 bool IsITANMSVCWindows =
909 TT.isWindowsMSVCEnvironment() || TT.isWindowsItaniumEnvironment();
910
911 const char *Prefix =
912 IsITANMSVCWindows || Type == ToolChain::FT_Object ? "" : "lib";
913 const char *Suffix;
914 switch (Type) {
916 Suffix = IsITANMSVCWindows ? ".obj" : ".o";
917 break;
919 Suffix = IsITANMSVCWindows ? ".lib" : ".a";
920 break;
922 if (TT.isOSWindows())
923 Suffix = TT.isOSCygMing() ? ".dll.a" : ".lib";
924 else if (TT.isOSAIX())
925 Suffix = ".a";
926 else
927 Suffix = ".so";
928 break;
929 }
930
931 std::string ArchAndEnv;
932 if (AddArch) {
933 StringRef Arch = getArchNameForCompilerRTLib(*this, Args);
934 const char *Env = TT.isAndroid() ? "-android" : "";
935 ArchAndEnv = ("-" + Arch + Env).str();
936 }
937
938 std::string LibName = IsFortran ? "flang_rt." : "clang_rt.";
939 return (Prefix + Twine(LibName) + Component + ArchAndEnv + Suffix).str();
940}
941
942std::string ToolChain::getCompilerRT(const ArgList &Args, StringRef Component,
943 FileType Type, bool IsFortran) const {
944 // Check for runtime files in the new layout without the architecture first.
945 std::string CRTBasename = buildCompilerRTBasename(
946 Args, Component, Type, /*AddArch=*/false, IsFortran);
947 SmallString<128> Path;
948 for (const auto &LibPath : getLibraryPaths()) {
949 SmallString<128> P(LibPath);
950 llvm::sys::path::append(P, CRTBasename);
951 if (getVFS().exists(P))
952 return std::string(P);
953 if (Path.empty())
954 Path = P;
955 }
956
957 // Check the filename for the old layout if the new one does not exist.
958 CRTBasename = buildCompilerRTBasename(Args, Component, Type,
959 /*AddArch=*/!IsFortran, IsFortran);
961 llvm::sys::path::append(OldPath, CRTBasename);
962 if (Path.empty() || getVFS().exists(OldPath))
963 return std::string(OldPath);
964
965 // If none is found, use a file name from the new layout, which may get
966 // printed in an error message, aiding users in knowing what Clang is
967 // looking for.
968 return std::string(Path);
969}
970
971const char *ToolChain::getCompilerRTArgString(const llvm::opt::ArgList &Args,
972 StringRef Component,
974 bool isFortran) const {
975 return Args.MakeArgString(getCompilerRT(Args, Component, Type, isFortran));
976}
977
978/// Add Fortran runtime libs
979void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
980 llvm::opt::ArgStringList &CmdArgs) const {
981 // Link flang_rt.runtime
982 // These are handled earlier on Windows by telling the frontend driver to
983 // add the correct libraries to link against as dependents in the object
984 // file.
985 if (!getTriple().isKnownWindowsMSVCEnvironment()) {
986 StringRef F128LibName = getDriver().getFlangF128MathLibrary();
987 F128LibName.consume_front_insensitive("lib");
988 if (!F128LibName.empty()) {
989 bool AsNeeded = !getTriple().isOSAIX();
990 CmdArgs.push_back("-lflang_rt.quadmath");
991 if (AsNeeded)
992 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/true);
993 CmdArgs.push_back(Args.MakeArgString("-l" + F128LibName));
994 if (AsNeeded)
995 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/false);
996 }
997 addFlangRTLibPath(Args, CmdArgs);
998
999 // needs libexecinfo for backtrace functions
1000 if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() ||
1001 getTriple().isOSOpenBSD() || getTriple().isOSDragonFly())
1002 CmdArgs.push_back("-lexecinfo");
1003 }
1004
1005 // libomp needs libatomic for atomic operations if using libgcc
1006 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1007 options::OPT_fno_openmp, false)) {
1010 if ((OMPRuntime == Driver::OMPRT_OMP &&
1011 RuntimeLib == ToolChain::RLT_Libgcc) &&
1012 !getTriple().isKnownWindowsMSVCEnvironment()) {
1013 if (getTriple().isOSAIX())
1014 CmdArgs.push_back("-lcompiler_rt");
1015 else
1016 CmdArgs.push_back("-latomic");
1017 }
1018 }
1019}
1020
1021void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
1022 ArgStringList &CmdArgs) const {
1023 auto AddLibSearchPathIfExists = [&](const Twine &Path) {
1024 // Linker may emit warnings about non-existing directories
1025 if (!llvm::sys::fs::is_directory(Path))
1026 return;
1027
1028 if (getTriple().isKnownWindowsMSVCEnvironment())
1029 CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
1030 else
1031 CmdArgs.push_back(Args.MakeArgString("-L" + Path));
1032 };
1033
1034 // Search for flang_rt.* at the same location as clang_rt.* with
1035 // LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
1036 // located at the path returned by getRuntimePath() which is already added to
1037 // the library search path. This exception is for Apple-Darwin.
1038 AddLibSearchPathIfExists(getCompilerRTPath());
1039
1040 // Fall back to the non-resource directory <driver-path>/../lib. We will
1041 // probably have to refine this in the future. In particular, on some
1042 // platforms, we may need to use lib64 instead of lib.
1043 SmallString<256> DefaultLibPath =
1044 llvm::sys::path::parent_path(getDriver().Dir);
1045 llvm::sys::path::append(DefaultLibPath, "lib");
1046 AddLibSearchPathIfExists(DefaultLibPath);
1047}
1048
1049void ToolChain::addFlangRTLibPath(const ArgList &Args,
1050 llvm::opt::ArgStringList &CmdArgs) const {
1051 // Link static flang_rt.runtime.a or shared flang_rt.runtime.so.
1052 // On AIX, default to static flang-rt.
1053 if (Args.hasFlag(options::OPT_static_libflangrt,
1054 options::OPT_shared_libflangrt, getTriple().isOSAIX()))
1055 CmdArgs.push_back(
1056 getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
1057 else
1058 CmdArgs.push_back("-lflang_rt.runtime");
1059}
1060
1061// Android target triples contain a target version. If we don't have libraries
1062// for the exact target version, we should fall back to the next newest version
1063// or a versionless path, if any.
1064std::optional<std::string>
1065ToolChain::getFallbackAndroidTargetPath(StringRef BaseDir) const {
1066 llvm::Triple TripleWithoutLevel(getTriple());
1067 TripleWithoutLevel.setEnvironmentName("android"); // remove any version number
1068 const std::string &TripleWithoutLevelStr = TripleWithoutLevel.str();
1069 unsigned TripleVersion = getTriple().getEnvironmentVersion().getMajor();
1070 unsigned BestVersion = 0;
1071
1072 SmallString<32> TripleDir;
1073 bool UsingUnversionedDir = false;
1074 std::error_code EC;
1075 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(BaseDir, EC), LE;
1076 !EC && LI != LE; LI = LI.increment(EC)) {
1077 StringRef DirName = llvm::sys::path::filename(LI->path());
1078 StringRef DirNameSuffix = DirName;
1079 if (DirNameSuffix.consume_front(TripleWithoutLevelStr)) {
1080 if (DirNameSuffix.empty() && TripleDir.empty()) {
1081 TripleDir = DirName;
1082 UsingUnversionedDir = true;
1083 } else {
1084 unsigned Version;
1085 if (!DirNameSuffix.getAsInteger(10, Version) && Version > BestVersion &&
1086 Version < TripleVersion) {
1087 BestVersion = Version;
1088 TripleDir = DirName;
1089 UsingUnversionedDir = false;
1090 }
1091 }
1092 }
1093 }
1094
1095 if (TripleDir.empty())
1096 return {};
1097
1098 SmallString<128> P(BaseDir);
1099 llvm::sys::path::append(P, TripleDir);
1100 if (UsingUnversionedDir)
1101 D.Diag(diag::warn_android_unversioned_fallback) << P << getTripleString();
1102 return std::string(P);
1103}
1104
1106 return (Triple.hasEnvironment()
1107 ? llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1108 llvm::Triple::getOSTypeName(Triple.getOS()),
1109 llvm::Triple::getEnvironmentTypeName(
1110 Triple.getEnvironment()))
1111 : llvm::Triple(Triple.getArchName(), Triple.getVendorName(),
1112 llvm::Triple::getOSTypeName(Triple.getOS())));
1113}
1114
1115std::optional<std::string>
1116ToolChain::getTargetSubDirPath(StringRef BaseDir) const {
1117 auto getPathForTriple =
1118 [&](const llvm::Triple &Triple) -> std::optional<std::string> {
1119 SmallString<128> P(BaseDir);
1120 llvm::sys::path::append(P, Triple.str());
1121 if (getVFS().exists(P))
1122 return std::string(P);
1123 return {};
1124 };
1125
1126 const llvm::Triple &T = getTriple();
1127 if (auto Path = getPathForTriple(T))
1128 return *Path;
1129
1130 if (T.isAMDGCN()) {
1131 // Clear the subarch as a fallback.
1132 // TODO: Remove this when libc and compiler-rt builds are migrated.
1133 llvm::Triple AMDGPUTriple = T;
1134 AMDGPUTriple.setArch(Triple::amdgpu);
1135 if (auto Path = getPathForTriple(AMDGPUTriple))
1136 return *Path;
1137
1138 // Try legacy architecture name.
1139 AMDGPUTriple.setArchName("amdgcn");
1140 if (auto Path = getPathForTriple(AMDGPUTriple))
1141 return *Path;
1142 }
1143
1144 // Short SPIR-V spellings like "spirv64" are installed under the three-part
1145 // name, "spirv64-unknown-unknown".
1146 if (T.isSPIRV()) {
1147 llvm::Triple SPIRVTriple(
1148 T.normalize(llvm::Triple::CanonicalForm::THREE_IDENT));
1149 if (auto Path = getPathForTriple(SPIRVTriple))
1150 return *Path;
1151 }
1152
1153 if (T.isOSAIX()) {
1154 llvm::Triple AIXTriple;
1155 if (T.getEnvironment() == Triple::UnknownEnvironment) {
1156 // Strip unknown environment and the OS version from the triple.
1157 AIXTriple = llvm::Triple(T.getArchName(), T.getVendorName(),
1158 llvm::Triple::getOSTypeName(T.getOS()));
1159 } else {
1160 // Strip the OS version from the triple.
1161 AIXTriple = getTripleWithoutOSVersion();
1162 }
1163 if (auto Path = getPathForTriple(AIXTriple))
1164 return *Path;
1165 }
1166
1167 if (T.isOSzOS() &&
1168 (!T.getOSVersion().empty() || !T.getEnvironmentVersion().empty())) {
1169 // Build the triple without version information
1170 const llvm::Triple &TripleWithoutVersion = getTripleWithoutOSVersion();
1171 if (auto Path = getPathForTriple(TripleWithoutVersion))
1172 return *Path;
1173 }
1174
1175 // When building with per target runtime directories, various ways of naming
1176 // the Arm architecture may have been normalised to simply "arm".
1177 // For example "armv8l" (Armv8 AArch32 little endian) is replaced with "arm".
1178 // Since an armv8l system can use libraries built for earlier architecture
1179 // versions assuming endian and float ABI match.
1180 //
1181 // Original triple: armv8l-unknown-linux-gnueabihf
1182 // Runtime triple: arm-unknown-linux-gnueabihf
1183 //
1184 // We do not do this for armeb (big endian) because doing so could make us
1185 // select little endian libraries. In addition, all known armeb triples only
1186 // use the "armeb" architecture name.
1187 //
1188 // M profile Arm is bare metal and we know they will not be using the per
1189 // target runtime directory layout.
1190 if (T.getArch() == Triple::arm && !T.isArmMClass()) {
1191 llvm::Triple ArmTriple = T;
1192 ArmTriple.setArch(Triple::arm);
1193 if (auto Path = getPathForTriple(ArmTriple))
1194 return *Path;
1195 }
1196
1197 if (T.isAndroid())
1198 return getFallbackAndroidTargetPath(BaseDir);
1199
1200 return {};
1201}
1202
1203std::optional<std::string> ToolChain::getDefaultIntrinsicModuleDir() const {
1204 SmallString<128> P(D.ResourceDir);
1205 llvm::sys::path::append(P, "finclude", "flang");
1206 return getTargetSubDirPath(P);
1207}
1208
1209std::optional<std::string> ToolChain::getRuntimePath() const {
1210 SmallString<128> P(D.ResourceDir);
1211 llvm::sys::path::append(P, "lib");
1212 if (auto Ret = getTargetSubDirPath(P))
1213 return Ret;
1214 // Darwin does not use per-target runtime directory.
1215 if (Triple.isOSDarwin())
1216 return {};
1217
1218 llvm::sys::path::append(P, Triple.str());
1219 return std::string(P);
1220}
1221
1222std::optional<std::string> ToolChain::getStdlibPath() const {
1223 SmallString<128> P(D.Dir);
1224 llvm::sys::path::append(P, "..", "lib");
1225 return getTargetSubDirPath(P);
1226}
1227
1228std::optional<std::string> ToolChain::getStdlibIncludePath() const {
1229 SmallString<128> P(D.Dir);
1230 llvm::sys::path::append(P, "..", "include");
1231 return getTargetSubDirPath(P);
1232}
1233
1235 path_list Paths;
1236
1237 auto AddPath = [&](const ArrayRef<StringRef> &SS) {
1238 SmallString<128> Path(getDriver().ResourceDir);
1239 llvm::sys::path::append(Path, "lib");
1240 for (auto &S : SS)
1241 llvm::sys::path::append(Path, S);
1242 Paths.push_back(std::string(Path));
1243 };
1244
1245 AddPath({getTriple().str()});
1246
1247 // For AMDGPU, fall back to the subarch-stripped triple path, trying both the
1248 // canonical "amdgpu" name and the legacy "amdgcn" name.
1249 //
1250 // TODO: Also try major subarch?
1251 // TODO: Remove this when libc and compiler-rt builds are migrated.
1252 if (getTriple().isAMDGCN()) {
1253 llvm::Triple Canon(getTriple());
1254 for (StringRef ArchName : {"amdgpu", "amdgcn"}) {
1255 if (ArchName == getTriple().getArchName())
1256 continue;
1257 Canon.setArchName(ArchName);
1258 AddPath({Canon.str()});
1259 }
1260 }
1261
1262 AddPath({getOSLibName(), llvm::Triple::getArchTypeName(getArch())});
1263 return Paths;
1264}
1265
1266bool ToolChain::needsProfileRT(const ArgList &Args) {
1267 if (Args.hasArg(options::OPT_noprofilelib))
1268 return false;
1269
1270 return Args.hasArg(options::OPT_fprofile_generate) ||
1271 Args.hasArg(options::OPT_fprofile_generate_EQ) ||
1272 Args.hasArg(options::OPT_fcs_profile_generate) ||
1273 Args.hasArg(options::OPT_fcs_profile_generate_EQ) ||
1274 Args.hasArg(options::OPT_fprofile_instr_generate) ||
1275 Args.hasArg(options::OPT_fprofile_instr_generate_EQ) ||
1276 Args.hasArg(options::OPT_fcreate_profile) ||
1277 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage) ||
1278 Args.hasArg(options::OPT_fprofile_generate_cold_function_coverage_EQ);
1279}
1280
1281bool ToolChain::needsGCovInstrumentation(const llvm::opt::ArgList &Args) {
1282 return Args.hasArg(options::OPT_coverage) ||
1283 Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
1284 false);
1285}
1286
1288 if (D.IsFlangMode() && getDriver().ShouldUseFlangCompiler(JA)) return getFlang();
1289 if (getDriver().ShouldUseClangCompiler(JA)) return getClang();
1290 Action::ActionClass AC = JA.getKind();
1292 !getTriple().isOSAIX())
1293 return getClangAs();
1294 return getTool(AC);
1295}
1296
1297std::string ToolChain::GetFilePath(const char *Name) const {
1298 return D.GetFilePath(Name, *this);
1299}
1300
1301std::optional<std::string>
1302ToolChain::GetFilePathIfExists(const char *Name) const {
1303 std::string Path = D.GetFilePath(Name, *this);
1304 if (Path == Name)
1305 return std::nullopt;
1306 return Path;
1307}
1308
1309std::string ToolChain::GetProgramPath(const char *Name) const {
1310 return D.GetProgramPath(Name, *this);
1311}
1312
1313std::string ToolChain::GetLinkerPath(bool *LinkerIsLLD) const {
1314 if (LinkerIsLLD)
1315 *LinkerIsLLD = false;
1316
1317 // Get -fuse-ld= first to prevent -Wunused-command-line-argument. -fuse-ld= is
1318 // considered as the linker flavor, e.g. "bfd", "gold", or "lld".
1319 const Arg* A = Args.getLastArg(options::OPT_fuse_ld_EQ);
1320 StringRef UseLinker = A ? A->getValue() : getDriver().getPreferredLinker();
1321
1322 // --ld-path= takes precedence over -fuse-ld= and specifies the executable
1323 // name. -B, COMPILER_PATH and PATH and consulted if the value does not
1324 // contain a path component separator.
1325 // -fuse-ld=lld can be used with --ld-path= to inform clang that the binary
1326 // that --ld-path= points to is lld.
1327 if (const Arg *A = Args.getLastArg(options::OPT_ld_path_EQ)) {
1328 std::string Path(A->getValue());
1329 if (!Path.empty()) {
1330 if (llvm::sys::path::parent_path(Path).empty())
1331 Path = GetProgramPath(A->getValue());
1332 if (llvm::sys::fs::can_execute(Path)) {
1333 if (LinkerIsLLD)
1334 *LinkerIsLLD = UseLinker == "lld";
1335 return std::string(Path);
1336 }
1337 }
1338 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1340 }
1341 // If we're passed -fuse-ld= with no argument, or with the argument ld,
1342 // then use whatever the default system linker is.
1343 if (UseLinker.empty() || UseLinker == "ld") {
1344 const char *DefaultLinker = getDefaultLinker();
1345 if (llvm::sys::path::is_absolute(DefaultLinker))
1346 return std::string(DefaultLinker);
1347 else
1348 return GetProgramPath(DefaultLinker);
1349 }
1350
1351 // Extending -fuse-ld= to an absolute or relative path is unexpected. Checking
1352 // for the linker flavor is brittle. In addition, prepending "ld." or "ld64."
1353 // to a relative path is surprising. This is more complex due to priorities
1354 // among -B, COMPILER_PATH and PATH. --ld-path= should be used instead.
1355 if (UseLinker.contains('/'))
1356 getDriver().Diag(diag::warn_drv_fuse_ld_path);
1357
1358 if (llvm::sys::path::is_absolute(UseLinker)) {
1359 // If we're passed what looks like an absolute path, don't attempt to
1360 // second-guess that.
1361 if (llvm::sys::fs::can_execute(UseLinker))
1362 return std::string(UseLinker);
1363 } else {
1364 llvm::SmallString<8> LinkerName;
1365 if (Triple.isOSDarwin())
1366 LinkerName.append("ld64.");
1367 else
1368 LinkerName.append("ld.");
1369 LinkerName.append(UseLinker);
1370
1371 std::string LinkerPath(GetProgramPath(LinkerName.c_str()));
1372 if (llvm::sys::fs::can_execute(LinkerPath)) {
1373 if (LinkerIsLLD)
1374 *LinkerIsLLD = UseLinker == "lld";
1375 return LinkerPath;
1376 }
1377 }
1378
1379 if (A)
1380 getDriver().Diag(diag::err_drv_invalid_linker_name) << A->getAsString(Args);
1381
1383}
1384
1386 // TODO: Add support for static lib archiving on Windows
1387 if (Triple.isOSDarwin())
1388 return GetProgramPath("libtool");
1389 return GetProgramPath("llvm-ar");
1390}
1391
1394
1395 // Flang always runs the preprocessor and has no notion of "preprocessed
1396 // fortran". Here, TY_PP_Fortran is coerced to TY_Fortran to avoid treating
1397 // them differently.
1398 if (D.IsFlangMode() && id == types::TY_PP_Fortran)
1399 id = types::TY_Fortran;
1400
1401 return id;
1402}
1403
1405 return false;
1406}
1407
1409
1410bool ToolChain::isUsingLTO(const llvm::opt::ArgList &Args,
1411 Action::OffloadKind Kind) const {
1412 return getLTOMode(Args, Kind) != LTOK_None;
1413}
1414
1415static LTOKind parseLTOMode(const llvm::opt::ArgList &Args,
1416 llvm::opt::OptSpecifier OptEq,
1417 llvm::opt::OptSpecifier OptNeg) {
1418 if (!Args.hasFlag(OptEq, OptNeg, false))
1419 return LTOK_None;
1420
1421 const Arg *A = Args.getLastArg(OptEq);
1422 StringRef LTOName = A->getValue();
1423
1424 return llvm::StringSwitch<LTOKind>(LTOName)
1425 .Case("full", LTOK_Full)
1426 .Case("thin", LTOK_Thin)
1427 .Case("none", LTOK_None)
1428 .Default(LTOK_Unknown);
1429}
1430
1431LTOKind ToolChain::getLTOMode(const llvm::opt::ArgList &Args,
1432 Action::OffloadKind Kind) const {
1433 bool IsOffload = Kind != Action::OFK_None;
1434 auto OptEq = IsOffload ? options::OPT_foffload_lto_EQ : options::OPT_flto_EQ;
1435 auto OptNeg = IsOffload ? options::OPT_fno_offload_lto : options::OPT_fno_lto;
1436
1437 // -fopenmp-target-jit implies -foffload-lto=full for device compilations,
1438 // overriding any explicit -fno-offload-lto.
1439 if (IsOffload && Args.hasFlag(options::OPT_fopenmp_target_jit,
1440 options::OPT_fno_openmp_target_jit, false)) {
1441 if (Arg *A = Args.getLastArg(OptEq, OptNeg))
1442 if (parseLTOMode(Args, OptEq, OptNeg) != LTOK_Full)
1443 getDriver().Diag(diag::err_drv_incompatible_options)
1444 << A->getSpelling() << "-fopenmp-target-jit";
1445 return LTOK_Full;
1446 }
1447
1448 if (!Args.hasArg(OptEq, OptNeg))
1449 return getDefaultLTOMode();
1450
1451 LTOKind Mode = parseLTOMode(Args, OptEq, OptNeg);
1452
1453 if (Mode == LTOK_Unknown) {
1454 const Arg *A = Args.getLastArg(OptEq);
1455 getDriver().Diag(diag::err_drv_unsupported_option_argument)
1456 << A->getSpelling() << A->getValue();
1457 return LTOK_None;
1458 }
1459 return Mode;
1460}
1461
1463 llvm::Triple HostTriple(LLVM_HOST_TRIPLE);
1464 switch (HostTriple.getArch()) {
1465 // The A32/T32/T16 instruction sets are not separate architectures in this
1466 // context.
1467 case llvm::Triple::arm:
1468 case llvm::Triple::armeb:
1469 case llvm::Triple::thumb:
1470 case llvm::Triple::thumbeb:
1471 return getArch() != llvm::Triple::arm && getArch() != llvm::Triple::thumb &&
1472 getArch() != llvm::Triple::armeb && getArch() != llvm::Triple::thumbeb;
1473 default:
1474 return HostTriple.getArch() != getArch();
1475 }
1476}
1477
1479 return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
1480 VersionTuple());
1481}
1482
1483llvm::ExceptionHandling
1484ToolChain::GetExceptionModel(const llvm::opt::ArgList &Args) const {
1485 return llvm::ExceptionHandling::Default;
1486}
1487
1488bool ToolChain::isThreadModelSupported(const StringRef Model) const {
1489 if (Model == "single") {
1490 // FIXME: 'single' is only supported on ARM and WebAssembly so far.
1491 return Triple.getArch() == llvm::Triple::arm ||
1492 Triple.getArch() == llvm::Triple::armeb ||
1493 Triple.getArch() == llvm::Triple::thumb ||
1494 Triple.getArch() == llvm::Triple::thumbeb || Triple.isWasm();
1495 } else if (Model == "posix")
1496 return true;
1497
1498 return false;
1499}
1500
1501std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, BoundArch BA,
1502 types::ID InputType) const {
1503 switch (getTriple().getArch()) {
1504 default:
1505 return getTripleString().str();
1506
1507 case llvm::Triple::x86_64: {
1508 llvm::Triple Triple = getTriple();
1509 if (!Triple.isOSBinFormatMachO())
1510 return getTripleString().str();
1511
1512 if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
1513 // x86_64h goes in the triple. Other -march options just use the
1514 // vanilla triple we already have.
1515 StringRef MArch = A->getValue();
1516 if (MArch == "x86_64h")
1517 Triple.setArchName(MArch);
1518 }
1519 return Triple.getTriple();
1520 }
1521 case llvm::Triple::aarch64: {
1522 llvm::Triple Triple = getTriple();
1523 if (!Triple.isOSBinFormatMachO())
1524 return Triple.getTriple();
1525
1526 if (Triple.isArm64e())
1527 return Triple.getTriple();
1528
1529 // FIXME: older versions of ld64 expect the "arm64" component in the actual
1530 // triple string and query it to determine whether an LTO file can be
1531 // handled. Remove this when we don't care any more.
1532 Triple.setArchName("arm64");
1533 return Triple.getTriple();
1534 }
1535 case llvm::Triple::aarch64_32:
1536 return getTripleString().str();
1537 case llvm::Triple::amdgpu: {
1538 llvm::Triple Triple = getTriple();
1539 tools::AMDGPU::setArchNameInTriple(getDriver(), Args, BA, InputType,
1540 Triple);
1541 return Triple.getTriple();
1542 }
1543 case llvm::Triple::arm:
1544 case llvm::Triple::armeb:
1545 case llvm::Triple::thumb:
1546 case llvm::Triple::thumbeb: {
1547 llvm::Triple Triple = getTriple();
1548 tools::arm::setArchNameInTriple(getDriver(), Args, InputType, Triple);
1550 tools::arm::setEABIInTriple(getDriver(), Args, Triple);
1551 return Triple.getTriple();
1552 }
1553 }
1554}
1555
1556std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
1557 BoundArch BA,
1558 types::ID InputType) const {
1559 return ComputeLLVMTriple(Args, BA, InputType);
1560}
1561
1562std::string ToolChain::computeSysRoot() const {
1563 return D.SysRoot;
1564}
1565
1566void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
1567 ArgStringList &CC1Args) const {
1568 // Each toolchain should provide the appropriate include flags.
1569}
1570
1572 const ArgList &DriverArgs, ArgStringList &CC1Args, BoundArch BA,
1573 Action::OffloadKind DeviceOffloadKind) const {}
1574
1576 ArgStringList &CC1ASArgs) const {}
1577
1578void ToolChain::addClangWarningOptions(ArgStringList &CC1Args) const {}
1579
1580void ToolChain::addProfileRTLibs(const llvm::opt::ArgList &Args,
1581 llvm::opt::ArgStringList &CmdArgs) const {
1582 if (!needsProfileRT(Args) && !needsGCovInstrumentation(Args))
1583 return;
1584
1585 CmdArgs.push_back(getCompilerRTArgString(Args, "profile"));
1586}
1587
1589 const ArgList &Args) const {
1590 if (runtimeLibType)
1591 return *runtimeLibType;
1592
1593 const Arg* A = Args.getLastArg(options::OPT_rtlib_EQ);
1594 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_RTLIB;
1595
1596 // Only use "platform" in tests to override CLANG_DEFAULT_RTLIB!
1597 if (LibName == "compiler-rt")
1598 runtimeLibType = ToolChain::RLT_CompilerRT;
1599 else if (LibName == "libgcc")
1600 runtimeLibType = ToolChain::RLT_Libgcc;
1601 else if (LibName == "platform")
1602 runtimeLibType = GetDefaultRuntimeLibType();
1603 else {
1604 if (A)
1605 getDriver().Diag(diag::err_drv_invalid_rtlib_name)
1606 << A->getAsString(Args);
1607
1608 runtimeLibType = GetDefaultRuntimeLibType();
1609 }
1610
1611 return *runtimeLibType;
1612}
1613
1615 const ArgList &Args) const {
1616 if (unwindLibType)
1617 return *unwindLibType;
1618
1619 const Arg *A = Args.getLastArg(options::OPT_unwindlib_EQ);
1620 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_UNWINDLIB;
1621
1622 if (LibName == "none")
1623 unwindLibType = ToolChain::UNW_None;
1624 else if (LibName == "platform" || LibName == "") {
1626 if (RtLibType == ToolChain::RLT_CompilerRT) {
1627 if (getTriple().isAndroid() || getTriple().isOSAIX() ||
1628 getTriple().isOSSerenity())
1629 unwindLibType = ToolChain::UNW_CompilerRT;
1630 else
1631 unwindLibType = ToolChain::UNW_None;
1632 } else if (RtLibType == ToolChain::RLT_Libgcc)
1633 unwindLibType = ToolChain::UNW_Libgcc;
1634 } else if (LibName == "libunwind") {
1635 if (GetRuntimeLibType(Args) == RLT_Libgcc)
1636 getDriver().Diag(diag::err_drv_incompatible_unwindlib);
1637 unwindLibType = ToolChain::UNW_CompilerRT;
1638 } else if (LibName == "libgcc")
1639 unwindLibType = ToolChain::UNW_Libgcc;
1640 else {
1641 if (A)
1642 getDriver().Diag(diag::err_drv_invalid_unwindlib_name)
1643 << A->getAsString(Args);
1644
1645 unwindLibType = GetDefaultUnwindLibType();
1646 }
1647
1648 return *unwindLibType;
1649}
1650
1652 if (cxxStdlibType)
1653 return *cxxStdlibType;
1654
1655 const Arg *A = Args.getLastArg(options::OPT_stdlib_EQ);
1656 StringRef LibName = A ? A->getValue() : CLANG_DEFAULT_CXX_STDLIB;
1657
1658 // Only use "platform" in tests to override CLANG_DEFAULT_CXX_STDLIB!
1659 if (LibName == "libc++")
1660 cxxStdlibType = ToolChain::CST_Libcxx;
1661 else if (LibName == "libstdc++")
1662 cxxStdlibType = ToolChain::CST_Libstdcxx;
1663 else if (LibName == "platform")
1664 cxxStdlibType = GetDefaultCXXStdlibType();
1665 else {
1666 if (A)
1667 getDriver().Diag(diag::err_drv_invalid_stdlib_name)
1668 << A->getAsString(Args);
1669
1670 cxxStdlibType = GetDefaultCXXStdlibType();
1671 }
1672
1673 return *cxxStdlibType;
1674}
1675
1676StringRef ToolChain::GetCXXStdlibName(const ArgList &Args) const {
1677 switch (GetCXXStdlibType(Args)) {
1679 return "libc++";
1681 return "libstdc++";
1682 }
1683 llvm_unreachable("unknown C++ standard library type");
1684}
1685
1687 if (cStdlibType)
1688 return *cStdlibType;
1689
1690 const Arg *A = Args.getLastArg(options::OPT_cstdlib_EQ);
1691 StringRef LibName = A ? A->getValue() : "system";
1692
1693 if (LibName == "newlib")
1694 cStdlibType = ToolChain::CST_Newlib;
1695 else if (LibName == "picolibc")
1696 cStdlibType = ToolChain::CST_Picolibc;
1697 else if (LibName == "llvm-libc")
1698 cStdlibType = ToolChain::CST_LLVMLibC;
1699 else if (LibName == "system")
1700 cStdlibType = ToolChain::CST_System;
1701 else {
1702 if (A)
1703 getDriver().Diag(diag::err_drv_invalid_cstdlib_name)
1704 << A->getAsString(Args);
1705 cStdlibType = ToolChain::CST_System;
1706 }
1707
1708 return *cStdlibType;
1709}
1710
1711/// Utility function to add a system framework directory to CC1 arguments.
1712void ToolChain::addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs,
1713 llvm::opt::ArgStringList &CC1Args,
1714 const Twine &Path) {
1715 CC1Args.push_back("-internal-iframework");
1716 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1717}
1718
1719/// Utility function to add a system include directory with extern "C"
1720/// semantics to CC1 arguments.
1721///
1722/// Note that this should be used rarely, and only for directories that
1723/// historically and for legacy reasons are treated as having implicit extern
1724/// "C" semantics. These semantics are *ignored* by and large today, but its
1725/// important to preserve the preprocessor changes resulting from the
1726/// classification.
1727void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
1728 ArgStringList &CC1Args,
1729 const Twine &Path) {
1730 CC1Args.push_back("-internal-externc-isystem");
1731 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1732}
1733
1734void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
1735 ArgStringList &CC1Args,
1736 const Twine &Path) {
1737 if (llvm::sys::fs::exists(Path))
1738 addExternCSystemInclude(DriverArgs, CC1Args, Path);
1739}
1740
1741/// Utility function to add a system include directory to CC1 arguments.
1742/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
1743 ArgStringList &CC1Args,
1744 const Twine &Path) {
1745 CC1Args.push_back("-internal-isystem");
1746 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1747}
1748
1749/// Utility function to add a list of system framework directories to CC1.
1750void ToolChain::addSystemFrameworkIncludes(const ArgList &DriverArgs,
1751 ArgStringList &CC1Args,
1752 ArrayRef<StringRef> Paths) {
1753 for (const auto &Path : Paths) {
1754 CC1Args.push_back("-internal-iframework");
1755 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1756 }
1757}
1758
1759/// Utility function to add a list of system include directories to CC1.
1760void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
1761 ArgStringList &CC1Args,
1762 ArrayRef<StringRef> Paths) {
1763 for (const auto &Path : Paths) {
1764 CC1Args.push_back("-internal-isystem");
1765 CC1Args.push_back(DriverArgs.MakeArgString(Path));
1766 }
1767}
1768
1769std::string ToolChain::concat(StringRef Path, const Twine &A, const Twine &B,
1770 const Twine &C, const Twine &D) {
1772 llvm::sys::path::append(Result, llvm::sys::path::Style::posix, A, B, C, D);
1773 return std::string(Result);
1774}
1775
1776std::string ToolChain::detectLibcxxVersion(StringRef IncludePath) const {
1777 std::error_code EC;
1778 int MaxVersion = 0;
1779 std::string MaxVersionString;
1780 SmallString<128> Path(IncludePath);
1781 llvm::sys::path::append(Path, "c++");
1782 for (llvm::vfs::directory_iterator LI = getVFS().dir_begin(Path, EC), LE;
1783 !EC && LI != LE; LI = LI.increment(EC)) {
1784 StringRef VersionText = llvm::sys::path::filename(LI->path());
1785 int Version;
1786 if (VersionText[0] == 'v' &&
1787 !VersionText.substr(1).getAsInteger(10, Version)) {
1788 if (Version > MaxVersion) {
1789 MaxVersion = Version;
1790 MaxVersionString = std::string(VersionText);
1791 }
1792 }
1793 }
1794 if (!MaxVersion)
1795 return "";
1796 return MaxVersionString;
1797}
1798
1799void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
1800 ArgStringList &CC1Args) const {
1801 // Header search paths should be handled by each of the subclasses.
1802 // Historically, they have not been, and instead have been handled inside of
1803 // the CC1-layer frontend. As the logic is hoisted out, this generic function
1804 // will slowly stop being called.
1805 //
1806 // While it is being called, replicate a bit of a hack to propagate the
1807 // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
1808 // header search paths with it. Once all systems are overriding this
1809 // function, the CC1 flag and this line can be removed.
1810 DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
1811}
1812
1814 const llvm::opt::ArgList &DriverArgs,
1815 llvm::opt::ArgStringList &CC1Args) const {
1816 DriverArgs.ClaimAllArgs(options::OPT_stdlibxx_isystem);
1817 // This intentionally only looks at -nostdinc++, and not -nostdinc or
1818 // -nostdlibinc. The purpose of -stdlib++-isystem is to support toolchain
1819 // setups with non-standard search logic for the C++ headers, while still
1820 // allowing users of the toolchain to bring their own C++ headers. Such a
1821 // toolchain likely also has non-standard search logic for the C headers and
1822 // uses -nostdinc to suppress the default logic, but -stdlib++-isystem should
1823 // still work in that case and only be suppressed by an explicit -nostdinc++
1824 // in a project using the toolchain.
1825 if (!DriverArgs.hasArg(options::OPT_nostdincxx))
1826 for (const auto &P :
1827 DriverArgs.getAllArgValues(options::OPT_stdlibxx_isystem))
1828 addSystemInclude(DriverArgs, CC1Args, P);
1829}
1830
1831bool ToolChain::ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const {
1832 return getDriver().CCCIsCXX() &&
1833 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
1834 options::OPT_nostdlibxx);
1835}
1836
1837void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
1838 ArgStringList &CmdArgs) const {
1839 assert(!Args.hasArg(options::OPT_nostdlibxx) &&
1840 "should not have called this");
1842
1843 switch (Type) {
1845 CmdArgs.push_back("-lc++");
1846 if (Args.hasArg(options::OPT_fexperimental_library))
1847 CmdArgs.push_back("-lc++experimental");
1848 break;
1849
1851 CmdArgs.push_back("-lstdc++");
1852 break;
1853 }
1854}
1855
1856void ToolChain::AddFilePathLibArgs(const ArgList &Args,
1857 ArgStringList &CmdArgs) const {
1858 for (const auto &LibPath : getFilePaths())
1859 if(LibPath.length() > 0)
1860 CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + LibPath));
1861}
1862
1863void ToolChain::AddCCKextLibArgs(const ArgList &Args,
1864 ArgStringList &CmdArgs) const {
1865 CmdArgs.push_back("-lcc_kext");
1866}
1867
1869 std::string &Path) const {
1870 // Don't implicitly link in mode-changing libraries in a shared library, since
1871 // this can have very deleterious effects. See the various links from
1872 // https://github.com/llvm/llvm-project/issues/57589 for more information.
1873 bool Default = !Args.hasArgNoClaim(options::OPT_shared);
1874
1875 // Do not check for -fno-fast-math or -fno-unsafe-math when -Ofast passed
1876 // (to keep the linker options consistent with gcc and clang itself).
1877 if (Default && !isOptimizationLevelFast(Args)) {
1878 // Check if -ffast-math or -funsafe-math.
1879 Arg *A = Args.getLastArg(
1880 options::OPT_ffast_math, options::OPT_fno_fast_math,
1881 options::OPT_funsafe_math_optimizations,
1882 options::OPT_fno_unsafe_math_optimizations, options::OPT_ffp_model_EQ);
1883
1884 if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
1885 A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
1886 Default = false;
1887 if (A && A->getOption().getID() == options::OPT_ffp_model_EQ) {
1888 StringRef Model = A->getValue();
1889 if (Model != "fast" && Model != "aggressive")
1890 Default = false;
1891 }
1892 }
1893
1894 // Whatever decision came as a result of the above implicit settings, either
1895 // -mdaz-ftz or -mno-daz-ftz is capable of overriding it.
1896 if (!Args.hasFlag(options::OPT_mdaz_ftz, options::OPT_mno_daz_ftz, Default))
1897 return false;
1898
1899 // If crtfastmath.o exists add it to the arguments.
1900 Path = GetFilePath("crtfastmath.o");
1901 return (Path != "crtfastmath.o"); // Not found.
1902}
1903
1905 ArgStringList &CmdArgs) const {
1906 std::string Path;
1907 if (isFastMathRuntimeAvailable(Args, Path)) {
1908 CmdArgs.push_back(Args.MakeArgString(Path));
1909 return true;
1910 }
1911
1912 return false;
1913}
1914
1916ToolChain::getSystemGPUArchs(const llvm::opt::ArgList &Args) const {
1917 return SmallVector<std::string>();
1918}
1919
1922 Action::OffloadKind DeviceOffloadKind) const {
1923 // Return sanitizers which don't require runtime support and are not
1924 // platform dependent.
1925
1926 SanitizerMask Res =
1927 (SanitizerKind::Undefined & ~SanitizerKind::Vptr) |
1928 (SanitizerKind::CFI & ~SanitizerKind::CFIICall) |
1929 SanitizerKind::CFICastStrict | SanitizerKind::FloatDivideByZero |
1930 SanitizerKind::KCFI | SanitizerKind::UnsignedIntegerOverflow |
1931 SanitizerKind::UnsignedShiftBase | SanitizerKind::ImplicitConversion |
1932 SanitizerKind::Nullability | SanitizerKind::LocalBounds |
1933 SanitizerKind::AllocToken;
1934 if (getTriple().getArch() == llvm::Triple::x86 ||
1935 getTriple().getArch() == llvm::Triple::x86_64 ||
1936 getTriple().getArch() == llvm::Triple::arm ||
1937 getTriple().getArch() == llvm::Triple::thumb || getTriple().isWasm() ||
1938 getTriple().isAArch64() || getTriple().isRISCV() ||
1939 getTriple().isLoongArch64() ||
1940 getTriple().getArch() == llvm::Triple::hexagon)
1941 Res |= SanitizerKind::CFIICall;
1942 if (getTriple().getArch() == llvm::Triple::x86_64 ||
1943 getTriple().isAArch64(64) || getTriple().isRISCV())
1944 Res |= SanitizerKind::ShadowCallStack;
1945 if (getTriple().isAArch64(64))
1946 Res |= SanitizerKind::MemTag;
1947 if (getTriple().isBPF())
1948 Res |= SanitizerKind::KernelAddress;
1949 return Res;
1950}
1951
1952void ToolChain::AddCudaIncludeArgs(const ArgList &DriverArgs,
1953 ArgStringList &CC1Args) const {}
1954
1955void ToolChain::AddHIPIncludeArgs(const ArgList &DriverArgs,
1956 ArgStringList &CC1Args) const {}
1957
1958void ToolChain::addSYCLIncludeArgs(const ArgList &DriverArgs,
1959 ArgStringList &CC1Args) const {}
1960
1962ToolChain::getDeviceLibs(const ArgList &DriverArgs, BoundArch BA,
1963 const Action::OffloadKind DeviceOffloadingKind) const {
1964 return {};
1965}
1966
1967void ToolChain::AddIAMCUIncludeArgs(const ArgList &DriverArgs,
1968 ArgStringList &CC1Args) const {}
1969
1970static VersionTuple separateMSVCFullVersion(unsigned Version) {
1971 if (Version < 100)
1972 return VersionTuple(Version);
1973
1974 if (Version < 10000)
1975 return VersionTuple(Version / 100, Version % 100);
1976
1977 unsigned Build = 0, Factor = 1;
1978 for (; Version > 10000; Version = Version / 10, Factor = Factor * 10)
1979 Build = Build + (Version % 10) * Factor;
1980 return VersionTuple(Version / 100, Version % 100, Build);
1981}
1982
1983VersionTuple
1985 const llvm::opt::ArgList &Args) const {
1986 const Arg *MSCVersion = Args.getLastArg(options::OPT_fmsc_version);
1987 const Arg *MSCompatibilityVersion =
1988 Args.getLastArg(options::OPT_fms_compatibility_version);
1989
1990 if (MSCVersion && MSCompatibilityVersion) {
1991 if (D)
1992 D->Diag(diag::err_drv_argument_not_allowed_with)
1993 << MSCVersion->getAsString(Args)
1994 << MSCompatibilityVersion->getAsString(Args);
1995 return VersionTuple();
1996 }
1997
1998 if (MSCompatibilityVersion) {
1999 VersionTuple MSVT;
2000 if (MSVT.tryParse(MSCompatibilityVersion->getValue())) {
2001 if (D)
2002 D->Diag(diag::err_drv_invalid_value)
2003 << MSCompatibilityVersion->getAsString(Args)
2004 << MSCompatibilityVersion->getValue();
2005 } else {
2006 return MSVT;
2007 }
2008 }
2009
2010 if (MSCVersion) {
2011 unsigned Version = 0;
2012 if (StringRef(MSCVersion->getValue()).getAsInteger(10, Version)) {
2013 if (D)
2014 D->Diag(diag::err_drv_invalid_value)
2015 << MSCVersion->getAsString(Args) << MSCVersion->getValue();
2016 } else {
2017 return separateMSVCFullVersion(Version);
2018 }
2019 }
2020
2021 return VersionTuple();
2022}
2023
2024llvm::opt::DerivedArgList *ToolChain::TranslateOpenMPTargetArgs(
2025 const llvm::opt::DerivedArgList &Args, const llvm::Triple &HostTriple,
2026 SmallVectorImpl<llvm::opt::Arg *> &AllocatedArgs) const {
2027 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2028 const OptTable &Opts = getDriver().getOpts();
2029 bool Modified = false;
2030 bool SameTripleAsHost = getTriple() == HostTriple;
2031
2032 // Handle -Xopenmp-target flags
2033 for (auto *A : Args) {
2034 // Exclude flags which may only apply to the host toolchain.
2035 // Do not exclude flags when the host triple (AuxTriple)
2036 // matches the current toolchain triple. If it is not present
2037 // at all, target and host share a toolchain.
2038 if (A->getOption().matches(options::OPT_m_Group)) {
2039 // Pass certain options to the device toolchain even when the triple
2040 // differs from the host: code object version must be passed to correctly
2041 // set metadata in intermediate files; linker version must be passed
2042 // because the Darwin toolchain requires the host and device linker
2043 // versions to match (the host version is cached in
2044 // MachO::getLinkerVersion).
2045 if (SameTripleAsHost ||
2046 A->getOption().matches(options::OPT_mcode_object_version_EQ) ||
2047 A->getOption().matches(options::OPT_mlinker_version_EQ))
2048 DAL->append(A);
2049 else
2050 Modified = true;
2051 continue;
2052 }
2053
2054 unsigned Index;
2055 unsigned Prev;
2056 bool XOpenMPTargetNoTriple =
2057 A->getOption().matches(options::OPT_Xopenmp_target);
2058
2059 if (A->getOption().matches(options::OPT_Xopenmp_target_EQ)) {
2060 llvm::Triple TT = normalizeOffloadTriple(A->getValue(0));
2061
2062 // Passing device args: -Xopenmp-target=<triple> -opt=val.
2063 if (TT.isCompatibleWith(getTriple()))
2064 Index = Args.getBaseArgs().MakeIndex(A->getValue(1));
2065 else
2066 continue;
2067 } else if (XOpenMPTargetNoTriple) {
2068 // Passing device args: -Xopenmp-target -opt=val.
2069 Index = Args.getBaseArgs().MakeIndex(A->getValue(0));
2070 } else {
2071 DAL->append(A);
2072 continue;
2073 }
2074
2075 // Parse the argument to -Xopenmp-target.
2076 Prev = Index;
2077 std::unique_ptr<Arg> XOpenMPTargetArg(Opts.ParseOneArg(Args, Index));
2078 if (!XOpenMPTargetArg || Index > Prev + 1) {
2079 if (!A->isClaimed()) {
2080 getDriver().Diag(diag::err_drv_invalid_Xopenmp_target_with_args)
2081 << A->getAsString(Args);
2082 }
2083 continue;
2084 }
2085 if (XOpenMPTargetNoTriple && XOpenMPTargetArg &&
2086 Args.getAllArgValues(options::OPT_offload_targets_EQ).size() != 1) {
2087 getDriver().Diag(diag::err_drv_Xopenmp_target_missing_triple);
2088 continue;
2089 }
2090 XOpenMPTargetArg->setBaseArg(A);
2091 A = XOpenMPTargetArg.release();
2092 if (A->getOption().matches(options::OPT_D) &&
2093 (getDriver().IsCLMode() || HostTriple.isWindowsMSVCEnvironment()))
2094 A->getValues()[0] =
2095 ClangCLArgs::translateMacroDefinition(A->getValue(), Args);
2096 AllocatedArgs.push_back(A);
2097 DAL->append(A);
2098 Modified = true;
2099 }
2100
2101 if (Modified) {
2102 // GNU-mode Clang targeting MSVC also accepts forwarded clang-cl options.
2103 if (!getDriver().IsCLMode() && HostTriple.isWindowsMSVCEnvironment()) {
2104 DerivedArgList *Translated =
2105 ClangCLArgs::translateArgs(*DAL, HostTriple, Args);
2106 delete DAL;
2107 return Translated;
2108 }
2109 return DAL;
2110 }
2111
2112 delete DAL;
2113 return nullptr;
2114}
2115
2116// TODO: Currently argument values separated by space e.g.
2117// -Xclang -mframe-pointer=no cannot be passed by -Xarch_. This should be
2118// fixed.
2120 const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A,
2121 llvm::opt::DerivedArgList *DAL,
2122 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2123 const OptTable &Opts = getDriver().getOpts();
2124 unsigned ValuePos = 1;
2125 if (A->getOption().matches(options::OPT_Xarch_device) ||
2126 A->getOption().matches(options::OPT_Xarch_host))
2127 ValuePos = 0;
2128
2129 const InputArgList &BaseArgs = Args.getBaseArgs();
2130 unsigned Index = BaseArgs.MakeIndex(A->getValue(ValuePos));
2131 unsigned Prev = Index;
2132 std::unique_ptr<llvm::opt::Arg> XarchArg(Opts.ParseOneArg(
2133 Args, Index, llvm::opt::Visibility(options::ClangOption)));
2134
2135 // If the argument parsing failed or more than one argument was
2136 // consumed, the -Xarch_ argument's parameter tried to consume
2137 // extra arguments. Emit an error and ignore.
2138 //
2139 // We also want to disallow any options which would alter the
2140 // driver behavior; that isn't going to work in our model. We
2141 // use options::NoXarchOption to control this.
2142 if (!XarchArg || Index > Prev + 1) {
2143 getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args)
2144 << A->getAsString(Args);
2145 return;
2146 } else if (XarchArg->getOption().hasFlag(options::NoXarchOption)) {
2147 auto &Diags = getDriver().getDiags();
2148 unsigned DiagID =
2150 "invalid Xarch argument: '%0', not all driver "
2151 "options can be forwared via Xarch argument");
2152 Diags.Report(DiagID) << A->getAsString(Args);
2153 return;
2154 }
2155
2156 XarchArg->setBaseArg(A);
2157 A = XarchArg.release();
2158
2159 // Linker input arguments require custom handling. The problem is that we
2160 // have already constructed the phase actions, so we can not treat them as
2161 // "input arguments".
2162 if (A->getOption().hasFlag(options::LinkerInput)) {
2163 // Convert the argument into individual Zlinker_input_args. Need to do this
2164 // manually to avoid memory leaks with the allocated arguments.
2165 for (const char *Value : A->getValues()) {
2166 auto Opt = Opts.getOption(options::OPT_Zlinker_input);
2167 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
2168 auto NewArg =
2169 new Arg(Opt, BaseArgs.MakeArgString(Opt.getPrefix() + Opt.getName()),
2170 Index, BaseArgs.getArgString(Index + 1), A);
2171
2172 DAL->append(NewArg);
2173 if (!AllocatedArgs)
2174 DAL->AddSynthesizedArg(NewArg);
2175 else
2176 AllocatedArgs->push_back(NewArg);
2177 }
2178 }
2179
2180 if (!AllocatedArgs)
2181 DAL->AddSynthesizedArg(A);
2182 else
2183 AllocatedArgs->push_back(A);
2184
2185 // Forwarded macros are parsed after the shared input translation.
2186 if (A->getOption().matches(options::OPT_D) &&
2187 (getDriver().IsCLMode() ||
2188 llvm::Triple(llvm::Triple::normalize(getDriver().getTargetTriple()))
2189 .isWindowsMSVCEnvironment()))
2190 A->getValues()[0] =
2191 ClangCLArgs::translateMacroDefinition(A->getValue(), Args);
2192}
2193
2194/// Match any triple recognized arch aliases.
2195static bool isXArchCompatibleTripleArch(const llvm::Triple &TT,
2196 StringRef XArchVal) {
2197 llvm::Triple ParsedTriple(XArchVal);
2198
2199 // Accept -Xarch_amdgcn for all amdgpu subarches, and -Xarch_amdgpu9 for
2200 // amdgpu9.xx
2201 if (TT.isAMDGCN() && ParsedTriple.isAMDGCN())
2202 return llvm::AMDGPU::isSubArchCompatible(TT, ParsedTriple);
2203
2204 return TT.getArch() == ParsedTriple.getArch() &&
2205 TT.getSubArch() == ParsedTriple.getSubArch();
2206}
2207
2208llvm::opt::DerivedArgList *ToolChain::TranslateXarchArgs(
2209 const llvm::opt::DerivedArgList &Args, BoundArch BA,
2211 SmallVectorImpl<llvm::opt::Arg *> *AllocatedArgs) const {
2212 DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs());
2213 bool Modified = false;
2214
2215 bool IsDevice = OFK != Action::OFK_None && OFK != Action::OFK_Host;
2216 for (Arg *A : Args) {
2217 bool NeedTrans = false;
2218 bool Skip = false;
2219 if (A->getOption().matches(options::OPT_Xarch_device)) {
2220 NeedTrans = IsDevice;
2221 Skip = !IsDevice;
2222 } else if (A->getOption().matches(options::OPT_Xarch_host)) {
2223 NeedTrans = !IsDevice;
2224 Skip = IsDevice;
2225 } else if (A->getOption().matches(options::OPT_Xarch__)) {
2226 StringRef Val = A->getValue();
2227 NeedTrans = Val == getArchName() || (BA && Val == BA.ArchName) ||
2228 isXArchCompatibleTripleArch(Triple, Val);
2229 Skip = !NeedTrans;
2230 }
2231 if (NeedTrans || Skip)
2232 Modified = true;
2233 if (NeedTrans) {
2234 A->claim();
2235 TranslateXarchArgs(Args, A, DAL, AllocatedArgs);
2236 }
2237 if (!Skip)
2238 DAL->append(A);
2239 }
2240
2241 if (Modified)
2242 return DAL;
2243
2244 delete DAL;
2245 return nullptr;
2246}
Result
Implement __builtin_bit_cast and related operations.
Defines types useful for describing an Objective-C runtime.
Defines the clang::SanitizerKind enum.
static void processMultilibCustomFlags(Multilib::flags_list &List, const llvm::opt::ArgList &Args)
static const DriverSuffix * parseDriverSuffix(StringRef ProgName, size_t &Pos)
static void getAArch64MultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
static LTOKind parseLTOMode(const llvm::opt::ArgList &Args, llvm::opt::OptSpecifier OptEq, llvm::opt::OptSpecifier OptNeg)
static std::string normalizeProgramName(llvm::StringRef Argv0)
Normalize the program name from argv[0] by stripping the file extension if present and lower-casing t...
static StringRef getArchNameForCompilerRTLib(const ToolChain &TC, const ArgList &Args)
static void getRISCVMultilibFlags(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, Multilib::flags_list &Result, bool hasShadowCallStack)
static VersionTuple separateMSVCFullVersion(unsigned Version)
static const DriverSuffix * FindDriverSuffix(StringRef ProgName, size_t &Pos)
static ToolChain::ExceptionsMode CalculateExceptionsMode(const ArgList &Args)
Definition ToolChain.cpp:85
static llvm::opt::Arg * GetRTTIArgument(const ArgList &Args)
Definition ToolChain.cpp:64
static bool isXArchCompatibleTripleArch(const llvm::Triple &TT, StringRef XArchVal)
Match any triple recognized arch aliases.
static void getARMMultilibFlags(const Driver &D, const llvm::Triple &Triple, llvm::Reloc::Model RelocationModel, const llvm::opt::ArgList &Args, Multilib::flags_list &Result)
static ToolChain::RTTIMode CalculateRTTIMode(const ArgList &Args, const llvm::Triple &Triple, const Arg *CachedRTTIArg)
Definition ToolChain.cpp:69
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition Diagnostic.h:946
The basic abstraction for the target Objective-C runtime.
Definition ObjCRuntime.h:28
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition ObjCRuntime.h:53
The base class of the type hierarchy.
Definition TypeBase.h:1879
ActionClass getKind() const
Definition Action.h:152
static llvm::opt::DerivedArgList * translateArgs(const llvm::opt::DerivedArgList &Args, const llvm::Triple &HostTriple, const llvm::opt::DerivedArgList &Owner)
Translate a filtered list that may contain new clang-cl options, replacing earlier /O expansions.
static const char * translateMacroDefinition(const char *Value, const llvm::opt::ArgList &Args)
Normalize MSVC's '#' macro separator, also used by Clang targeting MSVC and by arguments parsed after...
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:918
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
StringRef getFlangF128MathLibrary() const
Definition Driver.h:450
const llvm::opt::OptTable & getOpts() const
Definition Driver.h:406
llvm::vfs::FileSystem & getVFS() const
Definition Driver.h:410
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
StringRef getPreferredLinker() const
Definition Driver.h:432
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
Definition Driver.h:220
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getFilename() const
Definition InputInfo.h:83
static llvm::ErrorOr< MultilibSet > parseYaml(llvm::MemoryBufferRef, llvm::SourceMgr::DiagHandlerTy=nullptr, void *DiagHandlerCtxt=nullptr)
Definition Multilib.cpp:479
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag.
Definition Multilib.h:35
std::vector< std::string > flags_list
Definition Multilib.h:37
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
static void normalizeOffloadTriple(llvm::Triple &TT)
Definition ToolChain.h:907
virtual bool isFastMathRuntimeAvailable(const llvm::opt::ArgList &Args, std::string &Path) const
If a runtime library exists that sets global flags for unsafe floating point math,...
virtual void AddCCKextLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCCKextLibArgs - Add the system specific linker arguments to use for kernel extensions (Darwin-spec...
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
static void addSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory to CC1 arguments.
bool isUsingLTO(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Returns true if LTO is active for this toolchain given the args.
virtual CStdlibType GetCStdlibType(const llvm::opt::ArgList &Args) const
virtual std::string computeSysRoot() const
Return the sysroot, possibly searching for a default sysroot using target-specific logic.
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
std::optional< std::string > getStdlibPath() const
virtual RuntimeLibType GetRuntimeLibType(const llvm::opt::ArgList &Args) const
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
virtual llvm::SmallVector< BitCodeLibraryInfo, 12 > getDeviceLibs(const llvm::opt::ArgList &Args, BoundArch BA, const Action::OffloadKind DeviceOffloadingKind) const
Get paths for device libraries.
virtual LTOKind getDefaultLTOMode() const
Returns the default LTO mode for this toolchain.
bool ShouldLinkCXXStdlib(const llvm::opt::ArgList &Args) const
Returns if the C++ standard library should be linked in.
static void addSystemFrameworkIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system framework directories to CC1.
static void addExternCSystemInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system include directory with extern "C" semantics to CC1 arguments.
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
virtual Tool * buildStaticLibTool() const
virtual bool IsIntegratedBackendSupported() const
IsIntegratedBackendSupported - Does this tool chain support -fintegrated-objemitter.
Definition ToolChain.h:494
virtual void addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds the path for the Fortran runtime libraries to CmdArgs.
std::optional< std::string > findMultilibsYAML(const llvm::opt::ArgList &Args, const Driver &D, StringRef FallbackDir={})
Load multilib configuration from a YAML file at MultilibPath,.
std::string GetFilePath(const char *Name) const
virtual void addFortranRuntimeLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Adds Fortran runtime libraries to CmdArgs.
path_list & getFilePaths()
Definition ToolChain.h:322
virtual Tool * SelectTool(const JobAction &JA) const
Choose a tool to use to handle the action JA.
static bool needsProfileRT(const llvm::opt::ArgList &Args)
needsProfileRT - returns true if instrumentation profile is on.
StringRef getOS() const
Definition ToolChain.h:301
virtual std::string ComputeEffectiveClangTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeEffectiveClangTriple - Return the Clang triple to use for this target, which may take into acc...
virtual bool isBareMetal() const
isBareMetal - Is this a bare metal target.
Definition ToolChain.h:706
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
virtual SanitizerMask getSupportedSanitizers(BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Return sanitizers which are available in this toolchain.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
virtual std::string detectLibcxxVersion(StringRef IncludePath) const
static std::string concat(StringRef Path, const Twine &A, const Twine &B="", const Twine &C="", const Twine &D="")
RTTIMode getRTTIMode() const
Definition ToolChain.h:365
ExceptionsMode getExceptionsMode() const
Definition ToolChain.h:368
llvm::vfs::FileSystem & getVFS() const
Multilib::flags_list getMultilibFlags(const llvm::opt::ArgList &) const
Get flags suitable for multilib selection, based on the provided clang command line arguments.
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
bool loadMultilibsFromYAML(const llvm::opt::ArgList &Args, const Driver &D, StringRef Fallback={})
Discover and load a multilib.yaml configuration.
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
ToolChain(const Driver &D, const llvm::Triple &T, const llvm::opt::ArgList &Args)
Definition ToolChain.cpp:93
static void addSystemFrameworkInclude(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
Utility function to add a system framework directory to CC1 arguments.
SmallVector< std::string > MultilibMacroDefines
Definition ToolChain.h:214
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
bool addFastMathRuntimeIfAvailable(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFastMathRuntimeIfAvailable - If a runtime library exists that sets global flags for unsafe floatin...
static void addExternCSystemIncludeIfExists(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, const Twine &Path)
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
virtual bool useIntegratedBackend() const
Check if the toolchain should use the integrated backend.
std::string GetStaticLibToolPath() const
Returns the linker path for emitting a static library.
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
virtual void AddCXXStdlibLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddCXXStdlibLibArgs - Add the system specific linker arguments to use for the given C++ standard libr...
static ParsedClangName getTargetAndModeFromProgramName(StringRef ProgName)
Return any implicit target and/or mode flag for an invocation of the compiler driver as ProgName.
virtual bool IsIntegratedBackendDefault() const
IsIntegratedBackendDefault - Does this tool chain enable -fintegrated-objemitter by default.
Definition ToolChain.h:490
virtual const char * getDefaultLinker() const
GetDefaultLinker - Get the default linker to use.
Definition ToolChain.h:545
virtual Tool * buildLinker() const
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
virtual types::ID LookupTypeForExtension(StringRef Ext) const
LookupTypeForExtension - Return the default language type to use for the given extension.
virtual bool HasNativeLLVMSupport() const
HasNativeLTOLinker - Check whether the linker and related tools have native LLVM support.
virtual UnwindLibType GetUnwindLibType(const llvm::opt::ArgList &Args) const
void addFlangRTLibPath(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Add the path for libflang_rt.runtime.a.
std::optional< std::string > getTargetSubDirPath(StringRef BaseDir) const
Find the target-specific subdirectory for the current target triple under BaseDir,...
virtual void addProfileRTLibs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
addProfileRTLibs - When -fprofile-instr-profile is specified, try to pass a suitable profile runtime ...
const XRayArgs getXRayArgs(const llvm::opt::ArgList &) const
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
OrderedMultilibs getOrderedMultilibs() const
Get selected multilibs in priority order with default fallback.
virtual llvm::opt::DerivedArgList * TranslateOpenMPTargetArgs(const llvm::opt::DerivedArgList &Args, const llvm::Triple &HostTriple, SmallVectorImpl< llvm::opt::Arg * > &AllocatedArgs) const
TranslateOpenMPTargetArgs - Create a new derived argument list for that contains the OpenMP target sp...
llvm::iterator_range< llvm::SmallVector< Multilib >::const_reverse_iterator > OrderedMultilibs
Definition ToolChain.h:216
StringRef getTripleString() const
Definition ToolChain.h:307
virtual std::string getCompilerRTPath() const
llvm::Triple getTripleWithoutOSVersion() const
std::string GetLinkerPath(bool *LinkerIsLLD=nullptr) const
Returns the linker path, respecting the -fuse-ld= argument to determine the linker suffix or name.
virtual std::string buildCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type, bool AddArch, bool IsFortran=false) const
virtual Expected< SmallVector< std::string > > getSystemGPUArchs(const llvm::opt::ArgList &Args) const
getSystemGPUArchs - Use a tool to detect the user's availible GPUs.
virtual std::string ComputeLLVMTriple(const llvm::opt::ArgList &Args, BoundArch BA={}, types::ID InputType=types::TY_INVALID) const
ComputeLLVMTriple - Return the LLVM target triple to use, after taking command line arguments into ac...
std::string GetProgramPath(const char *Name) const
static void addSystemIncludes(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, ArrayRef< StringRef > Paths)
Utility function to add a list of system include directories to CC1.
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
virtual StringRef getOSLibName() const
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
virtual CXXStdlibType GetDefaultCXXStdlibType() const
Definition ToolChain.h:552
std::optional< std::string > getStdlibIncludePath() const
virtual void AddFilePathLibArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
AddFilePathLibArgs - Add each thing in getFilePaths() as a "-L" option.
virtual RuntimeLibType GetDefaultRuntimeLibType() const
GetDefaultRuntimeLibType - Get the default runtime library variant to use.
Definition ToolChain.h:548
StringRef getDefaultUniversalArchName() const
Provide the default architecture name (as expected by -arch) for this toolchain.
virtual Tool * buildAssembler() const
virtual StringRef GetCXXStdlibName(const llvm::opt::ArgList &Args) const
void setTripleEnvironment(llvm::Triple::EnvironmentType Env)
virtual void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const
Add options that need to be passed to cc1as for this target.
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition ToolChain.h:486
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
llvm::SmallVector< Multilib > SelectedMultilibs
Definition ToolChain.h:213
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs, BoundArch BA={}, Action::OffloadKind DeviceOffloadKind=Action::OFK_None) const
path_list & getLibraryPaths()
Definition ToolChain.h:319
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
virtual UnwindLibType GetDefaultUnwindLibType() const
Definition ToolChain.h:556
std::optional< std::string > getRuntimePath() const
virtual Tool * getTool(Action::ActionClass AC) const
const char * getCompilerRTArgString(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static, bool IsFortran=false) const
friend class RegisterEffectiveTriple
Definition ToolChain.h:145
virtual path_list getArchSpecificLibPaths() const
std::optional< std::string > GetFilePathIfExists(const char *Name) const
virtual bool isCrossCompiling() const
Returns true if the toolchain is targeting a non-native architecture.
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
virtual bool IsNonIntegratedBackendSupported() const
IsNonIntegratedBackendSupported - Does this tool chain support -fno-integrated-objemitter.
Definition ToolChain.h:498
std::optional< std::string > getDefaultIntrinsicModuleDir() const
Returns the target-specific path for Flang's intrinsic modules in the resource directory if it exists...
virtual void TranslateXarchArgs(const llvm::opt::DerivedArgList &Args, llvm::opt::Arg *&A, llvm::opt::DerivedArgList *DAL, SmallVectorImpl< llvm::opt::Arg * > *AllocatedArgs=nullptr) const
Append the argument following A to DAL assuming A is an Xarch argument.
virtual bool useRelaxRelocations() const
Check whether to enable x86 relax relocations by default.
StringRef getArchName() const
Definition ToolChain.h:299
SmallVector< std::string, 16 > path_list
Definition ToolChain.h:94
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
Tool - Information on a specific compilation tool.
Definition Tool.h:31
Clang integrated assembler tool.
Definition Clang.h:120
Clang compiler tool.
Definition Clang.h:28
Flang compiler tool.
Definition Flang.h:25
void setArchNameInTriple(const Driver &D, const llvm::opt::ArgList &Args, BoundArch BA, types::ID InputType, llvm::Triple &Triple)
void getAArch64TargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS, bool ForMultilib=false)
void setArchNameInTriple(const Driver &D, const llvm::opt::ArgList &Args, types::ID InputType, llvm::Triple &Triple)
void setFloatABIInTriple(const Driver &D, const llvm::opt::ArgList &Args, llvm::Triple &triple)
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
void setEABIInTriple(const Driver &D, const llvm::opt::ArgList &Args, llvm::Triple &triple)
llvm::ARM::FPUKind getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, std::vector< llvm::StringRef > &Features, bool ForAS, bool ForMultilib=false)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:305
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
SmallVector< StringRef > unifyTargetFeatures(ArrayRef< StringRef > Features)
If there are multiple +xxx or -xxx features, keep the last one.
void addAsNeededOption(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool as_needed)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
ID lookupTypeForExtension(llvm::StringRef Ext)
lookupTypeForExtension - Lookup the type to use for the file extension Ext.
Definition Types.cpp:335
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition Driver.h:57
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
Top level wrappers for InstallAPI frontend operations.
@ Link
'link' clause, allowed on 'declare' construct.
@ Default
Set to the current date and time.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Represents a bound architecture for offload / multiple architecture compilation.
llvm::StringRef ArchName
Helper structure used to pass information extracted from clang executable name such as i686-linux-and...
Definition ToolChain.h:65