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