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