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