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