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.
TargetInfo(const llvm::Triple & T)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.
~TargetInfo()151 TargetInfo::~TargetInfo() {}
152 
resetDataLayout(StringRef DL,const char * ULP)153 void TargetInfo::resetDataLayout(StringRef DL, const char *ULP) {
154   DataLayoutString = DL.str();
155   UserLabelPrefix = ULP;
156 }
157 
158 bool
checkCFProtectionBranchSupported(DiagnosticsEngine & Diags) const159 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
checkCFProtectionReturnSupported(DiagnosticsEngine & Diags) const165 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".
getTypeName(IntType T)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".
getTypeConstantSuffix(IntType T) const190 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 
getTypeFormatModifier(IntType T)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().
getTypeWidth(IntType T) const233 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 
getIntTypeByWidth(unsigned BitWidth,bool IsSigned) const249 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 
getLeastIntTypeByWidth(unsigned BitWidth,bool IsSigned) const264 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 
getRealTypeByWidth(unsigned BitWidth,bool ExplicitIEEE) const279 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().
getTypeAlign(IntType T) const309 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.
isTypeSigned(IntType T)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.
adjust(LangOptions & Opts)349 void TargetInfo::adjust(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 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeatureVec) const435 bool TargetInfo::initFeatureMap(
436     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
437     const std::vector<std::string> &FeatureVec) const {
438   for (const auto &F : FeatureVec) {
439     StringRef Name = F;
440     // Apply the feature via the target.
441     bool Enabled = Name[0] == '+';
442     setFeatureEnabled(Features, Name.substr(1), Enabled);
443   }
444   return true;
445 }
446 
447 TargetInfo::CallingConvKind
getCallingConvKind(bool ClangABICompat4) const448 TargetInfo::getCallingConvKind(bool ClangABICompat4) const {
449   if (getCXXABI() != TargetCXXABI::Microsoft &&
450       (ClangABICompat4 || getTriple().getOS() == llvm::Triple::PS4))
451     return CCK_ClangABI4OrPS4;
452   return CCK_Default;
453 }
454 
getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const455 LangAS TargetInfo::getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const {
456   switch (TK) {
457   case OCLTK_Image:
458   case OCLTK_Pipe:
459     return LangAS::opencl_global;
460 
461   case OCLTK_Sampler:
462     return LangAS::opencl_constant;
463 
464   default:
465     return LangAS::Default;
466   }
467 }
468 
469 //===----------------------------------------------------------------------===//
470 
471 
removeGCCRegisterPrefix(StringRef Name)472 static StringRef removeGCCRegisterPrefix(StringRef Name) {
473   if (Name[0] == '%' || Name[0] == '#')
474     Name = Name.substr(1);
475 
476   return Name;
477 }
478 
479 /// isValidClobber - Returns whether the passed in string is
480 /// a valid clobber in an inline asm statement. This is used by
481 /// Sema.
isValidClobber(StringRef Name) const482 bool TargetInfo::isValidClobber(StringRef Name) const {
483   return (isValidGCCRegisterName(Name) || Name == "memory" || Name == "cc" ||
484           Name == "unwind");
485 }
486 
487 /// isValidGCCRegisterName - Returns whether the passed in string
488 /// is a valid register name according to GCC. This is used by Sema for
489 /// inline asm statements.
isValidGCCRegisterName(StringRef Name) const490 bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
491   if (Name.empty())
492     return false;
493 
494   // Get rid of any register prefix.
495   Name = removeGCCRegisterPrefix(Name);
496   if (Name.empty())
497     return false;
498 
499   ArrayRef<const char *> Names = getGCCRegNames();
500 
501   // If we have a number it maps to an entry in the register name array.
502   if (isDigit(Name[0])) {
503     unsigned n;
504     if (!Name.getAsInteger(0, n))
505       return n < Names.size();
506   }
507 
508   // Check register names.
509   if (llvm::is_contained(Names, Name))
510     return true;
511 
512   // Check any additional names that we have.
513   for (const AddlRegName &ARN : getGCCAddlRegNames())
514     for (const char *AN : ARN.Names) {
515       if (!AN)
516         break;
517       // Make sure the register that the additional name is for is within
518       // the bounds of the register names from above.
519       if (AN == Name && ARN.RegNum < Names.size())
520         return true;
521     }
522 
523   // Now check aliases.
524   for (const GCCRegAlias &GRA : getGCCRegAliases())
525     for (const char *A : GRA.Aliases) {
526       if (!A)
527         break;
528       if (A == Name)
529         return true;
530     }
531 
532   return false;
533 }
534 
getNormalizedGCCRegisterName(StringRef Name,bool ReturnCanonical) const535 StringRef TargetInfo::getNormalizedGCCRegisterName(StringRef Name,
536                                                    bool ReturnCanonical) const {
537   assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
538 
539   // Get rid of any register prefix.
540   Name = removeGCCRegisterPrefix(Name);
541 
542   ArrayRef<const char *> Names = getGCCRegNames();
543 
544   // First, check if we have a number.
545   if (isDigit(Name[0])) {
546     unsigned n;
547     if (!Name.getAsInteger(0, n)) {
548       assert(n < Names.size() && "Out of bounds register number!");
549       return Names[n];
550     }
551   }
552 
553   // Check any additional names that we have.
554   for (const AddlRegName &ARN : getGCCAddlRegNames())
555     for (const char *AN : ARN.Names) {
556       if (!AN)
557         break;
558       // Make sure the register that the additional name is for is within
559       // the bounds of the register names from above.
560       if (AN == Name && ARN.RegNum < Names.size())
561         return ReturnCanonical ? Names[ARN.RegNum] : Name;
562     }
563 
564   // Now check aliases.
565   for (const GCCRegAlias &RA : getGCCRegAliases())
566     for (const char *A : RA.Aliases) {
567       if (!A)
568         break;
569       if (A == Name)
570         return RA.Register;
571     }
572 
573   return Name;
574 }
575 
validateOutputConstraint(ConstraintInfo & Info) const576 bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
577   const char *Name = Info.getConstraintStr().c_str();
578   // An output constraint must start with '=' or '+'
579   if (*Name != '=' && *Name != '+')
580     return false;
581 
582   if (*Name == '+')
583     Info.setIsReadWrite();
584 
585   Name++;
586   while (*Name) {
587     switch (*Name) {
588     default:
589       if (!validateAsmConstraint(Name, Info)) {
590         // FIXME: We temporarily return false
591         // so we can add more constraints as we hit it.
592         // Eventually, an unknown constraint should just be treated as 'g'.
593         return false;
594       }
595       break;
596     case '&': // early clobber.
597       Info.setEarlyClobber();
598       break;
599     case '%': // commutative.
600       // FIXME: Check that there is a another register after this one.
601       break;
602     case 'r': // general register.
603       Info.setAllowsRegister();
604       break;
605     case 'm': // memory operand.
606     case 'o': // offsetable memory operand.
607     case 'V': // non-offsetable memory operand.
608     case '<': // autodecrement memory operand.
609     case '>': // autoincrement memory operand.
610       Info.setAllowsMemory();
611       break;
612     case 'g': // general register, memory operand or immediate integer.
613     case 'X': // any operand.
614       Info.setAllowsRegister();
615       Info.setAllowsMemory();
616       break;
617     case ',': // multiple alternative constraint.  Pass it.
618       // Handle additional optional '=' or '+' modifiers.
619       if (Name[1] == '=' || Name[1] == '+')
620         Name++;
621       break;
622     case '#': // Ignore as constraint.
623       while (Name[1] && Name[1] != ',')
624         Name++;
625       break;
626     case '?': // Disparage slightly code.
627     case '!': // Disparage severely.
628     case '*': // Ignore for choosing register preferences.
629     case 'i': // Ignore i,n,E,F as output constraints (match from the other
630               // chars)
631     case 'n':
632     case 'E':
633     case 'F':
634       break;  // Pass them.
635     }
636 
637     Name++;
638   }
639 
640   // Early clobber with a read-write constraint which doesn't permit registers
641   // is invalid.
642   if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
643     return false;
644 
645   // If a constraint allows neither memory nor register operands it contains
646   // only modifiers. Reject it.
647   return Info.allowsMemory() || Info.allowsRegister();
648 }
649 
resolveSymbolicName(const char * & Name,ArrayRef<ConstraintInfo> OutputConstraints,unsigned & Index) const650 bool TargetInfo::resolveSymbolicName(const char *&Name,
651                                      ArrayRef<ConstraintInfo> OutputConstraints,
652                                      unsigned &Index) const {
653   assert(*Name == '[' && "Symbolic name did not start with '['");
654   Name++;
655   const char *Start = Name;
656   while (*Name && *Name != ']')
657     Name++;
658 
659   if (!*Name) {
660     // Missing ']'
661     return false;
662   }
663 
664   std::string SymbolicName(Start, Name - Start);
665 
666   for (Index = 0; Index != OutputConstraints.size(); ++Index)
667     if (SymbolicName == OutputConstraints[Index].getName())
668       return true;
669 
670   return false;
671 }
672 
validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,ConstraintInfo & Info) const673 bool TargetInfo::validateInputConstraint(
674                               MutableArrayRef<ConstraintInfo> OutputConstraints,
675                               ConstraintInfo &Info) const {
676   const char *Name = Info.ConstraintStr.c_str();
677 
678   if (!*Name)
679     return false;
680 
681   while (*Name) {
682     switch (*Name) {
683     default:
684       // Check if we have a matching constraint
685       if (*Name >= '0' && *Name <= '9') {
686         const char *DigitStart = Name;
687         while (Name[1] >= '0' && Name[1] <= '9')
688           Name++;
689         const char *DigitEnd = Name;
690         unsigned i;
691         if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
692                 .getAsInteger(10, i))
693           return false;
694 
695         // Check if matching constraint is out of bounds.
696         if (i >= OutputConstraints.size()) return false;
697 
698         // A number must refer to an output only operand.
699         if (OutputConstraints[i].isReadWrite())
700           return false;
701 
702         // If the constraint is already tied, it must be tied to the
703         // same operand referenced to by the number.
704         if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
705           return false;
706 
707         // The constraint should have the same info as the respective
708         // output constraint.
709         Info.setTiedOperand(i, OutputConstraints[i]);
710       } else if (!validateAsmConstraint(Name, Info)) {
711         // FIXME: This error return is in place temporarily so we can
712         // add more constraints as we hit it.  Eventually, an unknown
713         // constraint should just be treated as 'g'.
714         return false;
715       }
716       break;
717     case '[': {
718       unsigned Index = 0;
719       if (!resolveSymbolicName(Name, OutputConstraints, Index))
720         return false;
721 
722       // If the constraint is already tied, it must be tied to the
723       // same operand referenced to by the number.
724       if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
725         return false;
726 
727       // A number must refer to an output only operand.
728       if (OutputConstraints[Index].isReadWrite())
729         return false;
730 
731       Info.setTiedOperand(Index, OutputConstraints[Index]);
732       break;
733     }
734     case '%': // commutative
735       // FIXME: Fail if % is used with the last operand.
736       break;
737     case 'i': // immediate integer.
738       break;
739     case 'n': // immediate integer with a known value.
740       Info.setRequiresImmediate();
741       break;
742     case 'I':  // Various constant constraints with target-specific meanings.
743     case 'J':
744     case 'K':
745     case 'L':
746     case 'M':
747     case 'N':
748     case 'O':
749     case 'P':
750       if (!validateAsmConstraint(Name, Info))
751         return false;
752       break;
753     case 'r': // general register.
754       Info.setAllowsRegister();
755       break;
756     case 'm': // memory operand.
757     case 'o': // offsettable memory operand.
758     case 'V': // non-offsettable memory operand.
759     case '<': // autodecrement memory operand.
760     case '>': // autoincrement memory operand.
761       Info.setAllowsMemory();
762       break;
763     case 'g': // general register, memory operand or immediate integer.
764     case 'X': // any operand.
765       Info.setAllowsRegister();
766       Info.setAllowsMemory();
767       break;
768     case 'E': // immediate floating point.
769     case 'F': // immediate floating point.
770     case 'p': // address operand.
771       break;
772     case ',': // multiple alternative constraint.  Ignore comma.
773       break;
774     case '#': // Ignore as constraint.
775       while (Name[1] && Name[1] != ',')
776         Name++;
777       break;
778     case '?': // Disparage slightly code.
779     case '!': // Disparage severely.
780     case '*': // Ignore for choosing register preferences.
781       break;  // Pass them.
782     }
783 
784     Name++;
785   }
786 
787   return true;
788 }
789 
CheckFixedPointBits() const790 void TargetInfo::CheckFixedPointBits() const {
791   // Check that the number of fractional and integral bits (and maybe sign) can
792   // fit into the bits given for a fixed point type.
793   assert(ShortAccumScale + getShortAccumIBits() + 1 <= ShortAccumWidth);
794   assert(AccumScale + getAccumIBits() + 1 <= AccumWidth);
795   assert(LongAccumScale + getLongAccumIBits() + 1 <= LongAccumWidth);
796   assert(getUnsignedShortAccumScale() + getUnsignedShortAccumIBits() <=
797          ShortAccumWidth);
798   assert(getUnsignedAccumScale() + getUnsignedAccumIBits() <= AccumWidth);
799   assert(getUnsignedLongAccumScale() + getUnsignedLongAccumIBits() <=
800          LongAccumWidth);
801 
802   assert(getShortFractScale() + 1 <= ShortFractWidth);
803   assert(getFractScale() + 1 <= FractWidth);
804   assert(getLongFractScale() + 1 <= LongFractWidth);
805   assert(getUnsignedShortFractScale() <= ShortFractWidth);
806   assert(getUnsignedFractScale() <= FractWidth);
807   assert(getUnsignedLongFractScale() <= LongFractWidth);
808 
809   // Each unsigned fract type has either the same number of fractional bits
810   // as, or one more fractional bit than, its corresponding signed fract type.
811   assert(getShortFractScale() == getUnsignedShortFractScale() ||
812          getShortFractScale() == getUnsignedShortFractScale() - 1);
813   assert(getFractScale() == getUnsignedFractScale() ||
814          getFractScale() == getUnsignedFractScale() - 1);
815   assert(getLongFractScale() == getUnsignedLongFractScale() ||
816          getLongFractScale() == getUnsignedLongFractScale() - 1);
817 
818   // When arranged in order of increasing rank (see 6.3.1.3a), the number of
819   // fractional bits is nondecreasing for each of the following sets of
820   // fixed-point types:
821   // - signed fract types
822   // - unsigned fract types
823   // - signed accum types
824   // - unsigned accum types.
825   assert(getLongFractScale() >= getFractScale() &&
826          getFractScale() >= getShortFractScale());
827   assert(getUnsignedLongFractScale() >= getUnsignedFractScale() &&
828          getUnsignedFractScale() >= getUnsignedShortFractScale());
829   assert(LongAccumScale >= AccumScale && AccumScale >= ShortAccumScale);
830   assert(getUnsignedLongAccumScale() >= getUnsignedAccumScale() &&
831          getUnsignedAccumScale() >= getUnsignedShortAccumScale());
832 
833   // When arranged in order of increasing rank (see 6.3.1.3a), the number of
834   // integral bits is nondecreasing for each of the following sets of
835   // fixed-point types:
836   // - signed accum types
837   // - unsigned accum types
838   assert(getLongAccumIBits() >= getAccumIBits() &&
839          getAccumIBits() >= getShortAccumIBits());
840   assert(getUnsignedLongAccumIBits() >= getUnsignedAccumIBits() &&
841          getUnsignedAccumIBits() >= getUnsignedShortAccumIBits());
842 
843   // Each signed accum type has at least as many integral bits as its
844   // corresponding unsigned accum type.
845   assert(getShortAccumIBits() >= getUnsignedShortAccumIBits());
846   assert(getAccumIBits() >= getUnsignedAccumIBits());
847   assert(getLongAccumIBits() >= getUnsignedLongAccumIBits());
848 }
849 
copyAuxTarget(const TargetInfo * Aux)850 void TargetInfo::copyAuxTarget(const TargetInfo *Aux) {
851   auto *Target = static_cast<TransferrableTargetInfo*>(this);
852   auto *Src = static_cast<const TransferrableTargetInfo*>(Aux);
853   *Target = *Src;
854 }
855