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