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