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