1 //===- Type.cpp - Type representation and manipulation --------------------===//
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 // This file implements type-related functionality.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "clang/AST/Type.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DependenceFlags.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/NestedNameSpecifier.h"
26 #include "clang/AST/NonTrivialTypeVisitor.h"
27 #include "clang/AST/PrettyPrinter.h"
28 #include "clang/AST/TemplateBase.h"
29 #include "clang/AST/TemplateName.h"
30 #include "clang/AST/TypeVisitor.h"
31 #include "clang/Basic/AddressSpaces.h"
32 #include "clang/Basic/ExceptionSpecificationType.h"
33 #include "clang/Basic/IdentifierTable.h"
34 #include "clang/Basic/LLVM.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/Linkage.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TargetCXXABI.h"
39 #include "clang/Basic/TargetInfo.h"
40 #include "clang/Basic/Visibility.h"
41 #include "llvm/ADT/APInt.h"
42 #include "llvm/ADT/APSInt.h"
43 #include "llvm/ADT/ArrayRef.h"
44 #include "llvm/ADT/FoldingSet.h"
45 #include "llvm/ADT/SmallVector.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <cstring>
53 #include <optional>
54 #include <type_traits>
55
56 using namespace clang;
57
isStrictSupersetOf(Qualifiers Other) const58 bool Qualifiers::isStrictSupersetOf(Qualifiers Other) const {
59 return (*this != Other) &&
60 // CVR qualifiers superset
61 (((Mask & CVRMask) | (Other.Mask & CVRMask)) == (Mask & CVRMask)) &&
62 // ObjC GC qualifiers superset
63 ((getObjCGCAttr() == Other.getObjCGCAttr()) ||
64 (hasObjCGCAttr() && !Other.hasObjCGCAttr())) &&
65 // Address space superset.
66 ((getAddressSpace() == Other.getAddressSpace()) ||
67 (hasAddressSpace()&& !Other.hasAddressSpace())) &&
68 // Lifetime qualifier superset.
69 ((getObjCLifetime() == Other.getObjCLifetime()) ||
70 (hasObjCLifetime() && !Other.hasObjCLifetime()));
71 }
72
getBaseTypeIdentifier() const73 const IdentifierInfo* QualType::getBaseTypeIdentifier() const {
74 const Type* ty = getTypePtr();
75 NamedDecl *ND = nullptr;
76 if (ty->isPointerType() || ty->isReferenceType())
77 return ty->getPointeeType().getBaseTypeIdentifier();
78 else if (ty->isRecordType())
79 ND = ty->castAs<RecordType>()->getDecl();
80 else if (ty->isEnumeralType())
81 ND = ty->castAs<EnumType>()->getDecl();
82 else if (ty->getTypeClass() == Type::Typedef)
83 ND = ty->castAs<TypedefType>()->getDecl();
84 else if (ty->isArrayType())
85 return ty->castAsArrayTypeUnsafe()->
86 getElementType().getBaseTypeIdentifier();
87
88 if (ND)
89 return ND->getIdentifier();
90 return nullptr;
91 }
92
mayBeDynamicClass() const93 bool QualType::mayBeDynamicClass() const {
94 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
95 return ClassDecl && ClassDecl->mayBeDynamicClass();
96 }
97
mayBeNotDynamicClass() const98 bool QualType::mayBeNotDynamicClass() const {
99 const auto *ClassDecl = getTypePtr()->getPointeeCXXRecordDecl();
100 return !ClassDecl || ClassDecl->mayBeNonDynamicClass();
101 }
102
isConstant(QualType T,const ASTContext & Ctx)103 bool QualType::isConstant(QualType T, const ASTContext &Ctx) {
104 if (T.isConstQualified())
105 return true;
106
107 if (const ArrayType *AT = Ctx.getAsArrayType(T))
108 return AT->getElementType().isConstant(Ctx);
109
110 return T.getAddressSpace() == LangAS::opencl_constant;
111 }
112
113 // C++ [temp.dep.type]p1:
114 // A type is dependent if it is...
115 // - an array type constructed from any dependent type or whose
116 // size is specified by a constant expression that is
117 // value-dependent,
ArrayType(TypeClass tc,QualType et,QualType can,ArraySizeModifier sm,unsigned tq,const Expr * sz)118 ArrayType::ArrayType(TypeClass tc, QualType et, QualType can,
119 ArraySizeModifier sm, unsigned tq, const Expr *sz)
120 // Note, we need to check for DependentSizedArrayType explicitly here
121 // because we use a DependentSizedArrayType with no size expression as the
122 // type of a dependent array of unknown bound with a dependent braced
123 // initializer:
124 //
125 // template<int ...N> int arr[] = {N...};
126 : Type(tc, can,
127 et->getDependence() |
128 (sz ? toTypeDependence(
129 turnValueToTypeDependence(sz->getDependence()))
130 : TypeDependence::None) |
131 (tc == VariableArray ? TypeDependence::VariablyModified
132 : TypeDependence::None) |
133 (tc == DependentSizedArray
134 ? TypeDependence::DependentInstantiation
135 : TypeDependence::None)),
136 ElementType(et) {
137 ArrayTypeBits.IndexTypeQuals = tq;
138 ArrayTypeBits.SizeModifier = sm;
139 }
140
getNumAddressingBits(const ASTContext & Context,QualType ElementType,const llvm::APInt & NumElements)141 unsigned ConstantArrayType::getNumAddressingBits(const ASTContext &Context,
142 QualType ElementType,
143 const llvm::APInt &NumElements) {
144 uint64_t ElementSize = Context.getTypeSizeInChars(ElementType).getQuantity();
145
146 // Fast path the common cases so we can avoid the conservative computation
147 // below, which in common cases allocates "large" APSInt values, which are
148 // slow.
149
150 // If the element size is a power of 2, we can directly compute the additional
151 // number of addressing bits beyond those required for the element count.
152 if (llvm::isPowerOf2_64(ElementSize)) {
153 return NumElements.getActiveBits() + llvm::Log2_64(ElementSize);
154 }
155
156 // If both the element count and element size fit in 32-bits, we can do the
157 // computation directly in 64-bits.
158 if ((ElementSize >> 32) == 0 && NumElements.getBitWidth() <= 64 &&
159 (NumElements.getZExtValue() >> 32) == 0) {
160 uint64_t TotalSize = NumElements.getZExtValue() * ElementSize;
161 return 64 - llvm::countLeadingZeros(TotalSize);
162 }
163
164 // Otherwise, use APSInt to handle arbitrary sized values.
165 llvm::APSInt SizeExtended(NumElements, true);
166 unsigned SizeTypeBits = Context.getTypeSize(Context.getSizeType());
167 SizeExtended = SizeExtended.extend(std::max(SizeTypeBits,
168 SizeExtended.getBitWidth()) * 2);
169
170 llvm::APSInt TotalSize(llvm::APInt(SizeExtended.getBitWidth(), ElementSize));
171 TotalSize *= SizeExtended;
172
173 return TotalSize.getActiveBits();
174 }
175
getMaxSizeBits(const ASTContext & Context)176 unsigned ConstantArrayType::getMaxSizeBits(const ASTContext &Context) {
177 unsigned Bits = Context.getTypeSize(Context.getSizeType());
178
179 // Limit the number of bits in size_t so that maximal bit size fits 64 bit
180 // integer (see PR8256). We can do this as currently there is no hardware
181 // that supports full 64-bit virtual space.
182 if (Bits > 61)
183 Bits = 61;
184
185 return Bits;
186 }
187
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ET,const llvm::APInt & ArraySize,const Expr * SizeExpr,ArraySizeModifier SizeMod,unsigned TypeQuals)188 void ConstantArrayType::Profile(llvm::FoldingSetNodeID &ID,
189 const ASTContext &Context, QualType ET,
190 const llvm::APInt &ArraySize,
191 const Expr *SizeExpr, ArraySizeModifier SizeMod,
192 unsigned TypeQuals) {
193 ID.AddPointer(ET.getAsOpaquePtr());
194 ID.AddInteger(ArraySize.getZExtValue());
195 ID.AddInteger(SizeMod);
196 ID.AddInteger(TypeQuals);
197 ID.AddBoolean(SizeExpr != nullptr);
198 if (SizeExpr)
199 SizeExpr->Profile(ID, Context, true);
200 }
201
DependentSizedArrayType(const ASTContext & Context,QualType et,QualType can,Expr * e,ArraySizeModifier sm,unsigned tq,SourceRange brackets)202 DependentSizedArrayType::DependentSizedArrayType(const ASTContext &Context,
203 QualType et, QualType can,
204 Expr *e, ArraySizeModifier sm,
205 unsigned tq,
206 SourceRange brackets)
207 : ArrayType(DependentSizedArray, et, can, sm, tq, e),
208 Context(Context), SizeExpr((Stmt*) e), Brackets(brackets) {}
209
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ET,ArraySizeModifier SizeMod,unsigned TypeQuals,Expr * E)210 void DependentSizedArrayType::Profile(llvm::FoldingSetNodeID &ID,
211 const ASTContext &Context,
212 QualType ET,
213 ArraySizeModifier SizeMod,
214 unsigned TypeQuals,
215 Expr *E) {
216 ID.AddPointer(ET.getAsOpaquePtr());
217 ID.AddInteger(SizeMod);
218 ID.AddInteger(TypeQuals);
219 E->Profile(ID, Context, true);
220 }
221
DependentVectorType(const ASTContext & Context,QualType ElementType,QualType CanonType,Expr * SizeExpr,SourceLocation Loc,VectorType::VectorKind VecKind)222 DependentVectorType::DependentVectorType(const ASTContext &Context,
223 QualType ElementType,
224 QualType CanonType, Expr *SizeExpr,
225 SourceLocation Loc,
226 VectorType::VectorKind VecKind)
227 : Type(DependentVector, CanonType,
228 TypeDependence::DependentInstantiation |
229 ElementType->getDependence() |
230 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
231 : TypeDependence::None)),
232 Context(Context), ElementType(ElementType), SizeExpr(SizeExpr), Loc(Loc) {
233 VectorTypeBits.VecKind = VecKind;
234 }
235
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ElementType,const Expr * SizeExpr,VectorType::VectorKind VecKind)236 void DependentVectorType::Profile(llvm::FoldingSetNodeID &ID,
237 const ASTContext &Context,
238 QualType ElementType, const Expr *SizeExpr,
239 VectorType::VectorKind VecKind) {
240 ID.AddPointer(ElementType.getAsOpaquePtr());
241 ID.AddInteger(VecKind);
242 SizeExpr->Profile(ID, Context, true);
243 }
244
DependentSizedExtVectorType(const ASTContext & Context,QualType ElementType,QualType can,Expr * SizeExpr,SourceLocation loc)245 DependentSizedExtVectorType::DependentSizedExtVectorType(
246 const ASTContext &Context, QualType ElementType, QualType can,
247 Expr *SizeExpr, SourceLocation loc)
248 : Type(DependentSizedExtVector, can,
249 TypeDependence::DependentInstantiation |
250 ElementType->getDependence() |
251 (SizeExpr ? toTypeDependence(SizeExpr->getDependence())
252 : TypeDependence::None)),
253 Context(Context), SizeExpr(SizeExpr), ElementType(ElementType), loc(loc) {
254 }
255
256 void
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType ElementType,Expr * SizeExpr)257 DependentSizedExtVectorType::Profile(llvm::FoldingSetNodeID &ID,
258 const ASTContext &Context,
259 QualType ElementType, Expr *SizeExpr) {
260 ID.AddPointer(ElementType.getAsOpaquePtr());
261 SizeExpr->Profile(ID, Context, true);
262 }
263
DependentAddressSpaceType(const ASTContext & Context,QualType PointeeType,QualType can,Expr * AddrSpaceExpr,SourceLocation loc)264 DependentAddressSpaceType::DependentAddressSpaceType(const ASTContext &Context,
265 QualType PointeeType,
266 QualType can,
267 Expr *AddrSpaceExpr,
268 SourceLocation loc)
269 : Type(DependentAddressSpace, can,
270 TypeDependence::DependentInstantiation |
271 PointeeType->getDependence() |
272 (AddrSpaceExpr ? toTypeDependence(AddrSpaceExpr->getDependence())
273 : TypeDependence::None)),
274 Context(Context), AddrSpaceExpr(AddrSpaceExpr), PointeeType(PointeeType),
275 loc(loc) {}
276
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType PointeeType,Expr * AddrSpaceExpr)277 void DependentAddressSpaceType::Profile(llvm::FoldingSetNodeID &ID,
278 const ASTContext &Context,
279 QualType PointeeType,
280 Expr *AddrSpaceExpr) {
281 ID.AddPointer(PointeeType.getAsOpaquePtr());
282 AddrSpaceExpr->Profile(ID, Context, true);
283 }
284
MatrixType(TypeClass tc,QualType matrixType,QualType canonType,const Expr * RowExpr,const Expr * ColumnExpr)285 MatrixType::MatrixType(TypeClass tc, QualType matrixType, QualType canonType,
286 const Expr *RowExpr, const Expr *ColumnExpr)
287 : Type(tc, canonType,
288 (RowExpr ? (matrixType->getDependence() | TypeDependence::Dependent |
289 TypeDependence::Instantiation |
290 (matrixType->isVariablyModifiedType()
291 ? TypeDependence::VariablyModified
292 : TypeDependence::None) |
293 (matrixType->containsUnexpandedParameterPack() ||
294 (RowExpr &&
295 RowExpr->containsUnexpandedParameterPack()) ||
296 (ColumnExpr &&
297 ColumnExpr->containsUnexpandedParameterPack())
298 ? TypeDependence::UnexpandedPack
299 : TypeDependence::None))
300 : matrixType->getDependence())),
301 ElementType(matrixType) {}
302
ConstantMatrixType(QualType matrixType,unsigned nRows,unsigned nColumns,QualType canonType)303 ConstantMatrixType::ConstantMatrixType(QualType matrixType, unsigned nRows,
304 unsigned nColumns, QualType canonType)
305 : ConstantMatrixType(ConstantMatrix, matrixType, nRows, nColumns,
306 canonType) {}
307
ConstantMatrixType(TypeClass tc,QualType matrixType,unsigned nRows,unsigned nColumns,QualType canonType)308 ConstantMatrixType::ConstantMatrixType(TypeClass tc, QualType matrixType,
309 unsigned nRows, unsigned nColumns,
310 QualType canonType)
311 : MatrixType(tc, matrixType, canonType), NumRows(nRows),
312 NumColumns(nColumns) {}
313
DependentSizedMatrixType(const ASTContext & CTX,QualType ElementType,QualType CanonicalType,Expr * RowExpr,Expr * ColumnExpr,SourceLocation loc)314 DependentSizedMatrixType::DependentSizedMatrixType(
315 const ASTContext &CTX, QualType ElementType, QualType CanonicalType,
316 Expr *RowExpr, Expr *ColumnExpr, SourceLocation loc)
317 : MatrixType(DependentSizedMatrix, ElementType, CanonicalType, RowExpr,
318 ColumnExpr),
319 Context(CTX), RowExpr(RowExpr), ColumnExpr(ColumnExpr), loc(loc) {}
320
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & CTX,QualType ElementType,Expr * RowExpr,Expr * ColumnExpr)321 void DependentSizedMatrixType::Profile(llvm::FoldingSetNodeID &ID,
322 const ASTContext &CTX,
323 QualType ElementType, Expr *RowExpr,
324 Expr *ColumnExpr) {
325 ID.AddPointer(ElementType.getAsOpaquePtr());
326 RowExpr->Profile(ID, CTX, true);
327 ColumnExpr->Profile(ID, CTX, true);
328 }
329
VectorType(QualType vecType,unsigned nElements,QualType canonType,VectorKind vecKind)330 VectorType::VectorType(QualType vecType, unsigned nElements, QualType canonType,
331 VectorKind vecKind)
332 : VectorType(Vector, vecType, nElements, canonType, vecKind) {}
333
VectorType(TypeClass tc,QualType vecType,unsigned nElements,QualType canonType,VectorKind vecKind)334 VectorType::VectorType(TypeClass tc, QualType vecType, unsigned nElements,
335 QualType canonType, VectorKind vecKind)
336 : Type(tc, canonType, vecType->getDependence()), ElementType(vecType) {
337 VectorTypeBits.VecKind = vecKind;
338 VectorTypeBits.NumElements = nElements;
339 }
340
BitIntType(bool IsUnsigned,unsigned NumBits)341 BitIntType::BitIntType(bool IsUnsigned, unsigned NumBits)
342 : Type(BitInt, QualType{}, TypeDependence::None), IsUnsigned(IsUnsigned),
343 NumBits(NumBits) {}
344
DependentBitIntType(const ASTContext & Context,bool IsUnsigned,Expr * NumBitsExpr)345 DependentBitIntType::DependentBitIntType(const ASTContext &Context,
346 bool IsUnsigned, Expr *NumBitsExpr)
347 : Type(DependentBitInt, QualType{},
348 toTypeDependence(NumBitsExpr->getDependence())),
349 Context(Context), ExprAndUnsigned(NumBitsExpr, IsUnsigned) {}
350
isUnsigned() const351 bool DependentBitIntType::isUnsigned() const {
352 return ExprAndUnsigned.getInt();
353 }
354
getNumBitsExpr() const355 clang::Expr *DependentBitIntType::getNumBitsExpr() const {
356 return ExprAndUnsigned.getPointer();
357 }
358
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,bool IsUnsigned,Expr * NumBitsExpr)359 void DependentBitIntType::Profile(llvm::FoldingSetNodeID &ID,
360 const ASTContext &Context, bool IsUnsigned,
361 Expr *NumBitsExpr) {
362 ID.AddBoolean(IsUnsigned);
363 NumBitsExpr->Profile(ID, Context, true);
364 }
365
366 /// getArrayElementTypeNoTypeQual - If this is an array type, return the
367 /// element type of the array, potentially with type qualifiers missing.
368 /// This method should never be used when type qualifiers are meaningful.
getArrayElementTypeNoTypeQual() const369 const Type *Type::getArrayElementTypeNoTypeQual() const {
370 // If this is directly an array type, return it.
371 if (const auto *ATy = dyn_cast<ArrayType>(this))
372 return ATy->getElementType().getTypePtr();
373
374 // If the canonical form of this type isn't the right kind, reject it.
375 if (!isa<ArrayType>(CanonicalType))
376 return nullptr;
377
378 // If this is a typedef for an array type, strip the typedef off without
379 // losing all typedef information.
380 return cast<ArrayType>(getUnqualifiedDesugaredType())
381 ->getElementType().getTypePtr();
382 }
383
384 /// getDesugaredType - Return the specified type with any "sugar" removed from
385 /// the type. This takes off typedefs, typeof's etc. If the outer level of
386 /// the type is already concrete, it returns it unmodified. This is similar
387 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
388 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
389 /// concrete.
getDesugaredType(QualType T,const ASTContext & Context)390 QualType QualType::getDesugaredType(QualType T, const ASTContext &Context) {
391 SplitQualType split = getSplitDesugaredType(T);
392 return Context.getQualifiedType(split.Ty, split.Quals);
393 }
394
getSingleStepDesugaredTypeImpl(QualType type,const ASTContext & Context)395 QualType QualType::getSingleStepDesugaredTypeImpl(QualType type,
396 const ASTContext &Context) {
397 SplitQualType split = type.split();
398 QualType desugar = split.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
399 return Context.getQualifiedType(desugar, split.Quals);
400 }
401
402 // Check that no type class is polymorphic. LLVM style RTTI should be used
403 // instead. If absolutely needed an exception can still be added here by
404 // defining the appropriate macro (but please don't do this).
405 #define TYPE(CLASS, BASE) \
406 static_assert(!std::is_polymorphic<CLASS##Type>::value, \
407 #CLASS "Type should not be polymorphic!");
408 #include "clang/AST/TypeNodes.inc"
409
410 // Check that no type class has a non-trival destructor. Types are
411 // allocated with the BumpPtrAllocator from ASTContext and therefore
412 // their destructor is not executed.
413 //
414 // FIXME: ConstantArrayType is not trivially destructible because of its
415 // APInt member. It should be replaced in favor of ASTContext allocation.
416 #define TYPE(CLASS, BASE) \
417 static_assert(std::is_trivially_destructible<CLASS##Type>::value || \
418 std::is_same<CLASS##Type, ConstantArrayType>::value, \
419 #CLASS "Type should be trivially destructible!");
420 #include "clang/AST/TypeNodes.inc"
421
getLocallyUnqualifiedSingleStepDesugaredType() const422 QualType Type::getLocallyUnqualifiedSingleStepDesugaredType() const {
423 switch (getTypeClass()) {
424 #define ABSTRACT_TYPE(Class, Parent)
425 #define TYPE(Class, Parent) \
426 case Type::Class: { \
427 const auto *ty = cast<Class##Type>(this); \
428 if (!ty->isSugared()) return QualType(ty, 0); \
429 return ty->desugar(); \
430 }
431 #include "clang/AST/TypeNodes.inc"
432 }
433 llvm_unreachable("bad type kind!");
434 }
435
getSplitDesugaredType(QualType T)436 SplitQualType QualType::getSplitDesugaredType(QualType T) {
437 QualifierCollector Qs;
438
439 QualType Cur = T;
440 while (true) {
441 const Type *CurTy = Qs.strip(Cur);
442 switch (CurTy->getTypeClass()) {
443 #define ABSTRACT_TYPE(Class, Parent)
444 #define TYPE(Class, Parent) \
445 case Type::Class: { \
446 const auto *Ty = cast<Class##Type>(CurTy); \
447 if (!Ty->isSugared()) \
448 return SplitQualType(Ty, Qs); \
449 Cur = Ty->desugar(); \
450 break; \
451 }
452 #include "clang/AST/TypeNodes.inc"
453 }
454 }
455 }
456
getSplitUnqualifiedTypeImpl(QualType type)457 SplitQualType QualType::getSplitUnqualifiedTypeImpl(QualType type) {
458 SplitQualType split = type.split();
459
460 // All the qualifiers we've seen so far.
461 Qualifiers quals = split.Quals;
462
463 // The last type node we saw with any nodes inside it.
464 const Type *lastTypeWithQuals = split.Ty;
465
466 while (true) {
467 QualType next;
468
469 // Do a single-step desugar, aborting the loop if the type isn't
470 // sugared.
471 switch (split.Ty->getTypeClass()) {
472 #define ABSTRACT_TYPE(Class, Parent)
473 #define TYPE(Class, Parent) \
474 case Type::Class: { \
475 const auto *ty = cast<Class##Type>(split.Ty); \
476 if (!ty->isSugared()) goto done; \
477 next = ty->desugar(); \
478 break; \
479 }
480 #include "clang/AST/TypeNodes.inc"
481 }
482
483 // Otherwise, split the underlying type. If that yields qualifiers,
484 // update the information.
485 split = next.split();
486 if (!split.Quals.empty()) {
487 lastTypeWithQuals = split.Ty;
488 quals.addConsistentQualifiers(split.Quals);
489 }
490 }
491
492 done:
493 return SplitQualType(lastTypeWithQuals, quals);
494 }
495
IgnoreParens(QualType T)496 QualType QualType::IgnoreParens(QualType T) {
497 // FIXME: this seems inherently un-qualifiers-safe.
498 while (const auto *PT = T->getAs<ParenType>())
499 T = PT->getInnerType();
500 return T;
501 }
502
503 /// This will check for a T (which should be a Type which can act as
504 /// sugar, such as a TypedefType) by removing any existing sugar until it
505 /// reaches a T or a non-sugared type.
getAsSugar(const Type * Cur)506 template<typename T> static const T *getAsSugar(const Type *Cur) {
507 while (true) {
508 if (const auto *Sugar = dyn_cast<T>(Cur))
509 return Sugar;
510 switch (Cur->getTypeClass()) {
511 #define ABSTRACT_TYPE(Class, Parent)
512 #define TYPE(Class, Parent) \
513 case Type::Class: { \
514 const auto *Ty = cast<Class##Type>(Cur); \
515 if (!Ty->isSugared()) return 0; \
516 Cur = Ty->desugar().getTypePtr(); \
517 break; \
518 }
519 #include "clang/AST/TypeNodes.inc"
520 }
521 }
522 }
523
getAs() const524 template <> const TypedefType *Type::getAs() const {
525 return getAsSugar<TypedefType>(this);
526 }
527
getAs() const528 template <> const UsingType *Type::getAs() const {
529 return getAsSugar<UsingType>(this);
530 }
531
getAs() const532 template <> const TemplateSpecializationType *Type::getAs() const {
533 return getAsSugar<TemplateSpecializationType>(this);
534 }
535
getAs() const536 template <> const AttributedType *Type::getAs() const {
537 return getAsSugar<AttributedType>(this);
538 }
539
540 /// getUnqualifiedDesugaredType - Pull any qualifiers and syntactic
541 /// sugar off the given type. This should produce an object of the
542 /// same dynamic type as the canonical type.
getUnqualifiedDesugaredType() const543 const Type *Type::getUnqualifiedDesugaredType() const {
544 const Type *Cur = this;
545
546 while (true) {
547 switch (Cur->getTypeClass()) {
548 #define ABSTRACT_TYPE(Class, Parent)
549 #define TYPE(Class, Parent) \
550 case Class: { \
551 const auto *Ty = cast<Class##Type>(Cur); \
552 if (!Ty->isSugared()) return Cur; \
553 Cur = Ty->desugar().getTypePtr(); \
554 break; \
555 }
556 #include "clang/AST/TypeNodes.inc"
557 }
558 }
559 }
560
isClassType() const561 bool Type::isClassType() const {
562 if (const auto *RT = getAs<RecordType>())
563 return RT->getDecl()->isClass();
564 return false;
565 }
566
isStructureType() const567 bool Type::isStructureType() const {
568 if (const auto *RT = getAs<RecordType>())
569 return RT->getDecl()->isStruct();
570 return false;
571 }
572
isObjCBoxableRecordType() const573 bool Type::isObjCBoxableRecordType() const {
574 if (const auto *RT = getAs<RecordType>())
575 return RT->getDecl()->hasAttr<ObjCBoxableAttr>();
576 return false;
577 }
578
isInterfaceType() const579 bool Type::isInterfaceType() const {
580 if (const auto *RT = getAs<RecordType>())
581 return RT->getDecl()->isInterface();
582 return false;
583 }
584
isStructureOrClassType() const585 bool Type::isStructureOrClassType() const {
586 if (const auto *RT = getAs<RecordType>()) {
587 RecordDecl *RD = RT->getDecl();
588 return RD->isStruct() || RD->isClass() || RD->isInterface();
589 }
590 return false;
591 }
592
isVoidPointerType() const593 bool Type::isVoidPointerType() const {
594 if (const auto *PT = getAs<PointerType>())
595 return PT->getPointeeType()->isVoidType();
596 return false;
597 }
598
isUnionType() const599 bool Type::isUnionType() const {
600 if (const auto *RT = getAs<RecordType>())
601 return RT->getDecl()->isUnion();
602 return false;
603 }
604
isComplexType() const605 bool Type::isComplexType() const {
606 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
607 return CT->getElementType()->isFloatingType();
608 return false;
609 }
610
isComplexIntegerType() const611 bool Type::isComplexIntegerType() const {
612 // Check for GCC complex integer extension.
613 return getAsComplexIntegerType();
614 }
615
isScopedEnumeralType() const616 bool Type::isScopedEnumeralType() const {
617 if (const auto *ET = getAs<EnumType>())
618 return ET->getDecl()->isScoped();
619 return false;
620 }
621
getAsComplexIntegerType() const622 const ComplexType *Type::getAsComplexIntegerType() const {
623 if (const auto *Complex = getAs<ComplexType>())
624 if (Complex->getElementType()->isIntegerType())
625 return Complex;
626 return nullptr;
627 }
628
getPointeeType() const629 QualType Type::getPointeeType() const {
630 if (const auto *PT = getAs<PointerType>())
631 return PT->getPointeeType();
632 if (const auto *OPT = getAs<ObjCObjectPointerType>())
633 return OPT->getPointeeType();
634 if (const auto *BPT = getAs<BlockPointerType>())
635 return BPT->getPointeeType();
636 if (const auto *RT = getAs<ReferenceType>())
637 return RT->getPointeeType();
638 if (const auto *MPT = getAs<MemberPointerType>())
639 return MPT->getPointeeType();
640 if (const auto *DT = getAs<DecayedType>())
641 return DT->getPointeeType();
642 return {};
643 }
644
getAsStructureType() const645 const RecordType *Type::getAsStructureType() const {
646 // If this is directly a structure type, return it.
647 if (const auto *RT = dyn_cast<RecordType>(this)) {
648 if (RT->getDecl()->isStruct())
649 return RT;
650 }
651
652 // If the canonical form of this type isn't the right kind, reject it.
653 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
654 if (!RT->getDecl()->isStruct())
655 return nullptr;
656
657 // If this is a typedef for a structure type, strip the typedef off without
658 // losing all typedef information.
659 return cast<RecordType>(getUnqualifiedDesugaredType());
660 }
661 return nullptr;
662 }
663
getAsUnionType() const664 const RecordType *Type::getAsUnionType() const {
665 // If this is directly a union type, return it.
666 if (const auto *RT = dyn_cast<RecordType>(this)) {
667 if (RT->getDecl()->isUnion())
668 return RT;
669 }
670
671 // If the canonical form of this type isn't the right kind, reject it.
672 if (const auto *RT = dyn_cast<RecordType>(CanonicalType)) {
673 if (!RT->getDecl()->isUnion())
674 return nullptr;
675
676 // If this is a typedef for a union type, strip the typedef off without
677 // losing all typedef information.
678 return cast<RecordType>(getUnqualifiedDesugaredType());
679 }
680
681 return nullptr;
682 }
683
isObjCIdOrObjectKindOfType(const ASTContext & ctx,const ObjCObjectType * & bound) const684 bool Type::isObjCIdOrObjectKindOfType(const ASTContext &ctx,
685 const ObjCObjectType *&bound) const {
686 bound = nullptr;
687
688 const auto *OPT = getAs<ObjCObjectPointerType>();
689 if (!OPT)
690 return false;
691
692 // Easy case: id.
693 if (OPT->isObjCIdType())
694 return true;
695
696 // If it's not a __kindof type, reject it now.
697 if (!OPT->isKindOfType())
698 return false;
699
700 // If it's Class or qualified Class, it's not an object type.
701 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType())
702 return false;
703
704 // Figure out the type bound for the __kindof type.
705 bound = OPT->getObjectType()->stripObjCKindOfTypeAndQuals(ctx)
706 ->getAs<ObjCObjectType>();
707 return true;
708 }
709
isObjCClassOrClassKindOfType() const710 bool Type::isObjCClassOrClassKindOfType() const {
711 const auto *OPT = getAs<ObjCObjectPointerType>();
712 if (!OPT)
713 return false;
714
715 // Easy case: Class.
716 if (OPT->isObjCClassType())
717 return true;
718
719 // If it's not a __kindof type, reject it now.
720 if (!OPT->isKindOfType())
721 return false;
722
723 // If it's Class or qualified Class, it's a class __kindof type.
724 return OPT->isObjCClassType() || OPT->isObjCQualifiedClassType();
725 }
726
ObjCTypeParamType(const ObjCTypeParamDecl * D,QualType can,ArrayRef<ObjCProtocolDecl * > protocols)727 ObjCTypeParamType::ObjCTypeParamType(const ObjCTypeParamDecl *D, QualType can,
728 ArrayRef<ObjCProtocolDecl *> protocols)
729 : Type(ObjCTypeParam, can, toSemanticDependence(can->getDependence())),
730 OTPDecl(const_cast<ObjCTypeParamDecl *>(D)) {
731 initialize(protocols);
732 }
733
ObjCObjectType(QualType Canonical,QualType Base,ArrayRef<QualType> typeArgs,ArrayRef<ObjCProtocolDecl * > protocols,bool isKindOf)734 ObjCObjectType::ObjCObjectType(QualType Canonical, QualType Base,
735 ArrayRef<QualType> typeArgs,
736 ArrayRef<ObjCProtocolDecl *> protocols,
737 bool isKindOf)
738 : Type(ObjCObject, Canonical, Base->getDependence()), BaseType(Base) {
739 ObjCObjectTypeBits.IsKindOf = isKindOf;
740
741 ObjCObjectTypeBits.NumTypeArgs = typeArgs.size();
742 assert(getTypeArgsAsWritten().size() == typeArgs.size() &&
743 "bitfield overflow in type argument count");
744 if (!typeArgs.empty())
745 memcpy(getTypeArgStorage(), typeArgs.data(),
746 typeArgs.size() * sizeof(QualType));
747
748 for (auto typeArg : typeArgs) {
749 addDependence(typeArg->getDependence() & ~TypeDependence::VariablyModified);
750 }
751 // Initialize the protocol qualifiers. The protocol storage is known
752 // after we set number of type arguments.
753 initialize(protocols);
754 }
755
isSpecialized() const756 bool ObjCObjectType::isSpecialized() const {
757 // If we have type arguments written here, the type is specialized.
758 if (ObjCObjectTypeBits.NumTypeArgs > 0)
759 return true;
760
761 // Otherwise, check whether the base type is specialized.
762 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
763 // Terminate when we reach an interface type.
764 if (isa<ObjCInterfaceType>(objcObject))
765 return false;
766
767 return objcObject->isSpecialized();
768 }
769
770 // Not specialized.
771 return false;
772 }
773
getTypeArgs() const774 ArrayRef<QualType> ObjCObjectType::getTypeArgs() const {
775 // We have type arguments written on this type.
776 if (isSpecializedAsWritten())
777 return getTypeArgsAsWritten();
778
779 // Look at the base type, which might have type arguments.
780 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
781 // Terminate when we reach an interface type.
782 if (isa<ObjCInterfaceType>(objcObject))
783 return {};
784
785 return objcObject->getTypeArgs();
786 }
787
788 // No type arguments.
789 return {};
790 }
791
isKindOfType() const792 bool ObjCObjectType::isKindOfType() const {
793 if (isKindOfTypeAsWritten())
794 return true;
795
796 // Look at the base type, which might have type arguments.
797 if (const auto objcObject = getBaseType()->getAs<ObjCObjectType>()) {
798 // Terminate when we reach an interface type.
799 if (isa<ObjCInterfaceType>(objcObject))
800 return false;
801
802 return objcObject->isKindOfType();
803 }
804
805 // Not a "__kindof" type.
806 return false;
807 }
808
stripObjCKindOfTypeAndQuals(const ASTContext & ctx) const809 QualType ObjCObjectType::stripObjCKindOfTypeAndQuals(
810 const ASTContext &ctx) const {
811 if (!isKindOfType() && qual_empty())
812 return QualType(this, 0);
813
814 // Recursively strip __kindof.
815 SplitQualType splitBaseType = getBaseType().split();
816 QualType baseType(splitBaseType.Ty, 0);
817 if (const auto *baseObj = splitBaseType.Ty->getAs<ObjCObjectType>())
818 baseType = baseObj->stripObjCKindOfTypeAndQuals(ctx);
819
820 return ctx.getObjCObjectType(ctx.getQualifiedType(baseType,
821 splitBaseType.Quals),
822 getTypeArgsAsWritten(),
823 /*protocols=*/{},
824 /*isKindOf=*/false);
825 }
826
getDecl() const827 ObjCInterfaceDecl *ObjCInterfaceType::getDecl() const {
828 ObjCInterfaceDecl *Canon = Decl->getCanonicalDecl();
829 if (ObjCInterfaceDecl *Def = Canon->getDefinition())
830 return Def;
831 return Canon;
832 }
833
stripObjCKindOfTypeAndQuals(const ASTContext & ctx) const834 const ObjCObjectPointerType *ObjCObjectPointerType::stripObjCKindOfTypeAndQuals(
835 const ASTContext &ctx) const {
836 if (!isKindOfType() && qual_empty())
837 return this;
838
839 QualType obj = getObjectType()->stripObjCKindOfTypeAndQuals(ctx);
840 return ctx.getObjCObjectPointerType(obj)->castAs<ObjCObjectPointerType>();
841 }
842
843 namespace {
844
845 /// Visitor used to perform a simple type transformation that does not change
846 /// the semantics of the type.
847 template <typename Derived>
848 struct SimpleTransformVisitor : public TypeVisitor<Derived, QualType> {
849 ASTContext &Ctx;
850
recurse__anonc3ce83e00111::SimpleTransformVisitor851 QualType recurse(QualType type) {
852 // Split out the qualifiers from the type.
853 SplitQualType splitType = type.split();
854
855 // Visit the type itself.
856 QualType result = static_cast<Derived *>(this)->Visit(splitType.Ty);
857 if (result.isNull())
858 return result;
859
860 // Reconstruct the transformed type by applying the local qualifiers
861 // from the split type.
862 return Ctx.getQualifiedType(result, splitType.Quals);
863 }
864
865 public:
SimpleTransformVisitor__anonc3ce83e00111::SimpleTransformVisitor866 explicit SimpleTransformVisitor(ASTContext &ctx) : Ctx(ctx) {}
867
868 // None of the clients of this transformation can occur where
869 // there are dependent types, so skip dependent types.
870 #define TYPE(Class, Base)
871 #define DEPENDENT_TYPE(Class, Base) \
872 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
873 #include "clang/AST/TypeNodes.inc"
874
875 #define TRIVIAL_TYPE_CLASS(Class) \
876 QualType Visit##Class##Type(const Class##Type *T) { return QualType(T, 0); }
877 #define SUGARED_TYPE_CLASS(Class) \
878 QualType Visit##Class##Type(const Class##Type *T) { \
879 if (!T->isSugared()) \
880 return QualType(T, 0); \
881 QualType desugaredType = recurse(T->desugar()); \
882 if (desugaredType.isNull()) \
883 return {}; \
884 if (desugaredType.getAsOpaquePtr() == T->desugar().getAsOpaquePtr()) \
885 return QualType(T, 0); \
886 return desugaredType; \
887 }
888
TRIVIAL_TYPE_CLASS__anonc3ce83e00111::SimpleTransformVisitor889 TRIVIAL_TYPE_CLASS(Builtin)
890
891 QualType VisitComplexType(const ComplexType *T) {
892 QualType elementType = recurse(T->getElementType());
893 if (elementType.isNull())
894 return {};
895
896 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
897 return QualType(T, 0);
898
899 return Ctx.getComplexType(elementType);
900 }
901
VisitPointerType__anonc3ce83e00111::SimpleTransformVisitor902 QualType VisitPointerType(const PointerType *T) {
903 QualType pointeeType = recurse(T->getPointeeType());
904 if (pointeeType.isNull())
905 return {};
906
907 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
908 return QualType(T, 0);
909
910 return Ctx.getPointerType(pointeeType);
911 }
912
VisitBlockPointerType__anonc3ce83e00111::SimpleTransformVisitor913 QualType VisitBlockPointerType(const BlockPointerType *T) {
914 QualType pointeeType = recurse(T->getPointeeType());
915 if (pointeeType.isNull())
916 return {};
917
918 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
919 return QualType(T, 0);
920
921 return Ctx.getBlockPointerType(pointeeType);
922 }
923
VisitLValueReferenceType__anonc3ce83e00111::SimpleTransformVisitor924 QualType VisitLValueReferenceType(const LValueReferenceType *T) {
925 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
926 if (pointeeType.isNull())
927 return {};
928
929 if (pointeeType.getAsOpaquePtr()
930 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
931 return QualType(T, 0);
932
933 return Ctx.getLValueReferenceType(pointeeType, T->isSpelledAsLValue());
934 }
935
VisitRValueReferenceType__anonc3ce83e00111::SimpleTransformVisitor936 QualType VisitRValueReferenceType(const RValueReferenceType *T) {
937 QualType pointeeType = recurse(T->getPointeeTypeAsWritten());
938 if (pointeeType.isNull())
939 return {};
940
941 if (pointeeType.getAsOpaquePtr()
942 == T->getPointeeTypeAsWritten().getAsOpaquePtr())
943 return QualType(T, 0);
944
945 return Ctx.getRValueReferenceType(pointeeType);
946 }
947
VisitMemberPointerType__anonc3ce83e00111::SimpleTransformVisitor948 QualType VisitMemberPointerType(const MemberPointerType *T) {
949 QualType pointeeType = recurse(T->getPointeeType());
950 if (pointeeType.isNull())
951 return {};
952
953 if (pointeeType.getAsOpaquePtr() == T->getPointeeType().getAsOpaquePtr())
954 return QualType(T, 0);
955
956 return Ctx.getMemberPointerType(pointeeType, T->getClass());
957 }
958
VisitConstantArrayType__anonc3ce83e00111::SimpleTransformVisitor959 QualType VisitConstantArrayType(const ConstantArrayType *T) {
960 QualType elementType = recurse(T->getElementType());
961 if (elementType.isNull())
962 return {};
963
964 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
965 return QualType(T, 0);
966
967 return Ctx.getConstantArrayType(elementType, T->getSize(), T->getSizeExpr(),
968 T->getSizeModifier(),
969 T->getIndexTypeCVRQualifiers());
970 }
971
VisitVariableArrayType__anonc3ce83e00111::SimpleTransformVisitor972 QualType VisitVariableArrayType(const VariableArrayType *T) {
973 QualType elementType = recurse(T->getElementType());
974 if (elementType.isNull())
975 return {};
976
977 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
978 return QualType(T, 0);
979
980 return Ctx.getVariableArrayType(elementType, T->getSizeExpr(),
981 T->getSizeModifier(),
982 T->getIndexTypeCVRQualifiers(),
983 T->getBracketsRange());
984 }
985
VisitIncompleteArrayType__anonc3ce83e00111::SimpleTransformVisitor986 QualType VisitIncompleteArrayType(const IncompleteArrayType *T) {
987 QualType elementType = recurse(T->getElementType());
988 if (elementType.isNull())
989 return {};
990
991 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
992 return QualType(T, 0);
993
994 return Ctx.getIncompleteArrayType(elementType, T->getSizeModifier(),
995 T->getIndexTypeCVRQualifiers());
996 }
997
VisitVectorType__anonc3ce83e00111::SimpleTransformVisitor998 QualType VisitVectorType(const VectorType *T) {
999 QualType elementType = recurse(T->getElementType());
1000 if (elementType.isNull())
1001 return {};
1002
1003 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1004 return QualType(T, 0);
1005
1006 return Ctx.getVectorType(elementType, T->getNumElements(),
1007 T->getVectorKind());
1008 }
1009
VisitExtVectorType__anonc3ce83e00111::SimpleTransformVisitor1010 QualType VisitExtVectorType(const ExtVectorType *T) {
1011 QualType elementType = recurse(T->getElementType());
1012 if (elementType.isNull())
1013 return {};
1014
1015 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1016 return QualType(T, 0);
1017
1018 return Ctx.getExtVectorType(elementType, T->getNumElements());
1019 }
1020
VisitConstantMatrixType__anonc3ce83e00111::SimpleTransformVisitor1021 QualType VisitConstantMatrixType(const ConstantMatrixType *T) {
1022 QualType elementType = recurse(T->getElementType());
1023 if (elementType.isNull())
1024 return {};
1025 if (elementType.getAsOpaquePtr() == T->getElementType().getAsOpaquePtr())
1026 return QualType(T, 0);
1027
1028 return Ctx.getConstantMatrixType(elementType, T->getNumRows(),
1029 T->getNumColumns());
1030 }
1031
VisitFunctionNoProtoType__anonc3ce83e00111::SimpleTransformVisitor1032 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1033 QualType returnType = recurse(T->getReturnType());
1034 if (returnType.isNull())
1035 return {};
1036
1037 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr())
1038 return QualType(T, 0);
1039
1040 return Ctx.getFunctionNoProtoType(returnType, T->getExtInfo());
1041 }
1042
VisitFunctionProtoType__anonc3ce83e00111::SimpleTransformVisitor1043 QualType VisitFunctionProtoType(const FunctionProtoType *T) {
1044 QualType returnType = recurse(T->getReturnType());
1045 if (returnType.isNull())
1046 return {};
1047
1048 // Transform parameter types.
1049 SmallVector<QualType, 4> paramTypes;
1050 bool paramChanged = false;
1051 for (auto paramType : T->getParamTypes()) {
1052 QualType newParamType = recurse(paramType);
1053 if (newParamType.isNull())
1054 return {};
1055
1056 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1057 paramChanged = true;
1058
1059 paramTypes.push_back(newParamType);
1060 }
1061
1062 // Transform extended info.
1063 FunctionProtoType::ExtProtoInfo info = T->getExtProtoInfo();
1064 bool exceptionChanged = false;
1065 if (info.ExceptionSpec.Type == EST_Dynamic) {
1066 SmallVector<QualType, 4> exceptionTypes;
1067 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1068 QualType newExceptionType = recurse(exceptionType);
1069 if (newExceptionType.isNull())
1070 return {};
1071
1072 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1073 exceptionChanged = true;
1074
1075 exceptionTypes.push_back(newExceptionType);
1076 }
1077
1078 if (exceptionChanged) {
1079 info.ExceptionSpec.Exceptions =
1080 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1081 }
1082 }
1083
1084 if (returnType.getAsOpaquePtr() == T->getReturnType().getAsOpaquePtr() &&
1085 !paramChanged && !exceptionChanged)
1086 return QualType(T, 0);
1087
1088 return Ctx.getFunctionType(returnType, paramTypes, info);
1089 }
1090
VisitParenType__anonc3ce83e00111::SimpleTransformVisitor1091 QualType VisitParenType(const ParenType *T) {
1092 QualType innerType = recurse(T->getInnerType());
1093 if (innerType.isNull())
1094 return {};
1095
1096 if (innerType.getAsOpaquePtr() == T->getInnerType().getAsOpaquePtr())
1097 return QualType(T, 0);
1098
1099 return Ctx.getParenType(innerType);
1100 }
1101
1102 SUGARED_TYPE_CLASS(Typedef)
SUGARED_TYPE_CLASS__anonc3ce83e00111::SimpleTransformVisitor1103 SUGARED_TYPE_CLASS(ObjCTypeParam)
1104 SUGARED_TYPE_CLASS(MacroQualified)
1105
1106 QualType VisitAdjustedType(const AdjustedType *T) {
1107 QualType originalType = recurse(T->getOriginalType());
1108 if (originalType.isNull())
1109 return {};
1110
1111 QualType adjustedType = recurse(T->getAdjustedType());
1112 if (adjustedType.isNull())
1113 return {};
1114
1115 if (originalType.getAsOpaquePtr()
1116 == T->getOriginalType().getAsOpaquePtr() &&
1117 adjustedType.getAsOpaquePtr() == T->getAdjustedType().getAsOpaquePtr())
1118 return QualType(T, 0);
1119
1120 return Ctx.getAdjustedType(originalType, adjustedType);
1121 }
1122
VisitDecayedType__anonc3ce83e00111::SimpleTransformVisitor1123 QualType VisitDecayedType(const DecayedType *T) {
1124 QualType originalType = recurse(T->getOriginalType());
1125 if (originalType.isNull())
1126 return {};
1127
1128 if (originalType.getAsOpaquePtr()
1129 == T->getOriginalType().getAsOpaquePtr())
1130 return QualType(T, 0);
1131
1132 return Ctx.getDecayedType(originalType);
1133 }
1134
1135 SUGARED_TYPE_CLASS(TypeOfExpr)
SUGARED_TYPE_CLASS__anonc3ce83e00111::SimpleTransformVisitor1136 SUGARED_TYPE_CLASS(TypeOf)
1137 SUGARED_TYPE_CLASS(Decltype)
1138 SUGARED_TYPE_CLASS(UnaryTransform)
1139 TRIVIAL_TYPE_CLASS(Record)
1140 TRIVIAL_TYPE_CLASS(Enum)
1141
1142 // FIXME: Non-trivial to implement, but important for C++
1143 SUGARED_TYPE_CLASS(Elaborated)
1144
1145 QualType VisitAttributedType(const AttributedType *T) {
1146 QualType modifiedType = recurse(T->getModifiedType());
1147 if (modifiedType.isNull())
1148 return {};
1149
1150 QualType equivalentType = recurse(T->getEquivalentType());
1151 if (equivalentType.isNull())
1152 return {};
1153
1154 if (modifiedType.getAsOpaquePtr()
1155 == T->getModifiedType().getAsOpaquePtr() &&
1156 equivalentType.getAsOpaquePtr()
1157 == T->getEquivalentType().getAsOpaquePtr())
1158 return QualType(T, 0);
1159
1160 return Ctx.getAttributedType(T->getAttrKind(), modifiedType,
1161 equivalentType);
1162 }
1163
VisitSubstTemplateTypeParmType__anonc3ce83e00111::SimpleTransformVisitor1164 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1165 QualType replacementType = recurse(T->getReplacementType());
1166 if (replacementType.isNull())
1167 return {};
1168
1169 if (replacementType.getAsOpaquePtr()
1170 == T->getReplacementType().getAsOpaquePtr())
1171 return QualType(T, 0);
1172
1173 return Ctx.getSubstTemplateTypeParmType(replacementType,
1174 T->getAssociatedDecl(),
1175 T->getIndex(), T->getPackIndex());
1176 }
1177
1178 // FIXME: Non-trivial to implement, but important for C++
SUGARED_TYPE_CLASS__anonc3ce83e00111::SimpleTransformVisitor1179 SUGARED_TYPE_CLASS(TemplateSpecialization)
1180
1181 QualType VisitAutoType(const AutoType *T) {
1182 if (!T->isDeduced())
1183 return QualType(T, 0);
1184
1185 QualType deducedType = recurse(T->getDeducedType());
1186 if (deducedType.isNull())
1187 return {};
1188
1189 if (deducedType.getAsOpaquePtr()
1190 == T->getDeducedType().getAsOpaquePtr())
1191 return QualType(T, 0);
1192
1193 return Ctx.getAutoType(deducedType, T->getKeyword(),
1194 T->isDependentType(), /*IsPack=*/false,
1195 T->getTypeConstraintConcept(),
1196 T->getTypeConstraintArguments());
1197 }
1198
VisitObjCObjectType__anonc3ce83e00111::SimpleTransformVisitor1199 QualType VisitObjCObjectType(const ObjCObjectType *T) {
1200 QualType baseType = recurse(T->getBaseType());
1201 if (baseType.isNull())
1202 return {};
1203
1204 // Transform type arguments.
1205 bool typeArgChanged = false;
1206 SmallVector<QualType, 4> typeArgs;
1207 for (auto typeArg : T->getTypeArgsAsWritten()) {
1208 QualType newTypeArg = recurse(typeArg);
1209 if (newTypeArg.isNull())
1210 return {};
1211
1212 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr())
1213 typeArgChanged = true;
1214
1215 typeArgs.push_back(newTypeArg);
1216 }
1217
1218 if (baseType.getAsOpaquePtr() == T->getBaseType().getAsOpaquePtr() &&
1219 !typeArgChanged)
1220 return QualType(T, 0);
1221
1222 return Ctx.getObjCObjectType(
1223 baseType, typeArgs,
1224 llvm::ArrayRef(T->qual_begin(), T->getNumProtocols()),
1225 T->isKindOfTypeAsWritten());
1226 }
1227
TRIVIAL_TYPE_CLASS__anonc3ce83e00111::SimpleTransformVisitor1228 TRIVIAL_TYPE_CLASS(ObjCInterface)
1229
1230 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1231 QualType pointeeType = recurse(T->getPointeeType());
1232 if (pointeeType.isNull())
1233 return {};
1234
1235 if (pointeeType.getAsOpaquePtr()
1236 == T->getPointeeType().getAsOpaquePtr())
1237 return QualType(T, 0);
1238
1239 return Ctx.getObjCObjectPointerType(pointeeType);
1240 }
1241
VisitAtomicType__anonc3ce83e00111::SimpleTransformVisitor1242 QualType VisitAtomicType(const AtomicType *T) {
1243 QualType valueType = recurse(T->getValueType());
1244 if (valueType.isNull())
1245 return {};
1246
1247 if (valueType.getAsOpaquePtr()
1248 == T->getValueType().getAsOpaquePtr())
1249 return QualType(T, 0);
1250
1251 return Ctx.getAtomicType(valueType);
1252 }
1253
1254 #undef TRIVIAL_TYPE_CLASS
1255 #undef SUGARED_TYPE_CLASS
1256 };
1257
1258 struct SubstObjCTypeArgsVisitor
1259 : public SimpleTransformVisitor<SubstObjCTypeArgsVisitor> {
1260 using BaseType = SimpleTransformVisitor<SubstObjCTypeArgsVisitor>;
1261
1262 ArrayRef<QualType> TypeArgs;
1263 ObjCSubstitutionContext SubstContext;
1264
SubstObjCTypeArgsVisitor__anonc3ce83e00111::SubstObjCTypeArgsVisitor1265 SubstObjCTypeArgsVisitor(ASTContext &ctx, ArrayRef<QualType> typeArgs,
1266 ObjCSubstitutionContext context)
1267 : BaseType(ctx), TypeArgs(typeArgs), SubstContext(context) {}
1268
VisitObjCTypeParamType__anonc3ce83e00111::SubstObjCTypeArgsVisitor1269 QualType VisitObjCTypeParamType(const ObjCTypeParamType *OTPTy) {
1270 // Replace an Objective-C type parameter reference with the corresponding
1271 // type argument.
1272 ObjCTypeParamDecl *typeParam = OTPTy->getDecl();
1273 // If we have type arguments, use them.
1274 if (!TypeArgs.empty()) {
1275 QualType argType = TypeArgs[typeParam->getIndex()];
1276 if (OTPTy->qual_empty())
1277 return argType;
1278
1279 // Apply protocol lists if exists.
1280 bool hasError;
1281 SmallVector<ObjCProtocolDecl *, 8> protocolsVec;
1282 protocolsVec.append(OTPTy->qual_begin(), OTPTy->qual_end());
1283 ArrayRef<ObjCProtocolDecl *> protocolsToApply = protocolsVec;
1284 return Ctx.applyObjCProtocolQualifiers(
1285 argType, protocolsToApply, hasError, true/*allowOnPointerType*/);
1286 }
1287
1288 switch (SubstContext) {
1289 case ObjCSubstitutionContext::Ordinary:
1290 case ObjCSubstitutionContext::Parameter:
1291 case ObjCSubstitutionContext::Superclass:
1292 // Substitute the bound.
1293 return typeParam->getUnderlyingType();
1294
1295 case ObjCSubstitutionContext::Result:
1296 case ObjCSubstitutionContext::Property: {
1297 // Substitute the __kindof form of the underlying type.
1298 const auto *objPtr =
1299 typeParam->getUnderlyingType()->castAs<ObjCObjectPointerType>();
1300
1301 // __kindof types, id, and Class don't need an additional
1302 // __kindof.
1303 if (objPtr->isKindOfType() || objPtr->isObjCIdOrClassType())
1304 return typeParam->getUnderlyingType();
1305
1306 // Add __kindof.
1307 const auto *obj = objPtr->getObjectType();
1308 QualType resultTy = Ctx.getObjCObjectType(
1309 obj->getBaseType(), obj->getTypeArgsAsWritten(), obj->getProtocols(),
1310 /*isKindOf=*/true);
1311
1312 // Rebuild object pointer type.
1313 return Ctx.getObjCObjectPointerType(resultTy);
1314 }
1315 }
1316 llvm_unreachable("Unexpected ObjCSubstitutionContext!");
1317 }
1318
VisitFunctionType__anonc3ce83e00111::SubstObjCTypeArgsVisitor1319 QualType VisitFunctionType(const FunctionType *funcType) {
1320 // If we have a function type, update the substitution context
1321 // appropriately.
1322
1323 //Substitute result type.
1324 QualType returnType = funcType->getReturnType().substObjCTypeArgs(
1325 Ctx, TypeArgs, ObjCSubstitutionContext::Result);
1326 if (returnType.isNull())
1327 return {};
1328
1329 // Handle non-prototyped functions, which only substitute into the result
1330 // type.
1331 if (isa<FunctionNoProtoType>(funcType)) {
1332 // If the return type was unchanged, do nothing.
1333 if (returnType.getAsOpaquePtr() ==
1334 funcType->getReturnType().getAsOpaquePtr())
1335 return BaseType::VisitFunctionType(funcType);
1336
1337 // Otherwise, build a new type.
1338 return Ctx.getFunctionNoProtoType(returnType, funcType->getExtInfo());
1339 }
1340
1341 const auto *funcProtoType = cast<FunctionProtoType>(funcType);
1342
1343 // Transform parameter types.
1344 SmallVector<QualType, 4> paramTypes;
1345 bool paramChanged = false;
1346 for (auto paramType : funcProtoType->getParamTypes()) {
1347 QualType newParamType = paramType.substObjCTypeArgs(
1348 Ctx, TypeArgs, ObjCSubstitutionContext::Parameter);
1349 if (newParamType.isNull())
1350 return {};
1351
1352 if (newParamType.getAsOpaquePtr() != paramType.getAsOpaquePtr())
1353 paramChanged = true;
1354
1355 paramTypes.push_back(newParamType);
1356 }
1357
1358 // Transform extended info.
1359 FunctionProtoType::ExtProtoInfo info = funcProtoType->getExtProtoInfo();
1360 bool exceptionChanged = false;
1361 if (info.ExceptionSpec.Type == EST_Dynamic) {
1362 SmallVector<QualType, 4> exceptionTypes;
1363 for (auto exceptionType : info.ExceptionSpec.Exceptions) {
1364 QualType newExceptionType = exceptionType.substObjCTypeArgs(
1365 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1366 if (newExceptionType.isNull())
1367 return {};
1368
1369 if (newExceptionType.getAsOpaquePtr() != exceptionType.getAsOpaquePtr())
1370 exceptionChanged = true;
1371
1372 exceptionTypes.push_back(newExceptionType);
1373 }
1374
1375 if (exceptionChanged) {
1376 info.ExceptionSpec.Exceptions =
1377 llvm::ArrayRef(exceptionTypes).copy(Ctx);
1378 }
1379 }
1380
1381 if (returnType.getAsOpaquePtr() ==
1382 funcProtoType->getReturnType().getAsOpaquePtr() &&
1383 !paramChanged && !exceptionChanged)
1384 return BaseType::VisitFunctionType(funcType);
1385
1386 return Ctx.getFunctionType(returnType, paramTypes, info);
1387 }
1388
VisitObjCObjectType__anonc3ce83e00111::SubstObjCTypeArgsVisitor1389 QualType VisitObjCObjectType(const ObjCObjectType *objcObjectType) {
1390 // Substitute into the type arguments of a specialized Objective-C object
1391 // type.
1392 if (objcObjectType->isSpecializedAsWritten()) {
1393 SmallVector<QualType, 4> newTypeArgs;
1394 bool anyChanged = false;
1395 for (auto typeArg : objcObjectType->getTypeArgsAsWritten()) {
1396 QualType newTypeArg = typeArg.substObjCTypeArgs(
1397 Ctx, TypeArgs, ObjCSubstitutionContext::Ordinary);
1398 if (newTypeArg.isNull())
1399 return {};
1400
1401 if (newTypeArg.getAsOpaquePtr() != typeArg.getAsOpaquePtr()) {
1402 // If we're substituting based on an unspecialized context type,
1403 // produce an unspecialized type.
1404 ArrayRef<ObjCProtocolDecl *> protocols(
1405 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1406 if (TypeArgs.empty() &&
1407 SubstContext != ObjCSubstitutionContext::Superclass) {
1408 return Ctx.getObjCObjectType(
1409 objcObjectType->getBaseType(), {}, protocols,
1410 objcObjectType->isKindOfTypeAsWritten());
1411 }
1412
1413 anyChanged = true;
1414 }
1415
1416 newTypeArgs.push_back(newTypeArg);
1417 }
1418
1419 if (anyChanged) {
1420 ArrayRef<ObjCProtocolDecl *> protocols(
1421 objcObjectType->qual_begin(), objcObjectType->getNumProtocols());
1422 return Ctx.getObjCObjectType(objcObjectType->getBaseType(), newTypeArgs,
1423 protocols,
1424 objcObjectType->isKindOfTypeAsWritten());
1425 }
1426 }
1427
1428 return BaseType::VisitObjCObjectType(objcObjectType);
1429 }
1430
VisitAttributedType__anonc3ce83e00111::SubstObjCTypeArgsVisitor1431 QualType VisitAttributedType(const AttributedType *attrType) {
1432 QualType newType = BaseType::VisitAttributedType(attrType);
1433 if (newType.isNull())
1434 return {};
1435
1436 const auto *newAttrType = dyn_cast<AttributedType>(newType.getTypePtr());
1437 if (!newAttrType || newAttrType->getAttrKind() != attr::ObjCKindOf)
1438 return newType;
1439
1440 // Find out if it's an Objective-C object or object pointer type;
1441 QualType newEquivType = newAttrType->getEquivalentType();
1442 const ObjCObjectPointerType *ptrType =
1443 newEquivType->getAs<ObjCObjectPointerType>();
1444 const ObjCObjectType *objType = ptrType
1445 ? ptrType->getObjectType()
1446 : newEquivType->getAs<ObjCObjectType>();
1447 if (!objType)
1448 return newType;
1449
1450 // Rebuild the "equivalent" type, which pushes __kindof down into
1451 // the object type.
1452 newEquivType = Ctx.getObjCObjectType(
1453 objType->getBaseType(), objType->getTypeArgsAsWritten(),
1454 objType->getProtocols(),
1455 // There is no need to apply kindof on an unqualified id type.
1456 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
1457
1458 // If we started with an object pointer type, rebuild it.
1459 if (ptrType)
1460 newEquivType = Ctx.getObjCObjectPointerType(newEquivType);
1461
1462 // Rebuild the attributed type.
1463 return Ctx.getAttributedType(newAttrType->getAttrKind(),
1464 newAttrType->getModifiedType(), newEquivType);
1465 }
1466 };
1467
1468 struct StripObjCKindOfTypeVisitor
1469 : public SimpleTransformVisitor<StripObjCKindOfTypeVisitor> {
1470 using BaseType = SimpleTransformVisitor<StripObjCKindOfTypeVisitor>;
1471
StripObjCKindOfTypeVisitor__anonc3ce83e00111::StripObjCKindOfTypeVisitor1472 explicit StripObjCKindOfTypeVisitor(ASTContext &ctx) : BaseType(ctx) {}
1473
VisitObjCObjectType__anonc3ce83e00111::StripObjCKindOfTypeVisitor1474 QualType VisitObjCObjectType(const ObjCObjectType *objType) {
1475 if (!objType->isKindOfType())
1476 return BaseType::VisitObjCObjectType(objType);
1477
1478 QualType baseType = objType->getBaseType().stripObjCKindOfType(Ctx);
1479 return Ctx.getObjCObjectType(baseType, objType->getTypeArgsAsWritten(),
1480 objType->getProtocols(),
1481 /*isKindOf=*/false);
1482 }
1483 };
1484
1485 } // namespace
1486
UseExcessPrecision(const ASTContext & Ctx)1487 bool QualType::UseExcessPrecision(const ASTContext &Ctx) {
1488 const BuiltinType *BT = getTypePtr()->getAs<BuiltinType>();
1489 if (BT) {
1490 switch (BT->getKind()) {
1491 case BuiltinType::Kind::Float16: {
1492 const TargetInfo &TI = Ctx.getTargetInfo();
1493 if (TI.hasFloat16Type() && !TI.hasLegalHalfType() &&
1494 Ctx.getLangOpts().getFloat16ExcessPrecision() !=
1495 Ctx.getLangOpts().ExcessPrecisionKind::FPP_None)
1496 return true;
1497 return false;
1498 }
1499 default:
1500 return false;
1501 }
1502 }
1503 return false;
1504 }
1505
1506 /// Substitute the given type arguments for Objective-C type
1507 /// parameters within the given type, recursively.
substObjCTypeArgs(ASTContext & ctx,ArrayRef<QualType> typeArgs,ObjCSubstitutionContext context) const1508 QualType QualType::substObjCTypeArgs(ASTContext &ctx,
1509 ArrayRef<QualType> typeArgs,
1510 ObjCSubstitutionContext context) const {
1511 SubstObjCTypeArgsVisitor visitor(ctx, typeArgs, context);
1512 return visitor.recurse(*this);
1513 }
1514
substObjCMemberType(QualType objectType,const DeclContext * dc,ObjCSubstitutionContext context) const1515 QualType QualType::substObjCMemberType(QualType objectType,
1516 const DeclContext *dc,
1517 ObjCSubstitutionContext context) const {
1518 if (auto subs = objectType->getObjCSubstitutions(dc))
1519 return substObjCTypeArgs(dc->getParentASTContext(), *subs, context);
1520
1521 return *this;
1522 }
1523
stripObjCKindOfType(const ASTContext & constCtx) const1524 QualType QualType::stripObjCKindOfType(const ASTContext &constCtx) const {
1525 // FIXME: Because ASTContext::getAttributedType() is non-const.
1526 auto &ctx = const_cast<ASTContext &>(constCtx);
1527 StripObjCKindOfTypeVisitor visitor(ctx);
1528 return visitor.recurse(*this);
1529 }
1530
getAtomicUnqualifiedType() const1531 QualType QualType::getAtomicUnqualifiedType() const {
1532 if (const auto AT = getTypePtr()->getAs<AtomicType>())
1533 return AT->getValueType().getUnqualifiedType();
1534 return getUnqualifiedType();
1535 }
1536
1537 std::optional<ArrayRef<QualType>>
getObjCSubstitutions(const DeclContext * dc) const1538 Type::getObjCSubstitutions(const DeclContext *dc) const {
1539 // Look through method scopes.
1540 if (const auto method = dyn_cast<ObjCMethodDecl>(dc))
1541 dc = method->getDeclContext();
1542
1543 // Find the class or category in which the type we're substituting
1544 // was declared.
1545 const auto *dcClassDecl = dyn_cast<ObjCInterfaceDecl>(dc);
1546 const ObjCCategoryDecl *dcCategoryDecl = nullptr;
1547 ObjCTypeParamList *dcTypeParams = nullptr;
1548 if (dcClassDecl) {
1549 // If the class does not have any type parameters, there's no
1550 // substitution to do.
1551 dcTypeParams = dcClassDecl->getTypeParamList();
1552 if (!dcTypeParams)
1553 return std::nullopt;
1554 } else {
1555 // If we are in neither a class nor a category, there's no
1556 // substitution to perform.
1557 dcCategoryDecl = dyn_cast<ObjCCategoryDecl>(dc);
1558 if (!dcCategoryDecl)
1559 return std::nullopt;
1560
1561 // If the category does not have any type parameters, there's no
1562 // substitution to do.
1563 dcTypeParams = dcCategoryDecl->getTypeParamList();
1564 if (!dcTypeParams)
1565 return std::nullopt;
1566
1567 dcClassDecl = dcCategoryDecl->getClassInterface();
1568 if (!dcClassDecl)
1569 return std::nullopt;
1570 }
1571 assert(dcTypeParams && "No substitutions to perform");
1572 assert(dcClassDecl && "No class context");
1573
1574 // Find the underlying object type.
1575 const ObjCObjectType *objectType;
1576 if (const auto *objectPointerType = getAs<ObjCObjectPointerType>()) {
1577 objectType = objectPointerType->getObjectType();
1578 } else if (getAs<BlockPointerType>()) {
1579 ASTContext &ctx = dc->getParentASTContext();
1580 objectType = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, {}, {})
1581 ->castAs<ObjCObjectType>();
1582 } else {
1583 objectType = getAs<ObjCObjectType>();
1584 }
1585
1586 /// Extract the class from the receiver object type.
1587 ObjCInterfaceDecl *curClassDecl = objectType ? objectType->getInterface()
1588 : nullptr;
1589 if (!curClassDecl) {
1590 // If we don't have a context type (e.g., this is "id" or some
1591 // variant thereof), substitute the bounds.
1592 return llvm::ArrayRef<QualType>();
1593 }
1594
1595 // Follow the superclass chain until we've mapped the receiver type
1596 // to the same class as the context.
1597 while (curClassDecl != dcClassDecl) {
1598 // Map to the superclass type.
1599 QualType superType = objectType->getSuperClassType();
1600 if (superType.isNull()) {
1601 objectType = nullptr;
1602 break;
1603 }
1604
1605 objectType = superType->castAs<ObjCObjectType>();
1606 curClassDecl = objectType->getInterface();
1607 }
1608
1609 // If we don't have a receiver type, or the receiver type does not
1610 // have type arguments, substitute in the defaults.
1611 if (!objectType || objectType->isUnspecialized()) {
1612 return llvm::ArrayRef<QualType>();
1613 }
1614
1615 // The receiver type has the type arguments we want.
1616 return objectType->getTypeArgs();
1617 }
1618
acceptsObjCTypeParams() const1619 bool Type::acceptsObjCTypeParams() const {
1620 if (auto *IfaceT = getAsObjCInterfaceType()) {
1621 if (auto *ID = IfaceT->getInterface()) {
1622 if (ID->getTypeParamList())
1623 return true;
1624 }
1625 }
1626
1627 return false;
1628 }
1629
computeSuperClassTypeSlow() const1630 void ObjCObjectType::computeSuperClassTypeSlow() const {
1631 // Retrieve the class declaration for this type. If there isn't one
1632 // (e.g., this is some variant of "id" or "Class"), then there is no
1633 // superclass type.
1634 ObjCInterfaceDecl *classDecl = getInterface();
1635 if (!classDecl) {
1636 CachedSuperClassType.setInt(true);
1637 return;
1638 }
1639
1640 // Extract the superclass type.
1641 const ObjCObjectType *superClassObjTy = classDecl->getSuperClassType();
1642 if (!superClassObjTy) {
1643 CachedSuperClassType.setInt(true);
1644 return;
1645 }
1646
1647 ObjCInterfaceDecl *superClassDecl = superClassObjTy->getInterface();
1648 if (!superClassDecl) {
1649 CachedSuperClassType.setInt(true);
1650 return;
1651 }
1652
1653 // If the superclass doesn't have type parameters, then there is no
1654 // substitution to perform.
1655 QualType superClassType(superClassObjTy, 0);
1656 ObjCTypeParamList *superClassTypeParams = superClassDecl->getTypeParamList();
1657 if (!superClassTypeParams) {
1658 CachedSuperClassType.setPointerAndInt(
1659 superClassType->castAs<ObjCObjectType>(), true);
1660 return;
1661 }
1662
1663 // If the superclass reference is unspecialized, return it.
1664 if (superClassObjTy->isUnspecialized()) {
1665 CachedSuperClassType.setPointerAndInt(superClassObjTy, true);
1666 return;
1667 }
1668
1669 // If the subclass is not parameterized, there aren't any type
1670 // parameters in the superclass reference to substitute.
1671 ObjCTypeParamList *typeParams = classDecl->getTypeParamList();
1672 if (!typeParams) {
1673 CachedSuperClassType.setPointerAndInt(
1674 superClassType->castAs<ObjCObjectType>(), true);
1675 return;
1676 }
1677
1678 // If the subclass type isn't specialized, return the unspecialized
1679 // superclass.
1680 if (isUnspecialized()) {
1681 QualType unspecializedSuper
1682 = classDecl->getASTContext().getObjCInterfaceType(
1683 superClassObjTy->getInterface());
1684 CachedSuperClassType.setPointerAndInt(
1685 unspecializedSuper->castAs<ObjCObjectType>(),
1686 true);
1687 return;
1688 }
1689
1690 // Substitute the provided type arguments into the superclass type.
1691 ArrayRef<QualType> typeArgs = getTypeArgs();
1692 assert(typeArgs.size() == typeParams->size());
1693 CachedSuperClassType.setPointerAndInt(
1694 superClassType.substObjCTypeArgs(classDecl->getASTContext(), typeArgs,
1695 ObjCSubstitutionContext::Superclass)
1696 ->castAs<ObjCObjectType>(),
1697 true);
1698 }
1699
getInterfaceType() const1700 const ObjCInterfaceType *ObjCObjectPointerType::getInterfaceType() const {
1701 if (auto interfaceDecl = getObjectType()->getInterface()) {
1702 return interfaceDecl->getASTContext().getObjCInterfaceType(interfaceDecl)
1703 ->castAs<ObjCInterfaceType>();
1704 }
1705
1706 return nullptr;
1707 }
1708
getSuperClassType() const1709 QualType ObjCObjectPointerType::getSuperClassType() const {
1710 QualType superObjectType = getObjectType()->getSuperClassType();
1711 if (superObjectType.isNull())
1712 return superObjectType;
1713
1714 ASTContext &ctx = getInterfaceDecl()->getASTContext();
1715 return ctx.getObjCObjectPointerType(superObjectType);
1716 }
1717
getAsObjCQualifiedInterfaceType() const1718 const ObjCObjectType *Type::getAsObjCQualifiedInterfaceType() const {
1719 // There is no sugar for ObjCObjectType's, just return the canonical
1720 // type pointer if it is the right class. There is no typedef information to
1721 // return and these cannot be Address-space qualified.
1722 if (const auto *T = getAs<ObjCObjectType>())
1723 if (T->getNumProtocols() && T->getInterface())
1724 return T;
1725 return nullptr;
1726 }
1727
isObjCQualifiedInterfaceType() const1728 bool Type::isObjCQualifiedInterfaceType() const {
1729 return getAsObjCQualifiedInterfaceType() != nullptr;
1730 }
1731
getAsObjCQualifiedIdType() const1732 const ObjCObjectPointerType *Type::getAsObjCQualifiedIdType() const {
1733 // There is no sugar for ObjCQualifiedIdType's, just return the canonical
1734 // type pointer if it is the right class.
1735 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1736 if (OPT->isObjCQualifiedIdType())
1737 return OPT;
1738 }
1739 return nullptr;
1740 }
1741
getAsObjCQualifiedClassType() const1742 const ObjCObjectPointerType *Type::getAsObjCQualifiedClassType() const {
1743 // There is no sugar for ObjCQualifiedClassType's, just return the canonical
1744 // type pointer if it is the right class.
1745 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1746 if (OPT->isObjCQualifiedClassType())
1747 return OPT;
1748 }
1749 return nullptr;
1750 }
1751
getAsObjCInterfaceType() const1752 const ObjCObjectType *Type::getAsObjCInterfaceType() const {
1753 if (const auto *OT = getAs<ObjCObjectType>()) {
1754 if (OT->getInterface())
1755 return OT;
1756 }
1757 return nullptr;
1758 }
1759
getAsObjCInterfacePointerType() const1760 const ObjCObjectPointerType *Type::getAsObjCInterfacePointerType() const {
1761 if (const auto *OPT = getAs<ObjCObjectPointerType>()) {
1762 if (OPT->getInterfaceType())
1763 return OPT;
1764 }
1765 return nullptr;
1766 }
1767
getPointeeCXXRecordDecl() const1768 const CXXRecordDecl *Type::getPointeeCXXRecordDecl() const {
1769 QualType PointeeType;
1770 if (const auto *PT = getAs<PointerType>())
1771 PointeeType = PT->getPointeeType();
1772 else if (const auto *RT = getAs<ReferenceType>())
1773 PointeeType = RT->getPointeeType();
1774 else
1775 return nullptr;
1776
1777 if (const auto *RT = PointeeType->getAs<RecordType>())
1778 return dyn_cast<CXXRecordDecl>(RT->getDecl());
1779
1780 return nullptr;
1781 }
1782
getAsCXXRecordDecl() const1783 CXXRecordDecl *Type::getAsCXXRecordDecl() const {
1784 return dyn_cast_or_null<CXXRecordDecl>(getAsTagDecl());
1785 }
1786
getAsRecordDecl() const1787 RecordDecl *Type::getAsRecordDecl() const {
1788 return dyn_cast_or_null<RecordDecl>(getAsTagDecl());
1789 }
1790
getAsTagDecl() const1791 TagDecl *Type::getAsTagDecl() const {
1792 if (const auto *TT = getAs<TagType>())
1793 return TT->getDecl();
1794 if (const auto *Injected = getAs<InjectedClassNameType>())
1795 return Injected->getDecl();
1796
1797 return nullptr;
1798 }
1799
hasAttr(attr::Kind AK) const1800 bool Type::hasAttr(attr::Kind AK) const {
1801 const Type *Cur = this;
1802 while (const auto *AT = Cur->getAs<AttributedType>()) {
1803 if (AT->getAttrKind() == AK)
1804 return true;
1805 Cur = AT->getEquivalentType().getTypePtr();
1806 }
1807 return false;
1808 }
1809
1810 namespace {
1811
1812 class GetContainedDeducedTypeVisitor :
1813 public TypeVisitor<GetContainedDeducedTypeVisitor, Type*> {
1814 bool Syntactic;
1815
1816 public:
GetContainedDeducedTypeVisitor(bool Syntactic=false)1817 GetContainedDeducedTypeVisitor(bool Syntactic = false)
1818 : Syntactic(Syntactic) {}
1819
1820 using TypeVisitor<GetContainedDeducedTypeVisitor, Type*>::Visit;
1821
Visit(QualType T)1822 Type *Visit(QualType T) {
1823 if (T.isNull())
1824 return nullptr;
1825 return Visit(T.getTypePtr());
1826 }
1827
1828 // The deduced type itself.
VisitDeducedType(const DeducedType * AT)1829 Type *VisitDeducedType(const DeducedType *AT) {
1830 return const_cast<DeducedType*>(AT);
1831 }
1832
1833 // Only these types can contain the desired 'auto' type.
VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType * T)1834 Type *VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1835 return Visit(T->getReplacementType());
1836 }
1837
VisitElaboratedType(const ElaboratedType * T)1838 Type *VisitElaboratedType(const ElaboratedType *T) {
1839 return Visit(T->getNamedType());
1840 }
1841
VisitPointerType(const PointerType * T)1842 Type *VisitPointerType(const PointerType *T) {
1843 return Visit(T->getPointeeType());
1844 }
1845
VisitBlockPointerType(const BlockPointerType * T)1846 Type *VisitBlockPointerType(const BlockPointerType *T) {
1847 return Visit(T->getPointeeType());
1848 }
1849
VisitReferenceType(const ReferenceType * T)1850 Type *VisitReferenceType(const ReferenceType *T) {
1851 return Visit(T->getPointeeTypeAsWritten());
1852 }
1853
VisitMemberPointerType(const MemberPointerType * T)1854 Type *VisitMemberPointerType(const MemberPointerType *T) {
1855 return Visit(T->getPointeeType());
1856 }
1857
VisitArrayType(const ArrayType * T)1858 Type *VisitArrayType(const ArrayType *T) {
1859 return Visit(T->getElementType());
1860 }
1861
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)1862 Type *VisitDependentSizedExtVectorType(
1863 const DependentSizedExtVectorType *T) {
1864 return Visit(T->getElementType());
1865 }
1866
VisitVectorType(const VectorType * T)1867 Type *VisitVectorType(const VectorType *T) {
1868 return Visit(T->getElementType());
1869 }
1870
VisitDependentSizedMatrixType(const DependentSizedMatrixType * T)1871 Type *VisitDependentSizedMatrixType(const DependentSizedMatrixType *T) {
1872 return Visit(T->getElementType());
1873 }
1874
VisitConstantMatrixType(const ConstantMatrixType * T)1875 Type *VisitConstantMatrixType(const ConstantMatrixType *T) {
1876 return Visit(T->getElementType());
1877 }
1878
VisitFunctionProtoType(const FunctionProtoType * T)1879 Type *VisitFunctionProtoType(const FunctionProtoType *T) {
1880 if (Syntactic && T->hasTrailingReturn())
1881 return const_cast<FunctionProtoType*>(T);
1882 return VisitFunctionType(T);
1883 }
1884
VisitFunctionType(const FunctionType * T)1885 Type *VisitFunctionType(const FunctionType *T) {
1886 return Visit(T->getReturnType());
1887 }
1888
VisitParenType(const ParenType * T)1889 Type *VisitParenType(const ParenType *T) {
1890 return Visit(T->getInnerType());
1891 }
1892
VisitAttributedType(const AttributedType * T)1893 Type *VisitAttributedType(const AttributedType *T) {
1894 return Visit(T->getModifiedType());
1895 }
1896
VisitMacroQualifiedType(const MacroQualifiedType * T)1897 Type *VisitMacroQualifiedType(const MacroQualifiedType *T) {
1898 return Visit(T->getUnderlyingType());
1899 }
1900
VisitAdjustedType(const AdjustedType * T)1901 Type *VisitAdjustedType(const AdjustedType *T) {
1902 return Visit(T->getOriginalType());
1903 }
1904
VisitPackExpansionType(const PackExpansionType * T)1905 Type *VisitPackExpansionType(const PackExpansionType *T) {
1906 return Visit(T->getPattern());
1907 }
1908 };
1909
1910 } // namespace
1911
getContainedDeducedType() const1912 DeducedType *Type::getContainedDeducedType() const {
1913 return cast_or_null<DeducedType>(
1914 GetContainedDeducedTypeVisitor().Visit(this));
1915 }
1916
hasAutoForTrailingReturnType() const1917 bool Type::hasAutoForTrailingReturnType() const {
1918 return isa_and_nonnull<FunctionType>(
1919 GetContainedDeducedTypeVisitor(true).Visit(this));
1920 }
1921
hasIntegerRepresentation() const1922 bool Type::hasIntegerRepresentation() const {
1923 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
1924 return VT->getElementType()->isIntegerType();
1925 if (CanonicalType->isVLSTBuiltinType()) {
1926 const auto *VT = cast<BuiltinType>(CanonicalType);
1927 return VT->getKind() == BuiltinType::SveBool ||
1928 (VT->getKind() >= BuiltinType::SveInt8 &&
1929 VT->getKind() <= BuiltinType::SveUint64);
1930 }
1931
1932 return isIntegerType();
1933 }
1934
1935 /// Determine whether this type is an integral type.
1936 ///
1937 /// This routine determines whether the given type is an integral type per
1938 /// C++ [basic.fundamental]p7. Although the C standard does not define the
1939 /// term "integral type", it has a similar term "integer type", and in C++
1940 /// the two terms are equivalent. However, C's "integer type" includes
1941 /// enumeration types, while C++'s "integer type" does not. The \c ASTContext
1942 /// parameter is used to determine whether we should be following the C or
1943 /// C++ rules when determining whether this type is an integral/integer type.
1944 ///
1945 /// For cases where C permits "an integer type" and C++ permits "an integral
1946 /// type", use this routine.
1947 ///
1948 /// For cases where C permits "an integer type" and C++ permits "an integral
1949 /// or enumeration type", use \c isIntegralOrEnumerationType() instead.
1950 ///
1951 /// \param Ctx The context in which this type occurs.
1952 ///
1953 /// \returns true if the type is considered an integral type, false otherwise.
isIntegralType(const ASTContext & Ctx) const1954 bool Type::isIntegralType(const ASTContext &Ctx) const {
1955 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1956 return BT->getKind() >= BuiltinType::Bool &&
1957 BT->getKind() <= BuiltinType::Int128;
1958
1959 // Complete enum types are integral in C.
1960 if (!Ctx.getLangOpts().CPlusPlus)
1961 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1962 return ET->getDecl()->isComplete();
1963
1964 return isBitIntType();
1965 }
1966
isIntegralOrUnscopedEnumerationType() const1967 bool Type::isIntegralOrUnscopedEnumerationType() const {
1968 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1969 return BT->getKind() >= BuiltinType::Bool &&
1970 BT->getKind() <= BuiltinType::Int128;
1971
1972 if (isBitIntType())
1973 return true;
1974
1975 return isUnscopedEnumerationType();
1976 }
1977
isUnscopedEnumerationType() const1978 bool Type::isUnscopedEnumerationType() const {
1979 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
1980 return !ET->getDecl()->isScoped();
1981
1982 return false;
1983 }
1984
isCharType() const1985 bool Type::isCharType() const {
1986 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1987 return BT->getKind() == BuiltinType::Char_U ||
1988 BT->getKind() == BuiltinType::UChar ||
1989 BT->getKind() == BuiltinType::Char_S ||
1990 BT->getKind() == BuiltinType::SChar;
1991 return false;
1992 }
1993
isWideCharType() const1994 bool Type::isWideCharType() const {
1995 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
1996 return BT->getKind() == BuiltinType::WChar_S ||
1997 BT->getKind() == BuiltinType::WChar_U;
1998 return false;
1999 }
2000
isChar8Type() const2001 bool Type::isChar8Type() const {
2002 if (const BuiltinType *BT = dyn_cast<BuiltinType>(CanonicalType))
2003 return BT->getKind() == BuiltinType::Char8;
2004 return false;
2005 }
2006
isChar16Type() const2007 bool Type::isChar16Type() const {
2008 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2009 return BT->getKind() == BuiltinType::Char16;
2010 return false;
2011 }
2012
isChar32Type() const2013 bool Type::isChar32Type() const {
2014 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2015 return BT->getKind() == BuiltinType::Char32;
2016 return false;
2017 }
2018
2019 /// Determine whether this type is any of the built-in character
2020 /// types.
isAnyCharacterType() const2021 bool Type::isAnyCharacterType() const {
2022 const auto *BT = dyn_cast<BuiltinType>(CanonicalType);
2023 if (!BT) return false;
2024 switch (BT->getKind()) {
2025 default: return false;
2026 case BuiltinType::Char_U:
2027 case BuiltinType::UChar:
2028 case BuiltinType::WChar_U:
2029 case BuiltinType::Char8:
2030 case BuiltinType::Char16:
2031 case BuiltinType::Char32:
2032 case BuiltinType::Char_S:
2033 case BuiltinType::SChar:
2034 case BuiltinType::WChar_S:
2035 return true;
2036 }
2037 }
2038
2039 /// isSignedIntegerType - Return true if this is an integer type that is
2040 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2041 /// an enum decl which has a signed representation
isSignedIntegerType() const2042 bool Type::isSignedIntegerType() const {
2043 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2044 return BT->getKind() >= BuiltinType::Char_S &&
2045 BT->getKind() <= BuiltinType::Int128;
2046 }
2047
2048 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
2049 // Incomplete enum types are not treated as integer types.
2050 // FIXME: In C++, enum types are never integer types.
2051 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2052 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2053 }
2054
2055 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2056 return IT->isSigned();
2057 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2058 return IT->isSigned();
2059
2060 return false;
2061 }
2062
isSignedIntegerOrEnumerationType() const2063 bool Type::isSignedIntegerOrEnumerationType() const {
2064 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2065 return BT->getKind() >= BuiltinType::Char_S &&
2066 BT->getKind() <= BuiltinType::Int128;
2067 }
2068
2069 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2070 if (ET->getDecl()->isComplete())
2071 return ET->getDecl()->getIntegerType()->isSignedIntegerType();
2072 }
2073
2074 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2075 return IT->isSigned();
2076 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2077 return IT->isSigned();
2078
2079 return false;
2080 }
2081
hasSignedIntegerRepresentation() const2082 bool Type::hasSignedIntegerRepresentation() const {
2083 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2084 return VT->getElementType()->isSignedIntegerOrEnumerationType();
2085 else
2086 return isSignedIntegerOrEnumerationType();
2087 }
2088
2089 /// isUnsignedIntegerType - Return true if this is an integer type that is
2090 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool], an enum
2091 /// decl which has an unsigned representation
isUnsignedIntegerType() const2092 bool Type::isUnsignedIntegerType() const {
2093 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2094 return BT->getKind() >= BuiltinType::Bool &&
2095 BT->getKind() <= BuiltinType::UInt128;
2096 }
2097
2098 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2099 // Incomplete enum types are not treated as integer types.
2100 // FIXME: In C++, enum types are never integer types.
2101 if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
2102 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2103 }
2104
2105 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2106 return IT->isUnsigned();
2107 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2108 return IT->isUnsigned();
2109
2110 return false;
2111 }
2112
isUnsignedIntegerOrEnumerationType() const2113 bool Type::isUnsignedIntegerOrEnumerationType() const {
2114 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
2115 return BT->getKind() >= BuiltinType::Bool &&
2116 BT->getKind() <= BuiltinType::UInt128;
2117 }
2118
2119 if (const auto *ET = dyn_cast<EnumType>(CanonicalType)) {
2120 if (ET->getDecl()->isComplete())
2121 return ET->getDecl()->getIntegerType()->isUnsignedIntegerType();
2122 }
2123
2124 if (const auto *IT = dyn_cast<BitIntType>(CanonicalType))
2125 return IT->isUnsigned();
2126 if (const auto *IT = dyn_cast<DependentBitIntType>(CanonicalType))
2127 return IT->isUnsigned();
2128
2129 return false;
2130 }
2131
hasUnsignedIntegerRepresentation() const2132 bool Type::hasUnsignedIntegerRepresentation() const {
2133 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2134 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2135 if (const auto *VT = dyn_cast<MatrixType>(CanonicalType))
2136 return VT->getElementType()->isUnsignedIntegerOrEnumerationType();
2137 if (CanonicalType->isVLSTBuiltinType()) {
2138 const auto *VT = cast<BuiltinType>(CanonicalType);
2139 return VT->getKind() >= BuiltinType::SveUint8 &&
2140 VT->getKind() <= BuiltinType::SveUint64;
2141 }
2142 return isUnsignedIntegerOrEnumerationType();
2143 }
2144
isFloatingType() const2145 bool Type::isFloatingType() const {
2146 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2147 return BT->getKind() >= BuiltinType::Half &&
2148 BT->getKind() <= BuiltinType::Ibm128;
2149 if (const auto *CT = dyn_cast<ComplexType>(CanonicalType))
2150 return CT->getElementType()->isFloatingType();
2151 return false;
2152 }
2153
hasFloatingRepresentation() const2154 bool Type::hasFloatingRepresentation() const {
2155 if (const auto *VT = dyn_cast<VectorType>(CanonicalType))
2156 return VT->getElementType()->isFloatingType();
2157 else
2158 return isFloatingType();
2159 }
2160
isRealFloatingType() const2161 bool Type::isRealFloatingType() const {
2162 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2163 return BT->isFloatingPoint();
2164 return false;
2165 }
2166
isRealType() const2167 bool Type::isRealType() const {
2168 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2169 return BT->getKind() >= BuiltinType::Bool &&
2170 BT->getKind() <= BuiltinType::Ibm128;
2171 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2172 return ET->getDecl()->isComplete() && !ET->getDecl()->isScoped();
2173 return isBitIntType();
2174 }
2175
isArithmeticType() const2176 bool Type::isArithmeticType() const {
2177 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
2178 return BT->getKind() >= BuiltinType::Bool &&
2179 BT->getKind() <= BuiltinType::Ibm128 &&
2180 BT->getKind() != BuiltinType::BFloat16;
2181 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
2182 // GCC allows forward declaration of enum types (forbid by C99 6.7.2.3p2).
2183 // If a body isn't seen by the time we get here, return false.
2184 //
2185 // C++0x: Enumerations are not arithmetic types. For now, just return
2186 // false for scoped enumerations since that will disable any
2187 // unwanted implicit conversions.
2188 return !ET->getDecl()->isScoped() && ET->getDecl()->isComplete();
2189 return isa<ComplexType>(CanonicalType) || isBitIntType();
2190 }
2191
getScalarTypeKind() const2192 Type::ScalarTypeKind Type::getScalarTypeKind() const {
2193 assert(isScalarType());
2194
2195 const Type *T = CanonicalType.getTypePtr();
2196 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
2197 if (BT->getKind() == BuiltinType::Bool) return STK_Bool;
2198 if (BT->getKind() == BuiltinType::NullPtr) return STK_CPointer;
2199 if (BT->isInteger()) return STK_Integral;
2200 if (BT->isFloatingPoint()) return STK_Floating;
2201 if (BT->isFixedPointType()) return STK_FixedPoint;
2202 llvm_unreachable("unknown scalar builtin type");
2203 } else if (isa<PointerType>(T)) {
2204 return STK_CPointer;
2205 } else if (isa<BlockPointerType>(T)) {
2206 return STK_BlockPointer;
2207 } else if (isa<ObjCObjectPointerType>(T)) {
2208 return STK_ObjCObjectPointer;
2209 } else if (isa<MemberPointerType>(T)) {
2210 return STK_MemberPointer;
2211 } else if (isa<EnumType>(T)) {
2212 assert(cast<EnumType>(T)->getDecl()->isComplete());
2213 return STK_Integral;
2214 } else if (const auto *CT = dyn_cast<ComplexType>(T)) {
2215 if (CT->getElementType()->isRealFloatingType())
2216 return STK_FloatingComplex;
2217 return STK_IntegralComplex;
2218 } else if (isBitIntType()) {
2219 return STK_Integral;
2220 }
2221
2222 llvm_unreachable("unknown scalar type");
2223 }
2224
2225 /// Determines whether the type is a C++ aggregate type or C
2226 /// aggregate or union type.
2227 ///
2228 /// An aggregate type is an array or a class type (struct, union, or
2229 /// class) that has no user-declared constructors, no private or
2230 /// protected non-static data members, no base classes, and no virtual
2231 /// functions (C++ [dcl.init.aggr]p1). The notion of an aggregate type
2232 /// subsumes the notion of C aggregates (C99 6.2.5p21) because it also
2233 /// includes union types.
isAggregateType() const2234 bool Type::isAggregateType() const {
2235 if (const auto *Record = dyn_cast<RecordType>(CanonicalType)) {
2236 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(Record->getDecl()))
2237 return ClassDecl->isAggregate();
2238
2239 return true;
2240 }
2241
2242 return isa<ArrayType>(CanonicalType);
2243 }
2244
2245 /// isConstantSizeType - Return true if this is not a variable sized type,
2246 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2247 /// incomplete types or dependent types.
isConstantSizeType() const2248 bool Type::isConstantSizeType() const {
2249 assert(!isIncompleteType() && "This doesn't make sense for incomplete types");
2250 assert(!isDependentType() && "This doesn't make sense for dependent types");
2251 // The VAT must have a size, as it is known to be complete.
2252 return !isa<VariableArrayType>(CanonicalType);
2253 }
2254
2255 /// isIncompleteType - Return true if this is an incomplete type (C99 6.2.5p1)
2256 /// - a type that can describe objects, but which lacks information needed to
2257 /// determine its size.
isIncompleteType(NamedDecl ** Def) const2258 bool Type::isIncompleteType(NamedDecl **Def) const {
2259 if (Def)
2260 *Def = nullptr;
2261
2262 switch (CanonicalType->getTypeClass()) {
2263 default: return false;
2264 case Builtin:
2265 // Void is the only incomplete builtin type. Per C99 6.2.5p19, it can never
2266 // be completed.
2267 return isVoidType();
2268 case Enum: {
2269 EnumDecl *EnumD = cast<EnumType>(CanonicalType)->getDecl();
2270 if (Def)
2271 *Def = EnumD;
2272 return !EnumD->isComplete();
2273 }
2274 case Record: {
2275 // A tagged type (struct/union/enum/class) is incomplete if the decl is a
2276 // forward declaration, but not a full definition (C99 6.2.5p22).
2277 RecordDecl *Rec = cast<RecordType>(CanonicalType)->getDecl();
2278 if (Def)
2279 *Def = Rec;
2280 return !Rec->isCompleteDefinition();
2281 }
2282 case ConstantArray:
2283 case VariableArray:
2284 // An array is incomplete if its element type is incomplete
2285 // (C++ [dcl.array]p1).
2286 // We don't handle dependent-sized arrays (dependent types are never treated
2287 // as incomplete).
2288 return cast<ArrayType>(CanonicalType)->getElementType()
2289 ->isIncompleteType(Def);
2290 case IncompleteArray:
2291 // An array of unknown size is an incomplete type (C99 6.2.5p22).
2292 return true;
2293 case MemberPointer: {
2294 // Member pointers in the MS ABI have special behavior in
2295 // RequireCompleteType: they attach a MSInheritanceAttr to the CXXRecordDecl
2296 // to indicate which inheritance model to use.
2297 auto *MPTy = cast<MemberPointerType>(CanonicalType);
2298 const Type *ClassTy = MPTy->getClass();
2299 // Member pointers with dependent class types don't get special treatment.
2300 if (ClassTy->isDependentType())
2301 return false;
2302 const CXXRecordDecl *RD = ClassTy->getAsCXXRecordDecl();
2303 ASTContext &Context = RD->getASTContext();
2304 // Member pointers not in the MS ABI don't get special treatment.
2305 if (!Context.getTargetInfo().getCXXABI().isMicrosoft())
2306 return false;
2307 // The inheritance attribute might only be present on the most recent
2308 // CXXRecordDecl, use that one.
2309 RD = RD->getMostRecentNonInjectedDecl();
2310 // Nothing interesting to do if the inheritance attribute is already set.
2311 if (RD->hasAttr<MSInheritanceAttr>())
2312 return false;
2313 return true;
2314 }
2315 case ObjCObject:
2316 return cast<ObjCObjectType>(CanonicalType)->getBaseType()
2317 ->isIncompleteType(Def);
2318 case ObjCInterface: {
2319 // ObjC interfaces are incomplete if they are @class, not @interface.
2320 ObjCInterfaceDecl *Interface
2321 = cast<ObjCInterfaceType>(CanonicalType)->getDecl();
2322 if (Def)
2323 *Def = Interface;
2324 return !Interface->hasDefinition();
2325 }
2326 }
2327 }
2328
isSizelessBuiltinType() const2329 bool Type::isSizelessBuiltinType() const {
2330 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2331 switch (BT->getKind()) {
2332 // SVE Types
2333 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2334 #include "clang/Basic/AArch64SVEACLETypes.def"
2335 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2336 #include "clang/Basic/RISCVVTypes.def"
2337 return true;
2338 default:
2339 return false;
2340 }
2341 }
2342 return false;
2343 }
2344
isSizelessType() const2345 bool Type::isSizelessType() const { return isSizelessBuiltinType(); }
2346
isSVESizelessBuiltinType() const2347 bool Type::isSVESizelessBuiltinType() const {
2348 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2349 switch (BT->getKind()) {
2350 // SVE Types
2351 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2352 #include "clang/Basic/AArch64SVEACLETypes.def"
2353 return true;
2354 default:
2355 return false;
2356 }
2357 }
2358 return false;
2359 }
2360
isVLSTBuiltinType() const2361 bool Type::isVLSTBuiltinType() const {
2362 if (const BuiltinType *BT = getAs<BuiltinType>()) {
2363 switch (BT->getKind()) {
2364 case BuiltinType::SveInt8:
2365 case BuiltinType::SveInt16:
2366 case BuiltinType::SveInt32:
2367 case BuiltinType::SveInt64:
2368 case BuiltinType::SveUint8:
2369 case BuiltinType::SveUint16:
2370 case BuiltinType::SveUint32:
2371 case BuiltinType::SveUint64:
2372 case BuiltinType::SveFloat16:
2373 case BuiltinType::SveFloat32:
2374 case BuiltinType::SveFloat64:
2375 case BuiltinType::SveBFloat16:
2376 case BuiltinType::SveBool:
2377 return true;
2378 default:
2379 return false;
2380 }
2381 }
2382 return false;
2383 }
2384
getSveEltType(const ASTContext & Ctx) const2385 QualType Type::getSveEltType(const ASTContext &Ctx) const {
2386 assert(isVLSTBuiltinType() && "unsupported type!");
2387
2388 const BuiltinType *BTy = getAs<BuiltinType>();
2389 if (BTy->getKind() == BuiltinType::SveBool)
2390 // Represent predicates as i8 rather than i1 to avoid any layout issues.
2391 // The type is bitcasted to a scalable predicate type when casting between
2392 // scalable and fixed-length vectors.
2393 return Ctx.UnsignedCharTy;
2394 else
2395 return Ctx.getBuiltinVectorTypeInfo(BTy).ElementType;
2396 }
2397
isPODType(const ASTContext & Context) const2398 bool QualType::isPODType(const ASTContext &Context) const {
2399 // C++11 has a more relaxed definition of POD.
2400 if (Context.getLangOpts().CPlusPlus11)
2401 return isCXX11PODType(Context);
2402
2403 return isCXX98PODType(Context);
2404 }
2405
isCXX98PODType(const ASTContext & Context) const2406 bool QualType::isCXX98PODType(const ASTContext &Context) const {
2407 // The compiler shouldn't query this for incomplete types, but the user might.
2408 // We return false for that case. Except for incomplete arrays of PODs, which
2409 // are PODs according to the standard.
2410 if (isNull())
2411 return false;
2412
2413 if ((*this)->isIncompleteArrayType())
2414 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2415
2416 if ((*this)->isIncompleteType())
2417 return false;
2418
2419 if (hasNonTrivialObjCLifetime())
2420 return false;
2421
2422 QualType CanonicalType = getTypePtr()->CanonicalType;
2423 switch (CanonicalType->getTypeClass()) {
2424 // Everything not explicitly mentioned is not POD.
2425 default: return false;
2426 case Type::VariableArray:
2427 case Type::ConstantArray:
2428 // IncompleteArray is handled above.
2429 return Context.getBaseElementType(*this).isCXX98PODType(Context);
2430
2431 case Type::ObjCObjectPointer:
2432 case Type::BlockPointer:
2433 case Type::Builtin:
2434 case Type::Complex:
2435 case Type::Pointer:
2436 case Type::MemberPointer:
2437 case Type::Vector:
2438 case Type::ExtVector:
2439 case Type::BitInt:
2440 return true;
2441
2442 case Type::Enum:
2443 return true;
2444
2445 case Type::Record:
2446 if (const auto *ClassDecl =
2447 dyn_cast<CXXRecordDecl>(cast<RecordType>(CanonicalType)->getDecl()))
2448 return ClassDecl->isPOD();
2449
2450 // C struct/union is POD.
2451 return true;
2452 }
2453 }
2454
isTrivialType(const ASTContext & Context) const2455 bool QualType::isTrivialType(const ASTContext &Context) const {
2456 // The compiler shouldn't query this for incomplete types, but the user might.
2457 // We return false for that case. Except for incomplete arrays of PODs, which
2458 // are PODs according to the standard.
2459 if (isNull())
2460 return false;
2461
2462 if ((*this)->isArrayType())
2463 return Context.getBaseElementType(*this).isTrivialType(Context);
2464
2465 if ((*this)->isSizelessBuiltinType())
2466 return true;
2467
2468 // Return false for incomplete types after skipping any incomplete array
2469 // types which are expressly allowed by the standard and thus our API.
2470 if ((*this)->isIncompleteType())
2471 return false;
2472
2473 if (hasNonTrivialObjCLifetime())
2474 return false;
2475
2476 QualType CanonicalType = getTypePtr()->CanonicalType;
2477 if (CanonicalType->isDependentType())
2478 return false;
2479
2480 // C++0x [basic.types]p9:
2481 // Scalar types, trivial class types, arrays of such types, and
2482 // cv-qualified versions of these types are collectively called trivial
2483 // types.
2484
2485 // As an extension, Clang treats vector types as Scalar types.
2486 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2487 return true;
2488 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2489 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2490 // C++20 [class]p6:
2491 // A trivial class is a class that is trivially copyable, and
2492 // has one or more eligible default constructors such that each is
2493 // trivial.
2494 // FIXME: We should merge this definition of triviality into
2495 // CXXRecordDecl::isTrivial. Currently it computes the wrong thing.
2496 return ClassDecl->hasTrivialDefaultConstructor() &&
2497 !ClassDecl->hasNonTrivialDefaultConstructor() &&
2498 ClassDecl->isTriviallyCopyable();
2499 }
2500
2501 return true;
2502 }
2503
2504 // No other types can match.
2505 return false;
2506 }
2507
isTriviallyCopyableType(const ASTContext & Context) const2508 bool QualType::isTriviallyCopyableType(const ASTContext &Context) const {
2509 if ((*this)->isArrayType())
2510 return Context.getBaseElementType(*this).isTriviallyCopyableType(Context);
2511
2512 if (hasNonTrivialObjCLifetime())
2513 return false;
2514
2515 // C++11 [basic.types]p9 - See Core 2094
2516 // Scalar types, trivially copyable class types, arrays of such types, and
2517 // cv-qualified versions of these types are collectively
2518 // called trivially copyable types.
2519
2520 QualType CanonicalType = getCanonicalType();
2521 if (CanonicalType->isDependentType())
2522 return false;
2523
2524 if (CanonicalType->isSizelessBuiltinType())
2525 return true;
2526
2527 // Return false for incomplete types after skipping any incomplete array types
2528 // which are expressly allowed by the standard and thus our API.
2529 if (CanonicalType->isIncompleteType())
2530 return false;
2531
2532 // As an extension, Clang treats vector types as Scalar types.
2533 if (CanonicalType->isScalarType() || CanonicalType->isVectorType())
2534 return true;
2535
2536 if (const auto *RT = CanonicalType->getAs<RecordType>()) {
2537 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2538 if (!ClassDecl->isTriviallyCopyable()) return false;
2539 }
2540
2541 return true;
2542 }
2543
2544 // No other types can match.
2545 return false;
2546 }
2547
isTriviallyRelocatableType(const ASTContext & Context) const2548 bool QualType::isTriviallyRelocatableType(const ASTContext &Context) const {
2549 QualType BaseElementType = Context.getBaseElementType(*this);
2550
2551 if (BaseElementType->isIncompleteType()) {
2552 return false;
2553 } else if (const auto *RD = BaseElementType->getAsRecordDecl()) {
2554 return RD->canPassInRegisters();
2555 } else {
2556 switch (isNonTrivialToPrimitiveDestructiveMove()) {
2557 case PCK_Trivial:
2558 return !isDestructedType();
2559 case PCK_ARCStrong:
2560 return true;
2561 default:
2562 return false;
2563 }
2564 }
2565 }
2566
isNonWeakInMRRWithObjCWeak(const ASTContext & Context) const2567 bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
2568 return !Context.getLangOpts().ObjCAutoRefCount &&
2569 Context.getLangOpts().ObjCWeak &&
2570 getObjCLifetime() != Qualifiers::OCL_Weak;
2571 }
2572
hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl * RD)2573 bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD) {
2574 return RD->hasNonTrivialToPrimitiveDefaultInitializeCUnion();
2575 }
2576
hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl * RD)2577 bool QualType::hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD) {
2578 return RD->hasNonTrivialToPrimitiveDestructCUnion();
2579 }
2580
hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl * RD)2581 bool QualType::hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD) {
2582 return RD->hasNonTrivialToPrimitiveCopyCUnion();
2583 }
2584
2585 QualType::PrimitiveDefaultInitializeKind
isNonTrivialToPrimitiveDefaultInitialize() const2586 QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
2587 if (const auto *RT =
2588 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2589 if (RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize())
2590 return PDIK_Struct;
2591
2592 switch (getQualifiers().getObjCLifetime()) {
2593 case Qualifiers::OCL_Strong:
2594 return PDIK_ARCStrong;
2595 case Qualifiers::OCL_Weak:
2596 return PDIK_ARCWeak;
2597 default:
2598 return PDIK_Trivial;
2599 }
2600 }
2601
isNonTrivialToPrimitiveCopy() const2602 QualType::PrimitiveCopyKind QualType::isNonTrivialToPrimitiveCopy() const {
2603 if (const auto *RT =
2604 getTypePtr()->getBaseElementTypeUnsafe()->getAs<RecordType>())
2605 if (RT->getDecl()->isNonTrivialToPrimitiveCopy())
2606 return PCK_Struct;
2607
2608 Qualifiers Qs = getQualifiers();
2609 switch (Qs.getObjCLifetime()) {
2610 case Qualifiers::OCL_Strong:
2611 return PCK_ARCStrong;
2612 case Qualifiers::OCL_Weak:
2613 return PCK_ARCWeak;
2614 default:
2615 return Qs.hasVolatile() ? PCK_VolatileTrivial : PCK_Trivial;
2616 }
2617 }
2618
2619 QualType::PrimitiveCopyKind
isNonTrivialToPrimitiveDestructiveMove() const2620 QualType::isNonTrivialToPrimitiveDestructiveMove() const {
2621 return isNonTrivialToPrimitiveCopy();
2622 }
2623
isLiteralType(const ASTContext & Ctx) const2624 bool Type::isLiteralType(const ASTContext &Ctx) const {
2625 if (isDependentType())
2626 return false;
2627
2628 // C++1y [basic.types]p10:
2629 // A type is a literal type if it is:
2630 // -- cv void; or
2631 if (Ctx.getLangOpts().CPlusPlus14 && isVoidType())
2632 return true;
2633
2634 // C++11 [basic.types]p10:
2635 // A type is a literal type if it is:
2636 // [...]
2637 // -- an array of literal type other than an array of runtime bound; or
2638 if (isVariableArrayType())
2639 return false;
2640 const Type *BaseTy = getBaseElementTypeUnsafe();
2641 assert(BaseTy && "NULL element type");
2642
2643 // Return false for incomplete types after skipping any incomplete array
2644 // types; those are expressly allowed by the standard and thus our API.
2645 if (BaseTy->isIncompleteType())
2646 return false;
2647
2648 // C++11 [basic.types]p10:
2649 // A type is a literal type if it is:
2650 // -- a scalar type; or
2651 // As an extension, Clang treats vector types and complex types as
2652 // literal types.
2653 if (BaseTy->isScalarType() || BaseTy->isVectorType() ||
2654 BaseTy->isAnyComplexType())
2655 return true;
2656 // -- a reference type; or
2657 if (BaseTy->isReferenceType())
2658 return true;
2659 // -- a class type that has all of the following properties:
2660 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2661 // -- a trivial destructor,
2662 // -- every constructor call and full-expression in the
2663 // brace-or-equal-initializers for non-static data members (if any)
2664 // is a constant expression,
2665 // -- it is an aggregate type or has at least one constexpr
2666 // constructor or constructor template that is not a copy or move
2667 // constructor, and
2668 // -- all non-static data members and base classes of literal types
2669 //
2670 // We resolve DR1361 by ignoring the second bullet.
2671 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2672 return ClassDecl->isLiteral();
2673
2674 return true;
2675 }
2676
2677 // We treat _Atomic T as a literal type if T is a literal type.
2678 if (const auto *AT = BaseTy->getAs<AtomicType>())
2679 return AT->getValueType()->isLiteralType(Ctx);
2680
2681 // If this type hasn't been deduced yet, then conservatively assume that
2682 // it'll work out to be a literal type.
2683 if (isa<AutoType>(BaseTy->getCanonicalTypeInternal()))
2684 return true;
2685
2686 return false;
2687 }
2688
isStructuralType() const2689 bool Type::isStructuralType() const {
2690 // C++20 [temp.param]p6:
2691 // A structural type is one of the following:
2692 // -- a scalar type; or
2693 // -- a vector type [Clang extension]; or
2694 if (isScalarType() || isVectorType())
2695 return true;
2696 // -- an lvalue reference type; or
2697 if (isLValueReferenceType())
2698 return true;
2699 // -- a literal class type [...under some conditions]
2700 if (const CXXRecordDecl *RD = getAsCXXRecordDecl())
2701 return RD->isStructural();
2702 return false;
2703 }
2704
isStandardLayoutType() const2705 bool Type::isStandardLayoutType() const {
2706 if (isDependentType())
2707 return false;
2708
2709 // C++0x [basic.types]p9:
2710 // Scalar types, standard-layout class types, arrays of such types, and
2711 // cv-qualified versions of these types are collectively called
2712 // standard-layout types.
2713 const Type *BaseTy = getBaseElementTypeUnsafe();
2714 assert(BaseTy && "NULL element type");
2715
2716 // Return false for incomplete types after skipping any incomplete array
2717 // types which are expressly allowed by the standard and thus our API.
2718 if (BaseTy->isIncompleteType())
2719 return false;
2720
2721 // As an extension, Clang treats vector types as Scalar types.
2722 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2723 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2724 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2725 if (!ClassDecl->isStandardLayout())
2726 return false;
2727
2728 // Default to 'true' for non-C++ class types.
2729 // FIXME: This is a bit dubious, but plain C structs should trivially meet
2730 // all the requirements of standard layout classes.
2731 return true;
2732 }
2733
2734 // No other types can match.
2735 return false;
2736 }
2737
2738 // This is effectively the intersection of isTrivialType and
2739 // isStandardLayoutType. We implement it directly to avoid redundant
2740 // conversions from a type to a CXXRecordDecl.
isCXX11PODType(const ASTContext & Context) const2741 bool QualType::isCXX11PODType(const ASTContext &Context) const {
2742 const Type *ty = getTypePtr();
2743 if (ty->isDependentType())
2744 return false;
2745
2746 if (hasNonTrivialObjCLifetime())
2747 return false;
2748
2749 // C++11 [basic.types]p9:
2750 // Scalar types, POD classes, arrays of such types, and cv-qualified
2751 // versions of these types are collectively called trivial types.
2752 const Type *BaseTy = ty->getBaseElementTypeUnsafe();
2753 assert(BaseTy && "NULL element type");
2754
2755 if (BaseTy->isSizelessBuiltinType())
2756 return true;
2757
2758 // Return false for incomplete types after skipping any incomplete array
2759 // types which are expressly allowed by the standard and thus our API.
2760 if (BaseTy->isIncompleteType())
2761 return false;
2762
2763 // As an extension, Clang treats vector types as Scalar types.
2764 if (BaseTy->isScalarType() || BaseTy->isVectorType()) return true;
2765 if (const auto *RT = BaseTy->getAs<RecordType>()) {
2766 if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2767 // C++11 [class]p10:
2768 // A POD struct is a non-union class that is both a trivial class [...]
2769 if (!ClassDecl->isTrivial()) return false;
2770
2771 // C++11 [class]p10:
2772 // A POD struct is a non-union class that is both a trivial class and
2773 // a standard-layout class [...]
2774 if (!ClassDecl->isStandardLayout()) return false;
2775
2776 // C++11 [class]p10:
2777 // A POD struct is a non-union class that is both a trivial class and
2778 // a standard-layout class, and has no non-static data members of type
2779 // non-POD struct, non-POD union (or array of such types). [...]
2780 //
2781 // We don't directly query the recursive aspect as the requirements for
2782 // both standard-layout classes and trivial classes apply recursively
2783 // already.
2784 }
2785
2786 return true;
2787 }
2788
2789 // No other types can match.
2790 return false;
2791 }
2792
isNothrowT() const2793 bool Type::isNothrowT() const {
2794 if (const auto *RD = getAsCXXRecordDecl()) {
2795 IdentifierInfo *II = RD->getIdentifier();
2796 if (II && II->isStr("nothrow_t") && RD->isInStdNamespace())
2797 return true;
2798 }
2799 return false;
2800 }
2801
isAlignValT() const2802 bool Type::isAlignValT() const {
2803 if (const auto *ET = getAs<EnumType>()) {
2804 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2805 if (II && II->isStr("align_val_t") && ET->getDecl()->isInStdNamespace())
2806 return true;
2807 }
2808 return false;
2809 }
2810
isStdByteType() const2811 bool Type::isStdByteType() const {
2812 if (const auto *ET = getAs<EnumType>()) {
2813 IdentifierInfo *II = ET->getDecl()->getIdentifier();
2814 if (II && II->isStr("byte") && ET->getDecl()->isInStdNamespace())
2815 return true;
2816 }
2817 return false;
2818 }
2819
isSpecifierType() const2820 bool Type::isSpecifierType() const {
2821 // Note that this intentionally does not use the canonical type.
2822 switch (getTypeClass()) {
2823 case Builtin:
2824 case Record:
2825 case Enum:
2826 case Typedef:
2827 case Complex:
2828 case TypeOfExpr:
2829 case TypeOf:
2830 case TemplateTypeParm:
2831 case SubstTemplateTypeParm:
2832 case TemplateSpecialization:
2833 case Elaborated:
2834 case DependentName:
2835 case DependentTemplateSpecialization:
2836 case ObjCInterface:
2837 case ObjCObject:
2838 return true;
2839 default:
2840 return false;
2841 }
2842 }
2843
2844 ElaboratedTypeKeyword
getKeywordForTypeSpec(unsigned TypeSpec)2845 TypeWithKeyword::getKeywordForTypeSpec(unsigned TypeSpec) {
2846 switch (TypeSpec) {
2847 default: return ETK_None;
2848 case TST_typename: return ETK_Typename;
2849 case TST_class: return ETK_Class;
2850 case TST_struct: return ETK_Struct;
2851 case TST_interface: return ETK_Interface;
2852 case TST_union: return ETK_Union;
2853 case TST_enum: return ETK_Enum;
2854 }
2855 }
2856
2857 TagTypeKind
getTagTypeKindForTypeSpec(unsigned TypeSpec)2858 TypeWithKeyword::getTagTypeKindForTypeSpec(unsigned TypeSpec) {
2859 switch(TypeSpec) {
2860 case TST_class: return TTK_Class;
2861 case TST_struct: return TTK_Struct;
2862 case TST_interface: return TTK_Interface;
2863 case TST_union: return TTK_Union;
2864 case TST_enum: return TTK_Enum;
2865 }
2866
2867 llvm_unreachable("Type specifier is not a tag type kind.");
2868 }
2869
2870 ElaboratedTypeKeyword
getKeywordForTagTypeKind(TagTypeKind Kind)2871 TypeWithKeyword::getKeywordForTagTypeKind(TagTypeKind Kind) {
2872 switch (Kind) {
2873 case TTK_Class: return ETK_Class;
2874 case TTK_Struct: return ETK_Struct;
2875 case TTK_Interface: return ETK_Interface;
2876 case TTK_Union: return ETK_Union;
2877 case TTK_Enum: return ETK_Enum;
2878 }
2879 llvm_unreachable("Unknown tag type kind.");
2880 }
2881
2882 TagTypeKind
getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)2883 TypeWithKeyword::getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword) {
2884 switch (Keyword) {
2885 case ETK_Class: return TTK_Class;
2886 case ETK_Struct: return TTK_Struct;
2887 case ETK_Interface: return TTK_Interface;
2888 case ETK_Union: return TTK_Union;
2889 case ETK_Enum: return TTK_Enum;
2890 case ETK_None: // Fall through.
2891 case ETK_Typename:
2892 llvm_unreachable("Elaborated type keyword is not a tag type kind.");
2893 }
2894 llvm_unreachable("Unknown elaborated type keyword.");
2895 }
2896
2897 bool
KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword)2898 TypeWithKeyword::KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword) {
2899 switch (Keyword) {
2900 case ETK_None:
2901 case ETK_Typename:
2902 return false;
2903 case ETK_Class:
2904 case ETK_Struct:
2905 case ETK_Interface:
2906 case ETK_Union:
2907 case ETK_Enum:
2908 return true;
2909 }
2910 llvm_unreachable("Unknown elaborated type keyword.");
2911 }
2912
getKeywordName(ElaboratedTypeKeyword Keyword)2913 StringRef TypeWithKeyword::getKeywordName(ElaboratedTypeKeyword Keyword) {
2914 switch (Keyword) {
2915 case ETK_None: return {};
2916 case ETK_Typename: return "typename";
2917 case ETK_Class: return "class";
2918 case ETK_Struct: return "struct";
2919 case ETK_Interface: return "__interface";
2920 case ETK_Union: return "union";
2921 case ETK_Enum: return "enum";
2922 }
2923
2924 llvm_unreachable("Unknown elaborated type keyword.");
2925 }
2926
DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,ArrayRef<TemplateArgument> Args,QualType Canon)2927 DependentTemplateSpecializationType::DependentTemplateSpecializationType(
2928 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
2929 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args, QualType Canon)
2930 : TypeWithKeyword(Keyword, DependentTemplateSpecialization, Canon,
2931 TypeDependence::DependentInstantiation |
2932 (NNS ? toTypeDependence(NNS->getDependence())
2933 : TypeDependence::None)),
2934 NNS(NNS), Name(Name) {
2935 DependentTemplateSpecializationTypeBits.NumArgs = Args.size();
2936 assert((!NNS || NNS->isDependent()) &&
2937 "DependentTemplateSpecializatonType requires dependent qualifier");
2938 auto *ArgBuffer = const_cast<TemplateArgument *>(template_arguments().data());
2939 for (const TemplateArgument &Arg : Args) {
2940 addDependence(toTypeDependence(Arg.getDependence() &
2941 TemplateArgumentDependence::UnexpandedPack));
2942
2943 new (ArgBuffer++) TemplateArgument(Arg);
2944 }
2945 }
2946
2947 void
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,ElaboratedTypeKeyword Keyword,NestedNameSpecifier * Qualifier,const IdentifierInfo * Name,ArrayRef<TemplateArgument> Args)2948 DependentTemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
2949 const ASTContext &Context,
2950 ElaboratedTypeKeyword Keyword,
2951 NestedNameSpecifier *Qualifier,
2952 const IdentifierInfo *Name,
2953 ArrayRef<TemplateArgument> Args) {
2954 ID.AddInteger(Keyword);
2955 ID.AddPointer(Qualifier);
2956 ID.AddPointer(Name);
2957 for (const TemplateArgument &Arg : Args)
2958 Arg.Profile(ID, Context);
2959 }
2960
isElaboratedTypeSpecifier() const2961 bool Type::isElaboratedTypeSpecifier() const {
2962 ElaboratedTypeKeyword Keyword;
2963 if (const auto *Elab = dyn_cast<ElaboratedType>(this))
2964 Keyword = Elab->getKeyword();
2965 else if (const auto *DepName = dyn_cast<DependentNameType>(this))
2966 Keyword = DepName->getKeyword();
2967 else if (const auto *DepTST =
2968 dyn_cast<DependentTemplateSpecializationType>(this))
2969 Keyword = DepTST->getKeyword();
2970 else
2971 return false;
2972
2973 return TypeWithKeyword::KeywordIsTagTypeKind(Keyword);
2974 }
2975
getTypeClassName() const2976 const char *Type::getTypeClassName() const {
2977 switch (TypeBits.TC) {
2978 #define ABSTRACT_TYPE(Derived, Base)
2979 #define TYPE(Derived, Base) case Derived: return #Derived;
2980 #include "clang/AST/TypeNodes.inc"
2981 }
2982
2983 llvm_unreachable("Invalid type class.");
2984 }
2985
getName(const PrintingPolicy & Policy) const2986 StringRef BuiltinType::getName(const PrintingPolicy &Policy) const {
2987 switch (getKind()) {
2988 case Void:
2989 return "void";
2990 case Bool:
2991 return Policy.Bool ? "bool" : "_Bool";
2992 case Char_S:
2993 return "char";
2994 case Char_U:
2995 return "char";
2996 case SChar:
2997 return "signed char";
2998 case Short:
2999 return "short";
3000 case Int:
3001 return "int";
3002 case Long:
3003 return "long";
3004 case LongLong:
3005 return "long long";
3006 case Int128:
3007 return "__int128";
3008 case UChar:
3009 return "unsigned char";
3010 case UShort:
3011 return "unsigned short";
3012 case UInt:
3013 return "unsigned int";
3014 case ULong:
3015 return "unsigned long";
3016 case ULongLong:
3017 return "unsigned long long";
3018 case UInt128:
3019 return "unsigned __int128";
3020 case Half:
3021 return Policy.Half ? "half" : "__fp16";
3022 case BFloat16:
3023 return "__bf16";
3024 case Float:
3025 return "float";
3026 case Double:
3027 return "double";
3028 case LongDouble:
3029 return "long double";
3030 case ShortAccum:
3031 return "short _Accum";
3032 case Accum:
3033 return "_Accum";
3034 case LongAccum:
3035 return "long _Accum";
3036 case UShortAccum:
3037 return "unsigned short _Accum";
3038 case UAccum:
3039 return "unsigned _Accum";
3040 case ULongAccum:
3041 return "unsigned long _Accum";
3042 case BuiltinType::ShortFract:
3043 return "short _Fract";
3044 case BuiltinType::Fract:
3045 return "_Fract";
3046 case BuiltinType::LongFract:
3047 return "long _Fract";
3048 case BuiltinType::UShortFract:
3049 return "unsigned short _Fract";
3050 case BuiltinType::UFract:
3051 return "unsigned _Fract";
3052 case BuiltinType::ULongFract:
3053 return "unsigned long _Fract";
3054 case BuiltinType::SatShortAccum:
3055 return "_Sat short _Accum";
3056 case BuiltinType::SatAccum:
3057 return "_Sat _Accum";
3058 case BuiltinType::SatLongAccum:
3059 return "_Sat long _Accum";
3060 case BuiltinType::SatUShortAccum:
3061 return "_Sat unsigned short _Accum";
3062 case BuiltinType::SatUAccum:
3063 return "_Sat unsigned _Accum";
3064 case BuiltinType::SatULongAccum:
3065 return "_Sat unsigned long _Accum";
3066 case BuiltinType::SatShortFract:
3067 return "_Sat short _Fract";
3068 case BuiltinType::SatFract:
3069 return "_Sat _Fract";
3070 case BuiltinType::SatLongFract:
3071 return "_Sat long _Fract";
3072 case BuiltinType::SatUShortFract:
3073 return "_Sat unsigned short _Fract";
3074 case BuiltinType::SatUFract:
3075 return "_Sat unsigned _Fract";
3076 case BuiltinType::SatULongFract:
3077 return "_Sat unsigned long _Fract";
3078 case Float16:
3079 return "_Float16";
3080 case Float128:
3081 return "__float128";
3082 case Ibm128:
3083 return "__ibm128";
3084 case WChar_S:
3085 case WChar_U:
3086 return Policy.MSWChar ? "__wchar_t" : "wchar_t";
3087 case Char8:
3088 return "char8_t";
3089 case Char16:
3090 return "char16_t";
3091 case Char32:
3092 return "char32_t";
3093 case NullPtr:
3094 return Policy.NullptrTypeInNamespace ? "std::nullptr_t" : "nullptr_t";
3095 case Overload:
3096 return "<overloaded function type>";
3097 case BoundMember:
3098 return "<bound member function type>";
3099 case PseudoObject:
3100 return "<pseudo-object type>";
3101 case Dependent:
3102 return "<dependent type>";
3103 case UnknownAny:
3104 return "<unknown type>";
3105 case ARCUnbridgedCast:
3106 return "<ARC unbridged cast type>";
3107 case BuiltinFn:
3108 return "<builtin fn type>";
3109 case ObjCId:
3110 return "id";
3111 case ObjCClass:
3112 return "Class";
3113 case ObjCSel:
3114 return "SEL";
3115 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
3116 case Id: \
3117 return "__" #Access " " #ImgType "_t";
3118 #include "clang/Basic/OpenCLImageTypes.def"
3119 case OCLSampler:
3120 return "sampler_t";
3121 case OCLEvent:
3122 return "event_t";
3123 case OCLClkEvent:
3124 return "clk_event_t";
3125 case OCLQueue:
3126 return "queue_t";
3127 case OCLReserveID:
3128 return "reserve_id_t";
3129 case IncompleteMatrixIdx:
3130 return "<incomplete matrix index type>";
3131 case OMPArraySection:
3132 return "<OpenMP array section type>";
3133 case OMPArrayShaping:
3134 return "<OpenMP array shaping type>";
3135 case OMPIterator:
3136 return "<OpenMP iterator type>";
3137 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
3138 case Id: \
3139 return #ExtType;
3140 #include "clang/Basic/OpenCLExtensionTypes.def"
3141 #define SVE_TYPE(Name, Id, SingletonId) \
3142 case Id: \
3143 return Name;
3144 #include "clang/Basic/AArch64SVEACLETypes.def"
3145 #define PPC_VECTOR_TYPE(Name, Id, Size) \
3146 case Id: \
3147 return #Name;
3148 #include "clang/Basic/PPCTypes.def"
3149 #define RVV_TYPE(Name, Id, SingletonId) \
3150 case Id: \
3151 return Name;
3152 #include "clang/Basic/RISCVVTypes.def"
3153 }
3154
3155 llvm_unreachable("Invalid builtin type.");
3156 }
3157
getNonPackExpansionType() const3158 QualType QualType::getNonPackExpansionType() const {
3159 // We never wrap type sugar around a PackExpansionType.
3160 if (auto *PET = dyn_cast<PackExpansionType>(getTypePtr()))
3161 return PET->getPattern();
3162 return *this;
3163 }
3164
getNonLValueExprType(const ASTContext & Context) const3165 QualType QualType::getNonLValueExprType(const ASTContext &Context) const {
3166 if (const auto *RefType = getTypePtr()->getAs<ReferenceType>())
3167 return RefType->getPointeeType();
3168
3169 // C++0x [basic.lval]:
3170 // Class prvalues can have cv-qualified types; non-class prvalues always
3171 // have cv-unqualified types.
3172 //
3173 // See also C99 6.3.2.1p2.
3174 if (!Context.getLangOpts().CPlusPlus ||
3175 (!getTypePtr()->isDependentType() && !getTypePtr()->isRecordType()))
3176 return getUnqualifiedType();
3177
3178 return *this;
3179 }
3180
getNameForCallConv(CallingConv CC)3181 StringRef FunctionType::getNameForCallConv(CallingConv CC) {
3182 switch (CC) {
3183 case CC_C: return "cdecl";
3184 case CC_X86StdCall: return "stdcall";
3185 case CC_X86FastCall: return "fastcall";
3186 case CC_X86ThisCall: return "thiscall";
3187 case CC_X86Pascal: return "pascal";
3188 case CC_X86VectorCall: return "vectorcall";
3189 case CC_Win64: return "ms_abi";
3190 case CC_X86_64SysV: return "sysv_abi";
3191 case CC_X86RegCall : return "regcall";
3192 case CC_AAPCS: return "aapcs";
3193 case CC_AAPCS_VFP: return "aapcs-vfp";
3194 case CC_AArch64VectorCall: return "aarch64_vector_pcs";
3195 case CC_AArch64SVEPCS: return "aarch64_sve_pcs";
3196 case CC_AMDGPUKernelCall: return "amdgpu_kernel";
3197 case CC_IntelOclBicc: return "intel_ocl_bicc";
3198 case CC_SpirFunction: return "spir_function";
3199 case CC_OpenCLKernel: return "opencl_kernel";
3200 case CC_Swift: return "swiftcall";
3201 case CC_SwiftAsync: return "swiftasynccall";
3202 case CC_PreserveMost: return "preserve_most";
3203 case CC_PreserveAll: return "preserve_all";
3204 }
3205
3206 llvm_unreachable("Invalid calling convention.");
3207 }
3208
FunctionProtoType(QualType result,ArrayRef<QualType> params,QualType canonical,const ExtProtoInfo & epi)3209 FunctionProtoType::FunctionProtoType(QualType result, ArrayRef<QualType> params,
3210 QualType canonical,
3211 const ExtProtoInfo &epi)
3212 : FunctionType(FunctionProto, result, canonical, result->getDependence(),
3213 epi.ExtInfo) {
3214 FunctionTypeBits.FastTypeQuals = epi.TypeQuals.getFastQualifiers();
3215 FunctionTypeBits.RefQualifier = epi.RefQualifier;
3216 FunctionTypeBits.NumParams = params.size();
3217 assert(getNumParams() == params.size() && "NumParams overflow!");
3218 FunctionTypeBits.ExceptionSpecType = epi.ExceptionSpec.Type;
3219 FunctionTypeBits.HasExtParameterInfos = !!epi.ExtParameterInfos;
3220 FunctionTypeBits.Variadic = epi.Variadic;
3221 FunctionTypeBits.HasTrailingReturn = epi.HasTrailingReturn;
3222
3223 if (epi.requiresFunctionProtoTypeExtraBitfields()) {
3224 FunctionTypeBits.HasExtraBitfields = true;
3225 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3226 ExtraBits = FunctionTypeExtraBitfields();
3227 } else {
3228 FunctionTypeBits.HasExtraBitfields = false;
3229 }
3230
3231
3232 // Fill in the trailing argument array.
3233 auto *argSlot = getTrailingObjects<QualType>();
3234 for (unsigned i = 0; i != getNumParams(); ++i) {
3235 addDependence(params[i]->getDependence() &
3236 ~TypeDependence::VariablyModified);
3237 argSlot[i] = params[i];
3238 }
3239
3240 // Fill in the exception type array if present.
3241 if (getExceptionSpecType() == EST_Dynamic) {
3242 auto &ExtraBits = *getTrailingObjects<FunctionTypeExtraBitfields>();
3243 ExtraBits.NumExceptionType = epi.ExceptionSpec.Exceptions.size();
3244
3245 assert(hasExtraBitfields() && "missing trailing extra bitfields!");
3246 auto *exnSlot =
3247 reinterpret_cast<QualType *>(getTrailingObjects<ExceptionType>());
3248 unsigned I = 0;
3249 for (QualType ExceptionType : epi.ExceptionSpec.Exceptions) {
3250 // Note that, before C++17, a dependent exception specification does
3251 // *not* make a type dependent; it's not even part of the C++ type
3252 // system.
3253 addDependence(
3254 ExceptionType->getDependence() &
3255 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3256
3257 exnSlot[I++] = ExceptionType;
3258 }
3259 }
3260 // Fill in the Expr * in the exception specification if present.
3261 else if (isComputedNoexcept(getExceptionSpecType())) {
3262 assert(epi.ExceptionSpec.NoexceptExpr && "computed noexcept with no expr");
3263 assert((getExceptionSpecType() == EST_DependentNoexcept) ==
3264 epi.ExceptionSpec.NoexceptExpr->isValueDependent());
3265
3266 // Store the noexcept expression and context.
3267 *getTrailingObjects<Expr *>() = epi.ExceptionSpec.NoexceptExpr;
3268
3269 addDependence(
3270 toTypeDependence(epi.ExceptionSpec.NoexceptExpr->getDependence()) &
3271 (TypeDependence::Instantiation | TypeDependence::UnexpandedPack));
3272 }
3273 // Fill in the FunctionDecl * in the exception specification if present.
3274 else if (getExceptionSpecType() == EST_Uninstantiated) {
3275 // Store the function decl from which we will resolve our
3276 // exception specification.
3277 auto **slot = getTrailingObjects<FunctionDecl *>();
3278 slot[0] = epi.ExceptionSpec.SourceDecl;
3279 slot[1] = epi.ExceptionSpec.SourceTemplate;
3280 // This exception specification doesn't make the type dependent, because
3281 // it's not instantiated as part of instantiating the type.
3282 } else if (getExceptionSpecType() == EST_Unevaluated) {
3283 // Store the function decl from which we will resolve our
3284 // exception specification.
3285 auto **slot = getTrailingObjects<FunctionDecl *>();
3286 slot[0] = epi.ExceptionSpec.SourceDecl;
3287 }
3288
3289 // If this is a canonical type, and its exception specification is dependent,
3290 // then it's a dependent type. This only happens in C++17 onwards.
3291 if (isCanonicalUnqualified()) {
3292 if (getExceptionSpecType() == EST_Dynamic ||
3293 getExceptionSpecType() == EST_DependentNoexcept) {
3294 assert(hasDependentExceptionSpec() && "type should not be canonical");
3295 addDependence(TypeDependence::DependentInstantiation);
3296 }
3297 } else if (getCanonicalTypeInternal()->isDependentType()) {
3298 // Ask our canonical type whether our exception specification was dependent.
3299 addDependence(TypeDependence::DependentInstantiation);
3300 }
3301
3302 // Fill in the extra parameter info if present.
3303 if (epi.ExtParameterInfos) {
3304 auto *extParamInfos = getTrailingObjects<ExtParameterInfo>();
3305 for (unsigned i = 0; i != getNumParams(); ++i)
3306 extParamInfos[i] = epi.ExtParameterInfos[i];
3307 }
3308
3309 if (epi.TypeQuals.hasNonFastQualifiers()) {
3310 FunctionTypeBits.HasExtQuals = 1;
3311 *getTrailingObjects<Qualifiers>() = epi.TypeQuals;
3312 } else {
3313 FunctionTypeBits.HasExtQuals = 0;
3314 }
3315
3316 // Fill in the Ellipsis location info if present.
3317 if (epi.Variadic) {
3318 auto &EllipsisLoc = *getTrailingObjects<SourceLocation>();
3319 EllipsisLoc = epi.EllipsisLoc;
3320 }
3321 }
3322
hasDependentExceptionSpec() const3323 bool FunctionProtoType::hasDependentExceptionSpec() const {
3324 if (Expr *NE = getNoexceptExpr())
3325 return NE->isValueDependent();
3326 for (QualType ET : exceptions())
3327 // A pack expansion with a non-dependent pattern is still dependent,
3328 // because we don't know whether the pattern is in the exception spec
3329 // or not (that depends on whether the pack has 0 expansions).
3330 if (ET->isDependentType() || ET->getAs<PackExpansionType>())
3331 return true;
3332 return false;
3333 }
3334
hasInstantiationDependentExceptionSpec() const3335 bool FunctionProtoType::hasInstantiationDependentExceptionSpec() const {
3336 if (Expr *NE = getNoexceptExpr())
3337 return NE->isInstantiationDependent();
3338 for (QualType ET : exceptions())
3339 if (ET->isInstantiationDependentType())
3340 return true;
3341 return false;
3342 }
3343
canThrow() const3344 CanThrowResult FunctionProtoType::canThrow() const {
3345 switch (getExceptionSpecType()) {
3346 case EST_Unparsed:
3347 case EST_Unevaluated:
3348 llvm_unreachable("should not call this with unresolved exception specs");
3349
3350 case EST_DynamicNone:
3351 case EST_BasicNoexcept:
3352 case EST_NoexceptTrue:
3353 case EST_NoThrow:
3354 return CT_Cannot;
3355
3356 case EST_None:
3357 case EST_MSAny:
3358 case EST_NoexceptFalse:
3359 return CT_Can;
3360
3361 case EST_Dynamic:
3362 // A dynamic exception specification is throwing unless every exception
3363 // type is an (unexpanded) pack expansion type.
3364 for (unsigned I = 0; I != getNumExceptions(); ++I)
3365 if (!getExceptionType(I)->getAs<PackExpansionType>())
3366 return CT_Can;
3367 return CT_Dependent;
3368
3369 case EST_Uninstantiated:
3370 case EST_DependentNoexcept:
3371 return CT_Dependent;
3372 }
3373
3374 llvm_unreachable("unexpected exception specification kind");
3375 }
3376
isTemplateVariadic() const3377 bool FunctionProtoType::isTemplateVariadic() const {
3378 for (unsigned ArgIdx = getNumParams(); ArgIdx; --ArgIdx)
3379 if (isa<PackExpansionType>(getParamType(ArgIdx - 1)))
3380 return true;
3381
3382 return false;
3383 }
3384
Profile(llvm::FoldingSetNodeID & ID,QualType Result,const QualType * ArgTys,unsigned NumParams,const ExtProtoInfo & epi,const ASTContext & Context,bool Canonical)3385 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID, QualType Result,
3386 const QualType *ArgTys, unsigned NumParams,
3387 const ExtProtoInfo &epi,
3388 const ASTContext &Context, bool Canonical) {
3389 // We have to be careful not to get ambiguous profile encodings.
3390 // Note that valid type pointers are never ambiguous with anything else.
3391 //
3392 // The encoding grammar begins:
3393 // type type* bool int bool
3394 // If that final bool is true, then there is a section for the EH spec:
3395 // bool type*
3396 // This is followed by an optional "consumed argument" section of the
3397 // same length as the first type sequence:
3398 // bool*
3399 // Finally, we have the ext info and trailing return type flag:
3400 // int bool
3401 //
3402 // There is no ambiguity between the consumed arguments and an empty EH
3403 // spec because of the leading 'bool' which unambiguously indicates
3404 // whether the following bool is the EH spec or part of the arguments.
3405
3406 ID.AddPointer(Result.getAsOpaquePtr());
3407 for (unsigned i = 0; i != NumParams; ++i)
3408 ID.AddPointer(ArgTys[i].getAsOpaquePtr());
3409 // This method is relatively performance sensitive, so as a performance
3410 // shortcut, use one AddInteger call instead of four for the next four
3411 // fields.
3412 assert(!(unsigned(epi.Variadic) & ~1) &&
3413 !(unsigned(epi.RefQualifier) & ~3) &&
3414 !(unsigned(epi.ExceptionSpec.Type) & ~15) &&
3415 "Values larger than expected.");
3416 ID.AddInteger(unsigned(epi.Variadic) +
3417 (epi.RefQualifier << 1) +
3418 (epi.ExceptionSpec.Type << 3));
3419 ID.Add(epi.TypeQuals);
3420 if (epi.ExceptionSpec.Type == EST_Dynamic) {
3421 for (QualType Ex : epi.ExceptionSpec.Exceptions)
3422 ID.AddPointer(Ex.getAsOpaquePtr());
3423 } else if (isComputedNoexcept(epi.ExceptionSpec.Type)) {
3424 epi.ExceptionSpec.NoexceptExpr->Profile(ID, Context, Canonical);
3425 } else if (epi.ExceptionSpec.Type == EST_Uninstantiated ||
3426 epi.ExceptionSpec.Type == EST_Unevaluated) {
3427 ID.AddPointer(epi.ExceptionSpec.SourceDecl->getCanonicalDecl());
3428 }
3429 if (epi.ExtParameterInfos) {
3430 for (unsigned i = 0; i != NumParams; ++i)
3431 ID.AddInteger(epi.ExtParameterInfos[i].getOpaqueValue());
3432 }
3433 epi.ExtInfo.Profile(ID);
3434 ID.AddBoolean(epi.HasTrailingReturn);
3435 }
3436
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Ctx)3437 void FunctionProtoType::Profile(llvm::FoldingSetNodeID &ID,
3438 const ASTContext &Ctx) {
3439 Profile(ID, getReturnType(), param_type_begin(), getNumParams(),
3440 getExtProtoInfo(), Ctx, isCanonicalUnqualified());
3441 }
3442
TypedefType(TypeClass tc,const TypedefNameDecl * D,QualType Underlying,QualType can)3443 TypedefType::TypedefType(TypeClass tc, const TypedefNameDecl *D,
3444 QualType Underlying, QualType can)
3445 : Type(tc, can, toSemanticDependence(can->getDependence())),
3446 Decl(const_cast<TypedefNameDecl *>(D)) {
3447 assert(!isa<TypedefType>(can) && "Invalid canonical type");
3448 TypedefBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3449 if (!typeMatchesDecl())
3450 *getTrailingObjects<QualType>() = Underlying;
3451 }
3452
desugar() const3453 QualType TypedefType::desugar() const {
3454 return typeMatchesDecl() ? Decl->getUnderlyingType()
3455 : *getTrailingObjects<QualType>();
3456 }
3457
UsingType(const UsingShadowDecl * Found,QualType Underlying,QualType Canon)3458 UsingType::UsingType(const UsingShadowDecl *Found, QualType Underlying,
3459 QualType Canon)
3460 : Type(Using, Canon, toSemanticDependence(Canon->getDependence())),
3461 Found(const_cast<UsingShadowDecl *>(Found)) {
3462 UsingBits.hasTypeDifferentFromDecl = !Underlying.isNull();
3463 if (!typeMatchesDecl())
3464 *getTrailingObjects<QualType>() = Underlying;
3465 }
3466
getUnderlyingType() const3467 QualType UsingType::getUnderlyingType() const {
3468 return typeMatchesDecl()
3469 ? QualType(
3470 cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl(), 0)
3471 : *getTrailingObjects<QualType>();
3472 }
3473
desugar() const3474 QualType MacroQualifiedType::desugar() const { return getUnderlyingType(); }
3475
getModifiedType() const3476 QualType MacroQualifiedType::getModifiedType() const {
3477 // Step over MacroQualifiedTypes from the same macro to find the type
3478 // ultimately qualified by the macro qualifier.
3479 QualType Inner = cast<AttributedType>(getUnderlyingType())->getModifiedType();
3480 while (auto *InnerMQT = dyn_cast<MacroQualifiedType>(Inner)) {
3481 if (InnerMQT->getMacroIdentifier() != getMacroIdentifier())
3482 break;
3483 Inner = InnerMQT->getModifiedType();
3484 }
3485 return Inner;
3486 }
3487
TypeOfExprType(Expr * E,TypeOfKind Kind,QualType Can)3488 TypeOfExprType::TypeOfExprType(Expr *E, TypeOfKind Kind, QualType Can)
3489 : Type(TypeOfExpr,
3490 // We have to protect against 'Can' being invalid through its
3491 // default argument.
3492 Kind == TypeOfKind::Unqualified && !Can.isNull()
3493 ? Can.getAtomicUnqualifiedType()
3494 : Can,
3495 toTypeDependence(E->getDependence()) |
3496 (E->getType()->getDependence() &
3497 TypeDependence::VariablyModified)),
3498 TOExpr(E) {
3499 TypeOfBits.IsUnqual = Kind == TypeOfKind::Unqualified;
3500 }
3501
isSugared() const3502 bool TypeOfExprType::isSugared() const {
3503 return !TOExpr->isTypeDependent();
3504 }
3505
desugar() const3506 QualType TypeOfExprType::desugar() const {
3507 if (isSugared()) {
3508 QualType QT = getUnderlyingExpr()->getType();
3509 return TypeOfBits.IsUnqual ? QT.getAtomicUnqualifiedType() : QT;
3510 }
3511 return QualType(this, 0);
3512 }
3513
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,Expr * E,bool IsUnqual)3514 void DependentTypeOfExprType::Profile(llvm::FoldingSetNodeID &ID,
3515 const ASTContext &Context, Expr *E,
3516 bool IsUnqual) {
3517 E->Profile(ID, Context, true);
3518 ID.AddBoolean(IsUnqual);
3519 }
3520
DecltypeType(Expr * E,QualType underlyingType,QualType can)3521 DecltypeType::DecltypeType(Expr *E, QualType underlyingType, QualType can)
3522 // C++11 [temp.type]p2: "If an expression e involves a template parameter,
3523 // decltype(e) denotes a unique dependent type." Hence a decltype type is
3524 // type-dependent even if its expression is only instantiation-dependent.
3525 : Type(Decltype, can,
3526 toTypeDependence(E->getDependence()) |
3527 (E->isInstantiationDependent() ? TypeDependence::Dependent
3528 : TypeDependence::None) |
3529 (E->getType()->getDependence() &
3530 TypeDependence::VariablyModified)),
3531 E(E), UnderlyingType(underlyingType) {}
3532
isSugared() const3533 bool DecltypeType::isSugared() const { return !E->isInstantiationDependent(); }
3534
desugar() const3535 QualType DecltypeType::desugar() const {
3536 if (isSugared())
3537 return getUnderlyingType();
3538
3539 return QualType(this, 0);
3540 }
3541
DependentDecltypeType(const ASTContext & Context,Expr * E)3542 DependentDecltypeType::DependentDecltypeType(const ASTContext &Context, Expr *E)
3543 : DecltypeType(E, Context.DependentTy), Context(Context) {}
3544
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,Expr * E)3545 void DependentDecltypeType::Profile(llvm::FoldingSetNodeID &ID,
3546 const ASTContext &Context, Expr *E) {
3547 E->Profile(ID, Context, true);
3548 }
3549
UnaryTransformType(QualType BaseType,QualType UnderlyingType,UTTKind UKind,QualType CanonicalType)3550 UnaryTransformType::UnaryTransformType(QualType BaseType,
3551 QualType UnderlyingType, UTTKind UKind,
3552 QualType CanonicalType)
3553 : Type(UnaryTransform, CanonicalType, BaseType->getDependence()),
3554 BaseType(BaseType), UnderlyingType(UnderlyingType), UKind(UKind) {}
3555
DependentUnaryTransformType(const ASTContext & C,QualType BaseType,UTTKind UKind)3556 DependentUnaryTransformType::DependentUnaryTransformType(const ASTContext &C,
3557 QualType BaseType,
3558 UTTKind UKind)
3559 : UnaryTransformType(BaseType, C.DependentTy, UKind, QualType()) {}
3560
TagType(TypeClass TC,const TagDecl * D,QualType can)3561 TagType::TagType(TypeClass TC, const TagDecl *D, QualType can)
3562 : Type(TC, can,
3563 D->isDependentType() ? TypeDependence::DependentInstantiation
3564 : TypeDependence::None),
3565 decl(const_cast<TagDecl *>(D)) {}
3566
getInterestingTagDecl(TagDecl * decl)3567 static TagDecl *getInterestingTagDecl(TagDecl *decl) {
3568 for (auto *I : decl->redecls()) {
3569 if (I->isCompleteDefinition() || I->isBeingDefined())
3570 return I;
3571 }
3572 // If there's no definition (not even in progress), return what we have.
3573 return decl;
3574 }
3575
getDecl() const3576 TagDecl *TagType::getDecl() const {
3577 return getInterestingTagDecl(decl);
3578 }
3579
isBeingDefined() const3580 bool TagType::isBeingDefined() const {
3581 return getDecl()->isBeingDefined();
3582 }
3583
hasConstFields() const3584 bool RecordType::hasConstFields() const {
3585 std::vector<const RecordType*> RecordTypeList;
3586 RecordTypeList.push_back(this);
3587 unsigned NextToCheckIndex = 0;
3588
3589 while (RecordTypeList.size() > NextToCheckIndex) {
3590 for (FieldDecl *FD :
3591 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
3592 QualType FieldTy = FD->getType();
3593 if (FieldTy.isConstQualified())
3594 return true;
3595 FieldTy = FieldTy.getCanonicalType();
3596 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
3597 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
3598 RecordTypeList.push_back(FieldRecTy);
3599 }
3600 }
3601 ++NextToCheckIndex;
3602 }
3603 return false;
3604 }
3605
isQualifier() const3606 bool AttributedType::isQualifier() const {
3607 // FIXME: Generate this with TableGen.
3608 switch (getAttrKind()) {
3609 // These are type qualifiers in the traditional C sense: they annotate
3610 // something about a specific value/variable of a type. (They aren't
3611 // always part of the canonical type, though.)
3612 case attr::ObjCGC:
3613 case attr::ObjCOwnership:
3614 case attr::ObjCInertUnsafeUnretained:
3615 case attr::TypeNonNull:
3616 case attr::TypeNullable:
3617 case attr::TypeNullableResult:
3618 case attr::TypeNullUnspecified:
3619 case attr::LifetimeBound:
3620 case attr::AddressSpace:
3621 return true;
3622
3623 // All other type attributes aren't qualifiers; they rewrite the modified
3624 // type to be a semantically different type.
3625 default:
3626 return false;
3627 }
3628 }
3629
isMSTypeSpec() const3630 bool AttributedType::isMSTypeSpec() const {
3631 // FIXME: Generate this with TableGen?
3632 switch (getAttrKind()) {
3633 default: return false;
3634 case attr::Ptr32:
3635 case attr::Ptr64:
3636 case attr::SPtr:
3637 case attr::UPtr:
3638 return true;
3639 }
3640 llvm_unreachable("invalid attr kind");
3641 }
3642
isCallingConv() const3643 bool AttributedType::isCallingConv() const {
3644 // FIXME: Generate this with TableGen.
3645 switch (getAttrKind()) {
3646 default: return false;
3647 case attr::Pcs:
3648 case attr::CDecl:
3649 case attr::FastCall:
3650 case attr::StdCall:
3651 case attr::ThisCall:
3652 case attr::RegCall:
3653 case attr::SwiftCall:
3654 case attr::SwiftAsyncCall:
3655 case attr::VectorCall:
3656 case attr::AArch64VectorPcs:
3657 case attr::AArch64SVEPcs:
3658 case attr::AMDGPUKernelCall:
3659 case attr::Pascal:
3660 case attr::MSABI:
3661 case attr::SysVABI:
3662 case attr::IntelOclBicc:
3663 case attr::PreserveMost:
3664 case attr::PreserveAll:
3665 return true;
3666 }
3667 llvm_unreachable("invalid attr kind");
3668 }
3669
getDecl() const3670 CXXRecordDecl *InjectedClassNameType::getDecl() const {
3671 return cast<CXXRecordDecl>(getInterestingTagDecl(Decl));
3672 }
3673
getIdentifier() const3674 IdentifierInfo *TemplateTypeParmType::getIdentifier() const {
3675 return isCanonicalUnqualified() ? nullptr : getDecl()->getIdentifier();
3676 }
3677
getReplacedParameter(Decl * D,unsigned Index)3678 static const TemplateTypeParmDecl *getReplacedParameter(Decl *D,
3679 unsigned Index) {
3680 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
3681 return TTP;
3682 return cast<TemplateTypeParmDecl>(
3683 getReplacedTemplateParameterList(D)->getParam(Index));
3684 }
3685
SubstTemplateTypeParmType(QualType Replacement,Decl * AssociatedDecl,unsigned Index,std::optional<unsigned> PackIndex)3686 SubstTemplateTypeParmType::SubstTemplateTypeParmType(
3687 QualType Replacement, Decl *AssociatedDecl, unsigned Index,
3688 std::optional<unsigned> PackIndex)
3689 : Type(SubstTemplateTypeParm, Replacement.getCanonicalType(),
3690 Replacement->getDependence()),
3691 AssociatedDecl(AssociatedDecl) {
3692 SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType =
3693 Replacement != getCanonicalTypeInternal();
3694 if (SubstTemplateTypeParmTypeBits.HasNonCanonicalUnderlyingType)
3695 *getTrailingObjects<QualType>() = Replacement;
3696
3697 SubstTemplateTypeParmTypeBits.Index = Index;
3698 SubstTemplateTypeParmTypeBits.PackIndex = PackIndex ? *PackIndex + 1 : 0;
3699 assert(AssociatedDecl != nullptr);
3700 }
3701
3702 const TemplateTypeParmDecl *
getReplacedParameter() const3703 SubstTemplateTypeParmType::getReplacedParameter() const {
3704 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3705 }
3706
SubstTemplateTypeParmPackType(QualType Canon,Decl * AssociatedDecl,unsigned Index,bool Final,const TemplateArgument & ArgPack)3707 SubstTemplateTypeParmPackType::SubstTemplateTypeParmPackType(
3708 QualType Canon, Decl *AssociatedDecl, unsigned Index, bool Final,
3709 const TemplateArgument &ArgPack)
3710 : Type(SubstTemplateTypeParmPack, Canon,
3711 TypeDependence::DependentInstantiation |
3712 TypeDependence::UnexpandedPack),
3713 Arguments(ArgPack.pack_begin()),
3714 AssociatedDeclAndFinal(AssociatedDecl, Final) {
3715 SubstTemplateTypeParmPackTypeBits.Index = Index;
3716 SubstTemplateTypeParmPackTypeBits.NumArgs = ArgPack.pack_size();
3717 assert(AssociatedDecl != nullptr);
3718 }
3719
getAssociatedDecl() const3720 Decl *SubstTemplateTypeParmPackType::getAssociatedDecl() const {
3721 return AssociatedDeclAndFinal.getPointer();
3722 }
3723
getFinal() const3724 bool SubstTemplateTypeParmPackType::getFinal() const {
3725 return AssociatedDeclAndFinal.getInt();
3726 }
3727
3728 const TemplateTypeParmDecl *
getReplacedParameter() const3729 SubstTemplateTypeParmPackType::getReplacedParameter() const {
3730 return ::getReplacedParameter(getAssociatedDecl(), getIndex());
3731 }
3732
getIdentifier() const3733 IdentifierInfo *SubstTemplateTypeParmPackType::getIdentifier() const {
3734 return getReplacedParameter()->getIdentifier();
3735 }
3736
getArgumentPack() const3737 TemplateArgument SubstTemplateTypeParmPackType::getArgumentPack() const {
3738 return TemplateArgument(llvm::ArrayRef(Arguments, getNumArgs()));
3739 }
3740
Profile(llvm::FoldingSetNodeID & ID)3741 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID) {
3742 Profile(ID, getAssociatedDecl(), getIndex(), getFinal(), getArgumentPack());
3743 }
3744
Profile(llvm::FoldingSetNodeID & ID,const Decl * AssociatedDecl,unsigned Index,bool Final,const TemplateArgument & ArgPack)3745 void SubstTemplateTypeParmPackType::Profile(llvm::FoldingSetNodeID &ID,
3746 const Decl *AssociatedDecl,
3747 unsigned Index, bool Final,
3748 const TemplateArgument &ArgPack) {
3749 ID.AddPointer(AssociatedDecl);
3750 ID.AddInteger(Index);
3751 ID.AddBoolean(Final);
3752 ID.AddInteger(ArgPack.pack_size());
3753 for (const auto &P : ArgPack.pack_elements())
3754 ID.AddPointer(P.getAsType().getAsOpaquePtr());
3755 }
3756
anyDependentTemplateArguments(const TemplateArgumentListInfo & Args,ArrayRef<TemplateArgument> Converted)3757 bool TemplateSpecializationType::anyDependentTemplateArguments(
3758 const TemplateArgumentListInfo &Args, ArrayRef<TemplateArgument> Converted) {
3759 return anyDependentTemplateArguments(Args.arguments(), Converted);
3760 }
3761
anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,ArrayRef<TemplateArgument> Converted)3762 bool TemplateSpecializationType::anyDependentTemplateArguments(
3763 ArrayRef<TemplateArgumentLoc> Args, ArrayRef<TemplateArgument> Converted) {
3764 for (const TemplateArgument &Arg : Converted)
3765 if (Arg.isDependent())
3766 return true;
3767 return false;
3768 }
3769
anyInstantiationDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args)3770 bool TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
3771 ArrayRef<TemplateArgumentLoc> Args) {
3772 for (const TemplateArgumentLoc &ArgLoc : Args) {
3773 if (ArgLoc.getArgument().isInstantiationDependent())
3774 return true;
3775 }
3776 return false;
3777 }
3778
TemplateSpecializationType(TemplateName T,ArrayRef<TemplateArgument> Args,QualType Canon,QualType AliasedType)3779 TemplateSpecializationType::TemplateSpecializationType(
3780 TemplateName T, ArrayRef<TemplateArgument> Args, QualType Canon,
3781 QualType AliasedType)
3782 : Type(TemplateSpecialization, Canon.isNull() ? QualType(this, 0) : Canon,
3783 (Canon.isNull()
3784 ? TypeDependence::DependentInstantiation
3785 : toSemanticDependence(Canon->getDependence())) |
3786 (toTypeDependence(T.getDependence()) &
3787 TypeDependence::UnexpandedPack)),
3788 Template(T) {
3789 TemplateSpecializationTypeBits.NumArgs = Args.size();
3790 TemplateSpecializationTypeBits.TypeAlias = !AliasedType.isNull();
3791
3792 assert(!T.getAsDependentTemplateName() &&
3793 "Use DependentTemplateSpecializationType for dependent template-name");
3794 assert((T.getKind() == TemplateName::Template ||
3795 T.getKind() == TemplateName::SubstTemplateTemplateParm ||
3796 T.getKind() == TemplateName::SubstTemplateTemplateParmPack ||
3797 T.getKind() == TemplateName::UsingTemplate) &&
3798 "Unexpected template name for TemplateSpecializationType");
3799
3800 auto *TemplateArgs = reinterpret_cast<TemplateArgument *>(this + 1);
3801 for (const TemplateArgument &Arg : Args) {
3802 // Update instantiation-dependent, variably-modified, and error bits.
3803 // If the canonical type exists and is non-dependent, the template
3804 // specialization type can be non-dependent even if one of the type
3805 // arguments is. Given:
3806 // template<typename T> using U = int;
3807 // U<T> is always non-dependent, irrespective of the type T.
3808 // However, U<Ts> contains an unexpanded parameter pack, even though
3809 // its expansion (and thus its desugared type) doesn't.
3810 addDependence(toTypeDependence(Arg.getDependence()) &
3811 ~TypeDependence::Dependent);
3812 if (Arg.getKind() == TemplateArgument::Type)
3813 addDependence(Arg.getAsType()->getDependence() &
3814 TypeDependence::VariablyModified);
3815 new (TemplateArgs++) TemplateArgument(Arg);
3816 }
3817
3818 // Store the aliased type if this is a type alias template specialization.
3819 if (isTypeAlias()) {
3820 auto *Begin = reinterpret_cast<TemplateArgument *>(this + 1);
3821 *reinterpret_cast<QualType *>(Begin + Args.size()) = AliasedType;
3822 }
3823 }
3824
getAliasedType() const3825 QualType TemplateSpecializationType::getAliasedType() const {
3826 assert(isTypeAlias() && "not a type alias template specialization");
3827 return *reinterpret_cast<const QualType *>(template_arguments().end());
3828 }
3829
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Ctx)3830 void TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3831 const ASTContext &Ctx) {
3832 Profile(ID, Template, template_arguments(), Ctx);
3833 if (isTypeAlias())
3834 getAliasedType().Profile(ID);
3835 }
3836
3837 void
Profile(llvm::FoldingSetNodeID & ID,TemplateName T,ArrayRef<TemplateArgument> Args,const ASTContext & Context)3838 TemplateSpecializationType::Profile(llvm::FoldingSetNodeID &ID,
3839 TemplateName T,
3840 ArrayRef<TemplateArgument> Args,
3841 const ASTContext &Context) {
3842 T.Profile(ID);
3843 for (const TemplateArgument &Arg : Args)
3844 Arg.Profile(ID, Context);
3845 }
3846
3847 QualType
apply(const ASTContext & Context,QualType QT) const3848 QualifierCollector::apply(const ASTContext &Context, QualType QT) const {
3849 if (!hasNonFastQualifiers())
3850 return QT.withFastQualifiers(getFastQualifiers());
3851
3852 return Context.getQualifiedType(QT, *this);
3853 }
3854
3855 QualType
apply(const ASTContext & Context,const Type * T) const3856 QualifierCollector::apply(const ASTContext &Context, const Type *T) const {
3857 if (!hasNonFastQualifiers())
3858 return QualType(T, getFastQualifiers());
3859
3860 return Context.getQualifiedType(T, *this);
3861 }
3862
Profile(llvm::FoldingSetNodeID & ID,QualType BaseType,ArrayRef<QualType> typeArgs,ArrayRef<ObjCProtocolDecl * > protocols,bool isKindOf)3863 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID,
3864 QualType BaseType,
3865 ArrayRef<QualType> typeArgs,
3866 ArrayRef<ObjCProtocolDecl *> protocols,
3867 bool isKindOf) {
3868 ID.AddPointer(BaseType.getAsOpaquePtr());
3869 ID.AddInteger(typeArgs.size());
3870 for (auto typeArg : typeArgs)
3871 ID.AddPointer(typeArg.getAsOpaquePtr());
3872 ID.AddInteger(protocols.size());
3873 for (auto *proto : protocols)
3874 ID.AddPointer(proto);
3875 ID.AddBoolean(isKindOf);
3876 }
3877
Profile(llvm::FoldingSetNodeID & ID)3878 void ObjCObjectTypeImpl::Profile(llvm::FoldingSetNodeID &ID) {
3879 Profile(ID, getBaseType(), getTypeArgsAsWritten(),
3880 llvm::ArrayRef(qual_begin(), getNumProtocols()),
3881 isKindOfTypeAsWritten());
3882 }
3883
Profile(llvm::FoldingSetNodeID & ID,const ObjCTypeParamDecl * OTPDecl,QualType CanonicalType,ArrayRef<ObjCProtocolDecl * > protocols)3884 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID,
3885 const ObjCTypeParamDecl *OTPDecl,
3886 QualType CanonicalType,
3887 ArrayRef<ObjCProtocolDecl *> protocols) {
3888 ID.AddPointer(OTPDecl);
3889 ID.AddPointer(CanonicalType.getAsOpaquePtr());
3890 ID.AddInteger(protocols.size());
3891 for (auto *proto : protocols)
3892 ID.AddPointer(proto);
3893 }
3894
Profile(llvm::FoldingSetNodeID & ID)3895 void ObjCTypeParamType::Profile(llvm::FoldingSetNodeID &ID) {
3896 Profile(ID, getDecl(), getCanonicalTypeInternal(),
3897 llvm::ArrayRef(qual_begin(), getNumProtocols()));
3898 }
3899
3900 namespace {
3901
3902 /// The cached properties of a type.
3903 class CachedProperties {
3904 Linkage L;
3905 bool local;
3906
3907 public:
CachedProperties(Linkage L,bool local)3908 CachedProperties(Linkage L, bool local) : L(L), local(local) {}
3909
getLinkage() const3910 Linkage getLinkage() const { return L; }
hasLocalOrUnnamedType() const3911 bool hasLocalOrUnnamedType() const { return local; }
3912
merge(CachedProperties L,CachedProperties R)3913 friend CachedProperties merge(CachedProperties L, CachedProperties R) {
3914 Linkage MergedLinkage = minLinkage(L.L, R.L);
3915 return CachedProperties(MergedLinkage, L.hasLocalOrUnnamedType() ||
3916 R.hasLocalOrUnnamedType());
3917 }
3918 };
3919
3920 } // namespace
3921
3922 static CachedProperties computeCachedProperties(const Type *T);
3923
3924 namespace clang {
3925
3926 /// The type-property cache. This is templated so as to be
3927 /// instantiated at an internal type to prevent unnecessary symbol
3928 /// leakage.
3929 template <class Private> class TypePropertyCache {
3930 public:
get(QualType T)3931 static CachedProperties get(QualType T) {
3932 return get(T.getTypePtr());
3933 }
3934
get(const Type * T)3935 static CachedProperties get(const Type *T) {
3936 ensure(T);
3937 return CachedProperties(T->TypeBits.getLinkage(),
3938 T->TypeBits.hasLocalOrUnnamedType());
3939 }
3940
ensure(const Type * T)3941 static void ensure(const Type *T) {
3942 // If the cache is valid, we're okay.
3943 if (T->TypeBits.isCacheValid()) return;
3944
3945 // If this type is non-canonical, ask its canonical type for the
3946 // relevant information.
3947 if (!T->isCanonicalUnqualified()) {
3948 const Type *CT = T->getCanonicalTypeInternal().getTypePtr();
3949 ensure(CT);
3950 T->TypeBits.CacheValid = true;
3951 T->TypeBits.CachedLinkage = CT->TypeBits.CachedLinkage;
3952 T->TypeBits.CachedLocalOrUnnamed = CT->TypeBits.CachedLocalOrUnnamed;
3953 return;
3954 }
3955
3956 // Compute the cached properties and then set the cache.
3957 CachedProperties Result = computeCachedProperties(T);
3958 T->TypeBits.CacheValid = true;
3959 T->TypeBits.CachedLinkage = Result.getLinkage();
3960 T->TypeBits.CachedLocalOrUnnamed = Result.hasLocalOrUnnamedType();
3961 }
3962 };
3963
3964 } // namespace clang
3965
3966 // Instantiate the friend template at a private class. In a
3967 // reasonable implementation, these symbols will be internal.
3968 // It is terrible that this is the best way to accomplish this.
3969 namespace {
3970
3971 class Private {};
3972
3973 } // namespace
3974
3975 using Cache = TypePropertyCache<Private>;
3976
computeCachedProperties(const Type * T)3977 static CachedProperties computeCachedProperties(const Type *T) {
3978 switch (T->getTypeClass()) {
3979 #define TYPE(Class,Base)
3980 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
3981 #include "clang/AST/TypeNodes.inc"
3982 llvm_unreachable("didn't expect a non-canonical type here");
3983
3984 #define TYPE(Class,Base)
3985 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
3986 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
3987 #include "clang/AST/TypeNodes.inc"
3988 // Treat instantiation-dependent types as external.
3989 if (!T->isInstantiationDependentType()) T->dump();
3990 assert(T->isInstantiationDependentType());
3991 return CachedProperties(ExternalLinkage, false);
3992
3993 case Type::Auto:
3994 case Type::DeducedTemplateSpecialization:
3995 // Give non-deduced 'auto' types external linkage. We should only see them
3996 // here in error recovery.
3997 return CachedProperties(ExternalLinkage, false);
3998
3999 case Type::BitInt:
4000 case Type::Builtin:
4001 // C++ [basic.link]p8:
4002 // A type is said to have linkage if and only if:
4003 // - it is a fundamental type (3.9.1); or
4004 return CachedProperties(ExternalLinkage, false);
4005
4006 case Type::Record:
4007 case Type::Enum: {
4008 const TagDecl *Tag = cast<TagType>(T)->getDecl();
4009
4010 // C++ [basic.link]p8:
4011 // - it is a class or enumeration type that is named (or has a name
4012 // for linkage purposes (7.1.3)) and the name has linkage; or
4013 // - it is a specialization of a class template (14); or
4014 Linkage L = Tag->getLinkageInternal();
4015 bool IsLocalOrUnnamed =
4016 Tag->getDeclContext()->isFunctionOrMethod() ||
4017 !Tag->hasNameForLinkage();
4018 return CachedProperties(L, IsLocalOrUnnamed);
4019 }
4020
4021 // C++ [basic.link]p8:
4022 // - it is a compound type (3.9.2) other than a class or enumeration,
4023 // compounded exclusively from types that have linkage; or
4024 case Type::Complex:
4025 return Cache::get(cast<ComplexType>(T)->getElementType());
4026 case Type::Pointer:
4027 return Cache::get(cast<PointerType>(T)->getPointeeType());
4028 case Type::BlockPointer:
4029 return Cache::get(cast<BlockPointerType>(T)->getPointeeType());
4030 case Type::LValueReference:
4031 case Type::RValueReference:
4032 return Cache::get(cast<ReferenceType>(T)->getPointeeType());
4033 case Type::MemberPointer: {
4034 const auto *MPT = cast<MemberPointerType>(T);
4035 return merge(Cache::get(MPT->getClass()),
4036 Cache::get(MPT->getPointeeType()));
4037 }
4038 case Type::ConstantArray:
4039 case Type::IncompleteArray:
4040 case Type::VariableArray:
4041 return Cache::get(cast<ArrayType>(T)->getElementType());
4042 case Type::Vector:
4043 case Type::ExtVector:
4044 return Cache::get(cast<VectorType>(T)->getElementType());
4045 case Type::ConstantMatrix:
4046 return Cache::get(cast<ConstantMatrixType>(T)->getElementType());
4047 case Type::FunctionNoProto:
4048 return Cache::get(cast<FunctionType>(T)->getReturnType());
4049 case Type::FunctionProto: {
4050 const auto *FPT = cast<FunctionProtoType>(T);
4051 CachedProperties result = Cache::get(FPT->getReturnType());
4052 for (const auto &ai : FPT->param_types())
4053 result = merge(result, Cache::get(ai));
4054 return result;
4055 }
4056 case Type::ObjCInterface: {
4057 Linkage L = cast<ObjCInterfaceType>(T)->getDecl()->getLinkageInternal();
4058 return CachedProperties(L, false);
4059 }
4060 case Type::ObjCObject:
4061 return Cache::get(cast<ObjCObjectType>(T)->getBaseType());
4062 case Type::ObjCObjectPointer:
4063 return Cache::get(cast<ObjCObjectPointerType>(T)->getPointeeType());
4064 case Type::Atomic:
4065 return Cache::get(cast<AtomicType>(T)->getValueType());
4066 case Type::Pipe:
4067 return Cache::get(cast<PipeType>(T)->getElementType());
4068 }
4069
4070 llvm_unreachable("unhandled type class");
4071 }
4072
4073 /// Determine the linkage of this type.
getLinkage() const4074 Linkage Type::getLinkage() const {
4075 Cache::ensure(this);
4076 return TypeBits.getLinkage();
4077 }
4078
hasUnnamedOrLocalType() const4079 bool Type::hasUnnamedOrLocalType() const {
4080 Cache::ensure(this);
4081 return TypeBits.hasLocalOrUnnamedType();
4082 }
4083
computeTypeLinkageInfo(const Type * T)4084 LinkageInfo LinkageComputer::computeTypeLinkageInfo(const Type *T) {
4085 switch (T->getTypeClass()) {
4086 #define TYPE(Class,Base)
4087 #define NON_CANONICAL_TYPE(Class,Base) case Type::Class:
4088 #include "clang/AST/TypeNodes.inc"
4089 llvm_unreachable("didn't expect a non-canonical type here");
4090
4091 #define TYPE(Class,Base)
4092 #define DEPENDENT_TYPE(Class,Base) case Type::Class:
4093 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class,Base) case Type::Class:
4094 #include "clang/AST/TypeNodes.inc"
4095 // Treat instantiation-dependent types as external.
4096 assert(T->isInstantiationDependentType());
4097 return LinkageInfo::external();
4098
4099 case Type::BitInt:
4100 case Type::Builtin:
4101 return LinkageInfo::external();
4102
4103 case Type::Auto:
4104 case Type::DeducedTemplateSpecialization:
4105 return LinkageInfo::external();
4106
4107 case Type::Record:
4108 case Type::Enum:
4109 return getDeclLinkageAndVisibility(cast<TagType>(T)->getDecl());
4110
4111 case Type::Complex:
4112 return computeTypeLinkageInfo(cast<ComplexType>(T)->getElementType());
4113 case Type::Pointer:
4114 return computeTypeLinkageInfo(cast<PointerType>(T)->getPointeeType());
4115 case Type::BlockPointer:
4116 return computeTypeLinkageInfo(cast<BlockPointerType>(T)->getPointeeType());
4117 case Type::LValueReference:
4118 case Type::RValueReference:
4119 return computeTypeLinkageInfo(cast<ReferenceType>(T)->getPointeeType());
4120 case Type::MemberPointer: {
4121 const auto *MPT = cast<MemberPointerType>(T);
4122 LinkageInfo LV = computeTypeLinkageInfo(MPT->getClass());
4123 LV.merge(computeTypeLinkageInfo(MPT->getPointeeType()));
4124 return LV;
4125 }
4126 case Type::ConstantArray:
4127 case Type::IncompleteArray:
4128 case Type::VariableArray:
4129 return computeTypeLinkageInfo(cast<ArrayType>(T)->getElementType());
4130 case Type::Vector:
4131 case Type::ExtVector:
4132 return computeTypeLinkageInfo(cast<VectorType>(T)->getElementType());
4133 case Type::ConstantMatrix:
4134 return computeTypeLinkageInfo(
4135 cast<ConstantMatrixType>(T)->getElementType());
4136 case Type::FunctionNoProto:
4137 return computeTypeLinkageInfo(cast<FunctionType>(T)->getReturnType());
4138 case Type::FunctionProto: {
4139 const auto *FPT = cast<FunctionProtoType>(T);
4140 LinkageInfo LV = computeTypeLinkageInfo(FPT->getReturnType());
4141 for (const auto &ai : FPT->param_types())
4142 LV.merge(computeTypeLinkageInfo(ai));
4143 return LV;
4144 }
4145 case Type::ObjCInterface:
4146 return getDeclLinkageAndVisibility(cast<ObjCInterfaceType>(T)->getDecl());
4147 case Type::ObjCObject:
4148 return computeTypeLinkageInfo(cast<ObjCObjectType>(T)->getBaseType());
4149 case Type::ObjCObjectPointer:
4150 return computeTypeLinkageInfo(
4151 cast<ObjCObjectPointerType>(T)->getPointeeType());
4152 case Type::Atomic:
4153 return computeTypeLinkageInfo(cast<AtomicType>(T)->getValueType());
4154 case Type::Pipe:
4155 return computeTypeLinkageInfo(cast<PipeType>(T)->getElementType());
4156 }
4157
4158 llvm_unreachable("unhandled type class");
4159 }
4160
isLinkageValid() const4161 bool Type::isLinkageValid() const {
4162 if (!TypeBits.isCacheValid())
4163 return true;
4164
4165 Linkage L = LinkageComputer{}
4166 .computeTypeLinkageInfo(getCanonicalTypeInternal())
4167 .getLinkage();
4168 return L == TypeBits.getLinkage();
4169 }
4170
getTypeLinkageAndVisibility(const Type * T)4171 LinkageInfo LinkageComputer::getTypeLinkageAndVisibility(const Type *T) {
4172 if (!T->isCanonicalUnqualified())
4173 return computeTypeLinkageInfo(T->getCanonicalTypeInternal());
4174
4175 LinkageInfo LV = computeTypeLinkageInfo(T);
4176 assert(LV.getLinkage() == T->getLinkage());
4177 return LV;
4178 }
4179
getLinkageAndVisibility() const4180 LinkageInfo Type::getLinkageAndVisibility() const {
4181 return LinkageComputer{}.getTypeLinkageAndVisibility(this);
4182 }
4183
getNullability() const4184 std::optional<NullabilityKind> Type::getNullability() const {
4185 QualType Type(this, 0);
4186 while (const auto *AT = Type->getAs<AttributedType>()) {
4187 // Check whether this is an attributed type with nullability
4188 // information.
4189 if (auto Nullability = AT->getImmediateNullability())
4190 return Nullability;
4191
4192 Type = AT->getEquivalentType();
4193 }
4194 return std::nullopt;
4195 }
4196
canHaveNullability(bool ResultIfUnknown) const4197 bool Type::canHaveNullability(bool ResultIfUnknown) const {
4198 QualType type = getCanonicalTypeInternal();
4199
4200 switch (type->getTypeClass()) {
4201 // We'll only see canonical types here.
4202 #define NON_CANONICAL_TYPE(Class, Parent) \
4203 case Type::Class: \
4204 llvm_unreachable("non-canonical type");
4205 #define TYPE(Class, Parent)
4206 #include "clang/AST/TypeNodes.inc"
4207
4208 // Pointer types.
4209 case Type::Pointer:
4210 case Type::BlockPointer:
4211 case Type::MemberPointer:
4212 case Type::ObjCObjectPointer:
4213 return true;
4214
4215 // Dependent types that could instantiate to pointer types.
4216 case Type::UnresolvedUsing:
4217 case Type::TypeOfExpr:
4218 case Type::TypeOf:
4219 case Type::Decltype:
4220 case Type::UnaryTransform:
4221 case Type::TemplateTypeParm:
4222 case Type::SubstTemplateTypeParmPack:
4223 case Type::DependentName:
4224 case Type::DependentTemplateSpecialization:
4225 case Type::Auto:
4226 return ResultIfUnknown;
4227
4228 // Dependent template specializations can instantiate to pointer
4229 // types unless they're known to be specializations of a class
4230 // template.
4231 case Type::TemplateSpecialization:
4232 if (TemplateDecl *templateDecl
4233 = cast<TemplateSpecializationType>(type.getTypePtr())
4234 ->getTemplateName().getAsTemplateDecl()) {
4235 if (isa<ClassTemplateDecl>(templateDecl))
4236 return false;
4237 }
4238 return ResultIfUnknown;
4239
4240 case Type::Builtin:
4241 switch (cast<BuiltinType>(type.getTypePtr())->getKind()) {
4242 // Signed, unsigned, and floating-point types cannot have nullability.
4243 #define SIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4244 #define UNSIGNED_TYPE(Id, SingletonId) case BuiltinType::Id:
4245 #define FLOATING_TYPE(Id, SingletonId) case BuiltinType::Id:
4246 #define BUILTIN_TYPE(Id, SingletonId)
4247 #include "clang/AST/BuiltinTypes.def"
4248 return false;
4249
4250 // Dependent types that could instantiate to a pointer type.
4251 case BuiltinType::Dependent:
4252 case BuiltinType::Overload:
4253 case BuiltinType::BoundMember:
4254 case BuiltinType::PseudoObject:
4255 case BuiltinType::UnknownAny:
4256 case BuiltinType::ARCUnbridgedCast:
4257 return ResultIfUnknown;
4258
4259 case BuiltinType::Void:
4260 case BuiltinType::ObjCId:
4261 case BuiltinType::ObjCClass:
4262 case BuiltinType::ObjCSel:
4263 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4264 case BuiltinType::Id:
4265 #include "clang/Basic/OpenCLImageTypes.def"
4266 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
4267 case BuiltinType::Id:
4268 #include "clang/Basic/OpenCLExtensionTypes.def"
4269 case BuiltinType::OCLSampler:
4270 case BuiltinType::OCLEvent:
4271 case BuiltinType::OCLClkEvent:
4272 case BuiltinType::OCLQueue:
4273 case BuiltinType::OCLReserveID:
4274 #define SVE_TYPE(Name, Id, SingletonId) \
4275 case BuiltinType::Id:
4276 #include "clang/Basic/AArch64SVEACLETypes.def"
4277 #define PPC_VECTOR_TYPE(Name, Id, Size) \
4278 case BuiltinType::Id:
4279 #include "clang/Basic/PPCTypes.def"
4280 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
4281 #include "clang/Basic/RISCVVTypes.def"
4282 case BuiltinType::BuiltinFn:
4283 case BuiltinType::NullPtr:
4284 case BuiltinType::IncompleteMatrixIdx:
4285 case BuiltinType::OMPArraySection:
4286 case BuiltinType::OMPArrayShaping:
4287 case BuiltinType::OMPIterator:
4288 return false;
4289 }
4290 llvm_unreachable("unknown builtin type");
4291
4292 // Non-pointer types.
4293 case Type::Complex:
4294 case Type::LValueReference:
4295 case Type::RValueReference:
4296 case Type::ConstantArray:
4297 case Type::IncompleteArray:
4298 case Type::VariableArray:
4299 case Type::DependentSizedArray:
4300 case Type::DependentVector:
4301 case Type::DependentSizedExtVector:
4302 case Type::Vector:
4303 case Type::ExtVector:
4304 case Type::ConstantMatrix:
4305 case Type::DependentSizedMatrix:
4306 case Type::DependentAddressSpace:
4307 case Type::FunctionProto:
4308 case Type::FunctionNoProto:
4309 case Type::Record:
4310 case Type::DeducedTemplateSpecialization:
4311 case Type::Enum:
4312 case Type::InjectedClassName:
4313 case Type::PackExpansion:
4314 case Type::ObjCObject:
4315 case Type::ObjCInterface:
4316 case Type::Atomic:
4317 case Type::Pipe:
4318 case Type::BitInt:
4319 case Type::DependentBitInt:
4320 return false;
4321 }
4322 llvm_unreachable("bad type kind!");
4323 }
4324
getImmediateNullability() const4325 std::optional<NullabilityKind> AttributedType::getImmediateNullability() const {
4326 if (getAttrKind() == attr::TypeNonNull)
4327 return NullabilityKind::NonNull;
4328 if (getAttrKind() == attr::TypeNullable)
4329 return NullabilityKind::Nullable;
4330 if (getAttrKind() == attr::TypeNullUnspecified)
4331 return NullabilityKind::Unspecified;
4332 if (getAttrKind() == attr::TypeNullableResult)
4333 return NullabilityKind::NullableResult;
4334 return std::nullopt;
4335 }
4336
4337 std::optional<NullabilityKind>
stripOuterNullability(QualType & T)4338 AttributedType::stripOuterNullability(QualType &T) {
4339 QualType AttrTy = T;
4340 if (auto MacroTy = dyn_cast<MacroQualifiedType>(T))
4341 AttrTy = MacroTy->getUnderlyingType();
4342
4343 if (auto attributed = dyn_cast<AttributedType>(AttrTy)) {
4344 if (auto nullability = attributed->getImmediateNullability()) {
4345 T = attributed->getModifiedType();
4346 return nullability;
4347 }
4348 }
4349
4350 return std::nullopt;
4351 }
4352
isBlockCompatibleObjCPointerType(ASTContext & ctx) const4353 bool Type::isBlockCompatibleObjCPointerType(ASTContext &ctx) const {
4354 const auto *objcPtr = getAs<ObjCObjectPointerType>();
4355 if (!objcPtr)
4356 return false;
4357
4358 if (objcPtr->isObjCIdType()) {
4359 // id is always okay.
4360 return true;
4361 }
4362
4363 // Blocks are NSObjects.
4364 if (ObjCInterfaceDecl *iface = objcPtr->getInterfaceDecl()) {
4365 if (iface->getIdentifier() != ctx.getNSObjectName())
4366 return false;
4367
4368 // Continue to check qualifiers, below.
4369 } else if (objcPtr->isObjCQualifiedIdType()) {
4370 // Continue to check qualifiers, below.
4371 } else {
4372 return false;
4373 }
4374
4375 // Check protocol qualifiers.
4376 for (ObjCProtocolDecl *proto : objcPtr->quals()) {
4377 // Blocks conform to NSObject and NSCopying.
4378 if (proto->getIdentifier() != ctx.getNSObjectName() &&
4379 proto->getIdentifier() != ctx.getNSCopyingName())
4380 return false;
4381 }
4382
4383 return true;
4384 }
4385
getObjCARCImplicitLifetime() const4386 Qualifiers::ObjCLifetime Type::getObjCARCImplicitLifetime() const {
4387 if (isObjCARCImplicitlyUnretainedType())
4388 return Qualifiers::OCL_ExplicitNone;
4389 return Qualifiers::OCL_Strong;
4390 }
4391
isObjCARCImplicitlyUnretainedType() const4392 bool Type::isObjCARCImplicitlyUnretainedType() const {
4393 assert(isObjCLifetimeType() &&
4394 "cannot query implicit lifetime for non-inferrable type");
4395
4396 const Type *canon = getCanonicalTypeInternal().getTypePtr();
4397
4398 // Walk down to the base type. We don't care about qualifiers for this.
4399 while (const auto *array = dyn_cast<ArrayType>(canon))
4400 canon = array->getElementType().getTypePtr();
4401
4402 if (const auto *opt = dyn_cast<ObjCObjectPointerType>(canon)) {
4403 // Class and Class<Protocol> don't require retention.
4404 if (opt->getObjectType()->isObjCClass())
4405 return true;
4406 }
4407
4408 return false;
4409 }
4410
isObjCNSObjectType() const4411 bool Type::isObjCNSObjectType() const {
4412 if (const auto *typedefType = getAs<TypedefType>())
4413 return typedefType->getDecl()->hasAttr<ObjCNSObjectAttr>();
4414 return false;
4415 }
4416
isObjCIndependentClassType() const4417 bool Type::isObjCIndependentClassType() const {
4418 if (const auto *typedefType = getAs<TypedefType>())
4419 return typedefType->getDecl()->hasAttr<ObjCIndependentClassAttr>();
4420 return false;
4421 }
4422
isObjCRetainableType() const4423 bool Type::isObjCRetainableType() const {
4424 return isObjCObjectPointerType() ||
4425 isBlockPointerType() ||
4426 isObjCNSObjectType();
4427 }
4428
isObjCIndirectLifetimeType() const4429 bool Type::isObjCIndirectLifetimeType() const {
4430 if (isObjCLifetimeType())
4431 return true;
4432 if (const auto *OPT = getAs<PointerType>())
4433 return OPT->getPointeeType()->isObjCIndirectLifetimeType();
4434 if (const auto *Ref = getAs<ReferenceType>())
4435 return Ref->getPointeeType()->isObjCIndirectLifetimeType();
4436 if (const auto *MemPtr = getAs<MemberPointerType>())
4437 return MemPtr->getPointeeType()->isObjCIndirectLifetimeType();
4438 return false;
4439 }
4440
4441 /// Returns true if objects of this type have lifetime semantics under
4442 /// ARC.
isObjCLifetimeType() const4443 bool Type::isObjCLifetimeType() const {
4444 const Type *type = this;
4445 while (const ArrayType *array = type->getAsArrayTypeUnsafe())
4446 type = array->getElementType().getTypePtr();
4447 return type->isObjCRetainableType();
4448 }
4449
4450 /// Determine whether the given type T is a "bridgable" Objective-C type,
4451 /// which is either an Objective-C object pointer type or an
isObjCARCBridgableType() const4452 bool Type::isObjCARCBridgableType() const {
4453 return isObjCObjectPointerType() || isBlockPointerType();
4454 }
4455
4456 /// Determine whether the given type T is a "bridgeable" C type.
isCARCBridgableType() const4457 bool Type::isCARCBridgableType() const {
4458 const auto *Pointer = getAs<PointerType>();
4459 if (!Pointer)
4460 return false;
4461
4462 QualType Pointee = Pointer->getPointeeType();
4463 return Pointee->isVoidType() || Pointee->isRecordType();
4464 }
4465
4466 /// Check if the specified type is the CUDA device builtin surface type.
isCUDADeviceBuiltinSurfaceType() const4467 bool Type::isCUDADeviceBuiltinSurfaceType() const {
4468 if (const auto *RT = getAs<RecordType>())
4469 return RT->getDecl()->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>();
4470 return false;
4471 }
4472
4473 /// Check if the specified type is the CUDA device builtin texture type.
isCUDADeviceBuiltinTextureType() const4474 bool Type::isCUDADeviceBuiltinTextureType() const {
4475 if (const auto *RT = getAs<RecordType>())
4476 return RT->getDecl()->hasAttr<CUDADeviceBuiltinTextureTypeAttr>();
4477 return false;
4478 }
4479
hasSizedVLAType() const4480 bool Type::hasSizedVLAType() const {
4481 if (!isVariablyModifiedType()) return false;
4482
4483 if (const auto *ptr = getAs<PointerType>())
4484 return ptr->getPointeeType()->hasSizedVLAType();
4485 if (const auto *ref = getAs<ReferenceType>())
4486 return ref->getPointeeType()->hasSizedVLAType();
4487 if (const ArrayType *arr = getAsArrayTypeUnsafe()) {
4488 if (isa<VariableArrayType>(arr) &&
4489 cast<VariableArrayType>(arr)->getSizeExpr())
4490 return true;
4491
4492 return arr->getElementType()->hasSizedVLAType();
4493 }
4494
4495 return false;
4496 }
4497
isDestructedTypeImpl(QualType type)4498 QualType::DestructionKind QualType::isDestructedTypeImpl(QualType type) {
4499 switch (type.getObjCLifetime()) {
4500 case Qualifiers::OCL_None:
4501 case Qualifiers::OCL_ExplicitNone:
4502 case Qualifiers::OCL_Autoreleasing:
4503 break;
4504
4505 case Qualifiers::OCL_Strong:
4506 return DK_objc_strong_lifetime;
4507 case Qualifiers::OCL_Weak:
4508 return DK_objc_weak_lifetime;
4509 }
4510
4511 if (const auto *RT =
4512 type->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
4513 const RecordDecl *RD = RT->getDecl();
4514 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4515 /// Check if this is a C++ object with a non-trivial destructor.
4516 if (CXXRD->hasDefinition() && !CXXRD->hasTrivialDestructor())
4517 return DK_cxx_destructor;
4518 } else {
4519 /// Check if this is a C struct that is non-trivial to destroy or an array
4520 /// that contains such a struct.
4521 if (RD->isNonTrivialToPrimitiveDestroy())
4522 return DK_nontrivial_c_struct;
4523 }
4524 }
4525
4526 return DK_none;
4527 }
4528
getMostRecentCXXRecordDecl() const4529 CXXRecordDecl *MemberPointerType::getMostRecentCXXRecordDecl() const {
4530 return getClass()->getAsCXXRecordDecl()->getMostRecentNonInjectedDecl();
4531 }
4532
FixedPointValueToString(SmallVectorImpl<char> & Str,llvm::APSInt Val,unsigned Scale)4533 void clang::FixedPointValueToString(SmallVectorImpl<char> &Str,
4534 llvm::APSInt Val, unsigned Scale) {
4535 llvm::FixedPointSemantics FXSema(Val.getBitWidth(), Scale, Val.isSigned(),
4536 /*IsSaturated=*/false,
4537 /*HasUnsignedPadding=*/false);
4538 llvm::APFixedPoint(Val, FXSema).toString(Str);
4539 }
4540
AutoType(QualType DeducedAsType,AutoTypeKeyword Keyword,TypeDependence ExtraDependence,QualType Canon,ConceptDecl * TypeConstraintConcept,ArrayRef<TemplateArgument> TypeConstraintArgs)4541 AutoType::AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4542 TypeDependence ExtraDependence, QualType Canon,
4543 ConceptDecl *TypeConstraintConcept,
4544 ArrayRef<TemplateArgument> TypeConstraintArgs)
4545 : DeducedType(Auto, DeducedAsType, ExtraDependence, Canon) {
4546 AutoTypeBits.Keyword = (unsigned)Keyword;
4547 AutoTypeBits.NumArgs = TypeConstraintArgs.size();
4548 this->TypeConstraintConcept = TypeConstraintConcept;
4549 if (TypeConstraintConcept) {
4550 auto *ArgBuffer =
4551 const_cast<TemplateArgument *>(getTypeConstraintArguments().data());
4552 for (const TemplateArgument &Arg : TypeConstraintArgs) {
4553 addDependence(
4554 toSyntacticDependence(toTypeDependence(Arg.getDependence())));
4555
4556 new (ArgBuffer++) TemplateArgument(Arg);
4557 }
4558 }
4559 }
4560
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context,QualType Deduced,AutoTypeKeyword Keyword,bool IsDependent,ConceptDecl * CD,ArrayRef<TemplateArgument> Arguments)4561 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4562 QualType Deduced, AutoTypeKeyword Keyword,
4563 bool IsDependent, ConceptDecl *CD,
4564 ArrayRef<TemplateArgument> Arguments) {
4565 ID.AddPointer(Deduced.getAsOpaquePtr());
4566 ID.AddInteger((unsigned)Keyword);
4567 ID.AddBoolean(IsDependent);
4568 ID.AddPointer(CD);
4569 for (const TemplateArgument &Arg : Arguments)
4570 Arg.Profile(ID, Context);
4571 }
4572
Profile(llvm::FoldingSetNodeID & ID,const ASTContext & Context)4573 void AutoType::Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
4574 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
4575 getTypeConstraintConcept(), getTypeConstraintArguments());
4576 }
4577