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