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