TargetInfo.cpp revision 283526
14887Schin//===--- TargetInfo.cpp - Information about Target machine ----------------===//
24887Schin//
34887Schin//                     The LLVM Compiler Infrastructure
412068SRoger.Faulkner@Oracle.COM//
54887Schin// This file is distributed under the University of Illinois Open Source
64887Schin// License. See LICENSE.TXT for details.
78462SApril.Chin@Sun.COM//
84887Schin//===----------------------------------------------------------------------===//
94887Schin//
104887Schin//  This file implements the TargetInfo and TargetInfoImpl interfaces.
114887Schin//
124887Schin//===----------------------------------------------------------------------===//
134887Schin
144887Schin#include "clang/Basic/TargetInfo.h"
154887Schin#include "clang/Basic/AddressSpaces.h"
164887Schin#include "clang/Basic/CharInfo.h"
174887Schin#include "clang/Basic/LangOptions.h"
184887Schin#include "llvm/ADT/APFloat.h"
194887Schin#include "llvm/ADT/STLExtras.h"
204887Schin#include "llvm/Support/ErrorHandling.h"
214887Schin#include <cstdlib>
224887Schinusing namespace clang;
234887Schin
244887Schinstatic const LangAS::Map DefaultAddrSpaceMap = { 0 };
254887Schin
264887Schin// TargetInfo Constructor.
274887SchinTargetInfo::TargetInfo(const llvm::Triple &T) : TargetOpts(), Triple(T) {
284887Schin  // Set defaults.  Defaults are set for a 32-bit RISC platform, like PPC or
294887Schin  // SPARC.  These should be overridden by concrete targets as needed.
304887Schin  BigEndian = true;
314887Schin  TLSSupported = true;
324887Schin  NoAsmVariants = false;
334887Schin  PointerWidth = PointerAlign = 32;
344887Schin  BoolWidth = BoolAlign = 8;
354887Schin  IntWidth = IntAlign = 32;
364887Schin  LongWidth = LongAlign = 32;
374887Schin  LongLongWidth = LongLongAlign = 64;
384887Schin  SuitableAlign = 64;
394887Schin  MinGlobalAlign = 0;
404887Schin  HalfWidth = 16;
414887Schin  HalfAlign = 16;
424887Schin  FloatWidth = 32;
434887Schin  FloatAlign = 32;
444887Schin  DoubleWidth = 64;
454887Schin  DoubleAlign = 64;
464887Schin  LongDoubleWidth = 64;
474887Schin  LongDoubleAlign = 64;
484887Schin  LargeArrayMinWidth = 0;
494887Schin  LargeArrayAlign = 0;
504887Schin  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.
99TargetInfo::~TargetInfo() {}
100
101/// getTypeName - Return the user string for the specified integer type enum.
102/// For example, SignedShort -> "short".
103const char *TargetInfo::getTypeName(IntType T) {
104  switch (T) {
105  default: llvm_unreachable("not an integer!");
106  case SignedChar:       return "signed 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".
121const char *TargetInfo::getTypeConstantSuffix(IntType T) const {
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    if (getCharWidth() < getIntWidth())
131      return "";
132  case UnsignedShort:
133    if (getShortWidth() < getIntWidth())
134      return "";
135  case UnsignedInt:      return "U";
136  case UnsignedLong:     return "UL";
137  case UnsignedLongLong: return "ULL";
138  }
139}
140
141/// getTypeFormatModifier - Return the printf format modifier for the
142/// specified integer type enum. For example, SignedLong -> "l".
143
144const char *TargetInfo::getTypeFormatModifier(IntType T) {
145  switch (T) {
146  default: llvm_unreachable("not an integer!");
147  case SignedChar:
148  case UnsignedChar:     return "hh";
149  case SignedShort:
150  case UnsignedShort:    return "h";
151  case SignedInt:
152  case UnsignedInt:      return "";
153  case SignedLong:
154  case UnsignedLong:     return "l";
155  case SignedLongLong:
156  case UnsignedLongLong: return "ll";
157  }
158}
159
160/// getTypeWidth - Return the width (in bits) of the specified integer type
161/// enum. For example, SignedInt -> getIntWidth().
162unsigned TargetInfo::getTypeWidth(IntType T) const {
163  switch (T) {
164  default: llvm_unreachable("not an integer!");
165  case SignedChar:
166  case UnsignedChar:     return getCharWidth();
167  case SignedShort:
168  case UnsignedShort:    return getShortWidth();
169  case SignedInt:
170  case UnsignedInt:      return getIntWidth();
171  case SignedLong:
172  case UnsignedLong:     return getLongWidth();
173  case SignedLongLong:
174  case UnsignedLongLong: return getLongLongWidth();
175  };
176}
177
178TargetInfo::IntType TargetInfo::getIntTypeByWidth(
179    unsigned BitWidth, bool IsSigned) const {
180  if (getCharWidth() == BitWidth)
181    return IsSigned ? SignedChar : UnsignedChar;
182  if (getShortWidth() == BitWidth)
183    return IsSigned ? SignedShort : UnsignedShort;
184  if (getIntWidth() == BitWidth)
185    return IsSigned ? SignedInt : UnsignedInt;
186  if (getLongWidth() == BitWidth)
187    return IsSigned ? SignedLong : UnsignedLong;
188  if (getLongLongWidth() == BitWidth)
189    return IsSigned ? SignedLongLong : UnsignedLongLong;
190  return NoInt;
191}
192
193TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth,
194                                                       bool IsSigned) const {
195  if (getCharWidth() >= BitWidth)
196    return IsSigned ? SignedChar : UnsignedChar;
197  if (getShortWidth() >= BitWidth)
198    return IsSigned ? SignedShort : UnsignedShort;
199  if (getIntWidth() >= BitWidth)
200    return IsSigned ? SignedInt : UnsignedInt;
201  if (getLongWidth() >= BitWidth)
202    return IsSigned ? SignedLong : UnsignedLong;
203  if (getLongLongWidth() >= BitWidth)
204    return IsSigned ? SignedLongLong : UnsignedLongLong;
205  return NoInt;
206}
207
208TargetInfo::RealType TargetInfo::getRealTypeByWidth(unsigned BitWidth) const {
209  if (getFloatWidth() == BitWidth)
210    return Float;
211  if (getDoubleWidth() == BitWidth)
212    return Double;
213
214  switch (BitWidth) {
215  case 96:
216    if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended)
217      return LongDouble;
218    break;
219  case 128:
220    if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble ||
221        &getLongDoubleFormat() == &llvm::APFloat::IEEEquad)
222      return LongDouble;
223    break;
224  }
225
226  return NoFloat;
227}
228
229/// getTypeAlign - Return the alignment (in bits) of the specified integer type
230/// enum. For example, SignedInt -> getIntAlign().
231unsigned TargetInfo::getTypeAlign(IntType T) const {
232  switch (T) {
233  default: llvm_unreachable("not an integer!");
234  case SignedChar:
235  case UnsignedChar:     return getCharAlign();
236  case SignedShort:
237  case UnsignedShort:    return getShortAlign();
238  case SignedInt:
239  case UnsignedInt:      return getIntAlign();
240  case SignedLong:
241  case UnsignedLong:     return getLongAlign();
242  case SignedLongLong:
243  case UnsignedLongLong: return getLongLongAlign();
244  };
245}
246
247/// isTypeSigned - Return whether an integer types is signed. Returns true if
248/// the type is signed; false otherwise.
249bool TargetInfo::isTypeSigned(IntType T) {
250  switch (T) {
251  default: llvm_unreachable("not an integer!");
252  case SignedChar:
253  case SignedShort:
254  case SignedInt:
255  case SignedLong:
256  case SignedLongLong:
257    return true;
258  case UnsignedChar:
259  case UnsignedShort:
260  case UnsignedInt:
261  case UnsignedLong:
262  case UnsignedLongLong:
263    return false;
264  };
265}
266
267/// adjust - Set forced language options.
268/// Apply changes to the target information with respect to certain
269/// language options which change the target configuration.
270void TargetInfo::adjust(const LangOptions &Opts) {
271  if (Opts.NoBitFieldTypeAlign)
272    UseBitFieldTypeAlignment = false;
273  if (Opts.ShortWChar)
274    WCharType = UnsignedShort;
275
276  if (Opts.OpenCL) {
277    // OpenCL C requires specific widths for types, irrespective of
278    // what these normally are for the target.
279    // We also define long long and long double here, although the
280    // OpenCL standard only mentions these as "reserved".
281    IntWidth = IntAlign = 32;
282    LongWidth = LongAlign = 64;
283    LongLongWidth = LongLongAlign = 128;
284    HalfWidth = HalfAlign = 16;
285    FloatWidth = FloatAlign = 32;
286
287    // Embedded 32-bit targets (OpenCL EP) might have double C type
288    // defined as float. Let's not override this as it might lead
289    // to generating illegal code that uses 64bit doubles.
290    if (DoubleWidth != FloatWidth) {
291      DoubleWidth = DoubleAlign = 64;
292      DoubleFormat = &llvm::APFloat::IEEEdouble;
293    }
294    LongDoubleWidth = LongDoubleAlign = 128;
295
296    assert(PointerWidth == 32 || PointerWidth == 64);
297    bool Is32BitArch = PointerWidth == 32;
298    SizeType = Is32BitArch ? UnsignedInt : UnsignedLong;
299    PtrDiffType = Is32BitArch ? SignedInt : SignedLong;
300    IntPtrType = Is32BitArch ? SignedInt : SignedLong;
301
302    IntMaxType = SignedLongLong;
303    Int64Type = SignedLong;
304
305    HalfFormat = &llvm::APFloat::IEEEhalf;
306    FloatFormat = &llvm::APFloat::IEEEsingle;
307    LongDoubleFormat = &llvm::APFloat::IEEEquad;
308  }
309}
310
311//===----------------------------------------------------------------------===//
312
313
314static StringRef removeGCCRegisterPrefix(StringRef Name) {
315  if (Name[0] == '%' || Name[0] == '#')
316    Name = Name.substr(1);
317
318  return Name;
319}
320
321/// isValidClobber - Returns whether the passed in string is
322/// a valid clobber in an inline asm statement. This is used by
323/// Sema.
324bool TargetInfo::isValidClobber(StringRef Name) const {
325  return (isValidGCCRegisterName(Name) ||
326	  Name == "memory" || Name == "cc");
327}
328
329/// isValidGCCRegisterName - Returns whether the passed in string
330/// is a valid register name according to GCC. This is used by Sema for
331/// inline asm statements.
332bool TargetInfo::isValidGCCRegisterName(StringRef Name) const {
333  if (Name.empty())
334    return false;
335
336  const char * const *Names;
337  unsigned NumNames;
338
339  // Get rid of any register prefix.
340  Name = removeGCCRegisterPrefix(Name);
341  if (Name.empty())
342      return false;
343
344  getGCCRegNames(Names, NumNames);
345
346  // If we have a number it maps to an entry in the register name array.
347  if (isDigit(Name[0])) {
348    int n;
349    if (!Name.getAsInteger(0, n))
350      return n >= 0 && (unsigned)n < NumNames;
351  }
352
353  // Check register names.
354  for (unsigned i = 0; i < NumNames; i++) {
355    if (Name == Names[i])
356      return true;
357  }
358
359  // Check any additional names that we have.
360  const AddlRegName *AddlNames;
361  unsigned NumAddlNames;
362  getGCCAddlRegNames(AddlNames, NumAddlNames);
363  for (unsigned i = 0; i < NumAddlNames; i++)
364    for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) {
365      if (!AddlNames[i].Names[j])
366	break;
367      // Make sure the register that the additional name is for is within
368      // the bounds of the register names from above.
369      if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames)
370	return true;
371  }
372
373  // Now check aliases.
374  const GCCRegAlias *Aliases;
375  unsigned NumAliases;
376
377  getGCCRegAliases(Aliases, NumAliases);
378  for (unsigned i = 0; i < NumAliases; i++) {
379    for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) {
380      if (!Aliases[i].Aliases[j])
381        break;
382      if (Aliases[i].Aliases[j] == Name)
383        return true;
384    }
385  }
386
387  return false;
388}
389
390StringRef
391TargetInfo::getNormalizedGCCRegisterName(StringRef Name) const {
392  assert(isValidGCCRegisterName(Name) && "Invalid register passed in");
393
394  // Get rid of any register prefix.
395  Name = removeGCCRegisterPrefix(Name);
396
397  const char * const *Names;
398  unsigned NumNames;
399
400  getGCCRegNames(Names, NumNames);
401
402  // First, check if we have a number.
403  if (isDigit(Name[0])) {
404    int n;
405    if (!Name.getAsInteger(0, n)) {
406      assert(n >= 0 && (unsigned)n < NumNames &&
407             "Out of bounds register number!");
408      return Names[n];
409    }
410  }
411
412  // Check any additional names that we have.
413  const AddlRegName *AddlNames;
414  unsigned NumAddlNames;
415  getGCCAddlRegNames(AddlNames, NumAddlNames);
416  for (unsigned i = 0; i < NumAddlNames; i++)
417    for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) {
418      if (!AddlNames[i].Names[j])
419	break;
420      // Make sure the register that the additional name is for is within
421      // the bounds of the register names from above.
422      if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames)
423	return Name;
424    }
425
426  // Now check aliases.
427  const GCCRegAlias *Aliases;
428  unsigned NumAliases;
429
430  getGCCRegAliases(Aliases, NumAliases);
431  for (unsigned i = 0; i < NumAliases; 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
443bool 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
512bool 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
536bool 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
651bool TargetCXXABI::tryParse(llvm::StringRef name) {
652  const Kind unknown = static_cast<Kind>(-1);
653  Kind kind = llvm::StringSwitch<Kind>(name)
654    .Case("arm", GenericARM)
655    .Case("ios", iOS)
656    .Case("itanium", GenericItanium)
657    .Case("microsoft", Microsoft)
658    .Case("mips", GenericMIPS)
659    .Default(unknown);
660  if (kind == unknown) return false;
661
662  set(kind);
663  return true;
664}
665