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