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