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