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