1//===--- TargetInfo.cpp - Information about Target machine ----------------===//
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// This file implements the TargetInfo interface.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Basic/TargetInfo.h"
14#include "clang/Basic/AddressSpaces.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/DiagnosticFrontend.h"
18#include "clang/Basic/LangOptions.h"
19#include "llvm/ADT/APFloat.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/ErrorHandling.h"
22#include "llvm/TargetParser/TargetParser.h"
23#include <cstdlib>
24using namespace clang;
25
26static const LangASMap DefaultAddrSpaceMap = {0};
27// The fake address space map must have a distinct entry for each
28// language-specific address space.
29static const LangASMap FakeAddrSpaceMap = {
30 0, // Default
31 1, // opencl_global
32 3, // opencl_local
33 2, // opencl_constant
34 0, // opencl_private
35 4, // opencl_generic
36 5, // opencl_global_device
37 6, // opencl_global_host
38 7, // cuda_device
39 8, // cuda_constant
40 9, // cuda_shared
41 1, // sycl_global
42 5, // sycl_global_device
43 6, // sycl_global_host
44 3, // sycl_local
45 0, // sycl_private
46 10, // ptr32_sptr
47 11, // ptr32_uptr
48 12, // ptr64
49 13, // hlsl_groupshared
50 14, // hlsl_constant
51 15, // hlsl_private
52 16, // hlsl_device
53 17, // hlsl_input
54 20, // wasm_funcref
55};
56
57// TargetInfo Constructor.
58TargetInfo::TargetInfo(const llvm::Triple &T) : Triple(T) {
59 // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or
60 // SPARC. These should be overridden by concrete targets as needed.
61 BigEndian = !T.isLittleEndian();
62 TLSSupported = true;
63 VLASupported = true;
64 NoAsmVariants = false;
65 HasLegalHalfType = false;
66 HalfArgsAndReturns = false;
67 HasFloat128 = false;
68 HasIbm128 = false;
69 HasFloat16 = false;
70 HasBFloat16 = false;
71 HasFullBFloat16 = false;
72 HasLongDouble = true;
73 HasFPReturn = true;
74 HasStrictFP = false;
75 PointerWidth = PointerAlign = 32;
76 BoolWidth = BoolAlign = 8;
77 ShortWidth = ShortAlign = 16;
78 IntWidth = IntAlign = 32;
79 LongWidth = LongAlign = 32;
80 LongLongWidth = LongLongAlign = 64;
81 Int128Align = 128;
82
83 // Fixed point default bit widths
84 ShortAccumWidth = ShortAccumAlign = 16;
85 AccumWidth = AccumAlign = 32;
86 LongAccumWidth = LongAccumAlign = 64;
87 ShortFractWidth = ShortFractAlign = 8;
88 FractWidth = FractAlign = 16;
89 LongFractWidth = LongFractAlign = 32;
90
91 // Fixed point default integral and fractional bit sizes
92 // We give the _Accum 1 fewer fractional bits than their corresponding _Fract
93 // types by default to have the same number of fractional bits between _Accum
94 // and _Fract types.
95 PaddingOnUnsignedFixedPoint = false;
96 ShortAccumScale = 7;
97 AccumScale = 15;
98 LongAccumScale = 31;
99
100 SuitableAlign = 64;
101 DefaultAlignForAttributeAligned = 128;
102 MinGlobalAlign = 0;
103 // From the glibc documentation, on GNU systems, malloc guarantees 16-byte
104 // alignment on 64-bit systems and 8-byte alignment on 32-bit systems. See
105 // https://www.gnu.org/software/libc/manual/html_node/Malloc-Examples.html.
106 // This alignment guarantee also applies to Windows and Android. On Darwin
107 // and OpenBSD, the alignment is 16 bytes on both 64-bit and 32-bit systems.
108 if (T.isGNUEnvironment() || T.isWindowsMSVCEnvironment() || T.isAndroid() ||
109 T.isOHOSFamily())
110 NewAlign = Triple.isArch64Bit() ? 128 : Triple.isArch32Bit() ? 64 : 0;
111 else if (T.isOSDarwin() || T.isOSOpenBSD())
112 NewAlign = 128;
113 else
114 NewAlign = 0; // Infer from basic type alignment.
115 HalfWidth = 16;
116 HalfAlign = 16;
117 FloatWidth = 32;
118 FloatAlign = 32;
119 DoubleWidth = 64;
120 DoubleAlign = 64;
121 LongDoubleWidth = 64;
122 LongDoubleAlign = 64;
123 Float128Align = 128;
124 Ibm128Align = 128;
125 LargeArrayMinWidth = 0;
126 LargeArrayAlign = 0;
127 MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0;
128 MaxVectorAlign = 0;
129 MaxTLSAlign = 0;
130 SizeType = UnsignedLong;
131 PtrDiffType = SignedLong;
132 IntMaxType = SignedLongLong;
133 IntPtrType = SignedLong;
134 WCharType = SignedInt;
135 WIntType = SignedInt;
136 Char16Type = UnsignedShort;
137 Char32Type = UnsignedInt;
138 Int64Type = SignedLongLong;
139 Int16Type = SignedShort;
140 SigAtomicType = SignedInt;
141 ProcessIDType = SignedInt;
142 UseSignedCharForObjCBool = true;
143 UseBitFieldTypeAlignment = true;
144 UseZeroLengthBitfieldAlignment = false;
145 UseLeadingZeroLengthBitfield = true;
146 UseExplicitBitFieldAlignment = true;
147 ZeroLengthBitfieldBoundary = 0;
148 LargestOverSizedBitfieldContainer = 64;
149 MaxAlignedAttribute = 0;
150 HalfFormat = &llvm::APFloat::IEEEhalf();
151 FloatFormat = &llvm::APFloat::IEEEsingle();
152 DoubleFormat = &llvm::APFloat::IEEEdouble();
153 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
154 Float128Format = &llvm::APFloat::IEEEquad();
155 Ibm128Format = &llvm::APFloat::PPCDoubleDouble();
156 MCountName = "mcount";
157 UserLabelPrefix = "_";
158 RegParmMax = 0;
159 SSERegParmMax = 0;
160 HasAlignMac68kSupport = false;
161 HasBuiltinMSVaList = false;
162 HasAArch64ACLETypes = false;
163 HasRISCVVTypes = false;
164 AllowAMDGPUUnsafeFPAtomics = false;
165 HasUnalignedAccess = false;
166 ARMCDECoprocMask = 0;
167
168 // Default to no types using fpret.
169 RealTypeUsesObjCFPRetMask = 0;
170
171 // Default to not using fp2ret for __Complex long double
172 ComplexLongDoubleUsesFP2Ret = false;
173
174 // Set the C++ ABI based on the triple.
175 TheCXXABI.set(Triple.isKnownWindowsMSVCEnvironment()
176 ? TargetCXXABI::Microsoft
177 : TargetCXXABI::GenericItanium);
178
179 // Default to an empty address space map.
180 AddrSpaceMap = &DefaultAddrSpaceMap;
181 UseAddrSpaceMapMangling = false;
182
183 // Default to an unknown platform name.
184 PlatformName = "unknown";
185 PlatformMinVersion = VersionTuple();
186
187 MaxOpenCLWorkGroupSize = 1024;
188
189 MaxBitIntWidth.reset();
190}
191
192// Out of line virtual dtor for TargetInfo.
193TargetInfo::~TargetInfo() {}
194
195void TargetInfo::resetDataLayout(StringRef DL, const char *ULP) {
196 DataLayoutString = DL.str();
197 UserLabelPrefix = ULP;
198}
199
200bool
201TargetInfo::checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const {
202 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=branch";
203 return false;
204}
205
206CFBranchLabelSchemeKind TargetInfo::getDefaultCFBranchLabelScheme() const {
207 // if this hook is called, the target should override it to return a
208 // non-default scheme
209 llvm::report_fatal_error(reason: "not implemented");
210}
211
212bool TargetInfo::checkCFBranchLabelSchemeSupported(
213 const CFBranchLabelSchemeKind Scheme, DiagnosticsEngine &Diags) const {
214 if (Scheme != CFBranchLabelSchemeKind::Default)
215 Diags.Report(DiagID: diag::err_opt_not_valid_on_target)
216 << (Twine("mcf-branch-label-scheme=") +
217 getCFBranchLabelSchemeFlagVal(Scheme))
218 .str();
219 return false;
220}
221
222bool
223TargetInfo::checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const {
224 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "cf-protection=return";
225 return false;
226}
227
228/// getTypeName - Return the user string for the specified integer type enum.
229/// For example, SignedShort -> "short".
230const char *TargetInfo::getTypeName(IntType T) {
231 switch (T) {
232 default: llvm_unreachable("not an integer!");
233 case SignedChar: return "signed char";
234 case UnsignedChar: return "unsigned char";
235 case SignedShort: return "short";
236 case UnsignedShort: return "unsigned short";
237 case SignedInt: return "int";
238 case UnsignedInt: return "unsigned int";
239 case SignedLong: return "long int";
240 case UnsignedLong: return "long unsigned int";
241 case SignedLongLong: return "long long int";
242 case UnsignedLongLong: return "long long unsigned int";
243 }
244}
245
246/// getTypeConstantSuffix - Return the constant suffix for the specified
247/// integer type enum. For example, SignedLong -> "L".
248const char *TargetInfo::getTypeConstantSuffix(IntType T) const {
249 switch (T) {
250 default: llvm_unreachable("not an integer!");
251 case SignedChar:
252 case SignedShort:
253 case SignedInt: return "";
254 case SignedLong: return "L";
255 case SignedLongLong: return "LL";
256 case UnsignedChar:
257 if (getCharWidth() < getIntWidth())
258 return "";
259 [[fallthrough]];
260 case UnsignedShort:
261 if (getShortWidth() < getIntWidth())
262 return "";
263 [[fallthrough]];
264 case UnsignedInt: return "U";
265 case UnsignedLong: return "UL";
266 case UnsignedLongLong: return "ULL";
267 }
268}
269
270/// getTypeFormatModifier - Return the printf format modifier for the
271/// specified integer type enum. For example, SignedLong -> "l".
272
273const char *TargetInfo::getTypeFormatModifier(IntType T) {
274 switch (T) {
275 default: llvm_unreachable("not an integer!");
276 case SignedChar:
277 case UnsignedChar: return "hh";
278 case SignedShort:
279 case UnsignedShort: return "h";
280 case SignedInt:
281 case UnsignedInt: return "";
282 case SignedLong:
283 case UnsignedLong: return "l";
284 case SignedLongLong:
285 case UnsignedLongLong: return "ll";
286 }
287}
288
289/// getTypeWidth - Return the width (in bits) of the specified integer type
290/// enum. For example, SignedInt -> getIntWidth().
291unsigned TargetInfo::getTypeWidth(IntType T) const {
292 switch (T) {
293 default: llvm_unreachable("not an integer!");
294 case SignedChar:
295 case UnsignedChar: return getCharWidth();
296 case SignedShort:
297 case UnsignedShort: return getShortWidth();
298 case SignedInt:
299 case UnsignedInt: return getIntWidth();
300 case SignedLong:
301 case UnsignedLong: return getLongWidth();
302 case SignedLongLong:
303 case UnsignedLongLong: return getLongLongWidth();
304 };
305}
306
307TargetInfo::IntType TargetInfo::getIntTypeByWidth(
308 unsigned BitWidth, bool IsSigned) const {
309 if (getCharWidth() == BitWidth)
310 return IsSigned ? SignedChar : UnsignedChar;
311 if (getShortWidth() == BitWidth)
312 return IsSigned ? SignedShort : UnsignedShort;
313 if (getIntWidth() == BitWidth)
314 return IsSigned ? SignedInt : UnsignedInt;
315 if (getLongWidth() == BitWidth)
316 return IsSigned ? SignedLong : UnsignedLong;
317 if (getLongLongWidth() == BitWidth)
318 return IsSigned ? SignedLongLong : UnsignedLongLong;
319 return NoInt;
320}
321
322TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
323 bool IsSigned) const {
324 if (getCharWidth() >= BitWidth)
325 return IsSigned ? SignedChar : UnsignedChar;
326 if (getShortWidth() >= BitWidth)
327 return IsSigned ? SignedShort : UnsignedShort;
328 if (getIntWidth() >= BitWidth)
329 return IsSigned ? SignedInt : UnsignedInt;
330 if (getLongWidth() >= BitWidth)
331 return IsSigned ? SignedLong : UnsignedLong;
332 if (getLongLongWidth() >= BitWidth)
333 return IsSigned ? SignedLongLong : UnsignedLongLong;
334 return NoInt;
335}
336
337FloatModeKind TargetInfo::getRealTypeByWidth(unsigned BitWidth,
338 FloatModeKind ExplicitType) const {
339 if (getHalfWidth() == BitWidth)
340 return FloatModeKind::Half;
341 if (getFloatWidth() == BitWidth)
342 return FloatModeKind::Float;
343 if (getDoubleWidth() == BitWidth)
344 return FloatModeKind::Double;
345
346 switch (BitWidth) {
347 case 96:
348 if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended())
349 return FloatModeKind::LongDouble;
350 break;
351 case 128:
352 // The caller explicitly asked for an IEEE compliant type but we still
353 // have to check if the target supports it.
354 if (ExplicitType == FloatModeKind::Float128)
355 return hasFloat128Type() ? FloatModeKind::Float128
356 : FloatModeKind::NoFloat;
357 if (ExplicitType == FloatModeKind::Ibm128)
358 return hasIbm128Type() ? FloatModeKind::Ibm128
359 : FloatModeKind::NoFloat;
360 if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble() ||
361 &getLongDoubleFormat() == &llvm::APFloat::IEEEquad())
362 return FloatModeKind::LongDouble;
363 if (hasFloat128Type())
364 return FloatModeKind::Float128;
365 break;
366 }
367
368 return FloatModeKind::NoFloat;
369}
370
371/// getTypeAlign - Return the alignment (in bits) of the specified integer type
372/// enum. For example, SignedInt -> getIntAlign().
373unsigned TargetInfo::getTypeAlign(IntType T) const {
374 switch (T) {
375 default: llvm_unreachable("not an integer!");
376 case SignedChar:
377 case UnsignedChar: return getCharAlign();
378 case SignedShort:
379 case UnsignedShort: return getShortAlign();
380 case SignedInt:
381 case UnsignedInt: return getIntAlign();
382 case SignedLong:
383 case UnsignedLong: return getLongAlign();
384 case SignedLongLong:
385 case UnsignedLongLong: return getLongLongAlign();
386 };
387}
388
389/// isTypeSigned - Return whether an integer types is signed. Returns true if
390/// the type is signed; false otherwise.
391bool TargetInfo::isTypeSigned(IntType T) {
392 switch (T) {
393 default: llvm_unreachable("not an integer!");
394 case SignedChar:
395 case SignedShort:
396 case SignedInt:
397 case SignedLong:
398 case SignedLongLong:
399 return true;
400 case UnsignedChar:
401 case UnsignedShort:
402 case UnsignedInt:
403 case UnsignedLong:
404 case UnsignedLongLong:
405 return false;
406 };
407}
408
409/// adjust - Set forced language options.
410/// Apply changes to the target information with respect to certain
411/// language options which change the target configuration and adjust
412/// the language based on the target options where applicable.
413void TargetInfo::adjust(DiagnosticsEngine &Diags, LangOptions &Opts) {
414 if (Opts.NoBitFieldTypeAlign)
415 UseBitFieldTypeAlignment = false;
416
417 switch (Opts.WCharSize) {
418 default: llvm_unreachable("invalid wchar_t width");
419 case 0: break;
420 case 1: WCharType = Opts.WCharIsSigned ? SignedChar : UnsignedChar; break;
421 case 2: WCharType = Opts.WCharIsSigned ? SignedShort : UnsignedShort; break;
422 case 4: WCharType = Opts.WCharIsSigned ? SignedInt : UnsignedInt; break;
423 }
424
425 if (Opts.AlignDouble) {
426 DoubleAlign = LongLongAlign = 64;
427 LongDoubleAlign = 64;
428 }
429
430 // HLSL explicitly defines the sizes and formats of some data types, and we
431 // need to conform to those regardless of what architecture you are targeting.
432 if (Opts.HLSL) {
433 BoolWidth = BoolAlign = 32;
434 LongWidth = LongAlign = 64;
435 if (!Opts.NativeHalfType) {
436 HalfFormat = &llvm::APFloat::IEEEsingle();
437 HalfWidth = HalfAlign = 32;
438 }
439 }
440
441 if (Opts.OpenCL) {
442 // OpenCL C requires specific widths for types, irrespective of
443 // what these normally are for the target.
444 // We also define long long and long double here, although the
445 // OpenCL standard only mentions these as "reserved".
446 ShortWidth = ShortAlign = 16;
447 IntWidth = IntAlign = 32;
448 LongWidth = LongAlign = 64;
449 LongLongWidth = LongLongAlign = 128;
450 HalfWidth = HalfAlign = 16;
451 FloatWidth = FloatAlign = 32;
452
453 // Embedded 32-bit targets (OpenCL EP) might have double C type
454 // defined as float. Let's not override this as it might lead
455 // to generating illegal code that uses 64bit doubles.
456 if (DoubleWidth != FloatWidth) {
457 DoubleWidth = DoubleAlign = 64;
458 DoubleFormat = &llvm::APFloat::IEEEdouble();
459 }
460 LongDoubleWidth = LongDoubleAlign = 128;
461
462 unsigned MaxPointerWidth = getMaxPointerWidth();
463 assert(MaxPointerWidth == 32 || MaxPointerWidth == 64);
464 bool Is32BitArch = MaxPointerWidth == 32;
465 SizeType = Is32BitArch ? UnsignedInt : UnsignedLong;
466 PtrDiffType = Is32BitArch ? SignedInt : SignedLong;
467 IntPtrType = Is32BitArch ? SignedInt : SignedLong;
468
469 IntMaxType = SignedLongLong;
470 Int64Type = SignedLong;
471
472 HalfFormat = &llvm::APFloat::IEEEhalf();
473 FloatFormat = &llvm::APFloat::IEEEsingle();
474 LongDoubleFormat = &llvm::APFloat::IEEEquad();
475
476 // OpenCL C v3.0 s6.7.5 - The generic address space requires support for
477 // OpenCL C 2.0 or OpenCL C 3.0 with the __opencl_c_generic_address_space
478 // feature
479 // OpenCL C v3.0 s6.2.1 - OpenCL pipes require support of OpenCL C 2.0
480 // or later and __opencl_c_pipes feature
481 // FIXME: These language options are also defined in setLangDefaults()
482 // for OpenCL C 2.0 but with no access to target capabilities. Target
483 // should be immutable once created and thus these language options need
484 // to be defined only once.
485 if (Opts.getOpenCLCompatibleVersion() == 300) {
486 const auto &OpenCLFeaturesMap = getSupportedOpenCLOpts();
487 Opts.OpenCLGenericAddressSpace = hasFeatureEnabled(
488 Features: OpenCLFeaturesMap, Name: "__opencl_c_generic_address_space");
489 Opts.OpenCLPipes =
490 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_pipes");
491 Opts.Blocks =
492 hasFeatureEnabled(Features: OpenCLFeaturesMap, Name: "__opencl_c_device_enqueue");
493 }
494 }
495
496 if (Opts.DoubleSize) {
497 if (Opts.DoubleSize == 32) {
498 DoubleWidth = 32;
499 LongDoubleWidth = 32;
500 DoubleFormat = &llvm::APFloat::IEEEsingle();
501 LongDoubleFormat = &llvm::APFloat::IEEEsingle();
502 } else if (Opts.DoubleSize == 64) {
503 DoubleWidth = 64;
504 LongDoubleWidth = 64;
505 DoubleFormat = &llvm::APFloat::IEEEdouble();
506 LongDoubleFormat = &llvm::APFloat::IEEEdouble();
507 }
508 }
509
510 if (Opts.LongDoubleSize) {
511 if (Opts.LongDoubleSize == DoubleWidth) {
512 LongDoubleWidth = DoubleWidth;
513 LongDoubleAlign = DoubleAlign;
514 LongDoubleFormat = DoubleFormat;
515 } else if (Opts.LongDoubleSize == 128) {
516 LongDoubleWidth = LongDoubleAlign = 128;
517 LongDoubleFormat = &llvm::APFloat::IEEEquad();
518 } else if (Opts.LongDoubleSize == 80) {
519 LongDoubleFormat = &llvm::APFloat::x87DoubleExtended();
520 if (getTriple().isWindowsMSVCEnvironment()) {
521 LongDoubleWidth = 128;
522 LongDoubleAlign = 128;
523 } else { // Linux
524 if (getTriple().getArch() == llvm::Triple::x86) {
525 LongDoubleWidth = 96;
526 LongDoubleAlign = 32;
527 } else {
528 LongDoubleWidth = 128;
529 LongDoubleAlign = 128;
530 }
531 }
532 }
533 }
534
535 if (Opts.NewAlignOverride)
536 NewAlign = Opts.NewAlignOverride * getCharWidth();
537
538 // Each unsigned fixed point type has the same number of fractional bits as
539 // its corresponding signed type.
540 PaddingOnUnsignedFixedPoint |= Opts.PaddingOnUnsignedFixedPoint;
541 CheckFixedPointBits();
542
543 if (Opts.ProtectParens && !checkArithmeticFenceSupported()) {
544 Diags.Report(DiagID: diag::err_opt_not_valid_on_target) << "-fprotect-parens";
545 Opts.ProtectParens = false;
546 }
547
548 if (Opts.MaxBitIntWidth)
549 MaxBitIntWidth = static_cast<unsigned>(Opts.MaxBitIntWidth);
550
551 if (Opts.FakeAddressSpaceMap)
552 AddrSpaceMap = &FakeAddrSpaceMap;
553}
554
555bool TargetInfo::initFeatureMap(
556 llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
557 const std::vector<std::string> &FeatureVec) const {
558 for (StringRef Name : FeatureVec) {
559 if (Name.empty())
560 continue;
561 // Apply the feature via the target.
562 if (Name[0] != '+' && Name[0] != '-')
563 Diags.Report(DiagID: diag::warn_fe_backend_invalid_feature_flag) << Name;
564 else
565 setFeatureEnabled(Features, Name: Name.substr(Start: 1), Enabled: Name[0] == '+');
566 }
567 return true;
568}
569
570ParsedTargetAttr TargetInfo::parseTargetAttr(StringRef Features) const {
571 ParsedTargetAttr Ret;
572 if (Features == "default")
573 return Ret;
574 SmallVector<StringRef, 1> AttrFeatures;
575 Features.split(A&: AttrFeatures, Separator: ",");
576
577 // Grab the various features and prepend a "+" to turn on the feature to
578 // the backend and add them to our existing set of features.
579 for (auto &Feature : AttrFeatures) {
580 // Go ahead and trim whitespace rather than either erroring or
581 // accepting it weirdly.
582 Feature = Feature.trim();
583
584 // TODO: Support the fpmath option. It will require checking
585 // overall feature validity for the function with the rest of the
586 // attributes on the function.
587 if (Feature.starts_with(Prefix: "fpmath="))
588 continue;
589
590 if (Feature.starts_with(Prefix: "branch-protection=")) {
591 Ret.BranchProtection = Feature.split(Separator: '=').second.trim();
592 continue;
593 }
594
595 // While we're here iterating check for a different target cpu.
596 if (Feature.starts_with(Prefix: "arch=")) {
597 if (!Ret.CPU.empty())
598 Ret.Duplicate = "arch=";
599 else
600 Ret.CPU = Feature.split(Separator: "=").second.trim();
601 } else if (Feature.starts_with(Prefix: "tune=")) {
602 if (!Ret.Tune.empty())
603 Ret.Duplicate = "tune=";
604 else
605 Ret.Tune = Feature.split(Separator: "=").second.trim();
606 } else if (Feature.starts_with(Prefix: "no-"))
607 Ret.Features.push_back(x: "-" + Feature.split(Separator: "-").second.str());
608 else
609 Ret.Features.push_back(x: "+" + Feature.str());
610 }
611 return Ret;
612}
613
614TargetInfo::CallingConvKind
615TargetInfo::getCallingConvKind(bool ClangABICompat4) const {
616 if (getCXXABI() != TargetCXXABI::Microsoft &&
617 (ClangABICompat4 || getTriple().isPS4()))
618 return CCK_ClangABI4OrPS4;
619 return CCK_Default;
620}
621
622bool TargetInfo::areDefaultedSMFStillPOD(const LangOptions &LangOpts) const {
623 return LangOpts.getClangABICompat() > LangOptions::ClangABI::Ver15;
624}
625
626LangAS TargetInfo::getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const {
627 switch (TK) {
628 case OCLTK_Image:
629 case OCLTK_Pipe:
630 return LangAS::opencl_global;
631
632 case OCLTK_Sampler:
633 return LangAS::opencl_constant;
634
635 default:
636 return LangAS::Default;
637 }
638}
639
640//===----------------------------------------------------------------------===//
641
642
643static StringRef removeGCCRegisterPrefix(StringRef Name) {
644 if (Name[0] == '%' || Name[0] == '#')
645 Name = Name.substr(Start: 1);
646
647 return Name;
648}
649
650/// isValidClobber - Returns whether the passed in string is
651/// a valid clobber in an inline asm statement. This is used by
652/// Sema.
653bool TargetInfo::isValidClobber(StringRef Name) const {
654 return (isValidGCCRegisterName(Name) || Name == "memory" || Name == "cc" ||
655 Name == "unwind");
656}
657
658/// isValidGCCRegisterName - Returns whether the passed in string
659/// is a valid register name according to GCC. This is used by Sema for
660/// inline asm statements.
661bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
662 if (Name.empty())
663 return false;
664
665 // Get rid of any register prefix.
666 Name = removeGCCRegisterPrefix(Name);
667 if (Name.empty())
668 return false;
669
670 ArrayRef<const char *> Names = getGCCRegNames();
671
672 // If we have a number it maps to an entry in the register name array.
673 if (isDigit(c: Name[0])) {
674 unsigned n;
675 if (!Name.getAsInteger(Radix: 0, Result&: n))
676 return n < Names.size();
677 }
678
679 // Check register names.
680 if (llvm::is_contained(Range&: Names, Element: Name))
681 return true;
682
683 // Check any additional names that we have.
684 for (const AddlRegName &ARN : getGCCAddlRegNames())
685 for (const char *AN : ARN.Names) {
686 if (!AN)
687 break;
688 // Make sure the register that the additional name is for is within
689 // the bounds of the register names from above.
690 if (AN == Name && ARN.RegNum < Names.size())
691 return true;
692 }
693
694 // Now check aliases.
695 for (const GCCRegAlias &GRA : getGCCRegAliases())
696 for (const char *A : GRA.Aliases) {
697 if (!A)
698 break;
699 if (A == Name)
700 return true;
701 }
702
703 return false;
704}
705
706StringRef TargetInfo::getNormalizedGCCRegisterName(StringRef Name,
707 bool ReturnCanonical) const {
708 assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
709
710 // Get rid of any register prefix.
711 Name = removeGCCRegisterPrefix(Name);
712
713 ArrayRef<const char *> Names = getGCCRegNames();
714
715 // First, check if we have a number.
716 if (isDigit(c: Name[0])) {
717 unsigned n;
718 if (!Name.getAsInteger(Radix: 0, Result&: n)) {
719 assert(n < Names.size() && "Out of bounds register number!");
720 return Names[n];
721 }
722 }
723
724 // Check any additional names that we have.
725 for (const AddlRegName &ARN : getGCCAddlRegNames())
726 for (const char *AN : ARN.Names) {
727 if (!AN)
728 break;
729 // Make sure the register that the additional name is for is within
730 // the bounds of the register names from above.
731 if (AN == Name && ARN.RegNum < Names.size())
732 return ReturnCanonical ? Names[ARN.RegNum] : Name;
733 }
734
735 // Now check aliases.
736 for (const GCCRegAlias &RA : getGCCRegAliases())
737 for (const char *A : RA.Aliases) {
738 if (!A)
739 break;
740 if (A == Name)
741 return RA.Register;
742 }
743
744 return Name;
745}
746
747bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
748 const char *Name = Info.getConstraintStr().c_str();
749 // An output constraint must start with '=' or '+'
750 if (*Name != '=' && *Name != '+')
751 return false;
752
753 if (*Name == '+')
754 Info.setIsReadWrite();
755
756 Name++;
757 while (*Name) {
758 switch (*Name) {
759 default:
760 if (!validateAsmConstraint(Name, info&: Info)) {
761 // FIXME: We temporarily return false
762 // so we can add more constraints as we hit it.
763 // Eventually, an unknown constraint should just be treated as 'g'.
764 return false;
765 }
766 break;
767 case '&': // early clobber.
768 Info.setEarlyClobber();
769 break;
770 case '%': // commutative.
771 // FIXME: Check that there is a another register after this one.
772 break;
773 case 'r': // general register.
774 Info.setAllowsRegister();
775 break;
776 case 'm': // memory operand.
777 case 'o': // offsetable memory operand.
778 case 'V': // non-offsetable memory operand.
779 case '<': // autodecrement memory operand.
780 case '>': // autoincrement memory operand.
781 Info.setAllowsMemory();
782 break;
783 case 'g': // general register, memory operand or immediate integer.
784 case 'X': // any operand.
785 Info.setAllowsRegister();
786 Info.setAllowsMemory();
787 break;
788 case ',': // multiple alternative constraint. Pass it.
789 // Handle additional optional '=' or '+' modifiers.
790 if (Name[1] == '=' || Name[1] == '+')
791 Name++;
792 break;
793 case '#': // Ignore as constraint.
794 while (Name[1] && Name[1] != ',')
795 Name++;
796 break;
797 case '?': // Disparage slightly code.
798 case '!': // Disparage severely.
799 case '*': // Ignore for choosing register preferences.
800 case 'i': // Ignore i,n,E,F as output constraints (match from the other
801 // chars)
802 case 'n':
803 case 'E':
804 case 'F':
805 break; // Pass them.
806 }
807
808 Name++;
809 }
810
811 // Early clobber with a read-write constraint which doesn't permit registers
812 // is invalid.
813 if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
814 return false;
815
816 // If a constraint allows neither memory nor register operands it contains
817 // only modifiers. Reject it.
818 return Info.allowsMemory() || Info.allowsRegister();
819}
820
821bool TargetInfo::resolveSymbolicName(const char *&Name,
822 ArrayRef<ConstraintInfo> OutputConstraints,
823 unsigned &Index) const {
824 assert(*Name == '[' && "Symbolic name did not start with '['");
825 Name++;
826 const char *Start = Name;
827 while (*Name && *Name != ']')
828 Name++;
829
830 if (!*Name) {
831 // Missing ']'
832 return false;
833 }
834
835 std::string SymbolicName(Start, Name - Start);
836
837 for (Index = 0; Index != OutputConstraints.size(); ++Index)
838 if (SymbolicName == OutputConstraints[Index].getName())
839 return true;
840
841 return false;
842}
843
844bool TargetInfo::validateInputConstraint(
845 MutableArrayRef<ConstraintInfo> OutputConstraints,
846 ConstraintInfo &Info) const {
847 const char *Name = Info.ConstraintStr.c_str();
848
849 if (!*Name)
850 return false;
851
852 while (*Name) {
853 switch (*Name) {
854 default:
855 // Check if we have a matching constraint
856 if (*Name >= '0' && *Name <= '9') {
857 const char *DigitStart = Name;
858 while (Name[1] >= '0' && Name[1] <= '9')
859 Name++;
860 const char *DigitEnd = Name;
861 unsigned i;
862 if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
863 .getAsInteger(Radix: 10, Result&: i))
864 return false;
865
866 // Check if matching constraint is out of bounds.
867 if (i >= OutputConstraints.size()) return false;
868
869 // A number must refer to an output only operand.
870 if (OutputConstraints[i].isReadWrite())
871 return false;
872
873 // If the constraint is already tied, it must be tied to the
874 // same operand referenced to by the number.
875 if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
876 return false;
877
878 // The constraint should have the same info as the respective
879 // output constraint.
880 Info.setTiedOperand(N: i, Output&: OutputConstraints[i]);
881 } else if (!validateAsmConstraint(Name, info&: Info)) {
882 // FIXME: This error return is in place temporarily so we can
883 // add more constraints as we hit it. Eventually, an unknown
884 // constraint should just be treated as 'g'.
885 return false;
886 }
887 break;
888 case '[': {
889 unsigned Index = 0;
890 if (!resolveSymbolicName(Name, OutputConstraints, Index))
891 return false;
892
893 // If the constraint is already tied, it must be tied to the
894 // same operand referenced to by the number.
895 if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
896 return false;
897
898 // A number must refer to an output only operand.
899 if (OutputConstraints[Index].isReadWrite())
900 return false;
901
902 Info.setTiedOperand(N: Index, Output&: OutputConstraints[Index]);
903 break;
904 }
905 case '%': // commutative
906 // FIXME: Fail if % is used with the last operand.
907 break;
908 case 'i': // immediate integer.
909 break;
910 case 'n': // immediate integer with a known value.
911 Info.setRequiresImmediate();
912 break;
913 case 'I': // Various constant constraints with target-specific meanings.
914 case 'J':
915 case 'K':
916 case 'L':
917 case 'M':
918 case 'N':
919 case 'O':
920 case 'P':
921 if (!validateAsmConstraint(Name, info&: Info))
922 return false;
923 break;
924 case 'r': // general register.
925 Info.setAllowsRegister();
926 break;
927 case 'm': // memory operand.
928 case 'o': // offsettable memory operand.
929 case 'V': // non-offsettable memory operand.
930 case '<': // autodecrement memory operand.
931 case '>': // autoincrement memory operand.
932 Info.setAllowsMemory();
933 break;
934 case 'g': // general register, memory operand or immediate integer.
935 case 'X': // any operand.
936 Info.setAllowsRegister();
937 Info.setAllowsMemory();
938 break;
939 case 'E': // immediate floating point.
940 case 'F': // immediate floating point.
941 case 'p': // address operand.
942 break;
943 case ',': // multiple alternative constraint. Ignore comma.
944 break;
945 case '#': // Ignore as constraint.
946 while (Name[1] && Name[1] != ',')
947 Name++;
948 break;
949 case '?': // Disparage slightly code.
950 case '!': // Disparage severely.
951 case '*': // Ignore for choosing register preferences.
952 break; // Pass them.
953 }
954
955 Name++;
956 }
957
958 return true;
959}
960
961bool TargetInfo::validatePointerAuthKey(const llvm::APSInt &value) const {
962 return false;
963}
964
965void TargetInfo::CheckFixedPointBits() const {
966 // Check that the number of fractional and integral bits (and maybe sign) can
967 // fit into the bits given for a fixed point type.
968 assert(ShortAccumScale + getShortAccumIBits() + 1 <= ShortAccumWidth);
969 assert(AccumScale + getAccumIBits() + 1 <= AccumWidth);
970 assert(LongAccumScale + getLongAccumIBits() + 1 <= LongAccumWidth);
971 assert(getUnsignedShortAccumScale() + getUnsignedShortAccumIBits() <=
972 ShortAccumWidth);
973 assert(getUnsignedAccumScale() + getUnsignedAccumIBits() <= AccumWidth);
974 assert(getUnsignedLongAccumScale() + getUnsignedLongAccumIBits() <=
975 LongAccumWidth);
976
977 assert(getShortFractScale() + 1 <= ShortFractWidth);
978 assert(getFractScale() + 1 <= FractWidth);
979 assert(getLongFractScale() + 1 <= LongFractWidth);
980 assert(getUnsignedShortFractScale() <= ShortFractWidth);
981 assert(getUnsignedFractScale() <= FractWidth);
982 assert(getUnsignedLongFractScale() <= LongFractWidth);
983
984 // Each unsigned fract type has either the same number of fractional bits
985 // as, or one more fractional bit than, its corresponding signed fract type.
986 assert(getShortFractScale() == getUnsignedShortFractScale() ||
987 getShortFractScale() == getUnsignedShortFractScale() - 1);
988 assert(getFractScale() == getUnsignedFractScale() ||
989 getFractScale() == getUnsignedFractScale() - 1);
990 assert(getLongFractScale() == getUnsignedLongFractScale() ||
991 getLongFractScale() == getUnsignedLongFractScale() - 1);
992
993 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
994 // fractional bits is nondecreasing for each of the following sets of
995 // fixed-point types:
996 // - signed fract types
997 // - unsigned fract types
998 // - signed accum types
999 // - unsigned accum types.
1000 assert(getLongFractScale() >= getFractScale() &&
1001 getFractScale() >= getShortFractScale());
1002 assert(getUnsignedLongFractScale() >= getUnsignedFractScale() &&
1003 getUnsignedFractScale() >= getUnsignedShortFractScale());
1004 assert(LongAccumScale >= AccumScale && AccumScale >= ShortAccumScale);
1005 assert(getUnsignedLongAccumScale() >= getUnsignedAccumScale() &&
1006 getUnsignedAccumScale() >= getUnsignedShortAccumScale());
1007
1008 // When arranged in order of increasing rank (see 6.3.1.3a), the number of
1009 // integral bits is nondecreasing for each of the following sets of
1010 // fixed-point types:
1011 // - signed accum types
1012 // - unsigned accum types
1013 assert(getLongAccumIBits() >= getAccumIBits() &&
1014 getAccumIBits() >= getShortAccumIBits());
1015 assert(getUnsignedLongAccumIBits() >= getUnsignedAccumIBits() &&
1016 getUnsignedAccumIBits() >= getUnsignedShortAccumIBits());
1017
1018 // Each signed accum type has at least as many integral bits as its
1019 // corresponding unsigned accum type.
1020 assert(getShortAccumIBits() >= getUnsignedShortAccumIBits());
1021 assert(getAccumIBits() >= getUnsignedAccumIBits());
1022 assert(getLongAccumIBits() >= getUnsignedLongAccumIBits());
1023}
1024
1025void TargetInfo::copyAuxTarget(const TargetInfo *Aux) {
1026 auto *Target = static_cast<TransferrableTargetInfo*>(this);
1027 auto *Src = static_cast<const TransferrableTargetInfo*>(Aux);
1028 *Target = *Src;
1029}
1030