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