1 //===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Defines the clang::TargetInfo interface.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_BASIC_TARGETINFO_H
15 #define LLVM_CLANG_BASIC_TARGETINFO_H
16 
17 #include "clang/Basic/AddressSpaces.h"
18 #include "clang/Basic/CodeGenOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "clang/Basic/TargetCXXABI.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/IntrusiveRefCntPtr.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
34 #include "llvm/Support/DataTypes.h"
35 #include "llvm/Support/VersionTuple.h"
36 #include <cassert>
37 #include <string>
38 #include <vector>
39 
40 namespace llvm {
41 struct fltSemantics;
42 class DataLayout;
43 }
44 
45 namespace clang {
46 class DiagnosticsEngine;
47 class LangOptions;
48 class CodeGenOptions;
49 class MacroBuilder;
50 class QualType;
51 class SourceLocation;
52 class SourceManager;
53 
54 namespace Builtin { struct Info; }
55 
56 /// Fields controlling how types are laid out in memory; these may need to
57 /// be copied for targets like AMDGPU that base their ABIs on an auxiliary
58 /// CPU target.
59 struct TransferrableTargetInfo {
60   unsigned char PointerWidth, PointerAlign;
61   unsigned char BoolWidth, BoolAlign;
62   unsigned char IntWidth, IntAlign;
63   unsigned char HalfWidth, HalfAlign;
64   unsigned char BFloat16Width, BFloat16Align;
65   unsigned char FloatWidth, FloatAlign;
66   unsigned char DoubleWidth, DoubleAlign;
67   unsigned char LongDoubleWidth, LongDoubleAlign, Float128Align;
68   unsigned char LargeArrayMinWidth, LargeArrayAlign;
69   unsigned char LongWidth, LongAlign;
70   unsigned char LongLongWidth, LongLongAlign;
71 
72   // Fixed point bit widths
73   unsigned char ShortAccumWidth, ShortAccumAlign;
74   unsigned char AccumWidth, AccumAlign;
75   unsigned char LongAccumWidth, LongAccumAlign;
76   unsigned char ShortFractWidth, ShortFractAlign;
77   unsigned char FractWidth, FractAlign;
78   unsigned char LongFractWidth, LongFractAlign;
79 
80   // If true, unsigned fixed point types have the same number of fractional bits
81   // as their signed counterparts, forcing the unsigned types to have one extra
82   // bit of padding. Otherwise, unsigned fixed point types have
83   // one more fractional bit than its corresponding signed type. This is false
84   // by default.
85   bool PaddingOnUnsignedFixedPoint;
86 
87   // Fixed point integral and fractional bit sizes
88   // Saturated types share the same integral/fractional bits as their
89   // corresponding unsaturated types.
90   // For simplicity, the fractional bits in a _Fract type will be one less the
91   // width of that _Fract type. This leaves all signed _Fract types having no
92   // padding and unsigned _Fract types will only have 1 bit of padding after the
93   // sign if PaddingOnUnsignedFixedPoint is set.
94   unsigned char ShortAccumScale;
95   unsigned char AccumScale;
96   unsigned char LongAccumScale;
97 
98   unsigned char SuitableAlign;
99   unsigned char DefaultAlignForAttributeAligned;
100   unsigned char MinGlobalAlign;
101 
102   unsigned short NewAlign;
103   unsigned short MaxVectorAlign;
104   unsigned short MaxTLSAlign;
105 
106   const llvm::fltSemantics *HalfFormat, *BFloat16Format, *FloatFormat,
107     *DoubleFormat, *LongDoubleFormat, *Float128Format;
108 
109   ///===---- Target Data Type Query Methods -------------------------------===//
110   enum IntType {
111     NoInt = 0,
112     SignedChar,
113     UnsignedChar,
114     SignedShort,
115     UnsignedShort,
116     SignedInt,
117     UnsignedInt,
118     SignedLong,
119     UnsignedLong,
120     SignedLongLong,
121     UnsignedLongLong
122   };
123 
124   enum RealType {
125     NoFloat = 255,
126     Float = 0,
127     Double,
128     LongDouble,
129     Float128
130   };
131 protected:
132   IntType SizeType, IntMaxType, PtrDiffType, IntPtrType, WCharType,
133           WIntType, Char16Type, Char32Type, Int64Type, SigAtomicType,
134           ProcessIDType;
135 
136   /// Whether Objective-C's built-in boolean type should be signed char.
137   ///
138   /// Otherwise, when this flag is not set, the normal built-in boolean type is
139   /// used.
140   unsigned UseSignedCharForObjCBool : 1;
141 
142   /// Control whether the alignment of bit-field types is respected when laying
143   /// out structures. If true, then the alignment of the bit-field type will be
144   /// used to (a) impact the alignment of the containing structure, and (b)
145   /// ensure that the individual bit-field will not straddle an alignment
146   /// boundary.
147   unsigned UseBitFieldTypeAlignment : 1;
148 
149   /// Whether zero length bitfields (e.g., int : 0;) force alignment of
150   /// the next bitfield.
151   ///
152   /// If the alignment of the zero length bitfield is greater than the member
153   /// that follows it, `bar', `bar' will be aligned as the type of the
154   /// zero-length bitfield.
155   unsigned UseZeroLengthBitfieldAlignment : 1;
156 
157   ///  Whether explicit bit field alignment attributes are honored.
158   unsigned UseExplicitBitFieldAlignment : 1;
159 
160   /// If non-zero, specifies a fixed alignment value for bitfields that follow
161   /// zero length bitfield, regardless of the zero length bitfield type.
162   unsigned ZeroLengthBitfieldBoundary;
163 };
164 
165 /// OpenCL type kinds.
166 enum OpenCLTypeKind : uint8_t {
167   OCLTK_Default,
168   OCLTK_ClkEvent,
169   OCLTK_Event,
170   OCLTK_Image,
171   OCLTK_Pipe,
172   OCLTK_Queue,
173   OCLTK_ReserveID,
174   OCLTK_Sampler,
175 };
176 
177 /// Exposes information about the current target.
178 ///
179 class TargetInfo : public virtual TransferrableTargetInfo,
180                    public RefCountedBase<TargetInfo> {
181   std::shared_ptr<TargetOptions> TargetOpts;
182   llvm::Triple Triple;
183 protected:
184   // Target values set by the ctor of the actual target implementation.  Default
185   // values are specified by the TargetInfo constructor.
186   bool BigEndian;
187   bool TLSSupported;
188   bool VLASupported;
189   bool NoAsmVariants;  // True if {|} are normal characters.
190   bool HasLegalHalfType; // True if the backend supports operations on the half
191                          // LLVM IR type.
192   bool HasFloat128;
193   bool HasFloat16;
194   bool HasBFloat16;
195   bool HasStrictFP;
196 
197   unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
198   unsigned short SimdDefaultAlign;
199   std::unique_ptr<llvm::DataLayout> DataLayout;
200   const char *MCountName;
201   unsigned char RegParmMax, SSERegParmMax;
202   TargetCXXABI TheCXXABI;
203   const LangASMap *AddrSpaceMap;
204   const unsigned *GridValues =
205       nullptr; // Array of target-specific GPU grid values that must be
206                // consistent between host RTL (plugin), device RTL, and clang.
207 
208   mutable StringRef PlatformName;
209   mutable VersionTuple PlatformMinVersion;
210 
211   unsigned HasAlignMac68kSupport : 1;
212   unsigned RealTypeUsesObjCFPRet : 3;
213   unsigned ComplexLongDoubleUsesFP2Ret : 1;
214 
215   unsigned HasBuiltinMSVaList : 1;
216 
217   unsigned IsRenderScriptTarget : 1;
218 
219   unsigned HasAArch64SVETypes : 1;
220 
221   unsigned ARMCDECoprocMask : 8;
222 
223   unsigned MaxOpenCLWorkGroupSize;
224 
225   // TargetInfo Constructor.  Default initializes all fields.
226   TargetInfo(const llvm::Triple &T);
227 
228   void resetDataLayout(StringRef DL);
229 
230 public:
231   /// Construct a target for the given options.
232   ///
233   /// \param Opts - The options to use to initialize the target. The target may
234   /// modify the options to canonicalize the target feature information to match
235   /// what the backend expects.
236   static TargetInfo *
237   CreateTargetInfo(DiagnosticsEngine &Diags,
238                    const std::shared_ptr<TargetOptions> &Opts);
239 
240   virtual ~TargetInfo();
241 
242   /// Retrieve the target options.
getTargetOpts()243   TargetOptions &getTargetOpts() const {
244     assert(TargetOpts && "Missing target options");
245     return *TargetOpts;
246   }
247 
248   /// The different kinds of __builtin_va_list types defined by
249   /// the target implementation.
250   enum BuiltinVaListKind {
251     /// typedef char* __builtin_va_list;
252     CharPtrBuiltinVaList = 0,
253 
254     /// typedef void* __builtin_va_list;
255     VoidPtrBuiltinVaList,
256 
257     /// __builtin_va_list as defined by the AArch64 ABI
258     /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
259     AArch64ABIBuiltinVaList,
260 
261     /// __builtin_va_list as defined by the PNaCl ABI:
262     /// http://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Machine-Types
263     PNaClABIBuiltinVaList,
264 
265     /// __builtin_va_list as defined by the Power ABI:
266     /// https://www.power.org
267     ///        /resources/downloads/Power-Arch-32-bit-ABI-supp-1.0-Embedded.pdf
268     PowerABIBuiltinVaList,
269 
270     /// __builtin_va_list as defined by the x86-64 ABI:
271     /// http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
272     X86_64ABIBuiltinVaList,
273 
274     /// __builtin_va_list as defined by ARM AAPCS ABI
275     /// http://infocenter.arm.com
276     //        /help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
277     AAPCSABIBuiltinVaList,
278 
279     // typedef struct __va_list_tag
280     //   {
281     //     long __gpr;
282     //     long __fpr;
283     //     void *__overflow_arg_area;
284     //     void *__reg_save_area;
285     //   } va_list[1];
286     SystemZBuiltinVaList,
287 
288     // typedef struct __va_list_tag {
289     //    void *__current_saved_reg_area_pointer;
290     //    void *__saved_reg_area_end_pointer;
291     //    void *__overflow_area_pointer;
292     //} va_list;
293     HexagonBuiltinVaList
294   };
295 
296 protected:
297   /// Specify if mangling based on address space map should be used or
298   /// not for language specific address spaces
299   bool UseAddrSpaceMapMangling;
300 
301 public:
getSizeType()302   IntType getSizeType() const { return SizeType; }
getSignedSizeType()303   IntType getSignedSizeType() const {
304     switch (SizeType) {
305     case UnsignedShort:
306       return SignedShort;
307     case UnsignedInt:
308       return SignedInt;
309     case UnsignedLong:
310       return SignedLong;
311     case UnsignedLongLong:
312       return SignedLongLong;
313     default:
314       llvm_unreachable("Invalid SizeType");
315     }
316   }
getIntMaxType()317   IntType getIntMaxType() const { return IntMaxType; }
getUIntMaxType()318   IntType getUIntMaxType() const {
319     return getCorrespondingUnsignedType(IntMaxType);
320   }
getPtrDiffType(unsigned AddrSpace)321   IntType getPtrDiffType(unsigned AddrSpace) const {
322     return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
323   }
getUnsignedPtrDiffType(unsigned AddrSpace)324   IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
325     return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
326   }
getIntPtrType()327   IntType getIntPtrType() const { return IntPtrType; }
getUIntPtrType()328   IntType getUIntPtrType() const {
329     return getCorrespondingUnsignedType(IntPtrType);
330   }
getWCharType()331   IntType getWCharType() const { return WCharType; }
getWIntType()332   IntType getWIntType() const { return WIntType; }
getChar16Type()333   IntType getChar16Type() const { return Char16Type; }
getChar32Type()334   IntType getChar32Type() const { return Char32Type; }
getInt64Type()335   IntType getInt64Type() const { return Int64Type; }
getUInt64Type()336   IntType getUInt64Type() const {
337     return getCorrespondingUnsignedType(Int64Type);
338   }
getSigAtomicType()339   IntType getSigAtomicType() const { return SigAtomicType; }
getProcessIDType()340   IntType getProcessIDType() const { return ProcessIDType; }
341 
getCorrespondingUnsignedType(IntType T)342   static IntType getCorrespondingUnsignedType(IntType T) {
343     switch (T) {
344     case SignedChar:
345       return UnsignedChar;
346     case SignedShort:
347       return UnsignedShort;
348     case SignedInt:
349       return UnsignedInt;
350     case SignedLong:
351       return UnsignedLong;
352     case SignedLongLong:
353       return UnsignedLongLong;
354     default:
355       llvm_unreachable("Unexpected signed integer type");
356     }
357   }
358 
359   /// In the event this target uses the same number of fractional bits for its
360   /// unsigned types as it does with its signed counterparts, there will be
361   /// exactly one bit of padding.
362   /// Return true if unsigned fixed point types have padding for this target.
doUnsignedFixedPointTypesHavePadding()363   bool doUnsignedFixedPointTypesHavePadding() const {
364     return PaddingOnUnsignedFixedPoint;
365   }
366 
367   /// Return the width (in bits) of the specified integer type enum.
368   ///
369   /// For example, SignedInt -> getIntWidth().
370   unsigned getTypeWidth(IntType T) const;
371 
372   /// Return integer type with specified width.
373   virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const;
374 
375   /// Return the smallest integer type with at least the specified width.
376   virtual IntType getLeastIntTypeByWidth(unsigned BitWidth,
377                                          bool IsSigned) const;
378 
379   /// Return floating point type with specified width. On PPC, there are
380   /// three possible types for 128-bit floating point: "PPC double-double",
381   /// IEEE 754R quad precision, and "long double" (which under the covers
382   /// is represented as one of those two). At this time, there is no support
383   /// for an explicit "PPC double-double" type (i.e. __ibm128) so we only
384   /// need to differentiate between "long double" and IEEE quad precision.
385   RealType getRealTypeByWidth(unsigned BitWidth, bool ExplicitIEEE) const;
386 
387   /// Return the alignment (in bits) of the specified integer type enum.
388   ///
389   /// For example, SignedInt -> getIntAlign().
390   unsigned getTypeAlign(IntType T) const;
391 
392   /// Returns true if the type is signed; false otherwise.
393   static bool isTypeSigned(IntType T);
394 
395   /// Return the width of pointers on this target, for the
396   /// specified address space.
getPointerWidth(unsigned AddrSpace)397   uint64_t getPointerWidth(unsigned AddrSpace) const {
398     return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
399   }
getPointerAlign(unsigned AddrSpace)400   uint64_t getPointerAlign(unsigned AddrSpace) const {
401     return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
402   }
403 
404   /// Return the maximum width of pointers on this target.
getMaxPointerWidth()405   virtual uint64_t getMaxPointerWidth() const {
406     return PointerWidth;
407   }
408 
409   /// Get integer value for null pointer.
410   /// \param AddrSpace address space of pointee in source language.
getNullPointerValue(LangAS AddrSpace)411   virtual uint64_t getNullPointerValue(LangAS AddrSpace) const { return 0; }
412 
413   /// Return the size of '_Bool' and C++ 'bool' for this target, in bits.
getBoolWidth()414   unsigned getBoolWidth() const { return BoolWidth; }
415 
416   /// Return the alignment of '_Bool' and C++ 'bool' for this target.
getBoolAlign()417   unsigned getBoolAlign() const { return BoolAlign; }
418 
getCharWidth()419   unsigned getCharWidth() const { return 8; } // FIXME
getCharAlign()420   unsigned getCharAlign() const { return 8; } // FIXME
421 
422   /// Return the size of 'signed short' and 'unsigned short' for this
423   /// target, in bits.
getShortWidth()424   unsigned getShortWidth() const { return 16; } // FIXME
425 
426   /// Return the alignment of 'signed short' and 'unsigned short' for
427   /// this target.
getShortAlign()428   unsigned getShortAlign() const { return 16; } // FIXME
429 
430   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for
431   /// this target, in bits.
getIntWidth()432   unsigned getIntWidth() const { return IntWidth; }
getIntAlign()433   unsigned getIntAlign() const { return IntAlign; }
434 
435   /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long'
436   /// for this target, in bits.
getLongWidth()437   unsigned getLongWidth() const { return LongWidth; }
getLongAlign()438   unsigned getLongAlign() const { return LongAlign; }
439 
440   /// getLongLongWidth/Align - Return the size of 'signed long long' and
441   /// 'unsigned long long' for this target, in bits.
getLongLongWidth()442   unsigned getLongLongWidth() const { return LongLongWidth; }
getLongLongAlign()443   unsigned getLongLongAlign() const { return LongLongAlign; }
444 
445   /// getShortAccumWidth/Align - Return the size of 'signed short _Accum' and
446   /// 'unsigned short _Accum' for this target, in bits.
getShortAccumWidth()447   unsigned getShortAccumWidth() const { return ShortAccumWidth; }
getShortAccumAlign()448   unsigned getShortAccumAlign() const { return ShortAccumAlign; }
449 
450   /// getAccumWidth/Align - Return the size of 'signed _Accum' and
451   /// 'unsigned _Accum' for this target, in bits.
getAccumWidth()452   unsigned getAccumWidth() const { return AccumWidth; }
getAccumAlign()453   unsigned getAccumAlign() const { return AccumAlign; }
454 
455   /// getLongAccumWidth/Align - Return the size of 'signed long _Accum' and
456   /// 'unsigned long _Accum' for this target, in bits.
getLongAccumWidth()457   unsigned getLongAccumWidth() const { return LongAccumWidth; }
getLongAccumAlign()458   unsigned getLongAccumAlign() const { return LongAccumAlign; }
459 
460   /// getShortFractWidth/Align - Return the size of 'signed short _Fract' and
461   /// 'unsigned short _Fract' for this target, in bits.
getShortFractWidth()462   unsigned getShortFractWidth() const { return ShortFractWidth; }
getShortFractAlign()463   unsigned getShortFractAlign() const { return ShortFractAlign; }
464 
465   /// getFractWidth/Align - Return the size of 'signed _Fract' and
466   /// 'unsigned _Fract' for this target, in bits.
getFractWidth()467   unsigned getFractWidth() const { return FractWidth; }
getFractAlign()468   unsigned getFractAlign() const { return FractAlign; }
469 
470   /// getLongFractWidth/Align - Return the size of 'signed long _Fract' and
471   /// 'unsigned long _Fract' for this target, in bits.
getLongFractWidth()472   unsigned getLongFractWidth() const { return LongFractWidth; }
getLongFractAlign()473   unsigned getLongFractAlign() const { return LongFractAlign; }
474 
475   /// getShortAccumScale/IBits - Return the number of fractional/integral bits
476   /// in a 'signed short _Accum' type.
getShortAccumScale()477   unsigned getShortAccumScale() const { return ShortAccumScale; }
getShortAccumIBits()478   unsigned getShortAccumIBits() const {
479     return ShortAccumWidth - ShortAccumScale - 1;
480   }
481 
482   /// getAccumScale/IBits - Return the number of fractional/integral bits
483   /// in a 'signed _Accum' type.
getAccumScale()484   unsigned getAccumScale() const { return AccumScale; }
getAccumIBits()485   unsigned getAccumIBits() const { return AccumWidth - AccumScale - 1; }
486 
487   /// getLongAccumScale/IBits - Return the number of fractional/integral bits
488   /// in a 'signed long _Accum' type.
getLongAccumScale()489   unsigned getLongAccumScale() const { return LongAccumScale; }
getLongAccumIBits()490   unsigned getLongAccumIBits() const {
491     return LongAccumWidth - LongAccumScale - 1;
492   }
493 
494   /// getUnsignedShortAccumScale/IBits - Return the number of
495   /// fractional/integral bits in a 'unsigned short _Accum' type.
getUnsignedShortAccumScale()496   unsigned getUnsignedShortAccumScale() const {
497     return PaddingOnUnsignedFixedPoint ? ShortAccumScale : ShortAccumScale + 1;
498   }
getUnsignedShortAccumIBits()499   unsigned getUnsignedShortAccumIBits() const {
500     return PaddingOnUnsignedFixedPoint
501                ? getShortAccumIBits()
502                : ShortAccumWidth - getUnsignedShortAccumScale();
503   }
504 
505   /// getUnsignedAccumScale/IBits - Return the number of fractional/integral
506   /// bits in a 'unsigned _Accum' type.
getUnsignedAccumScale()507   unsigned getUnsignedAccumScale() const {
508     return PaddingOnUnsignedFixedPoint ? AccumScale : AccumScale + 1;
509   }
getUnsignedAccumIBits()510   unsigned getUnsignedAccumIBits() const {
511     return PaddingOnUnsignedFixedPoint ? getAccumIBits()
512                                        : AccumWidth - getUnsignedAccumScale();
513   }
514 
515   /// getUnsignedLongAccumScale/IBits - Return the number of fractional/integral
516   /// bits in a 'unsigned long _Accum' type.
getUnsignedLongAccumScale()517   unsigned getUnsignedLongAccumScale() const {
518     return PaddingOnUnsignedFixedPoint ? LongAccumScale : LongAccumScale + 1;
519   }
getUnsignedLongAccumIBits()520   unsigned getUnsignedLongAccumIBits() const {
521     return PaddingOnUnsignedFixedPoint
522                ? getLongAccumIBits()
523                : LongAccumWidth - getUnsignedLongAccumScale();
524   }
525 
526   /// getShortFractScale - Return the number of fractional bits
527   /// in a 'signed short _Fract' type.
getShortFractScale()528   unsigned getShortFractScale() const { return ShortFractWidth - 1; }
529 
530   /// getFractScale - Return the number of fractional bits
531   /// in a 'signed _Fract' type.
getFractScale()532   unsigned getFractScale() const { return FractWidth - 1; }
533 
534   /// getLongFractScale - Return the number of fractional bits
535   /// in a 'signed long _Fract' type.
getLongFractScale()536   unsigned getLongFractScale() const { return LongFractWidth - 1; }
537 
538   /// getUnsignedShortFractScale - Return the number of fractional bits
539   /// in a 'unsigned short _Fract' type.
getUnsignedShortFractScale()540   unsigned getUnsignedShortFractScale() const {
541     return PaddingOnUnsignedFixedPoint ? getShortFractScale()
542                                        : getShortFractScale() + 1;
543   }
544 
545   /// getUnsignedFractScale - Return the number of fractional bits
546   /// in a 'unsigned _Fract' type.
getUnsignedFractScale()547   unsigned getUnsignedFractScale() const {
548     return PaddingOnUnsignedFixedPoint ? getFractScale() : getFractScale() + 1;
549   }
550 
551   /// getUnsignedLongFractScale - Return the number of fractional bits
552   /// in a 'unsigned long _Fract' type.
getUnsignedLongFractScale()553   unsigned getUnsignedLongFractScale() const {
554     return PaddingOnUnsignedFixedPoint ? getLongFractScale()
555                                        : getLongFractScale() + 1;
556   }
557 
558   /// Determine whether the __int128 type is supported on this target.
hasInt128Type()559   virtual bool hasInt128Type() const {
560     return (getPointerWidth(0) >= 64) || getTargetOpts().ForceEnableInt128;
561   } // FIXME
562 
563   /// Determine whether the _ExtInt type is supported on this target. This
564   /// limitation is put into place for ABI reasons.
hasExtIntType()565   virtual bool hasExtIntType() const {
566     return false;
567   }
568 
569   /// Determine whether _Float16 is supported on this target.
hasLegalHalfType()570   virtual bool hasLegalHalfType() const { return HasLegalHalfType; }
571 
572   /// Determine whether the __float128 type is supported on this target.
hasFloat128Type()573   virtual bool hasFloat128Type() const { return HasFloat128; }
574 
575   /// Determine whether the _Float16 type is supported on this target.
hasFloat16Type()576   virtual bool hasFloat16Type() const { return HasFloat16; }
577 
578   /// Determine whether the _BFloat16 type is supported on this target.
hasBFloat16Type()579   virtual bool hasBFloat16Type() const { return HasBFloat16; }
580 
581   /// Determine whether constrained floating point is supported on this target.
hasStrictFP()582   virtual bool hasStrictFP() const { return HasStrictFP; }
583 
584   /// Return the alignment that is suitable for storing any
585   /// object with a fundamental alignment requirement.
getSuitableAlign()586   unsigned getSuitableAlign() const { return SuitableAlign; }
587 
588   /// Return the default alignment for __attribute__((aligned)) on
589   /// this target, to be used if no alignment value is specified.
getDefaultAlignForAttributeAligned()590   unsigned getDefaultAlignForAttributeAligned() const {
591     return DefaultAlignForAttributeAligned;
592   }
593 
594   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
595   /// unless its alignment is explicitly reduced via attributes.
getMinGlobalAlign(uint64_t)596   virtual unsigned getMinGlobalAlign (uint64_t) const {
597     return MinGlobalAlign;
598   }
599 
600   /// Return the largest alignment for which a suitably-sized allocation with
601   /// '::operator new(size_t)' is guaranteed to produce a correctly-aligned
602   /// pointer.
getNewAlign()603   unsigned getNewAlign() const {
604     return NewAlign ? NewAlign : std::max(LongDoubleAlign, LongLongAlign);
605   }
606 
607   /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in
608   /// bits.
getWCharWidth()609   unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
getWCharAlign()610   unsigned getWCharAlign() const { return getTypeAlign(WCharType); }
611 
612   /// getChar16Width/Align - Return the size of 'char16_t' for this target, in
613   /// bits.
getChar16Width()614   unsigned getChar16Width() const { return getTypeWidth(Char16Type); }
getChar16Align()615   unsigned getChar16Align() const { return getTypeAlign(Char16Type); }
616 
617   /// getChar32Width/Align - Return the size of 'char32_t' for this target, in
618   /// bits.
getChar32Width()619   unsigned getChar32Width() const { return getTypeWidth(Char32Type); }
getChar32Align()620   unsigned getChar32Align() const { return getTypeAlign(Char32Type); }
621 
622   /// getHalfWidth/Align/Format - Return the size/align/format of 'half'.
getHalfWidth()623   unsigned getHalfWidth() const { return HalfWidth; }
getHalfAlign()624   unsigned getHalfAlign() const { return HalfAlign; }
getHalfFormat()625   const llvm::fltSemantics &getHalfFormat() const { return *HalfFormat; }
626 
627   /// getFloatWidth/Align/Format - Return the size/align/format of 'float'.
getFloatWidth()628   unsigned getFloatWidth() const { return FloatWidth; }
getFloatAlign()629   unsigned getFloatAlign() const { return FloatAlign; }
getFloatFormat()630   const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; }
631 
632   /// getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
getBFloat16Width()633   unsigned getBFloat16Width() const { return BFloat16Width; }
getBFloat16Align()634   unsigned getBFloat16Align() const { return BFloat16Align; }
getBFloat16Format()635   const llvm::fltSemantics &getBFloat16Format() const { return *BFloat16Format; }
636 
637   /// getDoubleWidth/Align/Format - Return the size/align/format of 'double'.
getDoubleWidth()638   unsigned getDoubleWidth() const { return DoubleWidth; }
getDoubleAlign()639   unsigned getDoubleAlign() const { return DoubleAlign; }
getDoubleFormat()640   const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; }
641 
642   /// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long
643   /// double'.
getLongDoubleWidth()644   unsigned getLongDoubleWidth() const { return LongDoubleWidth; }
getLongDoubleAlign()645   unsigned getLongDoubleAlign() const { return LongDoubleAlign; }
getLongDoubleFormat()646   const llvm::fltSemantics &getLongDoubleFormat() const {
647     return *LongDoubleFormat;
648   }
649 
650   /// getFloat128Width/Align/Format - Return the size/align/format of
651   /// '__float128'.
getFloat128Width()652   unsigned getFloat128Width() const { return 128; }
getFloat128Align()653   unsigned getFloat128Align() const { return Float128Align; }
getFloat128Format()654   const llvm::fltSemantics &getFloat128Format() const {
655     return *Float128Format;
656   }
657 
658   /// Return the mangled code of long double.
getLongDoubleMangling()659   virtual const char *getLongDoubleMangling() const { return "e"; }
660 
661   /// Return the mangled code of __float128.
getFloat128Mangling()662   virtual const char *getFloat128Mangling() const { return "g"; }
663 
664   /// Return the mangled code of bfloat.
getBFloat16Mangling()665   virtual const char *getBFloat16Mangling() const {
666     llvm_unreachable("bfloat not implemented on this target");
667   }
668 
669   /// Return the value for the C99 FLT_EVAL_METHOD macro.
getFloatEvalMethod()670   virtual unsigned getFloatEvalMethod() const { return 0; }
671 
672   // getLargeArrayMinWidth/Align - Return the minimum array size that is
673   // 'large' and its alignment.
getLargeArrayMinWidth()674   unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
getLargeArrayAlign()675   unsigned getLargeArrayAlign() const { return LargeArrayAlign; }
676 
677   /// Return the maximum width lock-free atomic operation which will
678   /// ever be supported for the given target
getMaxAtomicPromoteWidth()679   unsigned getMaxAtomicPromoteWidth() const { return MaxAtomicPromoteWidth; }
680   /// Return the maximum width lock-free atomic operation which can be
681   /// inlined given the supported features of the given target.
getMaxAtomicInlineWidth()682   unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
683   /// Set the maximum inline or promote width lock-free atomic operation
684   /// for the given target.
setMaxAtomicWidth()685   virtual void setMaxAtomicWidth() {}
686   /// Returns true if the given target supports lock-free atomic
687   /// operations at the specified width and alignment.
hasBuiltinAtomic(uint64_t AtomicSizeInBits,uint64_t AlignmentInBits)688   virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
689                                 uint64_t AlignmentInBits) const {
690     return AtomicSizeInBits <= AlignmentInBits &&
691            AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
692            (AtomicSizeInBits <= getCharWidth() ||
693             llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
694   }
695 
696   /// Return the maximum vector alignment supported for the given target.
getMaxVectorAlign()697   unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
698   /// Return default simd alignment for the given target. Generally, this
699   /// value is type-specific, but this alignment can be used for most of the
700   /// types for the given target.
getSimdDefaultAlign()701   unsigned getSimdDefaultAlign() const { return SimdDefaultAlign; }
702 
getMaxOpenCLWorkGroupSize()703   unsigned getMaxOpenCLWorkGroupSize() const { return MaxOpenCLWorkGroupSize; }
704 
705   /// Return the alignment (in bits) of the thrown exception object. This is
706   /// only meaningful for targets that allocate C++ exceptions in a system
707   /// runtime, such as those using the Itanium C++ ABI.
getExnObjectAlignment()708   virtual unsigned getExnObjectAlignment() const {
709     // Itanium says that an _Unwind_Exception has to be "double-word"
710     // aligned (and thus the end of it is also so-aligned), meaning 16
711     // bytes.  Of course, that was written for the actual Itanium,
712     // which is a 64-bit platform.  Classically, the ABI doesn't really
713     // specify the alignment on other platforms, but in practice
714     // libUnwind declares the struct with __attribute__((aligned)), so
715     // we assume that alignment here.  (It's generally 16 bytes, but
716     // some targets overwrite it.)
717     return getDefaultAlignForAttributeAligned();
718   }
719 
720   /// Return the size of intmax_t and uintmax_t for this target, in bits.
getIntMaxTWidth()721   unsigned getIntMaxTWidth() const {
722     return getTypeWidth(IntMaxType);
723   }
724 
725   // Return the size of unwind_word for this target.
getUnwindWordWidth()726   virtual unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
727 
728   /// Return the "preferred" register width on this target.
getRegisterWidth()729   virtual unsigned getRegisterWidth() const {
730     // Currently we assume the register width on the target matches the pointer
731     // width, we can introduce a new variable for this if/when some target wants
732     // it.
733     return PointerWidth;
734   }
735 
736   /// Returns the name of the mcount instrumentation function.
getMCountName()737   const char *getMCountName() const {
738     return MCountName;
739   }
740 
741   /// Check if the Objective-C built-in boolean type should be signed
742   /// char.
743   ///
744   /// Otherwise, if this returns false, the normal built-in boolean type
745   /// should also be used for Objective-C.
useSignedCharForObjCBool()746   bool useSignedCharForObjCBool() const {
747     return UseSignedCharForObjCBool;
748   }
noSignedCharForObjCBool()749   void noSignedCharForObjCBool() {
750     UseSignedCharForObjCBool = false;
751   }
752 
753   /// Check whether the alignment of bit-field types is respected
754   /// when laying out structures.
useBitFieldTypeAlignment()755   bool useBitFieldTypeAlignment() const {
756     return UseBitFieldTypeAlignment;
757   }
758 
759   /// Check whether zero length bitfields should force alignment of
760   /// the next member.
useZeroLengthBitfieldAlignment()761   bool useZeroLengthBitfieldAlignment() const {
762     return UseZeroLengthBitfieldAlignment;
763   }
764 
765   /// Get the fixed alignment value in bits for a member that follows
766   /// a zero length bitfield.
getZeroLengthBitfieldBoundary()767   unsigned getZeroLengthBitfieldBoundary() const {
768     return ZeroLengthBitfieldBoundary;
769   }
770 
771   /// Check whether explicit bitfield alignment attributes should be
772   //  honored, as in "__attribute__((aligned(2))) int b : 1;".
useExplicitBitFieldAlignment()773   bool useExplicitBitFieldAlignment() const {
774     return UseExplicitBitFieldAlignment;
775   }
776 
777   /// Check whether this target support '\#pragma options align=mac68k'.
hasAlignMac68kSupport()778   bool hasAlignMac68kSupport() const {
779     return HasAlignMac68kSupport;
780   }
781 
782   /// Return the user string for the specified integer type enum.
783   ///
784   /// For example, SignedShort -> "short".
785   static const char *getTypeName(IntType T);
786 
787   /// Return the constant suffix for the specified integer type enum.
788   ///
789   /// For example, SignedLong -> "L".
790   const char *getTypeConstantSuffix(IntType T) const;
791 
792   /// Return the printf format modifier for the specified
793   /// integer type enum.
794   ///
795   /// For example, SignedLong -> "l".
796   static const char *getTypeFormatModifier(IntType T);
797 
798   /// Check whether the given real type should use the "fpret" flavor of
799   /// Objective-C message passing on this target.
useObjCFPRetForRealType(RealType T)800   bool useObjCFPRetForRealType(RealType T) const {
801     return RealTypeUsesObjCFPRet & (1 << T);
802   }
803 
804   /// Check whether _Complex long double should use the "fp2ret" flavor
805   /// of Objective-C message passing on this target.
useObjCFP2RetForComplexLongDouble()806   bool useObjCFP2RetForComplexLongDouble() const {
807     return ComplexLongDoubleUsesFP2Ret;
808   }
809 
810   /// Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used
811   /// to convert to and from __fp16.
812   /// FIXME: This function should be removed once all targets stop using the
813   /// conversion intrinsics.
useFP16ConversionIntrinsics()814   virtual bool useFP16ConversionIntrinsics() const {
815     return true;
816   }
817 
818   /// Specify if mangling based on address space map should be used or
819   /// not for language specific address spaces
useAddressSpaceMapMangling()820   bool useAddressSpaceMapMangling() const {
821     return UseAddrSpaceMapMangling;
822   }
823 
824   ///===---- Other target property query methods --------------------------===//
825 
826   /// Appends the target-specific \#define values for this
827   /// target set to the specified buffer.
828   virtual void getTargetDefines(const LangOptions &Opts,
829                                 MacroBuilder &Builder) const = 0;
830 
831 
832   /// Return information about target-specific builtins for
833   /// the current primary target, and info about which builtins are non-portable
834   /// across the current set of primary and secondary targets.
835   virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
836 
837   /// The __builtin_clz* and __builtin_ctz* built-in
838   /// functions are specified to have undefined results for zero inputs, but
839   /// on targets that support these operations in a way that provides
840   /// well-defined results for zero without loss of performance, it is a good
841   /// idea to avoid optimizing based on that undef behavior.
isCLZForZeroUndef()842   virtual bool isCLZForZeroUndef() const { return true; }
843 
844   /// Returns the kind of __builtin_va_list type that should be used
845   /// with this target.
846   virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
847 
848   /// Returns whether or not type \c __builtin_ms_va_list type is
849   /// available on this target.
hasBuiltinMSVaList()850   bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
851 
852   /// Returns true for RenderScript.
isRenderScriptTarget()853   bool isRenderScriptTarget() const { return IsRenderScriptTarget; }
854 
855   /// Returns whether or not the AArch64 SVE built-in types are
856   /// available on this target.
hasAArch64SVETypes()857   bool hasAArch64SVETypes() const { return HasAArch64SVETypes; }
858 
859   /// For ARM targets returns a mask defining which coprocessors are configured
860   /// as Custom Datapath.
getARMCDECoprocMask()861   uint32_t getARMCDECoprocMask() const { return ARMCDECoprocMask; }
862 
863   /// Returns whether the passed in string is a valid clobber in an
864   /// inline asm statement.
865   ///
866   /// This is used by Sema.
867   bool isValidClobber(StringRef Name) const;
868 
869   /// Returns whether the passed in string is a valid register name
870   /// according to GCC.
871   ///
872   /// This is used by Sema for inline asm statements.
873   virtual bool isValidGCCRegisterName(StringRef Name) const;
874 
875   /// Returns the "normalized" GCC register name.
876   ///
877   /// ReturnCannonical true will return the register name without any additions
878   /// such as "{}" or "%" in it's canonical form, for example:
879   /// ReturnCanonical = true and Name = "rax", will return "ax".
880   StringRef getNormalizedGCCRegisterName(StringRef Name,
881                                          bool ReturnCanonical = false) const;
882 
isSPRegName(StringRef)883   virtual bool isSPRegName(StringRef) const { return false; }
884 
885   /// Extracts a register from the passed constraint (if it is a
886   /// single-register constraint) and the asm label expression related to a
887   /// variable in the input or output list of an inline asm statement.
888   ///
889   /// This function is used by Sema in order to diagnose conflicts between
890   /// the clobber list and the input/output lists.
getConstraintRegister(StringRef Constraint,StringRef Expression)891   virtual StringRef getConstraintRegister(StringRef Constraint,
892                                           StringRef Expression) const {
893     return "";
894   }
895 
896   struct ConstraintInfo {
897     enum {
898       CI_None = 0x00,
899       CI_AllowsMemory = 0x01,
900       CI_AllowsRegister = 0x02,
901       CI_ReadWrite = 0x04,         // "+r" output constraint (read and write).
902       CI_HasMatchingInput = 0x08,  // This output operand has a matching input.
903       CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
904       CI_EarlyClobber = 0x20,      // "&" output constraint (early clobber).
905     };
906     unsigned Flags;
907     int TiedOperand;
908     struct {
909       int Min;
910       int Max;
911       bool isConstrained;
912     } ImmRange;
913     llvm::SmallSet<int, 4> ImmSet;
914 
915     std::string ConstraintStr;  // constraint: "=rm"
916     std::string Name;           // Operand name: [foo] with no []'s.
917   public:
ConstraintInfoConstraintInfo918     ConstraintInfo(StringRef ConstraintStr, StringRef Name)
919         : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
920           Name(Name.str()) {
921       ImmRange.Min = ImmRange.Max = 0;
922       ImmRange.isConstrained = false;
923     }
924 
getConstraintStrConstraintInfo925     const std::string &getConstraintStr() const { return ConstraintStr; }
getNameConstraintInfo926     const std::string &getName() const { return Name; }
isReadWriteConstraintInfo927     bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
earlyClobberConstraintInfo928     bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
allowsRegisterConstraintInfo929     bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
allowsMemoryConstraintInfo930     bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
931 
932     /// Return true if this output operand has a matching
933     /// (tied) input operand.
hasMatchingInputConstraintInfo934     bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; }
935 
936     /// Return true if this input operand is a matching
937     /// constraint that ties it to an output operand.
938     ///
939     /// If this returns true then getTiedOperand will indicate which output
940     /// operand this is tied to.
hasTiedOperandConstraintInfo941     bool hasTiedOperand() const { return TiedOperand != -1; }
getTiedOperandConstraintInfo942     unsigned getTiedOperand() const {
943       assert(hasTiedOperand() && "Has no tied operand!");
944       return (unsigned)TiedOperand;
945     }
946 
requiresImmediateConstantConstraintInfo947     bool requiresImmediateConstant() const {
948       return (Flags & CI_ImmediateConstant) != 0;
949     }
isValidAsmImmediateConstraintInfo950     bool isValidAsmImmediate(const llvm::APInt &Value) const {
951       if (!ImmSet.empty())
952         return Value.isSignedIntN(32) &&
953                ImmSet.count(Value.getZExtValue()) != 0;
954       return !ImmRange.isConstrained ||
955              (Value.sge(ImmRange.Min) && Value.sle(ImmRange.Max));
956     }
957 
setIsReadWriteConstraintInfo958     void setIsReadWrite() { Flags |= CI_ReadWrite; }
setEarlyClobberConstraintInfo959     void setEarlyClobber() { Flags |= CI_EarlyClobber; }
setAllowsMemoryConstraintInfo960     void setAllowsMemory() { Flags |= CI_AllowsMemory; }
setAllowsRegisterConstraintInfo961     void setAllowsRegister() { Flags |= CI_AllowsRegister; }
setHasMatchingInputConstraintInfo962     void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
setRequiresImmediateConstraintInfo963     void setRequiresImmediate(int Min, int Max) {
964       Flags |= CI_ImmediateConstant;
965       ImmRange.Min = Min;
966       ImmRange.Max = Max;
967       ImmRange.isConstrained = true;
968     }
setRequiresImmediateConstraintInfo969     void setRequiresImmediate(llvm::ArrayRef<int> Exacts) {
970       Flags |= CI_ImmediateConstant;
971       for (int Exact : Exacts)
972         ImmSet.insert(Exact);
973     }
setRequiresImmediateConstraintInfo974     void setRequiresImmediate(int Exact) {
975       Flags |= CI_ImmediateConstant;
976       ImmSet.insert(Exact);
977     }
setRequiresImmediateConstraintInfo978     void setRequiresImmediate() {
979       Flags |= CI_ImmediateConstant;
980     }
981 
982     /// Indicate that this is an input operand that is tied to
983     /// the specified output operand.
984     ///
985     /// Copy over the various constraint information from the output.
setTiedOperandConstraintInfo986     void setTiedOperand(unsigned N, ConstraintInfo &Output) {
987       Output.setHasMatchingInput();
988       Flags = Output.Flags;
989       TiedOperand = N;
990       // Don't copy Name or constraint string.
991     }
992   };
993 
994   /// Validate register name used for global register variables.
995   ///
996   /// This function returns true if the register passed in RegName can be used
997   /// for global register variables on this target. In addition, it returns
998   /// true in HasSizeMismatch if the size of the register doesn't match the
999   /// variable size passed in RegSize.
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch)1000   virtual bool validateGlobalRegisterVariable(StringRef RegName,
1001                                               unsigned RegSize,
1002                                               bool &HasSizeMismatch) const {
1003     HasSizeMismatch = false;
1004     return true;
1005   }
1006 
1007   // validateOutputConstraint, validateInputConstraint - Checks that
1008   // a constraint is valid and provides information about it.
1009   // FIXME: These should return a real error instead of just true/false.
1010   bool validateOutputConstraint(ConstraintInfo &Info) const;
1011   bool validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,
1012                                ConstraintInfo &info) const;
1013 
validateOutputSize(const llvm::StringMap<bool> & FeatureMap,StringRef,unsigned)1014   virtual bool validateOutputSize(const llvm::StringMap<bool> &FeatureMap,
1015                                   StringRef /*Constraint*/,
1016                                   unsigned /*Size*/) const {
1017     return true;
1018   }
1019 
validateInputSize(const llvm::StringMap<bool> & FeatureMap,StringRef,unsigned)1020   virtual bool validateInputSize(const llvm::StringMap<bool> &FeatureMap,
1021                                  StringRef /*Constraint*/,
1022                                  unsigned /*Size*/) const {
1023     return true;
1024   }
1025   virtual bool
validateConstraintModifier(StringRef,char,unsigned,std::string &)1026   validateConstraintModifier(StringRef /*Constraint*/,
1027                              char /*Modifier*/,
1028                              unsigned /*Size*/,
1029                              std::string &/*SuggestedModifier*/) const {
1030     return true;
1031   }
1032   virtual bool
1033   validateAsmConstraint(const char *&Name,
1034                         TargetInfo::ConstraintInfo &info) const = 0;
1035 
1036   bool resolveSymbolicName(const char *&Name,
1037                            ArrayRef<ConstraintInfo> OutputConstraints,
1038                            unsigned &Index) const;
1039 
1040   // Constraint parm will be left pointing at the last character of
1041   // the constraint.  In practice, it won't be changed unless the
1042   // constraint is longer than one character.
convertConstraint(const char * & Constraint)1043   virtual std::string convertConstraint(const char *&Constraint) const {
1044     // 'p' defaults to 'r', but can be overridden by targets.
1045     if (*Constraint == 'p')
1046       return std::string("r");
1047     return std::string(1, *Constraint);
1048   }
1049 
1050   /// Returns a string of target-specific clobbers, in LLVM format.
1051   virtual const char *getClobbers() const = 0;
1052 
1053   /// Returns true if NaN encoding is IEEE 754-2008.
1054   /// Only MIPS allows a different encoding.
isNan2008()1055   virtual bool isNan2008() const {
1056     return true;
1057   }
1058 
1059   /// Returns the target triple of the primary target.
getTriple()1060   const llvm::Triple &getTriple() const {
1061     return Triple;
1062   }
1063 
getDataLayout()1064   const llvm::DataLayout &getDataLayout() const {
1065     assert(DataLayout && "Uninitialized DataLayout!");
1066     return *DataLayout;
1067   }
1068 
1069   struct GCCRegAlias {
1070     const char * const Aliases[5];
1071     const char * const Register;
1072   };
1073 
1074   struct AddlRegName {
1075     const char * const Names[5];
1076     const unsigned RegNum;
1077   };
1078 
1079   /// Does this target support "protected" visibility?
1080   ///
1081   /// Any target which dynamic libraries will naturally support
1082   /// something like "default" (meaning that the symbol is visible
1083   /// outside this shared object) and "hidden" (meaning that it isn't)
1084   /// visibilities, but "protected" is really an ELF-specific concept
1085   /// with weird semantics designed around the convenience of dynamic
1086   /// linker implementations.  Which is not to suggest that there's
1087   /// consistent target-independent semantics for "default" visibility
1088   /// either; the entire thing is pretty badly mangled.
hasProtectedVisibility()1089   virtual bool hasProtectedVisibility() const { return true; }
1090 
1091   /// An optional hook that targets can implement to perform semantic
1092   /// checking on attribute((section("foo"))) specifiers.
1093   ///
1094   /// In this case, "foo" is passed in to be checked.  If the section
1095   /// specifier is invalid, the backend should return a non-empty string
1096   /// that indicates the problem.
1097   ///
1098   /// This hook is a simple quality of implementation feature to catch errors
1099   /// and give good diagnostics in cases when the assembler or code generator
1100   /// would otherwise reject the section specifier.
1101   ///
isValidSectionSpecifier(StringRef SR)1102   virtual std::string isValidSectionSpecifier(StringRef SR) const {
1103     return "";
1104   }
1105 
1106   /// Set forced language options.
1107   ///
1108   /// Apply changes to the target information with respect to certain
1109   /// language options which change the target configuration and adjust
1110   /// the language based on the target options where applicable.
1111   virtual void adjust(LangOptions &Opts);
1112 
1113   /// Adjust target options based on codegen options.
adjustTargetOptions(const CodeGenOptions & CGOpts,TargetOptions & TargetOpts)1114   virtual void adjustTargetOptions(const CodeGenOptions &CGOpts,
1115                                    TargetOptions &TargetOpts) const {}
1116 
1117   /// Initialize the map with the default set of target features for the
1118   /// CPU this should include all legal feature strings on the target.
1119   ///
1120   /// \return False on error (invalid features).
1121   virtual bool initFeatureMap(llvm::StringMap<bool> &Features,
1122                               DiagnosticsEngine &Diags, StringRef CPU,
1123                               const std::vector<std::string> &FeatureVec) const;
1124 
1125   /// Get the ABI currently in use.
getABI()1126   virtual StringRef getABI() const { return StringRef(); }
1127 
1128   /// Get the C++ ABI currently in use.
getCXXABI()1129   TargetCXXABI getCXXABI() const {
1130     return TheCXXABI;
1131   }
1132 
1133   /// Target the specified CPU.
1134   ///
1135   /// \return  False on error (invalid CPU name).
setCPU(const std::string & Name)1136   virtual bool setCPU(const std::string &Name) {
1137     return false;
1138   }
1139 
1140   /// Fill a SmallVectorImpl with the valid values to setCPU.
fillValidCPUList(SmallVectorImpl<StringRef> & Values)1141   virtual void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const {}
1142 
1143   /// brief Determine whether this TargetInfo supports the given CPU name.
isValidCPUName(StringRef Name)1144   virtual bool isValidCPUName(StringRef Name) const {
1145     return true;
1146   }
1147 
1148   /// Use the specified ABI.
1149   ///
1150   /// \return False on error (invalid ABI name).
setABI(const std::string & Name)1151   virtual bool setABI(const std::string &Name) {
1152     return false;
1153   }
1154 
1155   /// Use the specified unit for FP math.
1156   ///
1157   /// \return False on error (invalid unit name).
setFPMath(StringRef Name)1158   virtual bool setFPMath(StringRef Name) {
1159     return false;
1160   }
1161 
1162   /// Enable or disable a specific target feature;
1163   /// the feature name must be valid.
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled)1164   virtual void setFeatureEnabled(llvm::StringMap<bool> &Features,
1165                                  StringRef Name,
1166                                  bool Enabled) const {
1167     Features[Name] = Enabled;
1168   }
1169 
1170   /// Determine whether this TargetInfo supports the given feature.
isValidFeatureName(StringRef Feature)1171   virtual bool isValidFeatureName(StringRef Feature) const {
1172     return true;
1173   }
1174 
1175   struct BranchProtectionInfo {
1176     LangOptions::SignReturnAddressScopeKind SignReturnAddr =
1177         LangOptions::SignReturnAddressScopeKind::None;
1178     LangOptions::SignReturnAddressKeyKind SignKey =
1179         LangOptions::SignReturnAddressKeyKind::AKey;
1180     bool BranchTargetEnforcement = false;
1181   };
1182 
1183   /// Determine if this TargetInfo supports the given branch protection
1184   /// specification
validateBranchProtection(StringRef Spec,BranchProtectionInfo & BPI,StringRef & Err)1185   virtual bool validateBranchProtection(StringRef Spec,
1186                                         BranchProtectionInfo &BPI,
1187                                         StringRef &Err) const {
1188     Err = "";
1189     return false;
1190   }
1191 
1192   /// Perform initialization based on the user configured
1193   /// set of features (e.g., +sse4).
1194   ///
1195   /// The list is guaranteed to have at most one entry per feature.
1196   ///
1197   /// The target may modify the features list, to change which options are
1198   /// passed onwards to the backend.
1199   /// FIXME: This part should be fixed so that we can change handleTargetFeatures
1200   /// to merely a TargetInfo initialization routine.
1201   ///
1202   /// \return  False on error.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)1203   virtual bool handleTargetFeatures(std::vector<std::string> &Features,
1204                                     DiagnosticsEngine &Diags) {
1205     return true;
1206   }
1207 
1208   /// Determine whether the given target has the given feature.
hasFeature(StringRef Feature)1209   virtual bool hasFeature(StringRef Feature) const {
1210     return false;
1211   }
1212 
1213   /// Identify whether this target supports multiversioning of functions,
1214   /// which requires support for cpu_supports and cpu_is functionality.
supportsMultiVersioning()1215   bool supportsMultiVersioning() const { return getTriple().isX86(); }
1216 
1217   /// Identify whether this target supports IFuncs.
supportsIFunc()1218   bool supportsIFunc() const { return getTriple().isOSBinFormatELF(); }
1219 
1220   // Validate the contents of the __builtin_cpu_supports(const char*)
1221   // argument.
validateCpuSupports(StringRef Name)1222   virtual bool validateCpuSupports(StringRef Name) const { return false; }
1223 
1224   // Return the target-specific priority for features/cpus/vendors so
1225   // that they can be properly sorted for checking.
multiVersionSortPriority(StringRef Name)1226   virtual unsigned multiVersionSortPriority(StringRef Name) const {
1227     return 0;
1228   }
1229 
1230   // Validate the contents of the __builtin_cpu_is(const char*)
1231   // argument.
validateCpuIs(StringRef Name)1232   virtual bool validateCpuIs(StringRef Name) const { return false; }
1233 
1234   // Validate a cpu_dispatch/cpu_specific CPU option, which is a different list
1235   // from cpu_is, since it checks via features rather than CPUs directly.
validateCPUSpecificCPUDispatch(StringRef Name)1236   virtual bool validateCPUSpecificCPUDispatch(StringRef Name) const {
1237     return false;
1238   }
1239 
1240   // Get the character to be added for mangling purposes for cpu_specific.
CPUSpecificManglingCharacter(StringRef Name)1241   virtual char CPUSpecificManglingCharacter(StringRef Name) const {
1242     llvm_unreachable(
1243         "cpu_specific Multiversioning not implemented on this target");
1244   }
1245 
1246   // Get a list of the features that make up the CPU option for
1247   // cpu_specific/cpu_dispatch so that it can be passed to llvm as optimization
1248   // options.
getCPUSpecificCPUDispatchFeatures(StringRef Name,llvm::SmallVectorImpl<StringRef> & Features)1249   virtual void getCPUSpecificCPUDispatchFeatures(
1250       StringRef Name, llvm::SmallVectorImpl<StringRef> &Features) const {
1251     llvm_unreachable(
1252         "cpu_specific Multiversioning not implemented on this target");
1253   }
1254 
1255   // Get the cache line size of a given cpu. This method switches over
1256   // the given cpu and returns "None" if the CPU is not found.
getCPUCacheLineSize()1257   virtual Optional<unsigned> getCPUCacheLineSize() const { return None; }
1258 
1259   // Returns maximal number of args passed in registers.
getRegParmMax()1260   unsigned getRegParmMax() const {
1261     assert(RegParmMax < 7 && "RegParmMax value is larger than AST can handle");
1262     return RegParmMax;
1263   }
1264 
1265   /// Whether the target supports thread-local storage.
isTLSSupported()1266   bool isTLSSupported() const {
1267     return TLSSupported;
1268   }
1269 
1270   /// Return the maximum alignment (in bits) of a TLS variable
1271   ///
1272   /// Gets the maximum alignment (in bits) of a TLS variable on this target.
1273   /// Returns zero if there is no such constraint.
getMaxTLSAlign()1274   unsigned short getMaxTLSAlign() const {
1275     return MaxTLSAlign;
1276   }
1277 
1278   /// Whether target supports variable-length arrays.
isVLASupported()1279   bool isVLASupported() const { return VLASupported; }
1280 
1281   /// Whether the target supports SEH __try.
isSEHTrySupported()1282   bool isSEHTrySupported() const {
1283     return getTriple().isOSWindows() &&
1284            (getTriple().isX86() ||
1285             getTriple().getArch() == llvm::Triple::aarch64);
1286   }
1287 
1288   /// Return true if {|} are normal characters in the asm string.
1289   ///
1290   /// If this returns false (the default), then {abc|xyz} is syntax
1291   /// that says that when compiling for asm variant #0, "abc" should be
1292   /// generated, but when compiling for asm variant #1, "xyz" should be
1293   /// generated.
hasNoAsmVariants()1294   bool hasNoAsmVariants() const {
1295     return NoAsmVariants;
1296   }
1297 
1298   /// Return the register number that __builtin_eh_return_regno would
1299   /// return with the specified argument.
1300   /// This corresponds with TargetLowering's getExceptionPointerRegister
1301   /// and getExceptionSelectorRegister in the backend.
getEHDataRegisterNumber(unsigned RegNo)1302   virtual int getEHDataRegisterNumber(unsigned RegNo) const {
1303     return -1;
1304   }
1305 
1306   /// Return the section to use for C++ static initialization functions.
getStaticInitSectionSpecifier()1307   virtual const char *getStaticInitSectionSpecifier() const {
1308     return nullptr;
1309   }
1310 
getAddressSpaceMap()1311   const LangASMap &getAddressSpaceMap() const { return *AddrSpaceMap; }
1312 
1313   /// Map from the address space field in builtin description strings to the
1314   /// language address space.
getOpenCLBuiltinAddressSpace(unsigned AS)1315   virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const {
1316     return getLangASFromTargetAS(AS);
1317   }
1318 
1319   /// Map from the address space field in builtin description strings to the
1320   /// language address space.
getCUDABuiltinAddressSpace(unsigned AS)1321   virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const {
1322     return getLangASFromTargetAS(AS);
1323   }
1324 
1325   /// Return an AST address space which can be used opportunistically
1326   /// for constant global memory. It must be possible to convert pointers into
1327   /// this address space to LangAS::Default. If no such address space exists,
1328   /// this may return None, and such optimizations will be disabled.
getConstantAddressSpace()1329   virtual llvm::Optional<LangAS> getConstantAddressSpace() const {
1330     return LangAS::Default;
1331   }
1332 
1333   /// Return a target-specific GPU grid value based on the GVIDX enum \p gv
getGridValue(llvm::omp::GVIDX gv)1334   unsigned getGridValue(llvm::omp::GVIDX gv) const {
1335     assert(GridValues != nullptr && "GridValues not initialized");
1336     return GridValues[gv];
1337   }
1338 
1339   /// Retrieve the name of the platform as it is used in the
1340   /// availability attribute.
getPlatformName()1341   StringRef getPlatformName() const { return PlatformName; }
1342 
1343   /// Retrieve the minimum desired version of the platform, to
1344   /// which the program should be compiled.
getPlatformMinVersion()1345   VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
1346 
isBigEndian()1347   bool isBigEndian() const { return BigEndian; }
isLittleEndian()1348   bool isLittleEndian() const { return !BigEndian; }
1349 
1350   /// Gets the default calling convention for the given target and
1351   /// declaration context.
getDefaultCallingConv()1352   virtual CallingConv getDefaultCallingConv() const {
1353     // Not all targets will specify an explicit calling convention that we can
1354     // express.  This will always do the right thing, even though it's not
1355     // an explicit calling convention.
1356     return CC_C;
1357   }
1358 
1359   enum CallingConvCheckResult {
1360     CCCR_OK,
1361     CCCR_Warning,
1362     CCCR_Ignore,
1363     CCCR_Error,
1364   };
1365 
1366   /// Determines whether a given calling convention is valid for the
1367   /// target. A calling convention can either be accepted, produce a warning
1368   /// and be substituted with the default calling convention, or (someday)
1369   /// produce an error (such as using thiscall on a non-instance function).
checkCallingConvention(CallingConv CC)1370   virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const {
1371     switch (CC) {
1372       default:
1373         return CCCR_Warning;
1374       case CC_C:
1375         return CCCR_OK;
1376     }
1377   }
1378 
1379   enum CallingConvKind {
1380     CCK_Default,
1381     CCK_ClangABI4OrPS4,
1382     CCK_MicrosoftWin64
1383   };
1384 
1385   virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const;
1386 
1387   /// Controls if __builtin_longjmp / __builtin_setjmp can be lowered to
1388   /// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp.
hasSjLjLowering()1389   virtual bool hasSjLjLowering() const {
1390     return false;
1391   }
1392 
1393   /// Check if the target supports CFProtection branch.
1394   virtual bool
1395   checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const;
1396 
1397   /// Check if the target supports CFProtection branch.
1398   virtual bool
1399   checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const;
1400 
1401   /// Whether target allows to overalign ABI-specified preferred alignment
allowsLargerPreferedTypeAlignment()1402   virtual bool allowsLargerPreferedTypeAlignment() const { return true; }
1403 
1404   /// Set supported OpenCL extensions and optional core features.
setSupportedOpenCLOpts()1405   virtual void setSupportedOpenCLOpts() {}
1406 
1407   /// Set supported OpenCL extensions as written on command line
setOpenCLExtensionOpts()1408   virtual void setOpenCLExtensionOpts() {
1409     for (const auto &Ext : getTargetOpts().OpenCLExtensionsAsWritten) {
1410       getTargetOpts().SupportedOpenCLOptions.support(Ext);
1411     }
1412   }
1413 
1414   /// Get supported OpenCL extensions and optional core features.
getSupportedOpenCLOpts()1415   OpenCLOptions &getSupportedOpenCLOpts() {
1416     return getTargetOpts().SupportedOpenCLOptions;
1417   }
1418 
1419   /// Get const supported OpenCL extensions and optional core features.
getSupportedOpenCLOpts()1420   const OpenCLOptions &getSupportedOpenCLOpts() const {
1421       return getTargetOpts().SupportedOpenCLOptions;
1422   }
1423 
1424   /// Get address space for OpenCL type.
1425   virtual LangAS getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const;
1426 
1427   /// \returns Target specific vtbl ptr address space.
getVtblPtrAddressSpace()1428   virtual unsigned getVtblPtrAddressSpace() const {
1429     return 0;
1430   }
1431 
1432   /// \returns If a target requires an address within a target specific address
1433   /// space \p AddressSpace to be converted in order to be used, then return the
1434   /// corresponding target specific DWARF address space.
1435   ///
1436   /// \returns Otherwise return None and no conversion will be emitted in the
1437   /// DWARF.
getDWARFAddressSpace(unsigned AddressSpace)1438   virtual Optional<unsigned> getDWARFAddressSpace(unsigned AddressSpace) const {
1439     return None;
1440   }
1441 
1442   /// \returns The version of the SDK which was used during the compilation if
1443   /// one was specified, or an empty version otherwise.
getSDKVersion()1444   const llvm::VersionTuple &getSDKVersion() const {
1445     return getTargetOpts().SDKVersion;
1446   }
1447 
1448   /// Check the target is valid after it is fully initialized.
validateTarget(DiagnosticsEngine & Diags)1449   virtual bool validateTarget(DiagnosticsEngine &Diags) const {
1450     return true;
1451   }
1452 
setAuxTarget(const TargetInfo * Aux)1453   virtual void setAuxTarget(const TargetInfo *Aux) {}
1454 
1455   /// Whether target allows debuginfo types for decl only variables.
allowDebugInfoForExternalVar()1456   virtual bool allowDebugInfoForExternalVar() const { return false; }
1457 
1458 protected:
1459   /// Copy type and layout related info.
1460   void copyAuxTarget(const TargetInfo *Aux);
getPointerWidthV(unsigned AddrSpace)1461   virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
1462     return PointerWidth;
1463   }
getPointerAlignV(unsigned AddrSpace)1464   virtual uint64_t getPointerAlignV(unsigned AddrSpace) const {
1465     return PointerAlign;
1466   }
getPtrDiffTypeV(unsigned AddrSpace)1467   virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const {
1468     return PtrDiffType;
1469   }
1470   virtual ArrayRef<const char *> getGCCRegNames() const = 0;
1471   virtual ArrayRef<GCCRegAlias> getGCCRegAliases() const = 0;
getGCCAddlRegNames()1472   virtual ArrayRef<AddlRegName> getGCCAddlRegNames() const {
1473     return None;
1474   }
1475 
1476  private:
1477   // Assert the values for the fractional and integral bits for each fixed point
1478   // type follow the restrictions given in clause 6.2.6.3 of N1169.
1479   void CheckFixedPointBits() const;
1480 };
1481 
1482 }  // end namespace clang
1483 
1484 #endif
1485