1 //===--- TargetInfo.cpp - Information about Target machine ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the TargetInfo and TargetInfoImpl interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/TargetInfo.h"
15 #include "clang/Basic/AddressSpaces.h"
16 #include "clang/Basic/CharInfo.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 <cstdlib>
22 using namespace clang;
23 
24 static const LangAS::Map DefaultAddrSpaceMap = { 0 };
25 
26 // TargetInfo Constructor.
27 TargetInfo::TargetInfo(const llvm::Triple &T) : TargetOpts(), Triple(T) {
28   // Set defaults.  Defaults are set for a 32-bit RISC platform, like PPC or
29   // SPARC.  These should be overridden by concrete targets as needed.
30   BigEndian = !T.isLittleEndian();
31   TLSSupported = true;
32   NoAsmVariants = false;
33   HasFloat128 = false;
34   PointerWidth = PointerAlign = 32;
35   BoolWidth = BoolAlign = 8;
36   IntWidth = IntAlign = 32;
37   LongWidth = LongAlign = 32;
38   LongLongWidth = LongLongAlign = 64;
39   SuitableAlign = 64;
40   DefaultAlignForAttributeAligned = 128;
41   MinGlobalAlign = 0;
42   HalfWidth = 16;
43   HalfAlign = 16;
44   FloatWidth = 32;
45   FloatAlign = 32;
46   DoubleWidth = 64;
47   DoubleAlign = 64;
48   LongDoubleWidth = 64;
49   LongDoubleAlign = 64;
50   Float128Align = 128;
51   LargeArrayMinWidth = 0;
52   LargeArrayAlign = 0;
53   MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0;
54   MaxVectorAlign = 0;
55   MaxTLSAlign = 0;
56   SimdDefaultAlign = 0;
57   SizeType = UnsignedLong;
58   PtrDiffType = SignedLong;
59   IntMaxType = SignedLongLong;
60   IntPtrType = SignedLong;
61   WCharType = SignedInt;
62   WIntType = SignedInt;
63   Char16Type = UnsignedShort;
64   Char32Type = UnsignedInt;
65   Int64Type = SignedLongLong;
66   SigAtomicType = SignedInt;
67   ProcessIDType = SignedInt;
68   UseSignedCharForObjCBool = true;
69   UseBitFieldTypeAlignment = true;
70   UseZeroLengthBitfieldAlignment = false;
71   UseExplicitBitFieldAlignment = true;
72   ZeroLengthBitfieldBoundary = 0;
73   HalfFormat = &llvm::APFloat::IEEEhalf;
74   FloatFormat = &llvm::APFloat::IEEEsingle;
75   DoubleFormat = &llvm::APFloat::IEEEdouble;
76   LongDoubleFormat = &llvm::APFloat::IEEEdouble;
77   Float128Format = &llvm::APFloat::IEEEquad;
78   MCountName = "mcount";
79   RegParmMax = 0;
80   SSERegParmMax = 0;
81   HasAlignMac68kSupport = false;
82   HasBuiltinMSVaList = false;
83   IsRenderScriptTarget = false;
84 
85   // Default to no types using fpret.
86   RealTypeUsesObjCFPRet = 0;
87 
88   // Default to not using fp2ret for __Complex long double
89   ComplexLongDoubleUsesFP2Ret = false;
90 
91   // Set the C++ ABI based on the triple.
92   TheCXXABI.set(Triple.isKnownWindowsMSVCEnvironment()
93                     ? TargetCXXABI::Microsoft
94                     : TargetCXXABI::GenericItanium);
95 
96   // Default to an empty address space map.
97   AddrSpaceMap = &DefaultAddrSpaceMap;
98   UseAddrSpaceMapMangling = false;
99 
100   // Default to an unknown platform name.
101   PlatformName = "unknown";
102   PlatformMinVersion = VersionTuple();
103 }
104 
105 // Out of line virtual dtor for TargetInfo.
106 TargetInfo::~TargetInfo() {}
107 
108 /// getTypeName - Return the user string for the specified integer type enum.
109 /// For example, SignedShort -> "short".
110 const char *TargetInfo::getTypeName(IntType T) {
111   switch (T) {
112   default: llvm_unreachable("not an integer!");
113   case SignedChar:       return "signed char";
114   case UnsignedChar:     return "unsigned char";
115   case SignedShort:      return "short";
116   case UnsignedShort:    return "unsigned short";
117   case SignedInt:        return "int";
118   case UnsignedInt:      return "unsigned int";
119   case SignedLong:       return "long int";
120   case UnsignedLong:     return "long unsigned int";
121   case SignedLongLong:   return "long long int";
122   case UnsignedLongLong: return "long long unsigned int";
123   }
124 }
125 
126 /// getTypeConstantSuffix - Return the constant suffix for the specified
127 /// integer type enum. For example, SignedLong -> "L".
128 const char *TargetInfo::getTypeConstantSuffix(IntType T) const {
129   switch (T) {
130   default: llvm_unreachable("not an integer!");
131   case SignedChar:
132   case SignedShort:
133   case SignedInt:        return "";
134   case SignedLong:       return "L";
135   case SignedLongLong:   return "LL";
136   case UnsignedChar:
137     if (getCharWidth() < getIntWidth())
138       return "";
139   case UnsignedShort:
140     if (getShortWidth() < getIntWidth())
141       return "";
142   case UnsignedInt:      return "U";
143   case UnsignedLong:     return "UL";
144   case UnsignedLongLong: return "ULL";
145   }
146 }
147 
148 /// getTypeFormatModifier - Return the printf format modifier for the
149 /// specified integer type enum. For example, SignedLong -> "l".
150 
151 const char *TargetInfo::getTypeFormatModifier(IntType T) {
152   switch (T) {
153   default: llvm_unreachable("not an integer!");
154   case SignedChar:
155   case UnsignedChar:     return "hh";
156   case SignedShort:
157   case UnsignedShort:    return "h";
158   case SignedInt:
159   case UnsignedInt:      return "";
160   case SignedLong:
161   case UnsignedLong:     return "l";
162   case SignedLongLong:
163   case UnsignedLongLong: return "ll";
164   }
165 }
166 
167 /// getTypeWidth - Return the width (in bits) of the specified integer type
168 /// enum. For example, SignedInt -> getIntWidth().
169 unsigned TargetInfo::getTypeWidth(IntType T) const {
170   switch (T) {
171   default: llvm_unreachable("not an integer!");
172   case SignedChar:
173   case UnsignedChar:     return getCharWidth();
174   case SignedShort:
175   case UnsignedShort:    return getShortWidth();
176   case SignedInt:
177   case UnsignedInt:      return getIntWidth();
178   case SignedLong:
179   case UnsignedLong:     return getLongWidth();
180   case SignedLongLong:
181   case UnsignedLongLong: return getLongLongWidth();
182   };
183 }
184 
185 TargetInfo::IntType TargetInfo::getIntTypeByWidth(
186     unsigned BitWidth, bool IsSigned) const {
187   if (getCharWidth() == BitWidth)
188     return IsSigned ? SignedChar : UnsignedChar;
189   if (getShortWidth() == BitWidth)
190     return IsSigned ? SignedShort : UnsignedShort;
191   if (getIntWidth() == BitWidth)
192     return IsSigned ? SignedInt : UnsignedInt;
193   if (getLongWidth() == BitWidth)
194     return IsSigned ? SignedLong : UnsignedLong;
195   if (getLongLongWidth() == BitWidth)
196     return IsSigned ? SignedLongLong : UnsignedLongLong;
197   return NoInt;
198 }
199 
200 TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
201                                                        bool IsSigned) const {
202   if (getCharWidth() >= BitWidth)
203     return IsSigned ? SignedChar : UnsignedChar;
204   if (getShortWidth() >= BitWidth)
205     return IsSigned ? SignedShort : UnsignedShort;
206   if (getIntWidth() >= BitWidth)
207     return IsSigned ? SignedInt : UnsignedInt;
208   if (getLongWidth() >= BitWidth)
209     return IsSigned ? SignedLong : UnsignedLong;
210   if (getLongLongWidth() >= BitWidth)
211     return IsSigned ? SignedLongLong : UnsignedLongLong;
212   return NoInt;
213 }
214 
215 TargetInfo::RealType TargetInfo::getRealTypeByWidth(unsigned BitWidth) const {
216   if (getFloatWidth() == BitWidth)
217     return Float;
218   if (getDoubleWidth() == BitWidth)
219     return Double;
220 
221   switch (BitWidth) {
222   case 96:
223     if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended)
224       return LongDouble;
225     break;
226   case 128:
227     if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble ||
228         &getLongDoubleFormat() == &llvm::APFloat::IEEEquad)
229       return LongDouble;
230     if (hasFloat128Type())
231       return Float128;
232     break;
233   }
234 
235   return NoFloat;
236 }
237 
238 /// getTypeAlign - Return the alignment (in bits) of the specified integer type
239 /// enum. For example, SignedInt -> getIntAlign().
240 unsigned TargetInfo::getTypeAlign(IntType T) const {
241   switch (T) {
242   default: llvm_unreachable("not an integer!");
243   case SignedChar:
244   case UnsignedChar:     return getCharAlign();
245   case SignedShort:
246   case UnsignedShort:    return getShortAlign();
247   case SignedInt:
248   case UnsignedInt:      return getIntAlign();
249   case SignedLong:
250   case UnsignedLong:     return getLongAlign();
251   case SignedLongLong:
252   case UnsignedLongLong: return getLongLongAlign();
253   };
254 }
255 
256 /// isTypeSigned - Return whether an integer types is signed. Returns true if
257 /// the type is signed; false otherwise.
258 bool TargetInfo::isTypeSigned(IntType T) {
259   switch (T) {
260   default: llvm_unreachable("not an integer!");
261   case SignedChar:
262   case SignedShort:
263   case SignedInt:
264   case SignedLong:
265   case SignedLongLong:
266     return true;
267   case UnsignedChar:
268   case UnsignedShort:
269   case UnsignedInt:
270   case UnsignedLong:
271   case UnsignedLongLong:
272     return false;
273   };
274 }
275 
276 /// adjust - Set forced language options.
277 /// Apply changes to the target information with respect to certain
278 /// language options which change the target configuration.
279 void TargetInfo::adjust(const LangOptions &Opts) {
280   if (Opts.NoBitFieldTypeAlign)
281     UseBitFieldTypeAlignment = false;
282   if (Opts.ShortWChar)
283     WCharType = UnsignedShort;
284   if (Opts.AlignDouble) {
285     DoubleAlign = LongLongAlign = 64;
286     LongDoubleAlign = 64;
287   }
288 
289   if (Opts.OpenCL) {
290     // OpenCL C requires specific widths for types, irrespective of
291     // what these normally are for the target.
292     // We also define long long and long double here, although the
293     // OpenCL standard only mentions these as "reserved".
294     IntWidth = IntAlign = 32;
295     LongWidth = LongAlign = 64;
296     LongLongWidth = LongLongAlign = 128;
297     HalfWidth = HalfAlign = 16;
298     FloatWidth = FloatAlign = 32;
299 
300     // Embedded 32-bit targets (OpenCL EP) might have double C type
301     // defined as float. Let's not override this as it might lead
302     // to generating illegal code that uses 64bit doubles.
303     if (DoubleWidth != FloatWidth) {
304       DoubleWidth = DoubleAlign = 64;
305       DoubleFormat = &llvm::APFloat::IEEEdouble;
306     }
307     LongDoubleWidth = LongDoubleAlign = 128;
308 
309     unsigned MaxPointerWidth = getMaxPointerWidth();
310     assert(MaxPointerWidth == 32 || MaxPointerWidth == 64);
311     bool Is32BitArch = MaxPointerWidth == 32;
312     SizeType = Is32BitArch ? UnsignedInt : UnsignedLong;
313     PtrDiffType = Is32BitArch ? SignedInt : SignedLong;
314     IntPtrType = Is32BitArch ? SignedInt : SignedLong;
315 
316     IntMaxType = SignedLongLong;
317     Int64Type = SignedLong;
318 
319     HalfFormat = &llvm::APFloat::IEEEhalf;
320     FloatFormat = &llvm::APFloat::IEEEsingle;
321     LongDoubleFormat = &llvm::APFloat::IEEEquad;
322   }
323 }
324 
325 bool TargetInfo::initFeatureMap(
326     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
327     const std::vector<std::string> &FeatureVec) const {
328   for (const auto &F : FeatureVec) {
329     StringRef Name = F;
330     // Apply the feature via the target.
331     bool Enabled = Name[0] == '+';
332     setFeatureEnabled(Features, Name.substr(1), Enabled);
333   }
334   return true;
335 }
336 
337 //===----------------------------------------------------------------------===//
338 
339 
340 static StringRef removeGCCRegisterPrefix(StringRef Name) {
341   if (Name[0] == '%' || Name[0] == '#')
342     Name = Name.substr(1);
343 
344   return Name;
345 }
346 
347 /// isValidClobber - Returns whether the passed in string is
348 /// a valid clobber in an inline asm statement. This is used by
349 /// Sema.
350 bool TargetInfo::isValidClobber(StringRef Name) const {
351   return (isValidGCCRegisterName(Name) ||
352           Name == "memory" || Name == "cc");
353 }
354 
355 /// isValidGCCRegisterName - Returns whether the passed in string
356 /// is a valid register name according to GCC. This is used by Sema for
357 /// inline asm statements.
358 bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
359   if (Name.empty())
360     return false;
361 
362   // Get rid of any register prefix.
363   Name = removeGCCRegisterPrefix(Name);
364   if (Name.empty())
365     return false;
366 
367   ArrayRef<const char *> Names = getGCCRegNames();
368 
369   // If we have a number it maps to an entry in the register name array.
370   if (isDigit(Name[0])) {
371     unsigned n;
372     if (!Name.getAsInteger(0, n))
373       return n < Names.size();
374   }
375 
376   // Check register names.
377   if (std::find(Names.begin(), Names.end(), Name) != Names.end())
378     return true;
379 
380   // Check any additional names that we have.
381   for (const AddlRegName &ARN : getGCCAddlRegNames())
382     for (const char *AN : ARN.Names) {
383       if (!AN)
384         break;
385       // Make sure the register that the additional name is for is within
386       // the bounds of the register names from above.
387       if (AN == Name && ARN.RegNum < Names.size())
388         return true;
389     }
390 
391   // Now check aliases.
392   for (const GCCRegAlias &GRA : getGCCRegAliases())
393     for (const char *A : GRA.Aliases) {
394       if (!A)
395         break;
396       if (A == Name)
397         return true;
398     }
399 
400   return false;
401 }
402 
403 StringRef
404 TargetInfo::getNormalizedGCCRegisterName(StringRef Name) const {
405   assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
406 
407   // Get rid of any register prefix.
408   Name = removeGCCRegisterPrefix(Name);
409 
410   ArrayRef<const char *> Names = getGCCRegNames();
411 
412   // First, check if we have a number.
413   if (isDigit(Name[0])) {
414     unsigned n;
415     if (!Name.getAsInteger(0, n)) {
416       assert(n < Names.size() && "Out of bounds register number!");
417       return Names[n];
418     }
419   }
420 
421   // Check any additional names that we have.
422   for (const AddlRegName &ARN : getGCCAddlRegNames())
423     for (const char *AN : ARN.Names) {
424       if (!AN)
425         break;
426       // Make sure the register that the additional name is for is within
427       // the bounds of the register names from above.
428       if (AN == Name && ARN.RegNum < Names.size())
429         return Name;
430     }
431 
432   // Now check aliases.
433   for (const GCCRegAlias &RA : getGCCRegAliases())
434     for (const char *A : RA.Aliases) {
435       if (!A)
436         break;
437       if (A == Name)
438         return RA.Register;
439     }
440 
441   return Name;
442 }
443 
444 bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
445   const char *Name = Info.getConstraintStr().c_str();
446   // An output constraint must start with '=' or '+'
447   if (*Name != '=' && *Name != '+')
448     return false;
449 
450   if (*Name == '+')
451     Info.setIsReadWrite();
452 
453   Name++;
454   while (*Name) {
455     switch (*Name) {
456     default:
457       if (!validateAsmConstraint(Name, Info)) {
458         // FIXME: We temporarily return false
459         // so we can add more constraints as we hit it.
460         // Eventually, an unknown constraint should just be treated as 'g'.
461         return false;
462       }
463       break;
464     case '&': // early clobber.
465       Info.setEarlyClobber();
466       break;
467     case '%': // commutative.
468       // FIXME: Check that there is a another register after this one.
469       break;
470     case 'r': // general register.
471       Info.setAllowsRegister();
472       break;
473     case 'm': // memory operand.
474     case 'o': // offsetable memory operand.
475     case 'V': // non-offsetable memory operand.
476     case '<': // autodecrement memory operand.
477     case '>': // autoincrement memory operand.
478       Info.setAllowsMemory();
479       break;
480     case 'g': // general register, memory operand or immediate integer.
481     case 'X': // any operand.
482       Info.setAllowsRegister();
483       Info.setAllowsMemory();
484       break;
485     case ',': // multiple alternative constraint.  Pass it.
486       // Handle additional optional '=' or '+' modifiers.
487       if (Name[1] == '=' || Name[1] == '+')
488         Name++;
489       break;
490     case '#': // Ignore as constraint.
491       while (Name[1] && Name[1] != ',')
492         Name++;
493       break;
494     case '?': // Disparage slightly code.
495     case '!': // Disparage severely.
496     case '*': // Ignore for choosing register preferences.
497       break;  // Pass them.
498     }
499 
500     Name++;
501   }
502 
503   // Early clobber with a read-write constraint which doesn't permit registers
504   // is invalid.
505   if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister())
506     return false;
507 
508   // If a constraint allows neither memory nor register operands it contains
509   // only modifiers. Reject it.
510   return Info.allowsMemory() || Info.allowsRegister();
511 }
512 
513 bool TargetInfo::resolveSymbolicName(const char *&Name,
514                                      ArrayRef<ConstraintInfo> OutputConstraints,
515                                      unsigned &Index) const {
516   assert(*Name == '[' && "Symbolic name did not start with '['");
517   Name++;
518   const char *Start = Name;
519   while (*Name && *Name != ']')
520     Name++;
521 
522   if (!*Name) {
523     // Missing ']'
524     return false;
525   }
526 
527   std::string SymbolicName(Start, Name - Start);
528 
529   for (Index = 0; Index != OutputConstraints.size(); ++Index)
530     if (SymbolicName == OutputConstraints[Index].getName())
531       return true;
532 
533   return false;
534 }
535 
536 bool TargetInfo::validateInputConstraint(
537                               MutableArrayRef<ConstraintInfo> OutputConstraints,
538                               ConstraintInfo &Info) const {
539   const char *Name = Info.ConstraintStr.c_str();
540 
541   if (!*Name)
542     return false;
543 
544   while (*Name) {
545     switch (*Name) {
546     default:
547       // Check if we have a matching constraint
548       if (*Name >= '0' && *Name <= '9') {
549         const char *DigitStart = Name;
550         while (Name[1] >= '0' && Name[1] <= '9')
551           Name++;
552         const char *DigitEnd = Name;
553         unsigned i;
554         if (StringRef(DigitStart, DigitEnd - DigitStart + 1)
555                 .getAsInteger(10, i))
556           return false;
557 
558         // Check if matching constraint is out of bounds.
559         if (i >= OutputConstraints.size()) return false;
560 
561         // A number must refer to an output only operand.
562         if (OutputConstraints[i].isReadWrite())
563           return false;
564 
565         // If the constraint is already tied, it must be tied to the
566         // same operand referenced to by the number.
567         if (Info.hasTiedOperand() && Info.getTiedOperand() != i)
568           return false;
569 
570         // The constraint should have the same info as the respective
571         // output constraint.
572         Info.setTiedOperand(i, OutputConstraints[i]);
573       } else if (!validateAsmConstraint(Name, Info)) {
574         // FIXME: This error return is in place temporarily so we can
575         // add more constraints as we hit it.  Eventually, an unknown
576         // constraint should just be treated as 'g'.
577         return false;
578       }
579       break;
580     case '[': {
581       unsigned Index = 0;
582       if (!resolveSymbolicName(Name, OutputConstraints, Index))
583         return false;
584 
585       // If the constraint is already tied, it must be tied to the
586       // same operand referenced to by the number.
587       if (Info.hasTiedOperand() && Info.getTiedOperand() != Index)
588         return false;
589 
590       // A number must refer to an output only operand.
591       if (OutputConstraints[Index].isReadWrite())
592         return false;
593 
594       Info.setTiedOperand(Index, OutputConstraints[Index]);
595       break;
596     }
597     case '%': // commutative
598       // FIXME: Fail if % is used with the last operand.
599       break;
600     case 'i': // immediate integer.
601     case 'n': // immediate integer with a known value.
602       break;
603     case 'I':  // Various constant constraints with target-specific meanings.
604     case 'J':
605     case 'K':
606     case 'L':
607     case 'M':
608     case 'N':
609     case 'O':
610     case 'P':
611       if (!validateAsmConstraint(Name, Info))
612         return false;
613       break;
614     case 'r': // general register.
615       Info.setAllowsRegister();
616       break;
617     case 'm': // memory operand.
618     case 'o': // offsettable memory operand.
619     case 'V': // non-offsettable memory operand.
620     case '<': // autodecrement memory operand.
621     case '>': // autoincrement memory operand.
622       Info.setAllowsMemory();
623       break;
624     case 'g': // general register, memory operand or immediate integer.
625     case 'X': // any operand.
626       Info.setAllowsRegister();
627       Info.setAllowsMemory();
628       break;
629     case 'E': // immediate floating point.
630     case 'F': // immediate floating point.
631     case 'p': // address operand.
632       break;
633     case ',': // multiple alternative constraint.  Ignore comma.
634       break;
635     case '#': // Ignore as constraint.
636       while (Name[1] && Name[1] != ',')
637         Name++;
638       break;
639     case '?': // Disparage slightly code.
640     case '!': // Disparage severely.
641     case '*': // Ignore for choosing register preferences.
642       break;  // Pass them.
643     }
644 
645     Name++;
646   }
647 
648   return true;
649 }
650