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