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