1//===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===//
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/// \file
11/// \brief Defines the clang::TargetInfo interface.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_BASIC_TARGETINFO_H
16#define LLVM_CLANG_BASIC_TARGETINFO_H
17
18#include "clang/Basic/AddressSpaces.h"
19#include "clang/Basic/LLVM.h"
20#include "clang/Basic/Specifiers.h"
21#include "clang/Basic/TargetCXXABI.h"
22#include "clang/Basic/TargetOptions.h"
23#include "clang/Basic/VersionTuple.h"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/APInt.h"
26#include "llvm/ADT/SmallSet.h"
27#include "llvm/ADT/StringMap.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/Support/DataTypes.h"
32#include <cassert>
33#include <string>
34#include <vector>
35
36namespace llvm {
37struct fltSemantics;
38}
39
40namespace clang {
41class DiagnosticsEngine;
42class LangOptions;
43class MacroBuilder;
44class SourceLocation;
45class SourceManager;
46
47namespace Builtin { struct Info; }
48
49/// \brief Exposes information about the current target.
50///
51class TargetInfo : public RefCountedBase<TargetInfo> {
52  std::shared_ptr<TargetOptions> TargetOpts;
53  llvm::Triple Triple;
54protected:
55  // Target values set by the ctor of the actual target implementation.  Default
56  // values are specified by the TargetInfo constructor.
57  bool BigEndian;
58  bool TLSSupported;
59  bool NoAsmVariants;  // True if {|} are normal characters.
60  unsigned char PointerWidth, PointerAlign;
61  unsigned char BoolWidth, BoolAlign;
62  unsigned char IntWidth, IntAlign;
63  unsigned char HalfWidth, HalfAlign;
64  unsigned char FloatWidth, FloatAlign;
65  unsigned char DoubleWidth, DoubleAlign;
66  unsigned char LongDoubleWidth, LongDoubleAlign;
67  unsigned char LargeArrayMinWidth, LargeArrayAlign;
68  unsigned char LongWidth, LongAlign;
69  unsigned char LongLongWidth, LongLongAlign;
70  unsigned char SuitableAlign;
71  unsigned char DefaultAlignForAttributeAligned;
72  unsigned char MinGlobalAlign;
73  unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
74  unsigned short MaxVectorAlign;
75  unsigned short MaxTLSAlign;
76  unsigned short SimdDefaultAlign;
77  const char *DataLayoutString;
78  const char *UserLabelPrefix;
79  const char *MCountName;
80  const llvm::fltSemantics *HalfFormat, *FloatFormat, *DoubleFormat,
81    *LongDoubleFormat;
82  unsigned char RegParmMax, SSERegParmMax;
83  TargetCXXABI TheCXXABI;
84  const LangAS::Map *AddrSpaceMap;
85
86  mutable StringRef PlatformName;
87  mutable VersionTuple PlatformMinVersion;
88
89  unsigned HasAlignMac68kSupport : 1;
90  unsigned RealTypeUsesObjCFPRet : 3;
91  unsigned ComplexLongDoubleUsesFP2Ret : 1;
92
93  unsigned HasBuiltinMSVaList : 1;
94
95  // TargetInfo Constructor.  Default initializes all fields.
96  TargetInfo(const llvm::Triple &T);
97
98public:
99  /// \brief Construct a target for the given options.
100  ///
101  /// \param Opts - The options to use to initialize the target. The target may
102  /// modify the options to canonicalize the target feature information to match
103  /// what the backend expects.
104  static TargetInfo *
105  CreateTargetInfo(DiagnosticsEngine &Diags,
106                   const std::shared_ptr<TargetOptions> &Opts);
107
108  virtual ~TargetInfo();
109
110  /// \brief Retrieve the target options.
111  TargetOptions &getTargetOpts() const {
112    assert(TargetOpts && "Missing target options");
113    return *TargetOpts;
114  }
115
116  ///===---- Target Data Type Query Methods -------------------------------===//
117  enum IntType {
118    NoInt = 0,
119    SignedChar,
120    UnsignedChar,
121    SignedShort,
122    UnsignedShort,
123    SignedInt,
124    UnsignedInt,
125    SignedLong,
126    UnsignedLong,
127    SignedLongLong,
128    UnsignedLongLong
129  };
130
131  enum RealType {
132    NoFloat = 255,
133    Float = 0,
134    Double,
135    LongDouble
136  };
137
138  /// \brief The different kinds of __builtin_va_list types defined by
139  /// the target implementation.
140  enum BuiltinVaListKind {
141    /// typedef char* __builtin_va_list;
142    CharPtrBuiltinVaList = 0,
143
144    /// typedef void* __builtin_va_list;
145    VoidPtrBuiltinVaList,
146
147    /// __builtin_va_list as defind by the AArch64 ABI
148    /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
149    AArch64ABIBuiltinVaList,
150
151    /// __builtin_va_list as defined by the PNaCl ABI:
152    /// http://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Machine-Types
153    PNaClABIBuiltinVaList,
154
155    /// __builtin_va_list as defined by the Power ABI:
156    /// https://www.power.org
157    ///        /resources/downloads/Power-Arch-32-bit-ABI-supp-1.0-Embedded.pdf
158    PowerABIBuiltinVaList,
159
160    /// __builtin_va_list as defined by the x86-64 ABI:
161    /// http://www.x86-64.org/documentation/abi.pdf
162    X86_64ABIBuiltinVaList,
163
164    /// __builtin_va_list as defined by ARM AAPCS ABI
165    /// http://infocenter.arm.com
166    //        /help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
167    AAPCSABIBuiltinVaList,
168
169    // typedef struct __va_list_tag
170    //   {
171    //     long __gpr;
172    //     long __fpr;
173    //     void *__overflow_arg_area;
174    //     void *__reg_save_area;
175    //   } va_list[1];
176    SystemZBuiltinVaList
177  };
178
179protected:
180  IntType SizeType, IntMaxType, PtrDiffType, IntPtrType, WCharType,
181          WIntType, Char16Type, Char32Type, Int64Type, SigAtomicType,
182          ProcessIDType;
183
184  /// \brief Whether Objective-C's built-in boolean type should be signed char.
185  ///
186  /// Otherwise, when this flag is not set, the normal built-in boolean type is
187  /// used.
188  unsigned UseSignedCharForObjCBool : 1;
189
190  /// Control whether the alignment of bit-field types is respected when laying
191  /// out structures. If true, then the alignment of the bit-field type will be
192  /// used to (a) impact the alignment of the containing structure, and (b)
193  /// ensure that the individual bit-field will not straddle an alignment
194  /// boundary.
195  unsigned UseBitFieldTypeAlignment : 1;
196
197  /// \brief Whether zero length bitfields (e.g., int : 0;) force alignment of
198  /// the next bitfield.
199  ///
200  /// If the alignment of the zero length bitfield is greater than the member
201  /// that follows it, `bar', `bar' will be aligned as the type of the
202  /// zero-length bitfield.
203  unsigned UseZeroLengthBitfieldAlignment : 1;
204
205  /// If non-zero, specifies a fixed alignment value for bitfields that follow
206  /// zero length bitfield, regardless of the zero length bitfield type.
207  unsigned ZeroLengthBitfieldBoundary;
208
209  /// \brief Specify if mangling based on address space map should be used or
210  /// not for language specific address spaces
211  bool UseAddrSpaceMapMangling;
212
213public:
214  IntType getSizeType() const { return SizeType; }
215  IntType getIntMaxType() const { return IntMaxType; }
216  IntType getUIntMaxType() const {
217    return getCorrespondingUnsignedType(IntMaxType);
218  }
219  IntType getPtrDiffType(unsigned AddrSpace) const {
220    return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
221  }
222  IntType getIntPtrType() const { return IntPtrType; }
223  IntType getUIntPtrType() const {
224    return getCorrespondingUnsignedType(IntPtrType);
225  }
226  IntType getWCharType() const { return WCharType; }
227  IntType getWIntType() const { return WIntType; }
228  IntType getChar16Type() const { return Char16Type; }
229  IntType getChar32Type() const { return Char32Type; }
230  IntType getInt64Type() const { return Int64Type; }
231  IntType getUInt64Type() const {
232    return getCorrespondingUnsignedType(Int64Type);
233  }
234  IntType getSigAtomicType() const { return SigAtomicType; }
235  IntType getProcessIDType() const { return ProcessIDType; }
236
237  static IntType getCorrespondingUnsignedType(IntType T) {
238    switch (T) {
239    case SignedChar:
240      return UnsignedChar;
241    case SignedShort:
242      return UnsignedShort;
243    case SignedInt:
244      return UnsignedInt;
245    case SignedLong:
246      return UnsignedLong;
247    case SignedLongLong:
248      return UnsignedLongLong;
249    default:
250      llvm_unreachable("Unexpected signed integer type");
251    }
252  }
253
254  /// \brief Return the width (in bits) of the specified integer type enum.
255  ///
256  /// For example, SignedInt -> getIntWidth().
257  unsigned getTypeWidth(IntType T) const;
258
259  /// \brief Return integer type with specified width.
260  virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const;
261
262  /// \brief Return the smallest integer type with at least the specified width.
263  virtual IntType getLeastIntTypeByWidth(unsigned BitWidth,
264                                         bool IsSigned) const;
265
266  /// \brief Return floating point type with specified width.
267  RealType getRealTypeByWidth(unsigned BitWidth) const;
268
269  /// \brief Return the alignment (in bits) of the specified integer type enum.
270  ///
271  /// For example, SignedInt -> getIntAlign().
272  unsigned getTypeAlign(IntType T) const;
273
274  /// \brief Returns true if the type is signed; false otherwise.
275  static bool isTypeSigned(IntType T);
276
277  /// \brief Return the width of pointers on this target, for the
278  /// specified address space.
279  uint64_t getPointerWidth(unsigned AddrSpace) const {
280    return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
281  }
282  uint64_t getPointerAlign(unsigned AddrSpace) const {
283    return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
284  }
285
286  /// \brief Return the size of '_Bool' and C++ 'bool' for this target, in bits.
287  unsigned getBoolWidth() const { return BoolWidth; }
288
289  /// \brief Return the alignment of '_Bool' and C++ 'bool' for this target.
290  unsigned getBoolAlign() const { return BoolAlign; }
291
292  unsigned getCharWidth() const { return 8; } // FIXME
293  unsigned getCharAlign() const { return 8; } // FIXME
294
295  /// \brief Return the size of 'signed short' and 'unsigned short' for this
296  /// target, in bits.
297  unsigned getShortWidth() const { return 16; } // FIXME
298
299  /// \brief Return the alignment of 'signed short' and 'unsigned short' for
300  /// this target.
301  unsigned getShortAlign() const { return 16; } // FIXME
302
303  /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for
304  /// this target, in bits.
305  unsigned getIntWidth() const { return IntWidth; }
306  unsigned getIntAlign() const { return IntAlign; }
307
308  /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long'
309  /// for this target, in bits.
310  unsigned getLongWidth() const { return LongWidth; }
311  unsigned getLongAlign() const { return LongAlign; }
312
313  /// getLongLongWidth/Align - Return the size of 'signed long long' and
314  /// 'unsigned long long' for this target, in bits.
315  unsigned getLongLongWidth() const { return LongLongWidth; }
316  unsigned getLongLongAlign() const { return LongLongAlign; }
317
318  /// \brief Determine whether the __int128 type is supported on this target.
319  virtual bool hasInt128Type() const {
320    return getPointerWidth(0) >= 64;
321  } // FIXME
322
323  /// \brief Return the alignment that is suitable for storing any
324  /// object with a fundamental alignment requirement.
325  unsigned getSuitableAlign() const { return SuitableAlign; }
326
327  /// \brief Return the default alignment for __attribute__((aligned)) on
328  /// this target, to be used if no alignment value is specified.
329  unsigned getDefaultAlignForAttributeAligned() const {
330    return DefaultAlignForAttributeAligned;
331  }
332
333  /// getMinGlobalAlign - Return the minimum alignment of a global variable,
334  /// unless its alignment is explicitly reduced via attributes.
335  unsigned getMinGlobalAlign() const { return MinGlobalAlign; }
336
337  /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in
338  /// bits.
339  unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
340  unsigned getWCharAlign() const { return getTypeAlign(WCharType); }
341
342  /// getChar16Width/Align - Return the size of 'char16_t' for this target, in
343  /// bits.
344  unsigned getChar16Width() const { return getTypeWidth(Char16Type); }
345  unsigned getChar16Align() const { return getTypeAlign(Char16Type); }
346
347  /// getChar32Width/Align - Return the size of 'char32_t' for this target, in
348  /// bits.
349  unsigned getChar32Width() const { return getTypeWidth(Char32Type); }
350  unsigned getChar32Align() const { return getTypeAlign(Char32Type); }
351
352  /// getHalfWidth/Align/Format - Return the size/align/format of 'half'.
353  unsigned getHalfWidth() const { return HalfWidth; }
354  unsigned getHalfAlign() const { return HalfAlign; }
355  const llvm::fltSemantics &getHalfFormat() const { return *HalfFormat; }
356
357  /// getFloatWidth/Align/Format - Return the size/align/format of 'float'.
358  unsigned getFloatWidth() const { return FloatWidth; }
359  unsigned getFloatAlign() const { return FloatAlign; }
360  const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; }
361
362  /// getDoubleWidth/Align/Format - Return the size/align/format of 'double'.
363  unsigned getDoubleWidth() const { return DoubleWidth; }
364  unsigned getDoubleAlign() const { return DoubleAlign; }
365  const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; }
366
367  /// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long
368  /// double'.
369  unsigned getLongDoubleWidth() const { return LongDoubleWidth; }
370  unsigned getLongDoubleAlign() const { return LongDoubleAlign; }
371  const llvm::fltSemantics &getLongDoubleFormat() const {
372    return *LongDoubleFormat;
373  }
374
375  /// \brief Return true if the 'long double' type should be mangled like
376  /// __float128.
377  virtual bool useFloat128ManglingForLongDouble() const { return false; }
378
379  /// \brief Return the value for the C99 FLT_EVAL_METHOD macro.
380  virtual unsigned getFloatEvalMethod() const { return 0; }
381
382  // getLargeArrayMinWidth/Align - Return the minimum array size that is
383  // 'large' and its alignment.
384  unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
385  unsigned getLargeArrayAlign() const { return LargeArrayAlign; }
386
387  /// \brief Return the maximum width lock-free atomic operation which will
388  /// ever be supported for the given target
389  unsigned getMaxAtomicPromoteWidth() const { return MaxAtomicPromoteWidth; }
390  /// \brief Return the maximum width lock-free atomic operation which can be
391  /// inlined given the supported features of the given target.
392  unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
393  /// \brief Returns true if the given target supports lock-free atomic
394  /// operations at the specified width and alignment.
395  virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
396                                uint64_t AlignmentInBits) const {
397    return AtomicSizeInBits <= AlignmentInBits &&
398           AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
399           (AtomicSizeInBits <= getCharWidth() ||
400            llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
401  }
402
403  /// \brief Return the maximum vector alignment supported for the given target.
404  unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
405  /// \brief Return default simd alignment for the given target. Generally, this
406  /// value is type-specific, but this alignment can be used for most of the
407  /// types for the given target.
408  unsigned getSimdDefaultAlign() const { return SimdDefaultAlign; }
409
410  /// \brief Return the size of intmax_t and uintmax_t for this target, in bits.
411  unsigned getIntMaxTWidth() const {
412    return getTypeWidth(IntMaxType);
413  }
414
415  // Return the size of unwind_word for this target.
416  unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
417
418  /// \brief Return the "preferred" register width on this target.
419  unsigned getRegisterWidth() const {
420    // Currently we assume the register width on the target matches the pointer
421    // width, we can introduce a new variable for this if/when some target wants
422    // it.
423    return PointerWidth;
424  }
425
426  /// \brief Returns the default value of the __USER_LABEL_PREFIX__ macro,
427  /// which is the prefix given to user symbols by default.
428  ///
429  /// On most platforms this is "_", but it is "" on some, and "." on others.
430  const char *getUserLabelPrefix() const {
431    return UserLabelPrefix;
432  }
433
434  /// \brief Returns the name of the mcount instrumentation function.
435  const char *getMCountName() const {
436    return MCountName;
437  }
438
439  /// \brief Check if the Objective-C built-in boolean type should be signed
440  /// char.
441  ///
442  /// Otherwise, if this returns false, the normal built-in boolean type
443  /// should also be used for Objective-C.
444  bool useSignedCharForObjCBool() const {
445    return UseSignedCharForObjCBool;
446  }
447  void noSignedCharForObjCBool() {
448    UseSignedCharForObjCBool = false;
449  }
450
451  /// \brief Check whether the alignment of bit-field types is respected
452  /// when laying out structures.
453  bool useBitFieldTypeAlignment() const {
454    return UseBitFieldTypeAlignment;
455  }
456
457  /// \brief Check whether zero length bitfields should force alignment of
458  /// the next member.
459  bool useZeroLengthBitfieldAlignment() const {
460    return UseZeroLengthBitfieldAlignment;
461  }
462
463  /// \brief Get the fixed alignment value in bits for a member that follows
464  /// a zero length bitfield.
465  unsigned getZeroLengthBitfieldBoundary() const {
466    return ZeroLengthBitfieldBoundary;
467  }
468
469  /// \brief Check whether this target support '\#pragma options align=mac68k'.
470  bool hasAlignMac68kSupport() const {
471    return HasAlignMac68kSupport;
472  }
473
474  /// \brief Return the user string for the specified integer type enum.
475  ///
476  /// For example, SignedShort -> "short".
477  static const char *getTypeName(IntType T);
478
479  /// \brief Return the constant suffix for the specified integer type enum.
480  ///
481  /// For example, SignedLong -> "L".
482  const char *getTypeConstantSuffix(IntType T) const;
483
484  /// \brief Return the printf format modifier for the specified
485  /// integer type enum.
486  ///
487  /// For example, SignedLong -> "l".
488  static const char *getTypeFormatModifier(IntType T);
489
490  /// \brief Check whether the given real type should use the "fpret" flavor of
491  /// Objective-C message passing on this target.
492  bool useObjCFPRetForRealType(RealType T) const {
493    return RealTypeUsesObjCFPRet & (1 << T);
494  }
495
496  /// \brief Check whether _Complex long double should use the "fp2ret" flavor
497  /// of Objective-C message passing on this target.
498  bool useObjCFP2RetForComplexLongDouble() const {
499    return ComplexLongDoubleUsesFP2Ret;
500  }
501
502  /// \brief Specify if mangling based on address space map should be used or
503  /// not for language specific address spaces
504  bool useAddressSpaceMapMangling() const {
505    return UseAddrSpaceMapMangling;
506  }
507
508  ///===---- Other target property query methods --------------------------===//
509
510  /// \brief Appends the target-specific \#define values for this
511  /// target set to the specified buffer.
512  virtual void getTargetDefines(const LangOptions &Opts,
513                                MacroBuilder &Builder) const = 0;
514
515
516  /// Return information about target-specific builtins for
517  /// the current primary target, and info about which builtins are non-portable
518  /// across the current set of primary and secondary targets.
519  virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
520
521  /// The __builtin_clz* and __builtin_ctz* built-in
522  /// functions are specified to have undefined results for zero inputs, but
523  /// on targets that support these operations in a way that provides
524  /// well-defined results for zero without loss of performance, it is a good
525  /// idea to avoid optimizing based on that undef behavior.
526  virtual bool isCLZForZeroUndef() const { return true; }
527
528  /// \brief Returns the kind of __builtin_va_list type that should be used
529  /// with this target.
530  virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
531
532  /// Returns whether or not type \c __builtin_ms_va_list type is
533  /// available on this target.
534  bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
535
536  /// \brief Returns whether the passed in string is a valid clobber in an
537  /// inline asm statement.
538  ///
539  /// This is used by Sema.
540  bool isValidClobber(StringRef Name) const;
541
542  /// \brief Returns whether the passed in string is a valid register name
543  /// according to GCC.
544  ///
545  /// This is used by Sema for inline asm statements.
546  bool isValidGCCRegisterName(StringRef Name) const;
547
548  /// \brief Returns the "normalized" GCC register name.
549  ///
550  /// For example, on x86 it will return "ax" when "eax" is passed in.
551  StringRef getNormalizedGCCRegisterName(StringRef Name) const;
552
553  struct ConstraintInfo {
554    enum {
555      CI_None = 0x00,
556      CI_AllowsMemory = 0x01,
557      CI_AllowsRegister = 0x02,
558      CI_ReadWrite = 0x04,         // "+r" output constraint (read and write).
559      CI_HasMatchingInput = 0x08,  // This output operand has a matching input.
560      CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
561      CI_EarlyClobber = 0x20,      // "&" output constraint (early clobber).
562    };
563    unsigned Flags;
564    int TiedOperand;
565    struct {
566      int Min;
567      int Max;
568    } ImmRange;
569    llvm::SmallSet<int, 4> ImmSet;
570
571    std::string ConstraintStr;  // constraint: "=rm"
572    std::string Name;           // Operand name: [foo] with no []'s.
573  public:
574    ConstraintInfo(StringRef ConstraintStr, StringRef Name)
575        : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
576          Name(Name.str()) {
577      ImmRange.Min = ImmRange.Max = 0;
578    }
579
580    const std::string &getConstraintStr() const { return ConstraintStr; }
581    const std::string &getName() const { return Name; }
582    bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
583    bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
584    bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
585    bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
586
587    /// \brief Return true if this output operand has a matching
588    /// (tied) input operand.
589    bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; }
590
591    /// \brief Return true if this input operand is a matching
592    /// constraint that ties it to an output operand.
593    ///
594    /// If this returns true then getTiedOperand will indicate which output
595    /// operand this is tied to.
596    bool hasTiedOperand() const { return TiedOperand != -1; }
597    unsigned getTiedOperand() const {
598      assert(hasTiedOperand() && "Has no tied operand!");
599      return (unsigned)TiedOperand;
600    }
601
602    bool requiresImmediateConstant() const {
603      return (Flags & CI_ImmediateConstant) != 0;
604    }
605    bool isValidAsmImmediate(const llvm::APInt &Value) const {
606      return (Value.sge(ImmRange.Min) && Value.sle(ImmRange.Max)) ||
607             ImmSet.count(Value.getZExtValue()) != 0;
608    }
609
610    void setIsReadWrite() { Flags |= CI_ReadWrite; }
611    void setEarlyClobber() { Flags |= CI_EarlyClobber; }
612    void setAllowsMemory() { Flags |= CI_AllowsMemory; }
613    void setAllowsRegister() { Flags |= CI_AllowsRegister; }
614    void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
615    void setRequiresImmediate(int Min, int Max) {
616      Flags |= CI_ImmediateConstant;
617      ImmRange.Min = Min;
618      ImmRange.Max = Max;
619    }
620    void setRequiresImmediate(llvm::ArrayRef<int> Exacts) {
621      Flags |= CI_ImmediateConstant;
622      for (int Exact : Exacts)
623        ImmSet.insert(Exact);
624    }
625    void setRequiresImmediate(int Exact) {
626      Flags |= CI_ImmediateConstant;
627      ImmSet.insert(Exact);
628    }
629    void setRequiresImmediate() {
630      Flags |= CI_ImmediateConstant;
631      ImmRange.Min = INT_MIN;
632      ImmRange.Max = INT_MAX;
633    }
634
635    /// \brief Indicate that this is an input operand that is tied to
636    /// the specified output operand.
637    ///
638    /// Copy over the various constraint information from the output.
639    void setTiedOperand(unsigned N, ConstraintInfo &Output) {
640      Output.setHasMatchingInput();
641      Flags = Output.Flags;
642      TiedOperand = N;
643      // Don't copy Name or constraint string.
644    }
645  };
646
647  /// \brief Validate register name used for global register variables.
648  ///
649  /// This function returns true if the register passed in RegName can be used
650  /// for global register variables on this target. In addition, it returns
651  /// true in HasSizeMismatch if the size of the register doesn't match the
652  /// variable size passed in RegSize.
653  virtual bool validateGlobalRegisterVariable(StringRef RegName,
654                                              unsigned RegSize,
655                                              bool &HasSizeMismatch) const {
656    HasSizeMismatch = false;
657    return true;
658  }
659
660  // validateOutputConstraint, validateInputConstraint - Checks that
661  // a constraint is valid and provides information about it.
662  // FIXME: These should return a real error instead of just true/false.
663  bool validateOutputConstraint(ConstraintInfo &Info) const;
664  bool validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,
665                               ConstraintInfo &info) const;
666
667  virtual bool validateOutputSize(StringRef /*Constraint*/,
668                                  unsigned /*Size*/) const {
669    return true;
670  }
671
672  virtual bool validateInputSize(StringRef /*Constraint*/,
673                                 unsigned /*Size*/) const {
674    return true;
675  }
676  virtual bool
677  validateConstraintModifier(StringRef /*Constraint*/,
678                             char /*Modifier*/,
679                             unsigned /*Size*/,
680                             std::string &/*SuggestedModifier*/) const {
681    return true;
682  }
683  virtual bool
684  validateAsmConstraint(const char *&Name,
685                        TargetInfo::ConstraintInfo &info) const = 0;
686
687  bool resolveSymbolicName(const char *&Name,
688                           ArrayRef<ConstraintInfo> OutputConstraints,
689                           unsigned &Index) const;
690
691  // Constraint parm will be left pointing at the last character of
692  // the constraint.  In practice, it won't be changed unless the
693  // constraint is longer than one character.
694  virtual std::string convertConstraint(const char *&Constraint) const {
695    // 'p' defaults to 'r', but can be overridden by targets.
696    if (*Constraint == 'p')
697      return std::string("r");
698    return std::string(1, *Constraint);
699  }
700
701  /// \brief Returns a string of target-specific clobbers, in LLVM format.
702  virtual const char *getClobbers() const = 0;
703
704  /// \brief Returns true if NaN encoding is IEEE 754-2008.
705  /// Only MIPS allows a different encoding.
706  virtual bool isNan2008() const {
707    return true;
708  }
709
710  /// \brief Returns the target triple of the primary target.
711  const llvm::Triple &getTriple() const {
712    return Triple;
713  }
714
715  const char *getDataLayoutString() const {
716    assert(DataLayoutString && "Uninitialized DataLayoutString!");
717    return DataLayoutString;
718  }
719
720  struct GCCRegAlias {
721    const char * const Aliases[5];
722    const char * const Register;
723  };
724
725  struct AddlRegName {
726    const char * const Names[5];
727    const unsigned RegNum;
728  };
729
730  /// \brief Does this target support "protected" visibility?
731  ///
732  /// Any target which dynamic libraries will naturally support
733  /// something like "default" (meaning that the symbol is visible
734  /// outside this shared object) and "hidden" (meaning that it isn't)
735  /// visibilities, but "protected" is really an ELF-specific concept
736  /// with weird semantics designed around the convenience of dynamic
737  /// linker implementations.  Which is not to suggest that there's
738  /// consistent target-independent semantics for "default" visibility
739  /// either; the entire thing is pretty badly mangled.
740  virtual bool hasProtectedVisibility() const { return true; }
741
742  /// \brief An optional hook that targets can implement to perform semantic
743  /// checking on attribute((section("foo"))) specifiers.
744  ///
745  /// In this case, "foo" is passed in to be checked.  If the section
746  /// specifier is invalid, the backend should return a non-empty string
747  /// that indicates the problem.
748  ///
749  /// This hook is a simple quality of implementation feature to catch errors
750  /// and give good diagnostics in cases when the assembler or code generator
751  /// would otherwise reject the section specifier.
752  ///
753  virtual std::string isValidSectionSpecifier(StringRef SR) const {
754    return "";
755  }
756
757  /// \brief Set forced language options.
758  ///
759  /// Apply changes to the target information with respect to certain
760  /// language options which change the target configuration.
761  virtual void adjust(const LangOptions &Opts);
762
763  /// \brief Initialize the map with the default set of target features for the
764  /// CPU this should include all legal feature strings on the target.
765  ///
766  /// \return False on error (invalid features).
767  virtual bool initFeatureMap(llvm::StringMap<bool> &Features,
768                              DiagnosticsEngine &Diags, StringRef CPU,
769                              const std::vector<std::string> &FeatureVec) const;
770
771  /// \brief Get the ABI currently in use.
772  virtual StringRef getABI() const { return StringRef(); }
773
774  /// \brief Get the C++ ABI currently in use.
775  TargetCXXABI getCXXABI() const {
776    return TheCXXABI;
777  }
778
779  /// \brief Target the specified CPU.
780  ///
781  /// \return  False on error (invalid CPU name).
782  virtual bool setCPU(const std::string &Name) {
783    return false;
784  }
785
786  /// \brief Use the specified ABI.
787  ///
788  /// \return False on error (invalid ABI name).
789  virtual bool setABI(const std::string &Name) {
790    return false;
791  }
792
793  /// \brief Use the specified unit for FP math.
794  ///
795  /// \return False on error (invalid unit name).
796  virtual bool setFPMath(StringRef Name) {
797    return false;
798  }
799
800  /// \brief Enable or disable a specific target feature;
801  /// the feature name must be valid.
802  virtual void setFeatureEnabled(llvm::StringMap<bool> &Features,
803                                 StringRef Name,
804                                 bool Enabled) const {
805    Features[Name] = Enabled;
806  }
807
808  /// \brief Perform initialization based on the user configured
809  /// set of features (e.g., +sse4).
810  ///
811  /// The list is guaranteed to have at most one entry per feature.
812  ///
813  /// The target may modify the features list, to change which options are
814  /// passed onwards to the backend.
815  /// FIXME: This part should be fixed so that we can change handleTargetFeatures
816  /// to merely a TargetInfo initialization routine.
817  ///
818  /// \return  False on error.
819  virtual bool handleTargetFeatures(std::vector<std::string> &Features,
820                                    DiagnosticsEngine &Diags) {
821    return true;
822  }
823
824  /// \brief Determine whether the given target has the given feature.
825  virtual bool hasFeature(StringRef Feature) const {
826    return false;
827  }
828
829  // \brief Validate the contents of the __builtin_cpu_supports(const char*)
830  // argument.
831  virtual bool validateCpuSupports(StringRef Name) const { return false; }
832
833  // \brief Returns maximal number of args passed in registers.
834  unsigned getRegParmMax() const {
835    assert(RegParmMax < 7 && "RegParmMax value is larger than AST can handle");
836    return RegParmMax;
837  }
838
839  /// \brief Whether the target supports thread-local storage.
840  bool isTLSSupported() const {
841    return TLSSupported;
842  }
843
844  /// \brief Return the maximum alignment (in bits) of a TLS variable
845  ///
846  /// Gets the maximum alignment (in bits) of a TLS variable on this target.
847  /// Returns zero if there is no such constraint.
848  unsigned short getMaxTLSAlign() const {
849    return MaxTLSAlign;
850  }
851
852  /// \brief Whether the target supports SEH __try.
853  bool isSEHTrySupported() const {
854    return getTriple().isOSWindows() &&
855           (getTriple().getArch() == llvm::Triple::x86 ||
856            getTriple().getArch() == llvm::Triple::x86_64);
857  }
858
859  /// \brief Return true if {|} are normal characters in the asm string.
860  ///
861  /// If this returns false (the default), then {abc|xyz} is syntax
862  /// that says that when compiling for asm variant #0, "abc" should be
863  /// generated, but when compiling for asm variant #1, "xyz" should be
864  /// generated.
865  bool hasNoAsmVariants() const {
866    return NoAsmVariants;
867  }
868
869  /// \brief Return the register number that __builtin_eh_return_regno would
870  /// return with the specified argument.
871  virtual int getEHDataRegisterNumber(unsigned RegNo) const {
872    return -1;
873  }
874
875  /// \brief Return the section to use for C++ static initialization functions.
876  virtual const char *getStaticInitSectionSpecifier() const {
877    return nullptr;
878  }
879
880  const LangAS::Map &getAddressSpaceMap() const {
881    return *AddrSpaceMap;
882  }
883
884  /// \brief Retrieve the name of the platform as it is used in the
885  /// availability attribute.
886  StringRef getPlatformName() const { return PlatformName; }
887
888  /// \brief Retrieve the minimum desired version of the platform, to
889  /// which the program should be compiled.
890  VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
891
892  bool isBigEndian() const { return BigEndian; }
893
894  enum CallingConvMethodType {
895    CCMT_Unknown,
896    CCMT_Member,
897    CCMT_NonMember
898  };
899
900  /// \brief Gets the default calling convention for the given target and
901  /// declaration context.
902  virtual CallingConv getDefaultCallingConv(CallingConvMethodType MT) const {
903    // Not all targets will specify an explicit calling convention that we can
904    // express.  This will always do the right thing, even though it's not
905    // an explicit calling convention.
906    return CC_C;
907  }
908
909  enum CallingConvCheckResult {
910    CCCR_OK,
911    CCCR_Warning,
912    CCCR_Ignore,
913  };
914
915  /// \brief Determines whether a given calling convention is valid for the
916  /// target. A calling convention can either be accepted, produce a warning
917  /// and be substituted with the default calling convention, or (someday)
918  /// produce an error (such as using thiscall on a non-instance function).
919  virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const {
920    switch (CC) {
921      default:
922        return CCCR_Warning;
923      case CC_C:
924        return CCCR_OK;
925    }
926  }
927
928  /// Controls if __builtin_longjmp / __builtin_setjmp can be lowered to
929  /// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp.
930  virtual bool hasSjLjLowering() const {
931    return false;
932  }
933
934protected:
935  virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
936    return PointerWidth;
937  }
938  virtual uint64_t getPointerAlignV(unsigned AddrSpace) const {
939    return PointerAlign;
940  }
941  virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const {
942    return PtrDiffType;
943  }
944  virtual ArrayRef<const char *> getGCCRegNames() const = 0;
945  virtual ArrayRef<GCCRegAlias> getGCCRegAliases() const = 0;
946  virtual ArrayRef<AddlRegName> getGCCAddlRegNames() const {
947    return None;
948  }
949};
950
951}  // end namespace clang
952
953#endif
954