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